Convert datatable into XML - c#

I convert XML into datatable and now want to convert data table into XML again.
I have database in which four XML's are there and have to change that text xml
public ActionResult getChangeContent(string arg, string content)
{
char[] a = { ':' };
string[] id = arg.Split(a);
decimal tid = Convert.ToDecimal(id[0]);
decimal jid = Convert.ToDecimal(id[1]);
string groupname = id[2];
var gp = (from Trans_Mast in r2ge.Transcription_Master where Trans_Mast.Transcription_Id == tid && Trans_Mast.Entity_Id == jid select Trans_Mast).Distinct();
foreach (var g in gp)
{
DataSet ds = new DataSet();
ds.ReadXml(new XmlTextReader(new StringReader(g.Text_xml)));
DataTable text = ds.Tables[0];
for (int i = 0; i < text.Rows.Count; i++)
{
if (text.Rows[i]["group"].Equals(groupname))
{
text.Rows[i]["Text_Text"] = content;
}
text.AcceptChanges();
}
ConvertDatatableToXML(text);
}
return View();
}
public string ConvertDatatableToXML(DataTable dtTemp)
{
MemoryStream str = new MemoryStream();
dtTemp.WriteXml(str, true);
str.Seek(0, SeekOrigin.Begin);
StreamReader sr = new StreamReader(str);
string xmlstr;
xmlstr = sr.ReadToEnd();
return (xmlstr);
}
Data set is changed but there is no affect on XML.. any suggestion please..

use this piece of code :
private static string ConvertDataTableToXML(DataTable dtBuildSQL)
{
DataSet dsBuildSQL = new DataSet();
StringBuilder sbSQL;
StringWriter swSQL;
string XMLformat;
sbSQL = new StringBuilder();
swSQL = new StringWriter(sbSQL);
dsBuildSQL.Merge(dtBuildSQL, true, MissingSchemaAction.AddWithKey);
dsBuildSQL.Tables[0].TableName = “Table”;
foreach (DataColumn col in dsBuildSQL.Tables[0].Columns)
{
col.ColumnMapping = MappingType.Attribute;
}
dsBuildSQL.WriteXml(swSQL, XmlWriteMode.WriteSchema);
XMLformat = sbSQL.ToString();
return XMLformat;
}

Related

convert data set to xml string

