LINQ to XML - Nothing is binding? - c#

I am trying to parse from XML, but for some reason nothing is being disaplyed in my text boxes that I have binding for the variables.
I havae tried al sorts of variation sof Xdocuemnt or Xelement, but it doesn't seem to work. The XML structure seems fairly straight forward, so I can't figure out what is going wrong.
Any help would be appreciated.
edit************
All working now. Thanks for our help.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Xml.Linq;
namespace TradeMe
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
WebClient Trademe = new WebClient();
Trademe.DownloadStringCompleted += new DownloadStringCompletedEventHandler(Trademe_DownloadStringCompleted);
Trademe.DownloadStringAsync(new Uri ("http://api.trademe.co.nz/v1/Search/General.xml?search_string=" + TradeSearch.Text));
}
void Trademe_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error != null)
return;
var r = XDocument.Parse(e.Result);
// Declare the namespace
XNamespace ns = "http://api.trademe.co.nz/v1";
listBox1.ItemsSource = from TM in r.Root.Descendants(ns + "Listing")
select new TradeItem
{
//ImageSource = TM.Element(ns + "Listing").Element(ns + "PictureHref").Value,
Message = TM.Element(ns + "Title").Value,
UserName = TM.Element(ns + "Region").Value
};
}
public class TradeItem
{
public string UserName { get; set; }
public string Message { get; set; }
public string ImageSource { get; set; }
}
}
}
XML looks like this.
<SearchResults xmlns="http://api.trademe.co.nz/v1" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<TotalCount>12723</TotalCount>
<Page>1</Page>
<PageSize>50</PageSize>
- <List>
- <Listing>
<ListingId>399739762</ListingId>
<Title>Playstation 3 320GB Slim going at $1 Reserve</Title>
<Category>0202-6205-6207-</Category>
<StartPrice>1.0000</StartPrice>
<StartDate>2011-08-14T22:52:28.833Z</StartDate>
<EndDate>2011-08-21T08:45:00Z</EndDate>
<ListingLength i:nil="true" />
<HasGallery>true</HasGallery>
<MaxBidAmount>400.0000</MaxBidAmount>
<AsAt>2011-08-18T19:33:41.4561556Z</AsAt>
<CategoryPath>/Gaming/PlayStation-3/Consoles</CategoryPath>
<PictureHref>http://images.trademe.co.nz/photoserver/thumb/27/183787627.jpg</PictureHref>
<RegionId>2</RegionId>
<Region>Auckland</Region>
<BidCount>137</BidCount>
<IsReserveMet>true</IsReserveMet>
<HasReserve>true</HasReserve>
<NoteDate>1970-01-01T00:00:00Z</NoteDate>
<ReserveState>Met</ReserveState>
<PriceDisplay>$400.00</PriceDisplay>
</Listing>

Try this:
// Declare the namespace
XNamespace ns = "http://api.trademe.co.nz/v1";
listBox1.ItemsSource = from TM in r.Root.Descendants(ns+"List")
select new TradeItem
{
ImageSource = TM.Element(ns+"Listing")
.Element(ns+"PictureHref").Value,
Message = TM.Element(ns+"PageSize").Value,
UserName = TM.Element(ns+"SearchResults").Element(ns+"Page").Value
};

