public override object ConvertTo (ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
		{
			if (context == null)
				return null;
			var p = context.GetService (typeof (IXamlNameProvider)) as IXamlNameProvider;
			return p != null ? p.GetName (value) : null;
		}
		public override bool CanConvertTo (ITypeDescriptorContext context, Type destinationType)
		{
			if (context == null)
				return false;
			var p = context.GetService (typeof (IXamlNameProvider)) as IXamlNameProvider;
			return p != null && destinationType == typeof (string);
		}
        /// <summary> 
        ///     Convert a string like "Button.Click" into the corresponding RoutedEvent
        /// </summary> 
        public override object ConvertFrom(ITypeDescriptorContext typeDescriptorContext, 
                                           CultureInfo cultureInfo,
                                           object source) 
        {
            if (typeDescriptorContext == null)
            {
                throw new ArgumentNullException("typeDescriptorContext"); 
            }
            if (source == null) 
            { 
                throw new ArgumentNullException("source");
            } 
            IRootObjectProvider rootProvider = typeDescriptorContext.GetService(typeof(IRootObjectProvider)) as IRootObjectProvider;
            if (rootProvider != null && source is String)
            {
                IProvideValueTarget ipvt = typeDescriptorContext.GetService(typeof(IProvideValueTarget)) as IProvideValueTarget; 
                if (ipvt != null)
                { 
                    EventSetter setter = ipvt.TargetObject as EventSetter; 
                    string handlerName;
                    if(setter != null && (handlerName = source as string) != null) 
                    {
                        handlerName = handlerName.Trim();
                        return Delegate.CreateDelegate(setter.Event.HandlerType, rootProvider.RootObject, handlerName);
                    } 
                }
            } 
 
            throw GetConvertFromException(source);
        } 
		/// <summary>
		/// Converts the given object to the corresponding <see cref="System.Type"/>,
		/// using the specified context and culture information.
		/// </summary>
		/// <param name="culture">The <see cref="System.Globalization.CultureInfo"/> to
		/// use as the current culture. </param>
		/// <param name="context">An 
		/// <see cref="System.ComponentModel.ITypeDescriptorContext"/> that provides a
		/// format context. </param>
		/// <param name="value">The <see cref="System.Object"/> to convert. </param>
		/// <returns>
		/// An <see cref="System.Object"/> that represents the converted value.
		/// </returns>
		/// <exception cref="System.NotSupportedException">The conversion cannot be
		/// performed. </exception>
		public override object ConvertFrom(
			ITypeDescriptorContext context,
			CultureInfo            culture,
			object                 value)
		{
			if (value == null)
				return null;

			if (!(value is string))
				return base.ConvertFrom(context, culture, value);

			string str = (string)value;

			if (str.Length == 0 || str == NoType)
				return null;

			// Try VisualStudio own service first.
			//
			ITypeResolutionService typeResolver =
				(ITypeResolutionService)context.GetService(typeof(ITypeResolutionService));

			if (typeResolver != null)
			{
				Type type = typeResolver.GetType(str);

				if (type != null)
					return type;
			}

			return Type.GetType(str);
		}
	// Convert from another type to the one represented by this class.
	public override Object ConvertFrom(ITypeDescriptorContext context,
									   CultureInfo culture,
									   Object value)
			{
				if(value is String)
				{
					String val = (String)value;
					IReferenceService service;
					IContainer container;
					if(val == "(none)")
					{
						return null;
					}
					if(context != null)
					{
						service = (IReferenceService)
							(context.GetService(typeof(IReferenceService)));
						if(service != null)
						{
							return service.GetReference(val);
						}
						container = context.Container;
						if(container != null)
						{
							return container.Components[val];
						}
					}
					return null;
				}
				return base.ConvertFrom(context, culture, value);
			}
        /// <devdoc>
        /// Returns a collection of standard values retrieved from the context specified
        /// by the specified type descriptor.
        /// </devdoc>
        public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) {
            if (context == null) {
                return null;
            }

            // Get ControlID
            ControlParameter param = (ControlParameter)context.Instance;
            string controlID = param.ControlID;

            // Check that we actually have a control ID
            if (String.IsNullOrEmpty(controlID))
                return null;

            // Get designer host
            IDesignerHost host = (IDesignerHost)context.GetService(typeof(IDesignerHost));
            Debug.Assert(host != null, "Unable to get IDesignerHost in ControlPropertyNameConverter");

            if (host == null)
                return null;

            // Get control
            ComponentCollection allComponents = host.Container.Components;

            Control control = allComponents[controlID] as Control;

            if (control == null)
                return null;

            string[] propertyNames = GetPropertyNames(control);

            return new StandardValuesCollection(propertyNames);
        }
        public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
        {
            DTE service = (DTE)context.GetService(typeof(DTE));

              Cursor.Current = Cursors.WaitCursor;

              if (list != null)
              {
            return new StandardValuesCollection(list.ToArray());
              }

              list = new List<NameValueItem>();

              if (context != null)
              {
                SharePointBrigdeHelper helper = new SharePointBrigdeHelper(service);
                foreach (SharePointSolution solution in helper.GetAllSharePointSolutions())
            {
              NameValueItem item = new NameValueItem();
              item.Name = solution.Name;
              item.Value = solution.Name;
              item.ItemType = "Solution";
              item.Description = solution.DeploymentState;
              list.Add(item);
            }
              }

              Cursor.Current = Cursors.Default;

              return new StandardValuesCollection(list.ToArray());
        }
 public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
 {
     IDesignerHost service = (IDesignerHost) context.GetService(typeof(IDesignerHost));
     DataGrid instance = (DataGrid) context.Instance;
     ((BaseDataListDesigner) service.GetDesigner(instance)).InvokePropertyBuilder(DataGridComponentEditor.IDX_COLUMNS);
     return value;
 }
 public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
 {
     IDesignerHost service = (IDesignerHost) context.GetService(typeof(IDesignerHost));
     Menu instance = (Menu) context.Instance;
     ((MenuDesigner) service.GetDesigner(instance)).InvokeMenuItemCollectionEditor();
     return value;
 }
示例#10
0
        /// <summary>
        /// Parse - this method is called by the type converter to parse a Brush's string 
        /// (provided in "value") with the given IFormatProvider.
        /// </summary>
        /// <returns>
        /// A Brush which was created by parsing the "value".
        /// </returns>
        /// <param name="value"> String representation of a Brush.  Cannot be null/empty. </param>
        /// <param name="context"> The ITypeDescriptorContext for this call. </param>
        internal static Brush Parse(string value, ITypeDescriptorContext context)
        {
            Brush brush;
            IFreezeFreezables freezer = null;
            if (context != null)
            {
                freezer = (IFreezeFreezables)context.GetService(typeof(IFreezeFreezables));
                if ((freezer != null) && freezer.FreezeFreezables)
                {
                    brush = (Brush)freezer.TryGetFreezable(value);
                    if (brush != null)
                    {
                        return brush;
                    }
                }
            }
            
            brush = Parsers.ParseBrush(value, System.Windows.Markup.TypeConverterHelper.InvariantEnglishUS, context);
            
            if ((brush != null) && (freezer != null) && (freezer.FreezeFreezables))
            {
                freezer.TryFreeze(value, brush);
            }

            return brush;
        }
 public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
 {
     IDesignerHost service = (IDesignerHost)context.GetService(typeof(IDesignerHost));
     DeluxeTree component = (DeluxeTree)context.Instance;
     ((DeluxeTreeItemsDesigner)service.GetDesigner(component)).InvokeMenuItemCollectionEditor();
     return value;
 }
 public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
 {
     IDesignerHost service = (IDesignerHost) context.GetService(typeof(IDesignerHost));
     TreeView instance = (TreeView) context.Instance;
     ((TreeViewDesigner) service.GetDesigner(instance)).InvokeTreeNodeCollectionEditor();
     return value;
 }
示例#13
0
		public override object ConvertFrom (ITypeDescriptorContext context,
						    CultureInfo culture,
						    object value)
		{
			if (!(value is string))
				return base.ConvertFrom(context, culture, value);
			
			
			if (context != null) {
				object reference = null;
				// try 1 - IReferenceService
				IReferenceService referenceService = context.GetService (typeof (IReferenceService)) as IReferenceService;
				if (referenceService != null)
					reference = referenceService.GetReference ((string)value);

				// try 2 - Component by name
				if (reference == null) {
					if (context.Container != null && context.Container.Components != null)
						reference = context.Container.Components[(string)value];
				}

				return reference;
			}

			return null;
		}
        public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
        {
            Cursor.Current = Cursors.WaitCursor;

              /*
            if(list != null)
            {
              return new StandardValuesCollection(list.ToArray());
            }
              */

            list = new List<NameValueItem>();

            if (context != null)
            {
              _DTE service = (_DTE)context.GetService(typeof(_DTE));

              foreach (Project project in Helpers.GetAllProjects(service))
              {
            Helpers.GetAllFeatures(list, project);
              }
            }

            Cursor.Current = Cursors.Default;

            return new StandardValuesCollection(list.ToArray());
        }
 /// <internalonly/>
 /// <devdoc>
 ///    <para>Converts the given object to the reference type.</para>
 /// </devdoc>
 public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) {
 
     if (value is string) {
         string text = ((string)value).Trim();
         
         if (!String.Equals(text, none) && context != null) {
         
             // Try the reference service first.
             //
             IReferenceService refSvc = (IReferenceService)context.GetService(typeof(IReferenceService));
             if (refSvc != null) {
                 object obj = refSvc.GetReference(text);
                 if (obj != null) {
                     return obj;
                 }
             }
             
             // Now try IContainer
             //
             IContainer cont = context.Container;
             if (cont != null) {
                 object obj = cont.Components[text];
                 if (obj != null) {
                     return obj;
                 }
             }
         }
         return null;
         
     }
     return base.ConvertFrom(context, culture, value);
 }
 public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
 {
     if (!(value is string))
     {
         return base.ConvertFrom(context, culture, value);
     }
     string a = ((string) value).Trim();
     if (!string.Equals(a, none) && (context != null))
     {
         IReferenceService service = (IReferenceService) context.GetService(typeof(IReferenceService));
         if (service != null)
         {
             object reference = service.GetReference(a);
             if (reference != null)
             {
                 return reference;
             }
         }
         IContainer container = context.Container;
         if (container != null)
         {
             object obj3 = container.Components[a];
             if (obj3 != null)
             {
                 return obj3;
             }
         }
     }
     return null;
 }
 private IEventBindingService GetEventPropertyService(object obj, ITypeDescriptorContext context)
 {
     IEventBindingService service = null;
     if (!this.sunkEvent)
     {
         IDesignerEventService service2 = (IDesignerEventService) this.sp.GetService(typeof(IDesignerEventService));
         if (service2 != null)
         {
             service2.ActiveDesignerChanged += new ActiveDesignerEventHandler(this.OnActiveDesignerChanged);
         }
         this.sunkEvent = true;
     }
     if ((service == null) && (this.currentHost != null))
     {
         service = (IEventBindingService) this.currentHost.GetService(typeof(IEventBindingService));
     }
     if ((service == null) && (obj is IComponent))
     {
         ISite site = ((IComponent) obj).Site;
         if (site != null)
         {
             service = (IEventBindingService) site.GetService(typeof(IEventBindingService));
         }
     }
     if ((service == null) && (context != null))
     {
         service = (IEventBindingService) context.GetService(typeof(IEventBindingService));
     }
     return service;
 }
 public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
 {
     if ((context == null) || !(context.GetService(typeof(IXamlNameProvider)) is IXamlNameProvider))
     {
         return false;
     }
     return ((destinationType == typeof(string)) || base.CanConvertTo(context, destinationType));
 }
        public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
        {
            Cursor.Current = Cursors.WaitCursor;

            list = new List<string>();

            if (context != null)
            {
              DTE service = (DTE)context.GetService(typeof(DTE));
              try
              {
              if (service.SelectedItems.Count > 0)
              {
                  SelectedItem item = service.SelectedItems.Item(1);
                  ProjectItem selectedItem = null;

                  if (item is ProjectItem)
                  {
                      selectedItem = item as ProjectItem;
                  }
                  else if(item.ProjectItem is ProjectItem)
                  {
                      selectedItem = item.ProjectItem as ProjectItem;
                  }

                  if(selectedItem != null)
                  {
                      string itemPath = Helpers.GetFullPathOfProjectItem(selectedItem);

                      XmlDocument msbuildDoc = new XmlDocument();
                      msbuildDoc.Load(itemPath);

                      //what is the scope of the feature
                      XmlNamespaceManager msbuildnsmgr = new XmlNamespaceManager(msbuildDoc.NameTable);
                      msbuildnsmgr.AddNamespace("ns", "http://schemas.microsoft.com/developer/msbuild/2003");

                      foreach (XmlNode targetNode in msbuildDoc.SelectNodes("/ns:Project/ns:Target", msbuildnsmgr))
                      {
                          try
                          {
                            list.Add(targetNode.Attributes["Name"].Value);
                          }
                          catch(Exception)
                          {
                          }
                      }
                  }
              }
              }
              catch (Exception)
              {
              }
            }

            Cursor.Current = Cursors.Default;

            return new StandardValuesCollection(list.ToArray());
        }
 internal static void GetRootObjectAndDelegateType(ITypeDescriptorContext context, out object rootObject, out Type delegateType)
 {
     rootObject = null;
     delegateType = null;
     if (context != null)
     {
         IRootObjectProvider service = context.GetService(typeof(IRootObjectProvider)) as IRootObjectProvider;
         if (service != null)
         {
             rootObject = service.RootObject;
             IDestinationTypeProvider provider2 = context.GetService(typeof(IDestinationTypeProvider)) as IDestinationTypeProvider;
             if (provider2 != null)
             {
                 delegateType = provider2.GetDestinationType();
             }
         }
     }
 }
