C# Parse items from namespace - c#

I have the following XML:
https://pastebin.com/YQBhNzm5
I want to match up the item values with the field values.
XmlDocument xdoc = new XmlDocument();
xdoc.Load(ofd.FileName);
XmlNamespaceManager xmanager = new XmlNamespaceManager(xdoc.NameTable);
xmanager.AddNamespace("ns", "http://www.canto.com/ns/Export/1.0");
var result = xdoc.SelectNodes("//ns:Layout/ns:Fields", xmanager);
foreach(XmlElement item in result)
{
Console.WriteLine(item.InnerText);
}
When I do this I get all the field names in one line. How can I iterate through all fields in layout and go one by one?

I parsed xml using xml linq. First I put items into a dictionary. Then I parsed the fields looking up the uid from the dictionary. I parsed the fields recursively to keep the hierarchy.
It looks like the uid, type, value, and name are always the same for each item, but an item can appear in multiple catalogs with a catalog id and an id.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
Layout layout = new Layout(FILENAME);
}
}
public class Layout
{
public string tablename { get; set; }
public List<Field> fields { get; set; }
public Layout layout { get; set; }
public Dictionary<string, Item> dict = new Dictionary<string, Item>();
public Layout() { }
public Layout(string filename)
{
XDocument doc = XDocument.Load(filename);
XElement xLayout = doc.Descendants().Where(x => x.Name.LocalName == "Layout").FirstOrDefault();
XNamespace ns = xLayout.GetNamespaceOfPrefix("ns");
foreach (XElement item in doc.Descendants(ns + "Item"))
{
int catalogid = (int)item.Attribute("catalogid");
int id = (int)item.Attribute("id");
foreach(XElement fieldValue in item.Elements(ns + "FieldValue"))
{
string uid = (string)fieldValue.Attribute("uid");
uid = uid.Replace("{", "");
uid = uid.Replace("}", "");
string innertext = (string)fieldValue;
string displayValue = (string)fieldValue.Attribute("displayValue");
List<string> categoryValues = fieldValue.Elements(ns + "CategoryValue").Select(x => (string)x).ToList();
if (!dict.ContainsKey(uid))
{
Item newItem = new Item() {
catalogidId = new List<KeyValuePair<int, int>>() {new KeyValuePair<int, int>(catalogid, id)},
innertext = innertext,
uid = uid,
displayValue = displayValue,
categoryValues = categoryValues
};
dict.Add(uid, newItem);
}
else
{
dict[uid].catalogidId.Add(new KeyValuePair<int, int>(catalogid, id));
}
}
}
layout = new Layout();
RecursiveParse(ns, xLayout, layout);
}
public void RecursiveParse(XNamespace ns, XElement parent, Layout layout)
{
layout.tablename = (string)parent.Attribute("tableName");
foreach(XElement xField in parent.Element(ns + "Fields").Elements(ns + "Field"))
{
if (layout.fields == null) layout.fields = new List<Field>();
Field newField = new Field();
layout.fields.Add(newField);
newField.uid = (string)xField.Attribute("uid");
newField.uid = newField.uid.Replace("{", "");
newField.uid = newField.uid.Replace("}", "");
newField._type = (int)xField.Attribute("type");
newField.value = (int)xField.Attribute("valueInterpretation");
newField.name = (string)xField.Element(ns + "Name");
if (dict.ContainsKey(newField.uid))
{
newField.items = dict[newField.uid];
}
if (xField.Element(ns + "Layout") != null)
{
Layout newLayout = new Layout();
newField.layout = newLayout;
RecursiveParse(ns, xField.Element(ns + "Layout"), newLayout);
}
}
}
public class Field
{
public string uid { get; set; }
public int _type { get; set; }
public int value { get; set; }
public string name { get; set; }
public Layout layout { get; set; }
public Item items { get; set; }
}
public class Item
{
public List<KeyValuePair<int, int>> catalogidId { get; set; }
public string uid { get; set; }
public string innertext { get; set; }
public string displayValue { get; set; }
public List<string> categoryValues { get; set; }
}
}
}

Related

Add to List from XElement in foreach loop

