Cannot convert string to System.IO.TextReader - c#

I'm writing a code that can be dragged and drop to the program that can get it's directory (which must be a csv file) and will filter out the data. But I'm having trouble passing a string object(which is the path of the csv file) to a class which would make the filtering process. So here's the code:
private void Form1_DragDrop(object sender, DragEventArgs e)
{
//Takes dropped items and store in string array which is the path
string[] droppedFile = (string[])e.Data.GetData(DataFormats.FileDrop);
//passing the string object and this is where I get the error
CsvParser run = new CsvParser(droppedFile[0]);
MessageBox.Show("file path: " + droppedFile[0],"Message");
}
and the receiving class looks like this:
public CsvParser(string filePath)
{
//use of StreamReader to get csv file
using (var sr = new StreamReader(filePath))
using (DataTable dt = new DataTable("Table"))
{
//variable to be able to read csv file
var reader = new CsvReader(sr,true);
//some logic
}
}
I've also tried converting the string to a StringReader which look like this:
private void Form1_DragDrop(object sender, DragEventArgs e)
{
string[] droppedFile = (string[])e.Data.GetData(DataFormats.FileDrop);
//taking path of the file string to stringreader object
var textReader = new StringReader(droppedFile[0]);
CsvParser run = new CsvParser(textReader);
MessageBox.Show("file path: " + textReader,"Message");
}
when I coded this it actually bypasses the error but when it comes to the process where it should filter out the data nothing happens and the value of the converted string is only System.IO.StringReader. I'm still learning on C# so I'll be glad if you guys can help me out.
//update
This is what my CsvParser looks like for broad view:
using CsvHelper;
using CsvHelper.Configuration;
using System;
using System.Collections.Generic;
using System.IO;
using System.Data;
namespace Project
{
class CsvParser
{
public CsvParser(string filePath)
{
//use of library StreamReader to get csv file
using (var sr = new StreamReader(filePath))
using (DataTable dt = new DataTable("Table"))
{
//variable to be able to read csv file
var reader = new CsvReader(sr,true);
//csv configurations
reader.Configuration.RegisterClassMap<DataRecordMap>();
//CSVReader will now read the whole file into an enumerable
IEnumerable<DataRecord> records = reader.GetRecords<DataRecord>();
dt.Columns.Add("Create Date", typeof(string));
dt.Columns.Add("IR Initial Response", typeof(string));
dt.Columns.Add("FR Fix Response", typeof(string));
dt.Columns.Add("Summary", typeof(string));
dt.Columns.Add("Ticket #", typeof(string));
dt.Columns.Add("Company", typeof(string));
dt.Columns.Add("Assigned to", typeof(string));
dt.Columns.Add("Caller", typeof(string));
dt.Columns.Add("Case Type", typeof(string));
dt.Columns.Add("Close Date", typeof(string));
dt.Columns.Add("Days Open", typeof(string));
dt.Columns.Add("Department", typeof(string));
dt.Columns.Add("Infrastructure Type", typeof(string));
dt.Columns.Add("Location", typeof(string));
dt.Columns.Add("Priority", typeof(string));
dt.Columns.Add("IncidentType", typeof(string));
dt.Columns.Add("Resolution", typeof(string));
dt.Columns.Add("Status", typeof(string));
dt.Columns.Add("Shift", typeof(string));
foreach (DataRecord record in records)
{
dt.Rows.Add(record.CreateDate.Replace("\n", "").Replace(" ", "").Replace("\"", "").Replace("#", " # ").Replace("AM", " AM").Replace("PM", " PM"),
record.IRInitialResponse.Replace("\n", "").Replace(" ", "").Replace("\"", "").Replace("at", " # ").Replace("AM", " AM").Replace("PM", " PM"),
record.FRFixResponse.Replace("\n", "").Replace(" ", "").Replace("\"", "").Replace("at", " # ").Replace("AM", " AM").Replace("PM", " PM"),
record.Summary, record.TicketNo, record.Company, record.Assignedto, record.Caller, record.CaseType,
record.CloseDate.Replace("\n", "").Replace(" ", "").Replace("\"", "").Replace("at", " # ").Replace("AM", " AM").Replace("PM", " PM"),
record.DaysOpen, record.Department, record.InfrastructureType, record.Location,
record.Priority, record.IncidentType, record.Resolution, record.Status, record.Shift);
}
sr.Close();
WriteCsv wcsv = new WriteCsv(dt, filePath);
Console.WriteLine(dt.Rows.Count);
}
Console.WriteLine("FINISHED");
}
public sealed class DataRecordMap : ClassMap<DataRecord>
{
public DataRecordMap()
{
AutoMap();
Map(m => m.TicketNo).Name("Ticket #");
}
}
}
}