示例#21
0
		public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) {
			var service = (IWindowsFormsEditorService) context.GetService(typeof (IWindowsFormsEditorService));
			if (service != null) {
				var instance = (updateController) context.Instance;
				var releaseFilterControlInstance = new releaseFilterControl((releaseFilterType) value);
				service.DropDownControl(releaseFilterControlInstance);
				return releaseFilterControlInstance.Value;
			}
			return value;
		}
示例#22
0
		public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
		{
			if (context == null)
				return UITypeEditorEditStyle.DropDown;

			var dspService = (DataSourceProviderService)context.GetService(typeof(DataSourceProviderService));

			return dspService == null || !dspService.SupportsAddNewDataSource?
				UITypeEditorEditStyle.Modal: UITypeEditorEditStyle.DropDown;
		}
示例#23
0
		public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context,
			object value, System.Attribute[] attributes)
		{
			ArrayList props = new ArrayList(TypeDescriptor.GetProperties(value, attributes));
			IEditContext ec = (IEditContext)context.GetService(typeof (IEditContext));
			foreach (CultureInfo ci in ec.AvailableCultures)
				props.Add(new LocalePropertyDescriptor(ci));
			return new PropertyDescriptorCollection((PropertyDescriptor[])props.ToArray(
				typeof (PropertyDescriptor)));
		}
        /// <summary>
        /// Returns a collection of standard values for the data type this type converter is designed for when provided with a format context.
        /// </summary>
        /// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext"/> that provides a format context that can be used to extract additional information about the environment from which this converter is invoked. This parameter or properties of this parameter can be null.</param>
        /// <returns>
        /// A <see cref="T:System.ComponentModel.TypeConverter.StandardValuesCollection"/> that holds a standard set of valid values, or null if the data type does not support a standard set of values.
        /// </returns>
        public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
        {
            var patternManager = context.GetService<IPatternManager>();
            var extensionPoints =
                patternManager.InstalledToolkits.SelectMany(f => f.Schema.FindAll<IExtensionPointSchema>())
                .Where(this.filter)
                .Select(ext => CreateStandardValue(ext));

            return new StandardValuesCollection(extensionPoints.ToList());
        }
示例#25
0
 /// <summary>
 /// Converts the given object to the type of this converter, using the specified context and culture information.
 /// </summary>
 /// <param name="context">An System.ComponentModel.ITypeDescriptorContext that provides a format context.</param>
 /// <param name="culture">The System.Globalization.CultureInfo to use as the current culture.</param>
 /// <param name="value">The System.Object to convert.</param>
 /// <returns>An System.Object that represents the converted value.</returns>
 public override object ConvertFrom(ITypeDescriptorContext context, Globalization.CultureInfo culture, object value)
 {
     if (context == null)
         throw new ArgumentNullException("context");
     Guid id;
     if (!Guid.TryParse((string)value, out id))
         return null;
     dynamic queryable = context.GetService(((EntityValueConverterContext)context).Property.Property.PropertyType);
     return queryable.GetEntity(id);
 }
示例#26
0
		public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) {
			var service = (IWindowsFormsEditorService) context.GetService(typeof (IWindowsFormsEditorService));
			if (service != null) {
				var instance = (updateController) context.Instance;
				var vEditor = new versionEditorControl((string) value, instance.retrieveHostVersion);
				service.DropDownControl(vEditor);
				return parseVersion(vEditor.Value);
			}
			return value;
		}
        /// <summary>
        ///     Convert a string like "Button.Click" into the corresponding RoutedEvent
        /// </summary>
        public override object ConvertFrom(ITypeDescriptorContext typeDescriptorContext,
                                           CultureInfo cultureInfo,
                                           object source)
        {
            if (typeDescriptorContext == null)
            {
                throw new ArgumentNullException("typeDescriptorContext");
            }
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }
            if (s_ServiceProviderContextType == null)
            {
                // get typeof(MS.Internal.Xaml.ServiceProviderContext) via reflection
                Assembly a = typeof(IRootObjectProvider).Assembly;
                s_ServiceProviderContextType = a.GetType("MS.Internal.Xaml.ServiceProviderContext");
            }
            if (typeDescriptorContext.GetType() != s_ServiceProviderContextType)
            {
                // if the caller is not the XAML parser, don't answer.   This avoids
                // returning an arbitrary delegate to a (possibly malicious) caller.
                // See Dev11 629384.
                throw new ArgumentException(SR.Get(SRID.TextRange_InvalidParameterValue), "typeDescriptorContext");
            }
            IRootObjectProvider rootProvider = typeDescriptorContext.GetService(typeof(IRootObjectProvider)) as IRootObjectProvider;
            if (rootProvider != null && source is String)
            {
                IProvideValueTarget ipvt = typeDescriptorContext.GetService(typeof(IProvideValueTarget)) as IProvideValueTarget;
                if (ipvt != null)
                {
                    EventSetter setter = ipvt.TargetObject as EventSetter;
                    string handlerName;
                    if(setter != null && (handlerName = source as string) != null)
                    {
                        handlerName = handlerName.Trim();
                        return Delegate.CreateDelegate(setter.Event.HandlerType, rootProvider.RootObject, handlerName);
                    }
                }
            }

            throw GetConvertFromException(source);
        }
 List<Type> GetDbContextTypes(ITypeDescriptorContext context)
 {
     var values = new List<Type>();
     var tds = context.GetService(typeof(ITypeDiscoveryService)) as ITypeDiscoveryService;
     if (tds != null)
     {
         values.AddRange(from Type t in tds.GetTypes(typeof (System.Data.Entity.DbContext), true) where t.IsPublic && t.IsVisible && !t.IsAbstract && t != typeof (System.Data.Entity.DbContext) select t);
     }
     return values;
 }
示例#29
0
 public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
 {
     IDesignerHost service = (IDesignerHost) context.GetService(typeof(IDesignerHost));
     ObjectList instance = (ObjectList) context.Instance;
     ObjectListDesigner designer = (ObjectListDesigner) service.GetDesigner(instance);
     if (designer.ActiveDeviceFilter == null)
     {
         designer.InvokePropertyBuilder(2);
     }
     return value;
 }
        /// <summary>
        /// Returns a collection of standard values for the data type this type converter is designed for when provided with a format context.
        /// </summary>
        /// <param name="context">An <see cref="ITypeDescriptorContext"/> that provides a format context that can be used to extract additional information about the environment from which this converter is invoked. This parameter or properties of this parameter can be null.</param>
        /// <returns>
        /// A <see cref="TypeConverter.StandardValuesCollection"/> that holds a standard set of valid values, or null if the data type does not support a standard set of values.
        /// </returns>
        public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
        {
            var guidanceManager = context.GetService<IGuidanceManager>();

            var values = guidanceManager.InstantiatedGuidanceExtensions
                .Select(e => new StandardValue(e.InstanceName, e.InstanceName, GetDescription(guidanceManager, e)))
                .Concat(new[] { new StandardValue(Resources.GuidanceExtensionsTypeConverter_None, string.Empty) })
                .ToArray();

            return new StandardValuesCollection(values);
        }
示例#31
0
        /// <internalonly/>
        /// <summary>
        ///    <para>Converts the given value object to the reference type
        ///       using the specified context and arguments.</para>
        /// </summary>
        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            if (destinationType == null)
            {
                throw new ArgumentNullException(nameof(destinationType));
            }

            if (destinationType == typeof(string))
            {
                if (value != null)
                {
                    // Try the reference service first.
                    //
                    IReferenceService refSvc = (IReferenceService)context?.GetService(typeof(IReferenceService));
                    if (refSvc != null)
                    {
                        string name = refSvc.GetName(value);
                        if (name != null)
                        {
                            return(name);
                        }
                    }

                    // Now see if this is an IComponent.
                    //
                    if (!Marshal.IsComObject(value) && value is IComponent)
                    {
                        IComponent comp = (IComponent)value;
                        ISite      site = comp.Site;
                        string     name = site?.Name;
                        if (name != null)
                        {
                            return(name);
                        }
                    }

                    // Couldn't find it.
                    return(String.Empty);
                }
                return(s_none);
            }

            return(base.ConvertTo(context, culture, value, destinationType));
        }
