Esempio n. 1
0
        public static void DescribeComponent(object instance, ScriptComponentDescriptor descriptor, IUrlResolutionService urlResolver, IControlResolver controlResolver)
        {
            // validate preconditions
            if (instance == null)
            {
                throw new ArgumentNullException("instance");
            }
            if (descriptor == null)
            {
                throw new ArgumentNullException("descriptor");
            }
            if (urlResolver == null)
            {
                urlResolver = instance as IUrlResolutionService;
            }
            if (controlResolver == null)
            {
                controlResolver = instance as IControlResolver;
            }

            // describe properties
            // PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(instance);

            PropertyInfo[] properties = instance.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

            foreach (PropertyInfo prop in properties)
            {
                ScriptControlPropertyAttribute propAttr  = null;
                ScriptControlEventAttribute    eventAttr = null;
                string propertyName = prop.Name;

                System.ComponentModel.AttributeCollection attribs = new System.ComponentModel.AttributeCollection(Attribute.GetCustomAttributes(prop, false));

                // Try getting a property attribute
                propAttr = (ScriptControlPropertyAttribute)attribs[typeof(ScriptControlPropertyAttribute)];
                if (propAttr == null || !propAttr.IsScriptProperty)
                {
                    // Try getting an event attribute
                    eventAttr = (ScriptControlEventAttribute)attribs[typeof(ScriptControlEventAttribute)];
                    if (eventAttr == null || !eventAttr.IsScriptEvent)
                    {
                        continue;
                    }
                }

                // attempt to rename the property/event
                ClientPropertyNameAttribute nameAttr = (ClientPropertyNameAttribute)attribs[typeof(ClientPropertyNameAttribute)];
                if (nameAttr != null && !string.IsNullOrEmpty(nameAttr.PropertyName))
                {
                    propertyName = nameAttr.PropertyName;
                }

                // determine whether to serialize the value of a property.  readOnly properties should always be serialized
                //bool serialize = true;// prop.ShouldSerializeValue(instance) || prop.IsReadOnly;
                //if (serialize)
                //{
                // get the value of the property, skip if it is null
                Control c     = null;
                object  value = prop.GetValue(instance, new object[0] {
                });
                if (value == null)
                {
                    continue;
                }

                // convert and resolve the value
                if (eventAttr != null && prop.PropertyType != typeof(String))
                {
                    throw new InvalidOperationException("ScriptControlEventAttribute can only be applied to a property with a PropertyType of System.String.");
                }
                else
                {
                    if (!prop.PropertyType.IsPrimitive && !prop.PropertyType.IsEnum)
                    {
                        if (prop.PropertyType == typeof(Color))
                        {
                            value = ColorTranslator.ToHtml((Color)value);
                        }
                        else
                        {
                            // TODO: Determine if we should let ASP.NET AJAX handle this type of conversion, as it supports JSON serialization
                            //TypeConverter conv = prop.Converter;
                            //value = conv.ConvertToString(null, CultureInfo.InvariantCulture, value);

                            //if (prop.PropertyType == typeof(CssStyleCollection))
                            //    value = (new CssStyleCollectionJSCoverter()).Serialize(value, new JavaScriptSerializer());
                            //if (prop.PropertyType == typeof(Style))
                            //    value = (new CssStyleCollectionJSCoverter()).Serialize(((Style)value).GetStyleAttributes(null), new JavaScriptSerializer());

                            Type valueType = value.GetType();

                            JavaScriptConverterAttribute attr      = (JavaScriptConverterAttribute)attribs[typeof(JavaScriptConverterAttribute)];
                            JavaScriptConverter          converter = attr != null ?
                                                                     (JavaScriptConverter)TypeCreator.CreateInstance(attr.ConverterType) :
                                                                     JsonSerializerFactory.GetJavaScriptConverter(valueType);

                            if (converter != null)
                            {
                                value = converter.Serialize(value, JsonSerializerFactory.GetJavaScriptSerializer());
                            }
                            else
                            {
                                value = JsonHelper.PreSerializeObject(value);
                            }

                            //Dictionary<string, object> dict = value as Dictionary<string, object>;
                            //if (dict != null && !dict.ContainsKey("__type"))
                            //    dict["__type"] = valueType.AssemblyQualifiedName;
                        }
                    }
                    if (attribs[typeof(IDReferencePropertyAttribute)] != null && controlResolver != null)
                    {
                        c = controlResolver.ResolveControl((string)value);
                    }
                    if (attribs[typeof(UrlPropertyAttribute)] != null && urlResolver != null)
                    {
                        value = urlResolver.ResolveClientUrl((string)value);
                    }
                }

                // add the value as an appropriate description
                if (eventAttr != null)
                {
                    if (!string.IsNullOrEmpty((string)value))
                    {
                        descriptor.AddEvent(propertyName, (string)value);
                    }
                }
                else if (attribs[typeof(ElementReferenceAttribute)] != null)
                {
                    if (c == null && controlResolver != null)
                    {
                        c = controlResolver.ResolveControl((string)value);
                    }
                    if (c != null)
                    {
                        value = c.ClientID;
                    }
                    descriptor.AddElementProperty(propertyName, (string)value);
                }
                else if (attribs[typeof(ComponentReferenceAttribute)] != null)
                {
                    if (c == null && controlResolver != null)
                    {
                        c = controlResolver.ResolveControl((string)value);
                    }
                    if (c != null)
                    {
                        //ExtenderControlBase ex = c as ExtenderControlBase;
                        //if (ex != null && ex.BehaviorID.Length > 0)
                        //    value = ex.BehaviorID;
                        //else
                        value = c.ClientID;
                    }
                    descriptor.AddComponentProperty(propertyName, (string)value);
                }
                else
                {
                    if (c != null)
                    {
                        value = c.ClientID;
                    }
                    descriptor.AddProperty(propertyName, value);
                }
            }
            //}

            // determine if we should describe methods
            foreach (MethodInfo method in instance.GetType().GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public))
            {
                ScriptControlMethodAttribute methAttr = (ScriptControlMethodAttribute)Attribute.GetCustomAttribute(method, typeof(ScriptControlMethodAttribute));
                if (methAttr == null || !methAttr.IsScriptMethod)
                {
                    continue;
                }

                // We only need to support emitting the callback target and registering the WebForms.js script if there is at least one valid method
                Control control = instance as Control;
                if (control != null)
                {
                    // Force WebForms.js
                    control.Page.ClientScript.GetCallbackEventReference(control, null, null, null);

                    // Add the callback target
                    descriptor.AddProperty("_callbackTarget", control.UniqueID);
                }
                break;
            }
        }
        private static Dictionary <string, object> BuildGraph(object obj, IUrlResolutionService uriResolver,
                                                              IControlResolver controlResolver)
        {
            Dictionary <string, object>  dict = new Dictionary <string, object>();
            PropertyDescriptorCollection pdc  = TypeDescriptor.GetProperties(obj);

            foreach (PropertyDescriptor pd in pdc)
            {
                ExtenderControlPropertyAttribute ecpa = GetAttribute <ExtenderControlPropertyAttribute>(pd);

                ClientPropertyNameAttribute    cpna = GetAttribute <ClientPropertyNameAttribute>(pd);
                IDReferencePropertyAttribute   idr  = GetAttribute <IDReferencePropertyAttribute>(pd);
                UrlPropertyAttribute           ura  = GetAttribute <UrlPropertyAttribute>(pd);
                ExtenderControlMethodAttribute ecma = GetAttribute <ExtenderControlMethodAttribute>(pd);
                ExtenderControlEventAttribute  ecea = GetAttribute <ExtenderControlEventAttribute>(pd);
                ElementReferenceAttribute      era  = GetAttribute <ElementReferenceAttribute>(pd);
                ComponentReferenceAttribute    cra  = GetAttribute <ComponentReferenceAttribute>(pd);
                if (ecpa == null && cra == null && cpna == null && era == null)
                {
                    continue;
                }


                string propName =
                    cpna != null && !string.IsNullOrEmpty(cpna.PropertyName)
                        ? cpna.PropertyName
                        : pd.Name;


                if (propName == "ClientClassName")
                {
                    propName = "typeToBuild";
                }

                object o     = null;
                object value = pd.GetValue(obj);
                if (value == null)
                {
                    continue;
                }

                if (value as IClientClass != null && ((IClientClass)value).NotSet)
                {
                    continue;
                }

                if (value as ClientEvalScript != null && string.IsNullOrEmpty((value as ClientEvalScript).ClientScript))
                {
                    continue;
                }

                if (pd.PropertyType == typeof(string))
                {
                    o = value;
                    if (ura != null)
                    {
                        o = uriResolver.ResolveClientUrl((string)o);
                    }
                    else if (idr != null || cra != null)
                    {
                        o = BuildGraph(new Reference
                        {
                            ReferenceType = ReferenceType.Component,
                            ClientId      = controlResolver.ResolveControl((string)o).ClientID
                        }, uriResolver, controlResolver);
                    }
                    else if (era != null)
                    {
                        Control c = controlResolver.ResolveControl((string)o);
                        o = BuildGraph(
                            new Reference
                        {
                            ReferenceType = ReferenceType.Element, ClientId = c == null ? (string)o : c.ClientID
                        },
                            uriResolver, controlResolver);
                    }
                }
                else if (value is IEnumerable)
                {
                    List <object> lst = new List <object>();
                    foreach (object a in (IEnumerable)value)
                    {
                        object b;
                        if (a as IUICollectionItem != null)
                        {
                            b = a is UriValue
                                    ? uriResolver.ResolveClientUrl(((UriValue)a).Value.ToString())
                                    : ((IUICollectionItem)a).Value;
                        }
                        else
                        {
                            b = BuildGraph(a, uriResolver, controlResolver);
                        }
                        if (b != null)
                        {
                            lst.Add(b);
                        }
                    }
                    if (lst.Count > 0)
                    {
                        o = lst;
                    }
                }
                else if (pd.PropertyType.IsEnum)
                {
                    o = Enum.GetName(pd.PropertyType, value);
                }
                else if (pd.PropertyType.IsPrimitive || pd.PropertyType.IsValueType)
                {
                    o = value;
                }
                else
                {
                    o = BuildGraph(value, uriResolver, controlResolver);
                }

                if (o != null)
                {
                    dict.Add(propName, o);
                }
            }
            return(dict.Count > 0 ? dict : null);
        }
        public static void DescribeComponent(object instance, ScriptComponentDescriptor descriptor,
                                             IUrlResolutionService urlResolver, IControlResolver controlResolver)
        {
            // validate preconditions
            if (instance == null)
            {
                throw new ArgumentNullException("instance");
            }
            if (descriptor == null)
            {
                throw new ArgumentNullException("descriptor");
            }
            if (urlResolver == null)
            {
                urlResolver = instance as IUrlResolutionService;
            }
            if (controlResolver == null)
            {
                controlResolver = instance as IControlResolver;
            }

            // describe properties
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(instance);

            foreach (PropertyDescriptor prop in properties)
            {
                ExtenderControlPropertyAttribute propAttr  = null;
                ExtenderControlEventAttribute    eventAttr = null;
                string propertyName = prop.Name;

                // Try getting a property attribute
                propAttr = (ExtenderControlPropertyAttribute)prop.Attributes[typeof(ExtenderControlPropertyAttribute)];
                if (propAttr == null || !propAttr.IsScriptProperty)
                {
                    // Try getting an event attribute
                    eventAttr = (ExtenderControlEventAttribute)prop.Attributes[typeof(ExtenderControlEventAttribute)];
                    if (eventAttr == null || !eventAttr.IsScriptEvent)
                    {
                        continue;
                    }
                }

                // attempt to rename the property/event
                ClientPropertyNameAttribute nameAttr =
                    (ClientPropertyNameAttribute)prop.Attributes[typeof(ClientPropertyNameAttribute)];
                if (!string.IsNullOrEmpty(nameAttr.PropertyName))
                {
                    propertyName = nameAttr.PropertyName;
                }

                object value = prop.GetValue(instance);
                if (value == null)
                {
                    continue;
                }

                // determine whether to serialize the value of a property.  readOnly properties should always be serialized
                bool serialize = prop.ShouldSerializeValue(instance) || prop.IsReadOnly;
                if (serialize)
                {
                    // get the value of the property, skip if it is null
                    Control c = null;


                    // convert and resolve the value
                    if (eventAttr != null && prop.PropertyType != typeof(String))
                    {
                        throw new InvalidOperationException(
                                  "ExtenderControlEventAttribute can only be applied to a property with a PropertyType of System.String.");
                    }
                    else
                    {
                        if (!prop.PropertyType.IsPrimitive && !prop.PropertyType.IsEnum)
                        {
                            // Check if we can use any of our custom converters
                            // (first do a direct lookup on the property type,
                            // but also check all of its base types if nothing
                            // was found)
                            Converter <object, string> customConverter = null;
                            if (!_customConverters.TryGetValue(prop.PropertyType, out customConverter))
                            {
                                foreach (KeyValuePair <Type, Converter <object, string> > pair in _customConverters)
                                {
                                    if (prop.PropertyType.IsSubclassOf(pair.Key))
                                    {
                                        customConverter = pair.Value;
                                        break;
                                    }
                                }
                            }

                            // Use the custom converter if found, otherwise use
                            // its current type converter
                            if (customConverter != null)
                            {
                                value = customConverter(value);
                            }
                            else
                            {
                                // Determine if we should let ASP.NET AJAX handle this type of conversion, as it supports JSON serialization
                                if (propAttr != null && propAttr.UseJsonSerialization)
                                {
                                    if (value is IEnumerable)
                                    {
                                        List <object> lst = new List <object>();
                                        foreach (object a in (IEnumerable)value)
                                        {
                                            object b;
                                            Type   typ = a.GetType();
                                            if (a as IUICollectionItem != null)
                                            {
                                                b = a is UriValue
                                                        ? urlResolver.ResolveClientUrl(((UriValue)a).Value.ToString())
                                                        : ((IUICollectionItem)a).Value;
                                            }
                                            else if (typ.IsPrimitive || typ.IsValueType)
                                            {
                                                b = a;
                                            }
                                            else
                                            {
                                                b = BuildGraph(a, urlResolver, controlResolver);
                                            }
                                            if (b != null)
                                            {
                                                lst.Add(b);
                                            }
                                        }
                                        if (lst.Count > 0)
                                        {
                                            value = lst;
                                        }
                                    }
                                    else if (value.GetType().IsPrimitive || value.GetType().IsValueType)
                                    {
                                    }
                                    else
                                    {
                                        value = BuildGraph(value, urlResolver, controlResolver);
                                    }
                                    // Use ASP.NET JSON serialization
                                }
                                else
                                {
                                    // Use the property's own converter
                                    TypeConverter conv = prop.Converter;
                                    value = conv.ConvertToString(null, CultureInfo.InvariantCulture, value);
                                }
                            }
                        }
                        if (prop.Attributes[typeof(IDReferencePropertyAttribute)] != null && controlResolver != null)
                        {
                            c = controlResolver.ResolveControl((string)value);
                        }
                        if (prop.Attributes[typeof(UrlPropertyAttribute)] != null && urlResolver != null)
                        {
                            value = urlResolver.ResolveClientUrl((string)value);
                        }
                    }

                    // add the value as an appropriate description
                    if (eventAttr != null)
                    {
                        descriptor.AddEvent(propertyName, (string)value);
                    }
                    else if (prop.Attributes[typeof(ElementReferenceAttribute)] != null)
                    {
                        if (c == null && controlResolver != null)
                        {
                            c = controlResolver.ResolveControl((string)value);
                        }
                        if (c != null)
                        {
                            value = c.ClientID;
                        }
                        descriptor.AddElementProperty(propertyName, (string)value);
                    }
                    else if (prop.Attributes[typeof(ComponentReferenceAttribute)] != null)
                    {
                        if (c == null && controlResolver != null)
                        {
                            c = controlResolver.ResolveControl((string)value);
                        }
                        if (c != null)
                        {
                            ExtenderControlBase ex = c as ExtenderControlBase;
                            if (ex != null && ex.BehaviorID.Length > 0)
                            {
                                value = ex.BehaviorID;
                            }
                            else
                            {
                                value = c.ClientID;
                            }
                        }
                        descriptor.AddComponentProperty(propertyName, (string)value);
                    }
                    else
                    {
                        if (c != null)
                        {
                            value = c.ClientID;
                        }
                        descriptor.AddProperty(propertyName, value);
                    }
                }
            }


            // determine if we should describe methods
            foreach (
                MethodInfo method in
                instance.GetType().GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public))
            {
                ExtenderControlMethodAttribute methAttr =
                    (ExtenderControlMethodAttribute)
                    Attribute.GetCustomAttribute(method, typeof(ExtenderControlMethodAttribute));
                if (methAttr == null || !methAttr.IsScriptMethod)
                {
                    continue;
                }

                // We only need to support emitting the callback target and registering the WebForms.js script if there is at least one valid method
                Control control = instance as Control;
                if (control != null)
                {
                    // Force WebForms.js
                    control.Page.ClientScript.GetCallbackEventReference(control, null, null, null);

                    // Add the callback target
                    descriptor.AddProperty("_callbackTarget", control.UniqueID);
                }
                break;
            }
        }
        /// <summary>
        /// 预处理序列化对象,通过调用此函数,可对序列化进行预处理
        /// </summary>
        /// <param name="input">要序列化的对象</param>
        /// <param name="type">要序列化的类型,可以是input的基类或input实现的接口</param>
        /// <param name="resolverTypeLevel">要输出类型信息的级别深度</param>
        /// <returns>处理结果</returns>
        /// <remarks>预处理序列化对象,通过调用此函数,可对序列化进行预处理</remarks>
        public static object PreSerializeObject(object input, Type type, int resolverTypeLevel)
        {
            object result = input;

            if (input != null)
            {
                JavaScriptConverter converter = JsonSerializerFactory.GetJavaScriptConverter(input.GetType());
                if (converter != null)
                {
                    result = converter.Serialize(input, JsonSerializerFactory.GetJavaScriptSerializer());
                }
                else
                {
                    if (input is XElement || input is XmlElement)
                    {
                        result = null;
                    }
                    else if (input is DateTime)
                    {
                        result = input.ToString();
                    }
                    //当前判断条件,只适用经营指标系统,其他系统请注销此判断条件。
                    else if (input is double)
                    {
                        result = ((double)input).ToString("F7");
                    }
                    else if (!(input is ValueType) && !(input is string) && !(input is IDictionary))
                    {
                        IEnumerable list = input as IEnumerable;
                        if (list != null)
                        {
                            ArrayList a = new ArrayList();
                            foreach (object o in list)
                            {
                                a.Add(PreSerializeObject(o, null, resolverTypeLevel - 1));
                            }
                            result = a;
                        }
                        else
                        {
                            Dictionary <string, object> dict = new Dictionary <string, object>();
                            Type inputType = input.GetType();
                            if (type != null)
                            {
                                ExceptionHelper.FalseThrow(type.IsAssignableFrom(inputType),
                                                           string.Format("{0} 没有从类型{1}继承", inputType, type));
                            }
                            else
                            {
                                type = inputType;
                            }
                            foreach (PropertyInfo pi in type.GetProperties(BindingFlags.Instance | BindingFlags.Public))
                            {
                                ScriptIgnoreAttribute ignoreAttr = (ScriptIgnoreAttribute)Attribute.GetCustomAttribute(pi, typeof(ScriptIgnoreAttribute), false);
                                if (ignoreAttr == null)
                                {
                                    MethodInfo mi = pi.GetGetMethod();
                                    if (mi != null && mi.GetParameters().Length <= 0)
                                    {
                                        object v = PreSerializeObject(mi.Invoke(input, null), null, resolverTypeLevel - 1);

                                        ClientPropertyNameAttribute nameAttr = (ClientPropertyNameAttribute)Attribute.GetCustomAttribute(pi, typeof(ClientPropertyNameAttribute), false);
                                        string name = nameAttr == null ? pi.Name : nameAttr.PropertyName;
                                        dict.Add(name, v);
                                    }
                                }
                            }
                            result = dict;
                        }
                    }
                }
            }

            if (resolverTypeLevel > 0 && result is Dictionary <string, object> )
            {
                Dictionary <string, object> resultDict = result as Dictionary <string, object>;
                if (!resultDict.ContainsKey("__type"))
                {
                    resultDict["__type"] = input.GetType().AssemblyQualifiedName;
                }
            }

            return(result);
        }