c# AXL XElement Data to datagridview - c#

I'm busy with a application that extract data from Cisco CUCM to Datagridview with AXL/SOAP.
I get only the last record in the datagridview if I put the info to a combobox I get the compleet list.
The info what I extract with AXL is:
SEP0014A815DB0D
sk0000101
SEP0022555E7E26
AKijkindevegte
SEP0018BAC8C6C5
BT101139
This is my code:
byte[] soapBytes = Encoding.UTF8.GetBytes(soap);
ServicePointManager.ServerCertificateValidationCallback += delegate { return true; };
HttpWebRequest httpRQ = (HttpWebRequest)HttpWebRequest.Create(string.Format(#"https://XXX.XXX.XXX.XXX:8443/axl/"));
httpRQ.ProtocolVersion = System.Net.HttpVersion.Version10;
httpRQ.Credentials = new NetworkCredential("user1", "password");//Callmanager gebruikersnaam / password
httpRQ.Method = "POST";
httpRQ.ContentType = "text/xml; charset=utf-8";
httpRQ.Accept = "text/xml";
httpRQ.Headers.Add("SOAPAction: 'CUCM:DB ver=" + version + "'");
httpRQ.ContentLength = soapBytes.Length;
//Send the xml soap to cucm
Stream stm = httpRQ.GetRequestStream();
stm.Write(soapBytes, 0, soapBytes.Length);
stm.Close();
//Build the xml response
XDocument responcedoc = new XDocument();
HttpWebResponse responce = httpRQ.GetResponse() as HttpWebResponse;
Stream responcedata = responce.GetResponseStream();
StreamReader responsereader = new StreamReader(responcedata);
Logging.Text += "\n---------|AXL Response|---------\n\n";
XDocument respdoc = XDocument.Load(responsereader);
Logging.Text += respdoc + "\n";
soap = null;
//fill in the combo
DevicePhone.Items.Clear();
foreach (XElement item in respdoc.Descendants("name"))
{
// DataSet ds = new DataSet();
//ds.ReadXml((string)item);
DevicePhone.Items.Add((string)item);
string ds;
strDevicePhone = ((string)item);
ds = ((string)item);
label3.Text = strDevicePhone;
try
{
DataTable jmn = new DataTable("respdoc");
dataGridView1.DataSource = jmn;
jmn.Columns.Add("name");
jmn.Columns.Add("userid");
jmn.Rows.Add((string)item);
return;
}
catch (Exception e)
{
//Interaction.MsgBox(ex.ToString());
}
Please Help
Whats do I wrong.

You're creating a new DataTable for each element and assigning this to your DataGridView.DataSource. Predictably, this will result in setting a source containing the last item.
Move the creation of your DataTable outside the loop and add the rows within it. Then assign your DataSource once after you've finished populating it.
var jmn = new DataTable("respdoc");
jmn.Columns.Add("name");
jmn.Columns.Add("userid");
foreach (var item in respdoc.Descendants("item"))
{
// ...
jmn.Rows.Add((string)item);
// ...
}
dataGridView1.DataSource = jmn;

Related

Export to excel in c# showing error and not downloading the excel

My code, where the collection of values retrived from DB and that values stored one by one in datatable.And loading that dataTable to worksheet of Excel
var dataTable = new DataTable();
var sb = new StringBuilder();
var resultvalues=methodtogetvalues() ;
if (resultvalues!= null && resultvalues.Count > 0)
{
var icount = 1;
foreach (var values in resultvalues)
{
if (icount == 1)
{
sb.Append(values.Id);
icount += 1;
}
dataTable.Columns.Add("ID");
dataTable.Rows.Add(values.Id);
}
}
var firstName = context.Request.Params["FirstName"];
var lastName = context.Request.Params["LastName"];
var fileName = firstName+lastName+"_ProgramStatusHistory_"+DateTime.Now;
var tempText = Convert.ToString(sb);
var workBook = new ExpertXls.ExcelLib.ExcelWorkbook(ExpertXls.ExcelLib.ExcelWorkbookFormat.Xlsx_2007);
var accessedRangeStyle = workBook.Styles.AddStyle("ΑccessedRangeStyle");
accessedRangeStyle.Font.Size = 10;
accessedRangeStyle.Font.Bold = true;
accessedRangeStyle.Alignment.VerticalAlignment = ExpertXls.ExcelLib.ExcelCellVerticalAlignmentType.Center;
accessedRangeStyle.Alignment.HorizontalAlignment = ExpertXls.ExcelLib.ExcelCellHorizontalAlignmentType.Left;
workBook.Worksheets.AddWorksheet();
var workSheet = workBook.Worksheets[0];
workSheet.LoadDataTable(dataTable, 1, 1, true);
workSheet.AutofitColumns();
workBook.Worksheets.RemoveWorksheet("Sheet2");
workBook.Worksheets.RemoveWorksheet("Sheet3");
workBook.Worksheets.RemoveWorksheet("Sheet4");
workBook.LicenseKey = "gqmworCworOysrWitKyyorGzrLOwrLu7u7s=";
context.Response.Clear();
context.Response.Buffer = true;
context.Response.Charset = "";
context.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
context.Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
using (var MyMemoryStream = new System.IO.MemoryStream())
{
workBook.Save(MyMemoryStream);
MyMemoryStream.WriteTo(context.Response.OutputStream);
context.Response.Flush();
context.Response.End();
}
This code simply shows an alert box with the error message "Error".
I don't understand whats wrong. Can anyone redirect me with correct way.
I would move this line of code outside the using statement:
context.Response.End();
also show your catch block. It's unlikely to be giving just a message of 'Error' I would suggest placing a breakpoint in the catch block and looking inside the error object.

Trying to figure out how to fetch data from the database and output to an excel file. Not sure what to try next

Ok so here is my problem. I am trying to fetch data from a database and output all the data to an excel spread sheet or even a text document.
Whichever is easier.
Eventually i want it to be in excel though.
I am pretty new to this and have been looking for multiple answers for going on three weeks.
Any help is appreciated.
//Export to excel
[HttpPost]
public ActionResult Download()
{
List<string> persons = new List<string> { };
using (SqlConnection connection = new SqlConnection("Data Source=(local);Initial Catalog=WebApplication1;Integrated Security=SSPI"))
using (SqlCommand cmd = new SqlCommand("SELECT RMAFormModels AS cusName FROM RMAFormModels ", connection))
{
connection.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
// Check is the reader has any rows at all before starting to read.
if (reader.HasRows)
{
// Read advances to the next row.
while (reader.Read())
{
RMAFormModels p = new RMAFormModels();
// To avoid unexpected bugs access columns by name.
p.cusName = reader.GetString(reader.GetOrdinal("cusName"));
//p.FirstName = reader.GetString(reader.GetOrdinal("FirstName"));
// int middleNameIndex = reader.GetOrdinal("MiddleName");
// If a column is nullable always check for DBNull...
//if (!reader.IsDBNull(middleNameIndex))
// {
// p.MiddleName = reader.GetString(middleNameIndex);
// }
// p.LastName = reader.GetString(reader.GetOrdinal("LastName"));
// persons.Add(p);
}
}
}
}
// Use persons here...
// var name = collection.cusName;
//var date = collection.DatePurchased;
//var dateIssued = collection.DateIssued;
/* List<Lookup> collection = new List<Lookup>();
var grid = new System.Web.UI.WebControls.GridView();
grid.DataSource = collection;
grid.DataBind();
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=ExcelTest.xlsx");
Response.ContentType = "application/vnd.ms-excel";
//Response.ContentType = "application / vnd.openxmlformats - officedocument.spreadsheetml.sheet";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
grid.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
*/
//customer = new cusName();
// cusName = "Tod";
var string_with_your_data = persons ;
//List<>.ToCharArray(string_with_your_data);
var byteArray = Encoding.ASCII.GetBytes(string_with_your_data);
var stream = new MemoryStream(byteArray);
return File(stream, "text/plain", "your_file_name.txt"); // this goes to a file.txt
}
}`
It looks like you want this to be a web page that exports to excel. I recommend using an ApiController method that outputs an HttpResultMessage. Make the content be a CSV text representation of the table. Make the Content-Type be text/csv and add a file name to the http header section. In Windows anyone who has CSV files associated with Excel will have the option to open the downloaded file and it will automatically open into excel.
I have done this with ClosedXML nuget Package. I hope that it will be useful to you too.
add ClosedXML nuget Package to your project.
You will need to importClosedXML.Excel namespace
3.Export action
[HttpPost]
public FileResult Export()
{
DataTable dt = new DataTable("Grid");
dt.Columns.AddRange(new DataColumn[4] { new DataColumn("CustomerId"),
new DataColumn("ContactName"),
new DataColumn("City"),
new DataColumn("Country") });
var customers = GetCustomers(); //get customer from database;
foreach (var customer in customers)
{
dt.Rows.Add(customer.CustomerID, customer.ContactName, customer.City, customer.Country);
}
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(dt);
using (MemoryStream stream = new MemoryStream())
{
wb.SaveAs(stream);
return File(stream.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Grid.xlsx");
}
}
}
4.on the View
#using (Html.BeginForm("Export", "Home", FormMethod.Post))
{
<input type="submit" value="Export"/>
}

Mono for Android: XML data to spinner

My XML Example:
<Table diffgr:id="Table17" msdata:rowOrder="16">
<IdRec>17</IdRec>
<FieldId>1213</FieldId>
<FieldDesc>Equipment</FieldDesc>
<FieldType>OptionBOX</FieldType>
<isReadOnly>false</isReadOnly>
<FieldValue>388</FieldValue>
<FieldTextValue>B - satisfactory</FieldTextValue>
<OptBox_Options>
<Options>
<myOPT FieldValue="387" FieldTextValue="A - good"/>
<myOPT FieldValue="388" FieldTextValue="B - satisfactory"/>
<myOPT FieldValue="389" FieldTextValue="C - needs change"/>
<myOPT FieldValue="390" FieldTextValue="D - deal"/>
</Options>
</OptBox_Options>
</Table>
My problem
The above xml data comes from a webservice. I have no problem with any field other than OptBox_Options which is a field I need to use to populate my spinner. Ergo I need to get the string from OptBox_Options->Options->myOpt(FieldTextValue) (for example: ).
How to access this data? What would be the best approach. If you can't give me a direct solution I would be satisfied with a link to noob friendly C# tutorial on the subject.
Isssue Resolved
I transformed my string to XML, then converted it to a dataset and just cycled through it... Code below :)
List<string> entries = new List<string>();
String rawXML = item.OptBox_Options;
StringReader stream = null;
XmlTextReader reader = null;
DataSet xmlDS = new DataSet();
stream = new StringReader(rawXML);
// Load the XmlTextReader from the stream
reader = new XmlTextReader(stream);
xmlDS.ReadXml(reader);
DataSet myOPTvalues = new DataSet();
myOPTvalues = xmlDS;
foreach (DataRow row in myOPTvalues.Tables[0].Rows)
{
var optItem = new PrevzemSpin();
optItem.FieldValue = row["FieldValue"].ToString();
if (optItem.FieldValue.Equals("")) optItem.FieldValue = null;
optItem.FieldTextValue = row["FieldTextValue"].ToString();
if (optItem.FieldTextValue.Equals("")) optItem.FieldTextValue = null;
entries.Add(optItem.FieldTextValue);
SpinnerValue.Tag = optItem.FieldValue;
}
Use xml parsing techniques such as XmlPullParser ,SAX parser or DOM parser.
XML Pull parser is the parser recommended in the developer's site of android Here is a tutorial for Pull parser .
I transformed my string to XML, then converted it to a dataset and just cycled through it... Code below :)
List<string> entries = new List<string>();
String rawXML = item.OptBox_Options;
StringReader stream = null;
XmlTextReader reader = null;
DataSet xmlDS = new DataSet();
stream = new StringReader(rawXML);
// Load the XmlTextReader from the stream
reader = new XmlTextReader(stream);
xmlDS.ReadXml(reader);
DataSet myOPTvalues = new DataSet();
myOPTvalues = xmlDS;
foreach (DataRow row in myOPTvalues.Tables[0].Rows)
{
var optItem = new PrevzemSpin();
optItem.FieldValue = row["FieldValue"].ToString();
if (optItem.FieldValue.Equals("")) optItem.FieldValue = null;
optItem.FieldTextValue = row["FieldTextValue"].ToString();
if (optItem.FieldTextValue.Equals("")) optItem.FieldTextValue = null;
entries.Add(optItem.FieldTextValue);
SpinnerValue.Tag = optItem.FieldValue;
}

How do I use lucene.net for searching file content?

I am currently using lucene.net to search the content of files for keyword search. I am able to get the results correctly but I have a scenario where I need to display the keywords found in a particular file.
There are two different files containing "karthik" and "steven", and if I search for "karthik and steven" I am able to get both the files displayed. If I search only for "karthik" and "steven" separately, only the respective files are getting displayed.
When I search for "karthik and steven" simultaneously I get both the files in the result as I am displaying the filename alone, and now I need to display the particular keyword found in that particular file as a record in the listview.
Public bool StartSearch()
{
bool bResult = false;
Searcher objSearcher = new IndexSearcher(mstrIndexLocation);
Analyzer objAnalyzer = new StandardAnalyzer();
try
{
//Perform Search
DateTime dteStart = DateTime.Now;
Query objQuery = QueryParser.Parse(mstrSearchFor, "contents", objAnalyzer);
Hits objHits = objSearcher.Search(objQuery, objFilter);
DateTime dteEnd = DateTime.Now;
mlngTotalTime = (Date.GetTime(dteEnd) - Date.GetTime(dteStart));
mlngNumHitsFound = objHits.Length();
//GeneratePreviewText(objQuery, mstrSearchFor,objHits);
//Generate results - convert to XML
mstrResultsXML = "";
if (mlngNumHitsFound > 0)
{
mstrResultsXML = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><Results>";
//Loop through results
for (int i = 0; i < objHits.Length(); i++)
{
try
{
//Get the next result
Document objDocument = objHits.Doc(i);
//Extract the data
string strPath = objDocument.Get("path");
string strFileName = objDocument.Get("name");
if (strPath == null) { strPath = ""; }
string strLastWrite = objDocument.Get("last_write_time");
if (strLastWrite == null)
strLastWrite = "unavailable";
else
{
strLastWrite = DateField.StringToDate(strLastWrite).ToShortDateString();
}
double dblScore = objHits.Score(i) * 100;
string strScore = String.Format("{0:00.00}", dblScore);
//Add results as an XML row
mstrResultsXML += "<Row>";
//mstrResultsXML += "<Sequence>" + (i + 1).ToString() + "</Sequence>";
mstrResultsXML += "<Path>" + strPath + "</Path>";
mstrResultsXML += "<FileName>" + strFileName + "</FileName>";
//mstrResultsXML += "<Score>" + strScore + "%" + "</Score>";
mstrResultsXML += "</Row>";
}
catch
{
break;
}
}
//Finish off XML
mstrResultsXML += "</Results>";
//Build Dataview (to bind to datagrid
DataSet objDS = new DataSet();
StringReader objSR = new StringReader(mstrResultsXML);
objDS.ReadXml(objSR);
objSR = null;
mobjResultsDataView = new DataView();
mobjResultsDataView = objDS.Tables[0].DefaultView;
}
//Finish up
objSearcher.Close();
bResult = true;
}
catch (Exception e)
{
mstrError = "Exception: " + e.Message;
}
finally
{
objSearcher = null;
objAnalyzer = null;
}
return bResult;
}
Above is the code i am using for search and the xml i am binding to the listview, now i need to tag the particular keywords found in the respective document and display it in the listview as recordsss,simlar to the below listview
No FileName KeyWord(s)Found
1 Test.Doc karthik
2 Test2.Doc steven
i hope u guys undesrtood the question,
This depends on how your documents were indexed. You'll need to extract the original content, pass it through the analyzer to get the indexed tokens, and check which matches the generated query.
Just go with the Highlighter.Net package, part of contrib, which does this and more.

converting xml document to data table in C#

I'm trying to read a simple webservice (REST) and populate a drop down box in my C# desktop application. I;m using .net 2.0
Following is my web service return xml
<sections type="array">
<section>
<name>Standing</name>
<created-at type="datetime">2011-10-23T23:17:54+05:30</created-at>
<updated-at type="datetime">2011-10-23T23:17:54+05:30</updated-at>
<id type="integer">1</id>
<status type="integer">1</status>
<service-charge type="float">0.0</service-charge>
</section>
<section>
<name>VIP</name>
<created-at type="datetime">2011-10-30T11:27:05+05:30</created-at>
<updated-at type="datetime">2011-10-30T11:27:05+05:30</updated-at>
<id type="integer">2</id>
<status type="integer">1</status>
<service-charge type="float">10.0</service-charge>
</section>
and in the following code I'm trying to convert the xml document to a data table
public DataTable getSections() {
String url = "http://<site_url>/sections.xml";
DataTable t = new DataTable();
HttpHandler handle = new HttpHandler();
StreamReader sr = handle.executeGET(url);
String xml = "";
while (sr.Peek() >= 0)
{
xml += sr.ReadLine();
}
XmlDataDocument doc = new XmlDataDocument();
doc.LoadXml(xml);
XmlReader xmlReader = new XmlNodeReader(doc);
DataSet ds = new DataSet();
ds.ReadXml(xmlReader);
t = ds.Tables[0];
return t;
}
and in the last segment I'm trying to bind it to my drop down box (cmbSections)
DataTable t = sec.getSections();
cmbSections.DataSource = t;
cmbSections.DisplayMember = "name";
cmbSections.ValueMember = "id";
But I'm getting the following error
Cannot bind to the new display member.
Parameter name: newDisplayMember
What am i missing here, please help, I'm new to C# world
Use extension method to support conversion of XElement to Datatable. You can add this method to any of your utility classes. Make sure the class is static.
public static class XElementExtensions
{
public static DataTable ToDataTable(this XElement element)
{
DataSet ds = new DataSet();
string rawXml = element.ToString();
ds.ReadXml(new StringReader(rawXml));
return ds.Tables[0];
}
public static DataTable ToDataTable(this IEnumerable<XElement> elements)
{
return ToDataTable(new XElement("Root", elements));
}
}
How to use
//Add logic to store xml data in file or string & read accordingly here.
string file = Server.MapPath("~/Data.xml");
XDocument document = XDocument.Load(file);
var query = from b in document.Elements("sections").Elements("section")
select b;
DataTable table = query.ToDataTable();
Simple way to convert XML to DataSet:
StringReader strr = new StringReader(strXML);
XmlTextReader xtr = new XmlTextReader(strr);
YourTypeDataSet dstest = new YourTypeDataSet();
dstest.ReadXml(xtr);
if (dstest.Tables.Count > 0) ...
for correct conversion, you replace your type DataSet in place of:
DataSet dstest = new DataSet();
;)
I got it working with the following code, but I'm not quit sure if this is the correct way to do it
(This parse the above same xml)
public DataTable getSections() {
String url = "http://<site_url>/sections.xml/sections.xml";
DataTable t = new DataTable();
t.Columns.Add("id", typeof(String));
t.Columns.Add("name", typeof(String));
HttpHandler handle = new HttpHandler();
StreamReader sr = handle.executeGET(url);
String xml = "";
List<String> id = new List<string>();
List<String> name = new List<string>();
while (sr.Peek() >= 0)
{
xml += sr.ReadLine();
}
XmlDataDocument doc = new XmlDataDocument();
doc.LoadXml(xml);
XmlReader xmlReader = new XmlNodeReader(doc);
while (xmlReader.Read()){
if (xmlReader.IsStartElement()) {
String b = xmlReader.Name;
switch (xmlReader.Name) {
case "sections":
break;
case "section":
break;
case "id":
if (xmlReader.Read())
{
id.Add(xmlReader.Value.Trim());
}
break;
case "name":
if (xmlReader.Read())
{
name.Add(xmlReader.Value.Trim());
}
break;
}
}
}
int counter = 0;
foreach (String i in id) {
DataRow r = t.NewRow();
r["id"] = i;
r["name"] = name[counter];
t.Rows.Add(r);
counter += 1;
}
return t;
}
Thanks for the comments :D
Your valuable comments are always welcome

Categories