m2d-the blogger
"m2d-the blogger" is not for discuss about colonialism,feudalism blah blah blah...... Its about entertaining myself by discussing the things around me... :)
Thursday, June 14, 2012
Thursday, March 15, 2012
Software Programmer...
This post is inspired by a question “What habits made you a better programmer”. All the habits described below stem from one realization: I’m too stupid to write bug free code so I need ways to compensate for my inevitable human fallibility.
Code reviews
I welcome code reviews because a second pair of eyes might spot mistakes I’ve made. Some people can’t stand their code being criticized. I avoid bruised ego by assuming from the start that I’m too stupid to write correct code.
Using good tools
I seek out and use tools that help me find bugs automatically and tools that help me understand my code better. Those tools include:
static code checkers like clang analyzer or cppcheck or pychecker
Valgrind
memory and cpu profilers
debuggers
Source Insight (a text editor)
Automated testing and continuous builds
Continuous build quickly alerts to mistakes that break the build. Automated tests (unit tests, system tests) increase my confidence in the correctness of the code and catch mistakes that cause regressions.
Stepping through all new code in the debugger
I see a lot of macho anti-debugger posturing. The reasoning is: good debuggers make it too easy to fix problems which makes you a sloppier programmer. But this reasoning applies to unit tests as well (although I don’t see anyone criticizing unit tests for that reason). Stepping through newly written code in the debugger to double-check that it behaves the way I expect is just another way to compensate for the inevitability of writing buggy code.
Avoiding complexity
Unnecessary, productivity sapping complexity is something that no one would defend but popularity of C++ or boost shows that a definition of unnecessary complexity is different for different people. My bar for calling something complex is lower that many. I stay away from complexity, both self-inflicted (like trying to be too clever when implementing something, using multithreading when it’s not absolutely necessary) or inflicted by the tool (e.g. advanced features of C++).
Diagnostic code built into apps
I add diagnostics to my code. Logging, asserts in debug builds, crash dump submission to my site for analyzing crashes that happen in the wild. They all help to figure out the inevitable problems that you don’t see in testing on your machine but happen on user’s computers due to different configurations.
Writing readable code
No one has writing unreadable code as a goal but it does happen because writing readable code is harder and requires more care and attention that just writing some code that works. Readable code is important because I know that bugs will happen despite my best efforts to prevent it. To fix them I will have to read my own code long after I wrote it. Therefore I try to make my code as readable as possible for my future self. The specific techniques involve:
balanced commenting. Not too much (so that it doesn’t detract from the code itself) but also not too little so that non-obvious decisions that are not captured in the code are explained.
no cryptic names for variables or functions
no long functions with complex logic
taking the time to make the code look consistent
Re-use high-quality code
It’s much better if other people sweat writing code and fixing bugs.I look for high quality, reputable code and use it whenever I can e.g. I will use SQLite rather than writing my own persistence layer.
Am i Selfish !
5 Characteristics And Traits Of Selfish People
Many a times we come across people who are hard to forget. Well, not always because they are helpful or bequeath us with some wonderful experiences, but sometimes because they give us unforgettable awful experiences with their utterly bad behavior and selfish characteristics.
Though, we hardly expect everybody to be good and helpful to us, we don’t even expect that people use us for their benefits and behave in a manner to make us feel low or worthless. We don’t expect that people should help us in return for everything we do for them, but we do expect that people would at least notice and weigh our efforts made to help them and not just take our efforts as granted.
Despite this, we still come across people who are mean, arrogant, egotistical and selfish. Encounters with such people leave us feeling hurtful and used to a great extent. Moreover, if one is a sensitive person with a soft heart, then such associations might give them hard-to-forget, distressing experiences. One or two such experiences would surely leave us flabbergasted and we would wish to stay away from such people in the future.
5 Characteristics And Traits Of Selfish People
Though it is not easy to recognize a selfish person immediately, they possess some particular traits and some peculiar characteristics. We can keep ourselves off-hook if we know their baiting traits.
· All selfish people display a very uncaring attitude and a strong “Me first” trait.
A very peculiar and common trait which all selfish and conceited people possess is that they always put themselves and their needs on the forefront. They only give heed to their priorities, their goals and in the process would not think of anyone else, not even about those who might be really needy than them.
When it comes to getting their needs met and their work done, they would turn a deaf ear to the necessities of others. Such selfish people do not believe in the “Live and Let Live“ philosophy, constantly putting their own needs and desires first, they just live for themselves.
A selfish person would view others only as a means to get what they want. They have a have tunnel vision which starts from and leads to themselves and their personal needs alone.
· Another trait which selfish and conceited people show is being manipulative, scheming and plotting most of the times.
This trait arises from the fact that selfish people are driven by the fear of loss of control. They therefore become very manipulative and scheming. They tend to control everything by maligning someone’s reputation or by misrepresenting things.
Selfish people have a great inherent desire to control situations and people and are unwilling to reach compromises with others. To get their own way they would down cast others and debase anybody’s reputation.
· Another conspicuous trait which all conceited and selfish people display is of being calculative and accumulators.
Oscar Wilde, the Irish writer, poet and prominent aesthete, has expressed this demeaning selfish trait in such beautiful words, “There are many things that we would throw away if we were not afraid that others might pick them up.”
This selfish characteristic gives people a grave tendency to hold and hoard things to themselves.
It becomes difficult for such people to part with even simple things like their time and efforts, leave aside important things like money. They would hoard all the resources to themselves and would not share it with anyone even if those resources would go wasted and depleted.
They would never think of sacrificing anything for anybody and in case they do it some time they would expect a lot in return. Insecurity might be the reason behind this base characteristic the selfish people display. They feel it is their right to receive from others but never feel obliged to return anything. Selfish people behave in this manner because they don’t know how to balance giving with taking.
· Low self esteem is another characteristic displayed by selfish people that gives them a negative outlook towards life and making them contemptuous of others in general.
This negative trait towards everything makes them bad team players as they always try to pull down others with their remarks, actions or suggestions.
They find it hard to motivate and inspire people because they themselves lack motivation and the drive to look ahead in life. This characteristic makes them unpopular in a team and a misfit at group tasks.
· A selfish person is highly self centered and self obsessed.
This trait makes them see or hear no one else. They become bad listeners and give little or no consideration to what others have to say. They are inconsiderate and have little or no room for compassion. They would cut off conversations and bring the focus on themselves.
It becomes their earnest desire to be seen and heard more than anyone else making them oblivious to the opinions, suggestions and advices of others. All the conversations they indulge in pertain and turn back to themselves.
Looking at the traits and characteristics selfish people possess, one thing becomes obvious that selfish people do not need your contempt. You surely have to keep yourself shielded from their negativist traits but you don’t need to run from them.
All of us are selfish to some extent, but when the traits and characteristics go beyond control they make us selfish down to the core. Selfish people are ridiculed and downcast by the society in general.
A big non-selfish and selfless trait would be to understand such people and help them out of their selfishness and greedy attitude by accepting their presence, although cautiously.
Of course be careful not to fall in the trap of their cagey attitude, but by not ignoring them and remaining unfazed and unaffected by their damaging, detrimental and calculating behavior, you might help a selfish person understand the value of selflessness. You never know, how greatly your selfless approach can help a selfish person reform into a kind, loving and unassuming soul.
The thought is so rightly put forth by James Allen, the philosophical writer, “The selfishness must be discovered and understood before it can be removed. It is powerless to remove itself, neither will it pass away of itself. Darkness ceases only when light is introduced; So ignorance can only be dispersed by Knowledge; Selfishness by Love.”
Thursday, February 10, 2011
Dataset, Datatable to Json
If you break a Datatable down it is really only a List of Dictionary objects so that’s how we’ll approach this problem. This is compatible with .NET 2.0 and above, with the Ajax installed.
I’d like to acknowledge RichardD for the idea.
Below is the solution.
using System.Collections.Generic;
using System.Data;
public static class JsonMethods
{
private static List
RowsToDictionary(DataTable table)
{
List
new List
foreach (DataRow dr in table.Rows)
{
Dictionary
for (int i = 0; i < table.Columns.Count; i++)
{
drow.Add(table.Columns[i].ColumnName, dr[i]);
}
objs.Add(drow);
}
return objs;
}
public static Dictionary
{
Dictionary
d.Add(table.TableName, RowsToDictionary(table));
return d;
}
public static Dictionary
{
Dictionary
foreach (DataTable table in data.Tables)
{
d.Add(table.TableName, RowsToDictionary(table));
}
return d;
}
}
The static class JsonMethods exposes two public static methods and a private method. The public method ToJson() takes either a Dataset or a Datatable, and returns a Dictionary
This method iterates through all the rows creating a dictionary entry for each column in the row using the column name as the key and storing the data value into the object. It then adds the Dictionary object to a List of Dictionary Objects and returns this to the ToJson() method. This Dictionary list is then added to another Dictionary object using the table name as the key. We’ll see how this all works together soon.
Lets have a look at the code behind now.
[System.Web.Script.Services.ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[System.Web.Services.WebMethod]
public static Dictionary
{
string sql = "select user_name, active_indicator, create_date from users";
string connString = "database=db; server=localhost; user id=sa;";
return JsonMethods.ToJson(GetDataTable(sql, connString));
}
private static DataTable GetDataTable(string sql, string connString)
{
using (SqlConnection myConnection = new SqlConnection(connString))
{
using (SqlCommand myCommand = new SqlCommand(sql, myConnection))
{
myConnection.Open();
using (SqlDataReader myReader = myCommand.ExecuteReader())
{
DataTable myTable = new DataTable();
myTable.TableName = "mydt";
myTable.Load(myReader);
myConnection.Close();
return myTable;
}
}
}
}
So what I have above is two static methods. One is GetTable which is the one we will access from the client. The other is a generic method for loading a results set into a Datatable. Note how I have set the TableName property. You will see why soon.
So using the jMsAjax plugin as below will return the following JSON object.
$.jmsajax({
type: "POST",
url: "Default.aspx",
method: "getTable",
data: {},
dataType: "msjson",
success: function(data) {
$(outputDT(data.mydt)).appendTo("body");
}
});
Results (data):
{"mydt":{"user_name":"000001","active_indicator":"Y","create_date":"\/Date(1170892765197)\/"}, {"user_name":"000002","active_indicator":"Y","create_date":"\/Date(1170892765197)\/"}]}
In the resulting data, the table name is the key to referencing the array of values. In this case we use ‘mydt’ as the key. In the success function on the client request you may also notice an outputDT function. This is a little helper function which takes a JSON Datatable and returns a the results in a table. This is very useful for debugging. Here is the client side code.
function outputDT(dataTable)
{
var headers = [];
var rows = [];
headers.push("
for (var name in dataTable[0])
headers.push("
headers.push("
for (var row in dataTable)
{
rows.push("
for (var name in dataTable[row])
{
rows.push("
rows.push(dataTable[row][name]);
rows.push("
}
rows.push("
}
var top = "
return top + headers.join("") + rows.join("") + bottom;
}
So as you can see, its now very easy to return a Datatable or Dataset as a JSON object ready for use on the client.
Hope this is as useful for you as it is for me.
Cheers,
shareef Mohd
9633265407
For More Visit:
http://www.bramstein.com/projects/xsltjson/
Wednesday, February 9, 2011
Converting Data Table / Dataset Into JSON String
JSON (Java Script Object Notation), is a light weight, easily understandable to read and write string. It is also easily parse-able by machine.
JSON is introduced on two structues
A collection (key/value pair)
And ordered list of values.
I have not covered this topic in detail. Detailed analysis is stated on http://www.json.org/.
I am presenting a helper function (in C#) for developers for fast parsing on datatable / dataset into JSON String, and access it on client-side.
public static string GetJSONString(DataTable Dt)
{
string[] StrDc = new string[Dt.Columns.Count];
string HeadStr = string.Empty;
for (int i = 0; i < Dt.Columns.Count; i++)
{
StrDc[i] = Dt.Columns[i].Caption;
HeadStr += "\"" + StrDc[i] + "\" : \"" + StrDc[i] + i.ToString() + "¾" + "\",";
}
HeadStr = HeadStr.Substring(0, HeadStr.Length - 1);
StringBuilder Sb = new StringBuilder();
Sb.Append("{\"" + Dt.TableName + "\" : [");
for (int i = 0; i < Dt.Rows.Count; i++)
{
string TempStr = HeadStr;
Sb.Append("{");
for (int j = 0; j < Dt.Columns.Count; j++)
{
TempStr = TempStr.Replace(Dt.Columns[j] + j.ToString() + "¾", Dt.Rows[i][j].ToString());
}
Sb.Append(TempStr + "},");
}
Sb = new StringBuilder(Sb.ToString().Substring(0, Sb.ToString().Length - 1));
Sb.Append("]}");
return Sb.ToString();
}
Here, Dt is the datatable, and it returns JSON formatted string.
For detailed porcedure on how to access this string on client side, please refer to this link Exposing Webservices to Client-Side because I don't like to do task repetition.
Please donot forget to convert to JSON string to JSON Object using
var JObject = eval('(' + JSONString + ');');
in Javascript JObject have all characteristics of JSON object, through which you can Use JObject by iterrating or what so ever.
e.g., you can use your JObject as
for(var i = 0; i < JObject .Employees.length; i++)
{
var val1 = JObject.Employees[i].EmployeeID;
var val2 = JObject.Employees[i].NationalIDNumber;
var val3 = JObject.Employees[i].Title;
var val4 = JObject.Employees[i].BirthDate;
var val5 = JObject .Employees[i].HireDate ;
}
Please note that I am querieng data from AdventurWorksDB SQL Sample Database (Table: Employee).
I hope this article will be helpful for you.
Any Questions / Queries ??
Regards,
SHAREEF MOHD
JSON SERIALIZATION
DataTable JSON Serialization in JSON.NET and JavaScriptSerializer
I've been thinking about replacing the JSON serializer in my internal codebase for some time and finally put a little effort into allowing JSON.NET from James Newton King to be plugged into my Ajax framework as a replaceable engine. My own parser has served me well, but JSON.NET is a much cleaner design and more flexible especially when dealing with extensibility. There are also a few nice features like the ability to pretty-format the generated JSON for debugging purposes which is immensely helpful when sending data to the client during development.
Although I'm keeping my original parser class (including original basic functionality) JSON.NET can now be optionally plugged in. So why not just replace the parser altogether? As it turns out I've been experimenting with different JSON serializer/deserializers and being able to keep a 'high level' wrapper object into which each of these parsers can be plugged into has been a great time saver as the interface that various application components use doesn't change one bit which is nice indeed.
Anyway, here's the basic code to provide JSON encoding and deserialization in a simple wrapper functions:
public string Serialize(object value)
{
Type type = value.GetType();
Newtonsoft.Json.JsonSerializer json = new Newtonsoft.Json.JsonSerializer();
json.NullValueHandling = NullValueHandling.Ignore;
json.ObjectCreationHandling = Newtonsoft.Json.ObjectCreationHandling.Replace;
json.MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore;
json.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
if (type == typeof(DataRow))
json.Converters.Add(new DataRowConverter());
else if(type == typeof(DataTable))
json.Converters.Add(new DataTableConverter());
else if (type == typeof(DataSet))
json.Converters.Add(new DataSetConverter());
StringWriter sw = new StringWriter();
Newtonsoft.Json.JsonTextWriter writer = new JsonTextWriter(sw);
if (this.FormatJsonOutput)
writer.Formatting = Formatting.Indented;
else
writer.Formatting = Formatting.None;
writer.QuoteChar = '"';
json.Serialize(writer, value);
string output = sw.ToString();
writer.Close();
sw.Close();
return output;
}
public object Deserialize(string jsonText, Type valueType)
{
Newtonsoft.Json.JsonSerializer json = new Newtonsoft.Json.JsonSerializer();
json.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
json.ObjectCreationHandling = Newtonsoft.Json.ObjectCreationHandling.Replace;
json.MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore;
json.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
StringReader sr = new StringReader(jsonText);
Newtonsoft.Json.JsonTextReader reader = new JsonTextReader(sr);
object result = json.Deserialize(reader, valueType);
reader.Close();
return result;
}
One of the nice things about the JSON.NET parser is that there are a tons of configuration options that allow you to customize how JSON parsing occurs. You can see some of the options above for things like null value handling and managing how deep recursive loops should be handled for example.
JSON.NET also has a simplified JavaScriptConvert class that has much simpler serialization and deserialization methods, but this wrapper doesn't have access to the configuration options, so creating a custom wrapper that does exactly what I need certainly helps. As you can see above the parser has a ton of control over how many parsing aspects are handled which is really cool.
The really nice thing though - and the thing that really is missing in my parser - is extensibility. You can create custom Converters that can be plugged into the parsing pipeline to serialize and optionally deserialize custom types. Any JSON parser is likely to do well with most common types, but there may also be custom types or structures that are not supported or not well supported. For example, the ADO.NET objects, or a less obvious problem of how IDictionary types are handled (JSON.NET only supports string keys and then only those that result in valid JavaScript property/map names).
Luckily you can create your own converters, which is a common way of extensibility. The ASP.NET JavaScriptSerializer also supports extension via Converters. So, my immediate need before I could use the JSON.NET parser for a couple of old apps was to create a parser that can serialize JSON from Datatables.
Here's are a few converters that can create DataSet/DataTable and DataRow JSON with JSON.NET and turns them into simple value arrays (ie Dataset.Tables[].Rows[]). Note the converters are only for serialization not deserialization:
///Converts a
///object to and from JSON.
///
public class DataRowConverter : JsonConverter
{
///Writes the JSON representation of the object.
///
///
/// Theto write to.
/// The value.
public override void WriteJson(JsonWriter writer, object dataRow)
{
DataRow row = dataRow as DataRow;
// *** HACK: need to use root serializer to write the column value
// should be fixed in next ver of JSON.NET with writer.Serialize(object)
JsonSerializer ser = new JsonSerializer();
writer.WriteStartObject();
foreach (DataColumn column in row.Table.Columns)
{
writer.WritePropertyName(column.ColumnName);
ser.Serialize(writer,row[column]);
}
writer.WriteEndObject();
}
///Determines whether this instance can convert the specified value type.
///
///
/// Type of the value.
///true if this instance can convert the specified value type; otherwise,
///false.
///
public override bool CanConvert(Type valueType)
{
return typeof(DataRow).IsAssignableFrom(valueType);
}
///Reads the JSON representation of the object.
///
///
/// Theto read from.
/// Type of the object.
///The object value.
public override object ReadJson(JsonReader reader, Type objectType)
{
throw new NotImplementedException();
}
}
///Converts a DataTable to JSON. Note no support for deserialization
///
///
public class DataTableConverter : JsonConverter
{
///Writes the JSON representation of the object.
///
///
/// Theto write to.
/// The value.
public override void WriteJson(JsonWriter writer, object dataTable)
{
DataTable table = dataTable as DataTable;
DataRowConverter converter = new DataRowConverter();
writer.WriteStartObject();
writer.WritePropertyName("Rows");
writer.WriteStartArray();
foreach (DataRow row in table.Rows)
{
converter.WriteJson(writer, row);
}
writer.WriteEndArray();
writer.WriteEndObject();
}
///Determines whether this instance can convert the specified value type.
///
///
/// Type of the value.
///true if this instance can convert the specified value type; otherwise,
///false.
///
public override bool CanConvert(Type valueType)
{
return typeof(DataTable).IsAssignableFrom(valueType);
}
///Reads the JSON representation of the object.
///
///
/// Theto read from.
/// Type of the object.
///The object value.
public override object ReadJson(JsonReader reader, Type objectType)
{
throw new NotImplementedException();
}
}
///Converts a
///object to JSON. No support for reading.
///
public class DataSetConverter : JsonConverter
{
///Writes the JSON representation of the object.
///
///
/// Theto write to.
/// The value.
public override void WriteJson(JsonWriter writer, object dataset)
{
DataSet dataSet = dataset as DataSet;
DataTableConverter converter = new DataTableConverter();
writer.WriteStartObject();
writer.WritePropertyName("Tables");
writer.WriteStartArray();
foreach (DataTable table in dataSet.Tables)
{
converter.WriteJson(writer, table);
}
writer.WriteEndArray();
writer.WriteEndObject();
}
///Determines whether this instance can convert the specified value type.
///
///
/// Type of the value.
///true if this instance can convert the specified value type; otherwise,
///false.
///
public override bool CanConvert(Type valueType)
{
return typeof(DataSet).IsAssignableFrom(valueType);
}
///Reads the JSON representation of the object.
///
///
/// Theto read from.
/// Type of the object.
///The object value.
public override object ReadJson(JsonReader reader, Type objectType)
{
throw new NotImplementedException();
}
}
Maybe somebody else will find this useful as well. The serialization is one way only because I personally don't have any need for two-way and deserialization of these objects is tricky because deserialization requires a type to match properties to values in the parsed JSON and well these ADO structures don't have any type format.
Anyway JSON.NET is really nice because it's highly configurable and actively developed. It's also open code so you can look through it and see how its done and tweak if necessary. One thing though - it appears it is a bit slower than other solutions. I've found JSON.NET 2.0 to be more than twice as slow as other solutions, and JSON.NET 3.0 as much as 6 to 7 times slower in some informal iteration tests built into my test suite (I noticed this because tests were slowing down drastically on the perf loop). While processing times are still very small (7 seconds for 10,000 serializations w/ JN 3.0) it still rankles a bit when its considerably slower than other solutions.
DataSet/DataTable/DataRow Serialization in JavaScriptSerializer
The stock JavaScriptSerializer that ships with System.Web.Extensions as part of .NET 3.5 also doesn't directly support ADO.NET objects. Some time ago there was a Converter provided in the Futures package (might still be but I haven't checked) but I never actually used it because the Futures assembly is just too much in flux and you never know what sticks around and will get axed.
Luckily it's also pretty easy to create custom converters for JavaScriptSerializer and so it's easy to create DataSet/Table/Row converters that you can add to your own apps without having to rely on the futures DLL. Here's that same implementation for the JavaScriptSerializer:
internal class WebExtensionsJavaScriptSerializer : JSONSerializerBase, IJSONSerializer
{
public WebExtensionsJavaScriptSerializer(JSONSerializer serializer) : base(serializer)
{}
public string Serialize(object value)
{
JavaScriptSerializer ser = new JavaScriptSerializer();
List<JavaScriptConverter> converters = new List<JavaScriptConverter>();
if (value != null)
{
Type type = value.GetType();
if (type == typeof(DataTable) || type == typeof(DataRow) || type == typeof(DataSet))
{
converters.Add(new WebExtensionsDataRowConverter());
converters.Add(new WebExtensionsDataTableConverter());
converters.Add(new WebExtensionsDataSetConverter());
}
if (converters.Count > 0)
ser.RegisterConverters(converters);
}
return = ser.Serialize(value);
}
public object Deserialize(string jsonText, Type valueType)
{
// *** Have to use Reflection with a 'dynamic' non constant type instance
JavaScriptSerializer ser = new JavaScriptSerializer();
object result = ser.GetType()
.GetMethod("Deserialize")
.MakeGenericMethod(valueType)
.Invoke(ser, new object[1] { jsonText });
return result;
}
}
internal class WebExtensionsDataTableConverter : JavaScriptConverter
{
public override IEnumerable<Type> SupportedTypes
{
get { return new Type[] {typeof (DataTable)}; }
}
public override object Deserialize(IDictionary<string, object> dictionary, Type type,
JavaScriptSerializer serializer)
{
throw new NotImplementedException();
}
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
DataTable table = obj as DataTable;
// *** result 'object'
Dictionary<string, object> result = new Dictionary<string, object>();
if (table != null)
{
// *** We'll represent rows as an array/listType
List<object> rows = new List<object>();
foreach (DataRow row in table.Rows)
{
rows.Add(row); // Rely on DataRowConverter to handle
}
result["Rows"] = rows;
return result;
}
return new Dictionary<string, object>();
}
}
internal class WebExtensionsDataRowConverter : JavaScriptConverter
{
public override IEnumerable<Type> SupportedTypes
{
get { return new Type[] { typeof(DataRow) }; }
}
public override object Deserialize(IDictionary<string, object> dictionary, Type type,
JavaScriptSerializer serializer)
{
throw new NotImplementedException();
}
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
DataRow dataRow = obj as DataRow;
Dictionary<string, object> propValues = new Dictionary<string, object>();
if (dataRow != null)
{
foreach (DataColumn dc in dataRow.Table.Columns)
{
propValues.Add( dc.ColumnName, dataRow[dc]);
}
}
return propValues;
}
}
internal class WebExtensionsDataSetConverter : JavaScriptConverter
{
public override IEnumerable<Type> SupportedTypes
{
get { return new Type[] { typeof(DataSet) }; }
}
public override object Deserialize(IDictionary<string, object> dictionary, Type type,
JavaScriptSerializer serializer)
{
throw new NotImplementedException();
}
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
DataSet dataSet = obj as DataSet;
Dictionary<string, object> tables = new Dictionary<string, object>();
if (dataSet != null)
{
foreach (DataTable dt in dataSet.Tables)
{
tables.Add(dt.TableName, dt);
}
}
return tables;
}
}
Implementing a custom converter involves creating dictionaries of property name and value pairs with the abillity to create nested properties by specifying another dictionary as a value. This approach is makes it pretty easy to create custom serialization formats...
I know I'm not using DataSets much anymore these days but with older code still sitting around that does these converters are coming in handy. Maybe this will prove useful to some of you in a similar situation.