Beispiel #1
0
        /// <summary>
        /// Converts an IJavaScriptObject into an NET object.
        /// </summary>
        /// <param name="o">The IJavaScriptObject object to convert.</param>
        /// <param name="t"></param>
        /// <returns>Returns a .NET object.</returns>
        public override object Deserialize(IJavaScriptObject o, Type t)
        {
            JavaScriptObject jso = o as JavaScriptObject;

            if (!typeof(NameValueCollection).IsAssignableFrom(t) || jso == null)
            {
                throw new NotSupportedException();
            }

            NameValueCollection list = (NameValueCollection)Activator.CreateInstance(t);

            if (!jso.ContainsKey("keys") || !jso.ContainsKey("values"))
            {
                throw new ArgumentException("Missing values for 'keys' and 'values'.");
            }

            JavaScriptArray keys   = (JavaScriptArray)jso["keys"];
            JavaScriptArray values = (JavaScriptArray)jso["values"];

            if (keys.Count != values.Count)
            {
                throw new IndexOutOfRangeException("'keys' and 'values' have different length.");
            }

            for (int i = 0; i < keys.Count; i++)
            {
                list.Add(keys[i].ToString(), values[i].ToString());
            }
            return(list);
        }
Beispiel #2
0
        /// <summary>
        /// Converts an IJavaScriptObject into an NET object.
        /// </summary>
        /// <param name="o">The IJavaScriptObject object to convert.</param>
        /// <param name="t"></param>
        /// <returns>Returns a .NET object.</returns>
        public override object Deserialize(IJavaScriptObject o, Type t)
        {
            JavaScriptObject ht = o as JavaScriptObject;

            if (ht == null)
            {
                throw new NotSupportedException();
            }

            if (!ht.ContainsKey("tables") || !(ht["tables"] is JavaScriptArray))
            {
                throw new NotSupportedException();
            }

            JavaScriptArray tables = (JavaScriptArray)ht["tables"];

            DataSet   ds = new DataSet();
            DataTable dt = null;

            foreach (IJavaScriptObject table in tables)
            {
                dt = (DataTable)JavaScriptDeserializer.Deserialize(table, typeof(DataTable));

                if (dt != null)
                {
                    ds.Tables.Add(dt);
                }
            }

            return(ds);
        }
        /// <summary>
        /// Converts an IJavaScriptObject into an NET object.
        /// </summary>
        /// <param name="o">The IJavaScriptObject object to convert.</param>
        /// <param name="t"></param>
        /// <returns>Returns a .NET object.</returns>
        public override object Deserialize(IJavaScriptObject o, Type t)
        {
            JavaScriptObject ht = o as JavaScriptObject;

            if (ht == null)
            {
                throw new NotSupportedException();
            }

            IDictionary d = (IDictionary)Activator.CreateInstance(t);

            ParameterInfo[] p  = t.GetMethod("Add").GetParameters();
            Type            kT = p[0].ParameterType;
            Type            vT = p[1].ParameterType;

            if (ht.ContainsKey("keys") && ht.ContainsKey("values"))
            {
                object key;
                object value;

                JavaScriptArray keys   = ht["keys"] as JavaScriptArray;
                JavaScriptArray values = ht["values"] as JavaScriptArray;

                for (int i = 0; i < keys.Count && i < values.Count; i++)
                {
                    key   = JavaScriptDeserializer.Deserialize(keys[i], kT);
                    value = JavaScriptDeserializer.Deserialize(values[i], vT);

                    d.Add(key, value);
                }
            }
            else if (kT == typeof(string))
            {
                foreach (string key in ht.Keys)
                {
                    object value = JavaScriptDeserializer.Deserialize(ht[key], vT);
                    d.Add(key, value);
                }
            }
            else
            {
                throw new NotSupportedException();
            }

            return(d);
        }
        /// <summary>
        /// Deserializes the custom object.
        /// </summary>
        /// <param name="o">The o.</param>
        /// <param name="type">The type.</param>
        /// <returns></returns>
        internal static object DeserializeCustomObject(JavaScriptObject o, Type type)
        {
            object c = Activator.CreateInstance(type);

            // TODO: is this a security problem?
            // if(o.GetType().GetCustomAttributes(typeof(AjaxClassAttribute), true).Length == 0)
            //	throw new System.Security.SecurityException("Could not create class '" + type.FullName + "' because of missing AjaxClass attribute.");

            MemberInfo[] members = type.GetMembers(BindingFlags.GetField | BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance);
            foreach (MemberInfo memberInfo in members)
            {
                if (memberInfo.MemberType == MemberTypes.Field)
                {
                    if (o.ContainsKey(memberInfo.Name))
                    {
                        FieldInfo fieldInfo = (FieldInfo)memberInfo;

                        fieldInfo.SetValue(c, JavaScriptDeserializer.Deserialize((IJavaScriptObject)o[fieldInfo.Name], fieldInfo.FieldType));
                    }
                }
                else if (memberInfo.MemberType == MemberTypes.Property)
                {
                    if (o.ContainsKey(memberInfo.Name))
                    {
                        PropertyInfo propertyInfo = (PropertyInfo)memberInfo;

                        if (propertyInfo.CanWrite)
                        {
                            propertyInfo.SetValue(c, JavaScriptDeserializer.Deserialize((IJavaScriptObject)o[propertyInfo.Name], propertyInfo.PropertyType), new object[0]);
                        }
                    }
                }
            }

            return(c);
        }
        /// <summary>
        /// Retreives the parameters.
        /// </summary>
        /// <returns></returns>
        public override object[] RetreiveParameters()
        {
            context.Request.ContentEncoding = System.Text.UTF8Encoding.UTF8;

            ParameterInfo[] pi = method.GetParameters();

            object[] args = new object[pi.Length];

            // initialize default values
            for (int i = 0; i < pi.Length; i++)
            {
                args[i] = pi[i].DefaultValue;
            }

            byte[] b = new byte[context.Request.InputStream.Length];

            if (context.Request.InputStream.Read(b, 0, b.Length) == 0)
            {
                return(null);
            }

            StreamReader sr = new StreamReader(new MemoryStream(b), System.Text.UTF8Encoding.UTF8);

            string v = null;

            try
            {
                v = sr.ReadToEnd();
            }
            finally
            {
                sr.Close();
            }

            // If something went wrong or there are no arguments
            // we can return with the empty argument array.

            if (v == null || pi.Length == 0 || v == "{}")
            {
                return(args);
            }

            hashCode = v.GetHashCode();

            // check if we have to decrypt the JSON string.
            if (Utility.Settings != null && Utility.Settings.Security != null)
            {
                v = Utility.Settings.Security.SecurityProvider.Decrypt(v);
            }

            context.Items.Add(Constant.AjaxID + ".JSON", v);

            JavaScriptObject jso = (JavaScriptObject)JavaScriptDeserializer.DeserializeFromJson(v, typeof(JavaScriptObject));

            for (int i = 0; i < pi.Length; i++)
            {
                if (jso.ContainsKey(pi[i].Name))
                {
                    //if(pi[i].ParameterType.IsAssignableFrom(jso[pi[i].Name].GetType()))
                    //{
                    //    args[i] = jso[pi[i].Name];
                    //}
                    //else
                    {
                        args[i] = JavaScriptDeserializer.Deserialize((IJavaScriptObject)jso[pi[i].Name], pi[i].ParameterType);
                    }
                }
            }

            return(args);
        }
        /// <summary>
        /// Converts an IJavaScriptObject into an NET object.
        /// </summary>
        /// <param name="o">The IJavaScriptObject object to convert.</param>
        /// <param name="type">The type to convert the object to.</param>
        /// <returns>Returns a .NET object.</returns>
        public static object Deserialize(IJavaScriptObject o, Type type)
        {
            if (o == null)
            {
                return(null);
            }

            // If the IJavaScriptObject is an JavaScriptObject and we have a key
            // __type we will override the Type that is passed to this method. This
            // will allow us to use implemented classes where the method will use
            // only the interface.

            JavaScriptObject jso = o as JavaScriptObject;

            if (jso != null && jso.ContainsKey("__type"))
            {
                Type t = Type.GetType(jso["__type"].ToString());
                if (type == null || type.IsAssignableFrom(t))
                {
                    type = t;
                }
            }


            JavaScriptConverter c = null;

#if (NET20)
            if (Utility.Settings.DeserializableConverters.TryGetValue(type, out c))
            {
#else
            if (Utility.Settings.DeserializableConverters.ContainsKey(type))
            {
                c = (IJavaScriptConverter)Utility.Settings.DeserializableConverters[type];
#endif
                return(c.Deserialize(o, type));
            }

            object v;
#if (NET20)
            foreach (JavaScriptConverter c2 in Utility.Settings.DeserializableConverters.Values)
            {
                if (c2.TryDeserializeValue(o, type, out v))
                {
                    return(v);
                }
            }
#else
            IEnumerator m = Utility.Settings.DeserializableConverters.Values.GetEnumerator();
            while (m.MoveNext())
            {
                if (((IJavaScriptConverter)m.Current).TryDeserializeValue(o, type, out v))
                {
                    return(v);
                }
            }
#endif


#if (NET20)
            if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable <>))
            {
                //Type n = typeof(Nullable<>);
                //Type constructed = n.MakeGenericType(type.GetGenericArguments()[0]);
                object val  = null;
                Type   tval = type.GetGenericArguments()[0];
                string tmp  = o.ToString();

                if (string.IsNullOrEmpty(tmp) || tmp == "null")
                {
                    return(null);
                }

                object va = Deserialize(o, tval);
                val = Convert.ChangeType(va, tval);
                return(Activator.CreateInstance(type, val));
            }
