Ejemplo n.º 1
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.Contains(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.º 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.Contains("Columns") || !(ht["Columns"] is JavaScriptArray) ||
                !ht.Contains("Rows") || !(ht["Rows"] is JavaScriptArray))
            {
                throw new NotSupportedException();
            }

            JavaScriptArray columns = (JavaScriptArray)ht["Columns"];
            JavaScriptArray rows    = (JavaScriptArray)ht["Rows"];

            DataTable       dt  = new DataTable();
            DataRow         row = null;
            Type            colType;
            JavaScriptArray column;

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

            for (int i = 0; i < columns.Count; i++)
            {
                column = (JavaScriptArray)columns[i];

                colType = Type.GetType(column[1].ToString(), true);
                JavaScriptDeserializer.ThrowExceptionIfNotCustomTypeDeserializationAllowed(colType);

                dt.Columns.Add(column[0].ToString(), 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);
        }
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)
        {
            JavaScriptObject ht = o as JavaScriptObject;

            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("))"))
                {
                    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(Utility.Settings.OldStyle.Contains("noUtcTime") ? d1 : d1.AddMinutes(UtcOffsetMinutes));                      // TimeZone.CurrentTimeZone.GetUtcOffset(d1).TotalMinutes);
                }
            }
            else if (o is JavaScriptString)
            {
                string d = o.ToString();

#if (NET20)
                if (d.StartsWith("/Date(") && d.EndsWith(")/"))
#else
                if (d.Length >= 9 && d.Substring(0, 6) == "/Date(" && d.Substring(d.Length - 2) == ")/")
#endif
                {
                    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));
                }

#if (NET20)
                DateTime d2;

                if (DateTime.TryParseExact(o.ToString(),
                                           System.Globalization.DateTimeFormatInfo.InvariantInfo.UniversalSortableDateTimePattern,
                                           System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AllowWhiteSpaces, out d2
                                           ) == true)
                {
                    return(Utility.Settings.OldStyle.Contains("noUtcTime") ? d2 : d2.AddMinutes(UtcOffsetMinutes));                      // TimeZone.CurrentTimeZone.GetUtcOffset(d2).TotalMinutes);
                }
#else
                try
                {
                    DateTime d4 = DateTime.ParseExact(o.ToString(),
                                                      System.Globalization.DateTimeFormatInfo.InvariantInfo.UniversalSortableDateTimePattern,
                                                      System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AllowWhiteSpaces
                                                      );

                    return(Utility.Settings.OldStyle.Contains("noUtcTime") ? d4 : d4.AddMinutes(UtcOffsetMinutes));                      // TimeZone.CurrentTimeZone.GetUtcOffset(d4).TotalMinutes);
                }
                catch (FormatException)
                {
                }
#endif
            }


            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(Utility.Settings.OldStyle.Contains("noUtcTime") ? d5 : d5.AddMinutes(UtcOffsetMinutes));              // TimeZone.CurrentTimeZone.GetUtcOffset(d3).TotalMinutes);
        }
        /// <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.Contains("__type"))
            {
                Type t = Type.GetType(jso["__type"].ToString());
                if (type == null || type.IsAssignableFrom(t))
                {
                    type = t;
                    ThrowExceptionIfNotCustomTypeDeserializationAllowed(type);
                }
            }

            IJavaScriptConverter 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 (IJavaScriptConverter 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]);

                Type   tval = type.GetGenericArguments()[0];
                object va   = Deserialize(o, tval);
                object 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 + "'.");
        }
Ejemplo n.º 5
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, new JavaScriptString(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", new JavaScriptString(e.InnerText));
                                }
                                else if (o.Contains(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.Add(e.Name, GetIJavaScriptObjectFromXmlNode(e));
                                }
                            }
                        }
                    }
                    else if (textChild > 0)
                    {
                        if (n.Attributes.Count == 0)
                        {
                            return(new JavaScriptString(n.InnerText));
                        }
                        else
                        {
                            o.Add("#text", new JavaScriptString(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);
        }