示例#32
0
        /// <summary>
        /// Converts the given value object to the reference type using the specified context and arguments.
        /// </summary>
        public override object?ConvertTo(ITypeDescriptorContext?context, CultureInfo?culture, object?value, Type destinationType)
        {
            if (destinationType == typeof(string))
            {
                if (value != null)
                {
                    // Try the reference service first.
                    if (context?.GetService(typeof(IReferenceService)) is IReferenceService refSvc)
                    {
                        string?name = refSvc.GetName(value);
                        if (name != null)
                        {
                            return(name);
                        }
                    }

                    // Now see if this is an IComponent.
                    if (!Marshal.IsComObject(value) && value is IComponent comp)
                    {
                        ISite? site = comp.Site;
                        string?name = site?.Name;
                        if (name != null)
                        {
                            return(name);
                        }
                    }

                    // Couldn't find it.
                    return(string.Empty);
                }

                return(s_none);
            }

            return(base.ConvertTo(context, culture, value, destinationType));
        }
示例#33
0
        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            var text = value as string;

            if (text != null)
            {
                var rootObjectProvider      = context.GetService(typeof(IRootObjectProvider)) as IRootObjectProvider;
                var destinationTypeProvider = context.GetService(typeof(IDestinationTypeProvider)) as IDestinationTypeProvider;
                if (rootObjectProvider != null && destinationTypeProvider != null)
                {
                    var target          = rootObjectProvider.RootObject;
                    var eventType       = destinationTypeProvider.GetDestinationType();
                    var eventParameters = eventType.GetRuntimeMethods().First(r => r.Name == "Invoke").GetParameters();
                    // go in reverse to match System.Xaml behaviour
                    var methods = target.GetType().GetRuntimeMethods().Reverse();

                    // find based on exact match parameter types first
                    foreach (var method in methods)
                    {
                        if (method.Name != text)
                        {
                            continue;
                        }
                        var parameters = method.GetParameters();
                        if (eventParameters.Length != parameters.Length)
                        {
                            continue;
                        }
                        if (parameters.Length == 0)
                        {
                            return(method.CreateDelegate(eventType, target));
                        }

                        for (int i = 0; i < parameters.Length; i++)
                        {
                            var param      = parameters[i];
                            var eventParam = eventParameters[i];
                            if (param.ParameterType != eventParam.ParameterType)
                            {
                                break;
                            }
                            if (i == parameters.Length - 1)
                            {
                                return(method.CreateDelegate(eventType, target));
                            }
                        }
                    }

                    // EnhancedXaml: Find method with compatible base class parameters
                    foreach (var method in methods)
                    {
                        if (method.Name != text)
                        {
                            continue;
                        }
                        var parameters = method.GetParameters();
                        if (parameters.Length == 0 || eventParameters.Length != parameters.Length)
                        {
                            continue;
                        }

                        for (int i = 0; i < parameters.Length; i++)
                        {
                            var param      = parameters[i];
                            var eventParam = eventParameters[i];
                            if (!param.ParameterType.GetTypeInfo().IsAssignableFrom(eventParam.ParameterType.GetTypeInfo()))
                            {
                                break;
                            }
                            if (i == parameters.Length - 1)
                            {
                                return(method.CreateDelegate(eventType, target));
                            }
                        }
                    }

                    var contextProvider = (IXamlSchemaContextProvider)context.GetService(typeof(IXamlSchemaContextProvider));
                    var avaloniaContext = (AvaloniaXamlSchemaContext)contextProvider.SchemaContext;

                    if (avaloniaContext.IsDesignMode)
                    {
                        // We want to ignore missing events in the designer, so if event handler
                        // wasn't found create an empty delegate.
                        var lambdaExpression = Expression.Lambda(
                            eventType,
                            Expression.Empty(),
                            eventParameters.Select(x => Expression.Parameter(x.ParameterType)));
                        return(lambdaExpression.Compile());
                    }
                    else
                    {
                        throw new XamlObjectWriterException($"Referenced value method {text} in type {target.GetType()} indicated by event {eventType.FullName} was not found");
                    }
                }
            }
            return(base.ConvertFrom(context, culture, value));
        }
示例#34
0
 public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
 {
     if (value == null)
     {
         return(null);
     }
     if (value is string)
     {
         XamlTypeResolverProvider xamlTypeResolver = (XamlTypeResolverProvider)context.GetService(typeof(XamlTypeResolverProvider));
         if (xamlTypeResolver == null)
         {
             throw new XamlLoadException("XamlTypeResolverProvider not found in type descriptor context.");
         }
         XamlPropertyInfo prop = xamlTypeResolver.ResolveProperty((string)value);
         if (prop == null)
         {
             throw new XamlLoadException("Could not find property " + value + ".");
         }
         XamlDependencyPropertyInfo depProp = prop as XamlDependencyPropertyInfo;
         if (depProp != null)
         {
             return(depProp.DependencyProperty);
         }
         FieldInfo field = prop.TargetType.GetField(prop.Name + "Property", BindingFlags.Public | BindingFlags.Static);
         if (field != null && field.FieldType == typeof(DependencyProperty))
         {
             return((DependencyProperty)field.GetValue(null));
         }
         throw new XamlLoadException("Property " + value + " is not a dependency property.");
     }
     else
     {
         return(base.ConvertFrom(context, culture, value));
     }
 }
 private static TService GetService <TService>(ITypeDescriptorContext context) where TService : class
 {
     return(context.GetService(typeof(TService)) as TService);
 }
