/// <summary>
        /// Tries to set an attribute in the project file for the item.
        /// </summary>
        public async Task <bool> TrySetAttributeAsync(string name, string value)
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            GetItemInfo(out IVsHierarchy hierarchy, out uint itemId, out _);
            int hr = hierarchy.GetProperty(itemId, (int)__VSHPROPID.VSHPROPID_BrowseObject, out object?browseObject);

            // First try if the attribute name exist in the Property Descriptor Collection
            if (ErrorHandler.Succeeded(hr))
            {
                // Inspired by this sample: https://stackoverflow.com/a/24538728

                string cleanName = Regex.Replace(name, @"\s+", ""); // remove whitespace
                PropertyDescriptorCollection propertyDescriptors  = TypeDescriptor.GetProperties(browseObject);
                PropertyDescriptor?          customToolDescriptor = propertyDescriptors?.Find(cleanName, true);

                if (customToolDescriptor != null)
                {
                    string?invariantValue = customToolDescriptor.Converter.ConvertToInvariantString(value);
                    customToolDescriptor.SetValue(browseObject, invariantValue);
                    IVsUIShell?shell = await VS.Services.GetUIShellAsync();

                    // Refresh the Property window
                    if (customToolDescriptor.Attributes[typeof(DispIdAttribute)] is DispIdAttribute dispId)
                    {
                        ErrorHandler.ThrowOnFailure(shell.RefreshPropertyBrowser(dispId.Value));
                    }

                    return(true);
                }
            }
            // Then write straight to project file
            else if (hierarchy is IVsBuildPropertyStorage storage)
            {
                ErrorHandler.ThrowOnFailure(storage.SetItemAttribute(itemId, name, value));
                return(true);
            }

            return(false);
        }
示例#2
0
        public Control CreateControl(Type controlType, Size controlSize, Point controlLocation)
        {
            try {
                //- step.1
                //- get the IDesignerHost
                //- if we are not able to get it
                //- then rollback (return without do nothing)
                IDesignerHost host = GetIDesignerHost();
                if (null == host)
                {
                    return(null);
                }
                //- check if the root component has already been set
                //- if not so then rollback (return without do nothing)
                if (null == host.RootComponent)
                {
                    return(null);
                }
                //-
                //-
                //- step.2
                //- create a new component and initialize it via its designer
                //- if the component has not a designer
                //- then rollback (return without do nothing)
                //- else do the initialization
                IComponent newComp = host.CreateComponent(controlType);
                if (null == newComp)
                {
                    return(null);
                }
                IDesigner designer = host.GetDesigner(newComp);
                if (null == designer)
                {
                    return(null);
                }
                if (designer is IComponentInitializer)
                {
                    (( IComponentInitializer )designer).InitializeNewComponent(null);
                }
                //-
                //-
                //- step.3
                //- try to modify the Size/Location of the object just created
                PropertyDescriptorCollection pdc = TypeDescriptor.GetProperties(newComp);
                //- Sets a PropertyDescriptor to the specific property.
                PropertyDescriptor pdS = pdc.Find("Size", false);
                if (null != pdS)
                {
                    pdS.SetValue(newComp, controlSize);
                }
                PropertyDescriptor pdL = pdc.Find("Location", false);
                if (null != pdL)
                {
                    pdL.SetValue(newComp, controlLocation);
                }
                //-
                //-
                //- step.4
                //- commit the Creation Operation
                //- adding the control to the DesignSurface's root component
                //- and return the control just created to let further initializations
                (( Control )newComp).Parent = host.RootComponent as Control;
                return(newComp as Control);
            }//end_try
            catch (Exception exx) {
                Debug.WriteLine(exx.Message);
                if (null != exx.InnerException)
                {
                    Debug.WriteLine(exx.InnerException.Message);
                }

                throw;
            }//end_catch
        }
示例#3
0
 /// <summary>
 /// Seek for a PropertyDescriptor within the collection by Name with option to ignore case
 /// </summary>
 /// <returns>search result or null if nothing was found</returns>
 public static PropertyDescriptor GetByName(this PropertyDescriptorCollection collection,
                                            string name, bool ignoreCase)
 {
     return(collection.Find(name, ignoreCase));
 }
