How to upload Pending Attachment to Yammer - httpwebrequest

I'm trying to upload files to yammer via REST Api.
the API say ,i could use
POST https://www.yammer.com/api/v1/messages.json
attachmentn and pending_attachmentn - Yammer provides two methods to associate attachments with a message. Both make use of multi-part HTTP upload (see RFC1867).
then i try to post my message via WebRequest.like this link
but unfortunately, i got "Internal Server Error"[500]. like this question
is anyone could tell me ,how to upload a file to yammer?
and , how to get a pending_attachment list?

Well, finally , I know the reason for the failure .
request format.
RFC 1867say:
Content-type: multipart/form-data, boundary=AaB03x
--AaB03x
content-disposition: form-data; name="field1"
Joe Blow
--AaB03x
content-disposition: form-data; name="pics"; filename="file1.txt"
Content-Type: text/plain
... contents of file1.txt ...
--AaB03x--
there two points
multipart/form-data, boundary=AaB03x ->
multipart/form-data; boundary=AaB03x
no empty line at first line
Content-type: multipart/form-data, boundary=AaB03x
--AaB03x
Content-Disposition: form-data; name="field1"
Joe Blow
--AaB03x
Content-Disposition: form-data; name="pics"; filename="file1.txt"
Content-Type: text/plain
... contents of file1.txt ...
--AaB03x--

I stuck for days just to post message with attachment. I have no idea how to post message with attachmentN, but it is working with pending_attachmentN method.
First you have to call pending_attachment API and get the result ID. Then assign the ID into pending_attachmentN on message API.
I refer to sample as my baseline code. Then I merged with this C# HttpClient 4.5 multipart/form-data upload
Find below code to post message with attachment to Yammer. Hope can save your days.
public static async Task<PendingAttachment> Upload(string FilePath)
{
byte[] byteFile = System.IO.File.ReadAllBytes(FilePath);
FileInfo fi = new FileInfo(FilePath);
PendingAttachment pa = null;
using (var client = new HttpClient())
{
string token = "XXXXXXXXXXXXX";
client.DefaultRequestHeaders.Add("Authorization", "Bearer" + token);
using (var content = new MultipartFormDataContent("Upload----" + DateTime.Now.ToString(CultureInfo.InvariantCulture)))
{
content.Add(new StreamContent(new MemoryStream(byteFile)), "attachment", fi.Name);
using (var message = await client.PostAsync("https://www.yammer.com/api/v1/pending_attachments", content))
{
if (message.IsSuccessStatusCode)
{
var result = await message.Content.ReadAsStringAsync();
pa = Newtonsoft.Json.JsonConvert.DeserializeObject<PendingAttachment>(result);
return pa;
}
}
}
}
return null;
}
var FilePath = #"D:\Workspace\Lorem ipsum dolor sit amet.docx";
var pa = await Upload(FilePath);
MessageParam message = new MessageParam()
{
body = "posting attachment",
group_id = XXXXXXX,
pending_attachment1 = pa.id
};
var result = await CreateMessageAsync(message);
PendingAttachment Class and its property class
public class PendingAttachment
{
public int id { get; set; }
public int network_id { get; set; }
public string url { get; set; }
public string web_url { get; set; }
public string type { get; set; }
public string name { get; set; }
public string original_name { get; set; }
public string full_name { get; set; }
public string description { get; set; }
public string content_type { get; set; }
public string content_class { get; set; }
public string created_at { get; set; }
public int owner_id { get; set; }
public bool official { get; set; }
public string small_icon_url { get; set; }
public string large_icon_url { get; set; }
public string download_url { get; set; }
public string thumbnail_url { get; set; }
public string preview_url { get; set; }
public string large_preview_url { get; set; }
public int size { get; set; }
public string owner_type { get; set; }
public string last_uploaded_at { get; set; }
public int last_uploaded_by_id { get; set; }
public string last_uploaded_by_type { get; set; }
public object uuid { get; set; }
public object transcoded { get; set; }
public object streaming_url { get; set; }
public string path { get; set; }
public int y_id { get; set; }
public string overlay_url { get; set; }
public string privacy { get; set; }
public object group_id { get; set; }
public bool is_pending { get; set; }
public int height { get; set; }
public int width { get; set; }
public string scaled_url { get; set; }
public Image image { get; set; }
public int latest_version_id { get; set; }
public string status { get; set; }
public Latest_Version latest_version { get; set; }
public Stats stats { get; set; }
public string _OriginalFileName { get; set; }
}
public class Image
{
public string url { get; set; }
public int size { get; set; }
public string thumbnail_url { get; set; }
}
public class Latest_Version
{
public int id { get; set; }
public int file_id { get; set; }
public string content_type { get; set; }
public int size { get; set; }
public int uploader_id { get; set; }
public string created_at { get; set; }
public string path { get; set; }
public string download_url { get; set; }
public string thumbnail_url { get; set; }
public string preview_url { get; set; }
public string large_preview_url { get; set; }
public string post_processed_id { get; set; }
public object streaming_url { get; set; }
public string revert_url { get; set; }
public int height { get; set; }
public int width { get; set; }
public string scaled_url { get; set; }
public string thumbnail_path { get; set; }
public string preview_path { get; set; }
public string large_preview_path { get; set; }
public string status { get; set; }
}
public class Stats
{
public int following { get; set; }
public int followers { get; set; }
public int updates { get; set; }
public object first_reply_id { get; set; }
public object first_reply_at { get; set; }
public int latest_reply_id { get; set; }
public string latest_reply_at { get; set; }
public int shares { get; set; }
}

