Problems with parsing XML in C# - c#

I'm building a Windows Phone 8 App using a recipe API, the API returns data in XML and up to this point I've not had many problems with parsing API responses, however, after making a search for a recipe, a user should then be able to tap on a particular search result and see more information on that recipe, this is a Pivot page with three headers:
Details (Which contains the recipe name, image and description)
Ingredients (Obviously listing the ingredients and quantities)
Instructions (Contains the prep and cooking instructions)
I have no problem getting the elements for the Details and Instructions pages as there is only one of each of these elements in the xml returned by the API, however with Ingredients, each ingredient has its own section in the xml, so I thought a foreach loop in the code would be able to get all the details into a list, however, when running the app and navigating to this page, the app seems to load multiples of ALL the information, including items on the Details and Instructions pages.
So, there are now lots of the same image, title and decryption displayed on the details page, lots of the same instructions on the instructions page and lots of the same ingredient on the ingredients page. I'm not quite sure how to go about solving this as everything I try doesn't work.
Removing the foreach loop from the code below stops the app loading loads of the same information, but obviously without any ingredients, please see the code below, I'm unable to post an API link because there is a limit to how many requests I can make per hour, and inserting it here formats it in an unclear way, does anyone know any steps to try and fix this issue?
The code:
void bigOvenRecipe_RecipeDetailsCompleted(object sender, DownloadStringCompletedEventArgs e)
{
var xdoc = XDocument.Parse(e.Result);
Details content = new Details();
List<Details> contentList = new List<Details>();
try
{
content.RecipeImage = xdoc.Root.Element("ImageURL").Value;
content.Title = xdoc.Root.Element("Title").Value;
content.Description = xdoc.Root.Element("Description").Value;
content.Instructions = xdoc.Root.Element("Instructions").Value;
contentList.Add(content);
foreach (XElement item in xdoc.Elements("Recipe").Elements("Ingredients").Elements("Ingredient"))
{
content.IngredientName = item.Element("Name").Value;
content.IngredientQuantity = item.Element("Quantity").Value;
content.IngredientUnit = item.Element("Unit").Value;
contentList.Add(content);
}
}
catch (Exception error)
{
MessageBox.Show("An error was encountered while performing this request: " + error.Message);
}
detailsList.ItemsSource = contentList.ToList();
ingredientsList.ItemsSource = contentList.ToList();
instructionsList.ItemsSource = contentList.ToList();
}
Thank you in advance!

One glaring issue that I see is that you keep adding the same content object to contentList.
I'm guessing that Details is a reference type, and content is only a reference to that one Details object.
your entire contentList is just a bunch of references to the same object.
Try instantiating a new object for each ingredient.
foreach (XElement item in xdoc.Elements("Recipe").Elements("Ingredients").Elements("Ingredient"))
{
Details content = new Details();
// initialize other values
content.IngredientName = item.Element("Name").Value;
content.IngredientQuantity = item.Element("Quantity").Value;
content.IngredientUnit = item.Element("Unit").Value;
contentList.Add(content);
}

Related

Firebase data - error converting value