示例#4
0
        protected virtual void SetVariables()
        {
            if (_scenario != null)
            {
                PropertyDescriptorCollection props = TypeDescriptor.GetProperties(this);
                if (_outputProperties != null)
                {
                    PropertyDescriptor foundProp = null;
                    foreach (string name in _outputProperties.Keys)
                    {
                        foundProp = props.Find(name, false);
                        string variableName = _outputProperties[name];

                        if (foundProp != null)
                        {
                            object val = foundProp.GetValue(this);

                            DataTable   table = val as DataTable;
                            ICollection list  = val as ICollection;

                            if (table != null)
                            {
                                ScenarioVariable <DataTable> tableVar = _scenario.Tables[variableName];

                                if (tableVar != null)
                                {
                                    tableVar.Value = table;
                                }
                                else
                                {
                                    _scenario.Tables.AddOrReplace(new ScenarioTable(variableName, table, this));
                                }
                            }
                            else if (list != null)
                            {
                                string[] stringList = list.Cast <object>().Select(
                                    obj => (obj == null) ? "(null)" : obj.ToString()).ToArray();

                                ScenarioVariable <string[]> l = _scenario.Lists[variableName];
                                if (l != null)
                                {
                                    l.Value = stringList;
                                }
                                else
                                {
                                    _scenario.Lists.AddOrReplace(new ScenarioVariable <string[]>(variableName, stringList, this));
                                }
                            }
                            else if (val != null)
                            {
                                ScenarioVariable <string> v = _scenario.Variables[variableName];
                                if (v != null)
                                {
                                    v.Value = val.ToString();
                                }
                                else
                                {
                                    _scenario.Variables.AddOrReplace(new ScenarioVariable <string>(variableName, val.ToString(), this));
                                }
                            }
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Gets the data source.
        /// </summary>
        /// <returns></returns>
        protected virtual IEnumerable GetDataSource()
        {
            if (_dataSource == null)
            {
                return(null);
            }

            IEnumerable resolvedDataSource = _dataSource as IEnumerable;

            if (resolvedDataSource != null)
            {
                return(resolvedDataSource);
            }

            IListSource listSource = _dataSource as IListSource;

            if (listSource != null)
            {
                IList memberList = listSource.GetList();

                if (listSource.ContainsListCollection == false)
                {
                    return((IEnumerable)memberList);
                }

                ITypedList typedMemberList = memberList as ITypedList;
                if (typedMemberList != null)
                {
                    PropertyDescriptorCollection propDescs      = typedMemberList.GetItemProperties(new PropertyDescriptor[0]);
                    PropertyDescriptor           memberProperty = null;

                    if ((propDescs != null) && (propDescs.Count != 0))
                    {
                        string dataMember = DataMember;

                        if (dataMember.Length == 0)
                        {
                            memberProperty = propDescs[0];
                        }
                        else
                        {
                            memberProperty = propDescs.Find(dataMember, true);
                        }

                        if (memberProperty != null)
                        {
                            object listRow = memberList[0];
                            object list    = memberProperty.GetValue(listRow);

                            if (list is IEnumerable)
                            {
                                return((IEnumerable)list);
                            }
                        }
                        throw new Exception("A list corresponding to the selected DataMember was not found. Please specify a valid DataMember or bind to an explicit datasource (a DataTable for exemple).");
                    }

                    throw new Exception("The selected data source did not contain any data members to bind to.");
                }
            }

            return(null);
        }
示例#6
0
            public PropertyDescriptor GetPropertyDescriptor(object source, string propertyName)
            {
                TypePropertyPair key = new TypePropertyPair()
                {
                    type = source != null?source.GetType() : null, propertyName = propertyName
                };

                if (key.type == null || key.propertyName == null)
                {
                    return(null);
                }
                if (cache.ContainsKey(key))
                {
                    return(cache[key]);
                }
                else
                {
                    PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(source);
                    PropertyDescriptor           descriptor = properties == null ? null : properties.Find(propertyName, ignoreCase: true);
                    if (descriptor == null)
                    {
                        return(null);
                    }

                    lock (cache)
                    {
                        if (!cache.ContainsKey(key))
                        {
                            cache.Add(key, descriptor);
                        }
                    }
                    return(descriptor);
                }
            }
示例#7
0
        public override object Eval(object row, object context)
        {
            object o = context;

            if (null != this.parent)
            {
                o = this.parent.Eval(row, context);
            }
            else if (NameNode.FildsObject == this.name)
            {
                return(row);
            }

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

            IDataItem map = row as IDataItem; //changed from IDataMap

            if (null != map)
            {
                return(map[this.name]);
                //// The "old" field notation when there was no Fields global object
                //// and fields was referenced by thier name only; ex. =ProductCategory
                //// instead of =Fields.ProductCategory
                //try
                //{
                //		return map[this.name];
                //}
                //catch (Exception)
                //{
                //    // hide this exception; UndefinedObject will be raised after that
                //}
            }

            PropertyDescriptor property = null;
            Type objectType             = o.GetType();

            // Sometimes one expression may be evaluated on a different
            // type of data. Because of the caching of the expression trees
            // two expression (ex. the report's filters and a textbox
            // in the group header) may result in a single exp tree. The different
            // input data (same ex. - the filter operates with DataObject while
            // for the group sections is passed DataGroup objects) will result
            // in a different PropertyDescriptor, so we need to chache them
            // per object type.

            if (!this.properties.TryGetValue(objectType, out property))
            {
                PropertyDescriptorCollection collection = null;
                if (o is IDataDescriptor)
                {
                    collection = ((IDataDescriptor)o).GetProperties();
                }
                else
                {
                    collection = TypeDescriptor.GetProperties(o);
                }

                if (null != collection && collection.Count > 0)
                {
                    this.properties[objectType]
                          = property
                          = collection.Find(this.name, true);
                }
            }

            if (null != property)
            {
                return(property.GetValue(o));
            }

            throw InvalidExpressionException.UndefinedObject(this.name);
        }
示例#8
0
        private bool IsFormatModeAndBindingCompatible(DisplayFormatMode format, Binding binding)
        {
            if (binding == null || binding.BindingManagerBase == null)
            {
                return(true);
            }
            Type type = null;
            PropertyDescriptorCollection itemProperties     = binding.BindingManagerBase.GetItemProperties();
            PropertyDescriptor           propertyDescriptor = itemProperties.Find(binding.BindingMemberInfo.BindingField, true);

            if (propertyDescriptor != null)
            {
                FilterValuePropertyDescriptor filterValuePropertyDescriptor = propertyDescriptor as FilterValuePropertyDescriptor;
                if (filterValuePropertyDescriptor != null)
                {
                    type = filterValuePropertyDescriptor.ValuePropertyType;
                }
                else
                {
                    type = propertyDescriptor.PropertyType;
                }
            }
            if (type == null)
            {
                return(true);
            }
            Type type2 = null;
            Type left  = null;
            bool flag  = false;
            Type left2;

            switch (format)
            {
            case 1:
                left2 = typeof(EnhancedTimeSpan);
                break;

            case 2:
                left2 = typeof(EnhancedTimeSpan);
                break;

            case 3:
                left2 = typeof(EnhancedTimeSpan);
                break;

            case 4:
                left2 = typeof(EnhancedTimeSpan);
                break;

            case 5:
                left2 = typeof(EnhancedTimeSpan);
                flag  = true;
                break;

            case 6:
                left2 = typeof(ByteQuantifiedSize);
                break;

            case 7:
                left2 = typeof(ByteQuantifiedSize);
                break;

            case 8:
                left2 = typeof(ByteQuantifiedSize);
                flag  = true;
                break;

            case 9:
                left2 = typeof(bool);
                flag  = true;
                break;

            case 10:
                left2 = typeof(bool);
                flag  = true;
                break;

            case 11:
                left2 = typeof(bool);
                flag  = true;
                break;

            case 12:
                left2 = typeof(ADObjectId);
                if (typeof(MultiValuedProperty <ADObjectId>).IsAssignableFrom(type))
                {
                    flag = true;
                }
                break;

            case 13:
                left2 = typeof(DateTime);
                flag  = true;
                break;

            case 14:
                left2 = typeof(int);
                flag  = true;
                break;

            case 15:
                left2 = typeof(SmtpDomainWithSubdomains);
                break;

            default:
                left2 = null;
                break;
            }
            if (flag && binding.DataSourceUpdateMode != DataSourceUpdateMode.Never)
            {
                return(false);
            }
            Type type3 = type;

            if (type2 != null)
            {
                return(type.GetInterface(type2.ToString()) != null);
            }
            if (type3.IsGenericType)
            {
                if (type3.GetGenericTypeDefinition() == typeof(Nullable <>))
                {
                    type3 = type3.GetGenericArguments()[0];
                }
                Type[] genericArguments = type3.GetGenericArguments();
                if (genericArguments.Length == 1 && !genericArguments[0].IsGenericParameter)
                {
                    type3 = genericArguments[0];
                }
            }
            if (type3 == typeof(EnhancedTimeSpan) || type3 == typeof(ByteQuantifiedSize) || type3 == typeof(ADObjectId))
            {
                left = type3;
            }
            if (left2 != null || left != null)
            {
                return(left2 == type3);
            }
            return(format == 0);
        }
示例#9
0
        public void Map(object source, object target, MappingExecutionScope scope)
        {
            var ci = new PropertyMapDefinition
            {
                Source =
                {
                    Type  = source.GetType(),
                    Value = source
                },
                Target =
                {
                    Type  = target.GetType(),
                    Value = target
                }
            };

            var sourceProps = source.GetProperties();
            var targetProps = target.GetProperties();

            //create MemberExpressionSignature for each property
            var targetPropDefs = targetProps.Cast <PropertyDescriptor>()
                                 .Select(x => new
            {
                expression = new MemberExpressionSignature(
                    x.PropertyType,
                    typeof(TTarget),
                    x.Name),
                property = x
            }).ToArray();

            //before we map the members by name, we need to ignore any members that have been referenced in the member expressions
            var filteredTargetProps = new PropertyDescriptorCollection(
                (from t in targetPropDefs
                 where !_mapper.MappingContext.MemberExpressions.Any(x => x.Equals(t.expression))
                 select t.property).ToArray());

            foreach (PropertyDescriptor s in sourceProps)
            {
                var t = filteredTargetProps.Find(s.Name, false);
                if (t == null)
                {
                    continue;
                }
                var reflectedProp = ci.Target.Type.GetProperty(t.Name);
                if (reflectedProp == null)
                {
                    continue;
                }
                if (!reflectedProp.CanWrite)
                {
                    continue;
                }

                ci.SourceProp.Name  = s.Name;
                ci.SourceProp.Value = s.GetValue(source);
                ci.SourceProp.Type  = s.PropertyType;
                ci.TargetProp.Name  = t.Name;
                ci.TargetProp.Type  = t.PropertyType;
                ci.TargetProp.Value = t.GetValue(target);

                //if people have overridden this injector, we'll need to check that this hasn't already been mapped
                if (IsAlreadyMapped(ci))
                {
                    continue;
                }

                //check that we can proceed with setting this value
                if (IsTypeMappable(s.PropertyType, t.PropertyType))
                {
                    //set the output value to the source
                    ci.TargetProp.Value = ci.SourceProp.Value;
                }
                else
                {
                    var hasConverted = false;
                    // If no explicit mapping exists, but a TypeConverter exists between the source & destination types, use that
                    if (TypeFinder.IsImplicitValueType(ci.TargetProp.Type) &&
                        !IsMapperRegistered(ci.SourceProp.Type, ci.TargetProp.Type))
                    {
                        var converter = TypeDescriptor.GetConverter(ci.SourceProp.Type);
                        if (converter != null && converter.CanConvertTo(ci.TargetProp.Type))
                        {
                            ci.TargetProp.Value = converter.ConvertTo(ci.SourceProp.Value, ci.TargetProp.Type);
                            hasConverted        = true;
                        }
                        else
                        {
                            converter = TypeDescriptor.GetConverter(ci.TargetProp.Type);
                            if (converter != null && converter.CanConvertFrom(ci.SourceProp.Type))
                            {
                                ci.TargetProp.Value = converter.ConvertFrom(ci.SourceProp.Value);
                                hasConverted        = true;
                            }
                        }
                    }

                    if (!hasConverted)
                    {
                        // If we can't simply map it by setting the value, then we'll send the operation back through the mapper
                        // Also, if it's not a reference type, we can't map it in place and have to set the value of the property to a new value
                        if (TypeFinder.IsImplicitValueType(ci.TargetProp.Type) || ci.TargetProp.Value == null)
                        {
                            //map to new
                            var val = MapToNew(ci.SourceProp.Value, ci.SourceProp.Type, ci.TargetProp.Type, scope);
                            ci.TargetProp.Value = val;
                        }
                        else
                        {
                            //map to existing
                            MapToExisting(ci.SourceProp.Value, ci.TargetProp.Value, ci.SourceProp.Type, ci.TargetProp.Type);
                        }
                    }
                }

                SetProperty(reflectedProp, target, ci.TargetProp.Value, scope);
                //tag this as already mapped
                AddMemberMapped(ci);
            }

            //now that we've mapped by name, lets map by rule
            foreach (var signature in _mapper.MappingContext.MemberExpressions)
            {
                //get the target property definition with the expression mapped
                var targetProp = targetPropDefs.Single(x => x.expression.Equals(signature));

                var reflectedProp = ci.Target.Type.GetProperty(targetProp.property.Name);
                if (reflectedProp == null)
                {
                    throw new MissingMemberException("Could not access property " + targetProp.property.Name + " on object Type " + targetProp.property.ComponentType.Name);
                }

                //fill in the TypeMapDefinition object
                ci.TargetProp.Name = targetProp.property.Name;
                ci.TargetProp.Type = targetProp.property.PropertyType;

                //now, try to map from a rule, if successful set the value... the MapFromRule will automatically add the Info to the already mapped list.
                object val;
                if (!IsAlreadyMapped(ci) && _mapper.MappingContext.MapFromRule(ci, targetProp.expression, out val))
                {
                    if (!reflectedProp.CanWrite)
                    {
                        throw new MemberAccessException("A member expression has been declared for a writeable mapping operation for property " + targetProp.property.Name + " on object Type " + targetProp.property.ComponentType.Name + " but this property is readonly and cannot be written to");
                    }
                    SetProperty(reflectedProp, target, val, scope);
                    //tag this as already mapped
                    AddMemberMapped(ci);
                }
            }
        }
示例#10
0
 private bool EnsureDescriptors()
 {
     if (this.dataSource == null || this.OwnerTemplate == null || this.OwnerTemplate.BindingContext == null)
     {
         return(false);
     }
     if (this.currencyManager == null)
     {
         this.currencyManager = this.OwnerTemplate.BindingContext[this.dataSource] as CurrencyManager;
         this.BindToEnumerable();
         this.currencyManager.ListChanged += new ListChangedEventHandler(this.currencyManager_ListChanged);
     }
     if (this.currencyManager != null && !this.currencyManager.IsBindingSuspended)
     {
         PropertyDescriptorCollection itemProperties = this.currencyManager.GetItemProperties();
         if (!string.IsNullOrEmpty(this.valueMember))
         {
             this.valueDescriptor = itemProperties.Find(this.valueMember, true);
             if (this.valueDescriptor == null && this.valueMember.Contains("."))
             {
                 this.isValueSubProperty = true;
                 string[] strArray = this.valueMember.Split('.');
                 this.valueDescriptor = itemProperties.Find(strArray[0], true);
                 for (int index = 1; index < strArray.Length && this.valueDescriptor != null; ++index)
                 {
                     this.valueDescriptor = this.valueDescriptor.GetChildProperties().Find(strArray[index], true);
                 }
             }
         }
         if (!string.IsNullOrEmpty(this.displayMember))
         {
             this.displayDescriptor = itemProperties.Find(this.displayMember, true);
             if (this.displayDescriptor == null && this.displayMember.Contains("."))
             {
                 this.isDisplayValueSubProperty = true;
                 string[] strArray = this.displayMember.Split('.');
                 this.displayDescriptor = itemProperties.Find(strArray[0], true);
                 for (int index = 1; index < strArray.Length && this.displayDescriptor != null; ++index)
                 {
                     this.displayDescriptor = this.displayDescriptor.GetChildProperties().Find(strArray[index], true);
                 }
             }
             if (string.IsNullOrEmpty(this.valueMember))
             {
                 this.valueDescriptor = this.displayDescriptor;
             }
         }
         else
         {
             this.displayDescriptor = this.valueDescriptor;
         }
         if (this.valueDescriptor != null)
         {
             this.items.Clear();
             for (int i = 0; i < this.currencyManager.Count; ++i)
             {
                 this.AddItem(i);
             }
             this.DataType = this.valueDescriptor.PropertyType;
         }
     }
     if (this.valueDescriptor != null && this.displayDescriptor != null)
     {
         return(this.currencyManager != null);
     }
     return(false);
 }
        //- Create the DesignSurface and the rootComponent (a .NET Control)
        //- using IDesignSurfaceExt.CreateRootComponent()
        //- if the alignmentMode doesn't use the GRID, then the gridSize param is ignored
        //- Note:
        //-     the generics param is used to know which type of control to use as RootComponent
        //-     TT is requested to be derived from .NET Control class
        public DesignSurfaceExt2 AddDesignSurface <TT> (
            int startingFormWidth, int startingFormHeight,
            AlignmentModeEnum alignmentMode, Size gridSize
            ) where TT : Control
        {
            const string _signature_ = _Name_ + @"::AddDesignSurface<>()";

            if (!this)
            {
                throw new Exception(_signature_ + " - Exception: " + _Name_ + " is not initialized! Please set the Property: IpDesigner::Toolbox before calling any methods!");
            }


            //- step.0
            //- create a DesignSurface
            DesignSurfaceExt2 surface = DesignSurfaceManager.CreateDesignSurfaceExt2();

            this.DesignSurfaceManager.ActiveDesignSurface = surface;
            //-
            //-
            //- step.1
            //- choose an alignment mode...
            switch (alignmentMode)
            {
            case AlignmentModeEnum.SnapLines:
                surface.UseSnapLines();
                break;

            case AlignmentModeEnum.Grid:
                surface.UseGrid(gridSize);
                break;

            case AlignmentModeEnum.GridWithoutSnapping:
                surface.UseGridWithoutSnapping(gridSize);
                break;

            case AlignmentModeEnum.NoGuides:
                surface.UseNoGuides();
                break;

            default:
                surface.UseSnapLines();
                break;
            }//end_switch
            //-
            //-
            //- step.2
            //- enable the UndoEngine
            ((IDesignSurfaceExt)surface).GetUndoEngineExt().Enabled = true;
            //-
            //-
            //- step.3
            //- Select the service IToolboxService
            //- and hook it to our ListBox
            ToolboxServiceImp tbox = ((IDesignSurfaceExt2)surface).GetIToolboxService() as ToolboxServiceImp;

            //- we don't check if Toolbox is null because the very first check: if(!this)...
            if (null != tbox)
            {
                tbox.Toolbox = this.Toolbox;
            }
            //-
            //-
            //- step.4
            //- create the Root compoment, in these cases a Form
            Control rootComponent = null;

            //- cast to .NET Control because the TT object has a constraint: to be a ".NET Control"
            rootComponent = surface.CreateRootComponent(typeof(TT), new Size(startingFormWidth, startingFormHeight)) as Control;
            //- rename the Sited component
            //- (because the user may add more then one Form and every new Form will be called "Form1" if we don't set its Name)
            rootComponent.Site.Name = this.DesignSurfaceManager.GetValidFormName();
            //-
            //-
            //- step.5
            //- enable the Drag&Drop on RootComponent
            ((DesignSurfaceExt2)surface).EnableDragandDrop();
            //-
            //-
            //- step.6
            //- IComponentChangeService is marked as Non replaceable service
            IComponentChangeService componentChangeService = (IComponentChangeService)(surface.GetService(typeof(IComponentChangeService)));

            if (null != componentChangeService)
            {
                //- the Type "ComponentEventHandler Delegate" Represents the method that will
                //- handle the ComponentAdding, ComponentAdded, ComponentRemoving, and ComponentRemoved
                //- events raised for component-level events
                componentChangeService.ComponentChanged += (Object sender, ComponentChangedEventArgs e) =>
                {
                    if (e.Component is IEbControl)
                    {
                        (e.Component as IEbControl).BeforeSerialization();
                    }
                    // do nothing
                };

                componentChangeService.ComponentAdded += (Object sender, ComponentEventArgs e) =>
                {
                    DesignSurfaceManager.UpdatePropertyGridHost(surface);
                };
                componentChangeService.ComponentRemoved += (Object sender, ComponentEventArgs e) =>
                {
                    DesignSurfaceManager.UpdatePropertyGridHost(surface);
                };
            }
            //-
            //-
            //- step.7
            //- now set the Form::Text Property
            //- (because it will be an empty string
            //- if we don't set it)
            Control view = surface.GetView();

            if (null == view)
            {
                return(null);
            }
            PropertyDescriptorCollection pdc = TypeDescriptor.GetProperties(view);
            //- Sets a PropertyDescriptor to the specific property
            PropertyDescriptor pdS = pdc.Find("Text", false);

            if (null != pdS)
            {
                pdS.SetValue(rootComponent, rootComponent.Site.Name + " (design mode)");
            }
            //-
            //-
            //- step.8
            //- display the DesignSurface
            //string sTabPageText = rootComponent.Site.Name;
            //TabPage newPage = new TabPage( sTabPageText );
            //newPage.Name = sTabPageText;
            //newPage.SuspendLayout(); //----------------------------------------------------
            view.Dock   = DockStyle.Fill;
            view.Parent = this; // newPage; //- Note this assignment
            //this.tbCtrlpDesigner.TabPages.Add( newPage );
            //newPage.ResumeLayout(); //-----------------------------------------------------
            //- select the TabPage created
            //this.tbCtrlpDesigner.SelectedIndex = this.tbCtrlpDesigner.TabPages.Count - 1;
            //-
            //-
            //- step.9
            //- finally return the DesignSurface created to let it be modified again by user
            return(surface);
        }
示例#12
0
        /// <devdoc>
        /// </devdoc>
        private void OnDataBindField(object sender, EventArgs e)
        {
            Debug.Assert((DataTextField.Length != 0) || (DataNavigateUrlFields.Length != 0),
                         "Shouldn't be DataBinding without a DataTextField and DataNavigateUrlField");

            HyperLink boundControl     = (HyperLink)sender;
            Control   controlContainer = boundControl.NamingContainer;
            object    dataItem         = null;


            if (controlContainer == null)
            {
                throw new HttpException(SR.GetString(SR.DataControlField_NoContainer));
            }

            // Get the DataItem from the container
            dataItem = DataBinder.GetDataItem(controlContainer);

            if (dataItem == null && !DesignMode)
            {
                throw new HttpException(SR.GetString(SR.DataItem_Not_Found));
            }

            if ((textFieldDesc == null) && (urlFieldDescs == null))
            {
                PropertyDescriptorCollection props = TypeDescriptor.GetProperties(dataItem);
                string fieldName;

                fieldName = DataTextField;
                if (fieldName.Length != 0)
                {
                    textFieldDesc = props.Find(fieldName, true);
                    if ((textFieldDesc == null) && !DesignMode)
                    {
                        throw new HttpException(SR.GetString(SR.Field_Not_Found, fieldName));
                    }
                }

                string[] dataNavigateUrlFields       = DataNavigateUrlFields;
                int      dataNavigateUrlFieldsLength = dataNavigateUrlFields.Length;
                urlFieldDescs = new PropertyDescriptor[dataNavigateUrlFieldsLength];

                for (int i = 0; i < dataNavigateUrlFieldsLength; i++)
                {
                    fieldName = dataNavigateUrlFields[i];
                    if (fieldName.Length != 0)
                    {
                        urlFieldDescs[i] = props.Find(fieldName, true);
                        if ((urlFieldDescs[i] == null) && !DesignMode)
                        {
                            throw new HttpException(SR.GetString(SR.Field_Not_Found, fieldName));
                        }
                    }
                }
            }

            string dataTextValue = String.Empty;

            if (textFieldDesc != null && dataItem != null)
            {
                object data = textFieldDesc.GetValue(dataItem);
                dataTextValue = FormatDataTextValue(data);
            }
            if (DesignMode && (DataTextField.Length != 0) && dataTextValue.Length == 0)
            {
                dataTextValue = SR.GetString(SR.Sample_Databound_Text);
            }

            if (dataTextValue.Length > 0)
            {
                boundControl.Text = dataTextValue;
            }

            int    urlFieldDescsLength = urlFieldDescs.Length;
            string dataNavValue        = String.Empty;

            if (urlFieldDescs != null && urlFieldDescsLength > 0 && dataItem != null)
            {
                object[] data = new object[urlFieldDescsLength];

                for (int i = 0; i < urlFieldDescsLength; i++)
                {
                    if (urlFieldDescs[i] != null)
                    {
                        data[i] = urlFieldDescs[i].GetValue(dataItem);
                    }
                }
                string urlValue = FormatDataNavigateUrlValue(data);
                if (!CrossSiteScriptingValidation.IsDangerousUrl(urlValue))
                {
                    dataNavValue = urlValue;
                }
            }
            if (DesignMode && (DataNavigateUrlFields.Length != 0) && dataNavValue.Length == 0)
            {
                dataNavValue = "url";
            }

            if (dataNavValue.Length > 0)
            {
                boundControl.NavigateUrl = dataNavValue;
            }
        }
示例#13
0
        public TControl CreateRootComponent <TControl>(Size controlSize)
            where TControl : Control, IComponent
        {
            try
            {
                //- step.1
                //- get the IDesignerHost
                //- if we are not not able to get it
                //- then rollback (return without do nothing)
                IDesignerHost host = GetIDesignerHost();
                if (null == host)
                {
                    return(null);
                }
                //- check if the root component has already been set
                //- if so then rollback (return without do nothing)
                if (null != host.RootComponent)
                {
                    return(null);
                }
                //-
                //-
                //- step.2
                //- create a new root component and initialize it via its designer
                //- if the component has not a designer
                //- then rollback (return without do nothing)
                //- else do the initialization
                BeginLoad(typeof(TControl));
                if (LoadErrors.Count > 0)
                {
                    throw new Exception("the BeginLoad() failed! Some error during " + typeof(TControl).FullName + " loding");
                }
                //-
                //-
                //- step.3
                //- try to modify the Size of the object just created
                IDesignerHost ihost = GetIDesignerHost();
                //- Set the backcolor and the Size
                Control ctrl     = null;
                Type    hostType = host.RootComponent.GetType();
                if (hostType == typeof(Form))
                {
                    ctrl           = View as Control;
                    ctrl.BackColor = Color.LightGray;
                    //- set the Size
                    PropertyDescriptorCollection pdc = TypeDescriptor.GetProperties(ctrl);
                    //- Sets a PropertyDescriptor to the specific property.
                    PropertyDescriptor pdS = pdc.Find("Size", false);
                    if (null != pdS)
                    {
                        pdS.SetValue(ihost.RootComponent, controlSize);
                    }
                }
                else if (hostType == typeof(UserControl))
                {
                    ctrl           = View as Control;
                    ctrl.BackColor = Color.DarkGray;
                    //- set the Size
                    PropertyDescriptorCollection pdc = TypeDescriptor.GetProperties(ctrl);
                    //- Sets a PropertyDescriptor to the specific property.
                    PropertyDescriptor pdS = pdc.Find("Size", false);
                    if (null != pdS)
                    {
                        pdS.SetValue(ihost.RootComponent, controlSize);
                    }
                }
                else if (hostType == typeof(Component))
                {
                    ctrl           = View as Control;
                    ctrl.BackColor = Color.White;
                    //- don't set the Size
                }
                else
                {
                    throw new Exception("Undefined Host Type: " + hostType.ToString());
                }

                return((TControl)ihost.RootComponent);
            }//end_try
            catch (Exception ex)
            {
                throw new Exception(_Name_ + "::CreateRootComponent() - Exception: (see Inner Exception)", ex);
            }//end_catch
        }
示例#14
0
        /// <summary>
        /// Updates object from command-line arguments where
        /// <paramref name="properties" /> describes the target object.
        /// </summary>

        public static string[] ParseTo(IEnumerable <string> args, object target, PropertyDescriptorCollection properties)
        {
            if (target == null)
            {
                throw new ArgumentNullException("target");
            }
            if (args == null)
            {
                throw new ArgumentNullException("args");
            }

            var tails = new List <string>();

            var e = args.GetEnumerator();

            while (e.MoveNext())
            {
                var arg = e.Current;

                if (arg.Length == 0) // empty arg?
                {
                    tails.Add(arg);
                    continue;
                }

                // Get argument name, Unix or DOS style.

                string name;

                if (arg[0] == '/') // DOS style
                {
                    name = arg.Substring(1);
                }
                else if (arg.Length > 1 && arg[0] == '-' && arg[1] == '-') // Unix style
                {
                    if (arg.Length == 2)                                   // comment
                    {
                        break;
                    }
                    name = arg.Substring(2);
                }
                else
                {
                    tails.Add(arg); // anonymous argument
                    continue;
                }

                // Is the argument name and value paired in one?
                // Allows `arg=value` or `arg:value` style.

                var paired = name.IndexOfAny(_argSeparators) > 0;
                var pair   = name.Split(_argSeparators, (n, v) => new { Name = n, Value = v });

                if (paired)
                {
                    name = pair.Name; // Break the name out of the pair
                }
                // Get setting property from name.

                var propertyName = name.Replace("-", " ")
                                   .ToTitleCaseInvariant()
                                   .Replace(" ", string.Empty);

                if (properties == null)
                {
                    properties = TypeDescriptor.GetProperties(target);
                }

                var property = properties.Find(propertyName, true);

                if (property == null)
                {
                    throw new FormatException(string.Format("Unknown command-line argument: " + name));
                }

                // Process argument based on property type.

                var    type = property.PropertyType;
                object value;

                if (type == typeof(bool)) // Boolean?
                {
                    value = true;         // flag-style
                }
                else
                {
                    // If value was paired with name then break out the value
                    // from the pair other read it from the next argument.

                    if (paired)
                    {
                        value = pair.Value;
                    }
                    else
                    {
                        if (!e.MoveNext())
                        {
                            throw new FormatException("Missing value for command-line argument: " + name);
                        }

                        value = e.Current;
                    }

                    // If property is of another type than string and it
                    // support conversion then do that now.

                    if (type != typeof(string))
                    {
                        var converter = property.Converter ?? TypeDescriptor.GetConverter(type);

                        if (!converter.CanConvertFrom(typeof(string)))
                        {
                            throw new FormatException("Unsupported command-line argument:" + name);
                        }

                        value = converter.ConvertFromString(value.ToString());
                    }
                }

                property.SetValue(target, value);
            }

            return(tails.ToArray());
        }
        public JsonResult SearchDataTable()
        {
            DataTablesRequest req = DataTablesRequest.ExtractFormRequest(Request.Form);

            string valorBusqueda = req.searchValue.ToLower();

            int salteo  = req.start;
            int muestro = req.length;

            //Extraigo los campos del modelo, para armar tanto la búsqueda, como el ordenamiento.
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(Contacto));

            /*
             * La lógica de la búsqueda es simple, por cada uno de los campos que admiten ser buscados o campos searchables (por defecto todos),
             * me fijo si en su contenido contienen el valorBusqueda, que es el valor ingresado en el campo de búsqueda, lo hacemos mediante
             *  campo.ToString().ToLower().IndexOf(valorBusqueda) >= 0
             * Como hacemos esto por cada uno de los campos, vamos concatenando cada "consulta" con un OR, por lo que, con que al menos
             * una de todas sea verdadera, la fila en cuestión estará visible.
             *
             * Notar, que arranco la construccion de la consulta con un False, por qué?
             * Esta consulta se podria traducir a:
             *  false OR campo1.ToString().ToLower().IndexOf(valorBusqueda) >= 0 OR campo2.ToString().ToLower().IndexOf(valorBusqueda) >= 0
             * Con que una de las condiciones anteriores se cumpla, es suficiente para que esa fila sea visible.
             * Pero si arrancaramos la consulta con un TRUE, nos quedaria asi:
             *   true OR campo1.ToString().ToLower().IndexOf(valorBusqueda) >= 0 OR campo2.ToString().ToLower().IndexOf(valorBusqueda) >= 0
             * En este caso, todas, pero todas las filas seran visibles, porque todas retornan TRUE.
             */
            var predicateModel = PredicateBuilder.False <Contacto>();

            //Por cada una de las columnas me fijo si es searchable y construyo la consulta.
            for (int i = 0; i < req.columnsSearchable.Count; i++)
            {
                if (req.columnsSearchable[i])                                                      //Si es searchable, entonces...
                {
                    string             columnSearchable = req.columnsName[i].ToLower();            //Nombre de la columna
                    PropertyDescriptor prop             = properties.Find(columnSearchable, true); //Campo correspondiente
                    //Voy armando la consulta concatenando con un OR.
                    predicateModel = predicateModel.Or(x => prop.GetValue(x).ToString().ToLower().IndexOf(valorBusqueda) >= 0);
                }
            }

            //Agrego la consulta a la lista. Notar que convertimos la lista a IQueryable haciendo AsQueryable().
            //Si aplicaramos la consulta sobre Entity Framework esto no haria falta.
            var consultaBasica = Contactos.AsQueryable().Where(predicateModel);

            int cantidadFiltrados = consultaBasica.Count();

            foreach (int orderColumnIndex in req.orderColumn)
            {
                //Puedo ordenar por mas de un campo, por lo tanto, por cada uno, extraigo el nombre,
                //me fijo si es ascendente o descendente, y concateno el ordenamiento a la consulta.
                string             columnToOrder  = req.columnsName[orderColumnIndex].ToLower();
                string             orderDirection = req.orderDir[req.orderColumn.IndexOf(orderColumnIndex)].ToLower();
                PropertyDescriptor prop           = properties.Find(columnToOrder, true);
                if (orderDirection.Equals("asc"))
                {
                    consultaBasica = consultaBasica.OrderBy(x => prop.GetValue(x));
                }
                else
                {
                    consultaBasica = consultaBasica.OrderByDescending(x => prop.GetValue(x));
                }
            }

            consultaBasica = consultaBasica.Skip(salteo).Take(muestro);

            List <Contacto> model = consultaBasica.ToList(); //Realizo la consulta

            string json = JsonConvert.SerializeObject(model, Formatting.None, new IsoDateTimeConverter()
            {
                DateTimeFormat = "dd/MM/yyyy"
            });

            DataTablesResponse respuesta = new DataTablesResponse();

            respuesta.data            = model;
            respuesta.draw            = req.draw;
            respuesta.recordsFiltered = cantidadFiltrados;
            respuesta.recordsTotal    = Contactos.Count();

            return(Json(respuesta, JsonRequestBehavior.AllowGet));
        }
示例#16
0
        /// <summary>
        /// checks the checkboxes according to datasource
        /// </summary>
        private void setHaken()
        {
            if (!ready)
            {
                return;
            }

            this.ItemCheck -= itemCheckChangesHandler;

            //find the currently selected ID in the parent table
            object parentID = null;

            try
            {
                //do we always have type datarowview?!
                //another solution is parentDataManager.GetItemProperties().Find(parentIDMember, false).GetValue(parentDataManager.List[parentDataManager.Position]);
                //currencymanager.current shows buggy behavior sometimes
                DataRowView drv = (DataRowView)this.parentDataManager.Current;
                parentID = drv[this.parentIDMember];
            }
            catch (Exception) { }
            if (parentID == null)
            {
                return;
            }

            ArrayList childValues = new ArrayList();
            PropertyDescriptorCollection relationProps = relationDataManager.GetItemProperties();

            PropertyDescriptor parentValue = relationProps.Find(parentValueMember, false);
            PropertyDescriptor childValue  = relationProps.Find(childValueMember, false);

            for (int i = 0; i < relationDataManager.Count; i++)
            {
                object row = relationDataManager.List[i];
                object val = parentValue.GetValue(row);
                if (parentID.Equals(val))
                {
                    childValues.Add(childValue.GetValue(row));
                }
            }

            for (int i = 0; i < this.Items.Count; i++)
            {
                if (this.Items[i].GetType() != typeof(ListBoxItem))
                {
                    this.SetItemChecked(i, false);
                    continue;
                }

                if (childValues.Contains(((ListBoxItem)this.Items[i]).Value))
                {
                    this.SetItemChecked(i, true);
                }
                else
                {
                    this.SetItemChecked(i, false);
                }
            }
            this.ItemCheck += itemCheckChangesHandler;
        }
示例#17
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);
                }
            }
        }