what i am trying to do is converting a dataset to an xml string. where t is returning me the output which contains the datasetname with datatable name . just i want to remove the datatable name and want to bind with only dataset node tag name. what should i do. here is my code.
if (sID > 0)
{
String retXml = String.Empty;
DataSet ds = new DataSet();
DataTable dtpdfAndEmailInfo = new DataTable("pdfandemailinfo");
DataRow dr = dtpdfAndEmailInfo.NewRow();
dtpdfAndEmailInfo.Clear();
dtpdfAndEmailInfo.Columns.Add("mailFrom", typeof(string));
dtpdfAndEmailInfo.Columns.Add("mailTo", typeof(string));
dtpdfAndEmailInfo.Columns.Add("mailCC", typeof(string));
dtpdfAndEmailInfo.Columns.Add("mailBCC", typeof(string));
dtpdfAndEmailInfo.Columns.Add("mailSubject", typeof(string));
dtpdfAndEmailInfo.Columns.Add("salesorderpdfurl", typeof(string));
ds.Tables.Add(dtpdfAndEmailInfo);
dtpdfAndEmailInfo.Rows.Add(dr);
String fileDirectory="D:\\po\\Sandbox\\po\\BOID_858_ORGID_571\\SalesOrderPdf\\" ;
String FileName ="BOID_858_SOID_151382.pdf";
for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
ds.Tables[0].Rows[i]["mailFrom"] = "someemailid#yopmail.com";
ds.Tables[0].Rows[i]["mailTo"] = "someemailid1#yopmail.com";
ds.Tables[0].Rows[i]["mailCC"] = "someemailid2#yopmail.com";
ds.Tables[0].Rows[i]["mailSubject"] = "Test";
if (System.IO.File.Exists(Path.Combine(fileDirectory, FileName)))
{
ds.Tables[0].Rows[i]["SalesOrderPdfURL"] = Path.Combine(fileDirectory, FileName);
}
else
{
ds.Tables[0].Rows[i]["SalesOrderPdfURL"] = "";
}
}
Cmd.ResponseStatus.RowCount = ds.Tables[0].Rows.Count;
retXml = Util.GetXmlList(ds, "salesorderPdfAndEmailInfo", "pdfandemailinfos");
}
public static string GetXmlList(DataSet ds, String rootNode, String itemNode)
{
return GetXmlList(ds, rootNode, #"cls=""dataArray""", itemNode, #"cls=""dataItem""");
}
public static string GetXmlList(DataSet ds, String rootNode, String rootAttribute, String itemNode, String itemAttribute)
{
String rootNodeStartTag = String.Format("<{0} {1}>", rootNode, rootAttribute);
String rootNodeEndTag = String.Format("</{0}>", rootNode);
String nodeStartTag = String.Format("<{0} {1}>", itemNode, itemAttribute);
String nodeEndTag = String.Format("</{0}>", itemNode);
string retXML = ds.GetXml().Replace("<NewDataSet>", rootNodeStartTag).Replace("<Table>", nodeStartTag).Replace("</NewDataSet>", rootNodeEndTag).Replace("</Table>", nodeEndTag);
return HttpUtility.HtmlDecode(retXML);
}
and here is my response
"salesorderPdfAndEmailInfo": {
"pdfandemailinfo": {
"mailFrom": "someemailid#yopmail.com",
"mailTo": "someemailid1#yopmail.com",
"mailCC": "someemailid2#yopmail.com",
"mailSubject": "Test",
"salesorderpdfurl": "http://localhost/por/D:\\po\\Sandbox\\po\\BOID_858_ORGID_571\\SalesOrderPdf\\BOID_858_SOID_151382.pdf"
}
}
what response i want should be like remove the datatable node tag name.any help will be apprecited.
response should be like this..
"salesorderPdfAndEmailInfo": {
"mailFrom": "someemailid#yopmail.com",
"mailTo": "someemailid1#yopmail.com",
"mailCC": "someemailid2#yopmail.com",
"mailSubject": "Test",
"salesorderpdfurl": "http://localhost/por/D:\\po\\Sandbox\\po\\BOID_858_ORGID_571\\SalesOrderPdf\\BOID_858_SOID_151382.pdf"
}

how to return datatable and integer in c#

I am creating a method which returns datatable and an int value.I have create a method which returns only datatable.Please take a look on the code
public static DataTable ShutterstockSearchResults(string url)
{
int TotalCont=0;
DataTable dt = new DataTable();
try
{
//intigration using Basic Aouth with authrization headers
var request = (HttpWebRequest)WebRequest.Create(url);
var username = "SC";
var password = "SK";
string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(username + ":" + password));
request.Headers[HttpRequestHeader.Authorization] = string.Format("Basic {0}", credentials);
request.UserAgent = "MyApp 1.0";
var response = (HttpWebResponse)request.GetResponse();
using (var stream = response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
JavaScriptSerializer js = new JavaScriptSerializer();
var objText = reader.ReadToEnd();
SearchResult myojb = (SearchResult)js.Deserialize(objText, typeof(SearchResult));
TotalCount = myojb.total_count;
dt.Columns.Add("Id");
dt.Columns.Add("Discription");
dt.Columns.Add("Small_Thumb_URl");
dt.Columns.Add("Large_Thumb_URL");
dt.Columns.Add("Prieview_URL");
dt.Columns.Add("ContributorID");
dt.Columns.Add("aspect");
dt.Columns.Add("image_type");
dt.Columns.Add("is_illustration");
dt.Columns.Add("media_type");
foreach (var item in myojb.data)
{
var row = dt.NewRow();
row["ID"] = item.id;
row["Discription"] = item.description;
row["Small_Thumb_URl"] = item.assets.small_thumb.url;
row["Large_Thumb_URL"] = item.assets.large_thumb.url;
row["Prieview_URL"] = item.assets.preview.url;
row["ContributorID"] = item.contributor.id;
row["aspect"] = item.aspect;
row["image_type"] = item.image_type;
row["is_illustration"] = item.is_illustration;
row["media_type"] = item.media_type;
dt.Rows.Add(row);
}
// List<SearchResult> UserList = JsonConvert.DeserializeObject<List<SearchResult>>(objText);
// Response.Write(reader.ReadToEnd());
}
}
catch (WebException ea)
{
Console.WriteLine(ea.Message);
using (var stream = ea.Response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
Console.WriteLine(reader.ReadToEnd());
}
}
return dt;
}
I want to return datatable and TotalCont.please help
Generally speaking, a method can only return one type.
You have two options:
1) Create a class that has a DataTable and an int field, such as:
public class MyReturnType
{
public DataTable TheDataTable {get; set;}
public int TotalCount {get; set;}
}
And return this type from your method.
2) You can add an out parameter to your method:
public static DataTable ShutterstockSearchResults(string url, out totalCount)
And assign to totalCount within your method.
public static Tuple<DataTable, int> ShutterstockSearchResults(string url)
{
[...]
return new Tuple<DataTable, int>(dt, totalCount);
}
public static void SomeConsumerMethod()
{
var result = ShutterstockSearchResults(myPath);
DataTable dt = result.Item1;
int totalCount = result.Item2;
}
To answer the comments in Klaus answer:
public class MyReturnType
{
public DataTable TheDataTable {get; set;}
public int TotalCount {get; set;}
}
and in your method:
public static MyReturnType ShutterstockSearchResults(string url)
{
MyReturnType result=new MyReturnType();
int TotalCont=0;
DataTable dt = new DataTable();
try
{
//intigration using Basic Aouth with authrization headers
var request = (HttpWebRequest)WebRequest.Create(url);
var username = "SC";
var password = "SK";
string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(username + ":" + password));
request.Headers[HttpRequestHeader.Authorization] = string.Format("Basic {0}", credentials);
request.UserAgent = "MyApp 1.0";
var response = (HttpWebResponse)request.GetResponse();
using (var stream = response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
JavaScriptSerializer js = new JavaScriptSerializer();
var objText = reader.ReadToEnd();
SearchResult myojb = (SearchResult)js.Deserialize(objText, typeof(SearchResult));
TotalCount = myojb.total_count;
dt.Columns.Add("Id");
dt.Columns.Add("Discription");
dt.Columns.Add("Small_Thumb_URl");
dt.Columns.Add("Large_Thumb_URL");
dt.Columns.Add("Prieview_URL");
dt.Columns.Add("ContributorID");
dt.Columns.Add("aspect");
dt.Columns.Add("image_type");
dt.Columns.Add("is_illustration");
dt.Columns.Add("media_type");
foreach (var item in myojb.data)
{
var row = dt.NewRow();
row["ID"] = item.id;
row["Discription"] = item.description;
row["Small_Thumb_URl"] = item.assets.small_thumb.url;
row["Large_Thumb_URL"] = item.assets.large_thumb.url;
row["Prieview_URL"] = item.assets.preview.url;
row["ContributorID"] = item.contributor.id;
row["aspect"] = item.aspect;
row["image_type"] = item.image_type;
row["is_illustration"] = item.is_illustration;
row["media_type"] = item.media_type;
dt.Rows.Add(row);
}
// List<SearchResult> UserList = JsonConvert.DeserializeObject<List<SearchResult>>(objText);
// Response.Write(reader.ReadToEnd());
}
}
catch (WebException ea)
{
Console.WriteLine(ea.Message);
using (var stream = ea.Response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
Console.WriteLine(reader.ReadToEnd());
}
}
result.TheDataTable=dt;
result.TotalCount=TotalCount;
return result:
}
Your method needs an additional out parameter if you want to "return" more than one value. Just pass an uninitialized variable of the desired type into your method and assign that variable inside.
public void Test()
{
int i;
DataTable ShutterstockSearchResults("Some string", out i);
}
your ShutterstockSearchResults method needs to be modified accordingly:
public static DataTable ShutterstockSearchResults(string url, out int outParam)
{
outParam = 10;
// do other stuff
}
If you do not change outParam any further inside ShutterstockSearchResults, it will have the value 10 after returning to Test.
You can accomplish this with a Tuple. Consider the following simple example:
public class EmptyClass
{
public static void Main(){
EmptyClass something = new EmptyClass ();
Tuple<String, int> tuple = something.returnMe ();
Console.WriteLine ("Item 1: " + tuple.Item1);
Console.WriteLine ("Item 2: " + tuple.Item2);
}
public EmptyClass ()
{
}
public Tuple<String, int> returnMe() {
return Tuple.Create ("Hello", 2);
}
}