I have posted question regarding firebase two days ago:
Android Firebase - add authenticated user into database
I got help that I needed and that solved first problem. But now I have a new problem. I was googling for quite some time, there are some posts about this issue but nothing solved my problem. I din't want to spam the previous question so I posted a new one.
When I try reading inserted data from the firebase database I get this error:
Newtonsoft.Json.JsonSerializationException: Error converting value
"test#user.com" to type 'carServiceApp.My_Classes.Account'. Path
'email', line 1, position 24.
Here is the code:
private async Task LoadData()
{
FirebaseUser users = FirebaseAuth.GetInstance(loginActivity.app).CurrentUser;
id = users.Uid;
var firebase = new FirebaseClient(loginActivity.FirebaseURL);
var items = await firebase.Child("users").Child(id).OnceAsync<Account>();
foreach (var item in items)
{
Account user = new Account();
user.uid = item.Object.uid;
user.name = item.Object.name;
user.lastName = item.Object.lastName;
user.phone = item.Object.phone;
user.email = item.Object.email;
userInput_ime.Text = user.name;
userInput_prezime.Text = user.lastName;
userInput_broj.Text = user.phone;
userInput_email.Text = user.email;
}
}
This is firebase data:
-users
-jwAP2dYNzJeiF3QlmEIEQoruUkO2
email: "test#user.com"
lastName: "user"
name: "test"
phone: "12421"
uid: "jwAP2dYNzJeiF3QlmEIEQoruUkO2"
Interesting thing is that when I try reading data with this:
var items = await firebase.Child("users").OnceAsync<Account>();
This works fine (I get last inserted user) . But when I add 'uid' node, then I get error. I was trying to solve this for quite some time but I just can't figure it out. I guess that there is no problem with the account class because it works in the case without uid node but doesn't work when another child() method is added.
Other information (Account class code and the way of storing that data into the database) you can see in the link at the top.
Note: I tried adding constructor in Account class but that doesn't help.
Ok, so I didn't exactly find a solution for this problem nor do I really understand why was this happening but I have found a workaround. I believe it's not ideal solution and that it does not fix existing problem. Or maybe it was problem with me not understanding firebase logic but here is what I came up with.
So, considering that it was all working fine if I didn't specify that uid node it was obvious there was some problem with class and data in firebase, matching problem I guess. Anyway, I decided to have that last uid node so I can have specific user selected and also to have the same data in firebase as it was in case where it was all working. So, this is how I have inserted data into firebase:
var item = firebase.Child("users").Child(id).PostAsync<Account>(user);
This created users node and child node. And PostAsync method created one more node with random key.
So when I tried reading with this:
var data = await firebase.Child("users").Child(id).OnceAsync<Account>();
It worked without problem. Now firebase data looks like this:
users
JPKdQbwcXbhBatZ2ihBNLRauhV83
-LCXyLpvdfQ448KOPKUp
email: "spider#man.com"
lastName: "man"
name: "spider"
phone: "14412"
uid: "JPKdQbwcXbhBatZ2ihBNLRauhV83"
There is a bit of redundancy, I basically have two ID's, but I don't understand how to create my class so I can get that data any other way so I made it this way. It works fine.
If anyone has better solution, I will gladly change it. Cheers
This was suppose to be a comment, but this is just suppose to be an addition for anyone that needs help with this issue.
I know that this answer has been out there for a while but this still seems to be a running structural quirk with Firebase and the usage of their rules. I ran into this issue with a complex structure that looked kind of like this
-Orders
-9876trfghji (User ID)
-0
BusnID: "ty890oihg"
Name: "Some Name"
AddOns: Object
ItemData: Object(containing other objects)
UserID: "9876trfghji"
Note: In this case as well as the case with cordas, you will see that both of the final objects has a UserID or uid.
I also was running into the issue of class de-serialization of the object without having the actual User ID in the objects data when it was being sent back to the device.
The reason that you have a “redundant” usage of the user id is for a security measure with the Firebase rules. The first UserID with the structure above you are able to control the access to the information based off of the users id without having to have an extra validation clause in the rules. Currently as of this post the the rule below would protect the data based on the User ID.
“Orders” : {
"$uid":{
".read":"auth != null",
".write":"auth.uid == $uid"
}
}
this allows the user with only the authorized user id to write content but anyone that has valid credentials can view the data.
The second User ID has to be placed in the object because without it you would not be able to do a standard cast to the object because your object would not have all of the data it would need to create the object. Regardless of if you are using a package like GoogleGson or Newtonsoft.Json the object still isn't full.
There is how ever a work around for this problem besides re-entering the User ID into the object. With the object that I have above I decided to just re-enter the User ID in my personal code to save the time and hassle of manual creation.
Using the Firebase.Database NuGet package you can manually create the object. Here is an example of the object in cordas problem
public static void GetUser_Firebase(User user, FirebaseApp app)
{
FirebaseDatabase database = FirebaseDatabase.GetInstance(app);
DatabaseReference reference = database.GetReference($"/users/{user.UserID}");
//"Using for getting firebase information", $"/users/{user.UserID}"
reference.AddListenerForSingleValueEvent(new UserInfo_DataValue());
}
class UserInfo_DataValue : Java.Lang.Object, IValueEventListener
{
private string ID;
public UserInfo_DataValue(string uid)
{
this.ID = uid;
}
public void OnCancelled(DatabaseError error)
{
//"Failed To Get User Information For User "
}
public void OnDataChange(DataSnapshot snapshot)
{
Dictionary<string, string> Map = new Dictionary<string, string>();
var items = snapshot.Children?.ToEnumerable<DataSnapshot>(); // using Linq
foreach(DataSnapshot item in items)
{
try
{
Map.Add(item.Key, item.Value.ToString()); // item.value is a Java.Lang.Object
}
catch(Exception ex)
{
//"EXCEPTION WITH DICTIONARY MAP"
}
}
User toReturn = new User();
toReturn.UserID this.ID;
foreach (var item in Map)
{
switch (item.Key)
{
case "email":
toReturn.email = item.Value;
break;
case "lastName":
toReturn.lastName = item.Value;
break;
case "name":
toReturn.name = item.Value;
break;
case "phone":
toReturn.phone = item.Value;
break;
}
}
}
}
Update
There is something that I would like to mention that I left out when I was writing this and that is the usage of Firebase.Database NuGet package with the Gson NuGet package and the Newtonsoft.Json Library
If you decide to use the FIrebase.Database library just know that you will be working very close with the Java.Lang and the Java.Util libraries. Objects like Java.Lang.Object can be very difficult and time consuming to write the code needed to de-serialize the data, but don't fear Gson is here!
The Gson package if you allow it can take a large load of work off of your hands for class de-serialization if you allow it. Gson is a library that will allow you to do Java.Lang.Obj to json string de-serialization. I know it seems weird, hand it an object get back a string sounds counter intuitive I know but just bear with me.
Here is an example of how to us the Gson Library with the object in cordas problem.
public static void Get_User(User user, FirebaseApp app)
{
FirebaseDatabase database = FirebaseDatabase.GetInstance(app);
DatabaseReference reference = database.GetReference($"Users/{user.UserID}");
reference.AddListenerForSingleValueEvent(new User_DataValue(user, app));
//$"Trying to make call for user orders Users/{user.UserID}");
}
class User_DataValue : Java.Lang.Object, IValueEventListener
{
private User User;
private FirebaseApp app;
public UserOrderID_Init_DataValue(User user, FirebaseApp app)
{
this.User = user;
this.app = app;
}
public void OnCancelled(DatabaseError error)
{
//$"Failed To Get User Orders {error.Message}");
}
public void OnDataChange(DataSnapshot snapshot)
{
//"Data received for user orders");
var gson = new GsonBuilder().SetPrettyPrinting().Create();
var json = gson.ToJson(snapshot.Value); // Gson extention method obj -> string
Formatted_Output("Data received for user order json ", json);
User user = JsonConvert.DeserializeObject<User>(json); //Newtonsoft.Json extention method string -> object
//now the user is a fully populated object with very little work
}
For anyone that might run into this in the future I hope that this helps

OData V4 client adding child entity

I have a parent (Order) and child (OrderDetail) where Order already exists in the database and OrderDetail also exists in the database.
All I really want to do is add another OrderDetail record bound to the Order.
I have been down several paths and I'm not even sure what is the correct path.
Let's make some assumptions that navigations between these are already working.
I can $expand=OrderDetails fine and I can also Orders(1)/OrderDetails fine and do the reverse from OrderDetails.
Based on this Updating the Data Service, all I need to do is call AddRelatedObject and then Add the object to the OrderDetails collection.
// Add the new item with a link to the related Order
context.AddRelatedObject(order, "OrderDetails", newOrderDetail);
// Add the new order detail to the collection
order.Order_Details.Add(newOrderDetail);
newOrderDetail.Order = order;
Seems simple enough.
Yet when I execute context.SaveChanges(SaveChangesOptions.ReplaceOnUpdate) it will throw an error.
{"error":{"code":"","message":"No HTTP resource was found that matches the request URI 'http://localhost/Test/odata/Orders(1)/OrderDetails'.","innererror":{"message":"No routing convention was found to select an action for the OData path with template '~/entityset/key/navigation'.","type":"","stacktrace":""}}}
But if I navigate to the URL listed, it shows data.
Time for Fiddler.
In Fiddler, I can see this is a POST to the URL and not a GET.
Which it should be a POST but not to the URL listed.
The POST should have been to /odata/OrderDetails
Round 2
// Add the new item with a link to the related Order
context.AttachTo("OrderDetails", newOrderDetail);
// Add a link between Order and the new OrderDetail
context.AddLink(order, "OrderDetails", newOrderDetail);
// Add the new order detail to the collection
order.Order_Details.Add(newOrderDetail);
newOrderDetail.Order = order;
Still a POST with an error but the URL is slightly different and the json posted only has "/odata/OrderDetail(0)" it also now has "$ref".
{"error":{"code":"","message":"No HTTP resource was found that matches the request URI 'http://localhost/Test/odata/Orders(1)/OrderDetails/$ref'.","innererror":{"message":"No routing convention was found to select an action for the OData path with template '~/entityset/key/navigation/$ref'.","type":"","stacktrace":""}}}
Well a quick web search led me to this article Entity Relations in OData v4 Using ASP.NET Web API 2.2
This article says I need to add a "CreateRef" in the Orders controller.
I did create a "CreateRef" in the Orders controller and sure enough it gets called BUT the article assumes the OrderDetail exists in the database.
It is not posting the json OrderDetail object.
Round 3
// Add the new item with a link to the related Order
context.AttachTo("OrderDetails", newOrderDetail);
// Attach a link between Order and the new OrderDetail
context.AttachLink(order, "OrderDetails", newOrderDetail);
// Add the new order detail to the collection
order.Order_Details.Add(newOrderDetail);
newOrderDetail.Order = order;
Well this seems much better.
No error but it did not fully work.
It sent a PUT to the /odata/OrderDetails(0) and it did send the json OrderDetail object BUT this should have been a POST not a PUT.
I feel I am so close yet I can't seem to figure out how to get it to work properly.
Any ideas?
I had the same problem and found the solution today.
Take a look at http://aspnetwebstack.codeplex.com/discussions/457028 :
There is no inbuilt convention to handle POST requests to ~/entityset(key)/navigation. You have to build one yourself. Check out this a sample code for that.
You need first to create a EntitySetRoutingConvention :
public class CreateNavigationPropertyRoutingConvention : EntitySetRoutingConvention
{
public override string SelectAction(ODataPath odataPath, HttpControllerContext controllerContext, ILookup<string, HttpActionDescriptor> actionMap)
{
if (odataPath.PathTemplate == "~/entityset/key/navigation" && controllerContext.Request.Method == HttpMethod.Post)
{
IEdmNavigationProperty navigationProperty = (odataPath.Segments[2] as NavigationPathSegment).NavigationProperty;
controllerContext.RouteData.Values["key"] = (odataPath.Segments[1] as KeyValuePathSegment).Value; // set the key for model binding.
return "PostTo" + navigationProperty.Name;
}
return null;
}
}
Then, you have to register it in WebApiConfig.Register:
var routingConventions = ODataRoutingConventions.CreateDefault();
routingConventions.Insert(0, new CreateNavigationPropertyRoutingConvention());
server.Configuration.Routes.MapODataRoute("odata", "", GetEdmModel(), new DefaultODataPathHandler(), routingConventions);
Please note this sample is for oData v3 but can easily be converted to v4.
Then, you'll just have to add your parent object to the context and use AddRelatedObject for all the children.
Your request will be send to this void in your ParentController:
public HttpResponseMessage PostToOrders([FromODataUri] int key, Order order)
{
// create order.
return Request.CreateResponse(HttpStatusCode.Created, order);
}
After trial and error I found something that worked.
// create a new order detail
OrderDetail newOrderDetail = new OrderDetail();
// set the orderID on the new order detail
newOrderDetail.OrderID = order.ID;
// add the order back as a link on the order detail
newOrderDetail.Order = order;
// add the order detail to the order detail collection on the order
order.OrderDetails.Add(newOrderDetail);
// add the order detail to the context
context.AddToOrderDetail(newOrderDetail);
// now update context for the order
context.UpdateObject(order);
// now save
context.SaveChanges();

IsolatedStorage and navigation

I can't sort this weird issue out and I have tried anything and everything I can think of.
I got 5 pages, everyone of them passing variables with navigation this way:
Pass:
NavigationSerice.Navigate(new Uri("/myPage.xaml?key=" + myVariable, UriKind.Relative));
Retrieve:
If (NavigationContext.QueryString.ContainsKey(myKey))
{
String retrievedVariable = NavigationContext.QueryString["myKey"].toString();
}
I open a list on many pages and one of the pages automatically deletes an item from the list actualProject (actualProject is a variable for a string list). Then, when I go so far back that I reach a specific page - the app throws an exception. Why? I have no idea.
The code that deletes the item:
// Remove the active subject from the availible subjects
unlinkedSubjects.Remove(actualSubject);
unlinkedsubjectsListBox.ItemsSource = null;
unlinkedsubjectsListBox.ItemsSource = unlinkedSubjects;
Then the page that throws the exception's OnNavigatedTo event:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if (NavigationContext.QueryString.ContainsKey("key"))
{
actualProject = NavigationContext.QueryString["key"];
try
{
//Read subjectList from IsolatedStorage
subjectList = readSetting(actualProject) != null ? (List<String>)readSetting(actualProject) : new List<String>();
//Put the subjectList into the subjectListBox
subjectListBox.ItemsSource = subjectList;
//Set the subjectsPageTitle to the "actualProject" value, to display the name of the current open project at the top of the screen
subjectsPageTitle.Text = actualProject;
}
catch (Exception)
{
if (language.Equals("en."))
{
// Language is set to english
MessageBox.Show("Couldn't open the project, please try again or please report the error to Accelerated Code - details on the about page");
}
else if (language.Equals("no."))
{
// Language is set to norwegian
MessageBox.Show("Kunne ikke åpne prosjektet, vennligst prøv igjen eller rapporter problemet til Accelerated Code - du finner detaljer på om-siden");
}
}
}
}
Exception:
_exception {System.ArgumentException: Value does not fall within the expected range.} System.Exception {System.ArgumentException}
My theory:
The app kind of loads the currently opened and modified List. Is that possible? No idea.
So there are a number of ways to pass data between pages.
The way you have chosen is the least suggested.
You can use the PhoneApplicationService.Current dictionary but this is messy also if you have a ton of variables, doesn't persist after app shut down and could be simplified.
I wrote a free DLL that kept this exact scenario in mind called EZ_iso.
You can find it here
Basically what you would do to use it is this.
[DataContractAttribute]
public class YourPageVars{
[DataMember]
public Boolean Value1 = false;
[DataMember]
public String Value2 = "And so on";
[DataMember]
public List<String> MultipleValues;
}
Once you have your class setup you can pass it easily between pages
YourPageVars vars = new YourPageVars { /*Set all your values*/ };
//Now we save it
EZ_iso.IsolatedStorageAccess.SaveFile("PageVars",vars);
That's it! Now you can navigate and retrieve the file.
YourPageVars vars = (YourPageVars)EZ_iso.IsolatedStorageAccess.GetFile("PageVars",typeof(YorPageVars));
This is nice because you can use it for more than navigation. You can use it for anything that would require Isolated storage. This data is serialized to the device now so even if the app shuts down it will remain. You can of course always delete the file if you choose as well.
Please make sure to refer to the documentation for any exceptions you have. If you still need help feel free to hit me up on twitter #Anth0nyRussell or amr#AnthonyRussell.info