Program.cs
using ConsoleApp2.Models;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
string City_Name = "GdaƄsk";
var doc = XElement.Load($"https://maps.googleapis.com/maps/api/place/textsearch/xml?key={key}&query=restaurants+in+{City_Name}&language=pl&fields=place_id");
List<PlaceIdModel> IdList = doc.Descendants("result").Select(n => new PlaceIdModel
{
PlaceId = n.Element("place_id").Value
}).ToList();
List<PlaceDetailsModel> placeDetailsModel = new List<PlaceDetailsModel>();
foreach (var item in IdList)
{
var doc2 = XElement.Load($"https://maps.googleapis.com/maps/api/place/details/xml?key={key}&place_id={item.PlaceId}&language=pl&fields=name,vicinity,geometry/location,rating,website,opening_hours/weekday_text");
placeDetailsModel = doc2.Descendants("result").Select(x => new PlaceDetailsModel
{
Name = x.Element("name").Value,
Vicinity = x.Element("vicinity").Value,
Rating = x.Element("rating").Value,
Website = x.Element("website").Value,
Lat = x.Element("geometry").Element("location").Element("lat").Value,
Lng = x.Element("geometry").Element("location").Element("lng").Value,
Opening_hours = x.Descendants("weekday_text").Select(y => y.Value).ToList()
}).ToList();
};
}
}
}
PlaceIdModel.cs
namespace ConsoleApp2.Models
{
public class PlaceIdModel
{
public string PlaceId { get; set; }
}
}
PlaceDetailsModel.cs
using System.Collections.Generic;
namespace ConsoleApp2.Models
{
public class PlaceDetailsModel
{
public string Name { get; set; }
public string Vicinity { get; set; }
public string Rating { get; set; }
public string Website { get; set; }
public string Lat { get; set; }
public string Lng { get; set; }
public List<string> Opening_hours { get; set; }
}
}
I'm using goole API places. First I get place_id from city then I want to use loop foreach to save details of every place into list. Everytime everything save on [0] instead populate whole list.
With .ToList() you are creating a new list every time. Instead add the items to the existing list with the List.AddRange(IEnumerable) Method.
var placeDetailsModel = new List<PlaceDetailsModel>();
foreach (var item in IdList)
{
var doc2 = XElement.Load($"https://maps.googleapis.com/maps/...");
placeDetailsModel.AddRange(
doc2.Descendants("result")
.Select(x => new PlaceDetailsModel
{
Name = x.Element("name").Value,
Vicinity = x.Element("vicinity").Value,
Rating = x.Element("rating").Value,
Website = x.Element("website").Value,
Lat = x.Element("geometry").Element("location").Element("lat").Value,
Lng = x.Element("geometry").Element("location").Element("lng").Value,
Opening_hours = x.Descendants("weekday_text").Select(y => y.Value).ToList()
})
);
}
You do not need the .ToList() when reading the IdList. The foreach works well with an IEnumerable<T> and it saves you an unnecessary memory allocation.:
IEnumerable<PlaceIdModel> IdList = doc
.Descendants("result")
.Select(n => new PlaceIdModel
{
PlaceId = n.Element("place_id").Value
});
...
foreach (var item in IdList) ...
I also do not see the advantage of having a PlaceIdModel class just to store the Id temporarily. Just use the values directly:
var IdList = doc
.Descendants("result")
.Select(n => n.Element("place_id").Value);
...
foreach (var id in IdList) {
var doc2 = XElement.Load($"https://maps.googleapis.com/...&place_id={id}&language=...");
...
}

Converting table in tree