示例#36
0
        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            var text = value as string;

            if (text != null)
            {
                var rootObjectProvider      = context.GetService(typeof(IRootObjectProvider)) as IRootObjectProvider;
                var destinationTypeProvider = context.GetService(typeof(IDestinationTypeProvider)) as IDestinationTypeProvider;
                if (rootObjectProvider != null && destinationTypeProvider != null)
                {
                    var target          = rootObjectProvider.RootObject;
                    var eventType       = destinationTypeProvider.GetDestinationType();
                    var eventParameters = eventType.GetRuntimeMethods().First(r => r.Name == "Invoke").GetParameters();
                    // go in reverse to match System.Xaml behaviour
                    var methods = target.GetType().GetRuntimeMethods().Reverse();

                    // find based on exact match parameter types first
                    foreach (var method in methods)
                    {
                        if (method.Name != text)
                        {
                            continue;
                        }
                        var parameters = method.GetParameters();
                        if (eventParameters.Length != parameters.Length)
                        {
                            continue;
                        }
                        if (parameters.Length == 0)
                        {
                            return(method.CreateDelegate(eventType, target));
                        }

                        for (int i = 0; i < parameters.Length; i++)
                        {
                            var param      = parameters[i];
                            var eventParam = eventParameters[i];
                            if (param.ParameterType != eventParam.ParameterType)
                            {
                                break;
                            }
                            if (i == parameters.Length - 1)
                            {
                                return(method.CreateDelegate(eventType, target));
                            }
                        }
                    }

                    // EnhancedXaml: Find method with compatible base class parameters
                    foreach (var method in methods)
                    {
                        if (method.Name != text)
                        {
                            continue;
                        }
                        var parameters = method.GetParameters();
                        if (parameters.Length == 0 || eventParameters.Length != parameters.Length)
                        {
                            continue;
                        }

                        for (int i = 0; i < parameters.Length; i++)
                        {
                            var param      = parameters[i];
                            var eventParam = eventParameters[i];
                            if (!param.ParameterType.GetTypeInfo().IsAssignableFrom(eventParam.ParameterType.GetTypeInfo()))
                            {
                                break;
                            }
                            if (i == parameters.Length - 1)
                            {
                                return(method.CreateDelegate(eventType, target));
                            }
                        }
                    }

                    throw new XamlObjectWriterException($"Referenced value method {text} in type {target.GetType()} indicated by event {eventType.FullName} was not found");
                }
            }
            return(base.ConvertFrom(context, culture, value));
        }
 internal static IList<MemberInfo> GetBindableMembers(object obj, ITypeDescriptorContext context)
 {
     List<MemberInfo> list = new List<MemberInfo>();
     IDesignerHost service = context.GetService(typeof(IDesignerHost)) as IDesignerHost;
     Activity activity = (service != null) ? (service.RootComponent as Activity) : null;
     Type type = (obj == activity) ? Helpers.GetDataSourceClass(activity, context) : obj.GetType();
     Type toType = PropertyDescriptorUtils.GetBaseType(context.PropertyDescriptor, context.Instance, context);
     if ((type != null) && (toType != null))
     {
         DependencyProperty property = DependencyProperty.FromName(context.PropertyDescriptor.Name, context.PropertyDescriptor.ComponentType);
         bool flag = (property != null) && property.IsEvent;
         BindingFlags bindingAttr = BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance;
         if (obj == activity)
         {
             bindingAttr |= BindingFlags.NonPublic;
         }
         foreach (MemberInfo info in type.GetMembers(bindingAttr))
         {
             object[] customAttributes = info.GetCustomAttributes(typeof(DebuggerNonUserCodeAttribute), false);
             if (((customAttributes == null) || (customAttributes.Length <= 0)) || !(customAttributes[0] is DebuggerNonUserCodeAttribute))
             {
                 object[] objArray2 = info.GetCustomAttributes(typeof(BrowsableAttribute), false);
                 if (objArray2.Length > 0)
                 {
                     bool browsable = false;
                     BrowsableAttribute attribute = objArray2[0] as BrowsableAttribute;
                     if (attribute != null)
                     {
                         browsable = attribute.Browsable;
                     }
                     else
                     {
                         try
                         {
                             AttributeInfoAttribute attribute2 = objArray2[0] as AttributeInfoAttribute;
                             if ((attribute2 != null) && (attribute2.AttributeInfo.ArgumentValues.Count > 0))
                             {
                                 browsable = (bool) attribute2.AttributeInfo.GetArgumentValueAs(context, 0, typeof(bool));
                             }
                         }
                         catch
                         {
                         }
                     }
                     if (!browsable)
                     {
                         continue;
                     }
                 }
                 if ((info.DeclaringType != typeof(object)) || (!string.Equals(info.Name, "Equals", StringComparison.Ordinal) && !string.Equals(info.Name, "ReferenceEquals", StringComparison.Ordinal)))
                 {
                     bool flag3 = false;
                     bool flag4 = false;
                     bool isAssembly = false;
                     if (flag && (info is EventInfo))
                     {
                         EventInfo info2 = info as EventInfo;
                         MethodInfo addMethod = info2.GetAddMethod();
                         MethodInfo removeMethod = info2.GetRemoveMethod();
                         flag4 = ((((addMethod != null) && addMethod.IsFamily) || ((removeMethod != null) && removeMethod.IsFamily)) || ((addMethod != null) && addMethod.IsPublic)) || ((removeMethod != null) && removeMethod.IsPublic);
                         isAssembly = ((addMethod != null) && addMethod.IsAssembly) || ((removeMethod != null) && removeMethod.IsAssembly);
                         flag3 = TypeProvider.IsAssignable(toType, info2.EventHandlerType);
                     }
                     else if (info is FieldInfo)
                     {
                         FieldInfo info5 = info as FieldInfo;
                         flag4 = info5.IsFamily || info5.IsPublic;
                         isAssembly = info5.IsAssembly;
                         flag3 = TypeProvider.IsAssignable(toType, info5.FieldType);
                     }
                     else if (info is PropertyInfo)
                     {
                         PropertyInfo info6 = info as PropertyInfo;
                         MethodInfo getMethod = info6.GetGetMethod();
                         MethodInfo setMethod = info6.GetSetMethod();
                         flag4 = ((((getMethod != null) && getMethod.IsFamily) || ((setMethod != null) && setMethod.IsFamily)) || ((getMethod != null) && getMethod.IsPublic)) || ((setMethod != null) && setMethod.IsPublic);
                         isAssembly = ((getMethod != null) && getMethod.IsAssembly) || ((setMethod != null) && setMethod.IsAssembly);
                         flag3 = (getMethod != null) && TypeProvider.IsAssignable(toType, info6.PropertyType);
                     }
                     if (((info.DeclaringType != type) && !flag4) && ((info.DeclaringType.Assembly != null) || !isAssembly))
                     {
                         flag3 = false;
                     }
                     if (flag3)
                     {
                         list.Add(info);
                     }
                 }
             }
         }
     }
     return list.AsReadOnly();
 }
 public object GetService(Type serviceType)
 {
     return(originalTypeDescriptor.GetService(serviceType));
 }
        public static VisualBasicSettings CollectXmlNamespacesAndAssemblies(ITypeDescriptorContext context)
        {
            IList <Assembly>           referenceAssemblies = null;
            IXamlSchemaContextProvider service             = context.GetService(typeof(IXamlSchemaContextProvider)) as IXamlSchemaContextProvider;

            if ((service != null) && (service.SchemaContext != null))
            {
                referenceAssemblies = service.SchemaContext.ReferenceAssemblies;
                if ((referenceAssemblies != null) && (referenceAssemblies.Count == 0))
                {
                    referenceAssemblies = null;
                }
            }
            VisualBasicSettings    settings = null;
            IXamlNamespaceResolver resolver = (IXamlNamespaceResolver)context.GetService(typeof(IXamlNamespaceResolver));

            if (resolver == null)
            {
                return(null);
            }
            lock (AssemblyCache.XmlnsMappings)
            {
                foreach (System.Xaml.NamespaceDeclaration declaration in resolver.GetNamespacePrefixes())
                {
                    XmlnsMapping mapping;
                    XNamespace   key = XNamespace.Get(declaration.Namespace);
                    if (!AssemblyCache.XmlnsMappings.TryGetValue(key, out mapping))
                    {
                        Match match = assemblyQualifiedNamespaceRegex.Match(declaration.Namespace);
                        if (match.Success)
                        {
                            mapping.ImportReferences = new System.Collections.Generic.HashSet <VisualBasicImportReference>();
                            VisualBasicImportReference item = new VisualBasicImportReference {
                                Assembly = match.Groups["assembly"].Value,
                                Import   = match.Groups["namespace"].Value,
                                Xmlns    = key
                            };
                            mapping.ImportReferences.Add(item);
                        }
                        else
                        {
                            mapping.ImportReferences = new System.Collections.Generic.HashSet <VisualBasicImportReference>();
                        }
                        AssemblyCache.XmlnsMappings[key] = mapping;
                    }
                    if (!mapping.IsEmpty)
                    {
                        if (settings == null)
                        {
                            settings = new VisualBasicSettings();
                        }
                        foreach (VisualBasicImportReference reference2 in mapping.ImportReferences)
                        {
                            if (referenceAssemblies != null)
                            {
                                VisualBasicImportReference reference3;
                                AssemblyName assemblyName = reference2.AssemblyName;
                                if (reference2.EarlyBoundAssembly != null)
                                {
                                    if (referenceAssemblies.Contains(reference2.EarlyBoundAssembly))
                                    {
                                        reference3 = reference2.Clone();
                                        reference3.EarlyBoundAssembly = reference2.EarlyBoundAssembly;
                                        settings.ImportReferences.Add(reference3);
                                    }
                                }
                                else
                                {
                                    for (int i = 0; i < referenceAssemblies.Count; i++)
                                    {
                                        if (AssemblySatisfiesReference(VisualBasicHelper.GetFastAssemblyName(referenceAssemblies[i]), assemblyName))
                                        {
                                            reference3 = reference2.Clone();
                                            reference3.EarlyBoundAssembly = referenceAssemblies[i];
                                            settings.ImportReferences.Add(reference3);
                                            break;
                                        }
                                    }
                                }
                            }
                            else
                            {
                                VisualBasicImportReference reference4 = reference2.Clone();
                                if (reference2.EarlyBoundAssembly != null)
                                {
                                    reference4.EarlyBoundAssembly = reference2.EarlyBoundAssembly;
                                }
                                settings.ImportReferences.Add(reference4);
                            }
                        }
                    }
                }
            }
            return(settings);
        }
示例#40
0
 private static XamlSchemaContext GetSchemaContext(ITypeDescriptorContext context)
 {
     return(context.GetService(typeof(IXamlSchemaContextProvider)) is IXamlSchemaContextProvider provider ? provider.SchemaContext : null);
 }
示例#41
0
        ConvertTo(
            ITypeDescriptorContext context,
            System.Globalization.CultureInfo culture,
            object value,
            Type destinationType
            )
        {
            Toolbox.EmitEvent(EventTrace.Event.WClientDRXConvertImageBegin);

            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (!IsSupportedType(destinationType))
            {
                throw new NotSupportedException(SR.Get(SRID.Converter_ConvertToNotSupported));
            }

            //
            // Check that we have a valid BitmapSource instance.
            //
            BitmapSource bitmapSource = (BitmapSource)value;

            if (bitmapSource == null)
            {
                throw new ArgumentException(SR.Get(SRID.MustBeOfType, "value", "BitmapSource"));
            }

            //
            // Get the current serialization manager.
            //
            PackageSerializationManager manager = (PackageSerializationManager)context.GetService(typeof(XpsSerializationManager));

            //Get the image Uri if it has already been serialized
            Uri imageUri = GetBitmapSourceFromImageTable(manager, bitmapSource);

            //
            // Get the current page image cache
            //
            Dictionary <int, Uri> currentPageImageTable = manager.ResourcePolicy.CurrentPageImageTable;

            if (imageUri != null)
            {
                int uriHashCode = imageUri.GetHashCode();
                if (!currentPageImageTable.ContainsKey(uriHashCode))
                {
                    //
                    // Also, add a relationship for the current page to this image
                    // resource.  This is needed to conform with Xps specification.
                    //
                    manager.AddRelationshipToCurrentPage(imageUri, XpsS0Markup.ResourceRelationshipName);
                    currentPageImageTable.Add(uriHashCode, imageUri);
                }
            }
            else
            {
                //
                // This image as never serialized before so we will do it now.
                // Retrieve the image serialization service from the resource policy
                //
                IServiceProvider resourceServiceProvider = manager.ResourcePolicy;

                XpsImageSerializationService imageService = (XpsImageSerializationService)resourceServiceProvider.GetService(typeof(XpsImageSerializationService));
                if (imageService == null)
                {
                    throw new XpsSerializationException(SR.Get(SRID.ReachSerialization_NoImageService));
                }

                //
                // Obtain a valid encoder for the image.
                //
                BitmapEncoder encoder       = imageService.GetEncoder(bitmapSource);
                string        imageMimeType = GetImageMimeType(encoder);

                bool isSupportedMimeType = imageService.IsSupportedMimeType(bitmapSource);

                //
                // Acquire a writable stream from the serialization manager and encode
                // and serialize the image into the stream.
                //
                XpsResourceStream resourceStream = manager.AcquireResourceStream(typeof(BitmapSource), imageMimeType);
                bool bCopiedStream = false;

                BitmapFrame bitmapFrame = bitmapSource as BitmapFrame;

                if (isSupportedMimeType &&
                    bitmapFrame != null &&
                    bitmapFrame.Decoder != null
                    )
                {
                    BitmapDecoder decoder = bitmapFrame.Decoder;
                    try
                    {
                        Uri    sourceUri = new Uri(decoder.ToString());
                        Stream srcStream = MS.Internal.WpfWebRequestHelper.CreateRequestAndGetResponseStream(sourceUri);
                        CopyImageStream(srcStream, resourceStream.Stream);
                        srcStream.Close();
                        bCopiedStream = true;
                    }
                    catch (UriFormatException)
                    {
                        //the uri was not valid we will re-encode the image below
                    }
                    catch (WebException)
                    {
                        //Web Request failed we will re-encode the image below
                    }
                }

                if (!bCopiedStream)
                {
                    Stream stream = new MemoryStream();
                    ReEncodeImage(bitmapSource, encoder, stream);
                    stream.Position = 0;
                    CopyImageStream(stream, resourceStream.Stream);
                }

                //
                // Make sure to commit the resource stream by releasing it.
                //
                imageUri = resourceStream.Uri;
                manager.ReleaseResourceStream(typeof(BitmapSource));

                AddBitmapSourceToImageTables(manager, imageUri);
            }

            Toolbox.EmitEvent(EventTrace.Event.WClientDRXConvertImageEnd);

            return(imageUri);
        }
        private static XamlSchemaContext GetSchemaContext(ITypeDescriptorContext context)
        {
            IXamlSchemaContextProvider provider = context.GetService(typeof(IXamlSchemaContextProvider)) as IXamlSchemaContextProvider;

            return(provider != null ? provider.SchemaContext : null);
        }