#endif

            if (typeof(IJavaScriptObject).IsAssignableFrom(type))
            {
                return(o);
            }

            if (o is JavaScriptObject)
            {
                return(DeserializeCustomObject(o as JavaScriptObject, type));
            }

            throw new NotImplementedException("The object of type '" + o.GetType().FullName + "' could not converted to type '" + type + "'.");
        }
Beispiel #7
0
        /// <summary>
        /// Converts an XML document to an IJavaScriptObject (JSON).
        /// <see cref="http://www.xml.com/pub/a/2006/05/31/converting-between-xml-and-json.html?page=1">Stefan Goessner</see>
        ///     <see cref="http://developer.yahoo.com/common/json.html#xml">Yahoo XML JSON</see>
        /// </summary>
        /// <param name="n">The XmlNode to serialize to JSON.</param>
        /// <returns>A IJavaScriptObject.</returns>
        public static IJavaScriptObject GetIJavaScriptObjectFromXmlNode(XmlNode n)
        {
            if (n == null)
            {
                return(null);
            }

            //if (xpath == "" || xpath == "/")
            //    xpath = n.Name;

            System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(@"\w+|\W+", System.Text.RegularExpressions.RegexOptions.Compiled);
            JavaScriptObject o = new JavaScriptObject();

            if (n.NodeType == XmlNodeType.Element)
            {
                for (int i = 0; i < n.Attributes.Count; i++)
                {
                    o.Add("@" + n.Attributes[i].Name, n.Attributes[i].Value);
                }

                if (n.FirstChild != null)                       // element has child nodes
                {
                    int  textChild       = 0;
                    bool hasElementChild = false;

                    for (XmlNode e = n.FirstChild; e != null; e = e.NextSibling)
                    {
                        if (e.NodeType == XmlNodeType.Element)
                        {
                            hasElementChild = true;
                        }
                        if (e.NodeType == XmlNodeType.Text && r.IsMatch(e.InnerText))
                        {
                            textChild++;                                                                                        // non-whitespace text
                        }
                    }

                    if (hasElementChild)
                    {
                        if (textChild < 2)                              // structured element with evtl. a single text node
                        {
                            for (XmlNode e = n.FirstChild; e != null; e = e.NextSibling)
                            {
                                if (e.NodeType == XmlNodeType.Text)
                                {
                                    o.Add("#text", e.InnerText);
                                }
                                else if (o.ContainsKey(e.Name))
                                {
                                    if (o[e.Name] is JavaScriptArray)
                                    {
                                        ((JavaScriptArray)o[e.Name]).Add(GetIJavaScriptObjectFromXmlNode(e));
                                    }
                                    else
                                    {
                                        IJavaScriptObject _o = o[e.Name];
                                        JavaScriptArray   a  = new JavaScriptArray();
                                        a.Add(_o);
                                        a.Add(GetIJavaScriptObjectFromXmlNode(e));
                                        o[e.Name] = a;
                                    }
                                }
                                else
                                {
                                    o.AddInternal(e.Name, GetIJavaScriptObjectFromXmlNode(e));
                                }
                            }
                        }
                    }
                    else if (textChild > 0)
                    {
                        if (n.Attributes.Count == 0)
                        {
                            return(new JavaScriptString(n.InnerText));
                        }
                        else
                        {
                            o.Add("#text", n.InnerText);
                        }
                    }
                }
                if (n.Attributes.Count == 0 && n.FirstChild == null)
                {
                    return(new JavaScriptString(n.InnerText));
                }
            }
            else if (n.NodeType == XmlNodeType.Document)
            {
                return(GetIJavaScriptObjectFromXmlNode(((XmlDocument)n).DocumentElement));
            }
            else
            {
                throw new NotSupportedException("Unhandled node type '" + n.NodeType + "'.");
            }

            return(o);
        }