Set "NULL" in Empty cells in CsvReader

Here is my code:
using (System.Net.WebResponse tmpRes = tmpReq.GetResponse())
{
using (System.IO.Stream tmpStream = tmpRes.GetResponseStream())
{
using (System.IO.TextReader tmpReader = new System.IO.StreamReader(tmpStream))
{
string fileContents = tmpReader.ReadToEnd();
for (int i = 0; i < fileContents.Length; i++)
{
if (fileContents[i] == "")
{
fileContents[i] = "null";
}
}
using (Stream s = GenerateStreamFromString(fileContents))
{}
}
}
}
this shows error 'string' to 'char' convert implicitly. Is there any other way to set "NULL" in empty fields in CSVReader
You are not using the CsvReader at all. You are also not splitting the string by your delimiter to get "cells". However, you can load a DataTable from the CsvReader and modify that.
Here's an example presuming tab as delimiter:
var tblCSV = new DataTable();
using (System.Net.WebResponse tmpRes = tmpReq.GetResponse())
using (System.IO.Stream tmpStream = tmpRes.GetResponseStream())
using (System.IO.TextReader tmpReader = new System.IO.StreamReader(tmpStream))
using (var csv = new CsvReader(tmpReader, true, '\t', '"', '\0', '\0', ValueTrimmingOptions.All))
{
csv.MissingFieldAction = MissingFieldAction.ParseError;
csv.DefaultParseErrorAction = ParseErrorAction.RaiseEvent;
csv.ParseError += csv_ParseError;
csv.SkipEmptyLines = true;
// load into DataTable
tblCSV.Load(csv, LoadOption.OverwriteChanges, csvTable_FillError);
}
Now loop the rows and columns and modify them accordingly:
foreach(DataRow row in tblCSV.Rows)
{
foreach(DataColumn col in tblCSV.Columns)
{
if(string.IsNullOrWhiteSpace(row.Field<string>(col)))
row.SetField(col, "null");
}
}
Update related to your comment:
I wants to add NULL value in empty cells in sql database when the csv
data Save in database. Is there any other way?
You could simply use the loop above to update your table instead:
using (var con = new SqlConnection("ConnectionString"))
{
con.Open();
foreach (DataRow row in tblCSV.Rows)
{
using (var cmd = new SqlCommand("INSERT INTO table(Col1,Col2) VALUES (#Col1,Col2);", con))
{
string col1 = row.Field<string>("Col1");
if (string.IsNullOrWhiteSpace(col1))
col1 = null;
string col2 = row.Field<string>("Col2");
if (string.IsNullOrWhiteSpace(col2))
col2 = null;
cmd.Parameters.AddWithValue("#col1", col1);
cmd.Parameters.AddWithValue("#col2", col2);
int inserted = cmd.ExecuteNonQuery();
}
}
}

C# function nested within a class method

