simple way of adding an weather API to an windows app - e-commerce

I am making an e-commerce app and I wanted to suggest season based products.how would i use the weather API to access the present location of the user and finding out the climate at that place and suggest him the products accordingly.

I don't know what programming language your using, but assuming it's C#, here's some code:
First of all, you're going to have to add these classes, which I generated with http://json2csharp.com/ :
public class Coord
{
public double lon { get; set; }
public double lat { get; set; }
}
public class Weather
{
public int id { get; set; }
public string main { get; set; }
public string description { get; set; }
public string icon { get; set; }
}
public class Main
{
public double temp { get; set; }
public int pressure { get; set; }
public int humidity { get; set; }
public double temp_min { get; set; }
public double temp_max { get; set; }
}
public class Wind
{
public double speed { get; set; }
public double deg { get; set; }
}
public class Clouds
{
public int all { get; set; }
}
public class Sys
{
public int type { get; set; }
public int id { get; set; }
public double message { get; set; }
public string country { get; set; }
public int sunrise { get; set; }
public int sunset { get; set; }
}
public class RootObject
{
public Coord coord { get; set; }
public List<Weather> weather { get; set; }
public string #base { get; set; }
public Main main { get; set; }
public Wind wind { get; set; }
public Rain rain { get; set; }
public Clouds clouds { get; set; }
public int dt { get; set; }
public Sys sys { get; set; }
public int id { get; set; }
public string name { get; set; }
public int cod { get; set; }
}
Then, you can call the API from OpenWeatherMap.org, and use JSON.NET to deserialize it (You can find the package on Nuget) Please note that you're going to have to replace "YourAppID" with yours, which you can create here: http://openweathermap.org/appid
using (HttpClient client = new HttpClient())
{
using (HttpResponseMessage response = await client.GetAsync(("http://api.openweathermap.org/data/2.5/weather?lat=" + Position.Coordinate.Latitude.ToString() + "&lon=" + Position.Coordinate.Longitude.ToString() + "&APPID=" + YourAppID)))
{
using (Stream stream = response.Content.ReadAsStreamAsync().Result)
{
using (StreamReader reader = new StreamReader(stream))
{
string json = reader.ReadToEnd();
var root = JsonConvert.DeserializeObject<RootObject>(json);
//Here, you write a ton of if statements, such as the following:
if(root.Main.temp > 32)
{
//Suggest a large coat to the user
}
}
}
}
}

Related

Mapbox matching response convert to dynamic json in ASP.NET Core

I want to use mapbox matching in ASP.NET Core. This link you can get response https://api.mapbox.com/matching/v5/mapbox/driving/..
I want to convert this response to dynamic json in Asp.net core, I use this line
var jsonResponse = JsonConvert.DeserializeObject(mapResponse);
but I get empty values. Any help?
Firstly, The API you have shared I got follwing response using
postman:
If its same what you are getting then I follow below steps to retrive
the value from the API response in C# asp.net core controller
Model You should have :
public class Admin
{
public string iso_3166_1_alpha3 { get; set; }
public string iso_3166_1 { get; set; }
}
public class Leg
{
public List<object> via_waypoints { get; set; }
public List<Admin> admins { get; set; }
public double weight { get; set; }
public double duration { get; set; }
public List<object> steps { get; set; }
public double distance { get; set; }
public string summary { get; set; }
}
public class Matching
{
public double confidence { get; set; }
public string weight_name { get; set; }
public double weight { get; set; }
public double duration { get; set; }
public double distance { get; set; }
public List<Leg> legs { get; set; }
public string geometry { get; set; }
}
public class Tracepoint
{
public int matchings_index { get; set; }
public int waypoint_index { get; set; }
public int alternatives_count { get; set; }
public double distance { get; set; }
public string name { get; set; }
public List<double> location { get; set; }
}
public class MapResponseClass
{
public List<Matching> matchings { get; set; }
public List<Tracepoint> tracepoints { get; set; }
public string code { get; set; }
public string uuid { get; set; }
}
Asp.net core Controller:
public async Task<IActionResult> CallMapAPI()
{
try
{
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("https://api.mapbox.com/matching/v5/mapbox/driving/-117.17282,32.71204;-117.17288,32.71225;-117.17293,32.71244;-117.17292,32.71256;-117.17298,32.712603;-117.17314,32.71259;-117.17334,32.71254?access_token=pk.eyJ1Ijoibm92ZXJzbWFwIiwiYSI6ImNreTdwc3ppNTE3dzkyb3B2MnVzNXpueTUifQ.csYTL2GKkl99Yqk_TQjr5w");
response.EnsureSuccessStatusCode();
string mapAPIjson = await response.Content.ReadAsStringAsync();
var data = JsonConvert.DeserializeObject<MapResponseClass>(mapAPIjson);
}
catch (Exception ex)
{
throw;
}
return data;
}}
Output:
Note:
You should bound your class as per your API response. What I am
assuming of your empty values is you haven't converted the relevant
class accordingly. I hope above steps guided you accordingly.

