How to get xml file from isolated in wp8 - c#

I Try to get Xml file and Bind to list
Here is my Xml File
- <data>
- <Bookmarkdata>
<Bookname>TheNfame</Bookname>
<Bookid>5a1df538-6e91-4a39-819d-e043c9881fb7</Bookid>
<Pageno>0</Pageno>
</Bookmarkdata>
- <Bookmarkdata>
<Bookname>TheNfame</Bookname>
<Bookid>5a1df538-6e91-4a39-819d-e043c9881fb7</Bookid>
<Pageno>1</Pageno>
</Bookmarkdata>
</data>
This is my code
private void GetBookMarkData()
{
var doc = new XDocument();
XDocument xdoc= new XDocument();
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
{
try
{
if (store.FileExists("BookmarkFile.xml"))
{
using (var sr = new StreamReader(new IsolatedStorageFileStream("BookmarkFile.xml", FileMode.OpenOrCreate, store)))
{
doc = XDocument.Load(sr);
// xdoc = XDocument.Load(sr);
var data = from query in doc.Descendants("data")
select new Bookmarkdata
{
Bookname = (string)query.Element("Bookname"),
Bookid = (string)query.Element("Bookid"),
BookPath = (string)query.Element("BookPath"),
Pageno = (int)query.Element("Pageno")
};
Bookmark_List.ItemsSource = data;
}
}
}
catch
(Exception ex) { }
}
But in Catch return a error
Value cannot be null.
Parameter name: element
In my code doc = XDocument.Load(sr);
i have get a xml data dubag time but in next line is error Please Help

Your LINQ-to-XML query is a bit off. query variable represent <data> element here :
var data = from query in doc.Descendants("data")
select new Bookmarkdata
{
Bookname = (string)query.Element("Bookname"),
Bookid = (string)query.Element("Bookid"),
BookPath = (string)query.Element("BookPath"),
Pageno = (int)query.Element("Pageno")
};
so it doesn't have direct child named Bookname, Bookid, BookPath, or Pageno. I guess you want to select from <Bookmarkdata> elements instead :
var data = from query in doc.Descendants("Bookmarkdata")
select new
{
Bookname = (string)query.Element("Bookname"),
Bookid = (string)query.Element("Bookid"),
BookPath = (string)query.Element("BookPath"),
Pageno = (int)query.Element("Pageno")
};

Related

Reading XML Response from envelope event notification

In my MakeEnvelope method, I have added an event notification as follows:
var en = new EventNotification
{
Url = "<Listener URL>",
LoggingEnabled = "true",
RequireAcknowledgment = "true",
EnvelopeEvents = new List<EnvelopeEvent>
{
new EnvelopeEvent
{
EnvelopeEventStatusCode = "Completed",
IncludeDocuments = "true"
},
new EnvelopeEvent
{
EnvelopeEventStatusCode = "Delivered",
IncludeDocuments = "false"
},
new EnvelopeEvent
{
EnvelopeEventStatusCode = "Sent",
IncludeDocuments = "false"
}
}
};
envelopeDefinition.EventNotification = en;
I get the following XML response (I removed the Names and Emails, and changed the Guids):
<?xml version="1.0" encoding="utf-8"?><DocuSignEnvelopeInformation xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.docusign.net/API/3.0"><EnvelopeStatus><RecipientStatuses><RecipientStatus><Type>Signer</Type><Email>someEmail#email.com</Email><UserName>SomeUserName</UserName><RoutingOrder>1</RoutingOrder><Sent>2021-04-28T14:14:41.163</Sent><Delivered>2021-04-28T14:14:54.997</Delivered><Signed>2021-04-28T14:14:59.73</Signed><DeclineReason xsi:nil="true" /><Status>Completed</Status><RecipientIPAddress>IP Address</RecipientIPAddress><ClientUserId>The ClientId</ClientUserId><CustomFields /><TabStatuses><TabStatus><TabType>SignHere</TabType><Status>Signed</Status><XPosition>938</XPosition><YPosition>1169</YPosition><TabLabel>Sign Here</TabLabel><TabName>SignHere</TabName><TabValue /><DocumentID>3</DocumentID><PageNumber>1</PageNumber></TabStatus></TabStatuses><AccountStatus>Active</AccountStatus><RecipientId>f571daaf-cd2c-4fge-a72e-d32277929305</RecipientId></RecipientStatus><RecipientStatus><Type>Signer</Type><Email>anotherEmail.Email.com</Email><UserName>Another Name</UserName><RoutingOrder>1</RoutingOrder><Sent>2021-04-28T14:14:41.503</Sent><DeclineReason xsi:nil="true" /><Status>Sent</Status><RecipientIPAddress /><CustomFields /><TabStatuses><TabStatus><TabType>SignHere</TabType><Status>Active</Status><XPosition>196</XPosition><YPosition>1169</YPosition><TabLabel>Sign Here</TabLabel><TabName>SignHere</TabName><TabValue /><DocumentID>3</DocumentID><PageNumber>1</PageNumber></TabStatus></TabStatuses><AccountStatus>Active</AccountStatus><RecipientId>1eb9d346-33ae-4444-b5f1-be30f8bcf041</RecipientId></RecipientStatus></RecipientStatuses><TimeGenerated>2021-04-28T14:15:03.3011225</TimeGenerated><EnvelopeID>3c9281c7-3345-44ac-9c4f-3d39274c49f4</EnvelopeID><Subject>Please sign this document</Subject><UserName>User Name</UserName><Email>Users Email Address Here</Email><Status>Sent</Status><Created>2021-04-28T14:14:40.41</Created><Sent>2021-04-28T14:14:41.557</Sent><ACStatus>Original</ACStatus><ACStatusDate>2021-04-28T14:14:40.41</ACStatusDate><ACHolder>Account Holders name</ACHolder><ACHolderEmail>Account Holders Email</ACHolderEmail><ACHolderLocation>DocuSign</ACHolderLocation><SigningLocation>Online</SigningLocation><SenderIPAddress>Senders IP Address</SenderIPAddress><EnvelopePDFHash /><CustomFields /><AutoNavigation>true</AutoNavigation><EnvelopeIdStamping>true</EnvelopeIdStamping><AuthoritativeCopy>false</AuthoritativeCopy><DocumentStatuses><DocumentStatus><ID>3</ID><Name>PG Document</Name><TemplateName /><Sequence>1</Sequence></DocumentStatus></DocumentStatuses></EnvelopeStatus></DocuSignEnvelopeInformation>
I was having issues parsing the response, so I created a console application to parse the xml string, and using the response xml shown above. The following is the code that I used to parse.
static void Main(string[] args)
{
string strXML = GetXML();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(strXML);
string xpath = "DocuSignEnvelopeInformation/EnvelopeStatus";
var nodes = xmlDoc.SelectNodes(xpath);
foreach (XmlNode childrenNode in nodes)
{
Console.WriteLine(childrenNode.SelectSingleNode("//status").Value);
}
Console.Read();
}
nodes is always empty.
What am I missing here?
Thank you in advance.
I was able to get it to work by using the namespace it was using.
var ns = new XmlNamespaceManager(xmlDoc.NameTable);
ns.AddNamespace("docusign", "http://www.docusign.net/API/3.0");
var envelopeId = xmlDoc.SelectSingleNode("//docusign:EnvelopeID", ns);
var status = xmlDoc.SelectSingleNode("//docusign:Status", ns);
I changed the method and I am able to get the values:
Request.InputStream.Position = 0;
var xmlDoc = new XmlDocument();
xmlDoc.Load(Request.InputStream);
var ns = new XmlNamespaceManager(xmlDoc.NameTable);
ns.AddNamespace("docusign", "http://www.docusign.net/API/3.0");
var envelopeId = xmlDoc.SelectSingleNode("//docusign:EnvelopeID", ns);
var status = xmlDoc.SelectSingleNode("//docusign:EnvelopeStatus/docusign:Status", ns);
if (envelopeId == null || String.IsNullOrEmpty(envelopeId.InnerText) || status == null || string.IsNullOrEmpty(status.InnerText)) return;
if (status.InnerText.ToLower() == "completed")
{
// Update the Document Status
var extra = _uow.JobExtraRepository.GetByEnvelopeId(envelopeId.InnerText);
extra.StatusId = (int)ExtraJobStatus.Completed;
Save();
var docBytes = xmlDoc.SelectSingleNode("//docusign:docBytes", ns);
}

add two group into one group in c#

I have two groups like below, theyh have different data. Based on both I need to create an xml file .
How can I write a for-loop for both groups and generate a single xml file?
var groups = checkFile.AsEnumerable().GroupBy(x => new { DocNum = x.Field<int>("orderid"), Type = x.Field<string>("Type"), ProdName = x.Field<string>("ProdName"), Status = x.Field<string>("Status"), productno = x.Field<string>("productno"), uom = x.Field<string>("uom"), customer = x.Field<string>("customer"), remark = x.Field<string>("remark"), U_JobNumber = x.Field<string>("U_JobNumber"), U_SalesPerson = x.Field<string>("U_SalesPerson"), U_POnum = x.Field<string>("U_POnum"), U_JobType = x.Field<string>("U_JobType"), PlannedQty = x.Field<decimal>("PlannedQty"), OriginNum = x.Field<int?>("OriginNum"), orderdate = x.Field<DateTime>("orderdate"), duedate = x.Field<DateTime>("duedate"), DocTotal = x.Field<decimal>("DocTotal") });
var groups2 = checkFile2.AsEnumerable().GroupBy(x => new { DocNum = x.Field<int>("DocNum") });
//now i need to take both group data inside this loop to print the file
foreach (var group in groups)
{
var stringwriter = new StringWriter();
using (var xmlWriter = XmlWriter.Create(stringwriter, new XmlWriterSettings { Indent = true }))
{
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("Root");
xmlWriter.WriteEndElement();
}
var xml = stringwriter.ToString();
XmlDocument docSave = new XmlDocument();
docSave.LoadXml(stringwriter.ToString());
docSave.Save(System.IO.Path.Combine(#SystemSettings.ImportBankStatementPendingFolderPath, "DocNum -" + group.Key.DocNum + ".xml"));
count++;
}
Try following :
DataTable checkFile = new DataTable();
var groups = checkFile.AsEnumerable().GroupBy(x => new
{
DocNum = x.Field<int>("orderid"),
Type = x.Field<string>("Type"),
ProdName = x.Field<string>("ProdName"),
Status = x.Field<string>("Status"),
productno = x.Field<string>("productno"),
uom = x.Field<string>("uom"),
customer = x.Field<string>("customer"),
remark = x.Field<string>("remark"),
U_JobNumber = x.Field<string>("U_JobNumber"),
U_SalesPerson = x.Field<string>("U_SalesPerson"),
U_POnum = x.Field<string>("U_POnum"),
U_JobType = x.Field<string>("U_JobType"),
PlannedQty = x.Field<decimal>("PlannedQty"),
OriginNum = x.Field<int?>("OriginNum"),
orderdate = x.Field<DateTime>("orderdate"),
duedate = x.Field<DateTime>("duedate"),
DocTotal = x.Field<decimal>("DocTotal")
});
DataTable checkFile2 = new DataTable();
//now i need to take both group data inside this loop to print the file
foreach (var group in groups)
{
List<DataRow> groups2 = checkFile2.AsEnumerable().Where(x => group.Key.DocNum == x.Field<int>("DocNum")).ToList();
}

Need help retrieving XML data using Linq

I am trying to retrieve data from an XML file and return the parsed data in a list. Depending on what I use to access the data (Element or Attributes) I either get null (in case of Element) or something I cannot decipher (in case of Attributes).
XML Looks like this:
<DATA_RESPONSE>
<HEADER>
<MSGID>IS20101P:091317125610:98::34:0</MSGID>
</HEADER>
<DATA>
<ROW ID='IS20101P' PE_NAME='APP-029' PE_ID='4' CODE='4829' DATA='5,1,500,1' />
<ROW ID='IS20101P' PE_NAME='APPS-029' PE_ID='4' CODE='4829' DATA='4,1,500,1' />
...
</DATA>
<SUMMARY>
</SUMMARY>
<ERRORS>
</ERRORS>
</DATA_RESPONSE>
I am using the following to get the data. I read the file and store XML in a string and call a method with this string as argument:
public static Hashtable GetIDSData(string sXMLString)
{
Hashtable result = new Hashtable();
result.Add("Success", false);
result.Add("ErrorMessage", "");
result.Add("ID", "");
result.Add("PE_NAME", "");
result.Add("PE_ID", "");
result.Add("CODE", "");
result.Add("DATA", "");
xmlDoc.InnerXml = sXMLString;
XmlElement root = xmlDoc.DocumentElement;
XDocument doc = XDocument.Parse(sXMLString);
XmlNode node = xmlDoc.SelectSingleNode("DATA_RESPONSE/DATA");
if (node != null)
{
var AddressInfoList = doc.Root.Descendants("ROW").Select(Address => new
{
ID = Address.Attributes("ID")?.ToString(),
PEName = Address.Attributes("PE_NAME")?.ToString(),
PEID = Address.Attributes("PE_ID")?.ToString(),
Code = Address.Attributes("CODE")?.ToString(),
Data = Address.Attributes("DATA")?.ToString(),
}).ToList();
foreach (var AddressInfo in AddressInfoList)
{
if (string.IsNullOrEmpty(AddressInfo.Code))
{
result["Success"] = false;
result["ErrorMessage"] = "Invalid Code; code is empty.";
}
else
{
result["Success"] = true;
result["ErrorMessage"] = "";
result["ID"] = AddressInfo.ID;
result["PE_NAME"] = AddressInfo.PEName;
result["PE_ID"] = AddressInfo.PEID;
result["CODE"] = AddressInfo.Code;
result["DATA"] = AddressInfo.Data;
}
}
return result;
}
In Linq section, if I use Address.Element("ID").Value, I get null returned.
There is no namespace used in XML.
First off, the GetIDSData() method does not compile as is, because at the line xmlDoc.InnerXml = sXMLString, xmlDoc has not been defined.
I'm assuming you want xmlDoc to be an XmlDocument loaded with the contents of the sXMLString parameter, so I'm changing that line to:
XmlDocument xmlDoc = new XmlDocument {InnerXml = sXMLString};
Also, your root variable is never used, so I removed it for clarity.
Now as for the main part of your question, given your current syntax, you are calling .ToString() on a collection of attributes, which is obviously not what you want. To fix this, when you're iterating the AddressInfoList, You want to fetch the attribute values like:
ID = Address.Attributes("ID")?.Single().Value
or
ID = address.Attribute("ID")?.Value
...rather than Address.Attributes("ID")?.ToString() as you have above.
You are not selecting values of attributes. In your code you are selecting attributes. Not sure what are you trying to achieve, but here is my modified version of your code that loads all elements into DataTable
public static DataTable GetIDSData(string sXMLString)
{
DataTable result = new DataTable();
result.Columns.Add("Success");
result.Columns.Add("ErrorMessage");
result.Columns.Add("ID");
result.Columns.Add("PE_NAME");
result.Columns.Add("PE_ID");
result.Columns.Add("CODE");
result.Columns.Add("DATA");
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.InnerXml = sXMLString;
XmlElement root = xmlDoc.DocumentElement;
XDocument doc = XDocument.Parse(sXMLString);
XmlNode node = xmlDoc.SelectSingleNode("DATA_RESPONSE/DATA");
if (node != null)
{
var AddressInfoList = doc.Root.Descendants("ROW").Select(Address => new
{
ID = Address.Attributes("ID").Select(i=>i.Value) ,
PEName = Address.Attributes("PE_NAME").Select(i=>i.Value),
PEID = Address.Attributes("PE_ID").Select(i=>i.Value),
Code = Address.Attributes("CODE").Select(i=>i.Value),
Data = Address.Attributes("DATA").Select(i=>i.Value),
}).ToList();
AddressInfoList.ForEach(e =>
{
e.Code.ToList().ForEach(c =>
{
DataRow row = result.NewRow();
if (!string.IsNullOrEmpty(c))
{
row["Success"] = true;
row["ErrorMessage"] = "";
row["ID"] = e.ID.First();
row["PE_NAME"] = e.PEName.First();
row["PE_ID"] = e.PEID.First();
row["CODE"] = e.Code.First();
row["DATA"] = e.Data.First();
}
else
{
row["Success"] = false;
row["ErrorMessage"] = "Invalid Code; code is empty.";
}
result.Rows.Add(row);
});});
result.Dump();
return result;
}
return result;
}
And this is the result that you will get in your datatable.
ID = Address.Attributes("ID")?.ToString(),
You want to use Attribute(name) (without s) instead:
ID = Address.Attributes("ID")?.Value,

Trouble Fetching Value in Variable

Basically here's my code which I'm having trouble with. Insanely new to mongoDB and would love to understand how to get values out of a JSON string that is returns in the variable 'line'.
public string get_data()
{
var client = new MongoClient();
var db = client.GetDatabase("test");
var collection = db.GetCollection<BsonDocument>("metacorp");
var cursor = collection.Find("{'movie_name' : 'Hemin'}").ToCursor();
var line = "";
foreach (var document in cursor.ToEnumerable())
{
using (var stringWriter = new StringWriter())
using (var jsonWriter = new JsonWriter(stringWriter))
{
var context = BsonSerializationContext.CreateRoot(jsonWriter);
collection.DocumentSerializer.Serialize(context, document);
line = stringWriter.ToString();
}
}
var js = new JavaScriptSerializer();
var d = js.Deserialize<dynamic>(line);
var a = d["movie_name"];
return line;
}
This is the output I get if I return line:
{ "_id" : ObjectId("58746dcafead398e4d7233f5"), "movie_name" : "Hemin"
}
I want to be able to fetch the value 'Hemin' into 'a'.
I know this is not what you're asking for but since you're using the c# driver then I would recommend the following. Assumes you have a c# class corresponding to metacorp collection or at least a serializer that handles it. Hope it helps.
var client = new MongoClient();
var db = client.GetDatabase("test");
var collection = db.GetCollection<MetaCorp>("metacorp");
var m = collection.SingleOrDefault(x => x.Movie_Name == "Hemin"); // Assuming 0 or 1 with that name. Use Where otherwise
var movieName = "Not found";
if(m!= null)
movieName = m.Movie_Name;
You could have your dto class for movie ans just fetch the data from collection:
public class Movie
{
public ObjectId Id { get; set; }
public string movie_name { get; set;}
}
...
var client = new MongoClient();
var db = client.GetDatabase("test");
var collection = db.GetCollection<BsonDocument>("metacorp");
var movies = collection.Find(x=>x.movie_name == "Hemin").ToEnumerable();

How to get value from a specific child element in XML using XmlReader

Here is the XML
<?xml version="1.0" encoding="UTF-8"?>
<Data_Speed>
<Tech ID = "UMTS">
<Coverage ID="Dense_Urban">
<DownLoad_Speed>10</DownLoad_Speed>
<Upload_Speed>20</Upload_Speed>
</Coverage>
<Coverage ID="Urban">
<DownLoad_Speed>30</DownLoad_Speed>
<Upload_Speed>40</Upload_Speed>
</Coverage>
<Coverage ID="SubUrban">
<DownLoad_Speed>50</DownLoad_Speed>
<Upload_Speed>60</Upload_Speed>
</Coverage>
</Tech>
<Tech ID = "UMTS900">
<Coverage ID="Dense_Urban">
<DownLoad_Speed>11</DownLoad_Speed>
<Upload_Speed>12</Upload_Speed>
</Coverage>
<Coverage ID="Urban">
<DownLoad_Speed>13</DownLoad_Speed>
<Upload_Speed>14</Upload_Speed>
</Coverage>
<Coverage ID="SubUrban">
<DownLoad_Speed>15</DownLoad_Speed>
<Upload_Speed>16</Upload_Speed>
</Coverage>
</Tech>
<Tech ID = "4G800">
<Coverage ID="Dense_Urban">
<DownLoad_Speed>30</DownLoad_Speed>
<Upload_Speed>42</Upload_Speed>
</Coverage>
<Coverage ID="Urban">
<DownLoad_Speed>50</DownLoad_Speed>
<Upload_Speed>34</Upload_Speed>
</Coverage>
<Coverage ID="SubUrban">
<DownLoad_Speed>45</DownLoad_Speed>
<Upload_Speed>46</Upload_Speed>
</Coverage>
<Coverage ID="Rural">
<DownLoad_Speed>47</DownLoad_Speed>
<Upload_Speed>48</Upload_Speed>
</Coverage>
<Coverage ID="Variable">
<DownLoad_Speed>15</DownLoad_Speed>
<Upload_Speed>52</Upload_Speed>
</Coverage>
<Coverage ID="Outdoor">
<DownLoad_Speed>25</DownLoad_Speed>
<Upload_Speed>22</Upload_Speed>
</Coverage>
</Tech>
</Data_Speed>
So how could I get value of DownLoad_Speed> & UpLoad_Speed> element by given Coverage ID Urban> and Tech ID UMTS900>? Say, if I give tech id value = "UMTS900" and coverage id value "Urban", I'd like to have string value dwnload_speed = 13 and Upload_Speed = 14 as result.
Using Linq to Xml
XDocument doc = XDocument.Load(filepath);
//ex...
string technology = "UMTS900";
string coverage = "Dense_Urban";
var result = doc.Descendants("Tech")
.Where(x=> (string)x.Attribute("ID") == technology)
.Elements("Coverage")
.Where(x=>(string)x.Attribute("ID")== coverage)
.Select(x=> new
{
Dowload_Speed = (string)x.Element("DownLoad_Speed"),
Upload_Speed = (string)x.Element("Upload_Speed")
});
Check this Demo
You need to open XML document
XmlDocument _document = new XmlDocument();
byte[] bytes = File.ReadAllBytes(filePath);
string xml = Encoding.UTF8.GetString(bytes);
try
{
_document.LoadXml(xml);
}
catch (XmlException e)
{
//exception handling
}
var doc = (XmlDocument)_document.CloneNode(true);
XmlNode node = doc.GetElementsByTagName("your child node name");
Once you get your node then you can do necessary thing with it
string techId = "UMTS900";
string coverageId = "SUBURBAN";
int downloadSpeed = 0;
int uploadSpeed = 0;
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(#"C:\....\DataSpeed.xml");
XmlNodeList techTags = xmlDoc.GetElementsByTagName("Tech");
foreach (XmlNode techTag in techTags)
{
if (techTag.Attributes["ID"].Value.Equals(techId,StringComparison.OrdinalIgnoreCase))
{
XmlNodeList coverageTags = techTag.ChildNodes;
foreach (XmlNode coverageTag in coverageTags)
{
if (coverageTag.Attributes["ID"].Value.Equals(coverageId, StringComparison.OrdinalIgnoreCase))
{
downloadSpeed =Convert.ToInt16(coverageTag.ChildNodes[0].InnerText);
uploadSpeed = Convert.ToInt16(coverageTag.ChildNodes[1].InnerText);
break;
}
}
break;
}
}
if (downloadSpeed == 0 && uploadSpeed == 0)
{
Console.WriteLine("Specified Tech Id and Coverage Id not found");
}
else
{
Console.WriteLine("Download Speed is {0}. Upload Speed is {1}.",downloadSpeed,uploadSpeed);
}
Here is solution using XmlReader with xml linq
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication4
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XmlReader reader = XmlReader.Create(FILENAME);
string id = "UMTS900";
object coverages = null;
while (!reader.EOF)
{
if (reader.Name != "Tech")
{
reader.ReadToFollowing("Tech");
}
if (!reader.EOF)
{
XElement tech = (XElement)XElement.ReadFrom(reader);
if((string)tech.Attribute("ID") == id)
{
coverages = tech.Descendants("Coverage").Select(x => new
{
id = (string)x.Attribute("ID"),
downLoad_Speed = (int)x.Element("DownLoad_Speed"),
upLoad_Speed = (int)x.Element("Upload_Speed"),
}).ToList();
break;
}
}
}
}
}
}

Categories