示例#43
0
 /// <summary>
 ///  Gets the service object of the specified type.
 /// </summary>
 /// <typeparam name="T">The type of the service object to get.</typeparam>
 /// <param name="context">The <see cref="ITypeDescriptorContext"/> to retrieve the service object from.</param>
 /// <param name="service">If found, contains the service object when this method returns; otherwise, <see langword="null"/>.</param>
 /// <returns>A service object of type <typeparamref name="T"/> or <see langword="null"/> if there is no such service.</returns>
 public static bool TryGetService <T>(
     this ITypeDescriptorContext?context,
     [NotNullWhen(true)] out T?service)
     where T : class
 => (service = context?.GetService(typeof(T)) as T) is not null;
        /// <summary>
        /// ConvertTo - Attempt to convert a PropertyPath to the given type
        /// </summary>
        /// <returns>
        /// The object which was constructed.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// An ArgumentNullException is thrown if the example object is null.
        /// </exception>
        /// <exception cref="ArgumentException">
        /// An ArgumentException is thrown if the example object is not null and is not a Brush,
        /// or if the destinationType isn't one of the valid destination types.
        /// </exception>
        /// <param name="typeDescriptorContext"> The ITypeDescriptorContext for this call.
        ///  If this is null, then no namespace prefixes will be included.</param>
        /// <param name="cultureInfo"> The CultureInfo which is respected when converting. </param>
        /// <param name="value"> The PropertyPath to convert. </param>
        /// <param name="destinationType">The type to which to convert the PropertyPath instance. </param>
        public override object ConvertTo(ITypeDescriptorContext typeDescriptorContext,
                                         CultureInfo cultureInfo,
                                         object value,
                                         Type destinationType)
        {
            if (null == value)
            {
                throw new ArgumentNullException("value");
            }

            if (null == destinationType)
            {
                throw new ArgumentNullException("destinationType");
            }

            if (destinationType != typeof(String))
            {
                throw new ArgumentException(SR.Get(SRID.CannotConvertType, typeof(PropertyPath), destinationType.FullName));
            }

            PropertyPath path = value as PropertyPath;

            if (path == null)
            {
                throw new ArgumentException(SR.Get(SRID.UnexpectedParameterType, value.GetType(), typeof(PropertyPath)), "value");
            }

            if (path.PathParameters.Count == 0)
            {
                // if the path didn't use paramaters, just write it out as it is
                return(path.Path);
            }
            else
            {
                // if the path used parameters, convert them to (NamespacePrefix:OwnerType.DependencyPropertyName) syntax
                string originalPath                      = path.Path;
                Collection <object> parameters           = path.PathParameters;
                XamlDesignerSerializationManager manager = typeDescriptorContext == null ?
                                                           null :
                                                           typeDescriptorContext.GetService(typeof(XamlDesignerSerializationManager)) as XamlDesignerSerializationManager;
                ValueSerializer         typeSerializer    = null;
                IValueSerializerContext serializerContext = null;
                if (manager == null)
                {
                    serializerContext = typeDescriptorContext as IValueSerializerContext;
                    if (serializerContext != null)
                    {
                        typeSerializer = ValueSerializer.GetSerializerFor(typeof(Type), serializerContext);
                    }
                }

                StringBuilder builder = new StringBuilder();

                int start = 0;
                for (int i = 0; i < originalPath.Length; ++i)
                {
                    // look for (n)
                    if (originalPath[i] == '(')
                    {
                        int j;
                        for (j = i + 1; j < originalPath.Length; ++j)
                        {
                            if (originalPath[j] == ')')
                            {
                                break;
                            }
                        }

                        int index;
                        if (Int32.TryParse(originalPath.AsSpan(i + 1, j - i - 1),
                                           NumberStyles.Integer,
                                           TypeConverterHelper.InvariantEnglishUS.NumberFormat,
                                           out index))
                        {
                            // found (n). Write out the path so far, including the opening (
                            builder.Append(originalPath.AsSpan(start, i - start + 1));

                            object pathPart = parameters[index];

                            // get the owner type and name of the accessor
                            DependencyProperty    dp;
                            PropertyInfo          pi;
                            PropertyDescriptor    pd;
                            DynamicObjectAccessor doa;
                            PropertyPath.DowncastAccessor(pathPart, out dp, out pi, out pd, out doa);

                            Type   type;       // the accessor's ownerType, or type of indexer parameter
                            string name;       // the accessor's propertyName, or string value of indexer parameter

                            if (dp != null)
                            {
                                type = dp.OwnerType;
                                name = dp.Name;
                            }
                            else if (pi != null)
                            {
                                type = pi.DeclaringType;
                                name = pi.Name;
                            }
                            else if (pd != null)
                            {
                                type = pd.ComponentType;
                                name = pd.Name;
                            }
                            else if (doa != null)
                            {
                                type = doa.OwnerType;
                                name = doa.PropertyName;
                            }
                            else
                            {
                                // pathPart is an Indexer Parameter
                                type = pathPart.GetType();
                                name = null;
                            }

                            // write out the type of the accessor or index parameter
                            if (typeSerializer != null)
                            {
                                builder.Append(typeSerializer.ConvertToString(type, serializerContext));
                            }
                            else
                            {
                                // Need the prefix here
                                string prefix = null;
                                if (prefix != null && prefix != string.Empty)
                                {
                                    builder.Append(prefix);
                                    builder.Append(':');
                                }
                                builder.Append(type.Name);
                            }

                            if (name != null)
                            {
                                // write out the accessor name
                                builder.Append('.');
                                builder.Append(name);
                                // write out the closing )
                                builder.Append(')');
                            }
                            else
                            {
                                // write out the ) that closes the parameter's type
                                builder.Append(')');

                                name = pathPart as string;
                                if (name == null)
                                {
                                    // convert the parameter into string
                                    TypeConverter converter = TypeDescriptor.GetConverter(type);
                                    if (converter.CanConvertTo(typeof(string)) && converter.CanConvertFrom(typeof(string)))
                                    {
                                        try
                                        {
                                            name = converter.ConvertToString(pathPart);
                                        }
                                        catch (NotSupportedException)
                                        {
                                        }
                                    }
                                }

                                // write out the parameter's value string
                                builder.Append(name);
                            }

                            // resume after the (n)
                            i     = j;
                            start = j + 1;
                        }
                    }
                }

                if (start < originalPath.Length)
                {
                    builder.Append(originalPath.AsSpan(start));
                }

                return(builder.ToString());
            }
        }
示例#45
0
        public override bool EditComponent(ITypeDescriptorContext context, object obj, IWin32Window parent)
        {
            IntPtr handle = (parent == null ? IntPtr.Zero : parent.Handle);

            // try to get the page guid
            if (obj is NativeMethods.IPerPropertyBrowsing)
            {
                // check for a property page
                Guid guid = Guid.Empty;
                int  hr   = ((NativeMethods.IPerPropertyBrowsing)obj).MapPropertyToPage(NativeMethods.MEMBERID_NIL, out guid);
                if (hr == NativeMethods.S_OK)
                {
                    if (!guid.Equals(Guid.Empty))
                    {
                        object o = obj;
                        SafeNativeMethods.OleCreatePropertyFrame(new HandleRef(parent, handle), 0, 0, "PropertyPages", 1, ref o, 1, new Guid[] { guid }, Application.CurrentCulture.LCID, 0, IntPtr.Zero);
                        return(true);
                    }
                }
            }

            if (obj is NativeMethods.ISpecifyPropertyPages)
            {
                bool      failed = false;
                Exception failureException;

                try {
                    NativeMethods.tagCAUUID uuids = new NativeMethods.tagCAUUID();
                    try {
                        ((NativeMethods.ISpecifyPropertyPages)obj).GetPages(uuids);
                        if (uuids.cElems <= 0)
                        {
                            return(false);
                        }
                    }
                    catch {
                        return(false);
                    }
                    try {
                        object o = obj;
                        SafeNativeMethods.OleCreatePropertyFrame(new HandleRef(parent, handle), 0, 0, "PropertyPages", 1, ref o, uuids.cElems, new HandleRef(uuids, uuids.pElems), Application.CurrentCulture.LCID, 0, IntPtr.Zero);
                        return(true);
                    }
                    finally {
                        if (uuids.pElems != IntPtr.Zero)
                        {
                            Marshal.FreeCoTaskMem(uuids.pElems);
                        }
                    }
                }
                catch (Exception ex1) {
                    failed           = true;
                    failureException = ex1;
                }

                if (failed)
                {
                    string errString = SR.ErrorPropertyPageFailed;

                    IUIService uiSvc = (context != null) ? ((IUIService)context.GetService(typeof(IUIService))) : null;

                    if (uiSvc == null)
                    {
                        RTLAwareMessageBox.Show(null, errString, SR.PropertyGridTitle,
                                                MessageBoxButtons.OK, MessageBoxIcon.Error,
                                                MessageBoxDefaultButton.Button1, 0);
                    }
                    else if (failureException != null)
                    {
                        uiSvc.ShowError(failureException, errString);
                    }
                    else
                    {
                        uiSvc.ShowError(errString);
                    }
                }
            }
            return(false);
        }
示例#46
0
 /// <summary>
 /// Gets the service.
 /// </summary>
 /// <param name="serviceType"></param>
 /// <returns></returns>
 public object GetService(Type serviceType)
 {
     return(innerTypeDescriptor.GetService(serviceType));
 }
示例#47
0
        public override object ConvertFrom(
            ITypeDescriptorContext context,
            CultureInfo culture,
            object value)
        {
            var destinationTypeProvider =
                context.GetService(
                    typeof(IDestinationTypeProvider))
                .As <IDestinationTypeProvider>();

            if (destinationTypeProvider == null)
            {
                throw new NullReferenceException(
                          $"The destination type provider is null " +
                          $"and not available in this context.");
            }

            var destinationType = destinationTypeProvider
                                  .GetDestinationType();

            if (destinationType == typeof(string))
            {
                switch (value)
                {
                case string @string:
                    return(@string);

                case SolidColorBrush solidColorBrush:
                    return(solidColorBrush);

                case Brush brush:
                    return((SolidColorBrush)brush);

                case MaterialBrush materialBrush:
                    return(materialBrush.Brush);

                default:
                    throw new InvalidEnumArgumentException();
                }
            }
            if (destinationType == typeof(SolidColorBrush))
            {
                switch (value)
                {
                case string @string:
                    throw new NotImplementedException();

                case SolidColorBrush solidColorBrush:
                    return(solidColorBrush);

                case Brush brush:
                    return((SolidColorBrush)brush);

                case MaterialBrush materialBrush:
                    return(materialBrush.Brush);

                default:
                    throw new InvalidEnumArgumentException();
                }
            }
            if (destinationType == typeof(Brush))
            {
                switch (value)
                {
                case string @string:
                    throw new NotImplementedException();

                case SolidColorBrush solidColorBrush:
                    return(solidColorBrush);

                case Brush brush:
                    return(brush);

                case MaterialBrush materialBrush:
                    return(materialBrush.Brush);

                default:
                    throw new InvalidEnumArgumentException();
                }
            }
            if (destinationType == typeof(MaterialBrush))
            {
                switch (value)
                {
                case string @string:
                {
                    throw new NotImplementedException();
                    //  return GlobalResources.MaterialDesignPalette.Swatches[]i
                }

                case SolidColorBrush solidColorBrush:
                    throw new NotImplementedException();

                case Brush brush:
                    throw new NotImplementedException();

                case MaterialBrush materialBrush:
                    return(materialBrush);

                default:
                    throw new InvalidEnumArgumentException();
                }
            }
            return(base.ConvertFrom(context, culture, value));
        }