Is there any scope for improvement in my program which converts flat db entity to a tree data structure.
I don't want to loose the Generic flexibility as i should be able to use the same method for any other DBEntity class
Interface for db entity class
public interface IDbEntityNode
{
int Id { get; set; }
int ParentId { get; set; }
}
Example of db Entity class
public class ExceptionCategory :IDbEntityNode
{
public int Id { get; set; }
public int ParentId { get; set; }
public string Data { get; set; }
public ExceptionCategory(string data, int id, int parentId)
{
Id = id;
ParentId = parentId;
Data = data;
}
}
Generic class which holds the structure of tree node
public class GenericNode<T>
{
public T NodeInformation { get; set; }
public GenericNode<T> Parent { get; set; }
public List<GenericNode<T>> Children { get; set; } = new List<GenericNode<T>>();
}
Method which coverts flat list to tree
public static List<GenericNode<T>> CreateGenericTree<T>(List<T> flatDataObject,Func<T,bool> IsRootNode) where T : IDbEntityNode
{
var lookup = new Dictionary<int, GenericNode<T>>();
var rootNodes = new List<GenericNode<T>>();
var noOfElements = flatDataObject.Count;
for (int element = 0; element < noOfElements; element++)
{
GenericNode<T> currentNode;
if (lookup.TryGetValue(flatDataObject[element].Id, out currentNode))
{
currentNode.NodeInformation = flatDataObject[element];
}
else
{
currentNode = new GenericNode<T>() { NodeInformation = flatDataObject[element] };
lookup.Add(flatDataObject[element].Id, currentNode);
}
if (IsRootNode(flatDataObject[element]))
{
rootNodes.Add(currentNode);
}
else
{
GenericNode<T> parentNode;
if (!lookup.TryGetValue(flatDataObject[element].ParentId, out parentNode))
{
parentNode = new GenericNode<T>();
lookup.Add(flatDataObject[element].ParentId, parentNode);
}
parentNode.Children.Add(currentNode);
currentNode.Parent = parentNode;
}
}
return rootNodes;
}
Execution:
private static void Main(string[] args)
{
List<IDbEntityNode> flatDataStructure = new List<IDbEntityNode>
{
new ExceptionCategory("System Exception",1,0),
new ExceptionCategory("Index out of range",2,1),
new ExceptionCategory("Null Reference",3,1),
new ExceptionCategory("Invalid Cast",4,1),
new ExceptionCategory("OOM",5,1),
new ExceptionCategory("Argument Exception",6,1),
new ExceptionCategory("Argument Out Of Range",7,6),
new ExceptionCategory("Argument Null",8,6),
new ExceptionCategory("External Exception",9,1),
new ExceptionCategory("Com",10,9),
new ExceptionCategory("SEH",11,9),
new ExceptionCategory("Arithmatic Exception",12,1),
new ExceptionCategory("DivideBy0",13,12),
new ExceptionCategory("Overflow",14,12),
};
var tree = CreateGenericTree(flatDataStructure, IsRootNode);
}
private static bool IsRootNode(IDbEntityNode dbEntity)
{
bool isRootNode = false;
if (dbEntity.ParentId == 0 )
isRootNode = true;
return isRootNode;
}
Created a generic approach, table objects need to follow the dbSet interface and TreeNode objects need to follow the ITreeNode. I used binarySerach to make this as fast as possible. No recursion needed. The logic ensures that you do not need to have the items in a particular order. I did not throw an error when out of the loop when there are still unassigned objects, this can be easy added.
using System.Collections.Generic;
public interface ITreeNode
{
string ParentId { get; set; }
string Id { get; set; }
dbItem item { get; set; }
List<ITreeNode> Nodes { get; set; }
}
public class TreeNode : ITreeNode
{
public TreeNode()
{ }
public string ParentId { get; set; }
public string Id { get; set; }
public dbItem item { get; set; }
public List<ITreeNode> Nodes { get; set; }
}
public class dbItem
{
public string ParentId { get; set; }
public string Id { get; set; }
public string Name { get; set; }
}
class app
{
static void Main()
{
List<dbItem> dbSet = new List<dbItem>();
dbSet.Add(new dbItem() { Id = "5", ParentId = "1", Name = "Jan" });
dbSet.Add(new dbItem() { Id = "25", ParentId = "1", Name = "Maria" });
dbSet.Add(new dbItem() { Id = "1", Name = "John" });
dbSet.Add(new dbItem() { Id = "8", ParentId = "2", Name = "Cornelis" });
dbSet.Add(new dbItem() { Id = "2", Name = "Ilse" });
dbSet.Add(new dbItem() { Id = "3", Name = "Nick" });
dbSet.Add(new dbItem() { Id = "87", ParentId = "5", Name = "Rianne" });
dbSet.Add(new dbItem() { Id = "67", ParentId = "3000", Name = "Rianne" });
dbSet.Add(new dbItem() { Id = "3000", Name = "Max" });
List<TreeNode> result = BuildTree<TreeNode>(dbSet);
}
private class ParentComparer<T> : IComparer<ITreeNode> where T: ITreeNode
{
public int Compare(ITreeNode x, ITreeNode y)
{
if (x.ParentId == null) return -1; //have the parents first
return x.ParentId.CompareTo(y.ParentId);
}
}
private class IdComparer<T> : IComparer<ITreeNode> where T : ITreeNode
{
public int Compare(ITreeNode x, ITreeNode y)
{
return x.Id.CompareTo(y.Id);
}
}
static private List<T> BuildTree<T> (List<dbItem> table) where T: ITreeNode, new()
{
//temporary list of tree nodes to build the tree
List<T> tmpNotAssignedNodes = new List<T>();
List<T> tmpIdNodes = new List<T>();
List<T> roots = new List<T>();
IComparer<T> pc = (IComparer<T>) new ParentComparer<T>();
IComparer<T> ic = (IComparer<T>) new IdComparer<T>();
foreach (dbItem item in table)
{
T newNode = new T() { Id = item.Id, ParentId = item.ParentId, item = item };
newNode.Nodes = new List<ITreeNode>();
T dummySearchNode = new T() { Id = item.ParentId, ParentId = item.ParentId };
if (string.IsNullOrEmpty(item.ParentId))
roots.Add(newNode);
else
{
int parentIndex = tmpIdNodes.BinarySearch(dummySearchNode, ic);//Get the parent
if (parentIndex >=0)
{
T parent = tmpIdNodes[parentIndex];
parent.Nodes.Add(newNode);
}
else
{
parentIndex = tmpNotAssignedNodes.BinarySearch(dummySearchNode, pc);
if (parentIndex < 0) parentIndex = ~parentIndex;
tmpNotAssignedNodes.Insert(parentIndex, newNode);
}
}
dummySearchNode.ParentId = newNode.Id;
//Cleanup Unassigned
int unAssignedChildIndex = tmpNotAssignedNodes.BinarySearch(dummySearchNode, pc);
while (unAssignedChildIndex >= 0 && unAssignedChildIndex < tmpNotAssignedNodes.Count)
{
if (dummySearchNode.ParentId == tmpNotAssignedNodes[unAssignedChildIndex].ParentId)
{
T child = tmpNotAssignedNodes[unAssignedChildIndex];
newNode.Nodes.Add(child);
tmpNotAssignedNodes.RemoveAt(unAssignedChildIndex);
}
else unAssignedChildIndex--;
}
int index = tmpIdNodes.BinarySearch(newNode, ic);
tmpIdNodes.Insert(~index, newNode);
}
return roots;
}
}
Try following solution using recursive code :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
public static List<IDbEntityNode> flatDataStructure = null;
public static Dictionary<int?, List<IDbEntityNode>> dict = null;
static void Main(string[] args)
{
flatDataStructure = new List<IDbEntityNode>
{
new ExceptionCategory("System Exception",1,0),
new ExceptionCategory("Index out of range",2,1),
new ExceptionCategory("Null Reference",3,1),
new ExceptionCategory("Invalid Cast",4,1),
new ExceptionCategory("OOM",5,1),
new ExceptionCategory("Argument Exception",6,1),
new ExceptionCategory("Argument Out Of Range",7,6),
new ExceptionCategory("Argument Null",8,6),
new ExceptionCategory("External Exception",9,1),
new ExceptionCategory("Com",10,9),
new ExceptionCategory("SEH",11,9),
new ExceptionCategory("Arithmatic Exception",12,1),
new ExceptionCategory("DivideBy0",13,12),
new ExceptionCategory("Overflow",14,12),
};
dict = flatDataStructure.GroupBy(x => x.ParentId, y => y)
.ToDictionary(x => x.Key, y => y.ToList());
GenericNode<IDbEntityNode> root = new GenericNode<IDbEntityNode>();
root.Parent = null;
int rootId = 0;
root.NodeInformation.Id = rootId;
root.NodeInformation.name = "root";
root.NodeInformation.ParentId = null;
CreateGenericTree(root);
}
public static void CreateGenericTree<T>(GenericNode<T> parent) where T : IDbEntityNode, new()
{
if (dict.ContainsKey(parent.NodeInformation.Id))
{
List<IDbEntityNode> children = dict[parent.NodeInformation.Id];
foreach (IDbEntityNode child in children)
{
GenericNode<T> newChild = new GenericNode<T>();
if (parent.Children == null) parent.Children = new List<GenericNode<T>>();
parent.Children.Add(newChild);
newChild.NodeInformation.Id = child.Id;
newChild.NodeInformation.ParentId = parent.NodeInformation.Id;
newChild.NodeInformation.name = child.name;
newChild.Parent = parent;
CreateGenericTree(newChild);
}
}
}
}
public class GenericNode<T> where T : new()
{
public T NodeInformation = new T();
public GenericNode<T> Parent { get; set; }
public List<GenericNode<T>> Children { get; set; }
}
public class IDbEntityNode
{
public int Id { get; set; }
public int? ParentId { get; set; }
public string name { get; set; }
}
public class ExceptionCategory : IDbEntityNode
{
public string Data { get; set; }
public ExceptionCategory(string data, int id, int parentId)
{
Id = id;
ParentId = parentId;
Data = data;
}
}
}