示例#18
0
        private void gGrupo_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (gGrupo.Columns[e.ColumnIndex].SortMode == DataGridViewColumnSortMode.NotSortable)
            {
                return;
            }
            if (bsGrupo.Count < 1)
            {
                return;
            }
            PropertyDescriptorCollection lP = TypeDescriptor.GetProperties(new CamadaDados.PostoCombustivel.Cadastros.TRegistro_CfgPainelVendaConv_X_Grupo());

            CamadaDados.PostoCombustivel.Cadastros.TList_CfgPainelVendaConv_X_Grupo lComparer;
            SortOrder direcao = SortOrder.None;

            if ((gGrupo.Columns[e.ColumnIndex].HeaderCell.SortGlyphDirection == SortOrder.None) ||
                (gGrupo.Columns[e.ColumnIndex].HeaderCell.SortGlyphDirection == SortOrder.Descending))
            {
                lComparer = new CamadaDados.PostoCombustivel.Cadastros.TList_CfgPainelVendaConv_X_Grupo(lP.Find(gGrupo.Columns[e.ColumnIndex].DataPropertyName, true), SortOrder.Ascending);
                foreach (DataGridViewColumn c in gGrupo.Columns)
                {
                    c.HeaderCell.SortGlyphDirection = SortOrder.None;
                }
                direcao = SortOrder.Ascending;
            }
            else
            {
                lComparer = new CamadaDados.PostoCombustivel.Cadastros.TList_CfgPainelVendaConv_X_Grupo(lP.Find(gGrupo.Columns[e.ColumnIndex].DataPropertyName, true), SortOrder.Descending);
                foreach (DataGridViewColumn c in gGrupo.Columns)
                {
                    c.HeaderCell.SortGlyphDirection = SortOrder.None;
                }
                direcao = SortOrder.Descending;
            }
            (bsGrupo.List as CamadaDados.PostoCombustivel.Cadastros.TList_CfgPainelVendaConv_X_Grupo).Sort(lComparer);
            bsGrupo.ResetBindings(false);
            gGrupo.Columns[e.ColumnIndex].HeaderCell.SortGlyphDirection = direcao;
        }
