Ejemplo n.º 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 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);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Converts an JSON string into an NET object.
        /// </summary>
        /// <param name="json">The JSON string representation.</param>
        /// <param name="type">The type to convert the string to.</param>
        /// <returns>Returns a .NET object.</returns>
        /// <example>
        /// using System;
        /// using AjaxNet;
        /// namespace Demo
        /// {
        ///		public class WebForm1 : System.Web.UI.Page
        ///		{
        ///			private void Page_Load(object sender, System.EventArgs e)
        ///			{
        ///				string json = "[1,2,3,4,5,6]";
        ///				object o = JavaScriptDeserializer.Deserialize(json, typeof(int[]);
        ///				if(o != null)
        ///				{
        ///					foreach(int i in (int[])o)
        ///					{
        ///						Response.Write(i.ToString());
        ///					}
        ///				}
        ///			}
        ///		}
        /// }
        /// </example>
        public static object DeserializeFromJson(string json, Type type)
        {
            JSONParser        p = new JSONParser();
            IJavaScriptObject o = p.GetJSONObject(json);

            return(JavaScriptDeserializer.Deserialize(o, type));
        }
Ejemplo n.º 3
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)
        {
#if (!JSONLIB)
            //if (!Utility.Settings.OldStyle.Contains("allowNumberBooleanAsString"))
#endif
            {
                if (o is JavaScriptNumber)
                {
                    return(JavaScriptDeserializer.Deserialize(o, typeof(Int64)));
                }
                else if (o is JavaScriptBoolean)
                {
                    return(JavaScriptDeserializer.Deserialize(o, typeof(Boolean)));
                }
            }

            if (t == typeof(char))
            {
                string s = o.ToString();

                if (s.Length == 0)
                {
                    return('\0');
                }
                return(s[0]);
            }

            return(o.ToString());
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Retreives the parameters.
        /// </summary>
        /// <returns></returns>
        public override object[] RetreiveParameters()
        {
            ParameterInfo[] pis = method.GetParameters();

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

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

            List <string> keys = new List <string>();

            foreach (string key in context.Request.QueryString.Keys)
            {
                keys.Add(key);
            }
            foreach (string key in context.Request.Form.Keys)
            {
                if (!keys.Contains(key))
                {
                    keys.Add(key);
                }
            }
            //keys.Sort();

            Dictionary <string, string> values = new Dictionary <string, string>();

            foreach (string key in keys)
            {
                values.Add(key, context.Request.Params[key]);
            }

            for (int i = 0; i < pis.Length; i++)
            {
                IJavaScriptObject jso = Process(pis[i].Name, values);
                if (jso != null)
                {
                    args[i] = JavaScriptDeserializer.Deserialize(jso, pis[i].ParameterType);
                    if (hashCode == 0)
                    {
                        hashCode = jso.Value.GetHashCode();
                    }
                    else
                    {
                        hashCode ^= jso.Value.GetHashCode();
                    }
                }
            }

            return(args);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Retreives the parameters.
        /// </summary>
        /// <returns></returns>
        public override object[] RetreiveParameters()
        {
            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;
            }

            string v = context.Request["data"];

            // 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);
            }

            if (context.Request.ContentEncoding != System.Text.Encoding.UTF8)
            {
                v = System.Text.Encoding.UTF8.GetString(context.Request.ContentEncoding.GetBytes(v));
            }

            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 (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);
        }
Ejemplo n.º 6
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)
        {
            //return Enum.Parse(type, o.ToString());

            object enumValue = JavaScriptDeserializer.Deserialize(o, Enum.GetUnderlyingType(t));

            if (!Enum.IsDefined(t, enumValue))
            {
                throw new ArgumentException("Invalid value for enum of type '" + t.ToString() + "'.", "o");
            }

            return(Enum.ToObject(t, enumValue));
        }
Ejemplo n.º 7
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)
        {
            JavaScriptArray list = o as JavaScriptArray;

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

            if (t.IsArray)
            {
                Type  type = Type.GetType(t.AssemblyQualifiedName.Replace("[]", ""));
                Array a    = Array.CreateInstance(type, (list != null ? list.Count : 0));

                try
                {
                    if (list != null)
                    {
                        for (int i = 0; i < list.Count; i++)
                        {
                            object v = JavaScriptDeserializer.Deserialize(list[i], type);
                            a.SetValue(v, i);
                        }
                    }
                }
                catch (System.InvalidCastException iex)
                {
                    throw new InvalidCastException("Array ('" + t.Name + "') could not be filled with value of type '" + type.Name + "'.", iex);
                }

                return(a);
            }

            if (!typeof(IList).IsAssignableFrom(t) || !(o is JavaScriptArray))
            {
                throw new NotSupportedException();
            }

            IList l = (IList)Activator.CreateInstance(t);

            MethodInfo    mi = t.GetMethod("Add");
            ParameterInfo pi = mi.GetParameters()[0];

            for (int i = 0; i < list.Count; i++)
            {
                l.Add(JavaScriptDeserializer.Deserialize(list[i], pi.ParameterType));
            }

            return(l);
        }
