/// <summary>
        /// Converts a .NET object into a JSON string.
        /// </summary>
        /// <param name="o">The object to convert.</param>
        /// <param name="sb">A StringBuilder object.</param>
        /// <example>
        /// using System;
        /// using System.Text;
        /// using AjaxPro;
        /// namespace Demo
        /// {
        /// public class WebForm1 : System.Web.UI.Page
        /// {
        /// private void Page_Load(object sender, System.EventArgs e)
        /// {
        /// DateTime serverTime = DateTime.Now;
        /// StringBuilder sb = new StringBuilder();
        /// JavaScriptSerializer.Serialize(serverTime, sb);
        /// // sb.ToString() = "new Date(...)";
        /// }
        /// }
        /// }
        /// </example>
        public static void Serialize(object o, StringBuilder sb)
        {
            if (o == null || o is System.DBNull)
            {
                sb.Append("null");
                return;
            }

            IJavaScriptConverter c = null;
            Type type = o.GetType();

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

#if (NET20)
            foreach (IJavaScriptConverter c2 in Utility.Settings.SerializableConverters.Values)
            {
                if (c2.TrySerializeValue(o, type, sb))
                {
                    return;
                }
            }
#else
            IEnumerator m = Utility.Settings.SerializableConverters.Values.GetEnumerator();
            while (m.MoveNext())
            {
                if (((IJavaScriptConverter)m.Current).TrySerializeValue(o, type, sb))
                {
                    sb.ToString();
                    return;
                }
            }
#endif

            try
            {
                SerializeCustomObject(o, sb);
                return;
            }
            catch (StackOverflowException)
            {
                throw new Exception(Constant.AjaxID + " stack overflow exception while trying to serialize type '" + type.Name + "'.");
            }
        }
Exemple #2
0
        /// <summary>
        /// Adds the converter.
        /// </summary>
        /// <param name="settings">The settings.</param>
        /// <param name="converter">The converter.</param>
        /// <param name="replace">if set to <c>true</c> [replace].</param>
        internal static void AddConverter(AjaxSettings settings, IJavaScriptConverter converter, bool replace)
        {
            Type t;

            for (int i = 0; i < converter.SerializableTypes.Length; i++)
            {
                t = converter.SerializableTypes[i];

                if (settings.SerializableConverters.ContainsKey(t))
                {
                    if (replace)
                    {
                        settings.SerializableConverters[t] = converter;
                    }
                    continue;
                }

                settings.SerializableConverters.Add(t, converter);
            }

            for (int i = 0; i < converter.DeserializableTypes.Length; i++)
            {
                t = converter.DeserializableTypes[i];

                if (settings.DeserializableConverters.ContainsKey(t))
                {
                    if (replace)
                    {
                        settings.DeserializableConverters[t] = converter;
                    }
                    continue;
                }

                settings.DeserializableConverters.Add(t, converter);
            }
        }
Exemple #3
0
 public static void RegisterConverterForAjax(IJavaScriptConverter converter)
 {
     Utility.AddConverter(Utility.Settings, converter);
 }
Exemple #4
0
 /// <summary>
 /// Adds the converter.
 /// </summary>
 /// <param name="settings">The settings.</param>
 /// <param name="converter">The converter.</param>
 internal static void AddConverter(AjaxSettings settings, IJavaScriptConverter converter)
 {
     AddConverter(settings, converter, false);
 }
Exemple #5
0
        /// <summary>
        /// Adds the converter.
        /// </summary>
        /// <param name="settings">The settings.</param>
        /// <param name="converter">The converter.</param>
        /// <param name="replace">if set to <c>true</c> [replace].</param>
        internal static void AddConverter(AjaxSettings settings, IJavaScriptConverter converter, bool replace)
        {
            Type t;

            for (int i = 0; i < converter.SerializableTypes.Length; i++)
            {
                t = converter.SerializableTypes[i];

                if (settings.SerializableConverters.ContainsKey(t))
                {
                    if (replace)
                        settings.SerializableConverters[t] = converter;
                    continue;
                }

                settings.SerializableConverters.Add(t, converter);
            }

            for (int i = 0; i < converter.DeserializableTypes.Length; i++)
            {
                t = converter.DeserializableTypes[i];

                if (settings.DeserializableConverters.ContainsKey(t))
                {
                    if (replace)
                        settings.DeserializableConverters[t] = converter;
                    continue;
                }

                settings.DeserializableConverters.Add(t, converter);
            }
        }