示例#19
0
        private void InitilizeRelationBinding()
        {
            ClearRelationBinding();
            for (int i = 0; i < this.TreeView.RelationBindings.Count; i++)
            {
                RelationBinding relation = this.TreeView.RelationBindings[i];
                relation.PropertyChanged += new PropertyChangedEventHandler(relation_PropertyChanged);

                CurrencyManager cm = null;
                if (relation.DataSource is BindingSource)
                {
                    cm = ((BindingSource)relation.DataSource).CurrencyManager;
                }

                if (cm == null && relation.DataSource != null)
                {
                    cm = this.TreeView.BindingContext[relation.DataSource, relation.DataMember] as CurrencyManager;
                }

                if (cm != null)
                {
                    WireEvents(cm);

                    PropertyDescriptorCollection properties = null;
                    if (i == 0)
                    {
                        if (((ICurrencyManagerProvider)this.TreeView.ListSource).CurrencyManager != null)
                        {
                            properties = ((ICurrencyManagerProvider)this.TreeView.ListSource).CurrencyManager.GetItemProperties();
                        }
                    }
                    else
                    {
                        properties = this.relationBindings[i - 1].GetItemProperties();
                    }

                    PropertyDescriptor descriptor = null;
                    if (properties != null)
                    {
                        descriptor = properties.Find(relation.ParentMember, true);
                    }

                    if (descriptor == null)
                    {
                        return;
                    }
                    this.TreeView.BoundDescriptors[i].ParentDescriptor = descriptor;

                    properties = cm.GetItemProperties();
                    TreeNodeDescriptor relationDescriptor = new TreeNodeDescriptor();

                    string             childPath = relation.ChildMember.Split('\\')[0];
                    string[]           names     = childPath.Split('.');
                    PropertyDescriptor pd        = properties.Find(names[0], true);
                    if (pd != null)
                    {
                        if (names.Length > 1)
                        {
                            relationDescriptor.SetChildDescriptor(pd, childPath);
                        }
                        else
                        {
                            relationDescriptor.ChildDescriptor = pd;
                        }
                    }

                    string valuePath = relation.ValueMember.Split('\\')[0];
                    names = valuePath.Split('.');
                    pd    = properties.Find(names[0], true);
                    if (pd != null)
                    {
                        if (names.Length > 1)
                        {
                            relationDescriptor.SetValueDescriptor(pd, valuePath);
                        }
                        else
                        {
                            relationDescriptor.ValueDescriptor = pd;
                        }
                    }

                    string displayPath = relation.DisplayMember.Split('\\')[0];
                    names = displayPath.Split('.');
                    pd    = properties.Find(names[0], true);
                    if (pd != null)
                    {
                        if (names.Length > 1)
                        {
                            relationDescriptor.SetDisplaytDescriptor(pd, valuePath);
                        }
                        else
                        {
                            relationDescriptor.DisplayDescriptor = pd;
                        }
                    }



                    this.TreeView.BoundDescriptors.Add(relationDescriptor);

                    AvlTree <RadTreeNode> nodes = new AvlTree <RadTreeNode>(new ChildComparer());
                    this.relationIndex.Add(nodes);
                    this.relationBindings.Add(cm);
                    this.relationLevelLoaded.Add(false);
                }
            }
        }