Nothing is matching because you did not specify the namespace. See the sample code at MSDN, repeated here:
XElement root = XElement.Parse(
#"<Root xmlns='http://www.adventure-works.com'>
<Child>1</Child>
<Child>2</Child>
<Child>3</Child>
<AnotherChild>4</AnotherChild>
<AnotherChild>5</AnotherChild>
<AnotherChild>6</AnotherChild>
</Root>");
XNamespace aw = "http://www.adventure-works.com";
IEnumerable<XElement> c1 =
from el in root.Elements(aw + "Child")
select el;
Console.WriteLine("Result set follows:");
foreach (XElement el in c1)
Console.WriteLine((int)el);
Console.WriteLine("End of result set");

Related

Find category's parameter's and combine them in the right order

This code filters elements of certain category and finds and concatenates parameters although what needed is something a little more complex.
First of all, a person needs to be able to choose a category (out of a drop down list) or search and find the necessary ones.
And the second thing is that a user is supposed to specify what parameters he would like to combine (we have shared parameters txt fyi) and choose the order in which they are going to follow one another. Any resource on it or something similar to it would help greatly!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.UI.Selection;
namespace CombineParameters
{
[Transaction(TransactionMode.Manual)]
public class Class : IExternalCommand
{
public Result Execute(ExternalCommandData commandData,
ref string message,
ElementSet elements)
{
UIApplication uiapp = commandData.Application;
UIDocument uidoc = uiapp.ActiveUIDocument;
//Application app = uiapp.Application;
Document doc = uidoc.Document;
//Create Filtered Element Collector and Filter
FilteredElementCollector collector = new FilteredElementCollector(doc);
ElementCategoryFilter filter = new ElementCategoryFilter(BuiltInCategory.OST_DuctFitting);
//Applying Filter
IList <Element> ducts = collector.WherePasses(filter).WhereElementIsNotElementType().ToElements();
foreach (Element e in ducts)
{
//Get Parameter values
string parameterValue1 = e.LookupParameter("AA").AsString();
string parameterValue2 = e.LookupParameter("BB").AsString();
string parameterValue3 = e.LookupParameter("CC").AsString();
string newValue = parameterValue1 + "-" + parameterValue2 + "-" + parameterValue3;
using (Transaction t = new Transaction(doc, "Set Parameter name"))
{
t.Start();
e.LookupParameter("DD").Set(newValue).ToString();
t.Commit();
}
}
return Result.Succeeded;
}
}
}
You want to combine user selected parameters in a specific order? Why dont you use a simple windows form gui.
Example
command.cs
#region Namespaces
using Autodesk.Revit.ApplicationServices;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace combineParameters
{
[Transaction(TransactionMode.Manual)]
public class Command : IExternalCommand
{
public Result Execute(
ExternalCommandData commandData,
ref string message,
ElementSet elements)
{
UIApplication uiapp = commandData.Application;
UIDocument uidoc = uiapp.ActiveUIDocument;
Application app = uiapp.Application;
Document doc = uidoc.Document;
Form1 form = new Form1(doc);
//Show Dialouge form
form.ShowDialog();
return Result.Succeeded;
}
}
}
Forms1.cs
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace combineParameters
{
public partial class Form1 : System.Windows.Forms.Form
{
//Class variable
Document revitDoc { get; set; }
public Form1(Document doc)
{
InitializeComponent();
this.revitDoc = doc;
//Create a list of the parameters you want your user to choose from
List<string> stringParameters = new List<string>
{
"textParameter1",
"textParameter2",
"textParameter3",
"textParameter4"
};
//Add list to comboboxes on form
foreach (string parameterName in stringParameters)
{
comboBox1.Items.Insert(0, parameterName);
comboBox2.Items.Insert(0, parameterName);
comboBox3.Items.Insert(0, parameterName);
}
}
private void button1_Click(object sender, EventArgs e)
{
FilteredElementCollector collector = new FilteredElementCollector(revitDoc);
ElementCategoryFilter filter = new ElementCategoryFilter(BuiltInCategory.OST_DuctFitting);
//Applying Filter
IList<Element> ducts = collector.WherePasses(filter).WhereElementIsNotElementType().ToElements();
using (Transaction t = new Transaction(revitDoc, "Set Parameter name"))
{
//Use a try and catch for transactions
try
{
t.Start();
foreach (Element duct in ducts)
{
//Get Parameter values
string parameterValue1 = duct.LookupParameter(comboBox1.Text).AsString();
string parameterValue2 = duct.LookupParameter(comboBox2.Text).AsString();
string parameterValue3 = duct.LookupParameter(comboBox3.Text).AsString();
string newValue = parameterValue1 + "-" + parameterValue2 + "-" + parameterValue3;
//do not need .ToString() when setting parameter
duct.LookupParameter("NewParameter").Set(newValue);
}
t.Commit();
}
//Catch with error message
catch (Exception err)
{
TaskDialog.Show("Error", err.Message);
t.RollBack();
}
}
}
}
}
Snip of this example inside Revit:
Example photo

The type or namespace name 'Utility' does not exist in the namespace 'Aspose.Cells' (are you missing an assembly reference?)

Heyyy.. I'm facing a pickle at the moment.
I need to develop a program and one of it many functions is that it could convert JSON files into CSV files..
Here's what I have :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using Aspose;
using Aspose.Cells;
namespace WpfApplication1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
string str = File.ReadAllText(#"C:\cpi\log\V510ResultsInfo\cpi001.json");
Aspose.Cells.Workbook workbook = new Aspose.Cells.Workbook();
Aspose.Cells.Cells cells = workbook.Worksheets[0].Cells;
Aspose.Cells.Utility.JsonLayoutOptions importOptions = new
Aspose.Cells.Utility.JsonLayoutOptions();
importOptions.ConvertNumericOrDate = true;
importOptions.ArrayAsTable = true;
importOptions.IgnoreArrayTitle = true;
importOptions.IgnoreObjectTitle = true;
Aspose.Cells.Utility.JsonUtility.ImportData(str, cells, 0, 0, importOptions);
workbook.Save(#"C:\cpi\log\V510ResultsInfo\convertedjson.csv");
}
}
}
The problem is 'Utility' in 'Aspose.Cells.Utility' .. Been breaking my head searching online but it seems that there's nothing much going on about this..
All I know is that 'Aspose.Cells.Utility.JsonLayoutOptions' is in the 'Aspose.Cells.Utility' namespace which falls in the Aspose.Cells.dll.. There's nothing wrong with the DLL everything is great.. Just that the error is still there :
Error Message : The type or namespace name 'Utility' does not exist in the namespace 'Aspose.Cells' (are you missing an assembly reference?)
adding to the provided answer of jayrag I would like to say, that Apsose.Cells.Utility seems to be a newer namespace and therefore it's not available for older versions of Aspose. I just checked it for the version 17 and there it is definitely not available. I also couldn't find any alternative method inside Aspose.Cells which could help you. It simply seems that the json support is still quite new and to use it you would need to upgrade the license. In the light of the prices for aspose you should probably go with a work-around. Hope that helps a bit.
Cheers!
i dont think you need Aspose for create csv
Try this:
private void Button_Click(object sender, RoutedEventArgs e)
{
string json = File.ReadAllText(#"C:\cpi\log\V510ResultsInfo\cpi001.json");
var model = JsonConvert.DeserializeObject<MyModel>(json, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
InsertRecordInCsv(model, "convertedjson");
}
public static void InsertRecordInCsv<T>(T model, string fileName)
{
string targetFolder = #"C:\cpi\log\V510ResultsInfo\";//fileSaveFolderName
if (!Directory.Exists(targetFolder))
{
Directory.CreateDirectory(targetFolder);
}
string targetPath = Path.Combine(targetFolder, fileName + ".csv");
if (!File.Exists(targetPath))
{
var fs = new FileStream(targetPath, FileMode.Create);
fs.Close();
string csvHeader = string.Empty;
foreach (PropertyInfo info in typeof(T).GetProperties())
{
csvHeader += (!string.IsNullOrEmpty(csvHeader) ? "," : string.Empty) + info.Name;
}
csvHeader += Environment.NewLine;
File.AppendAllText(targetPath, csvHeader);
}
StringBuilder sbData = new StringBuilder();
string csvModel = string.Empty;
foreach (PropertyInfo info in typeof(T).GetProperties())
{
string value = GetPropValue(model, info.Name) != null ? GetPropValue(model, info.Name).ToString() : string.Empty;
sbData.Append("\"" + value.Replace("\"", "\"\"") + "\",");
}
sbData.Replace(",", Environment.NewLine, sbData.Length - 1, 1);
File.AppendAllText(targetPath, sbData.ToString());
}
public static object GetPropValue(object src, string propName)
{
if (src.GetType().GetProperty(propName) != null)
return src.GetType().GetProperty(propName).GetValue(src, null);
return new object();
}

Parse Big XML file using XMLReader

I have a very big xml file with below format
<ABC>
<NAMEDETAILS></NAMEDETAILS>
<PRODUCT>
<PRODUCTDETAILS>
<ProductName>
<name>Car</Name>
<name>lorry<name>
<name>Car<name>
</ProductName>
</PRODUCTDETAILS>
<PRODUCTDETAILS>
<ProductName>
<name>van</Name>
<name>cycle</Name>
<name>bus</Name>
</ProductName>
</PRODUCTDETAILS>
<PRODUCTDETAILS>
<ProductName>
<name>car</Name>
<name>cycle</Name>
<name>bus</Name>
</ProductName>
</PRODUCTDETAILS>
<PRODUCT>
</ABC>
I want to retrieve the PRODUCTDETAILS data whose name tag has the value "car" and save it in a new xml file. I am using XMLReader but i am stuck in moving forward. Can somebody help me. Below is the c# code
XMLReader xmlReader = XMLReader.Create(#"\\Drive\xmlfile.xml")
while (xmlReader.Read())
{
If (xmlReader.NodeType == XMLNodeType.Element) && (xmlReader.Name == "PRODUCTDETAILS")
{
xmlReader.ReadtoDescendant("ProductName")
}
}
using System;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
namespace ConApp1
{
class Program
{
static void Main()
{
using (var xmlWriter = XmlWriter.Create("result.xml"))
using (var xmlReader = XmlReader.Create("test.xml"))
{
xmlWriter.WriteStartElement("PRODUCT");
while (xmlReader.ReadToFollowing("PRODUCTDETAILS"))
{
using (var nodeReader = xmlReader.ReadSubtree())
{
nodeReader.MoveToContent();
var elem = (XElement)XNode.ReadFrom(nodeReader);
var name = elem.Descendants("name").First().Value;
if (name.Equals("car", StringComparison.OrdinalIgnoreCase))
{
elem.WriteTo(xmlWriter);
}
}
}
}
}
}
}
Since you say that the file is large, both reading and writing should be done using streaming tools. XmlWriter is used for writing. This guarantees low memory consumption and no OutOfMemoryException occurs.
Try following :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string INPUT_FILENAME = #"c:\temp\test.xml";
const string OUTPUT_FILENAME = #"c:\temp\test1.xml";
static void Main(string[] args)
{
XmlReader reader = XmlReader.Create(INPUT_FILENAME);
string header = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><Cars></Cars>";
XDocument doc = XDocument.Parse(header);
XElement cars = doc.Root;
while (!reader.EOF)
{
if (reader.Name != "PRODUCTDETAILS")
{
reader.ReadToFollowing("PRODUCTDETAILS");
}
if (!reader.EOF)
{
XElement product = (XElement)XElement.ReadFrom(reader);
if(product.Descendants("name").Any(x => ((string)x).Trim() == "Car"))
{
cars.Add(product);
}
}
}
doc.Save(OUTPUT_FILENAME);
}
}
}

how to find printer's flow control whether it is hardware or software

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Printing;
using System.IO.Ports;
namespace Printer
{
public partial class portname : Window
{
PrintServer server = new PrintServer();
public portname()
{
this.InitializeComponent();
foreach (PrintQueue queue in server.GetPrintQueues())
{
com_pinter.Items.Add(queue.FullName);
}
var DefaultPrinter = new LocalPrintServer().DefaultPrintQueue;
string default_name=DefaultPrinter.FullName;
txt_dpn.Text = "Default printe is " + " " + default_name.ToUpper();
string default_port = DefaultPrinter.QueuePort.Name;
txt_pn.Text = "PortName is" + " " + default_port.ToUpper();
}
private void com_pinter_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
foreach (PrintQueue queue in server.GetPrintQueues())
{
string selecteditem = com_pinter.SelectedItem.ToString();
string portname = queue.FullName;
SerialPort mySerialPort = new SerialPort(queue.QueuePort.Name);
btn_br.Content = mySerialPort.BaudRate;
btn_db.Content = mySerialPort.DataBits;
btn_pty.Content = mySerialPort.Parity;
btn_sb.Content = mySerialPort.StopBits;
if (selecteditem == portname)
{
string select_portname = queue.QueuePort.Name;
txt_pn.Text = "PortName is" + " " + select_portname.ToUpper();
}
}
}
}
}
But i don't know whether this way is correct or not to get output like this(above figure).I just messed up
with this.if you know the correct way,please tell me that way i just upgrade it.
finally i need to find flow control(software or hardware).as per the above figure the combobox has to devices which are software device.so i have to dynamically find that value(s/w or h/w).