Related

Label message is not printing for empty data table

I want to display message if data table is empty but label is not printing text.
I tried ScriptManager.RegisterStartupScript(this, GetType(), "message", "alert('No data found');", true); But still its not printing any message.
I believe I am downloading file from server in ZIP folder may be that's why I am not able print message ?
Please guide me where I am doing mistake ?
#Adyson Please check my updated code
Business Logic Explanation :
Here we have requirement is: To store multiples file on one button click and it is not possible Because for one HTTP request One Response we can generate so alternatively what I do is : First I Create csv File and store on server latter after completion of csv file generation I am zipping all csv in a single file and able to download. and on page load I am deleting old csv files to avoid duplicacate files.
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string[] files = Directory.GetFiles(Server.MapPath("~/Order_Files/"));
int iCnt = 0;
foreach (string file in files)
{
FileInfo info = new FileInfo(file);
info.Refresh();
if (info.LastWriteTime <= DateTime.Now)
{
info.Delete();
iCnt += 1;
}
}
btnGenerate.Attributes.Add("onclick", "waitdownload();");
if (!Page.IsPostBack)
{
BindRegion();
//lblINQ.Text = "";
//lblQUO.Text = "";
}
}
public void BindRegion()
{
//Binding Code
}
protected void ddlregion_SelectedIndexChanged(object sender, EventArgs e)
{
//Select Index change code
}
protected void btnGenerate_Click(object sender, EventArgs e)
{
#region CSV Generation
DateTime Order_Date = Convert.ToDateTime(deOrderDate.Text);
var Order_Date_Datemodified = Order_Date.ToString("yyyyMMdd");
foreach (ListItem listItem in ddlDepot.Items)
{
int OrderSum = 0;
int LineSum = 0;
if (listItem.Selected)
{
#region for INQ
if (ddlInqfileType.SelectedItem.Text == "INQ" || ddlInqfileType.SelectedItem.Text == "QUO")
{
OracleCommand CmdB = new OracleCommand(String.Format(#"//Select Query"
, ddlInqfileType.SelectedItem.Text, listItem.Value,
(ddlInqfileType.SelectedItem.Text.Equals("ÏNQ") ? deInqDate.Text.ToString() : deQuoDate.Text.ToString()),
deOrderDate.Text.ToString()), con);
CmdB.CommandType = CommandType.Text;
OracleDataAdapter daBINQ = new OracleDataAdapter();
DataTable dtINQ = new DataTable();
dtINQ.Columns.Add("DEPOT_CODE", typeof(string));
dtINQ.Columns.Add("ROUTE_CODE", typeof(string));
dtINQ.Columns.Add("UPLOAD_DATE", typeof(string));
dtINQ.Columns.Add("SAP_REGION_CODE", typeof(string));
dtINQ.Columns.Add("SAP_SUB_REGION_CODE", typeof(string));
dtINQ.Columns.Add("SAP_CUSTOMER_CODE", typeof(string));
dtINQ.Columns.Add("SALES_DATE", typeof(string));
dtINQ.Columns.Add("PRODUCT_CODE", typeof(string));
dtINQ.Columns.Add("ORDER_QTY", typeof(string));
dtINQ.Columns.Add("UOM_CODE", typeof(string));
dtINQ.Columns.Add("LINE_TOTAL", typeof(string));
daBINQ.SelectCommand = CmdB;
daBINQ.Fill(dtINQ);
if (dtINQ.Rows.Count <= 0)
{
lblINQ.Text = "No data found for Selected Inquiry date, Please select other date";
lblINQ.ForeColor = System.Drawing.Color.Red;
}
else
{
foreach (DataRow dr in dtINQ.Rows)
{
OrderSum += Convert.ToInt32(dr["ORDER_QTY"]);
}
foreach (DataRow dr in dtINQ.Rows)
{
LineSum += Convert.ToInt32(dr["LINE_TOTAL"]);
}
DataRow row = dtINQ.NewRow();
row["DEPOT_CODE"] = "TOT";
row["ORDER_QTY"] = OrderSum;
row["LINE_TOTAL"] = LineSum;
dtINQ.Rows.Add(row);
string fileName = "INQ" + listItem.Value + Order_Date_Datemodified + ".CSV";
string filePath = HttpContext.Current.Server.MapPath("~/Order_Files/" + fileName);
Almarai.AlmTextReadWrite.GenerateCSV(filePath.Replace(fileName, ""), fileName, dtINQ, false, false);
}
}
#endregion FOR INQ
#region For QUO
if (ddlqoutatfileType.SelectedItem.Text == "INQ" || ddlqoutatfileType.SelectedItem.Text == "QUO")
{
OracleCommand CmdB = new OracleCommand(String.Format(#"//Select Query"
, ddlqoutatfileType.SelectedItem.Text, listItem.Value,
(ddlqoutatfileType.SelectedItem.Text.Equals("QUO") ? deInqDate.Text.ToString() : deQuoDate.Text.ToString()),
deOrderDate.Text.ToString()), con);
CmdB.CommandType = CommandType.Text;
OracleDataAdapter daQUO = new OracleDataAdapter();
DataTable dtQUO = new DataTable();
dtQUO.Columns.Add("DEPOT_CODE", typeof(string));
dtQUO.Columns.Add("ROUTE_CODE", typeof(string));
dtQUO.Columns.Add("UPLOAD_DATE", typeof(string));
dtQUO.Columns.Add("SAP_REGION_CODE", typeof(string));
dtQUO.Columns.Add("SAP_SUB_REGION_CODE", typeof(string));
dtQUO.Columns.Add("SAP_CUSTOMER_CODE", typeof(string));
dtQUO.Columns.Add("SALES_DATE", typeof(string));
dtQUO.Columns.Add("PRODUCT_CODE", typeof(string));
dtQUO.Columns.Add("ORDER_QTY", typeof(string));
dtQUO.Columns.Add("UOM_CODE", typeof(string));
dtQUO.Columns.Add("LINE_TOTAL", typeof(string));
daQUO.SelectCommand = CmdB;
daQUO.Fill(dtQUO);
if (dtQUO.Rows.Count <= 0)
{
lblQUO.Visible = true;
}
else
{
foreach (DataRow dr in dtQUO.Rows)
{
OrderSum += Convert.ToInt32(dr["ORDER_QTY"]);
}
foreach (DataRow dr in dtQUO.Rows)
{
LineSum += Convert.ToInt32(dr["LINE_TOTAL"]);
}
DataRow row = dtQUO.NewRow();
row["DEPOT_CODE"] = "TOT";
row["ORDER_QTY"] = OrderSum;
row["LINE_TOTAL"] = LineSum;
dtQUO.Rows.Add(row);
string fileName = "QUO" + listItem.Value + Order_Date_Datemodified + ".CSV";
string filePath = HttpContext.Current.Server.MapPath("~/Order_Files/" + fileName);
Almarai.AlmTextReadWrite.GenerateCSV(filePath.Replace(fileName, ""), fileName, dtQUO, false, false);
}
}
#endregion For QUO
}
}
#endregion CSV Generation
#region ZIP Generation
using (ZipFile zip = new ZipFile())
{
//string fileName = ddlqoutatfileType.SelectedItem.Text + ".csv";
string filePath = HttpContext.Current.Server.MapPath("~/Order_Files/");
zip.AlternateEncodingUsage = ZipOption.AsNecessary;
zip.AddDirectoryByName("Orders");
string directoryName = Path.GetDirectoryName(filePath);
foreach (String filename in Directory.GetFiles(directoryName, "*.csv"))
{
zip.AddFile(filename, "Orders");
}
// cookies
HttpCookie cookie = new HttpCookie("ExcelDownloadFlag");
cookie.Value = "Flag";
cookie.Expires = DateTime.Now.AddDays(1);
Response.AppendCookie(cookie);
//cookies
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.BufferOutput = false;
string zipName = String.Format("Zip_{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
HttpContext.Current.Response.ContentType = "application/zip";
HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + zipName);
zip.Save(HttpContext.Current.Response.OutputStream);
HttpContext.Current.Response.End();
}
#endregion ZIP Generation
}
ASPX:
<asp:Label ID="lblQUO" runat="server"></asp:Label>
If the request returns a file to download, it cannot also return content for the web page in the same response. The browser will treat it as either a file to download, or something to display, not both (it uses the headers to decide). A HTTP response can only have one content type.
If you want to return a message to the user when there is no data to download, then you should arrange the code so that it doesn't initiate the file download in that situation.
Currently your code is creating a zip file and setting the HTTP headers which tell the browser to treat the response as an attachment. It does this regardless of whether there is actually any data to download or not.
To prevent this behaviour, simply move that code into your else block, so it only does that when the query returned some rows:
foreach (ListItem listItem in ddlDepot.Items)
{
if (listItem.Selected)
{
OracleCommand CmdB = new OracleCommand(String.Format(#"SELECT Query"
OracleDataAdapter daBINQ = new OracleDataAdapter();
DataTable dtINQ = new DataTable();
//adding data table columns
dtINQ.Columns.Add("DEPOT_CODE", typeof(string));
dtINQ.Columns.Add("ROUTE_CODE", typeof(string));
daBINQ.SelectCommand = CmdB;
daBINQ.Fill(dtINQ);
if (dtINQ.Rows.Count <= 0)
{
//ScriptManager.RegisterStartupScript(this, GetType(), "message", "alert('No data found for Selected Inquiry date, Please select other date');", true);
lblQUO.Text = "No data found for Selected Inquiry date, Please select other date";
lblQUO.ForeColor = System.Drawing.Color.Red;
}
else
{
//calculating SUM of column
foreach (DataRow dr in dtINQ.Rows)
{
OrderSum += Convert.ToInt32(dr["ORDER_QTY"]);
}
DataRow row = dtINQ.NewRow();
row["DEPOT_CODE"] = "TOT";
row["ORDER_QTY"] = OrderSum;
//Crating CSV and storing on server
string fileName = "INQ" + listItem.Value + Order_Date_Datemodified + ".CSV";
string filePath = HttpContext.Current.Server.MapPath("~/Order_Files/" + fileName);
//using dll
Almarai.AlmTextReadWrite.GenerateCSV(filePath.Replace(fileName, ""), fileName, dtINQ, false, false);
using (ZipFile zip = new ZipFile())
{
fileName = ddlqoutatfileType.SelectedItem.Text + ".csv";
filePath = HttpContext.Current.Server.MapPath("~/Order_Files/");
zip.AlternateEncodingUsage = ZipOption.AsNecessary;
zip.AddDirectoryByName("Orders");
string directoryName = Path.GetDirectoryName(filePath);
foreach (String filename in Directory.GetFiles(directoryName, "*.csv"))
{
zip.AddFile(filename, "Orders");
}
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.BufferOutput = false;
string zipName = String.Format("Zip_{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
HttpContext.Current.Response.ContentType = "application/zip";
HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + zipName);
zip.Save(HttpContext.Current.Response.OutputStream);
HttpContext.Current.Response.End();
}
}
}
Now in the case where there's no data, the server will return a "normal" response containing the HTML generated by the aspx code, and the standard headers to go with it. This should mean that the browser takes the HTML and displays it as a web page, instead of trying to download a zip file.

How can I bind a XML web response into a dataGridView in a Windows Forms using C#?

I am working in a Plugin in Windows Forms in C#. I basically send a soap request and get a response in xml. I am simply returning the response in a message box right now but I am trying to bind the response into a datagrid view. How can I do that?
This is what my SOAP req looks like the following.
private void getEntitySummary(long entityID)
{
//Create client
myAPI.ResolvingBinding resol = new myAPI.ResolvingBinding();
//Create parameters
myAPI.EntityID[] entityIDArr = new myAPI.EntityID[1];
myAPI.EntityID entityIDitem = new myAPI.EntityID();
entityIDitem.entityID = entityID;
entityIDArr[0] = entityIDitem;
myAPI.DepthSpecifier depth = new myAPI.DepthSpecifier();
myAPI.CustomInformation customInfo = new myAPI.CustomInformation();
//Make request
myAPI.EntitySummary[] entitySummaryRes = resol.getEntitySummaries(entityIDArr, depth, customInfo);
//Handle response
foreach (myAPI.EntitySummary e in entitySummaryRes)
{
string firstName = e.bestName?.givenName;
string surName = e.bestName?.surname;
string streetName = e.bestAddress?.street1;
string city = e.bestAddress?.city;
string state = e.bestAddress?.state;
string country = e.bestAddress?.country;
string address = (streetName + " " + city + " " + state + " " + country).Trim();
string email = e.bestEmail?.emailAddress;
string number = e.bestNumber?.numberValue;
MessageBox.Show(firstName + " " + surName + ", " + address +", " + number );
// need datagridView instead of a msg box here
}
}
The code works fine and gives me response in xml format in the background. It looks something like the following:
<?xml version="1.0" encoding="UTF-8"?> <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:errdetail="http://rr.eas.ibm.com/EntityResolver/ErrorDetail" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
<getEntitySummariesResponse xmlns="http://services/">
<entitySummaries xmlns="">
<entityID>101010</entityID>
<nameCount>3</nameCount>
<numberCount>7</numberCount>
<addressCount>9</addressCount>
<emailCount>0</emailCount>
<attributeCount>6</attributeCount>
<accountCount>21</accountCount>
<roleAlertCount>447</roleAlertCount>
<relationshipCount>19</relationshipCount>
<eventAlertCount>0</eventAlertCount>
<bestName>
<identityHandle>
<internalID>222</internalID>
<externalID>333John</externalID>
<dataSourceCode>neutral</dataSourceCode>
<externalReference>333John</externalReference>
</identityHandle>
<timestamp>2016-06-28T12:24:21</timestamp>
<lastModifiedTimestamp>2010-05-28T12:24:21</lastModifiedTimestamp>
<nameID>444</nameID>
<nameTypeCode>M</nameTypeCode>
<givenName>John</givenName>
<surname>Doe</surname>
<culture>culture</culture>
</bestName>
<bestAddress>
<identityHandle>
<internalID>222</internalID>
<externalID>333John</externalID>
<dataSourceCode>neutral</dataSourceCode>
<externalReference>333John</externalReference>
</identityHandle>
<timestamp>2010-05-28T12:24:21</timestamp>
<lastModifiedTimestamp>2010-05-28T12:24:21</lastModifiedTimestamp>
<addressID>395116</addressID>
<addressTypeCode>H</addressTypeCode>
<street1>1111 East St</street1>
<city>Pikesville</city>
<state>AL</state>
<country>USA</country>
</bestAddress>
<bestNumber>
<identityHandle>
<internalID>222</internalID>
<externalID>333John</externalID>
<dataSourceCode>neutral</dataSourceCode>
<externalReference>333John</externalReference>
</identityHandle>
<timestamp>2010-05-28T12:24:21</timestamp>
<lastModifiedTimestamp>2010-05-28T12:24:21</lastModifiedTimestamp>
<numberID>6666</numberID>
<numberTypeID>2</numberTypeID>
<numberValue>123-45-6789</numberValue>
</bestNumber>
<bestAttribute xmlns:ns2="http://entity/results/" xsi:type="ns2:CharacteristicDetail">
<identityHandle>
<internalID>222</internalID>
<externalID>333John</externalID>
<dataSourceCode>neutral</dataSourceCode>
<externalReference>333John</externalReference>
</identityHandle>
<timestamp>2010-05-28T12:24:21</timestamp>
<lastModifiedTimestamp>2010-05-28T12:24:21</lastModifiedTimestamp>
<characteristicID>8888</characteristicID>
<characteristicValue>M</characteristicValue>
<characteristicTypeID>2</characteristicTypeID>
</bestAttribute>
</entitySummaries>
</getEntitySummariesResponse>
</soapenv:Body> </soapenv:Envelope>
In short, I need to bind, the name, address, and number in a dataGridView.
According to the above response, it would be :
I tried the following method but I don't understand how to get the xml response into my datagrid:
DataSet ds = new DataSet();
XmlTextReader reader = new XmlTextReader(new StringReader(xml));
ds.ReadXml(reader);
dataGridView1.DataSource = ds;
Any help would be greatly appreciated!
The ReadXml won't work because the number of nested levels on xml is too deep. You end up with lots of datatables with the data fragmented with no way of putting the data back into usable format. I will work on a solution. Will take me a few minutes.
I parsed some of the code to get a flat result. See code below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;
using System.Data;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
string response = File.ReadAllText(FILENAME);
XDocument doc = XDocument.Parse(response);
XElement root = doc.Root;
XNamespace ns = root.GetDefaultNamespace();
DataTable dt = new DataTable();
dt.Columns.Add("entityID", typeof(string));
dt.Columns.Add("nameCount", typeof(int));
dt.Columns.Add("numberCount", typeof(int));
dt.Columns.Add("addressCount", typeof(int));
dt.Columns.Add("emailCount", typeof(int));
dt.Columns.Add("attributeCount", typeof(int));
dt.Columns.Add("accountCount", typeof(int));
dt.Columns.Add("roleAlertCount", typeof(int));
dt.Columns.Add("relationshipCount", typeof(int));
dt.Columns.Add("eventAlertCount", typeof(int));
dt.Columns.Add("bestName_internalID", typeof(int));
dt.Columns.Add("bestName_externalID", typeof(string));
dt.Columns.Add("bestName_dataSourceCode", typeof(string));
dt.Columns.Add("bestName_externalReference", typeof(string));
dt.Columns.Add("bestName_timestamp", typeof(DateTime));
dt.Columns.Add("bestName_lastModifiedTimestamp", typeof(DateTime));
dt.Columns.Add("bestName_nameID", typeof(int));
dt.Columns.Add("bestName_nameTypeCode", typeof(string));
dt.Columns.Add("bestName_givenName", typeof(string));
dt.Columns.Add("bestName_surname", typeof(string));
dt.Columns.Add("bestName_culture", typeof(string));
List<XElement> entitySummaries = root.Descendants(ns + "entitySummaries").ToList();
foreach (XElement entitySummary in entitySummaries)
{
DataRow newRow = dt.Rows.Add();
string entityID = (string)entitySummary.Element(ns + "entityID");
int nameCount = (int)entitySummary.Element(ns + "nameCount");
int numberCount = (int)entitySummary.Element(ns + "numberCount");
int addressCount = (int)entitySummary.Element(ns + "addressCount");
int emailCount = (int)entitySummary.Element(ns + "emailCount");
int attributeCount = (int)entitySummary.Element(ns + "attributeCount");
int accountCount = (int)entitySummary.Element(ns + "accountCount");
int roleAlertCount = (int)entitySummary.Element(ns + "roleAlertCount");
int relationshipCount = (int)entitySummary.Element(ns + "relationshipCount");
int eventAlertCount = (int)entitySummary.Element(ns + "eventAlertCount");
XElement bestName = entitySummary.Element(ns + "bestName");
int internalID = (int)bestName.Descendants(ns + "internalID").FirstOrDefault();
string externalID = (string)bestName.Descendants(ns + "externalID").FirstOrDefault();
string dataSourceCode = (string)bestName.Descendants(ns + "dataSourceCode").FirstOrDefault();
string externalReference = (string)bestName.Descendants(ns + "externalReference").FirstOrDefault();
DateTime timestamp = (DateTime)bestName.Element(ns + "timestamp");
DateTime lastModifiedTimestamp = (DateTime)bestName.Element(ns + "lastModifiedTimestamp");
int nameID = (int)bestName.Element(ns + "nameID");
string nameTypeCode = (string)bestName.Element(ns + "nameTypeCode");
string givenName = (string)bestName.Element(ns + "givenName");
string surname = (string)bestName.Element(ns + "surname");
string culture = (string)bestName.Element(ns + "culture");
newRow.ItemArray = new object[] {
entityID,
nameCount,
numberCount,
addressCount,
emailCount,
attributeCount,
accountCount,
roleAlertCount,
relationshipCount,
eventAlertCount,
internalID,
externalID,
dataSourceCode,
externalReference,
timestamp,
lastModifiedTimestamp,
nameID,
nameTypeCode,
givenName,
surname,
culture
};
}//end foreach
datagridview1.Datasource = dt;
}
}
}