示例#20
0
        /// <summary>
        /// Applies the sort.
        /// </summary>
        /// <param name="sortBy">Sort by.</param>
        /// <param name="direction">Direction.</param>
        public void ApplySort(string sortBy, ListSortDirection direction)
        {
            PropertyDescriptor descriptor = PropertyDescriptorCollection.Find(sortBy, false);

            Sort(descriptor, direction);
        }
示例#21
0
        public override IList <RadTreeNode> GetNodes(RadTreeNode parent)
        {
            if (parent is RadTreeViewElement.RootTreeNode)
            {
                for (int i = 0; i < this.TreeView.ListSource.Count; i++)
                {
                    this.TreeView.ListSource[i].Parent = parent;
                }

                return(this.TreeView.ListSource);
            }

            if (ResolveDescriptors(parent.BoundIndex + 1, parent.DataBoundItem))
            {
                List <RadTreeNode> nodes    = new List <RadTreeNode>();
                IEnumerable        children = this.TreeView.BoundDescriptors[parent.BoundIndex + 1].ChildDescriptor.GetValue(parent.DataBoundItem) as IEnumerable;
                if (children != null)
                {
                    if (parent.BoundIndex + 1 < this.displayMembers.Length)
                    {
                        PropertyDescriptorCollection properties = ListBindingHelper.GetListItemProperties(children);
                        this.TreeView.BoundDescriptors[parent.BoundIndex + 1].DisplayDescriptor = properties.Find(this.displayMembers[parent.BoundIndex + 1], true);
                    }

                    foreach (object item in children)
                    {
                        RadTreeNode node = this.TreeView.CreateNewNode();
                        ((IDataItem)node).DataBoundItem = item;
                        node.Parent     = parent;
                        node.BoundIndex = parent.BoundIndex + 1;
                        nodes.Add(node);
                    }

                    parent.NodesLoaded = true;
                }

                return(nodes);
            }

            return(RadTreeNodeCollection.Empty);
        }