Save data on local storage

I am developing an app using Xamarin Forms PCL.
I want to save this class (I use this class as List in code)
public class TagInformation {
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public string name { get; set; }
public bool isJob { get; set; }
public string _color { get; set; }
[Ignore]
public Color color { get; set; }
[Ignore]
public JobInformation jobInformation { get; set; }
public TagInformation(Color c, string n) {
color = c;
_color = c.ToHex();
name = n;
isJob = false;
}
public TagInformation() {
}
public void setColor() {
color = Color.FromHex(_color);
}
}
public class JobInformation {
public string shopName { get; set; }
public int wage { get; set; }
public bool isHoliday { get; set; }
public int holidayWage { get; set; }
public bool isMid { get; set; }
public int midnightWage { get; set; }
public bool[] holidayFlgs { get; set; }
public DateTime midStart { get; set; }
public DateTime midEnd { get; set; }
public int tranceportCost { get; set; }
public int closeDay { get; set; }
public int payMentDay { get; set; }
public TimeSpan shortRest { get; set; }
public TimeSpan longRest { get; set; }
public TimeSpan shortRestTime { get; set; }
public TimeSpan longRestTime { get; set; }
public TimeSpan commuteTime { get; set; }
public JobInformation() {
/* do samething */
}
}
Using SQLite, this class has another class, so it doesn't work on.
Is there any other way?
Do you have any ideas?
You could try to use Xamarin.Essentials: Preferences to save it as a json string.
1.Install the Newtonsoft.Json nuget.
2.Serialize your class to json string and save it with a key.
TagInformation tarinformation = xxxxx;
string jsonString = JsonConvert.SerializeObject(tarinformation);
Preferences.Set("your_key", jsonString); //save the data
3.Retrieve a value from preferences and deserialize the string.
var myValue = Preferences.Get("my_key", "default_value");//get the data string
TagInformation infor = JsonConvert.DeserializeObject<TagInformation>(myValue); //deserialize to your class

How to reference a nested array in a XAML Binding?