示例#48
0
        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            try
            {
                if (value == null)
                {
                    throw GetConvertFromException(value);
                }

                if (((value is string) && (!string.IsNullOrEmpty((string)value))) || (value is Uri))
                {
                    UriHolder uriHolder = TypeConverterHelper.GetUriFromUriContext(context, value);
                    return(BitmapFrame.CreateFromUriOrStream(
                               uriHolder.BaseUri,
                               uriHolder.OriginalUri,
                               null,
                               BitmapCreateOptions.None,
                               BitmapCacheOption.Default,
                               null
                               ));
                }
                else if (value is byte[])
                {
                    byte[] bytes = (byte[])value;

                    if (bytes != null)
                    {
                        Stream memStream = null;

                        //
                        // this might be a magical OLE thing, try that first.
                        //
                        memStream = GetBitmapStream(bytes);

                        if (memStream == null)
                        {
                            //
                            // guess not.  Try plain memory.
                            //
                            memStream = new MemoryStream(bytes);
                        }

                        return(BitmapFrame.Create(
                                   memStream,
                                   BitmapCreateOptions.None,
                                   BitmapCacheOption.Default
                                   ));
                    }
                }
                else if (value is Stream)
                {
                    Stream stream = (Stream)value;

                    return(BitmapFrame.Create(
                               stream,
                               BitmapCreateOptions.None,
                               BitmapCacheOption.Default
                               ));
                }

                return(base.ConvertFrom(context, culture, value));
            }
            catch (Exception e)
            {
                if (!CriticalExceptions.IsCriticalException(e))
                {
                    if (context == null && CoreAppContextSwitches.OverrideExceptionWithNullReferenceException)
                    {
                        throw new NullReferenceException();
                    }

                    IProvideValueTarget ipvt = context?.GetService(typeof(IProvideValueTarget)) as IProvideValueTarget;
                    if (ipvt != null)
                    {
                        IProvidePropertyFallback ippf = ipvt.TargetObject as IProvidePropertyFallback;
                        DependencyProperty       dp   = ipvt.TargetProperty as DependencyProperty;
                        // We only want to call IPPF.SetValue if the target can handle it.
                        // We need to check for non DP scenarios (This is currently an internal interface used
                        //             only by Image so it's okay for now)

                        if (ippf != null && dp != null && ippf.CanProvidePropertyFallback(dp.Name))
                        {
                            return(ippf.ProvidePropertyFallback(dp.Name, e));
                        }
                    }
                }

                // We want to rethrow the exception in the case we can't handle it.
                throw;
            }
        }
        // Token: 0x0600224E RID: 8782 RVA: 0x000AA9F8 File Offset: 0x000A8BF8
        internal static object ResolveValue(ITypeDescriptorContext serviceProvider, DependencyProperty property, CultureInfo culture, object source)
        {
            if (serviceProvider == null)
            {
                throw new ArgumentNullException("serviceProvider");
            }
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }
            if (!(source is byte[]) && !(source is string) && !(source is Stream))
            {
                return(source);
            }
            IXamlSchemaContextProvider xamlSchemaContextProvider = serviceProvider.GetService(typeof(IXamlSchemaContextProvider)) as IXamlSchemaContextProvider;

            if (xamlSchemaContextProvider == null)
            {
                throw new NotSupportedException(SR.Get("ParserCannotConvertPropertyValue", new object[]
                {
                    "Value",
                    typeof(object).FullName
                }));
            }
            XamlSchemaContext schemaContext = xamlSchemaContextProvider.SchemaContext;

            if (property == null)
            {
                return(source);
            }
            XamlMember xamlMember = schemaContext.GetXamlType(property.OwnerType).GetMember(property.Name);

            if (xamlMember == null)
            {
                xamlMember = schemaContext.GetXamlType(property.OwnerType).GetAttachableMember(property.Name);
            }
            XamlValueConverter <TypeConverter> typeConverter;

            if (xamlMember != null)
            {
                if (xamlMember.Type.UnderlyingType.IsEnum && schemaContext is Baml2006SchemaContext)
                {
                    typeConverter = XamlReader.BamlSharedSchemaContext.GetTypeConverter(xamlMember.Type.UnderlyingType);
                }
                else
                {
                    typeConverter = xamlMember.TypeConverter;
                    if (typeConverter == null)
                    {
                        typeConverter = xamlMember.Type.TypeConverter;
                    }
                }
            }
            else
            {
                typeConverter = schemaContext.GetXamlType(property.PropertyType).TypeConverter;
            }
            if (typeConverter.ConverterType == null)
            {
                return(source);
            }
            TypeConverter typeConverter2;

            if (xamlMember != null && xamlMember.Type.UnderlyingType == typeof(bool))
            {
                if (source is string)
                {
                    typeConverter2 = new BooleanConverter();
                }
                else
                {
                    if (!(source is byte[]))
                    {
                        throw new NotSupportedException(SR.Get("ParserCannotConvertPropertyValue", new object[]
                        {
                            "Value",
                            typeof(object).FullName
                        }));
                    }
                    byte[] array = source as byte[];
                    if (array != null && array.Length == 1)
                    {
                        return(array[0] > 0);
                    }
                    throw new NotSupportedException(SR.Get("ParserCannotConvertPropertyValue", new object[]
                    {
                        "Value",
                        typeof(object).FullName
                    }));
                }
            }
            else
            {
                typeConverter2 = typeConverter.ConverterInstance;
            }
            return(typeConverter2.ConvertFrom(serviceProvider, culture, source));
        }
示例#50
0
 protected object GetService(Type serviceType)
 {
     return(context.GetService(serviceType));
 }
 internal static bool CreateField(ITypeDescriptorContext context, ActivityBind activityBind, bool throwOnError)
 {
     if (!string.IsNullOrEmpty(activityBind.Path))
     {
         Type toType = PropertyDescriptorUtils.GetBaseType(context.PropertyDescriptor, context.Instance, context);
         Activity component = PropertyDescriptorUtils.GetComponent(context) as Activity;
         if ((component != null) && (toType != null))
         {
             component = Helpers.ParseActivityForBind(component, activityBind.Name);
             if (component == Helpers.GetRootActivity(component))
             {
                 bool ignoreCase = CompilerHelpers.GetSupportedLanguage(context) == SupportedLanguages.VB;
                 Type dataSourceClass = Helpers.GetDataSourceClass(component, context);
                 if (dataSourceClass != null)
                 {
                     string path = activityBind.Path;
                     int length = path.IndexOfAny(new char[] { '.', '/', '[' });
                     if (length != -1)
                     {
                         path = path.Substring(0, length);
                     }
                     MemberInfo info = FindMatchingMember(path, dataSourceClass, ignoreCase);
                     if (info != null)
                     {
                         Type fromType = null;
                         bool isPrivate = false;
                         if (info is FieldInfo)
                         {
                             isPrivate = ((FieldInfo) info).IsPrivate;
                             fromType = ((FieldInfo) info).FieldType;
                         }
                         else if (info is PropertyInfo)
                         {
                             MethodInfo getMethod = ((PropertyInfo) info).GetGetMethod();
                             MethodInfo setMethod = ((PropertyInfo) info).GetSetMethod();
                             isPrivate = ((getMethod != null) && getMethod.IsPrivate) || ((setMethod != null) && setMethod.IsPrivate);
                         }
                         else if (info is MethodInfo)
                         {
                             isPrivate = ((MethodInfo) info).IsPrivate;
                         }
                         if (length != -1)
                         {
                             PathWalker walker = new PathWalker();
                             PathMemberInfoEventArgs finalEventArgs = null;
                             walker.MemberFound = (EventHandler<PathMemberInfoEventArgs>) Delegate.Combine(walker.MemberFound, delegate (object sender, PathMemberInfoEventArgs eventArgs) {
                                 finalEventArgs = eventArgs;
                             });
                             if (!walker.TryWalkPropertyPath(dataSourceClass, activityBind.Path))
                             {
                                 if (throwOnError)
                                 {
                                     throw new InvalidOperationException(SR.GetString("Error_MemberWithSameNameExists", new object[] { activityBind.Path, dataSourceClass.FullName }));
                                 }
                                 return false;
                             }
                             fromType = BindHelpers.GetMemberType(finalEventArgs.MemberInfo);
                         }
                         if (((info.DeclaringType == dataSourceClass) || !isPrivate) && ((info is FieldInfo) && TypeProvider.IsAssignable(toType, fromType)))
                         {
                             return true;
                         }
                         if (throwOnError)
                         {
                             throw new InvalidOperationException(SR.GetString("Error_MemberWithSameNameExists", new object[] { activityBind.Path, dataSourceClass.FullName }));
                         }
                         return false;
                     }
                     Activity activity2 = null;
                     if (string.Compare(component.Name, path, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) == 0)
                     {
                         activity2 = component;
                     }
                     else if ((component is CompositeActivity) && (component is CompositeActivity))
                     {
                         foreach (Activity activity3 in Helpers.GetAllNestedActivities(component as CompositeActivity))
                         {
                             if (string.Compare(activity3.Name, path, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) == 0)
                             {
                                 activity2 = activity3;
                             }
                         }
                     }
                     if (activity2 != null)
                     {
                         if (TypeProvider.IsAssignable(toType, activity2.GetType()))
                         {
                             return true;
                         }
                         if (throwOnError)
                         {
                             throw new InvalidOperationException(SR.GetString("Error_MemberWithSameNameExists", new object[] { activityBind.Path, dataSourceClass.FullName }));
                         }
                         return false;
                     }
                     IMemberCreationService service = context.GetService(typeof(IMemberCreationService)) as IMemberCreationService;
                     if (service != null)
                     {
                         IDesignerHost host = context.GetService(typeof(IDesignerHost)) as IDesignerHost;
                         if (host != null)
                         {
                             service.CreateField(host.RootComponentClassName, activityBind.Path, toType, null, MemberAttributes.Public, null, false);
                             return true;
                         }
                         if (throwOnError)
                         {
                             throw new InvalidOperationException(SR.GetString("General_MissingService", new object[] { typeof(IDesignerHost).FullName }));
                         }
                     }
                     else if (throwOnError)
                     {
                         throw new InvalidOperationException(SR.GetString("General_MissingService", new object[] { typeof(IMemberCreationService).FullName }));
                     }
                 }
             }
         }
         else
         {
             if ((component == null) && throwOnError)
             {
                 throw new InvalidOperationException(SR.GetString("Error_InvalidActivityIdentifier", new object[] { activityBind.Name }));
             }
             if ((toType == null) && throwOnError)
             {
                 throw new InvalidOperationException(SR.GetString("Error_PropertyTypeNotDefined", new object[] { context.PropertyDescriptor.Name, typeof(ActivityBind).Name, typeof(IDynamicPropertyTypeProvider).Name }));
             }
         }
     }
     return false;
 }