I'm trying to implement a function within a Class method and I am somewhat new to C#.
Basically, I have a method that iterates through row in a database and sets values to variables. Then, if a document has been created already it updates the document, if not it creates the document. I'm trying to factor out some of the code and I don't know where to put it as it still needs a reference to my variables. I would like to factor out the repeated items in the if else statement.
private void SyncKinases()
{
DataSet ds = new DataSet();
ds = gn.ExecuteQuery("dx.kinasedatasheet.selectstagingkinases", null);
TreeProvider tp = new TreeProvider(ui);
VersionManager vm = new VersionManager(tp);
TreeNode node;
WorkflowManager wm = new WorkflowManager(tp);
if (ds.Tables[0].Rows.Count > 0)
{
foreach (DataRow dr in ds.Tables[0].Rows)
{
string className = "dx.kinasedatasheet";
string title = dr["Title"].ToString();
string technologyPlatform = dr["TechnologyPlatform"].ToString();
string ambitGeneSymbol = dr["AmbitGeneSymbol"].ToString();
string targetDescription = dr["TargetDescription"].ToString();
string entrezGeneSymbol = dr["EntrezGeneSymbol"].ToString();
int entrezGeneID = int.Parse(dr["EntrezGeneID"].ToString());
string aliases = dr["Aliases"].ToString();
string kinaseGroup = dr["KinaseGroup"].ToString();
string species = dr["Species"].ToString();
string accessionNumber = dr["AccessionNumber"].ToString();
string kinaseConstruct = dr["KinaseConstruct"].ToString();
string kinaseForm = dr["KinaseForm"].ToString();
string expressionSystem = dr["ExpressionSystem"].ToString();
double avgZValue = 0;
if (!(dr["AverageZValue"] is DBNull))
{
avgZValue = double.Parse(dr["AverageZValue"].ToString());
}
string panel = dr["Panel"].ToString();
string compoundsKds = dr["CompoundsKds"].ToString();
string mutationRelevance = dr["MutationRelevance"].ToString();
string mutationReferences = dr["MutationReferences"].ToString();
string kinaseAliasPath = "/Kinase-Data-Sheets";
if (!(dr["NodeID"] is System.DBNull))
{
node = tp.SelectSingleNode(int.Parse(dr["NodeID"].ToString()));
vm.CheckOut(node);
node.DocumentName = ambitGeneSymbol;
node.NodeName = ambitGeneSymbol;
node.SetValue("Title", title);
node.SetValue("TechnologyPlatform", technologyPlatform);
node.SetValue("AmbitGeneSymbol", ambitGeneSymbol);
node.SetValue("TargetDescription", targetDescription);
node.SetValue("EntrezGeneSymbol", entrezGeneSymbol);
node.SetValue("EntrezGeneID", entrezGeneID);
node.SetValue("Aliases", aliases);
node.SetValue("KinaseGroup", kinaseGroup);
node.SetValue("Species", species);
node.SetValue("AccessionNumber", accessionNumber);
node.SetValue("KinaseConstruct", kinaseConstruct);
node.SetValue("KinaseForm", kinaseForm);
node.SetValue("ExpressionSystem", expressionSystem);
if (!(dr["AverageZValue"] is DBNull))
{
node.SetValue("AverageZValue", avgZValue);
}
node.SetValue("Panel", panel);
node.SetValue("CompoundsKds", compoundsKds);
node.SetValue("MutationRelevance", mutationRelevance);
node.SetValue("MutationReferences", mutationReferences);
node.SetValue("DocumentPublishTo", null);
node.Update();
updatedKinaseCount++;
vm.CheckIn(node, null, null);
WorkflowInfo wi = wm.GetNodeWorkflow(node);
if (node.IsPublished)
{
wm.AutomaticallyPublish(node, wi, null);
}
}
else
{
node = TreeNode.New(className, tp);
node.DocumentName = ambitGeneSymbol;
node.NodeName = ambitGeneSymbol;
node.SetValue("Title", title);
node.SetValue("TechnologyPlatform", technologyPlatform);
node.SetValue("AmbitGeneSymbol", ambitGeneSymbol);
node.SetValue("TargetDescription", targetDescription);
node.SetValue("EntrezGeneSymbol", entrezGeneSymbol);
node.SetValue("EntrezGeneID", entrezGeneID);
node.SetValue("Aliases", aliases);
node.SetValue("KinaseGroup", kinaseGroup);
node.SetValue("Species", species);
node.SetValue("AccessionNumber", accessionNumber);
node.SetValue("KinaseConstruct", kinaseConstruct);
node.SetValue("KinaseForm", kinaseForm);
node.SetValue("ExpressionSystem", expressionSystem);
if (!(dr["AverageZValue"] is DBNull))
{
node.SetValue("AverageZValue", avgZValue);
}
node.SetValue("Panel", panel);
node.SetValue("CompoundsKds", compoundsKds);
node.SetValue("MutationRelevance", mutationRelevance);
node.SetValue("MutationReferences", mutationReferences);
node.SetValue("DocumentPublishTo", null);
node.SetValue("DocumentCulture", "en-US");
TreeNode parentNode = tp.SelectSingleNode("DiscoveRx", kinaseAliasPath, "en-US");
node.Insert(parentNode);
//vm.CheckIn(node, null, null);
newKinaseCount++;
}
}
}
ArchiveItems(archivedKinaseCount, "dx.kinasedatasheet.selectarchivekinases");
}
In addition to refactoring your routine I'd recommend creating some extension methods to save you some typing. For example, here's the an extension for parsing your doubles:
public static class Extensions
{
public static double ToDoubleIfNotDBNull(this object item)
{
if (item is DBNULL) return 0;
return double.Parse(item.ToString());
}
}
So then your code becomes:
double avgZValue = dr["AverageZValue"].ToDoubleIfNotDBNull();
You can just refactor your code so you don't need to set the node values in different cases:
private void SyncKinases()
{
DataSet ds = new DataSet();
ds = gn.ExecuteQuery("dx.kinasedatasheet.selectstagingkinases", null);
TreeProvider tp = new TreeProvider(ui);
VersionManager vm = new VersionManager(tp);
TreeNode node;
WorkflowManager wm = new WorkflowManager(tp);
if (ds.Tables[0].Rows.Count > 0)
{
foreach (DataRow dr in ds.Tables[0].Rows)
{
string className = "dx.kinasedatasheet";
string title = dr["Title"].ToString();
string technologyPlatform = dr["TechnologyPlatform"].ToString();
string ambitGeneSymbol = dr["AmbitGeneSymbol"].ToString();
string targetDescription = dr["TargetDescription"].ToString();
string entrezGeneSymbol = dr["EntrezGeneSymbol"].ToString();
int entrezGeneID = int.Parse(dr["EntrezGeneID"].ToString());
string aliases = dr["Aliases"].ToString();
string kinaseGroup = dr["KinaseGroup"].ToString();
string species = dr["Species"].ToString();
string accessionNumber = dr["AccessionNumber"].ToString();
string kinaseConstruct = dr["KinaseConstruct"].ToString();
string kinaseForm = dr["KinaseForm"].ToString();
string expressionSystem = dr["ExpressionSystem"].ToString();
double avgZValue = 0;
if (!(dr["AverageZValue"] is DBNull))
{
avgZValue = double.Parse(dr["AverageZValue"].ToString());
}
string panel = dr["Panel"].ToString();
string compoundsKds = dr["CompoundsKds"].ToString();
string mutationRelevance = dr["MutationRelevance"].ToString();
string mutationReferences = dr["MutationReferences"].ToString();
string kinaseAliasPath = "/Kinase-Data-Sheets";
bool isNewNode = false;
if (!(dr["NodeID"] is System.DBNull))
{
node = tp.SelectSingleNode(int.Parse(dr["NodeID"].ToString()));
vm.CheckOut(node);
}
else
{
node = TreeNode.New(className, tp);
node.SetValue("DocumentCulture", "en-US");
isNewNewNode = true;
}
node.DocumentName = ambitGeneSymbol;
node.NodeName = ambitGeneSymbol;
node.SetValue("Title", title);
node.SetValue("TechnologyPlatform", technologyPlatform);
node.SetValue("AmbitGeneSymbol", ambitGeneSymbol);
node.SetValue("TargetDescription", targetDescription);
node.SetValue("EntrezGeneSymbol", entrezGeneSymbol);
node.SetValue("EntrezGeneID", entrezGeneID);
node.SetValue("Aliases", aliases);
node.SetValue("KinaseGroup", kinaseGroup);
node.SetValue("Species", species);
node.SetValue("AccessionNumber", accessionNumber);
node.SetValue("KinaseConstruct", kinaseConstruct);
node.SetValue("KinaseForm", kinaseForm);
node.SetValue("ExpressionSystem", expressionSystem);
if (!(dr["AverageZValue"] is DBNull))
{
node.SetValue("AverageZValue", avgZValue);
}
node.SetValue("Panel", panel);
node.SetValue("CompoundsKds", compoundsKds);
node.SetValue("MutationRelevance", mutationRelevance);
node.SetValue("MutationReferences", mutationReferences);
node.SetValue("DocumentPublishTo", null);
if (isNewNode)
{
TreeNode parentNode = tp.SelectSingleNode("DiscoveRx", kinaseAliasPath, "en-US");
node.Insert(parentNode);
//vm.CheckIn(node, null, null);
newKinaseCount++;
}
else
{
node.Update();
updatedKinaseCount++;
vm.CheckIn(node, null, null);
WorkflowInfo wi = wm.GetNodeWorkflow(node);
if (node.IsPublished)
{
wm.AutomaticallyPublish(node, wi, null);
}
}
}
}
ArchiveItems(archivedKinaseCount, "dx.kinasedatasheet.selectarchivekinases");
}
You now also don't need all of those temporary variables from dr columns since they will only be used once. Removing those will make your method much shorter and more readable.
Just create a new method and send the values as parameters.
void SetNodeValues(Node node, DataRow row)
{
string title = dr["Title"].ToString();
....
node.SetValue("Title", title);
...
}
You might be able to do it all with a for loop (untested and not match your variables)
foreach(var col in Table.Columns)
node.SetValue(col.Name, dr[col]);
If you were using an ORM, you could send an object instead of the DataRow but that is beyond the scope of this question.