I have a complex model of data based on reading in a JSON file which has a collection of objects, properties and arrays.
I am reading my data into a model which I am populating with design-time data and instantiating in my UWP project in XAML like this:
<local:UntappdUserInfoSampleData x:Key="data1" />
I want to set the ItemsSource for a ListView control to a collection in my model but I'm not sure how to reference it in my data Binding.
My object model has this structure:
user
checkins
items[]
venue
venue_name
comments
badges
items[]
badge_id
badge_description
badge_image
small
medium
large
I want to get to badge_image.small within that stack as a Binding within my XAML.
I know how to get to higher level data like this to get to checkins.items[]:
<ListView x:Name="lvRecenCheckins"
d:DataContext="{StaticResource data1}"
ItemsSource="{Binding checkins.items}"
CanDragItems="False"
IsItemClickEnabled="True"
IsSwipeEnabled="False"
SelectionMode="None" ItemTemplate="{StaticResource RecentCheckinsTemplate}" Grid.Row="1"
/>
But how can I get all the way down to the items collection for checkins.items[].badges.items[]?
I can get to the collection I want in code behind with this as an example:
UntappdUserInfoSampleData usersampleinfo = new UntappdUserInfoSampleData();
string iii2 = usersampleinfo.checkins.items[].badges.items[0].badge_image.small;
I want to bind a different ListView to checkins.items[].badges.items[]
How can I do that?
Here are the data classes:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
namespace UntappdExplorer
{
public class UntappdUserInfoSampleData : User_User {
public UntappdUserInfoSampleData()
{
string[] names = this.GetType().GetTypeInfo().Assembly.GetManifestResourceNames();
Stream stream = this.GetType().GetTypeInfo().Assembly.GetManifestResourceStream("UntappdExplorer.DataModel.ricke_User_info.json");
string result = String.Empty;
using (StreamReader reader = new StreamReader(stream))
{
result = reader.ReadToEnd();
}
var resolver = new DefaultContractResolver(); // Cache for performance
var Serializersettings = new JsonSerializerSettings
{
ContractResolver = resolver,
Converters = { new IgnoreUnexpectedArraysConverter(resolver) },
};
User_RootObject rootJSON = JsonConvert.DeserializeObject<User_RootObject>(result, Serializersettings);
User_User userinfo = rootJSON.response.user;
uid = userinfo.uid;
id = userinfo.id;
user_name = userinfo.user_name;
first_name = userinfo.first_name;
last_name = userinfo.last_name;
user_avatar = userinfo.user_avatar;
user_avatar_hd = userinfo.user_avatar_hd;
user_cover_photo = userinfo.user_cover_photo;
user_cover_photo_offset = userinfo.user_cover_photo_offset;
is_private = userinfo.is_private;
location = userinfo.location;
url = userinfo.url;
bio = userinfo.bio;
is_supporter = userinfo.is_supporter;
is_moderator = userinfo.is_moderator;
relationship = userinfo.relationship;
block_status = userinfo.block_status;
untappd_url = userinfo.untappd_url;
account_type = userinfo.account_type;
stats = userinfo.stats;
recent_brews = userinfo.recent_brews;
checkins = userinfo.checkins;
media = userinfo.media;
contact = userinfo.contact;
date_joined = userinfo.date_joined;
settings = userinfo.settings;
}
}
public class User_User
{
public int uid { get; set; }
public int id { get; set; }
public string user_name { get; set; }
public string first_name { get; set; }
public string last_name { get; set; }
public string user_avatar { get; set; }
public string user_avatar_hd { get; set; }
public string user_cover_photo { get; set; }
public int user_cover_photo_offset { get; set; }
public int is_private { get; set; }
public string location { get; set; }
public string url { get; set; }
public string bio { get; set; }
public int is_supporter { get; set; }
public int is_moderator { get; set; }
public string relationship { get; set; }
public string block_status { get; set; }
public string untappd_url { get; set; }
public string account_type { get; set; }
public User_Stats stats { get; set; }
public User_RecentBrews recent_brews { get; set; }
public User_Checkins checkins { get; set; }
public User_Media2 media { get; set; }
public List<object> contact { get; set; }
public string date_joined { get; set; }
public User_Settings settings { get; set; }
}
public class User_RootObject
{
public User_Meta meta { get; set; }
public User_Notifications notifications { get; set; }
public User_Response response { get; set; }
}
public class User_Response
{
public User_User user { get; set; }
}
public class User_ResponseTime
{
public double time { get; set; }
public string measure { get; set; }
}
public class User_InitTime
{
public int time { get; set; }
public string measure { get; set; }
}
public class User_Meta
{
public int code { get; set; }
public User_ResponseTime response_time { get; set; }
public User_InitTime init_time { get; set; }
}
public class User_UnreadCount
{
public int comments { get; set; }
public int toasts { get; set; }
public int friends { get; set; }
public int messages { get; set; }
public int venues { get; set; }
public int veunes { get; set; }
public int others { get; set; }
public int news { get; set; }
}
public class User_Notifications
{
public string type { get; set; }
public User_UnreadCount unread_count { get; set; }
}
public class User_Stats
{
public int total_badges { get; set; }
public int total_friends { get; set; }
public int total_checkins { get; set; }
public int total_beers { get; set; }
public int total_created_beers { get; set; }
public int total_followings { get; set; }
public int total_photos { get; set; }
}
public class User_Beer
{
public int bid { get; set; }
public string beer_name { get; set; }
public string beer_label { get; set; }
public double beer_abv { get; set; }
public string beer_description { get; set; }
public string beer_style { get; set; }
public double auth_rating { get; set; }
public bool wish_list { get; set; }
}
public class User_Contact
{
public string twitter { get; set; }
public string facebook { get; set; }
public string instagram { get; set; }
public string url { get; set; }
}
public class User_Location
{
public string brewery_city { get; set; }
public string brewery_state { get; set; }
public double lat { get; set; }
public double lng { get; set; }
}
public class User_Brewery
{
public int brewery_id { get; set; }
public string brewery_name { get; set; }
public string brewery_slug { get; set; }
public string brewery_label { get; set; }
public string country_name { get; set; }
public User_Contact contact { get; set; }
public User_Location location { get; set; }
public int brewery_active { get; set; }
}
public class User_Item
{
public User_Beer beer { get; set; }
public User_Brewery brewery { get; set; }
}
public class User_RecentBrews
{
public int count { get; set; }
public List<User_Item> items { get; set; }
}
public class User_User2
{
public int uid { get; set; }
public string user_name { get; set; }
public string first_name { get; set; }
public string last_name { get; set; }
public string location { get; set; }
public int is_supporter { get; set; }
public string url { get; set; }
public string bio { get; set; }
public string relationship { get; set; }
public string user_avatar { get; set; }
public int is_private { get; set; }
public List<object> contact { get; set; }
}
public class User_Beer2
{
public int bid { get; set; }
public string beer_name { get; set; }
public string beer_label { get; set; }
public string beer_style { get; set; }
public string beer_slug { get; set; }
public double beer_abv { get; set; }
public int beer_active { get; set; }
public bool has_had { get; set; }
public double auth_rating { get; set; }
public bool wish_list { get; set; }
}
public class User_Contact2
{
public string twitter { get; set; }
public string facebook { get; set; }
public string instagram { get; set; }
public string url { get; set; }
}
public class User_Location2
{
public string brewery_city { get; set; }
public string brewery_state { get; set; }
public double lat { get; set; }
public double lng { get; set; }
}
public class User_Brewery2
{
public int brewery_id { get; set; }
public string brewery_name { get; set; }
public string brewery_slug { get; set; }
public string brewery_label { get; set; }
public string country_name { get; set; }
public User_Contact2 contact { get; set; }
public User_Location2 location { get; set; }
public int brewery_active { get; set; }
}
public class User_Comments
{
public int total_count { get; set; }
public int count { get; set; }
public List<object> items { get; set; }
}
public class User_User3
{
public int uid { get; set; }
public string user_name { get; set; }
public string first_name { get; set; }
public string last_name { get; set; }
public string bio { get; set; }
public string location { get; set; }
public string user_avatar { get; set; }
public string account_type { get; set; }
public List<object> venue_details { get; set; }
public object brewery_details { get; set; }
public string user_link { get; set; }
}
public class User_Item3
{
public int uid { get; set; }
public User_User3 user { get; set; }
public int like_id { get; set; }
public bool like_owner { get; set; }
public string created_at { get; set; }
}
public class User_Toasts
{
public int total_count { get; set; }
public int count { get; set; }
public bool auth_toast { get; set; }
public List<User_Item3> items { get; set; }
}
public class User_Media
{
public int count { get; set; }
public List<object> items { get; set; }
}
public class User_Source
{
public string app_name { get; set; }
public string app_website { get; set; }
}
public class User_Badges
{
public bool retro_status { get; set; }
public int count { get; set; }
public List<Item4> items { get; set; }
}
public class Item4
{
public int badge_id { get; set; }
public int user_badge_id { get; set; }
public string badge_name { get; set; }
public string badge_description { get; set; }
public string created_at { get; set; }
public BadgeImage badge_image { get; set; }
}
public class BadgeImage
{
public string sm { get; set; }
public string md { get; set; }
public string lg { get; set; }
}
public class User_Item2
{
public int checkin_id { get; set; }
public string created_at { get; set; }
public string checkin_comment { get; set; }
public double rating_score { get; set; }
public User_User2 user { get; set; }
public User_Beer2 beer { get; set; }
public User_Brewery2 brewery { get; set; }
////public object venue { get; set; }
public User_Venue venue { get; set; }
public User_Comments comments { get; set; }
public User_Toasts toasts { get; set; }
public User_Media media { get; set; }
public User_Source source { get; set; }
public User_Badges badges { get; set; }
}
//public class User_Venue
//{
// public int venue_id { get; set; }
// public string venue_name { get; set; }
// public string venue_slug { get; set; }
// public string primary_category { get; set; }
// public string parent_category_id { get; set; }
// public User_Categories categories { get; set; }
// public User_Location3 location { get; set; }
// public User_Contact3 contact { get; set; }
// public User_Foursquare foursquare { get; set; }
// public User_VenueIcon venue_icon { get; set; }
// public bool is_verified { get; set; }
//}
//public class User_Categories
//{
// public int count { get; set; }
// public List<User_Item3> items { get; set; }
//}
//public class User_Foursquare
//{
// public string foursquare_id { get; set; }
// public string foursquare_url { get; set; }
//}
public class User_Pagination
{
public string since_url { get; set; }
public string next_url { get; set; }
public int max_id { get; set; }
}
public class User_Checkins
{
public int count { get; set; }
public List<User_Item2> items { get; set; }
public User_Pagination pagination { get; set; }
}
public class User_Photo
{
public string photo_img_sm { get; set; }
public string photo_img_md { get; set; }
public string photo_img_lg { get; set; }
public string photo_img_og { get; set; }
}
public class User_User4
{
public int uid { get; set; }
public string user_name { get; set; }
public string location { get; set; }
public string bio { get; set; }
public string first_name { get; set; }
public string last_name { get; set; }
public string user_avatar { get; set; }
public string account_type { get; set; }
public object url { get; set; }
}
public class User_Beer3
{
public int bid { get; set; }
public string beer_name { get; set; }
public string beer_label { get; set; }
public double beer_abv { get; set; }
public string beer_style { get; set; }
public string beer_description { get; set; }
public double auth_rating { get; set; }
public bool wish_list { get; set; }
}
public class User_Contact3
{
public string twitter { get; set; }
public string facebook { get; set; }
public string instagram { get; set; }
public string url { get; set; }
}
public class User_Location3
{
public string brewery_city { get; set; }
public string brewery_state { get; set; }
public double lat { get; set; }
public double lng { get; set; }
}
public class User_Brewery3
{
public int brewery_id { get; set; }
public string brewery_name { get; set; }
public string brewery_slug { get; set; }
public string brewery_label { get; set; }
public string country_name { get; set; }
public User_Contact3 contact { get; set; }
public User_Location3 location { get; set; }
public int brewery_active { get; set; }
}
public class User_Item5
{
public string category_name { get; set; }
public string category_id { get; set; }
public bool is_primary { get; set; }
}
public class User_Categories
{
public int count { get; set; }
public List<User_Item5> items { get; set; }
}
public class User_Location4
{
public string venue_address { get; set; }
public string venue_city { get; set; }
public string venue_state { get; set; }
public string venue_country { get; set; }
public double lat { get; set; }
public double lng { get; set; }
}
public class User_Contact4
{
public string twitter { get; set; }
public string venue_url { get; set; }
}
public class User_Foursquare
{
public string foursquare_id { get; set; }
public string foursquare_url { get; set; }
}
public class User_VenueIcon
{
public string sm { get; set; }
public string md { get; set; }
public string lg { get; set; }
}
public class User_Venue
{
public int venue_id { get; set; }
public string venue_name { get; set; }
public string venue_slug { get; set; }
public string primary_category { get; set; }
public string parent_category_id { get; set; }
public User_Categories categories { get; set; }
public User_Location4 location { get; set; }
public User_Contact4 contact { get; set; }
public User_Foursquare foursquare { get; set; }
public User_VenueIcon venue_icon { get; set; }
public bool is_verified { get; set; }
}
public class User_Item4
{
public int photo_id { get; set; }
public User_Photo photo { get; set; }
public string created_at { get; set; }
public int checkin_id { get; set; }
public User_User4 user { get; set; }
public User_Beer3 beer { get; set; }
public User_Brewery3 brewery { get; set; }
public User_Venue venue { get; set; }
}
public class User_Media2
{
public int count { get; set; }
public List<User_Item4> items { get; set; }
}
public class User_Badge
{
public int badges_to_facebook { get; set; }
public int badges_to_twitter { get; set; }
}
public class User_Checkin
{
public int checkin_to_facebook { get; set; }
public int checkin_to_twitter { get; set; }
public int checkin_to_foursquare { get; set; }
}
public class User_Navigation
{
public int default_to_checkin { get; set; }
}
public class User_Settings
{
public User_Badge badge { get; set; }
public User_Checkin checkin { get; set; }
public User_Navigation navigation { get; set; }
public string email_address { get; set; }
}
public class AvailableColor
{
public string name { get; set; }
public string color { get; set; }
public List<int> values { get; set; }
}
public class MainItems
{
public string ItemName { get; set; }
public ObservableCollection<SubItems> SubItemsList { get; set; }
}
public class SubItems
{
public string SubItemName { get; set; }
}
public class IgnoreUnexpectedArraysConverter<T> : IgnoreUnexpectedArraysConverterBase
{
public override bool CanConvert(Type objectType)
{
return typeof(T).IsAssignableFrom(objectType);
}
}
public class IgnoreUnexpectedArraysConverter : IgnoreUnexpectedArraysConverterBase
{
readonly IContractResolver resolver;
public IgnoreUnexpectedArraysConverter(IContractResolver resolver)
{
if (resolver == null)
throw new ArgumentNullException();
this.resolver = resolver;
}
public override bool CanConvert(Type objectType)
{
if (objectType.IsPrimitive || objectType == typeof(string))
return false;
return resolver.ResolveContract(objectType) is JsonObjectContract;
}
}
public abstract class IgnoreUnexpectedArraysConverterBase : JsonConverter
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var contract = serializer.ContractResolver.ResolveContract(objectType);
if (!(contract is JsonObjectContract))
{
throw new JsonSerializationException(string.Format("{0} is not a JSON object", objectType));
}
do
{
if (reader.TokenType == JsonToken.Null)
return null;
else if (reader.TokenType == JsonToken.Comment)
continue;
else if (reader.TokenType == JsonToken.StartArray)
{
var array = JArray.Load(reader);
if (array.Count > 0)
throw new JsonSerializationException(string.Format("Array was not empty."));
return existingValue ?? contract.DefaultCreator();
}
else if (reader.TokenType == JsonToken.StartObject)
{
// Prevent infinite recursion by using Populate()
existingValue = existingValue ?? contract.DefaultCreator();
serializer.Populate(reader, existingValue);
return existingValue;
}
else
{
throw new JsonSerializationException(string.Format("Unexpected token {0}", reader.TokenType));
}
}
while (reader.Read());
throw new JsonSerializationException("Unexpected end of JSON.");
}
public override bool CanWrite { get { return false; } }
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
///// END OF CLASSES /////////
}
Thanks,
Rick
Since you have nesting what you can do is show the checkins.items[] in the listview like you are showing now and once the user selects an "item" from the checkins (i.e, an item from the listView), within the Tapped or SelectionChanged event of the list view get the selected item and show its list of "badge" items in a new listView.
private void lvRecenCheckins_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var selectedCheckinItem = (sender as items).badges;
newListView.ItemSource = selectedCheckinItem.items;
}
Please note : this is based on the information that is provided in the question, actual class names might differ.
Hope this helps..! Do ask if you have any queries..
maybe you can have a look here: https://learn.microsoft.com/en-us/windows/uwp/xaml-platform/x-bind-markup-extension
I would try something like this:
<DataTemplate x:DataType="local:YourClass">
<Grid>
<TextBlock Text="{x:Bind GetFirstBadgeItemSmall(badges)}" />
</Grid>
</DataTemplate>
In your code behind, aka ViewModel you need to implement a new Method:
public string GetFirstBadgeItemSmall(IEnumerable<badge> badges)
{
return (badges?.items?[0].badge_image.small ?? string.empty);
}
Update
Maybe like this. I haven't tried it, just a guess:
<DataTemplate>
<Grid DataContext={Binding badges.items}>
<TextBlock Text="{Binding badge_image.small}" />
</Grid>
</DataTemplate>