displaying every xml element in datagridview

I try to display every "package" element in datagridview. But it looks like it only show version 1.02. here is my code :
private void button1_Click(object sender, EventArgs e)
{
string path = Environment.CurrentDirectory;
DataTable dt = new DataTable();
dt.Columns.Add("version", typeof(string));
dt.Columns.Add("sha1sum", typeof(string));
dt.Columns.Add("url", typeof(string));
dt.Columns.Add("ps3_system_ver", typeof(string));
dt.Columns.Add("size", typeof(string));
XmlDocument xDoc = new XmlDocument();
xDoc.Load(path + #"\\temp\\BCES01893-ver.xml");
XDocument doc = XDocument.Load(path + #"\\temp\\BCES01893-ver.xml");
XmlNodeList p = xDoc.GetElementsByTagName("package");
for (int i = 0; i < p.Count; i++)
{
if (p.Count > 0)
{
foreach (XElement addresdm in doc.Descendants().Where(x => x.Name.LocalName == "tag"))
{
XElement avee = addresdm.Descendants("package").FirstOrDefault();
dt.Rows.Add(new object[] {
(string)avee.Attribute("version"),
(string)avee.Attribute("sha1sum"),
(string)avee.Attribute("url"),
(string)avee.Attribute("ps3_system_ver"),
(string)avee.Attribute("size"),
});
}
}
dataGridView1.DataSource = dt;
}
}
xml file :
<titlepatch status="alive" titleid="BCES01893">
<tag name="BCES01893_T359" popup="true" signoff="true" min_system_ver="03.60">
<package version="01.02" size="1315387312" sha1sum="d68d0584aa30b6d02a7aee95236f91ef43fdc11e" url="http://b0.ww.np.dl.playstation.net/tppkg/np/BCES01893/BCES01893_T359/b80952de9329a9ba/EP9001-BCES01893_00-0000000000000000-A0102-V0101-PE.pkg" ps3_system_ver="04.4000"/>
<package version="01.03" size="102857792" sha1sum="7b1c6b9dd621ed9a5ae130737bfa5a4dd386db66" url="http://b0.ww.np.dl.playstation.net/tppkg/np/BCES01893/BCES01893_T359/b80952de9329a9ba/EP9001-BCES01893_00-0000000000000000-A0103-V0100-PE.pkg" ps3_system_ver="04.4000"/>
<package version="01.04" size="223699280" sha1sum="4cedbc07c384b0f5556d5f0697b03c81376fd89d" url="http://b0.ww.np.dl.playstation.net/tppkg/np/BCES01893/BCES01893_T359/b80952de9329a9ba/EP9001-BCES01893_00-0000000000000000-A0104-V0100-PE.pkg" ps3_system_ver="04.4000"/>
</package>
</tag>
</titlepatch>
the result : https://i.ibb.co/cQJRFzj/Untitled.png
how can i make it display correctly?
You are only getting last item because following is inside for loop : dataGridView1.DataSource = dt;Move outside for loop.
Here is my code which is a little simpler.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Data;
namespace ConsoleApplication103
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
DataTable dt = new DataTable();
dt.Columns.Add("version", typeof(string));
dt.Columns.Add("sha1sum", typeof(string));
dt.Columns.Add("url", typeof(string));
dt.Columns.Add("ps3_system_ver", typeof(string));
dt.Columns.Add("size", typeof(string));
XDocument doc = XDocument.Load(FILENAME);
foreach (XElement addresdm in doc.Descendants("package"))
{
dt.Rows.Add(new object[] {
(string)addresdm.Attribute("version"),
(string)addresdm.Attribute("sha1sum"),
(string)addresdm.Attribute("url"),
(string)addresdm.Attribute("ps3_system_ver"),
(string)addresdm.Attribute("size"),
});
}
}
}
}