Related

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>

simple way of adding an weather API to an windows app

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
}
}
}
}
}

Entity Framework Parent\Child Retrieval

I have an ID of a "Component" parent record that I need to retrieve all the "Attachment" child records. The grid I am using need fields returned an placed in "TheComponentAttachmentsJoinedTable" I am only able to retrieve one record. I have used the value of FirstorDefault. That is the only way it will accept the line of code without complaining about the IEnumerable to int. Could someone please explain what is incorrect?
public class Component
{
public int ID { get; set; }
public string ComponentCode { get; set; }
public string ComponentDescription { get; set; }
public double ComponentWeight { get; set; }
public double ComponentQuantity { get; set; }
public string LastModUser { get; set; }
public DateTime LastModDate { get; set; }
public virtual ICollection<Attachment> Attachments { get; set; }
public virtual ICollection<Product> Products { get; set; }
public virtual ICollection<Element> Elements { get; set; }
}
public class Attachment
{
public int ID { get; set; }
public string AttachmentDescription { get; set; }
public string OriginalName { get; set; }
public string MimeType { get; set; }
public byte[] bytes { get; set; }
public string LastModUser { get; set; }
public DateTime LastModDate { get; set; }
//Navigation
public virtual ICollection<Element> Elements { get; set; }
public virtual ICollection<Component> Components { get; set; } //lt M-m
}
public class TheComponentAttachmentsJoinedTable
{
public int ComponentID { get; set; }
public int AttachmentID { get; set; }
public string OriginalName { get; set; }
}
public static List<TheComponentAttachmentsJoinedTable> ComponentAttachments_GetAllByComponentID(int ComponentID)
{
using (TheContext TheDB = new TheContext())
{
var r = (from x in TheDB.Component
.Where(x => x.ID == ComponentID)
.Include(x => x.Attachments)
select new TheComponentAttachmentsJoinedTable
{
ComponentID = x.ID,
AttachmentID = x.Attachments.Select(y => (y.ID)).FirstOrDefault(),
OriginalName = x.Attachments.Select(y => y.OriginalName).FirstOrDefault().ToString(),
}
);
return r.ToList();
}

WCF cannot implement interface - no matching return type

Why do I get this error:
Error 1 'JoomlaWebservice.KundeService' does not implement interface
member 'JoomlaWebservice.ServiceInterface.HentOpgave(int)'.
'JoomlaWebservice.KundeService.HentOpgave(int)' cannot implement
'JoomlaWebservice.ServiceInterface.HentOpgave(int)' because it does
not have the matching return type of
'JoomlaWebservice.Opgave'. C:\Visual Studio
2010\Projects\JoomlaWebservice\JoomlaWebservice\KundeService.svc.cs 12 18 JoomlaWebservice
Code (Service):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
namespace JoomlaWebservice
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
public class KundeService : ServiceInterface
{
LIMSEntities LimsEntities;
public class OpgaveOverskrift
{
public int id { get; set; }
public string nummer { get; set; }
public string sagsnavn { get; set; }
public string sagsnr { get; set; }
public string matrix { get; set; }
public string status { get; set; }
}
public class Opgave
{
public int id { get; set; }
public string nummer { get; set; }
public string sagsnavn { get; set; }
public string sagsnr { get; set; }
public string journalnr { get; set; }
public string omnummer { get; set; }
public string matrix { get; set; }
public string status { get; set; }
public string anlaeg { get; set; }
public string anlaeg_kode2 { get; set; }
public bool akkrediteret { get; set; }
public string modtagdato { get; set; }
public string analysedato { get; set; }
public string rapportdato { get; set; }
public int antalproever { get; set; }
public string preopbevar { get; set; }
public int antalbilag { get; set; }
public string rapportnoter { get; set; }
public string afssagsbehandler_navn { get; set; }
public string afssagsbehandler_titel { get; set; }
public string hmansvarlig_navn { get; set; }
public string hmansvarlig_titel { get; set; }
public string kontakt { get; set; } //k0_kontakt01
public string afdeling { get; set; }
public string adresse { get; set; }
public string nation { get; set; }
public string postnummer { get; set; }
public string distrikt { get; set; }
public string postdist { get; set; } //std00002
}
public class Parameter
{
public int id { get; set; }
public int o1id { get; set; }
public string minimum { get; set; }
public string vejledende { get; set; }
public string maksimum { get; set; }
public string bemaerkning { get; set; }
public string parameter { get; set; }
public int metoderf { get; set; }
public int raekkefoelge { get; set; }
public string enhed { get; set; }
public string metoderef { get; set; }
public string detektionsgraense { get; set; }
public string nedremaalegraense { get; set; }
public string oevremaalegraense { get; set; }
public string knaek { get; set; }
public string nedreusikkerhedabs { get; set; }
public string nedreusikkerhedrel { get; set; }
public string oevreusikkerhedabs { get; set; }
public string oevreusikkerhedrel { get; set; }
public string resultat { get; set; }
public int a0id { get; set; }
public bool akkrediteret { get; set; }
public string analysested { get; set; }
public string kommentar { get; set; }
public int laboratorieid { get; set; } //a_internmetode
public string danakkode { get; set; } //k0_kontakt01
}
public List<Parameter> Parametre(int o1id)
{
using (LimsEntities = new LIMSEntities())
{
return (from i in LimsEntities.O2_Parameter01
where i.O1ID == o1id
select new Parameter()
{
a0id = i.A0ID.HasValue ? (int)i.A0ID : 0,
akkrediteret = i.Akkrediteret.HasValue ? (bool)i.Akkrediteret : false,
analysested = i.AnalyseSted,
bemaerkning = i.Bemærkning,
detektionsgraense = i.Detektionsgrænse,
enhed = i.Enhed,
id = i.ID,
knaek = i.Knæk,
kommentar = i.Kommentar,
maksimum = i.Maksimum,
metoderef = i.Metoderef,
metoderf = i.MetodeRf.HasValue ? (int)i.MetodeRf : 1,
minimum = i.Minimum,
nedremaalegraense = i.NedreMålegrænse,
nedreusikkerhedabs = i.NedreUsikkerhedAbs,
nedreusikkerhedrel = i.NedreUsikkerhedRel,
o1id = i.O1ID,
oevremaalegraense = i.ØvreMålegrænse,
oevreusikkerhedabs = i.ØvreUsikkerhedAbs,
oevreusikkerhedrel = i.ØvreUsikkerhedRel,
parameter = i.Parameter,
raekkefoelge = i.Rækkefølge.HasValue ? (int)i.Rækkefølge : 1,
resultat = i.Resultat,
vejledende = i.VejledendeVærdi,
laboratorieid = i.ParameterIAnalyser.A_InternMetode.K0ID.HasValue ? (int)i.ParameterIAnalyser.A_InternMetode.K0ID : 0,
danakkode = i.ParameterIAnalyser.A_InternMetode.K0_Kontakt01.DANAKkode
}).ToList();
}
}
public class Proeve
{
public int id { get; set; }
public int o0id { get; set; }
public string omfang { get; set; }
public string formaal { get; set; }
public string proevetager { get; set; }
public string udtagdatostart { get; set; }
public string udtagdatoslut { get; set; }
public string dybde { get; set; }
public string proeveid { get; set; }
public string abtekst { get; set; } //ab_formål
}
public List<Proeve> Proever(int o0id)
{
using (LimsEntities = new LIMSEntities())
{
return (from i in LimsEntities.O1_Prøve
join f in LimsEntities.AB_Formål on i.Formål equals f.ID.ToString() into fs
from f in fs.DefaultIfEmpty()
where i.O0ID == o0id
select new Proeve()
{
id = i.ID,
o0id = i.O0ID,
omfang = i.Omfang,
formaal = i.Formål,
proevetager = i.Prøvetager,
udtagdatostart = i.UdtagDatoStart,
udtagdatoslut = i.UdtagDatoSlut,
dybde = i.Dybde,
proeveid = i.PrøveID,
abtekst = f == null ? "" : f.Tekst
}).ToList();
}
}
public int Login(String username, String password)
{
LimsEntities = new LIMSEntities();
IEnumerable<K1_Kontaktperson01> kontakter = from k in LimsEntities.K1_Kontaktperson01
where k.HSBrugernavn == username && k.HSAdgangskode == password
select k;
return kontakter.FirstOrDefault().K0ID;
}
public List<OpgaveOverskrift> OpgaveOverskrifter(int k0id)
{
using (LimsEntities = new LIMSEntities())
{
return (from i in LimsEntities.O0_Opgave01
where i.K0ID == k0id
select new OpgaveOverskrift()
{
id = i.ID,
nummer = i.Nummer,
sagsnavn = i.Sagsnavn,
sagsnr = i.SagsNr,
matrix = i.Matrix,
status = i.Status
}).ToList();
}
}
public Opgave HentOpgave(int o0id)
{
/* Opgave test = new Opgave();
return test;*/
using (LimsEntities = new LIMSEntities())
{
return (from i in LimsEntities.O0_Opgave01
where i.ID == o0id
select new Opgave()
{
id = i.ID,
nummer = i.Nummer,
sagsnavn = i.Sagsnavn,
sagsnr = i.SagsNr,
matrix = i.Matrix,
journalnr = i.JournalNr,
omnummer = i.OMNummer,
status = i.Status,
anlaeg = i.Anlæg,
anlaeg_kode2 = i.Anlæg_Kode2,
akkrediteret = i.Akkrediteret,
modtagdato = i.ModtagDato,
analysedato = i.AnalyseDato,
rapportdato = i.RapportDato,
antalproever = i.AntalPrøver.HasValue ? (int)i.AntalPrøver.Value : 0,
preopbevar = i.PreOpbevar,
antalbilag = i.AntalBilag.HasValue ? (int)i.AntalBilag.Value : 0,
rapportnoter = i.RapportNoter,
afssagsbehandler_navn = i.AFSSagsbehandler_Navn,
afssagsbehandler_titel = i.AFSSagsbehandler_Titel,
hmansvarlig_navn = i.HMAnsvarlig_Navn,
hmansvarlig_titel = i.HMAnsvarlig_Titel,
kontakt = i.K0_Kontakt01.Kontakt,
afdeling = i.K0_Kontakt01.Afdeling,
adresse = i.K0_Kontakt01.Adresse,
nation = i.K0_Kontakt01.Nation,
postnummer = i.K0_Kontakt01.Postnummer,
distrikt = i.K0_Kontakt01.Distrikt,
postdist = i.K0_Kontakt01.std00002.postdist
}).FirstOrDefault();
}
}
}
}
Code (Interface):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
namespace JoomlaWebservice
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
[ServiceContract]
public interface ServiceInterface
{
[OperationContract]
int Login(String username, String password);
[OperationContract]
Opgave HentOpgave(int o0id);
// TODO: Add your service operations here
}
// Use a data contract as illustrated in the sample below to add composite types to service operations.
[DataContract]
public class OpgaveOverskrift
{
[DataMember]
public int id { get; set; }
[DataMember]
public string sagsnavn { get; set; }
[DataMember]
public string sagsnr { get; set; }
[DataMember]
public string matrix { get; set; }
[DataMember]
public string status { get; set; }
}
[DataContract]
public class Opgave
{
[DataMember]
public int id { get; set; }
[DataMember]
public string nummer { get; set; }
[DataMember]
public string sagsnavn { get; set; }
[DataMember]
public string sagsnr { get; set; }
[DataMember]
public string journalnr { get; set; }
[DataMember]
public string omnummer { get; set; }
[DataMember]
public string matrix { get; set; }
[DataMember]
public string status { get; set; }
[DataMember]
public string anlaeg { get; set; }
[DataMember]
public string anlaeg_kode2 { get; set; }
[DataMember]
public bool akkrediteret { get; set; }
[DataMember]
public string modtagdato { get; set; }
[DataMember]
public string analysedato { get; set; }
[DataMember]
public string rapportdato { get; set; }
[DataMember]
public int antalproever { get; set; }
[DataMember]
public string preopbevar { get; set; }
[DataMember]
public int antalbilag { get; set; }
[DataMember]
public string rapportnoter { get; set; }
[DataMember]
public string afssagsbehandler_navn { get; set; }
[DataMember]
public string afssagsbehandler_titel { get; set; }
[DataMember]
public string hmansvarlig_navn { get; set; }
[DataMember]
public string hmansvarlig_titel { get; set; }
[DataMember]
public string kontakt { get; set; } //k0_kontakt01
[DataMember]
public string afdeling { get; set; }
[DataMember]
public string adresse { get; set; }
[DataMember]
public string nation { get; set; }
[DataMember]
public string postnummer { get; set; }
[DataMember]
public string distrikt { get; set; }
[DataMember]
public string postdist { get; set; } //std00002
}
[DataContract]
public class Proeve
{
[DataMember]
public int id { get; set; }
[DataMember]
public int o0id { get; set; }
[DataMember]
public string omfang { get; set; }
[DataMember]
public string formaal { get; set; }
[DataMember]
public string proevetager { get; set; }
[DataMember]
public string udtagdatostart { get; set; }
[DataMember]
public string udtagdatoslut { get; set; }
[DataMember]
public string dybde { get; set; }
[DataMember]
public string proeveid { get; set; }
[DataMember]
public string abtekst { get; set; } //ab_formål
}
[DataContract]
public class Parameter
{
[DataMember]
public int id { get; set; }
[DataMember]
public int o1id { get; set; }
[DataMember]
public string minimum { get; set; }
[DataMember]
public string vejledende { get; set; }
[DataMember]
public string maksimum { get; set; }
[DataMember]
public string bemaerkning { get; set; }
[DataMember]
public string parameter { get; set; }
[DataMember]
public int metoderf { get; set; }
[DataMember]
public int raekkefoelge { get; set; }
[DataMember]
public string enhed { get; set; }
[DataMember]
public string metoderef { get; set; }
[DataMember]
public string detektionsgraense { get; set; }
[DataMember]
public string nedremaalegraense { get; set; }
[DataMember]
public string oevremaalegraense { get; set; }
[DataMember]
public string knaek { get; set; }
[DataMember]
public string nedreusikkerhedabs { get; set; }
[DataMember]
public string nedreusikkerhedrel { get; set; }
[DataMember]
public string oevreusikkerhedabs { get; set; }
[DataMember]
public string oevreusikkerhedrel { get; set; }
[DataMember]
public string resultat { get; set; }
[DataMember]
public int a0id { get; set; }
[DataMember]
public bool akkrediteret { get; set; }
[DataMember]
public string analysested { get; set; }
[DataMember]
public string kommentar { get; set; }
[DataMember]
public int laboratorieid { get; set; } //a_internmetode
[DataMember]
public string danakkode { get; set; } //k0_kontakt01
}
}
You're returning JoomlaWebservice.KundeService.Opgave, not JoomlaWebservice.Opgave. You need to change your code to either return the contract directly or to map between your created object and the contract.