private void SetValue(object value) { if (value == null) { _value = null; _nodeType = PluginTreeNodeType.Empty; this.Plugin = null; return; } if (TypeExtension.IsAssignableFrom(typeof(Builtin), value.GetType())) { this.SetBuiltin((Builtin)value); } else { _value = value; _nodeType = PluginTreeNodeType.Custom; this.Plugin = null; var properties = _properties; if (properties != null && properties.Count > 0) { foreach (PluginExtendedProperty property in properties) { var propertyType = Tiandao.Common.Converter.GetMemberType(_value, property.Name); Tiandao.Common.Converter.SetValue(_value, property.Name, property.GetValue(propertyType)); } } } }
protected virtual IOptionLoader CreateLoader(Type type) { if (type == null) { return(null); } if (!TypeExtension.IsAssignableFrom(typeof(IOptionLoader), type)) { throw new ArgumentException("The parameter is not a IOptionLoader type."); } #if !CORE_CLR var constructor = type.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { typeof(OptionNode) }, null); #else var constructor = type.GetConstructor(new Type[] { typeof(OptionNode) }); #endif try { if (constructor != null) { return((IOptionLoader)constructor.Invoke(new object[] { _root })); } return((IOptionLoader)Activator.CreateInstance(type, true)); } catch (Exception ex) { throw new InvalidOperationException(string.Format("Can create a option-loader instance from the '{0}' type.", type), ex); } }
public static bool TrySerialize(Stream serializationStream, object graph) { if (serializationStream == null) { throw new ArgumentNullException("serializationStream"); } if (graph == null) { return(false); } if (TypeExtension.IsAssignableFrom(typeof(ISerializable), graph.GetType())) { ((ISerializable)graph).Serialize(serializationStream); return(true); } var attribute = (SerializerAttribute)graph.GetType().GetCustomAttribute(typeof(SerializerAttribute)); if (attribute != null && attribute.Type != null) { var serializer = Activator.CreateInstance(attribute.Type) as ISerializer; if (serializer != null) { serializer.Serialize(serializationStream, graph); return(true); } } return(false); }
private void SetPropertyValue(OptionConfigurationProperty property, object value) { if (property == null) { throw new ArgumentNullException("property"); } if (object.Equals(value, property.DefaultValue)) { _values.Remove(property); } else { if (TypeExtension.IsAssignableFrom(property.Type, value.GetType())) { _values[property] = value; } else { if (property.Converter == null) { _values[property] = Converter.ConvertValue(value, property.Type, property.DefaultValue); } else { _values[property] = property.Converter.ConvertFrom(value); } } } }
public void AssignableTest() { Assert.True(TypeExtension.IsAssignableFrom(typeof(IEnumerable), typeof(IDictionary <string, object>))); Assert.True(TypeExtension.IsAssignableFrom(typeof(IEnumerable), typeof(IList))); Assert.True(TypeExtension.IsAssignableFrom(typeof(IEnumerable), typeof(int[]))); Assert.True(TypeExtension.IsAssignableFrom(typeof(IList), typeof(List <string>))); }
internal static bool ObtainParameter(Plugin plugin, Type parameterType, string parameterName, out object parameterValue) { if (parameterType == typeof(Plugin)) { parameterValue = plugin; return(true); } if (parameterType == typeof(PluginContext)) { parameterValue = plugin.Context; return(true); } if (TypeExtension.IsAssignableFrom(typeof(Tiandao.ComponentModel.ApplicationContextBase), parameterType)) { parameterValue = plugin.Context.ApplicationContext; return(true); } if (TypeExtension.IsAssignableFrom(typeof(Tiandao.Services.IServiceProviderFactory), parameterType)) { parameterValue = plugin.Context.ServiceFactory; return(true); } if (TypeExtension.IsAssignableFrom(typeof(Tiandao.Services.IServiceProvider), parameterType)) { parameterValue = plugin.Context.ServiceFactory.Default; return(true); } if (TypeExtension.IsAssignableFrom(typeof(Tiandao.Options.Profiles.Profile), parameterType)) { parameterValue = Tiandao.Options.Plugins.OptionUtility.GetProfile(plugin); return(true); } if (TypeExtension.IsAssignableFrom(typeof(Tiandao.Options.Configuration.OptionConfiguration), parameterType)) { parameterValue = Tiandao.Options.Plugins.OptionUtility.GetConfiguration(plugin); return(true); } if (TypeExtension.IsAssignableFrom(typeof(Tiandao.Options.IOptionProvider), parameterType)) { parameterValue = plugin.Context.ApplicationContext.OptionManager; return(true); } if (TypeExtension.IsAssignableFrom(typeof(Tiandao.Options.ISettingsProvider), parameterType)) { parameterValue = Tiandao.Options.Plugins.SettingProviderFactory.GetProvider(plugin); return(true); } parameterValue = null; return(false); }
protected virtual bool IsCollectionType(Type type) { if (type == null || type.IsPrimitive() || type == typeof(string)) { return(false); } return(TypeExtension.IsAssignableFrom(typeof(System.Collections.IEnumerable), type)); }
protected override bool ValidateType(Type type) { if (type == null) { return(false); } return(TypeExtension.IsAssignableFrom(typeof(T), type)); }
internal static object BuildType(string typeName, Builtin builtin) { Type type = PluginUtility.GetType(typeName); if (type == null) { throw new PluginException(string.Format("Can not get type from '{0}' text for '{1}' builtin.", typeName, builtin)); } try { object result = BuildType(type, (Type parameterType, string parameterName, out object parameterValue) => { if (parameterType == typeof(Builtin)) { parameterValue = builtin; return(true); } if (parameterType == typeof(PluginTreeNode)) { parameterValue = builtin.Node; return(true); } if (parameterType == typeof(string) && string.Equals(parameterName, "name", StringComparison.OrdinalIgnoreCase)) { parameterValue = builtin.Name; return(true); } if (TypeExtension.IsAssignableFrom(typeof(Tiandao.Services.IServiceProvider), parameterType)) { parameterValue = FindServiceProvider(builtin); return(true); } return(ObtainParameter(builtin.Plugin, parameterType, parameterName, out parameterValue)); }); if (result == null) { throw new PluginException(string.Format("Can not build instance of '{0}' type, Maybe that's cause type-generator not found matched constructor with parameters. in '{1}' builtin.", type.FullName, builtin)); } //注入依赖属性 InjectProperties(result, builtin); return(result); } catch (Exception ex) { throw new PluginException(string.Format("Occurred an exception on create a builtin instance of '{0}' type, at '{1}' builtin.", type.FullName, builtin), ex); } }
protected virtual bool IsTermination(SerializationWriterContext context) { if (context.Terminated || context.Value == null) { return(true); } var type = context.Value.GetType(); return(type.IsPrimitive() || type.IsEnum() || type == typeof(decimal) || type == typeof(DateTime) || type == typeof(DBNull) || type == typeof(Guid) || type == typeof(object) || type == typeof(string) || TypeExtension.IsAssignableFrom(typeof(Type), type)); }
public void Save(Stream stream) { if (stream == null) { throw new ArgumentNullException(nameof(stream)); } using (XmlWriter writer = XmlWriter.Create(stream, new XmlWriterSettings() { Encoding = Encoding.UTF8, Indent = true, IndentChars = "\t", OmitXmlDeclaration = false, NewLineOnAttributes = false, })) { writer.WriteStartElement("options"); foreach (var section in _sections) { //写入option开始元素 writer.WriteStartElement("option"); writer.WriteStartAttribute("path"); writer.WriteString(string.IsNullOrEmpty(section.Path) ? "/" : section.Path); writer.WriteEndAttribute(); //依次写入选项申明节点下的各级子元素 foreach (var child in section.Children) { writer.WriteStartElement(child.Key); if (TypeExtension.IsAssignableFrom(typeof(OptionConfigurationElement), child.Value.GetType())) { writer.WriteStartAttribute(child.Key + ".type"); writer.WriteString(child.Value.GetType().AssemblyQualifiedName); writer.WriteEndAttribute(); } child.Value.SerializeElement(writer); writer.WriteEndElement(); } //关闭option元素,即写入</option>元素 writer.WriteEndElement(); } writer.WriteEndElement(); } }
public void TestIsAssignableFrom() { var baseType = typeof(ICollection <Person>); var instanceType = typeof(Collection <Person>); Assert.True(Zongsoft.Common.TypeExtension.IsAssignableFrom(baseType, instanceType)); Assert.True(baseType.IsAssignableFrom(instanceType)); baseType = typeof(ICollection <>); Assert.True(Zongsoft.Common.TypeExtension.IsAssignableFrom(baseType, instanceType)); Assert.False(baseType.IsAssignableFrom(instanceType)); Assert.True(TypeExtension.IsAssignableFrom(typeof(PersonServiceBase <>), typeof(EmployeeService))); }
public static bool CanSerialize(object graph) { if (graph == null) { return(false); } if (TypeExtension.IsAssignableFrom(typeof(ISerializable), graph.GetType())) { return(true); } var attribute = (SerializerAttribute)graph.GetType().GetCustomAttribute(typeof(SerializerAttribute)); return(attribute != null && attribute.Type != null); }
protected internal virtual void SerializeElement(XmlWriter writer) { var elementName = this.ElementProperty != null ? this.ElementProperty.Name : string.Empty; if (!string.IsNullOrEmpty(elementName)) { writer.WriteStartElement(elementName); } object value; var elements = new List <OptionConfigurationElement>(); foreach (var property in this.Properties) { if (TypeExtension.IsAssignableFrom(typeof(OptionConfigurationElement), property.Type)) { if (_values.TryGetValue(property, out value)) { elements.Add((OptionConfigurationElement)value); } } else { if (_values.TryGetValue(property, out value)) { writer.WriteStartAttribute(property.Name); writer.WriteString(OptionConfigurationUtility.GetValueString(value, property.Converter)); writer.WriteEndAttribute(); } } } if (elements.Count > 0) { foreach (var element in elements) { element.SerializeElement(writer); } } if (!string.IsNullOrEmpty(elementName)) { writer.WriteEndElement(); } }
private OptionConfigurationElement EnsureElementPropertyValue(OptionConfigurationProperty property) { if (property == null) { throw new ArgumentNullException("property"); } object value = null; lock (_values) { _values.TryGetValue(property, out value); if (value == null) { //如果当前配置属性定义项的类型不是一个选项配置元素,则抛出异常。因为所有复合类型必须从选项配置元素继承 if (!TypeExtension.IsAssignableFrom(typeof(OptionConfigurationElement), property.Type)) { throw new OptionConfigurationException(); } //根据配置属性定义项的类型创建其对应的目标对象 if (property.Type.IsGenericType() && property.Type.GetGenericTypeDefinition() == typeof(OptionConfigurationElementCollection <>)) { value = Activator.CreateInstance(property.Type, new object[] { property.ElementName, null }); } else { value = Activator.CreateInstance(property.Type); } //设置创建的选项配置元素对象的表示其自身的属性定义项 ((OptionConfigurationElement)value)._elementProperty = property; //将创建的目标对象保存到对应的属性值中 _values[property] = value; } } return((OptionConfigurationElement)value); }
protected virtual bool GetDirectedValue(object value, out string valueText) { valueText = null; if (value == null) { return(true); } Type valueType = value.GetType(); bool isDirectedValue = valueType.IsPrimitive() || valueType.IsEnum() || valueType == typeof(decimal) || valueType == typeof(DateTime) || valueType == typeof(DBNull) || valueType == typeof(object) || valueType == typeof(string) || valueType == typeof(Guid) || TypeExtension.IsAssignableFrom(typeof(Type), valueType); if (isDirectedValue) { valueText = value.ToString(); return(true); } #if !CORE_CLR var converter = TypeDescriptor.GetConverter(value); #else var converter = TypeDescriptor.GetConverter(value.GetType()); #endif if (converter != null && converter.GetType() != typeof(TypeConverter)) { isDirectedValue = converter.CanConvertFrom(typeof(string)) && converter.CanConvertTo(typeof(string)); if (isDirectedValue) { valueText = converter.ConvertToInvariantString(value); } } return(isDirectedValue); }
/// <summary> /// 读取选项配置文件中的XML内容。 /// </summary> /// <param name="reader">在选项配置文件中进行读取操作的<seealso cref="System.Xml.XmlReader"/>读取器。</param> protected internal virtual void DeserializeElement(XmlReader reader) { if (reader.ReadState == ReadState.Initial) { if (!reader.Read()) { throw new OptionConfigurationException(); } } OptionConfigurationProperty property; if (reader.NodeType == XmlNodeType.Element) { var elementName = reader.Name; for (int i = 0; i < reader.AttributeCount; i++) { reader.MoveToAttribute(i); //XML特性名中间含点的,并且是以表示是以元素名打头的,则表示为系统内置特性因而无需解析处理 if (reader.Name.StartsWith(elementName + ".")) { continue; } //获取当前XML元素特性对应的配置属性定义项 if (this.Properties.TryGetValue(reader.Name, out property)) { this.SetPropertyValue(property, reader.Value); } else { //执行处理未知的属性反序列化 if (!this.OnDeserializeUnrecognizedAttribute(reader.Name, reader.Value)) { throw new OptionConfigurationException(string.Format("The '{0}' option configuration attribute is unrecognized.", reader.Name)); } } } //将当前读取器移到元素上 reader.MoveToElement(); } //如果当前XML元素是空元素(即其没有子节点的元素),则返回 if (reader.IsEmptyElement) { return; } //定义当前读取器的初始深度 int depth = reader.Depth; //定义当前待解析子元素的当前配置项元素 OptionConfigurationElement element = this; while (reader.Read() && reader.Depth > depth) { if (reader.NodeType != XmlNodeType.Element) { continue; } if (reader.Depth == depth + 1) { element = this; } //如果当前配置项元素是配置集合,则约定当前读取器所处的位置应当处于其下的集合元素的XML节点处 if (TypeExtension.IsAssignableFrom(typeof(OptionConfigurationElementCollection), element.GetType())) { //使用当前配置集合来解析当前读取器所处的XML节点内容 element.DeserializeElement(reader.ReadSubtree()); //忽略后续操作,直接进行后续XML内容处理 continue; } //根据当前XML元素名获取对应的配置属性定义项,如果获取失败则获取当前配置项中的默认集合属性定义项 if (!element.Properties.TryGetValue(reader.Name, out property)) { property = OptionConfigurationUtility.GetDefaultCollectionProperty(element.Properties); } //如果对应的配置属性定义项均获取失败则抛出异常 if (property == null) { throw new OptionConfigurationException(string.Format("The '{0}' option configuration element is unrecognized.", reader.Name)); } //获取或创建当前配置属性定义项对应的目标元素对象 element = element.EnsureElementPropertyValue(property); //判断获取的配置项元素是否为配置项集合 var collection = element as OptionConfigurationElementCollection; if (collection != null) { //如果当前配置项集合不是默认集合(即集合有对应的XML节点),则将当前读取器移动到其下的子元素的XML节点上 if (!property.IsDefaultCollection) { reader.ReadToDescendant(string.IsNullOrWhiteSpace(property.ElementName) ? collection.ElementName : property.ElementName); } } //调用当前配置元素对象的反序列化方法 element.DeserializeElement(reader.ReadSubtree()); } }
private IContainer GetContainer(object target) { if (target == null) { return(null); } #if !CORE_CLR var memberInfo = target.GetType().FindMembers((MemberTypes.Field | MemberTypes.Property), (BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.GetProperty), (member, criteria) => { if (member.MemberType == MemberTypes.Field) { return(typeof(IContainer).IsAssignableFrom(((FieldInfo)member).FieldType)); } if (member.MemberType == MemberTypes.Property) { return(typeof(IContainer).IsAssignableFrom(((PropertyInfo)member).PropertyType)); } return(false); }, null).FirstOrDefault(); if (memberInfo.MemberType == MemberTypes.Field) { return(((FieldInfo)memberInfo).GetValue(target) as IContainer); } if (memberInfo.MemberType == MemberTypes.Property) { return(((PropertyInfo)memberInfo).GetValue(target, null) as IContainer); } #else var memberInfo = target.GetType().GetMembers(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(member => { if (member.IsField()) { return(TypeExtension.IsAssignableFrom(typeof(IContainer), ((FieldInfo)member).FieldType)); } if (member.IsProperty()) { return(TypeExtension.IsAssignableFrom(typeof(IContainer), ((PropertyInfo)member).PropertyType)); } return(false); }).FirstOrDefault(); if (memberInfo.IsField()) { return(((FieldInfo)memberInfo).GetValue(target) as IContainer); } if (memberInfo.IsProperty()) { return(((PropertyInfo)memberInfo).GetValue(target, null) as IContainer); } #endif return(null); }