Ektron taxonomy and library items (in v9)

We recently upgraded from Ektron 8.6 to 9.0 (Ektron CMS400.NET, Version: 9.00 SP2(Build 9.0.0.249)).
I have some code (below) which we use to display links to items in a taxonomy. Under 8.6, this would show library items if they had been added to the taxonomy. As of 9.0, it no longer displays library items. It still works for DMS items and normal pages (all first class content in Ektron).
private List<ContentData> getTaxonomyItems(long TaxonomyId)
{
listContentManager = new ContentManager();
criteria = new ContentTaxonomyCriteria(ContentProperty.Id, EkEnumeration.OrderByDirection.Ascending);
criteria.PagingInfo = new Ektron.Cms.PagingInfo(400); // there's a lot of items and I don't want to page them.
criteria.AddFilter(TaxonomyId, true); // this gets sub taxonomies too :)
List<ContentData> contentList = listContentManager.GetList(criteria);
return contentList;
}
(I would love to simply say to users to use the DMS instead of the library, but we have a security requirement and I'm not aware of a way I can enforce security on DMS items like we can with library items by dropping a webconfig file in the library folder.)
Is this a bug that anyone else has experienced?
Or is there a problem with my code (did an API change in the upgrade to 9.0)?
Thanks.
I ended up emailing Ektron support in Sydney (I'm in Australia), and they said:
I would expect ContentManager to only return content, not library
items – must have been a loophole which is now closed. Taxonomy is the
way to go.
So I used some of the code they provided and came up with the following, which appears to work...
private List<TaxonomyItemData> getTaxonomyItems(long TaxonomyId)
{
List<TaxonomyItemData> list = new List<TaxonomyItemData>();
TaxonomyManager taxManager = new TaxonomyManager(Ektron.Cms.Framework.ApiAccessMode.Admin);
TaxonomyCriteria taxonomyCriteria = new Ektron.Cms.Organization.TaxonomyCriteria();
taxonomyCriteria.AddFilter(Ektron.Cms.Organization.TaxonomyProperty.Path,
Ektron.Cms.Common.CriteriaFilterOperator.StartsWith, GetTaxonomyPathById(TaxonomyId));
List<TaxonomyData> TaxonomyDataList = taxManager.GetList(taxonomyCriteria);
foreach (TaxonomyData taxd in TaxonomyDataList)
{
TaxonomyData taxTree = taxManager.GetTree(taxd.Path,
1, // depth. doesn't seem to work. have to manually tranverse lower taxonomies.
true, // include items
null,
Ektron.Cms.Common.EkEnumeration.TaxonomyType.Content,
Ektron.Cms.Common.EkEnumeration.TaxonomyItemsSortOrder.taxonomy_item_display_order);
foreach (TaxonomyItemData taxItem in taxTree.TaxonomyItems)
{
list.Add(taxItem);
}
}
return list;
}
private static String GetTaxonomyPathById(long taxonomyId)
{
TaxonomyManager tMgr = new TaxonomyManager();
TaxonomyData tData = tMgr.GetItem(taxonomyId);
if (tData != null)
{
return tData.Path;
}
return "";
}
This code fetches items for all the child taxonomies as well as returning library items.
The one problem is that it fetches duplicates for some items, but those are easy to clean out.
I was also told by Ektron that...
TaxonomyManager.GetItem(“{path}”) is a more efficient way to get the
categories
That's why I've included the GetTaxonomyPathById() method (inspired by this blog post: http://www.nimbleuser.com/blog/posts/2009/iterating-through-ektron-content-in-multiple-taxonomies-via-directly-interfacing-with-search-indexing-services/ )

OData client only returning last entry in sequence?

I'm hoping that I'm just using the API incorrectly, but for some reason, when I query my oData service from wp7, I am only receiving the last entry in the sequence. I'm pretty sure the service is working just fine as I'm able to just visit the oData query URL in the browser and get the correct results. However, the following method only ends up displaying one item on the list.
I based the following code from the sample at this blog post: http://chriskoenig.net/2010/10/30/odata-v2-and-windows-phone-7/
The observable collection which is passed in is the one which is bound to the wpf listbox.
private static void LoadRuntimeData(ObservableCollection<CategoryItem> items)
{
var catalog = GetCatalog();
var queryUri = new Uri("/Categories?&$orderby=Name", UriKind.Relative);
var categories = new DataServiceCollection<Category>(catalog);
var queryHandle = App.ViewModel.StartQuerying();
categories.LoadAsync(queryUri);
categories.LoadCompleted += (e, c) =>
{
using (queryHandle)
{
var serverItems = categories.Select(k => new CategoryItem
{
Name = k.Name,
Description = k.Description
});
items.Clear();
foreach (var item in serverItems)
{
items.Add(item);
}
}
};
}
Any tips would be greatly appreciated.
Edit: per a comment below, I've uploaded the source code in which this issue is reproducible: http://khanviewer.codeplex.com/
Taking a quick stab at this (and I suspect that Chris would know better).
But don't you need to somehow identify/tag with an attribute a primary key column (the property or properties that define uniqueness).
I know I have run into something similar to this with RIA Services, and the issue there was that I wasn't setting a value for the unique identifier column. As a result I saw all my data come down, but the when the client got the data it saw all the data as a single record.
Jay

Categories

Resources