示例#22
0
        public void SetCurrentObject(IEnumerable <object> obj, bool isEnable = true, bool isRootNode = false, string rootType = "")
        {
            this.isRootNode    = isRootNode;
            this.currentObject = (object)obj;
            if (this._property != null)
            {
                foreach (PropertyItem propertyItem in this._property)
                {
                    if (propertyItem != null && propertyItem.TypeEditor != null)
                    {
                        propertyItem.TypeEditor.EditorDispose();
                    }
                }
            }
            foreach (Widget child in this.container.Children)
            {
                this.container.Remove(child);
            }
            foreach (Widget child in this._propertyTable.Children)
            {
                this._propertyTable.Remove(child);
            }
            if (this._property == null)
            {
                this._property = new List <PropertyItem>();
            }
            this._property.Clear();
            if (obj == null)
            {
                return;
            }
            List <object> source = new List <object>();

            foreach (object obj1 in obj)
            {
                object item = obj1;
                if (source.FirstOrDefault <object>((Func <object, bool>)(w => w.GetType().Name == item.GetType().Name)) == null)
                {
                    source.Add(item);
                }
            }
            if (source.Count <object>() == 0)
            {
                return;
            }
            PropertyDescriptorCollection propertyDescriptors1   = PropertyGridUtilities.GetPropertyDescriptors(this.currentObject = source[0]);
            List <PropertyDescriptor>    propertyDescriptorList = new List <PropertyDescriptor>();

            foreach (PropertyDescriptor propertyDescriptor in propertyDescriptors1)
            {
                propertyDescriptorList.Add(propertyDescriptor);
            }
            for (int index1 = 1; index1 <= source.Count - 1; ++index1)
            {
                PropertyDescriptorCollection propertyDescriptors2 = PropertyGridUtilities.GetPropertyDescriptors(source[index1]);
                for (int index2 = propertyDescriptorList.Count - 1; index2 >= 0; --index2)
                {
                    PropertyDescriptor propertyDescriptor1 = propertyDescriptorList[index2];
                    if (!propertyDescriptors2.Contains(propertyDescriptor1))
                    {
                        propertyDescriptorList.RemoveAt(index2);
                    }
                    else
                    {
                        PropertyDescriptor propertyDescriptor2 = propertyDescriptors2.Find(propertyDescriptor1.Name, true);
                        if (propertyDescriptor2 != null && (propertyDescriptor2.Attributes.OfType <BrowsableAttribute>().FirstOrDefault <BrowsableAttribute>() == null || !propertyDescriptor2.Attributes.OfType <BrowsableAttribute>().FirstOrDefault <BrowsableAttribute>().Browsable))
                        {
                            propertyDescriptorList.RemoveAt(index2);
                        }
                    }
                }
            }
            ITransform currentObject = this.currentObject as ITransform;

            foreach (PropertyDescriptor property in propertyDescriptorList)
            {
                if (property.Attributes.Contains((Attribute) new UndoPropertyAttribute()) || !string.IsNullOrEmpty(property.Category))
                {
                    PropertyItem propertyItem = PropertyGridUtilities.CreatePropertyItem(property, obj.LastOrDefault <object>());
                    if (propertyItem != null)
                    {
                        propertyItem.IsEnable      = isEnable;
                        propertyItem.InstanceList  = obj.ToList <object>();
                        propertyItem.InstanceCount = obj.Count <object>();
                        if (obj.Count <object>() <= 1 || !(propertyItem.Calegory != "Group_Routine"))
                        {
                            this._property.Add(propertyItem);
                        }
                    }
                }
            }
            int type = this._selectTab;

            if (this.currentObject is IPropertyTitle)
            {
                this._generalGrid = new GeneralGrid(new List <string>()
                {
                    LanguageInfo.BasicProperty,
                    LanguageInfo.AdvancedProperty
                }, 0, this._selectTab);
                this._generalGrid.TabChanged += new EventHandler <TabEventArgs>(this._generalGrid_TabChanged);
                this._propertyTable.Attach((Widget)this._generalGrid, 0U, 1U, 0U, 1U, AttachOptions.Expand | AttachOptions.Fill, AttachOptions.Fill, 1U, 0U);
                this._generalGrid.Show();
                this._titleTable = new GeneralTitle(this._editorManager);
                this._propertyTable.Attach((Widget)this._titleTable.hBox, 0U, 1U, 1U, 2U, AttachOptions.Expand | AttachOptions.Fill, AttachOptions.Fill, 1U, 0U);
                this._titleTable.hBox.Show();
                if (this.currentObject is IPropertyTitle)
                {
                    this._titleTable.SetImage(obj.Count <object>() == 1 ? this.currentObject : (object)null, obj.Count <object>(), rootType);
                }
                List <PropertyItem> list = this._property.Where <PropertyItem>((Func <PropertyItem, bool>)(w => w.DiaplayName == "Display_Name" || w.DiaplayName == "Display_Target")).ToList <PropertyItem>();
                if (list != null)
                {
                    this._titleTable.SetControl(list);
                }
                if (list != null)
                {
                    list.ForEach((System.Action <PropertyItem>)(w => this._property.Remove(w)));
                }
                PropertyItem propertyItem = this._property.FirstOrDefault <PropertyItem>((Func <PropertyItem, bool>)(w => w.DiaplayName == "CallBack_ClassName"));
                if (propertyItem != null)
                {
                    if (isRootNode)
                    {
                        this._property.Clear();
                        this._property.Add(propertyItem);
                    }
                    else
                    {
                        this._property.Remove(propertyItem);
                    }
                }
            }
            else
            {
                type = 0;
            }
            this.AddTable(type);
        }
示例#23
0
        private void gProgEspecialVenda_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (gProgEspecialVenda.Columns[e.ColumnIndex].SortMode == DataGridViewColumnSortMode.NotSortable)
            {
                return;
            }
            if (bsProgEspecialVenda.Count < 1)
            {
                return;
            }
            PropertyDescriptorCollection lP = TypeDescriptor.GetProperties(new CamadaDados.Faturamento.ProgEspecialVenda.TRegistro_ProgEspecialVenda());

            CamadaDados.Faturamento.ProgEspecialVenda.TList_ProgEspecialVenda lComparer;
            SortOrder direcao = SortOrder.None;

            if ((gProgEspecialVenda.Columns[e.ColumnIndex].HeaderCell.SortGlyphDirection == SortOrder.None) ||
                (gProgEspecialVenda.Columns[e.ColumnIndex].HeaderCell.SortGlyphDirection == SortOrder.Descending))
            {
                lComparer = new CamadaDados.Faturamento.ProgEspecialVenda.TList_ProgEspecialVenda(lP.Find(gProgEspecialVenda.Columns[e.ColumnIndex].DataPropertyName, true), SortOrder.Ascending);
                foreach (DataGridViewColumn c in gProgEspecialVenda.Columns)
                {
                    c.HeaderCell.SortGlyphDirection = SortOrder.None;
                }
                direcao = SortOrder.Ascending;
            }
            else
            {
                lComparer = new CamadaDados.Faturamento.ProgEspecialVenda.TList_ProgEspecialVenda(lP.Find(gProgEspecialVenda.Columns[e.ColumnIndex].DataPropertyName, true), SortOrder.Descending);
                foreach (DataGridViewColumn c in gProgEspecialVenda.Columns)
                {
                    c.HeaderCell.SortGlyphDirection = SortOrder.None;
                }
                direcao = SortOrder.Descending;
            }
            (bsProgEspecialVenda.List as CamadaDados.Faturamento.ProgEspecialVenda.TList_ProgEspecialVenda).Sort(lComparer);
            bsProgEspecialVenda.ResetBindings(false);
            gProgEspecialVenda.Columns[e.ColumnIndex].HeaderCell.SortGlyphDirection = direcao;
        }
示例#24
0
        protected override object GetValue(Control controlContainer)
        {
            object data       = null;
            string boundField = DataField;

            if (controlContainer == null)
            {
                throw new HttpException("DataControlField_NoContainer");
            }

            // Get the DataItem from the container
            object dataItem = DataBinder.GetDataItem(controlContainer);

            if (dataItem == null && !DesignMode)
            {
                throw new HttpException("DataItem_Not_Found");
            }

            // Get value of field in data item.
            if (!boundField.Equals(ThisExpression) && dataItem != null)
            {
                PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(dataItem);
                string propertyName = boundField;

                // Store current object here as we'll be traversing object graph.
                object currObject = dataItem;

                string[]           propPath = propertyName.Split('.');
                PropertyDescriptor property = null;

                // We're going to access the object graph from the root (dataItem)
                // property by property as specified in the BoundField.
                for (int i = 0; i < propPath.Length; ++i)
                {
                    string currProp = propPath[i];
                    property = properties.Find(currProp, false);

                    if (property == null)
                    {
                        throw new HttpException("Could not find property or subproperty " + currProp);
                    }

                    if (i < propPath.Length - 1)
                    {
                        object newCurrObject = property.GetValue(currObject);

                        if (newCurrObject == null)
                        {
                            // Make binding silently fail to be consistent with ASP.NET databinding.
                            currObject = null;
                            break;
                        }
                        currObject = newCurrObject;
                        properties = TypeDescriptor.GetProperties(currObject);
                    }
                }

                if (property != null)
                {
                    data = currObject != null?property.GetValue(currObject) : null;
                }
            }
            else
            {
                // dataItem is null or we are binding against the data source itself
                data = DesignMode ? GetDesignTimeValue() : dataItem;
            }

            return(data);
        }
