I am currently working on a project where I have send values ("PFOID" and "Quantity") to a stored procedure in a XML format.
the required XML format is something like this
<string>
<PFOID>04676723-2afb-49ff-9fa1-0131cabb407c</PFOID>
<Quantity>90</Quantity>
</string>
My code looks like this.
internal void UpdateQuantity(PFO pfo)
{
string pfoIds = "<PFO>" + "<PFOID>" + pfo.PFOId.ToString() + "</PFOID>" + " " + "<Quantity>" + pfo.PlannedQty.ToString() + "</Quantity>" + "</PFO>";
//pfoIds = pfoIds.Replace("<","<").Replace(">",">");
// string pfoIds = pfo.PFOId.ToString() + pfo.PlannedQty.ToString();
//XDocument d = new XDocument(pfoIds,
// new XElement
// ("PFO",
// new XElement("PFOID", pfo.PFOId.ToString()),
// new XElement("Quantity", pfo.PlannedQty.ToString())
// )
// );
List<string> pfoIdList = new List<string>();
pfoIdList.Add(pfoIds);
XmlSerializer serializer = new XmlSerializer(pfoIdList.GetType());
StringBuilder xmlString = new StringBuilder();
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
settings.Encoding = new UTF8Encoding();
XmlWriter writer = XmlWriter.Create(new StringWriter(xmlString), settings);
//XDocument xDoc = XDocument.Load(pfoIds);
//XmlNode xNode = xmlDoc.SelectSingleNode("PFOID", "Quantity");
//string onlyvalue = xNode.InnerText;
//System.Xml.Linq.XDocument xDoc = new XDocument();
////System.Xml.Linq.XNode xNode =new System.Xml.Linq.XDocument();
//XmlDocument xmlDoc = new XmlDocument();
//xmlDoc.Load(pfoIds);
//XmlNode xNode = xmlDoc.SelectSingleNode("PFOID", "Quantity");
//string onlyvalue = xNode.InnerText;
//serializer.WriteObject(writer, SelectedStoreIds.ToArray());
serializer.Serialize(writer, pfoIdList);
if (writer != null)
writer.Close();
xmlString.ToString();
{
Context.PFOValidateUpdateData(xmlString.ToString(), WebContext.Current.User.UserID, op =>
{
IsProcessing = false;
if (ValidateUpdateCompleted != null)
ValidateUpdateCompleted(this, EventArgs.Empty);
}, null);
}
}
}
}
I tried Using XmlDocument and XmlNodes but unfortunately silverlight system.xml assembly dont have these extensions in its library.
Can anyone help me out with this please, I would really be great full to you. Thank you very much.
It looks like this... Sorry I used white spaces between & lt;
& lt; PFOID>" 04676723-2afb-49ff-9fa1-0131cabb407c & lt;/ PFOID &
gt;" & lt; Quantity & gt;" 90 & lt;/Quantity & gt;"
I don't know if it is a possible solution for you, but you can try to do something like this.
// Create a DataSet with one table containing two columns.
DataSet dataSet = new DataSet("dataSet");
DataTable table = dataSet.Tables.Add("string");
table.Columns.Add("PFOID", typeof(string));
table.Columns.Add("Quantity", typeof(value));
DataRow row;
row = table.NewRow();
row["PFOID"]= "04676723-2afb-49ff-9fa1-0131cabb407c";
row["Quantity"]= 90;
table.Rows.Add(row);
// Display the DataSet contents as XML.
Console.WriteLine(dataSet.GetXml());
Related
I am trying to build a WebPage that includes "Rating of Site". Instead of using Database i am storing two variables to compute Avg of Rating in xml file as
<?xml version="1.0" encoding="utf-8"?>
<data>
<RatingCount>6</RatingCount>
<RatingTotal>17</RatingTotal>
</data>
Here is my Logic Code Both On the Page Load and AJAX Rating Control
Page_Load()
string rootPath = Server.MapPath("~/");
if (File.Exists(rootPath + "data.xml"))
{
XmlDocument xdoc = new XmlDocument();
xdoc.Load(rootPath + "data.xml");
XmlNode ratingCount = xdoc.DocumentElement.SelectSingleNode("/data/RatingCount");
XmlNode ratingTotal = xdoc.DocumentElement.SelectSingleNode("/data/RatingTotal");
string rating = ratingTotal.InnerText;
string count = ratingCount.InnerText;
if (Convert.ToInt32(count) >= 1)
{
double resultRating = Convert.ToSingle(rating) / Convert.ToSingle(count);
Rating1.CurrentRating = Convert.ToInt32(resultRating);
lblerror.Text = resultRating + " Rating in " + count + " Totals Votes";
}
else
{
lblerror.Text = "No Votes Till Now";
}
}
Rating_Control()
string rootPath = Server.MapPath("~/");
if (File.Exists(rootPath + "data.xml"))
{
XmlDocument xdoc = new XmlDocument();
xdoc.Load(rootPath + "data.xml");
XmlNode ratingCount = xdoc.DocumentElement.SelectSingleNode("/data/RatingCount");
XmlNode ratingTotal = xdoc.DocumentElement.SelectSingleNode("/data/RatingTotal");
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
XmlWriter xwrite = XmlWriter.Create(rootPath + #"data.xml", settings);
xwrite.WriteStartDocument();
xwrite.WriteStartElement("data");
string r = (Convert.ToInt32(ratingCount.InnerText) + 1).ToString();
string t = (Convert.ToInt32(ratingTotal.InnerText) + Convert.ToInt32(e.Value)).ToString();
xwrite.WriteElementString("RatingCount", r);
xwrite.WriteElementString("RatingTotal", t);
xwrite.WriteEndElement();
xwrite.WriteEndDocument();
xwrite.Flush();
xwrite.Close();
}
else
{
lblerror.Text = "File Doesnt Exists";
}
Any Help will be Appreciated!
I am putting xml code into a RichTextBox and user can make changes here when the program is running. I want to save the content of the RichTextBox inside xml-file, during its creation.
Note:
I am already creating an xml file. I want to save the content of the RichTextBox into the xml-file, during its creation.
saveFileDialog1.Filter = "XML files(.xml)|*.xml|all Files(*.*)|*.*";
saveFileDialog1.FilterIndex = 1;
saveFileDialog1.ShowDialog();
if (saveFileDialog1.FileName != "")
{
gridView1.AddNewRow();
XmlDocument document = new XmlDocument();
XmlElement anaeleman = document.CreateElement("onbase-certificate");
//i want to do it here
TextWriter yaz = new StreamWriter(saveFileDialog1.FileName,true);
yaz.Write(f2.richTextBox1.Text);
yaz.Close();
XmlElement alteleman = document.CreateElement("licences");
for (int i = 0; i < Convert.ToInt32(gridView1.DataRowCount); i++)
{
XmlElement elemanlar = document.CreateElement("licence");
XmlElement eleman = document.CreateElement("name");
eleman.InnerText = "![CDATA[" + gridView1.GetRowCellValue(i, "productname").ToString() + "]";
elemanlar.AppendChild(eleman);
eleman = document.CreateElement("code");
eleman.SetAttribute("sig", "1");
eleman.InnerText = gridView1.GetRowCellValue(i, "producttype").ToString();
elemanlar.AppendChild(eleman);
eleman = document.CreateElement("count");
eleman.InnerText = gridView1.GetRowCellValue(i, "count").ToString();
eleman.SetAttribute("sig", "1");
elemanlar.AppendChild(eleman);
if (gridView1.GetRowCellValue(i, "pilotdate").ToString() != "")
{
eleman = document.CreateElement("pilotdate");
eleman.InnerText = gridView1.GetRowCellValue(i, "pilotdate").ToString();
eleman.SetAttribute("sig", "1");
elemanlar.AppendChild(eleman);
}
alteleman.AppendChild(elemanlar);
}
//anaeleman.AppendChild(alteleman);
anaeleman.AppendChild(alteleman);
document.AppendChild(anaeleman);
document.Save(saveFileDialog1.FileName);
}
Instead of using XmlDocument you can use plain StringBuilder.
var builder = new StringBuilder();
builder.AppendLine("<onbase-certificate>");
builder.AppendLine(f2.richTextBox1.Text);
builder.AppendLine("<licenses>");
for (int i = 0; i < Convert.ToInt32(gridView1.DataRowCount); i++)
{
builder.AppendLine("<license>");
builder.AppendLine("<name>![CDATA[" + gridView1.GetRowCellValue(i, "productname").ToString() + "]</name>");
builder.AppendLine("<code sig=\"1\">");
builder.AppendLine(gridView1.GetRowCellValue(i, "count").ToString(););
builder.AppendLine("</code>");
// ...
builder.AppendLine("</license>");
}
builder.AppendLine("</licenses>");
builder.AppendLine("</onbase-certificate>");
File.WriteAllText(saveFileDialog1.FileName, builder.ToString());
I am not sure what you want to do. Do you want to save the text from richtextbox to xml element anaeleman? If yes, have you tried this:?
anaeleman.InnerText = f2.richTextBox1.Text
Brand new to C#. I am working on a ASP MVC app. I am exporting data to an XML and all of that works correctly. The problem I am having is I can't figure out how to make the data output correctly. Basically I am grabbing data from a column which is a number for example 12 based on an ID as well as the logged in users ID.
This example pulls 3 rows based on the controllerID as well as userID, and the numbers are as follows: 12, 12, 11. In my XML I would like it to display 1 - 35. They way it is now it is 1-12, 1-12, 1-11. The data is correct, However can I take the numbers returned from my list, add them all together and display them as 1-35.
Here is the code:
public ActionResult ExportToXML()
{
var lClist = db.LightControllers.Where(x => x.userID == LoggedInUser.id).OrderBy(x => x.controllerID).ToList();
Networks n = new Networks();
n.computer = "computer1";
foreach(var i in lClist)
{
int numU = Convert.ToInt32(i.NumUniverses);
for (int j = 0; j < numU; j++)
{
network netToAdd = new network();
netToAdd.NetworkType = "E131";
netToAdd.ComPort = i.ipaddress;
netToAdd.BaudRate = (j + 1).ToString();
netToAdd.MaxChannels = "510";
n.network.Add(netToAdd);
}
}
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
string path = Server.MapPath("~/XMLFiles/");
string filename = "x_networks.xml";
string filepath = Path.Combine(path, filename);
if (System.IO.File.Exists(filepath))
{
System.IO.File.Delete(filepath);
}
XmlSerializer serial = new XmlSerializer(typeof(viewmodels.Networks));
StreamWriter writer = new StreamWriter(filepath);
serial.Serialize(writer, n, ns);
writer.Close();
return File(filepath, "application/xml", filename);
}
Here is an example of the current xml output.
<?xml version="1.0" encoding="utf-8"?>
<Networks computer="xlights">
<network NetworkType="E131" ComPort="192.168.1.110" BaudRate="1" MaxChannels="510" />
<network NetworkType="E131" ComPort="192.168.1.110" BaudRate="2" MaxChannels="510" />
...
</Networks>
Try this:
public ActionResult ExportToXML()
{
var lClist = db.LightControllers.Where(x => x.userID == LoggedInUser.id).OrderBy(x => x.controllerID).ToList();
int baudIterator = 1;
Networks n = new Networks();
n.computer = "computer1";
foreach(var i in lClist)
{
int numU = Convert.ToInt32(i.NumUniverses);
for (int j = 0; j < numU; j++)
{
network netToAdd = new network();
netToAdd.NetworkType = "E131";
netToAdd.ComPort = i.ipaddress;
netToAdd.BaudRate = baudIterator.ToString();
netToAdd.MaxChannels = "510";
n.network.Add(netToAdd);
baudIterator++;
}
}
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
string path = Server.MapPath("~/XMLFiles/");
string filename = "x_networks.xml";
string filepath = Path.Combine(path, filename);
if (System.IO.File.Exists(filepath))
{
System.IO.File.Delete(filepath);
}
XmlSerializer serial = new XmlSerializer(typeof(viewmodels.Networks));
StreamWriter writer = new StreamWriter(filepath);
serial.Serialize(writer, n, ns);
writer.Close();
return File(filepath, "application/xml", filename);
}
I want to write XML Log File from two or more Application into LogData.xml file. while running the one application it creats the LogData.xml file correctly but at the same time both the allpication are run simulteniously and try to write the LogData.xml file it gives me an error message such as The process cannot access the file Log_Data.xml' because it is being used by another process.
I use this code
public void WriteXmlLog(string logType, string logFlag, string logModule, string logLocation, string logText, string logStackTrace)
{
if (!File.Exists(_logFilePath))
{
//File.WriteAllText(_logFilePath, "<?xml version='1.0' encoding='utf-8' standalone='yes'?>\r\n<AppXmlLogWritter></AppXmlLogWritter>");
XmlTextWriter textWritter = new XmlTextWriter(_logFilePath, null);
textWritter.WriteStartDocument();
textWritter.WriteStartElement("AppXmlLogWritter");
textWritter.WriteEndElement();
textWritter.Close();
}
XmlDocument xmlDoc = new XmlDocument();
using (FileStream fileStream = new FileStream(_logFilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
{
string currentDateTime = DateTime.Now.ToString("yyyyMMddHHmmss");
xmlDoc.Load(fileStream);
XmlElement newelement = xmlDoc.CreateElement("LogData");
XmlElement xmlLogID = xmlDoc.CreateElement("LogID");
XmlElement xmlLogDateTime = xmlDoc.CreateElement("LogDateTime");
XmlElement xmlLogType = xmlDoc.CreateElement("LogType");
XmlElement xmlLogFlag = xmlDoc.CreateElement("LogFlag");
XmlElement xmlLogApplication = xmlDoc.CreateElement("LogApplication");
XmlElement xmlLogModule = xmlDoc.CreateElement("LogModule");
XmlElement xmlLogLocation = xmlDoc.CreateElement("LogLocation");
XmlElement xmlLogText = xmlDoc.CreateElement("LogText");
XmlElement xmlLogStackTrace = xmlDoc.CreateElement("LogStackTrace");
xmlLogID.InnerText = _logIDPrefix + currentDateTime + randomNumber;
xmlLogDateTime.InnerText = currentDateTime;
xmlLogType.InnerText = ((LogTypes)Convert.ToInt32(logType)).ToString();
xmlLogFlag.InnerText = logFlag;
xmlLogApplication.InnerText = _logApplication;
xmlLogModule.InnerText = logModule;
xmlLogLocation.InnerText = logLocation;
xmlLogText.InnerText = logText;
xmlLogStackTrace.InnerText = logStackTrace;
newelement.AppendChild(xmlLogID);
newelement.AppendChild(xmlLogDateTime);
newelement.AppendChild(xmlLogType);
newelement.AppendChild(xmlLogFlag);
newelement.AppendChild(xmlLogApplication);
newelement.AppendChild(xmlLogModule);
newelement.AppendChild(xmlLogLocation);
newelement.AppendChild(xmlLogText);
xmlDoc.DocumentElement.AppendChild(newelement);
//}
//finally
//{
// objMutex.ReleaseMutex();
//}
}
xmlDoc.Save(_logFilePath);
}
I want to achive this without Threading
Perhaps try implementing logging with NLog in both applications and set as the target the same xml.
i am able to retrieve data from sharepoint
com.sharepoint2.Lists lists = new Lists();
lists.Credentials = new System.Net.NetworkCredential("user", "pwd", "domain");
lists.Url = "http://sharepoint2.company.com/sites/mysite/_vti_bin/Lists.asmx";
XmlNode ndQuery = xmlDoc.CreateNode(XmlNodeType.Element, "Query", "");
XmlNode ndViewFields = xmlDoc.CreateNode(XmlNodeType.Element, "ViewFields", "");
XmlNode ndQueryOptions = xmlDoc.CreateNode(XmlNodeType.Element, "QueryOptions", "");
XmlNode listitems = lists.GetListItems("MyList", null, ndQuery, ndViewFields, null,ndQueryOptions, null);
i now have this huge XML blog with all of my data. Is there any easy way to convert this to a datatable so i treat this like a matrix to loop through each row ??
i tried something like this but it doesn't seem to work:
System.IO.StringReader sr = new System.IO.StringReader(listitems.OuterXml);
XmlTextReader tr = new XmlTextReader(sr);
DataSet ds = new DataSet("resultDataSet");
ds.ReadXml(tr);
Ahh, xml returned from GetListItems is almos the same as SPListItemCollection.Xml. I have an extension method that converts this XML into datatable.
You can just try to use ConvertZRowToRegularXml method on your returned XML - and you would get back an XML that DataTable understands.
Credits for the solution goes to Vincent Rothwell.
public static class SPListItemCollectionExtensions
{
public static readonly string xsltFromZRowToXml =
"<xsl:stylesheet version=\"1.0\" " +
"xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" " +
"xmlns:s=\"uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882\" " +
"xmlns:z=\"#RowsetSchema\">" +
"<s:Schema id=\"RowsetSchema\"/>" +
"<xsl:output method=\"xml\" omit-xml-declaration=\"yes\" />" +
"<xsl:template match=\"/\">" +
"<xsl:text disable-output-escaping=\"yes\"><rows></xsl:text>" +
"<xsl:apply-templates select=\"//z:row\"/>" +
"<xsl:text disable-output-escaping=\"yes\"></rows></xsl:text>" +
"</xsl:template>" +
"<xsl:template match=\"z:row\">" +
"<xsl:text disable-output-escaping=\"yes\"><row></xsl:text>" +
"<xsl:apply-templates select=\"#*\"/>" +
"<xsl:text disable-output-escaping=\"yes\"></row></xsl:text>" +
"</xsl:template>" +
"<xsl:template match=\"#*\">" +
"<xsl:text disable-output-escaping=\"yes\"><</xsl:text>" +
"<xsl:value-of select=\"substring-after(name(), 'ows_')\"/>" +
"<xsl:text disable-output-escaping=\"yes\">></xsl:text>" +
"<xsl:value-of select=\".\"/>" +
"<xsl:text disable-output-escaping=\"yes\"></</xsl:text>" +
"<xsl:value-of select=\"substring-after(name(), 'ows_')\"/>" +
"<xsl:text disable-output-escaping=\"yes\">></xsl:text>" +
"</xsl:template>" +
"</xsl:stylesheet>";
public static DataTable GetFullDataTable(this SPListItemCollection itemCollection)
{
DataSet ds = new DataSet();
string xmlData = ConvertZRowToRegularXml(itemCollection.Xml);
if (string.IsNullOrEmpty(xmlData))
return null;
using (System.IO.StringReader sr = new System.IO.StringReader(xmlData))
{
ds.ReadXml(sr, XmlReadMode.Auto);
if (ds.Tables.Count == 0)
return null;
return ds.Tables[0];
}
}
static string ConvertZRowToRegularXml(string zRowData)
{
XslCompiledTransform transform = new XslCompiledTransform();
XmlDocument tidyXsl = new XmlDocument();
try
{
//Transformer
tidyXsl.LoadXml(Balticovo.SharePoint.Extensions. SPListItemCollectionExtensions.xsltFromZRowToXml);
transform.Load(tidyXsl);
//output (result) writers
using (System.IO.StringWriter sw = new System.IO.StringWriter())
{
using (XmlTextWriter tw = new XmlTextWriter(sw))
{
//Source (input) readers
using (System.IO.StringReader srZRow = new System.IO.StringReader(zRowData))
{
using (XmlTextReader xtrZRow = new XmlTextReader(srZRow))
{
//Transform
transform.Transform(xtrZRow, null, tw);
return sw.ToString();
}
}
}
}
}
catch
{
return null;
}
}
}
You should pass the XmlNodeType to the XmlTextReader like this:
DataSet ds=new DataSet();
using(var reader=new XmlTextReader(listItems.OuterXml,XmlNodeType.Element,null))
{
ds.ReadXml(reader);
}
Concering the object model vs the web services: The usual way to create web parts, event receivers etc. is to use Sharepoint's server object model. The web services are not used that much, because they are a bit cumbersome. In Sharepoint 2010 a new client object model and the WCF Data Services makes things a LOT easier and the old ASMX web services are considered deprecated.
BUT Sharepoint Online is actually a 2007 version that doesn't allow server-side code, so AJAX and the ASMX web services are the only way to customize and communicate with a Sharepoint Online site. This has brought the ASMX services to the front just as they became deprecated. Go figure.