Xpath Select all subnodes of a group of nodes

How can I select all subnodes of the current node?
XmlNodeList productNodes = doc.DocumentElement.SelectNodes("//PRODUCT");
Parallel.ForEach(productNodes.Cast<XmlNode>(),
(XmlNode productNode) =>
{
string _productMode = XmlUtils.nodeAsString(productNode, "#mode");
Product product = new Product()
{
Mode = XmlUtils.nodeAsString(productNode, "#mode"),
No = XmlUtils.nodeAsString(productNode, "./SUPPLIER_PID"),
DescriptionShort = XmlUtils.nodeAsString(productNode, "./PRODUCT_DETAILS/DESCRIPTION_SHORT"),
DescriptionLong = XmlUtils.nodeAsString(productNode, "./PRODUCT_DETAILS/DESCRIPTION_LONG"),
EANCode = XmlUtils.nodeAsString(productNode, "./PRODUCT_DETAILS/EAN"),
Stock = XmlUtils.nodeAsInt(productNode, "./PRODUCT_DETAILS/STOCK"),
OrderUnit = default(QuantityCodes).FromString(XmlUtils.nodeAsString(productNode, "./PRODUCT_ORDER_DETAILS/ORDER_UNIT")),
ContentUnit = default(QuantityCodes).FromString(XmlUtils.nodeAsString(productNode, "./PRODUCT_ORDER_DETAILS/CONTENT_UNIT")),
Currency = default(CurrencyCodes).FromString(XmlUtils.nodeAsString(productNode, "./PRODUCT_PRICE_DETAILS/PRODUCT_PRICE/PRICE_CURRENCY")),
VAT = XmlUtils.nodeAsInt(productNode, "./PRODUCT_PRICE_DETAILS/PRODUCT_PRICE/TAX"),
};
XmlNodeList MimeNodes = doc.DocumentElement.SelectNodes(".//MIME");
Parallel.ForEach(MimeNodes.Cast<XmlNode>(), (XmlNode MimeNode) =>
{
Mime mime = new Mime()
{
Source = XmlUtils.nodeAsString(MimeNode, "./MIME_SOURCE"),
Type = XmlUtils.nodeAsString(MimeNode, "./MIME_TYPE"),
Purpose = XmlUtils.nodeAsString(MimeNode, "./MIME_PURPOSE")
};
product.Mime.Add(mime);
});......
<PRODUCT mode="new">
<SUPPLIER_PID>1902</SUPPLIER_PID>
<PRODUCT_DETAILS>
<DESCRIPTION_SHORT>NORDEN Table</DESCRIPTION_SHORT>
<DESCRIPTION_LONG>massive birch wood. 135x74cm, 74 cm height by Mikael Warnhammar</DESCRIPTION_LONG>
</PRODUCT_DETAILS>
<PRODUCT_ORDER_DETAILS>
<ORDER_UNIT>C62</ORDER_UNIT>
<CONTENT_UNIT>C62</CONTENT_UNIT>
<NO_CU_PER_OU>1</NO_CU_PER_OU>
</PRODUCT_ORDER_DETAILS>
<PRODUCT_PRICE_DETAILS>
<VALID_START_DATE>2013-05-28</VALID_START_DATE>
<VALID_END_DATE>2013-05-30</VALID_END_DATE>
<PRODUCT_PRICE price_type="nrp">
<PRICE_AMOUNT>33.00</PRICE_AMOUNT>
<PRICE_CURRENCY>EUR</PRICE_CURRENCY>
<LOWER_BOUND>200</LOWER_BOUND>
<TERRITORY>AT</TERRITORY>
</PRODUCT_PRICE>
</PRODUCT_PRICE_DETAILS>
<MIME>
<MIME_SOURCE>http://www.google.de/</MIME_SOURCE>
<MIME_TYPE>text/html</MIME_TYPE>
<MIME_PURPOSE>url</MIME_PURPOSE>
</MIME>
<MIME>
<MIME_SOURCE>http://www.stackoverflow.com</MIME_SOURCE>
<MIME_TYPE>text/html</MIME_TYPE>
<MIME_PURPOSE>url</MIME_PURPOSE>
</MIME>
</PRODUCT>
actually i get all the product nodes and i am trying to get all the mimes sub nodes of each product node to save it.. but when i do i get the mime node repeated.
I dont know much about xpath maybe is because i need to speficy the ancestor node ? i tried using descendant but i am getting the same result.
Try following Xml Linq solution
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 FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
List<XElement> productNodes = doc.Descendants("PRODUCT").ToList();
List<Product> product = productNodes.Select(x => new Product() {
Mode = (string)x.Attribute("mode"),
No = (string)x.Element("SUPPLIER_PID"),
DescriptionShort = (string)x.Descendants("DESCRIPTION_SHORT").FirstOrDefault(),
DescriptionLong = (string)x.Descendants("DESCRIPTION_LONG").FirstOrDefault(),
//EANCode = XmlUtils.nodeAsString(productNode, "./PRODUCT_DETAILS/EAN"),
//Stock = XmlUtils.nodeAsInt(productNode, "./PRODUCT_DETAILS/STOCK"),
OrderUnit = (string)x.Descendants("ORDER_UNIT").FirstOrDefault(),
ContentUnit = (string)x.Descendants("CONTENT_UNIT").FirstOrDefault(),
Currency = (string)x.Descendants("PRICE_CURRENCY").FirstOrDefault(),
mime = x.Elements("MIME").Select(y => new Mime() {
Source = (string)y.Element("MIME_SOURCE"),
Type = (string)y.Element("MIME_TYPE"),
Purpose = (string)y.Element("MIME_PURPOSE")
}).ToList()
}).ToList();
}
}
public class Product
{
public string Mode { get; set;}
public string No { get; set;}
public string DescriptionShort { get; set;}
public string DescriptionLong { get; set;}
public string EANCode { get; set;}
public string OrderUnit { get; set;}
public string ContentUnit { get; set;}
public string Currency { get; set;}
public string Vat { get; set;}
public List<Mime> mime { get; set;}
}
public class Mime
{
public string Source { get; set; }
public string Type { get; set;}
public string Purpose { get; set;}
}
}