Beispiel #8
0
        /// <summary>
        /// Converts an IJavaScriptObject into an NET object.
        /// </summary>
        /// <param name="o">The IJavaScriptObject object to convert.</param>
        /// <param name="t"></param>
        /// <returns>Returns a .NET object.</returns>
        public override object Deserialize(IJavaScriptObject o, Type t)
        {
            JavaScriptObject ht = o as JavaScriptObject;

            if (ht == null)
            {
                throw new NotSupportedException();
            }

            if (!ht.ContainsKey("columns") || !(ht["columns"] is JavaScriptArray) ||
                !ht.ContainsKey("columnTypes") || !(ht["columnTypes"] is JavaScriptArray) ||
                !ht.ContainsKey("rows") || !(ht["rows"] is JavaScriptArray))
            {
                throw new NotSupportedException();
            }

            JavaScriptArray columns     = (JavaScriptArray)ht["columns"];
            JavaScriptArray columnTypes = (JavaScriptArray)ht["columnTypes"];
            JavaScriptArray rows        = (JavaScriptArray)ht["rows"];

            if (columns.Count != columnTypes.Count)
            {
                throw new NotSupportedException();
            }

            DataTable        dt  = new DataTable();
            DataRow          row = null;
            Type             colType;
            JavaScriptString columnName;
            JavaScriptString columnType;

            if (ht.ContainsKey("name") && ht["name"] is JavaScriptString)
            {
                dt.TableName = ht["name"].ToString();
            }

            for (int i = 0; i < columns.Count; i++)
            {
                columnName = (JavaScriptString)columns[i];
                columnType = (JavaScriptString)columnTypes[i];

                colType = Type.GetType(columnType, true);
                dt.Columns.Add(columnName, colType);
            }

            JavaScriptArray cols = null;
            object          obj;

            for (int y = 0; y < rows.Count; y++)
            {
                //				if(!(r is JavaScriptArray))
                //					continue;

                cols = (JavaScriptArray)rows[y];
                row  = dt.NewRow();

                for (int i = 0; i < cols.Count; i++)
                {
                    //row[i] = JavaScriptDeserializer.Deserialize((IJavaScriptObject)cols[i], dt.Columns[i].DataType);

                    obj    = JavaScriptDeserializer.Deserialize((IJavaScriptObject)cols[i], dt.Columns[i].DataType);
                    row[i] = (obj == null) ? DBNull.Value : obj;
                }

                dt.Rows.Add(row);
            }

            return(dt);
        }