Exemple #6
0
 /// <summary>
 /// Adds the converter.
 /// </summary>
 /// <param name="settings">The settings.</param>
 /// <param name="converter">The converter.</param>
 internal static void AddConverter(AjaxSettings settings, IJavaScriptConverter converter)
 {
     AddConverter(settings, converter, false);
 }
Exemple #7
0
 public static void RegisterConverterForAjax(IJavaScriptConverter converter)
 {
     Utility.AddConverter(Utility.Settings, converter);
 }
        /// <summary>
        /// Creates a configuration section handler.
        /// </summary>
        /// <param name="parent"></param>
        /// <param name="configContext">Configuration context object.</param>
        /// <param name="section"></param>
        /// <returns>The created section handler object.</returns>
        public object Create(object parent, object configContext, System.Xml.XmlNode section)
        {
            AjaxSettings settings = new AjaxSettings();

            Utility.AddDefaultConverter(settings);

            foreach (XmlNode n in section.ChildNodes)
            {
#if (!JSONLIB)
                if (n.Name == "coreScript")
                {
                    if (n.InnerText != null && n.InnerText.Length > 0)
                    {
                        settings.ScriptReplacements.Add("core", n.InnerText);
                    }
                }
                else if (n.Name == "scriptReplacements")
                {
                    foreach (XmlNode file in n.SelectNodes("file"))
                    {
                        string name = "";
                        string path = "";

                        if (file.Attributes["name"] != null)
                        {
                            name = file.Attributes["name"].InnerText;
                            if (file.Attributes["path"] != null)
                            {
                                path = file.Attributes["path"].InnerText;
                            }

                            if (settings.ScriptReplacements.ContainsKey(name))
                            {
                                settings.ScriptReplacements[name] = path;
                            }
                            else
                            {
                                settings.ScriptReplacements.Add(name, path);
                            }
                        }
                    }
                }
                else if (n.Name == "urlNamespaceMappings")
                {
                    settings.OnlyAllowTypesInList     = n.SelectSingleNode("@allowListOnly[.='true']") != null;
                    settings.UseAssemblyQualifiedName = n.SelectSingleNode("@useAssemblyQualifiedName[.='true']") != null;

                    XmlNode ns, url;

                    foreach (XmlNode e in n.SelectNodes("add"))
                    {
                        ns  = e.SelectSingleNode("@type");
                        url = e.SelectSingleNode("@path");
#if (NET20)
                        if (ns == null || String.IsNullOrEmpty(ns.InnerText) || url == null || String.IsNullOrEmpty(url.InnerText))
#else
                        if (ns == null || ns.InnerText.Length == 0 || url == null || url.InnerText.Length == 0)
#endif
                        { continue; }

                        if (settings.UrlNamespaceMappings.Contains(url.InnerText))
                        {
                            throw new Exception("Duplicate namespace mapping '" + url.InnerText + "'.");
                        }

                        settings.UrlNamespaceMappings.Add(url.InnerText, ns.InnerText);
                    }
                }
                else if (n.Name == "providers" || n.Name == "provider")
                {
                    foreach (XmlNode p in n.ChildNodes)
                    {
                        if (p.Name == "securityProvider")
                        {
                            if (p.SelectSingleNode("@type") != null)
                            {
                                string securityProviderType = p.SelectSingleNode("@type").InnerText;

                                AjaxSecurity sec = new AjaxSecurity(securityProviderType);

                                if (sec.Init())
                                {
                                    settings.Security = sec;
                                }
                            }
                        }
                        else if (p.Name == "typeJavaScriptProvider")
                        {
                            if (p.SelectSingleNode("@type") != null)
                            {
                                settings.TypeJavaScriptProvider = p.SelectSingleNode("@type").InnerText;
                            }
                        }
                    }
                }
                else if (n.Name == "token")
                {
                    // settings.TokenEnabled = n.SelectSingleNode("@enabled") != null && n.SelectSingleNode("@enabled").InnerText == "true";
                    settings.TokenSitePassword = n.SelectSingleNode("@sitePassword") != null?n.SelectSingleNode("@sitePassword").InnerText : settings.TokenSitePassword;
                }
                else if (n.Name == "debug")
                {
                    if (n.SelectSingleNode("@enabled") != null && n.SelectSingleNode("@enabled").InnerText == "true")
                    {
                        settings.DebugEnabled = true;
                    }
                }
                else if (n.Name == "contentSecurityPolicy")
                {
                    var a = n.SelectSingleNode("@nonce");
                    if (a != null && !string.IsNullOrEmpty(a.InnerText))
                    {
                        // TODO: check if that's a valid nonce
                        settings.ContentSecurityPolicyNonce = a.InnerText;
                    }
                }
                else if (n.Name == "jsonDeserializationCustomTypes")
                {
                    settings.IsCustomTypesDeserializationDisabled = n.Attributes["default"] == null || n.Attributes["default"].InnerText.ToLower() != "allow";

                    foreach (XmlNode sn in n.ChildNodes)
                    {
                        switch (sn.Name)
                        {
                        case "allow":
                            settings.JsonDeserializationCustomTypesAllowed.Add(sn.InnerText);
                            break;

                        case "deny":
                            settings.JsonDeserializationCustomTypesDenied.Add(sn.InnerText);
                            break;
                        }
                    }
                }
                else if (n.Name == "oldStyle" || n.Name == "configuration")
                {
                    foreach (XmlNode sn in n.ChildNodes)
                    {
                        switch (sn.Name)
                        {
                        case "useSimpleObjectNaming":
                            settings.UseSimpleObjectNaming = true;
                            break;

                        default:
                            settings.OldStyle.Add(sn.Name);
                            break;
                        }
                    }
                }
                else
#endif
                if (n.Name == "jsonConverters")
                {
                    if (n.SelectSingleNode("@includeTypeProperty") != null && n.SelectSingleNode("@includeTypeProperty").InnerText == "true")
                    {
                        settings.IncludeTypeProperty = true;
                    }

                    XmlNodeList jsonConverters = n.SelectNodes("add");

                    foreach (XmlNode j in jsonConverters)
                    {
                        XmlNode t = j.SelectSingleNode("@type");

                        if (t == null)
                        {
                            continue;
                        }

                        Type type = Type.GetType(t.InnerText);

                        if (type == null)
                        {
                            // throw new ArgumentException("Could not find type " + t.InnerText + ".");
                            continue;
                        }

                        if (!typeof(IJavaScriptConverter).IsAssignableFrom(type))
                        {
                            // throw new ArgumentException("Type " + t.InnerText + " does not inherit from JavaScriptObjectConverter.");
                            continue;
                        }

                        StringDictionary d = new StringDictionary();
                        foreach (XmlAttribute a in j.Attributes)
                        {
                            if (d.ContainsKey(a.Name))
                            {
                                continue;
                            }
                            d.Add(a.Name, a.Value);
                        }

                        IJavaScriptConverter c = (IJavaScriptConverter)Activator.CreateInstance(type);
                        c.Initialize(d);

                        Utility.AddConverter(settings, c, true);
                    }


                    jsonConverters = n.SelectNodes("remove");

                    foreach (XmlNode j in jsonConverters)
                    {
                        XmlNode t = j.SelectSingleNode("@type");

                        if (t == null)
                        {
                            continue;
                        }

                        Type type = Type.GetType(t.InnerText);

                        if (type == null)
                        {
                            // throw new ArgumentException("Could not find type " + t.InnerText + ".");
                            continue;
                        }

                        Utility.RemoveConverter(settings, type);
                    }
                }
            }

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


            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 + "'.");
        }