示例#52
0
        public static VisualBasicSettings CollectXmlNamespacesAndAssemblies(ITypeDescriptorContext context)
        {
            // access XamlSchemaContext.ReferenceAssemblies
            // for the Compiled Xaml scenario
            IList <Assembly>           xsCtxReferenceAssemblies  = null;
            IXamlSchemaContextProvider xamlSchemaContextProvider = context.GetService(typeof(IXamlSchemaContextProvider)) as IXamlSchemaContextProvider;

            if (xamlSchemaContextProvider != null && xamlSchemaContextProvider.SchemaContext != null)
            {
                xsCtxReferenceAssemblies = xamlSchemaContextProvider.SchemaContext.ReferenceAssemblies;
                if (xsCtxReferenceAssemblies != null && xsCtxReferenceAssemblies.Count == 0)
                {
                    xsCtxReferenceAssemblies = null;
                }
            }

            VisualBasicSettings    settings          = null;
            IXamlNamespaceResolver namespaceResolver = (IXamlNamespaceResolver)context.GetService(typeof(IXamlNamespaceResolver));

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

            lock (AssemblyCache.XmlnsMappingsLockObject)
            {
                // Fetch xmlnsMappings for the prefixes returned by the namespaceResolver service

                foreach (NamespaceDeclaration prefix in namespaceResolver.GetNamespacePrefixes())
                {
                    ReadOnlyXmlnsMapping mapping;
                    WrapCachedMapping(prefix, out mapping);
                    if (!mapping.IsEmpty)
                    {
                        if (settings == null)
                        {
                            settings = new VisualBasicSettings();
                        }

                        if (!mapping.IsEmpty)
                        {
                            foreach (ReadOnlyVisualBasicImportReference importReference in mapping.ImportReferences)
                            {
                                if (xsCtxReferenceAssemblies != null)
                                {
                                    // this is "compiled Xaml"
                                    VisualBasicImportReference newImportReference;

                                    if (importReference.EarlyBoundAssembly != null)
                                    {
                                        if (xsCtxReferenceAssemblies.Contains(importReference.EarlyBoundAssembly))
                                        {
                                            newImportReference = importReference.Clone();
                                            newImportReference.EarlyBoundAssembly = importReference.EarlyBoundAssembly;
                                            settings.ImportReferences.Add(newImportReference);
                                        }
                                        continue;
                                    }

                                    for (int i = 0; i < xsCtxReferenceAssemblies.Count; i++)
                                    {
                                        AssemblyName xsCtxAssemblyName = VisualBasicHelper.GetFastAssemblyName(xsCtxReferenceAssemblies[i]);
                                        if (importReference.AssemblySatisfiesReference(xsCtxAssemblyName))
                                        {
                                            // bind this assembly early to the importReference
                                            // so later AssemblyName resolution can be skipped
                                            newImportReference = importReference.Clone();
                                            newImportReference.EarlyBoundAssembly = xsCtxReferenceAssemblies[i];
                                            settings.ImportReferences.Add(newImportReference);
                                            break;
                                        }
                                    }
                                }
                                else
                                {
                                    // this is "loose Xaml"
                                    VisualBasicImportReference newImportReference = importReference.Clone();
                                    if (importReference.EarlyBoundAssembly != null)
                                    {
                                        // VBImportReference.Clone() method deliberately doesn't copy
                                        // its EarlyBoundAssembly to the cloned instance.
                                        // we need to explicitly copy the original's EarlyBoundAssembly
                                        newImportReference.EarlyBoundAssembly = importReference.EarlyBoundAssembly;
                                    }
                                    settings.ImportReferences.Add(newImportReference);
                                }
                            }
                        }
                    }
                }
            }
            return(settings);
        }
示例#53
0
        public unsafe override bool EditComponent(ITypeDescriptorContext context, object obj, IWin32Window parent)
        {
            IntPtr handle = (parent == null ? IntPtr.Zero : parent.Handle);

            // try to get the page guid
            if (obj is Oleaut32.IPerPropertyBrowsing)
            {
                // check for a property page
                Guid    guid = Guid.Empty;
                HRESULT hr   = ((Oleaut32.IPerPropertyBrowsing)obj).MapPropertyToPage(Ole32.DispatchID.MEMBERID_NIL, &guid);
                if (hr == HRESULT.S_OK & !guid.Equals(Guid.Empty))
                {
                    IntPtr pUnk = Marshal.GetIUnknownForObject(obj);
                    try
                    {
                        Oleaut32.OleCreatePropertyFrame(
                            new HandleRef(parent, handle),
                            0,
                            0,
                            "PropertyPages",
                            1,
                            &pUnk,
                            1,
                            &guid,
                            (uint)Application.CurrentCulture.LCID,
                            0,
                            IntPtr.Zero);
                        return(true);
                    }
                    finally
                    {
                        Marshal.Release(pUnk);
                    }
                }
            }

            if (obj is ISpecifyPropertyPages ispp)
            {
                try
                {
                    var     uuids = new CAUUID();
                    HRESULT hr    = ispp.GetPages(&uuids);
                    if (!hr.Succeeded() || uuids.cElems == 0)
                    {
                        return(false);
                    }

                    IntPtr pUnk = Marshal.GetIUnknownForObject(obj);
                    try
                    {
                        Oleaut32.OleCreatePropertyFrame(
                            new HandleRef(parent, handle),
                            0,
                            0,
                            "PropertyPages",
                            1,
                            &pUnk,
                            uuids.cElems,
                            uuids.pElems,
                            (uint)Application.CurrentCulture.LCID,
                            0,
                            IntPtr.Zero);
                        return(true);
                    }
                    finally
                    {
                        Marshal.Release(pUnk);
                        if (uuids.pElems != null)
                        {
                            Marshal.FreeCoTaskMem((IntPtr)uuids.pElems);
                        }
                    }
                }
                catch (Exception ex)
                {
                    string errString = SR.ErrorPropertyPageFailed;

                    IUIService uiSvc = (context != null) ? ((IUIService)context.GetService(typeof(IUIService))) : null;

                    if (uiSvc == null)
                    {
                        RTLAwareMessageBox.Show(null, errString, SR.PropertyGridTitle,
                                                MessageBoxButtons.OK, MessageBoxIcon.Error,
                                                MessageBoxDefaultButton.Button1, 0);
                    }
                    else if (ex != null)
                    {
                        uiSvc.ShowError(ex, errString);
                    }
                    else
                    {
                        uiSvc.ShowError(errString);
                    }
                }
            }

            return(false);
        }
示例#54
0
        private ListBox CreateListBox(ITypeDescriptorContext context, object value)
        {
            ListBox listBox = new ListBox();

            listBox.SelectedValueChanged += new EventHandler(listBox_SelectedValueChanged);
            listBox.Dock        = DockStyle.Fill;
            listBox.BorderStyle = BorderStyle.None;
            listBox.ItemHeight  = 13;

            listBox.Items.Add("(none)");

            // Load standard shapes
            if (context.Container != null)
            {
                ITypeDiscoveryService discoveryService = (ITypeDiscoveryService)context.GetService(typeof(ITypeDiscoveryService));
                foreach (Type type in discoveryService.GetTypes(typeof(ElementShape), false))
                {
                    if (type != typeof(CustomShape) && !type.IsAbstract && type.IsPublic)
                    {
                        listBox.Items.Add(type.Name);
                        shapes.Add(type);

                        if (value != null && value.GetType() == type)
                        {
                            listBox.SelectedIndex = listBox.Items.Count - 1;
                        }
                    }
                }
            }
            else
            {
                foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
                {
                    try
                    {
                        if (!IsTelerikAssembly(assembly))
                        {
                            continue;
                        }
                        foreach (Type type in assembly.GetTypes())
                        {
                            if (type.IsClass && type.IsPublic && !type.IsAbstract &&
                                typeof(ElementShape).IsAssignableFrom(type) &&
                                type != typeof(CustomShape))
                            {
                                listBox.Items.Add(type.Name);
                                shapes.Add(type);

                                if (value != null && value.GetType() == type)
                                {
                                    listBox.SelectedIndex = listBox.Items.Count - 1;
                                }
                            }
                        }
                    }
                    catch (ReflectionTypeLoadException e)
                    {
                        string message = e.Message + "\n\nLoader Exceptions:\n";
                        for (int i = 0; i < Math.Min(MaxLoaderExceptionsInMessageBox, e.LoaderExceptions.Length); i++)
                        {
                            message += e.LoaderExceptions[i].Message + "\n";
                        }
                        if (e.LoaderExceptions.Length > MaxLoaderExceptionsInMessageBox)
                        {
                            message += "More...";
                        }
                        MessageBox.Show(message, assembly.FullName);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, assembly.FullName);
                    }
                }
            }

            // Load custom shape components
            if (context.Container != null)
            {
                foreach (IComponent component in context.Container.Components)
                {
                    if (component is CustomShape)
                    {
                        listBox.Items.Add(component.Site.Name);
                        shapes.Add(component);

                        if (component == value)
                        {
                            listBox.SelectedIndex = listBox.Items.Count - 1;
                        }
                    }
                }

                listBox.Items.Add("Create new custom shape ...");
                if (value != null && value is CustomShape)
                {
                    listBox.Items.Add("Edit points ...");
                }
            }
            else
            {
                if (value != null && value is CustomShape)
                {
                    listBox.Items.Add("Edit points ...");
                }
                else
                {
                    listBox.Items.Add("Create new custom shape ...");
                }
            }


            return(listBox);
        }
示例#55
0
 object IServiceProvider.GetService(Type serviceType)
 {
     return(context.GetService(serviceType));
 }
示例#56
0
        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value,
                                         Type destinationType)
        {
            if (context != null)
            {
                var o = context.GetService(typeof(IProvideValueTarget));
                if (o == null)
                {
                    Logger.Debug("no servie");
                }

                var o2 = context.GetService(typeof(IDestinationTypeProvider));
                if (o2 == null)
                {
                    Logger.Debug("no servie");
                }

                var instance    = context.Instance;
                var instanceStr = $"[{instance.GetType()}]";
                if (instance is FrameworkElement fElem)
                {
                    var elemStr = $"Name={fElem.Name}";
                    instanceStr += elemStr;
                }

                if (context.PropertyDescriptor != null)
                {
                    var propType          = context.PropertyDescriptor.PropertyType;
                    var propName          = context.PropertyDescriptor.Name;
                    var propComponentType = context.PropertyDescriptor.ComponentType;
                    var propString        = $"[{propType}] [{propComponentType}].[{propName}]";
                    Logger.Debug($"prop: {propString}");
                }

                Logger.Debug($"instance: {instanceStr}");

                if (o is IProvideValueTarget service)
                {
                    Logger.Debug($"{service.TargetObject}.{service.TargetProperty}");
                }
            }

            Logger.Debug("ConvertTo");
            if (typeof(MarkupExtension).IsAssignableFrom(destinationType))
            {
                if (value == null)
                {
                    return(new NullExtension());
                }

                WpfLogEventInfo i    = (WpfLogEventInfo)value;
                var             json = JsonConvert.SerializeObject(i);

                return(new TestMarkupExtension(
                           System.Convert.ToBase64String(Encoding.UTF8.GetBytes(json))));
            }
            else if (destinationType == typeof(String))
            {
                WpfLogEventInfo i    = (WpfLogEventInfo)value;
                var             json = JsonConvert.SerializeObject(i);

                return(System.Convert.ToBase64String(Encoding.UTF8.GetBytes(json)));
            }

            Logger.Debug("beep");
            return(base.ConvertTo(context, culture, value, destinationType));
        }
