- using System;
- using System.Text;
- using System.Data;
- namespace AjaxPro
- {
- /// <summary>
- /// Provides methods to serialize and deserialize a DataSet object.
- /// </summary>
- public class DataSetConverter : IJavaScriptConverter
- {
- private string clientType = "Ajax.Web.DataSet";
- public DataSetConverter() : base()
- {
- }
- public override string GetClientScript()
- {
- return @"addNamespace(""Ajax.Web"");
- Ajax.Web.DataSet = function(tables) {
- this.__type = ""System.Data.DataSet, System.Data"";
- this.Tables = new Array();
- this.addTable = function(table) {
- this.Tables.push(table);
- }
- if(tables != null) {
- for(var i=0; i<tables.length; i++) {
- this.addTable(tables[i]);
- }
- }
- }
- ";
- }
- public override object Deserialize(IJavaScriptObject o, Type t)
- {
- if(!(o is JavaScriptObject))
- throw new NotSupportedException();
- JavaScriptObject ht = (JavaScriptObject)o;
- if(!ht.Contains("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;
- }
- public override string Serialize(object o)
- {
- if(!(o is DataSet))
- throw new NotSupportedException();
- StringBuilder sb = new StringBuilder();
- DataSet ds = (DataSet)o;
- bool b = true;
- sb.Append("new ");
- sb.Append(clientType);
- sb.Append("([");
- foreach(DataTable dt in ds.Tables)
- {
- if(b){ b = false; }
- else{ sb.Append(","); }
- sb.Append(JavaScriptSerializer.Serialize(dt));
- }
- sb.Append("])");
- return sb.ToString();
- }
- public override Type[] SerializableTypes
- {
- get
- {
- return new Type[]{typeof(DataSet)};
- }
- }
- public override Type[] DeserializableTypes
- {
- get
- {
- return new Type[]{typeof(DataSet)};
- }
- }
- }
- }