示例#25
0
        /// <summary>
        /// Given some properties (Properties) of an object (obj)
        /// this method returns the dump of the values of the given properties
        /// The ToString overloads helps diagnosing collection content and is
        /// particularly useful inside VS.NET debugger
        /// </summary>
        /// <param name="Properties">Property or Property1, Property2</param>
        /// <param name="obj">object to dump</param>
        /// <param name="Postfix">string to append before ")"</param>
        /// <returns>PropertyValue or (PropertyValue1, PropertyValue2, ...)</returns>
        private string GetValuesForProperties(string Properties, T obj, string Postfix)
        {
            if (Properties == null)
            {
                return(obj.ToString());
            }
            if (Properties.Trim().Length == 0 && Postfix.Length == 0)
            {
                return(obj.ToString());
            }

            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            try
            {
                string[] Props = Properties.Split(',');
                if (Props.Length > 1)
                {
                    sb.Append("(");
                }
                if (Props[0].Length != 0)
                {
                    PropertyDescriptorCollection pdc = TypeDescriptor.GetProperties(obj);
                    for (int i = 0; i < Props.Length; i++)
                    {
                        string             Prop = Props[i].Trim();
                        PropertyDescriptor pd   = pdc.Find(Prop, true);
                        if (pd == null)
                        {
                            sb.AppendFormat(null, "{0}=[Invalid Property]", Prop);
                        }
                        else
                        {
                            object PropValue = pd.GetValue(obj);
                            sb.AppendFormat(null, "{0}={1}", Prop, PropValue);
                        }
                        if (i != Props.Length - 1)
                        {
                            sb.Append(", ");
                        }
                    }
                }
                if (Postfix.Length != 0)
                {
                    if (Props[0].Length != 0)
                    {
                        sb.Append(" ");
                    }
                    sb.AppendFormat(null, "[{0}]", Postfix);
                }
                if (Props.Length > 1)
                {
                    sb.Append(")");
                }
            }
            catch (Exception Err)
            {
                System.Diagnostics.Debug.WriteLine(Err.ToString());
                string str = sb.ToString();
                if (str.EndsWith(")"))
                {
                    return(str);
                }
                else
                {
                    return(str + ")");
                }
            }
            return(sb.ToString());
        }
示例#26
0
        private IComponent CreateRootComponentCore(Type controlType, Size controlSize, DesignerLoader loader)
        {
            const string _signature_ = _Name_ + @"::CreateRootComponentCore()";

            try {
                //- step.1
                //- get the IDesignerHost
                //- if we are not not able to get it
                //- then rollback (return without do nothing)
                IDesignerHost host = GetIDesignerHost();
                if (null == host)
                {
                    return(null);
                }
                //- check if the root component has already been set
                //- if so then rollback (return without do nothing)
                if (null != host.RootComponent)
                {
                    return(null);
                }
                //-
                //-
                //- step.2
                //- create a new root component and initialize it via its designer
                //- if the component has not a designer
                //- then rollback (return without do nothing)
                //- else do the initialization
                if (null != loader)
                {
                    this.BeginLoad(loader);
                    if (this.LoadErrors.Count > 0)
                    {
                        throw new Exception(_signature_ + " - Exception: the BeginLoad(loader) failed!");
                    }
                }
                else
                {
                    this.BeginLoad(controlType);
                    if (this.LoadErrors.Count > 0)
                    {
                        throw new Exception(_signature_ + " - Exception: the BeginLoad(Type) failed! Some error during " + controlType.ToString() + " loading");
                    }
                }
                //-
                //-
                //- step.3
                //- try to modify the Size of the object just created
                IDesignerHost ihost = GetIDesignerHost();
                //- Set the backcolor and the Size
                Control ctrl = null;
                if (host.RootComponent is  Form)
                {
                    ctrl           = this.View as Control;
                    ctrl.BackColor = Color.LightGray;
                    //- set the Size
                    PropertyDescriptorCollection pdc = TypeDescriptor.GetProperties(ctrl);
                    //- Sets a PropertyDescriptor to the specific property
                    PropertyDescriptor pdS = pdc.Find("Size", false);
                    if (null != pdS)
                    {
                        object size = pdS.GetValue(host.RootComponent);
                        pdS.SetValue(ihost.RootComponent, controlSize);
                    }
                }
                else if (host.RootComponent is UserControl)
                {
                    ctrl           = this.View as Control;
                    ctrl.BackColor = Color.Gray;
                    //- set the Size
                    PropertyDescriptorCollection pdc = TypeDescriptor.GetProperties(ctrl);
                    //- Sets a PropertyDescriptor to the specific property
                    PropertyDescriptor pdS = pdc.Find("Size", false);
                    if (null != pdS)
                    {
                        pdS.SetValue(ihost.RootComponent, controlSize);
                    }
                }
                else if (host.RootComponent is  Control)
                {
                    ctrl           = this.View as Control;
                    ctrl.BackColor = Color.LightGray;
                    //- set the Size
                    PropertyDescriptorCollection pdc = TypeDescriptor.GetProperties(ctrl);
                    //- Sets a PropertyDescriptor to the specific property
                    PropertyDescriptor pdS = pdc.Find("Size", false);

                    if (null != pdS)
                    {
                        object size = pdS.GetValue(host.RootComponent);
                        pdS.SetValue(ihost.RootComponent, controlSize);
                    }
                }
                else if (host.RootComponent is  Component)
                {
                    ctrl           = this.View as Control;
                    ctrl.BackColor = Color.White;
                    //- don't set the Size
                }
                else
                {
                    //- Undefined Host Type
                    ctrl           = this.View as Control;
                    ctrl.BackColor = Color.Red;
                }

                return(ihost.RootComponent);
            }//end_try
            catch (Exception exx) {
                Debug.WriteLine(exx.Message);
                if (null != exx.InnerException)
                {
                    Debug.WriteLine(exx.InnerException.Message);
                }

                throw;
            }//end_catch
        }
示例#27
0
        // helper stuff

        protected void AddProperty(DynamicTypeDescriptor dt, string name)
        {
            dt.AddProperty(Properties.Find(name, false));
        }