Web API 2 OData v4 Requesting a Derived Entity Collection keep response 404

I m trying this tutorial: Requesting a Derived Entity Collection
When i make this request:
GET : http://tdd.stooges.com.my/api/paymentAbles?$format=application/json
I get this response:
{
"#odata.context":"http://tdd.stooges.com.my/api/$metadata#paymentAbles",
"value":[
{
"#odata.type":"#EFDB.Topup","id":1
},
{
"#odata.type":"#EFDB.Order","id":7
}
]
}
It is OK. But when i try this request:
GET : http://tdd.stooges.com.my/api/paymentAbles/EFDB.Order?$format=application/json
I get the response 404
I found a similar question on stackoverflow:
WCF Data Service gives 404 when making OData requests for derived types,
but the solution make all http request return 500 internal error.
How can I solve the problem? You can use this site: http://tdd.stooges.com.my for testing (for example using firebug to view teh request/response details).
Update :
modelBuilder.Entity<PaymentAble>()
.Map<Topup>(s => s.Requires("type").HasValue("topup"))
.Map<Order>(m => m.Requires("type").HasValue("order"));
[Table("payment_able")]
public abstract class PaymentAble
{
[Key]
public int id { get; set; }
public double amount { get; set; }
public string code { get; set; }
public string statusEnum { get; set; }
[ForeignKey("member")]
public int member_id { get; set; }
public virtual Member member { get; set; }
public virtual Payment payment { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTimeOffset rowCreatedDT { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
[ConcurrencyCheck]
public byte[] rowVersion { get; set; }
[ForeignKey("rowCreator")]
public int rowCreatorLoginPerson_id { get; set; }
[ForeignKey("rowLastModifiedBy")]
public int rowLastModifiedByLoginPerson_id { get; set; }
public virtual LoginPerson rowCreator { get; set; }
public virtual LoginPerson rowLastModifiedBy { get; set; }
}
public class Topup : PaymentAble
{
}
public class Order : PaymentAble
{
[Column("order_GSTPercent")]
public double GSTPercent { get; set; }
[Column("order_clientName")]
public string clientName { get; set; }
[Column("order_clientEmail")]
public string clientEmail { get; set; }
[Column("order_clientHp")]
public string clientHp { get; set; }
public virtual List<OrderItem> items { get; set; }
}
[Table("order_item")]
public class OrderItem : RowInfo
{
[Key]
public int id { get; set; }
public int qty { get; set; }
public double amount { get; set; }
[ForeignKey("order")]
public int order_id { get; set; }
public virtual Order order { get; set; }
public virtual OrderCard card { get; set; }
}
public static IEdmModel GetModel()
{
ODataModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<LoginPerson>("loginPersons");
builder.EntitySet<Admin>("admins");
builder.EntitySet<Member>("members");
builder.EntitySet<Card>("cards");
builder.EntitySet<CardPackage>("cardPackages");
builder.EntitySet<Game>("games");
builder.EntitySet<Img>("imgs");
builder.EntitySet<Currency>("currencys");
builder.EntitySet<Topup>("topups");
builder.EntitySet<Order>("orders");
builder.EntitySet<OrderItem>("OrderItems");
builder.EntitySet<Payment>("payments");
builder.EntitySet<PaymentAble>("paymentAbles");
builder.Namespace = "RPC"; //test only
var gettotalFn = builder.EntityType<PaymentAble>().Collection.Function("getTotal");
gettotalFn.Returns<int>();
return builder.GetEdmModel();
}
config.MapODataServiceRoute("odata", "api", GetModel());
[ODataRoutePrefix("paymentAbles")]
public class PaymentAblesController : BaseController
{
[ODataRoute("")]
[EnableQuery(AllowedQueryOptions = AllowedQueryOptions.All)]
public IQueryable<PaymentAble> get()
{
return db.paymentAbles;
}
public async Task<IHttpActionResult> getTotal()
{
return Ok(15);
}
}

ASP.NET MVC ViewModel is null on Post Back - sometimes

depending on my input in an HTML form (6 or 6.5 - or in general, integer VS float) I get or don't get the following exception (it works with int and doesn't work with float):
The model item passed into the dictionary is null, but this dictionary requires a non-null model item of type 'System.Boolean'.
The ViewModel of my View is null and the problem gets visible in a custom template which expects a bool value, but gets null instead. We use ASP.NET MVC 4 with .Net 4.0, C# and Razor Templates.
After several hours debugging I came to the following conclusion(s):
Post Form-Data are identical (except the one property which is different, but still look correct)
The execution order is somehow weirdly different:
for int I get Application_BeginRequest->Filter which runs through my attributes->Action->View Rendering OR Redirect (everything Normal)
for float I get Application_BeginRequest->Filter which runs through my attributes->View Rendering->END WITH AN EXCEPTION and Empty ViewModel
I have checked it dozen times -> If I pass float the View somehow gets rendered without any Action (which I would have seen) to be executed (and of course the breakpoints were the same all the time). Unfortunately I couldn't see anything in the StackTrace anymore once the View got rendered.
the ViewModel of my View is:
public class JabCommonViewModel
{
public int JAB_ID { get; set; }
[UIHint("Checkbox")]
public bool JAB_gesperrt { get; set; }
[UIHint("Checkbox")]
public bool JAB_Kontrolliert { get; set; }
public int e001 { get; set; }
public string e002 { get; set; }
public int e005 { get; set; }
[UIHint("Checkbox")]
public bool e013 { get; set; }
public bool e014 { get; set; }
public short? e015 { get; set; }
public bool? e149 { get; set; }
public int? e649 { get; set; }
public int? e310 { get; set; }
public int? LastJabe311 { get; set; }
public int jabIdE013 { get; set; }
public int jabIdPrev { get; set; }
public int updCnt { get; set; }
public int checks { get; set; }
public bool calculateInEur { get; set; }
public FormViewModel AktivaPassiva { get; set; }
public FormViewModel GuV1GuV2 { get; set; }
public FormViewModel GuV3 { get; set; }
public ActsFormViewModel ActsForm { get; set; }
public CommonDataViewModel CommonDataForm { get; set; }
public CompanyHeadViewModel CompanyHeadForm { get; set; }
public FacilitiesOverviewModel FacilitiesOverview { get; set; }
}
public class FormViewModel
{
public string ShowAllCaption { get; set; }
public string HideAllCaption { get; set; }
public string CurrentCaption { get; set; }
public string PreviousCaption { get; set; }
public bool HasPreviousData { get; set; }
public IEnumerable<FieldViewModel> Fields { get; set; }
public FormViewModel()
{
Fields = new FieldViewModel[0];
}
}
public class FieldViewModel
{
public string Name { get; set; }
public string Title { get; set; }
public object Value { get; set; }
public bool IsDisabled { get; set; }
public bool IsCollapsible { get; set; }
public bool IsSpecialCase { get; set; } // used currently to expand/collapse groups on second level
public FieldViewModel Previous { get; set; }
public Category DataCategory { get; set; }
public IEnumerable<FieldViewModel> Related { get; set; }
public FieldViewModel()
{
Related = new FieldViewModel[0];
}
public FieldViewModel(string name, string title, object value, bool isDisabled, Category dataCategory = Category.None, bool isCollapsible = true)
{
Name = name;
Title = title;
Value = value;
IsDisabled = isDisabled;
DataCategory = dataCategory;
IsCollapsible = isCollapsible;
Related = new FieldViewModel[0];
}
}
....
The Post-Back Action is
public ActionResult Edit(JAB2 jab)
{
ComponentFactory.Logger.Debug("Edit with JAB2");
....
}
public class JAB2 : JAB
{
public int jabIdE013 { get; set; }
public JAB LastJab { get; set; }
public int checks { get; set; }
}
public class JAB : BaseModel
{
public JAB()
{
}
public bool e116 { get; set; }
public bool e117 { get; set; }
public bool e118 { get; set; }
public bool e119 { get; set; }
public bool e120 { get; set; }
public bool e121 { get; set; }
public bool e122 { get; set; }
public bool e123 { get; set; }
public bool e124 { get; set; }
public bool e125 { get; set; }
public short? e126 { get; set; }
... /* 100 more properties */ ...
[LocalizedDisplayName("e751", NameResourceType = typeof(Resources.ModelPropertyNames))]
public float? e751 { get; set; } /* the property which works as int but not as float */
}
The Post-Back is actually to the link
/JAB/Edit/
Still the correct method get's executed when e751 (the special property) has an integer value.
Also we use the autoNumeric-JavaScript Plugin on that field. Also we use the plugin with other fields but so far found the error only with this one. As well, we have one Workstation where we aren't able to reproduce the error so it occurs on 2 out of 3 workstations + test server.
So far, nothing I've found explains the fact that it works sometimes.
Thank you very much for taking the time and reading my post.
Do you have any Ideas what could be wrong or what I could check?