Create xml file with dataset like this format

Create xml file with dataset like this format-
-<_XPXML Note="" CrtTime="" CN="" DBN="" Srv="" Ver="" AppId="" Class="" IC="" Stock="" Desc="">
<_InvTrans IC="010006" Stock="1" Desc="2 " OppKind="1" Amount="744" Batch="6" Mat="108208"/>
<_InvTrans IC="010006" Stock="1" Desc="2 " OppKind="1" Amount="744" Batch="6" Mat="108208"/>
<_InvTrans IC="010006" Stock="1" Desc="2 " OppKind="1" Amount="744" Batch="6" Mat="108208"/>
</_XPXML>
If you want to create some custom xml that you can use XElement.
How to create <_XPXML Note="" CrtTime="" CN="" DBN="" Srv="" Ver="" AppId="" Class="" IC="" Stock="" Desc="">?
You can use the code below to create.
var node=new XElement("_XPXML ");
node.SetAttributeValue("Note","");
node.SetAttributeValue("CrtTime","");
// ...
// please write the Attribute
doc.Root.Add(node);
Before you use the code that you should new doc as this code
XDocument doc = new XDocument();
And you should add using System.Xml.Linq in file top.
After you set the attribute that you can save it to file.
doc.Save(xx);
The example:
XDocument doc = new XDocument();
XElement node = new XElement("_XPXML");
node.SetAttributeValue("Note", "");
var invTrans = new XElement("_InvTrans");
node.Add(invTrans);
invTrans.SetAttributeValue("IC", "010006");
doc.Add(node);
StringBuilder str = new StringBuilder();
TextWriter stream = new StringWriter(str);
doc.Save(stream);
The str is
<?xml version="1.0" encoding="utf-16"?>
<_XPXML Note="">
<_InvTrans IC="010006" />
</_XPXML>
Try following using xml linq :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication23
{
class Program
{
static void Main(string[] args)
{
DataTable dt = new DataTable("_InvTrans");
dt.Columns.Add("IC", typeof(string));
dt.Columns.Add("Stock", typeof(string));
dt.Columns.Add("Desc", typeof(string));
dt.Columns.Add("OppKind", typeof(string));
dt.Columns.Add("Amount", typeof(string));
dt.Columns.Add("Batch", typeof(string));
dt.Columns.Add("Mat", typeof(string));
dt.Rows.Add(new object[] { "010006", "1", "2 ", "1", "744", "6", "108208" });
dt.Rows.Add(new object[] { "010006", "1", "2 ", "1", "744", "6", "108208" });
dt.Rows.Add(new object[] { "010006", "1", "2 ", "1", "744", "6", "108208" });
GetXmlTable(dt);
}
static XElement GetXmlTable(DataTable dt)
{
string tableName = dt.TableName;
XElement table = new XElement(tableName);
string[] columnNames = dt.Columns.Cast<DataColumn>().Select(x => x.ColumnName).ToArray();
foreach (DataRow row in dt.AsEnumerable())
{
XElement xRow = new XElement("_InvTrans");
table.Add(xRow);
foreach (string columnName in columnNames)
{
xRow.Add(new XAttribute(columnName, row[columnName]));
}
}
return table;
}
}
}

how to extract column of data using regular expression

i am trying to write c# code to extract columns of data. my data looks like
what should be the regular expression if i want to extract "everything" "under" a column header for example "COMMAND" or "PID".
No need to use regular expression. String Split method will work. Try code like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data;
namespace ConsoleApplication53
{
class Program
{
const string FILENAME = #"c:\temp\test.txt";
static void Main(string[] args)
{
DataTable dt = new DataTable();
dt.Columns.Add("PID", typeof(int));
dt.Columns.Add("TT", typeof(string));
dt.Columns.Add("STAT", typeof(string));
dt.Columns.Add("TIME", typeof(DateTime));
dt.Columns.Add("COMMAND", typeof(string));
StreamReader reader = new StreamReader(FILENAME);
int lineCount = 0;
string inputLine = "";
while ((inputLine = reader.ReadLine) != null)
{
if (++lineCount > 2)
{
string[] inputArray = inputLine.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
dt.Rows.Add(new object[] {
int.Parse(inputArray[0]),
inputArray[1],
inputArray[2],
DateTime.Parse(inputArray[3]),
inputArray[4]
});
}
}
}
}
}

Categories