Ejemplo n.º 8
0
        public static object BuildObjectFrom(HttpRequest request, string parameterName, Type parameterType)
        {
            if (request == null || parameterName == null || parameterType == null)
            {
                throw new ArgumentNullException();
            }
            List <string> keys = new List <string>();

            foreach (string key in request.QueryString.Keys)
            {
                if (key == parameterName ||
                    key.StartsWith(parameterName + ".") ||
                    key.StartsWith(parameterName + "["))
                {
                    keys.Add(key);
                }
            }
            foreach (string key in request.Form.Keys)
            {
                if (key == parameterName ||
                    key.StartsWith(parameterName + ".") ||
                    key.StartsWith(parameterName + "["))
                {
                    if (!keys.Contains(key))
                    {
                        keys.Add(key);
                    }
                }
            }
            //keys.Sort();

            Dictionary <string, string> values = new Dictionary <string, string>();

            foreach (string key in keys)
            {
                values.Add(key, request.Params[key]);
            }

            IJavaScriptObject jso = Process(parameterName, values);

            if (jso == null)
            {
                return(null);
            }
            else
            {
                return(JavaScriptDeserializer.Deserialize(jso, parameterType));
            }
        }
Ejemplo n.º 9
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();
            }

            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);
        }
Ejemplo n.º 10
0
        /// <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);
        }
Ejemplo n.º 11
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)
        {
            if (o is JavaScriptSource)
            {
                // new Date(Date.UTC(2006,6,9,5,36,18,875))

                string s = o.ToString();

                if (s.StartsWith("new Date(Date.UTC(") && s.EndsWith("))"))                 //AjaxPro format
                {
                    s = s.Substring(18, s.Length - 20);

                    //Regex r = new Regex(@"(\d{4}),(\d{1,2}),(\d{1,2}),(\d{1,2}),(\d{1,2}),(\d{1,2}),(\d{1,3})", RegexOptions.Compiled);
                    //Match m = r.Match(s);

                    //if (m.Groups.Count != 8)
                    //    throw new NotSupportedException();

                    //int Year = int.Parse(m.Groups[1].Value);
                    //int Month = int.Parse(m.Groups[2].Value) + 1;
                    //int Day = int.Parse(m.Groups[3].Value);
                    //int Hour = int.Parse(m.Groups[4].Value);
                    //int Minute = int.Parse(m.Groups[5].Value);
                    //int Second = int.Parse(m.Groups[6].Value);
                    //int Millisecond = int.Parse(m.Groups[7].Value);

                    //DateTime d = new DateTime(Year, Month, Day, Hour, Minute, Second, Millisecond);

                    string[] p = s.Split(',');
                    return(new DateTime(int.Parse(p[0]), int.Parse(p[1]) + 1, int.Parse(p[2]), int.Parse(p[3]), int.Parse(p[4]), int.Parse(p[5]), int.Parse(p[6])).AddMinutes(UtcOffsetMinutes));
                }
                else if (s.StartsWith("new Date(") && s.EndsWith(")"))
                {
                    long nanosecs = long.Parse(s.Substring(9, s.Length - 10)) * 10000;
#if (NET20)
                    nanosecs += new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).Ticks;
                    DateTime d1 = new DateTime(nanosecs, DateTimeKind.Utc);
#else
                    nanosecs += new DateTime(1970, 1, 1, 0, 0, 0, 0).Ticks;
                    DateTime d1 = new DateTime(nanosecs);
#endif
                    return(d1.ToLocalTime());
                }
            }
            else if (o is JavaScriptString)
            {
                string d = o.ToString();

                if (d.StartsWith("/Date(") && d.EndsWith(")/"))
                // if (d.Length >= 9 && d.Substring(0, 6) == "/Date(" && d.Substring(d.Length -2) == ")/")
                {
                    DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, new System.Globalization.GregorianCalendar(), System.DateTimeKind.Utc);

                    return(new DateTime(long.Parse(d.Substring(6, d.Length - 6 - 2)) * TimeSpan.TicksPerMillisecond, DateTimeKind.Utc)
                           .AddTicks(Epoch.Ticks).ToLocalTime());
                }

                DateTime d2;

                if (DateTime.TryParseExact(o.ToString(),
                                           System.Globalization.DateTimeFormatInfo.InvariantInfo.UniversalSortableDateTimePattern,
                                           System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AllowWhiteSpaces, out d2
                                           ) == true)
                {
                    return(d2.ToLocalTime());
                }

                try
                {
                    DateTime d4 = DateTime.Parse(o.ToString());

                    return(d4);
                }
                catch (FormatException)
                {
                }
            }

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

            int Year2        = (int)JavaScriptDeserializer.Deserialize(ht["Year"], typeof(int));
            int Month2       = (int)JavaScriptDeserializer.Deserialize(ht["Month"], typeof(int));
            int Day2         = (int)JavaScriptDeserializer.Deserialize(ht["Day"], typeof(int));
            int Hour2        = (int)JavaScriptDeserializer.Deserialize(ht["Hour"], typeof(int));
            int Minute2      = (int)JavaScriptDeserializer.Deserialize(ht["Minute"], typeof(int));
            int Second2      = (int)JavaScriptDeserializer.Deserialize(ht["Second"], typeof(int));
            int Millisecond2 = (int)JavaScriptDeserializer.Deserialize(ht["Millisecond"], typeof(int));

            DateTime d5 = new DateTime(Year2, Month2, Day2, Hour2, Minute2, Second2, Millisecond2);
            return(d5);
        }
Ejemplo n.º 12
0
        /// <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);
        }
Ejemplo n.º 13
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);
        }