Howto serialize a class containing an object (of any serializable type) to XML ? (Conditon: .NET 1.1)

Question: I must get the content of all sessions in a HttpModule, under .NET 1.1 ...
(don't ask my why certain people still use it)
I can write the module, I can get the sessions.
But... sessions are stored as
session["SomeString"] = object
How can I serialize a class that contains an object as member to XML ?
Specifically, I tried the example of a DataTable.
Condition: It must work on .NET 1.1 So NO generics
And since 1.1 does not have System.Web.SessionState, not this way either:
private string Serialize(System.Web.SessionState.SessionStateItemCollection items)
{
System.IO.MemoryStream ms = new System.IO.MemoryStream();
System.IO.BinaryWriter writer = new System.IO.BinaryWriter(ms);
if (items != null)
items.Serialize(writer);
writer.Close();
return Convert.ToBase64String(ms.ToArray());
} // End Function Serialize
Below is my attempt, which works very well on only-text values in the object, but fails on a DataTable. The funny thing is: DataTable IS serializable, so it "SHOULD" work...
using System;
using System.Collections.Generic;
using System.Text;
namespace SessionModuleUnitTest
{
public class Program
{
[Serializable()]
public class kvp
{
[System.Xml.Serialization.XmlElement(ElementName = "key")]
public string key = "";
[System.Xml.Serialization.XmlElement(ElementName = "value")]
public object value = new object();
public kvp()
{ }
public kvp(string strKey, object obj)
{
this.key = strKey;
this.value = obj;
}
}
[Serializable()]
public class whatever
{
[System.Xml.Serialization.XmlArrayItem(Type = typeof(kvp))]
public kvp[] MyKeyValueCollection;
}
public static void Serialization()
{
// http://www.java2s.com/Tutorial/CSharp/0220__Data-Structure/SerializeanArrayListobjecttoabinaryfile.htm
// http://www.java2s.com/Tutorial/CSharp/0220__Data-Structure/DeserializeanArrayListobjectfromabinaryfile.htm
System.Data.DataTable dt = new System.Data.DataTable();
dt.Columns.Add("abc", typeof(string));
dt.Columns.Add("def", typeof(int));
System.Data.DataRow dr = dt.NewRow();
dr["abc"] = "test1";
dr["def"] = 123;
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["abc"] = "test2";
dr["def"] = 456;
dt.Rows.Add(dr);
System.Data.DataSet ds = new System.Data.DataSet();
ds.Tables.Add(dt);
Console.WriteLine("Type: " + dt.GetType().FullName + ", Serializable: " + dt.GetType().IsSerializable);
kvp ObjectToSerialize1 = new kvp("key1", "value1");
kvp ObjectToSerialize2 = new kvp("key2", "value2");
kvp ObjectToSerialize3 = new kvp("key3", dt);
System.Collections.ArrayList al = new System.Collections.ArrayList();
al.Add(ObjectToSerialize1);
al.Add(ObjectToSerialize2);
al.Add(ObjectToSerialize3);
whatever what = new whatever();
what.MyKeyValueCollection = new kvp[3];
what.MyKeyValueCollection[0] = ObjectToSerialize1;
what.MyKeyValueCollection[1] = ObjectToSerialize2;
what.MyKeyValueCollection[2] = ObjectToSerialize3;
Type[] theExtraTypes = new Type[2];
//theExtraTypes[0] = typeof(System.Collections.ArrayList);
theExtraTypes[0] = typeof(kvp);
//theExtraTypes[2] = typeof(System.Data.DataTable);
System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(what.GetType());
//System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(what.GetType(), theExtraTypes);
//System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(al.GetType());
//System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(System.Collections.ArrayList), theExtraTypes);
System.Text.StringBuilder sb = new System.Text.StringBuilder();
System.IO.StringWriter writer = new System.IO.StringWriter(sb);
//ser.Serialize(writer, al); // Here Classes are converted to XML String.
ser.Serialize(writer, what); // Here Classes are converted to XML String.
// This can be viewed in SB or writer.
// Above XML in SB can be loaded in XmlDocument object
string strSerializedItem = sb.ToString();
Console.WriteLine(strSerializedItem);
/*
System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
xmlDoc.LoadXml(sb.ToString());
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Xml.XmlTextWriter xw = new System.Xml.XmlTextWriter(sw);
xmlDoc.WriteTo(xw);
string strSerialized = sw.ToString();
xw.Close();
sw.Close();
//sw.Dispose();
*/
}
static void Main(string[] args)
{
Serialization();
Console.WriteLine(Environment.NewLine);
Console.WriteLine(" --- Press any key to continue --- ");
Console.ReadKey(true);
}
}
}
Edit:
Obviously, there is a difference between runtime serialzation and XML serialzation.
Read here:
http://www.codeproject.com/KB/aspnet/Serialization.aspx
and here
http://manishagrahari.blogspot.com/2011/08/serialization-in-net-part-4.html
and here
http://blog.kowalczyk.info/article/Serialization-in-C.html
and here
http://www.codeproject.com/KB/XML/Serialization_Samples.aspx
And here for core methods:
http://www.15seconds.com/issue/020903.htm
and this
http://www.codeproject.com/KB/XML/Serialization_Samples.aspx
For SOAP serialzation, you need to add a reference to:
System.Runtime.Serialization.Formatters.Soap
In general, you can't do this. It's possible to put things into Session state that cannot be XML serialized.
It is freaking possible.
It was a hard fight, but it is possible.
Trick 77 in short:
Using a property, serializing the object to a string, then save the two strings (and the type information, INCLUDING assemblyname) in a containertype in an arraylist, and then serialize this ArrayList.
And then the reverse trick for deserialization.
3rd parties please note that I probably didn't properly catch the case that a object might not be serializable. Use a non-serializable type - like a dictionary - to test this, for example.
using System;
using System.Collections.Generic;
using System.Text;
namespace SessionModuleUnitTest
{
public class Program
{
[Serializable()]
[System.Xml.Serialization.XmlRoot(ElementName = "SessionData")]
public class cSessionData
{
[System.Xml.Serialization.XmlElement(ElementName = "key")]
public string key;
[System.Xml.Serialization.XmlElement(ElementName = "assembly")]
public string AssemblyQualifiedName;
[System.Xml.Serialization.XmlElement(ElementName = "value")]
public string m_value;
[System.Xml.Serialization.XmlIgnore()]
public object value
{
get
{
object obj = null;
if (m_value == null)
return obj;
// Type.GetType only looks in the currently executing assembly and mscorlib
// unless you specify the assembly name as well.
//Type T = Type.GetType(this.datatype);
Type T = Type.GetType(this.AssemblyQualifiedName);
System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(T);
System.IO.StringReader sr = new System.IO.StringReader(m_value);
obj = ser.Deserialize(sr);
sr.Close();
//sr.Dispose();
sr = null;
ser = null;
return obj;
} // End Get
set
{
//this.m_value = value;
//Console.WriteLine("Type: " + obj.GetType().FullName + ", Serializable: " + obj.GetType().IsSerializable);
if (value != null)
{
//this.datatype = value.GetType().FullName;
this.AssemblyQualifiedName = value.GetType().AssemblyQualifiedName;
if (value.GetType().IsSerializable)
{
System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(value.GetType());
System.Text.StringBuilder sb = new System.Text.StringBuilder();
System.IO.StringWriter writer = new System.IO.StringWriter(sb);
ser.Serialize(writer, value);
this.m_value = sb.ToString();
writer.Close();
//writer.Dispose();
sb = null;
writer = null;
ser = null;
}
else
this.m_value = null;
}
else
{
this.AssemblyQualifiedName = null;
this.m_value = null;
}
} // End Set
} // End Property value
public cSessionData()
{
} // End Constructor
public cSessionData(string strKey, object obj)
{
this.key = strKey;
this.value = obj;
} // End Constructor
} // End Class cSessionData
public static string Serialize(System.Collections.ArrayList al)
{
Type[] theExtraTypes = new Type[2];
theExtraTypes[0] = typeof(System.Collections.ArrayList);
theExtraTypes[1] = typeof(cSessionData);
System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(System.Collections.ArrayList), theExtraTypes);
System.Text.StringBuilder sb = new System.Text.StringBuilder();
System.IO.StringWriter writer = new System.IO.StringWriter(sb);
ser.Serialize(writer, al);
string strSerializedItem = sb.ToString();
sb = null;
writer.Close();
//writer.Dispose();
writer = null;
ser = null;
/*
System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
xmlDoc.LoadXml(sb.ToString());
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Xml.XmlTextWriter xw = new System.Xml.XmlTextWriter(sw);
xmlDoc.WriteTo(xw);
string strSerialized = sw.ToString();
xw.Close();
sw.Close();
//sw.Dispose();
*/
return strSerializedItem;
}
public static void Serialization()
{
// http://www.java2s.com/Tutorial/CSharp/0220__Data-Structure/SerializeanArrayListobjecttoabinaryfile.htm
// http://www.java2s.com/Tutorial/CSharp/0220__Data-Structure/DeserializeanArrayListobjectfromabinaryfile.htm
System.Data.DataTable dt = new System.Data.DataTable();
dt.Columns.Add("abc", typeof(string));
dt.Columns.Add("def", typeof(int));
System.Data.DataRow dr = dt.NewRow();
dr["abc"] = "test1";
dr["def"] = 123;
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["abc"] = "test2";
dr["def"] = 456;
dt.Rows.Add(dr);
System.Data.DataSet ds = new System.Data.DataSet();
ds.Tables.Add(dt);
Console.WriteLine("tname: " + dt.GetType().FullName);
cSessionData ObjectToSerialize1 = new cSessionData("key1", "value1");
cSessionData ObjectToSerialize2 = new cSessionData("key2", "value2");
cSessionData ObjectToSerialize3 = new cSessionData("key3", dt);
System.Collections.ArrayList al = new System.Collections.ArrayList();
al.Add(ObjectToSerialize1);
al.Add(ObjectToSerialize2);
al.Add(ObjectToSerialize3);
string strSerializedItem = Serialize(al);
Console.WriteLine(strSerializedItem);
Deserialize(strSerializedItem);
}
static void Deserialize(string strXML)
{
Type[] theExtraTypes = new Type[2];
theExtraTypes[0] = typeof(System.Collections.ArrayList);
theExtraTypes[1] = typeof(cSessionData);
System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(System.Collections.ArrayList), theExtraTypes);
System.IO.StringReader sr = new System.IO.StringReader(strXML);
System.Collections.ArrayList myal = (System.Collections.ArrayList ) ser.Deserialize(sr);
foreach (cSessionData SessionData in myal)
{
Console.WriteLine(SessionData.key + "=" + SessionData.value);
}
cSessionData MySessionData = (cSessionData) myal[2];
Console.WriteLine(MySessionData.key + "=" + MySessionData.value);
System.Data.DataTable d = (System.Data.DataTable)MySessionData.value;
Console.WriteLine(d.Rows[0]["def"]);
} // End Sub Deserialize
static void Main(string[] args)
{
Serialization();
Console.WriteLine(Environment.NewLine);
Console.WriteLine(" --- Press any key to continue --- ");
Console.ReadKey(true);
} // End Sub Main
} // End Class Program
} // Namespace SessionModuleUnitTest
Edit:
Rev 1:
using System;
using System.Collections.Generic;
using System.Text;
namespace SessionModuleUnitTest
{
public class Program
{
[Serializable()]
[System.Xml.Serialization.XmlRoot(ElementName = "SessionData")]
public class cSessionData
{
[System.Xml.Serialization.XmlElement(ElementName = "key")]
public string key;
[System.Xml.Serialization.XmlElement(ElementName = "assembly")]
public string AssemblyQualifiedName;
[System.Xml.Serialization.XmlElement(ElementName = "value")]
public string m_value;
[System.Xml.Serialization.XmlIgnore()]
public object value
{
get
{
object obj = null;
if (m_value == null)
return obj;
// Type.GetType only looks in the currently executing assembly and mscorlib
// unless you specify the assembly name as well.
//Type T = Type.GetType(this.datatype);
Type T = Type.GetType(this.AssemblyQualifiedName);
obj = DeSerializeSOAP(m_value);
return obj;
} // End Get
set
{
//this.m_value = value;
//Console.WriteLine("Type: " + obj.GetType().FullName + ", Serializable: " + obj.GetType().IsSerializable);
if (value != null)
{
//this.datatype = value.GetType().FullName;
this.AssemblyQualifiedName = value.GetType().AssemblyQualifiedName;
if (value.GetType().IsSerializable)
{
this.m_value = SerializeSOAP(value);
}
else
this.m_value = null;
}
else
{
this.AssemblyQualifiedName = null;
this.m_value = null;
}
} // End Set
} // End Property value
public cSessionData()
{
} // End Constructor
public cSessionData(string strKey, object obj)
{
this.key = strKey;
this.value = obj;
} // End Constructor
} // End Class cSessionData
//public static void InsertSessionData(cSessionData SessionData)
public static void InsertSessionData(string strSessionUID, string strSessionID, string strKey, string strValue, string strDataType)
{
strSessionUID = strSessionUID.Replace("'", "''");
strSessionID = strSessionID.Replace("'", "''");
strKey = strKey.Replace("'", "''");
strValue = strValue.Replace("'", "''");
strDataType = strDataType.Replace("'", "''");
string strSQL = #"
INSERT INTO dbo.T_SessionValues
(
Session_UID
,Session_ID
,Session_Key
,Session_Value
,Session_DataType
)
VALUES
(
'" + strSessionUID + #"' --<Session_UID, uniqueidentifier, newid()>
,N'" + strSessionID + #"' --<Session_ID, nvarchar(84), NULL>
,N'" + strKey + #"' --<Session_Key, nvarchar(100), NULL>
,N'" + strValue + #"' --<Session_Value, nvarchar(max),NULL>
,N'" + strDataType + #"' --<Session_DataType, nvarchar(4000),NULL>
)
";
//System.Runtime.Serialization.Formatters.Binary.
COR.SQL.MS_SQL.Execute(strSQL);
}
// Add reference to System.Runtime.Serialization.Formatters.Soap
public static string SerializeSOAP(object obj)
{
string strSOAP = null;
System.Runtime.Serialization.Formatters.Soap.SoapFormatter serializer = new System.Runtime.Serialization.Formatters.Soap.SoapFormatter();
using (System.IO.MemoryStream memStream = new System.IO.MemoryStream())
{
serializer.Serialize(memStream, obj);
long pos = memStream.Position;
memStream.Position = 0;
using (System.IO.StreamReader reader = new System.IO.StreamReader(memStream))
{
strSOAP = reader.ReadToEnd();
memStream.Position = pos;
reader.Close();
}
}
return strSOAP;
}
public static object DeSerializeSOAP(string SOAP)
{
if (string.IsNullOrEmpty(SOAP))
{
throw new ArgumentException("SOAP can not be null/empty");
}
using (System.IO.MemoryStream Stream = new System.IO.MemoryStream(UTF8Encoding.UTF8.GetBytes(SOAP)))
{
System.Runtime.Serialization.Formatters.Soap.SoapFormatter Formatter = new System.Runtime.Serialization.Formatters.Soap.SoapFormatter();
return Formatter.Deserialize(Stream);
}
}
public static System.Collections.ArrayList GetData()
{
System.Data.DataTable dt = new System.Data.DataTable();
dt.Columns.Add("abc", typeof(string));
dt.Columns.Add("def", typeof(int));
System.Data.DataRow dr = dt.NewRow();
dr["abc"] = "test1";
dr["def"] = 123;
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["abc"] = "test2";
dr["def"] = 456;
dt.Rows.Add(dr);
System.Data.DataSet ds = new System.Data.DataSet();
ds.Tables.Add(dt);
cSessionData ObjectToSerialize1 = new cSessionData("key1", "value1");
cSessionData ObjectToSerialize2 = new cSessionData("key2", "value2");
cSessionData ObjectToSerialize3 = new cSessionData("key3", dt);
System.Collections.ArrayList al = new System.Collections.ArrayList();
al.Add(ObjectToSerialize1);
al.Add(ObjectToSerialize2);
al.Add(ObjectToSerialize3);
return al;
}
public static void Deserialize(string strSOAP)
{
System.Collections.ArrayList myal = (System.Collections.ArrayList)DeSerializeSOAP(strSOAP);
foreach (cSessionData SessionData in myal)
{
Console.WriteLine(SessionData.key + "=" + SessionData.value);
}
cSessionData MySessionData = (cSessionData)myal[2];
Console.WriteLine(MySessionData.key + "=" + MySessionData.value);
System.Data.DataTable d = (System.Data.DataTable)MySessionData.value;
Console.WriteLine(d.Rows[0]["def"]);
}
public static string Serialize(System.Collections.ArrayList al)
{
// http://www.java2s.com/Tutorial/CSharp/0220__Data-Structure/SerializeanArrayListobjecttoabinaryfile.htm
// http://www.java2s.com/Tutorial/CSharp/0220__Data-Structure/DeserializeanArrayListobjectfromabinaryfile.htm
string strSerializedItem = SerializeSOAP(al);
Console.WriteLine(strSerializedItem);
return strSerializedItem;
}
static void Main(string[] args)
{
//InsertSessionData(System.Guid.NewGuid().ToString(), "fdslfkjsdalfj", "Key1", "Value1", typeof(System.Data.DataTable).AssemblyQualifiedName);
string strSOAP = Serialize(GetData());
Deserialize(strSOAP);
Console.WriteLine(Environment.NewLine);
Console.WriteLine(" --- Press any key to continue --- ");
Console.ReadKey(true);
} // End Sub Main
} // End Class Program
} // Namespace SessionModuleUnitTest

Categories