示例#28
0
        public Control CreateControl(ReportUtils.ReportControlProperties reportControlProperties)
        {
            try
            {
                //- step.1
                //- get the IDesignerHost
                //- if we are not able to get it
                //- then rollback (return without do nothing)
                IDesignerHost host = GetIDesignerHost();
                if (null == host)
                {
                    return(null);
                }
                //- check if the root component has already been set
                //- if not so then rollback (return without do nothing)
                if (null == host.RootComponent)
                {
                    return(null);
                }
                //-
                //-
                //- step.2
                //- create a new component and initialize it via its designer
                //- if the component has not a designer
                //- then rollback (return without do nothing)
                //- else do the initialization
                //IComponent newComp = host.CreateComponent(typeof(ReportUtils.Type));
                //IComponent newComp = host.CreateComponent(Type.GetType(reportControlProperties.Type));

                IComponent newComp = host.CreateComponent(GetTypeFromSimpleName(reportControlProperties.Type));

                Type type = GetTypeFromSimpleName(reportControlProperties.Type);

                if (null == newComp)
                {
                    return(null);
                }
                IDesigner designer = host.GetDesigner(newComp);
                if (null == designer)
                {
                    return(null);
                }
                if (designer is IComponentInitializer)
                {
                    ((IComponentInitializer)designer).InitializeNewComponent(null);
                }
                //-
                //-
                //- step.3
                //- try to modify the Size/Location of the object just created
                PropertyDescriptorCollection pdc = TypeDescriptor.GetProperties(newComp);

                //- Sets a PropertyDescriptor to the specific property.
                PropertyDescriptor pdS = pdc.Find("Size", false);
                if (null != pdS)
                {
                    pdS.SetValue(newComp, (reportControlProperties.Size));
                }

                PropertyDescriptor pdName = pdc.Find("Name", false);
                if (null != pdName)
                {
                    pdName.SetValue(newComp, (reportControlProperties.Name));
                }

                PropertyDescriptor pdL = pdc.Find("Location", false);
                if (null != pdL)
                {
                    pdL.SetValue(newComp, new Point(reportControlProperties.Location._X, reportControlProperties.Location._Y));
                }
                PropertyDescriptor pdF = pdc.Find("Font", false);
                if (null != pdF)
                {
                    Font font = new Font(reportControlProperties.Font.FontFamily, reportControlProperties.Font.FontSize, reportControlProperties.Font.FontStyle);
                    pdF.SetValue(newComp, font);
                }
                PropertyDescriptor pdFc = pdc.Find("ForeColor", false);
                if (null != pdFc)
                {
                    Color color = Color.FromName(reportControlProperties.Font.FontColor);
                    if (!color.IsKnownColor)
                    {
                        color = ColorTranslator.FromHtml("#" + color.Name);
                    }
                    pdFc.SetValue(newComp, color);
                }

                PropertyDescriptor pdFBorder = pdc.Find("BorderStyle", false);
                if (null != pdFBorder)
                {
                    if (reportControlProperties.Border)
                    {
                        pdFBorder.SetValue(newComp, BorderStyle.FixedSingle);
                    }
                    else
                    {
                        pdFBorder.SetValue(newComp, BorderStyle.None);
                    }
                }

                PropertyDescriptor pdText = pdc.Find("Text", false);
                if (null != pdText)
                {
                    pdText.SetValue(newComp, reportControlProperties.Text);
                }

                if (type == typeof(PictureBox))
                {
                    PropertyDescriptor pdImageLocation = pdc.Find("ImageLocation", false);
                    if (null != pdImageLocation)
                    {
                        pdImageLocation.SetValue(newComp, reportControlProperties.ImageName);
                    }
                    pdImageLocation = pdc.Find("SizeMode", false);
                    if (null != pdImageLocation)
                    {
                        pdImageLocation.SetValue(newComp, PictureBoxSizeMode.Zoom);
                    }
                }

                PropertyDescriptor pdMultiLine = pdc.Find("Multiline", false);
                if (null != pdMultiLine)
                {
                    pdMultiLine.SetValue(newComp, reportControlProperties.MultiLine);
                }
                PropertyDescriptor pdTextAlign = pdc.Find("TextAlign", false);
                if (null != pdTextAlign)
                {
                    if (type == typeof(Label))
                    {
                        ContentAlignment c = (ContentAlignment)Enum.Parse(typeof(ContentAlignment), reportControlProperties.TextAlign.ToString());
                        pdTextAlign.SetValue(newComp, c);
                    }
                }

                PropertyDescriptor pdTag = pdc.Find("Tag", false);
                if (null != pdTag)
                {
                    pdTag.SetValue(newComp, reportControlProperties.Binding);
                }

                if (type == typeof(TableLayoutPanel))
                {
                    PropertyDescriptor pdTableLayout = pdc.Find("RowCount", false);
                    if (null != pdTableLayout)
                    {
                        pdTableLayout.SetValue(newComp, reportControlProperties.RowsColumns._Rows);
                    }
                    pdTableLayout = pdc.Find("ColumnCount", false);
                    if (null != pdTableLayout)
                    {
                        pdTableLayout.SetValue(newComp, reportControlProperties.RowsColumns._Columns);
                    }
                    pdTableLayout = pdc.Find("CellBorderStyle", false);
                    if (null != pdTableLayout)
                    {
                        if (reportControlProperties.Border)
                        {
                            pdTableLayout.SetValue(newComp, DataGridViewAdvancedCellBorderStyle.Single);
                        }
                        else
                        {
                            pdTableLayout.SetValue(newComp, DataGridViewAdvancedCellBorderStyle.None);
                        }
                    }
                }
                if (type == typeof(IVL_ImagePanel))
                {
                    PropertyDescriptor pdTableLayout = pdc.Find("Images", false);
                    if (null != pdTableLayout)
                    {
                        pdTableLayout.SetValue(newComp, reportControlProperties.NumberOfImages);
                    }
                    pdTableLayout = pdc.Find("BorderStyle", false);
                    if (null != pdTableLayout)
                    {
                        pdTableLayout.SetValue(newComp, BorderStyle.FixedSingle);
                    }
                }
                //-
                //-
                //- step.4
                //- commit the Creation Operation
                //- adding the control to the DesignSurface's root component
                //- and return the control just created to let further initializations
                ((Control)newComp).Parent = host.RootComponent as Control;
                return(newComp as Control);
            }//end_try
            catch (Exception exx)
            {
                Debug.WriteLine(exx.Message);
                if (null != exx.InnerException)
                {
                    Debug.WriteLine(exx.InnerException.Message);
                }

                throw;
            }//end_catch
        }
示例#29
0
        /// <summary>
        /// Is called when (un)checking items of the listbox. updates the datasource relation table
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BoundCheckedListBox_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            if (!ready)
            {
                return;
            }

            if (e.Index < 0 || e.Index >= this.Items.Count)
            {
                return;
            }

            //just in case someone adds items manually
            //do not do that!
            if (this.Items[e.Index].GetType() != typeof(ListBoxItem))
            {
                return;
            }

            //find the currently selected ID in the parent table
            object parentID = null;
            object childID  = ((ListBoxItem)this.Items[e.Index]).Value;

            try
            {
                //do we always have type datarowview?!
                //another solution is parentDataManager.GetItemProperties().Find(parentIDMember, false).GetValue(parentDataManager.List[parentDataManager.Position]);
                //currencymanager.current shows buggy behavior sometimes when used with tostring()
                DataRowView drv = (DataRowView)this.parentDataManager.Current;
                parentID = drv[this.parentIDMember];
            }
            catch (Exception) { }

            if (parentID == null || childID == null)
            {
                return;
            }
            ArrayList rows = new ArrayList();
            PropertyDescriptorCollection relationProps = relationDataManager.GetItemProperties();

            PropertyDescriptor parentValue = relationProps.Find(parentValueMember, false);
            PropertyDescriptor childValue  = relationProps.Find(childValueMember, false);

            //find row(s) with current parentID and childId of item being (un)checked
            for (int i = 0; i < relationDataManager.Count; i++)
            {
                object row = relationDataManager.List[i];
                object val = parentValue.GetValue(row);
                if (!parentID.Equals(val))
                {
                    continue;
                }

                val = childValue.GetValue(row);

                if (childID.Equals(val))
                {
                    rows.Add(row);
                }
            }

            if (e.NewValue == CheckState.Checked)
            {
                //case: changing to checked state
                bool exists = false;
                foreach (DataRowView curRow in rows)
                {
                    //just in case of more than one row with same IDs, keep only one
                    if (exists)
                    {
                        curRow.Delete();
                    }

                    //TODO: we should rather undelete deleted rows than always create new ones and delete them
                    //means we might end in having several deleted rows with same ids
                    //but how to get hands on 'em?! maybe through dataview or sth.

                    /*if (curRow.Row.RowState == DataRowState.Deleted)
                     *  curRow.Row.
                     *  continue;*/

                    if (curRow.Row.RowState != DataRowState.Deleted &&
                        curRow.Row.RowState != DataRowState.Detached)
                    {
                        exists = true;
                    }
                }
                //if none was found, which should be the normal case, create one
                //attention! assign allownull to your colums in your dataset or assign proper default values
                if (!exists)
                {
                    relationDataManager.AddNew();
                    ((DataRowView)relationDataManager.Current)[parentValueMember] = parentID;
                    ((DataRowView)relationDataManager.Current)[childValueMember]  = childID;
                }
            }
            else if (e.NewValue == CheckState.Unchecked)
            {
                //case: changing to unchecked state
                //delete all concerned rows
                foreach (DataRowView curRow in rows)
                {
                    if (curRow.Row.RowState == DataRowState.Deleted)
                    {
                        continue;
                    }
                    else
                    {
                        curRow.Delete();
                    }
                }
            }
        }
        public void Find(string name, bool ignoreCase, bool exists)
        {
            const int LoopCount = 100;
            var propertyDescriptors = new PropertyDescriptor[]
            {
                new MockPropertyDescriptor("propertyDescriptor1"),
                new MockPropertyDescriptor("propertyDescriptor2"),
                new MockPropertyDescriptor("propertyDescriptor3"),
                new MockPropertyDescriptor("propertyDescriptor4"),
                new MockPropertyDescriptor("propertyDescriptor5"),
                new MockPropertyDescriptor("propertyDescriptor6"),
                new MockPropertyDescriptor("propertyDescriptor7"),
                new MockPropertyDescriptor("propertyDescriptor8"),
                new MockPropertyDescriptor("propertyDescriptor9")
            };

            // Loop through as there is caching that occurs
            for (int count = 0; count < LoopCount; count++)
            {
                var collection = new PropertyDescriptorCollection(propertyDescriptors);
                var result = collection.Find(name, ignoreCase);

                if (exists)
                {
                    Assert.NotNull(result);

                    PropertyDescriptor expected = propertyDescriptors
                        .First(p => string.Equals(p.Name, name, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal));

                    Assert.Equal(expected, result);
                }
                else
                {
                    Assert.Null(result);
                }
            }
        }
示例#31
0
        public static object ResolveDataSource(object dataSource, string dataMember)
        {
            if (dataSource == null)
            {
                return(null);
            }

            if (dataSource is IEnumerable)
            {
                return((IEnumerable)dataSource);
            }
            else if (dataSource is IListSource)
            {
                IList       list       = null;
                IListSource listSource = (IListSource)dataSource;
                list = listSource.GetList();
                if (listSource.ContainsListCollection)
                {
                    ITypedList typedList = (ITypedList)list;
                    PropertyDescriptorCollection propDescCol =
                        typedList.GetItemProperties(new PropertyDescriptor[0]); //was (null)

                    if (propDescCol.Count == 0)
                    {
                        throw new Exception("ListSource without DataMembers");
                    }

                    PropertyDescriptor propDesc = null;
                    //Check to see if dataMember has a value, if not, default to first
                    //property (DataTable) in the property collection (DataTableCollection)
                    if ((dataMember == null) || (dataMember.Length < 1))
                    {
                        propDesc = propDescCol[0];
                    }
                    else //If dataMember is set, try to find it in the property collection
                    {
                        propDesc = propDescCol.Find(dataMember, true);
                    }

                    if (propDesc == null)
                    {
                        throw new Exception("ListSource missing DataMember");
                    }

                    object listitem = list[0];

                    //Get the value of the property (DataTable) of interest
                    object member = propDesc.GetValue(listitem);

                    if ((member == null) || !(member is IEnumerable))
                    {
                        throw new Exception("ListSource missing DataMember");
                    }

                    return((IEnumerable)member);
                }
                else
                {
                    return((IEnumerable)list); //robcamer added (IEnumerable)
                }
            }
            return(null);
        }