How to replace link to hyperlink in RichTextBox (Windows phone)

I have a text:
Download it directly to the iTunes Store or Android Market. The application is launched for Swedish app store.
I know how to show a hyperlink in RichTextBox:
http://msdn.microsoft.com/en-us/library/ee681613%28v=vs.95%29.aspx
But how can I make this for everyone link in this code?
You should parse the string maybe with something like RegEx or using a library like html agility pack. This extension method should work, letting you just call richTextBlock.SetLinkedText(htmlFragment);
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
public static class RichTextBlockExtensions
{
public static void SetLinkedText(this RichTextBlock richTextBlock, string htmlFragment)
{
var regEx = new Regex(
#"\<a\s(href\=""|[^\>]+?\shref\="")(?<link>[^""]+)"".*?\>(?<text>.*?)(\<\/a\>|$)",
RegexOptions.IgnoreCase | RegexOptions.Multiline);
richTextBlock.Blocks.Clear();
int nextOffset = 0;
foreach (Match match in regEx.Matches(htmlFragment))
{
if (match.Index > nextOffset)
{
richTextBlock.AppendText(htmlFragment.Substring(nextOffset, match.Index - nextOffset));
nextOffset = match.Index + match.Length;
richTextBlock.AppendLink(match.Groups["text"].Value, new Uri(match.Groups["link"].Value));
}
Debug.WriteLine(match.Groups["text"] + ":" + match.Groups["link"]);
}
if (nextOffset < htmlFragment.Length)
{
richTextBlock.AppendText(htmlFragment.Substring(nextOffset));
}
}
public static void AppendText(this RichTextBlock richTextBlock, string text)
{
Paragraph paragraph;
if (richTextBlock.Blocks.Count == 0 ||
(paragraph = richTextBlock.Blocks[richTextBlock.Blocks.Count - 1] as Paragraph) == null)
{
paragraph = new Paragraph();
richTextBlock.Blocks.Add(paragraph);
}
paragraph.Inlines.Add(new Run { Text = text });
}
public static void AppendLink(this RichTextBlock richTextBlock, string text, Uri uri)
{
Paragraph paragraph;
if (richTextBlock.Blocks.Count == 0 ||
(paragraph = richTextBlock.Blocks[richTextBlock.Blocks.Count - 1] as Paragraph) == null)
{
paragraph = new Paragraph();
richTextBlock.Blocks.Add(paragraph);
}
var run = new Run { Text = text };
var link = new Hyperlink { NavigateUri = uri };
link.Inlines.Add(run);
paragraph.Inlines.Add(link);
}
}
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
this.richTextBlock.SetLinkedText(
"Download it directly to the iTunes Store or Android Market. The application is launched for Swedish app store.");
}
}

Categories

Resources