示例#57
0
        /// <include file='doc\AdvancedPropertyEditor.uex' path='docs/doc[@for="AdvancedPropertyEditor.EditValue"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
        {
            ComponentSettings compSettings = ((AdvancedPropertyDescriptor)value).ComponentSettings;
            IComponent        component    = compSettings.Component;

            // make sure it's OK to change
            IComponentChangeService changeService = null;

            if (component.Site != null)
            {
                changeService = (IComponentChangeService)component.Site.GetService(typeof(IComponentChangeService));
            }
            if (changeService != null)
            {
                try {
                    changeService.OnComponentChanging(component, (PropertyDescriptor)value);
                }
                catch (CheckoutException e) {
                    if (e == CheckoutException.Canceled)
                    {
                        return(value);
                    }
                    throw e;
                }
            }

            IWindowsFormsEditorService editorSvc = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService));

            Debug.Assert(editorSvc != null, "Couldn't get IWindowsFormsEditorService");
            if (editorSvc != null)
            {
                try {
                    using (AdvancedPropertyDialog dlg = new AdvancedPropertyDialog(component)) {
                        DialogResult result = editorSvc.ShowDialog(dlg);
                        if (result == DialogResult.OK)
                        {
                            bool changeMade = false;
                            PropertyBindingCollection newBindings = dlg.Bindings;
                            ManagedPropertiesService  svc         = (ManagedPropertiesService)context.GetService(typeof(ManagedPropertiesService));
                            Debug.Assert(svc != null, "Couldn't get ManagedPropertiesService");
                            if (svc != null)
                            {
                                for (int i = 0; i < newBindings.Count; i++)
                                {
                                    svc.EnsureKey(newBindings[i]);
                                    PropertyBinding oldBinding = svc.Bindings[component, newBindings[i].Property];
                                    if (oldBinding == null)
                                    {
                                        if (newBindings[i].Bound)
                                        {
                                            changeMade = true;
                                        }
                                    }
                                    else if ((oldBinding.Bound != newBindings[i].Bound) || (oldBinding.Key != newBindings[i].Key))
                                    {
                                        changeMade = true;
                                    }
                                    svc.Bindings[component, newBindings[i].Property] = newBindings[i];
                                }
                                svc.MakeDirty();

                                if (changeMade)
                                {
                                    TypeDescriptor.Refresh(compSettings.Component);
                                    if (changeService != null)
                                    {
                                        changeService.OnComponentChanged(compSettings.Component, null, null, null);
                                    }
                                    try {
                                        svc.WriteConfigFile();
                                    }
                                    catch {
                                    }
                                }

                                // this fools the properties window into thinking we changed the value, so it refreshes
                                // the owner object.
                                object retval = new AdvancedPropertyDescriptor(compSettings);
                                return(retval);
                            }
                        }
                    }
                }
                catch (Exception e) {
                    System.Windows.Forms.MessageBox.Show(e.Message, SR.GetString(SR.ConfigConfiguredProperties));
                }
            }

            return(value);
        }
示例#58
0
        public static ArrayList GetCommandDescriptors(ITypeDescriptorContext context)
        {
            if (_buffer != null)
            {
                return(_buffer);
            }

            ArrayList types = new ArrayList();

            try
            {
                types.Add(typeof(DCSoft.CSharpWriter.Commands.WriterCommandModuleBrowse));
                types.Add(typeof(DCSoft.CSharpWriter.Commands.WriterCommandModuleEdit));
                types.Add(typeof(DCSoft.CSharpWriter.Commands.WriterCommandModuleFile));


                //foreach (Type t in typeof(WriterCommandModule).Assembly.GetTypes())
                //{
                //    if (t.IsSubclassOf(typeof(WriterCommandModule)))
                //    {
                //        types.Add(t);
                //    }
                //    else if (t.IsSubclassOf(typeof(WriterCommand)))
                //    {
                //        types.Add(t);
                //    }
                //}
            }
            catch (Exception ext)
            {
                MessageBox.Show(ext.ToString());
            }
            //MessageBox.Show(td == null ? "null" : td.GetType().FullName);
            ITypeDiscoveryService td = (ITypeDiscoveryService)context.GetService(typeof(ITypeDiscoveryService));

            if (td != null)
            {
                //MessageBox.Show(td.GetType().FullName + " " + td.GetType().Assembly.Location );
                ICollection acts = td.GetTypes(typeof(WriterCommand), false);
                //MessageBox.Show(acts == null ? "-1" : acts.Count.ToString());
                if (acts != null)
                {
                    foreach (Type t in acts)
                    {
                        if (types.Contains(t) == false)
                        {
                            types.Add(t);
                        }
                    }

                    //types.AddRange(acts);
                }//if

                acts = td.GetTypes(typeof(CSWriterCommandModule), false);
                //MessageBox.Show(acts == null ? "no module" : acts.Count.ToString());
                if (acts != null)
                {
                    foreach (Type t in acts)
                    {
                        if (types.Contains(t) == false)
                        {
                            types.Add(t);
                        }
                    }
                    //types.AddRange(acts);
                }
            }//if
            _buffer = GetCommandDescriptors((Type[])types.ToArray(typeof(Type)));
            return(_buffer);
        }
        public override bool EditComponent(ITypeDescriptorContext context, object obj, IWin32Window parent)
        {
            IntPtr handle = (parent == null) ? IntPtr.Zero : parent.Handle;

            if (obj is System.Windows.Forms.NativeMethods.IPerPropertyBrowsing)
            {
                Guid empty = Guid.Empty;
                if ((((System.Windows.Forms.NativeMethods.IPerPropertyBrowsing)obj).MapPropertyToPage(-1, out empty) == 0) && !empty.Equals(Guid.Empty))
                {
                    object pobjs  = obj;
                    Guid[] pClsid = new Guid[] { empty };
                    SafeNativeMethods.OleCreatePropertyFrame(new HandleRef(parent, handle), 0, 0, "PropertyPages", 1, ref pobjs, 1, pClsid, Application.CurrentCulture.LCID, 0, IntPtr.Zero);
                    return(true);
                }
            }
            if (obj is System.Windows.Forms.NativeMethods.ISpecifyPropertyPages)
            {
                Exception exception;
                bool      flag = false;
                try
                {
                    System.Windows.Forms.NativeMethods.tagCAUUID pPages = new System.Windows.Forms.NativeMethods.tagCAUUID();
                    try
                    {
                        ((System.Windows.Forms.NativeMethods.ISpecifyPropertyPages)obj).GetPages(pPages);
                        if (pPages.cElems <= 0)
                        {
                            return(false);
                        }
                    }
                    catch
                    {
                        return(false);
                    }
                    try
                    {
                        object obj3 = obj;
                        SafeNativeMethods.OleCreatePropertyFrame(new HandleRef(parent, handle), 0, 0, "PropertyPages", 1, ref obj3, pPages.cElems, new HandleRef(pPages, pPages.pElems), Application.CurrentCulture.LCID, 0, IntPtr.Zero);
                        return(true);
                    }
                    finally
                    {
                        if (pPages.pElems != IntPtr.Zero)
                        {
                            Marshal.FreeCoTaskMem(pPages.pElems);
                        }
                    }
                }
                catch (Exception exception2)
                {
                    flag      = true;
                    exception = exception2;
                }
                if (flag)
                {
                    string     text    = System.Windows.Forms.SR.GetString("ErrorPropertyPageFailed");
                    IUIService service = (context != null) ? ((IUIService)context.GetService(typeof(IUIService))) : null;
                    if (service == null)
                    {
                        RTLAwareMessageBox.Show(null, text, System.Windows.Forms.SR.GetString("PropertyGridTitle"), MessageBoxButtons.OK, MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1, 0);
                    }
                    else if (exception != null)
                    {
                        service.ShowError(exception, text);
                    }
                    else
                    {
                        service.ShowError(text);
                    }
                }
            }
            return(false);
        }
        public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
        {
            if (context != null)
            {
                var workflowBuilder = (WorkflowBuilder)context.GetService(typeof(WorkflowBuilder));
                if (workflowBuilder != null)
                {
                    var hw_slots = (from builder in workflowBuilder.Workflow.Descendants()
                                    let ctx_config = ExpressionBuilder.GetWorkflowElement(builder) as ONIContext
                                                     where ctx_config != null && !string.IsNullOrEmpty(ctx_config.ContextConfiguration.Slot.Driver)
                                                     select ctx_config.ContextConfiguration.Slot)
                                   .Concat(ONIContextManager.LoadConfiguration())
                                   .Distinct()
                                   .ToList();

                    // This device
                    var      deviceattribute = context.PropertyDescriptor.ComponentType.GetCustomAttributes(typeof(ONIXDeviceIDAttribute), true).FirstOrDefault() as ONIXDeviceIDAttribute;
                    DeviceID deviceID        = deviceattribute == null ? DeviceID.Null : deviceattribute.deviceID;

                    // To fill after inspecting hardware
                    var deviceAddresses = new List <ONIDeviceAddress>();

                    foreach (var hw in hw_slots)
                    {
                        try
                        {
                            using (var c = ONIContextManager.ReserveContext(hw))
                            {
                                // Find valid device indices
                                var dev_matches = c.Context.DeviceTable
                                                  //.Where(dev => dev.Value.ID == (uint)device.ID)
                                                  .Where(dev =>
                                {
                                    return(deviceID == DeviceID.Null ?
                                           dev.Value.ID != (uint)DeviceID.Null :
                                           dev.Value.ID == (uint)deviceID);
                                })
                                                  .Select(x =>
                                {
                                    var d = new ONIDeviceAddress
                                    {
                                        HardwareSlot = hw,
                                        Address      = x.Key
                                    };
                                    return(d);
                                }).ToList();

                                deviceAddresses = deviceAddresses.Concat(dev_matches).ToList();
                            }
                        }
                        catch (InvalidProgramException) // Bad context initialization
                        {
                            return(base.GetStandardValues(context));
                        }
                        catch (oni.ONIException) // Something happened during hardware init
                        {
                            return(base.GetStandardValues(context));
                        }
                    }

                    return(deviceAddresses.Count == 0 ?
                           base.GetStandardValues(context) :
                           new StandardValuesCollection(deviceAddresses));
                }
            }

            return(base.GetStandardValues(context));
        }