Insufficient Memory error being thrown

namespace Calendar
{
public partial class MainCalendar : Form
{
private JArray items;
private List<String> AMList = new List<String>();
private List<String> PMList = new List<String>();
private List<String> accessToCalendarFilepath = new List<String>();
private List<CalendarModel> people;
private List<List<CalendarModel>> managers = new List<List<CalendarModel>>();
private List<String> userSelection = new List<String>();
private bool authorizedAccess = false;
private String javaScriptFileContainingJSONObject = "";
public MainCalendar()
{
InitializeComponent();
var locationInformation = System.Environment.CurrentDirectory + Path.DirectorySeparatorChar + "location.json";
using (StreamReader file = File.OpenText(locationInformation))
using (JsonTextReader reader = new JsonTextReader(file))
{
JArray o = (JArray)JToken.ReadFrom(reader);
items = o;
}
foreach (var item in items.Children())
{
var itemProperties = item.Children<JProperty>();
// you could do a foreach or a linq here depending on what you need to do exactly with the value
var myElement = itemProperties.FirstOrDefault(x => x.Name == "name");
var myElementValue = myElement.Value; ////This is a JValue type
if(myElementValue.ToString().Contains("AM"))
{
AMList.Add(myElementValue.ToString());
}
if (myElementValue.ToString().Contains("PM"))
{
PMList.Add(myElementValue.ToString());
}
}
mondayAM.DataSource = AMList.ToArray();
tuesdayAM.DataSource = AMList.ToArray();
wednesdayAM.DataSource = AMList.ToArray();
thursdayAM.DataSource = AMList.ToArray();
fridayAM.DataSource = AMList.ToArray();
mondayPM.DataSource = PMList.ToArray();
tuesdayPM.DataSource = PMList.ToArray();
wednesdayPM.DataSource = PMList.ToArray();
thursdayPM.DataSource = PMList.ToArray();
fridayPM.DataSource = PMList.ToArray();
loadAccessControl("accesscontrol.json");
dateTimePicker1.AlwaysChooseMonday(dateTimePicker1.Value);
String dateSelected = dateTimePicker1.Value.ToShortDateString();
findManagerForSelectedDate(dateSelected);
}
public void loadAccessControl(String fileName)
{
var accessControlInformation = Environment.CurrentDirectory + Path.DirectorySeparatorChar + fileName;
List<AccessControl> accounts = JsonConvert.DeserializeObject<List<AccessControl>>(File.ReadAllText(accessControlInformation));
foreach (AccessControl account in accounts)
{
Console.WriteLine(account.accountName);
if (account.accountName.ToLower().Contains(Environment.UserName.ToLower()))
{
foreach (CalendarFile file in account.files)
{
// Console.WriteLine(Environment.CurrentDirectory + Path.DirectorySeparatorChar + "content" + Path.DirectorySeparatorChar + file.Filename);
accessToCalendarFilepath.Add(Environment.CurrentDirectory + Path.DirectorySeparatorChar + "content" + Path.DirectorySeparatorChar + file.Filename);
}
break;
}
}
contentsOfFile();
}
private void contentsOfFile()
{
String line;
foreach(var file in accessToCalendarFilepath)
{
StreamReader contentsOfJSONFile = new StreamReader(file);
while((line = contentsOfJSONFile.ReadLine()) != null)
{
if(line.Contains("var "))
{
javaScriptFileContainingJSONObject = javaScriptFileContainingJSONObject + "[";
}
else if(line.Contains("];"))
{
javaScriptFileContainingJSONObject = javaScriptFileContainingJSONObject + "]";
}
else
{
javaScriptFileContainingJSONObject = javaScriptFileContainingJSONObject + line;
}
}
people = JsonConvert.DeserializeObject<List<CalendarModel>>((string)javaScriptFileContainingJSONObject);
managers.Add(people);
javaScriptFileContainingJSONObject = "";
}
}
private void findManagerForSelectedDate(String dateSelected)
{
dateSelected = dateTimePicker1.Value.ToShortDateString();
List<String> managerNames = new List<String>();
foreach(var item in managers)
{
foreach (var subitem in item)
{
CalendarModel c = subitem;
Console.WriteLine(c.date);
c.name = new CultureInfo("en-US", false).TextInfo.ToTitleCase(c.name);
if (userSelection.Count > 0)
{
foreach (var addedUser in userSelection.ToArray())
{
if (!addedUser.Contains(c.name))
{
userSelection.Add(c.name); // CRASHING HERE
//{"Exception of type 'System.OutOfMemoryException' was thrown."}
}
}
}
else
{
userSelection.Add(c.name);
}
}
}
Console.WriteLine();
}
I keep running out of memory.
The CalendarModel class:
namespace Calendar
{
class CalendarModel
{
[JsonProperty("name")]
public string name { get; set; }
[JsonProperty("date")]
public string date { get; set; }
[JsonProperty("title")]
public string title { get; set; }
[JsonProperty("mondayAM")]
public string mondayAM { get; set; }
[JsonProperty("mondayPM")]
public string mondayPM { get; set; }
[JsonProperty("tuesdayAM")]
public string tuesdayAM { get; set; }
[JsonProperty("tuesdayPM")]
public string tuesdayPM { get; set; }
[JsonProperty("wednesdayAM")]
public string wednesdayAM { get; set; }
[JsonProperty("wednesdayPM")]
public string wednesdayPM { get; set; }
[JsonProperty("thursdayAM")]
public string thursdayAM { get; set; }
[JsonProperty("thursdayPM")]
public string thursdayPM { get; set; }
[JsonProperty("fridayAM")]
public string fridayAM { get; set; }
[JsonProperty("fridayPM")]
public string fridayPM { get; set; }
[JsonProperty("saturdayAM")]
public string saturdayAM { get; set; }
[JsonProperty("saturdayPM")]
public string saturdayPM { get; set; }
}
}
I keep crashing at
userSelection.Add(c.name)
Take a close look at what you are doing
foreach (var addedUser in userSelection.ToArray())
{
if (!addedUser.Contains(c.name))
{
userSelection.Add(c.name);
}
}
You are adding to userSelection in the userSelection loop
The test is on !addedUser.Contains
You should not even be able to do that but I think the ToArrray() is letting it happen
So you add Sally
Then then Mark
Then you add Mark again because in the loop Mark != Sally
You are not using List<String> managerNames = new List<String>();
private void findManagerForSelectedDate(String dateSelected)
{
dateSelected = dateTimePicker1.Value.ToShortDateString();
You pass in dateSelected, then overright with dateTimePicker1, and then you don't even use it
Most of you code makes very little sense to me

parse xml children nodes

What is the best way to parse XML children nodes into a specific list? This is a small example of the XML.
<Area Name="Grey Bathroom" IntegrationID="3" OccupancyGroupAssignedToID="141">
<Outputs>
<Output Name="Light/Exhaust Fan" IntegrationID="46" OutputType="NON_DIM" Wattage="0" />
</Outputs>
</Area>
I want to create a list or something that will be called the Area Name and hold the information of the Output Name and IntegrationID. So I can call the list and pull out the Output Name and IntegrationID.
I can create a list of all Area Names and then a list of Outputs but cannot figure out how to create a list that will be called "Grey Bathroom" and hold the output "Light/Exhaust Fan" with an ID of 46.
XDocument doc = XDocument.Load(#"E:\a\b.xml");
List<Area> result = new List<Area>();
foreach (var item in doc.Elements("Area"))
{
var tmp = new Area();
tmp.Name = item.Attribute("Name").Value;
tmp.IntegrationID = int.Parse(item.Attribute("IntegrationID").Value);
tmp.OccupancyGroupAssignedToID = int.Parse(item.Attribute("OccupancyGroupAssignedToID").Value);
foreach (var bitem in item.Elements("Outputs"))
{
foreach (var citem in bitem.Elements("Output"))
{
tmp.Outputs.Add(new Output
{
IntegrationID = int.Parse(citem.Attribute("IntegrationID").Value),
Name = citem.Attribute("Name").Value,
OutputType = citem.Attribute("OutputType").Value,
Wattage = int.Parse(citem.Attribute("Wattage").Value)
});
}
}
result.Add(tmp);
}
public class Area
{
public String Name { get; set; }
public int IntegrationID { get; set; }
public int OccupancyGroupAssignedToID { get; set; }
public List<Output> Outputs = new List<Output>();
}
public class Output
{
public String Name { get; set; }
public int IntegrationID { get; set; }
public String OutputType { get; set; }
public int Wattage { get; set; }
}
The example uses an anonymous type. You could (and I warmly advice you to) use your own.
var doc = XDocument.Parse(xml);
var areaLists = doc.Elements("Area").
Select(e => e.Descendants("Output").
Select(d => new
{
Name = (string) d.Attribute("Name"),
Id = (int) d.Attribute("IntegrationID")
}).
ToArray()).
ToList();

Categories