I'm trying to use Integration Studio for the first time to create an extension to make an API call with a file upload. Unfortunately, I'm not very well versed with .NET. This is the code I'm trying to replicate on Integration Studio:
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;
}
So, this is what I've tried. I have created the following structures on Integration Studio:
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; }
}
As this extension will be used for mobile, I have added 2 input parameters, to send the FileData as well as the FileName, to avoid having to extract that data. I have added an output parameter with the data type PendingAttachment which is the structure mentioned above.
So the issue I'm facing is that since it is an async method, Visual Studio isn't allowing me to have an output parameter. So is there a way to fix this?
P.S: Yes, I have tried implementing this normally on Service Studio, by referencing the Box File Upload plugin. It did not work (gave a 500 error). I have also been assured that this method works properly.
Thank you for your help!
If you need to use an async method in one that's not, you can call the method .Wait() on the Task object returned by the async method. This will hold the calling thread until the asynchronous code has been fully executed.
Related
Trying best how to take the following classes and deserialize a Json file to return each class values back to Simpl+. I am able to receive the Total value but anything in a list I am at a lost.
public class Client
{
public string clientId { get; set; }
public string locale { get; set; }
public string location { get; set; }
public string auxiliaryId { get; set; }
public string description { get; set; }
public string type { get; set; }
public string typeDescription { get; set; }
public Hardware hardware { get; set; }
public Network network { get; set; }
}
public class Hardware
{
public string type { get; set; }
public string softwareVersion { get; set; }
public string serialNumber { get; set; }
public string hardwareVersion { get; set; }
public string model { get; set; }
}
public class Network
{
public string ip { get; set; }
public string mac { get; set; }
public object homepage { get; set; }
public string dhcpSubnet { get; set; }
}
public class Result
{
public List<Client> clients { get; set; }
public string total { get; set; }
public int limit { get; set; }
public int page { get; set; }
}
public class Root
{
public string jsonrpc { get; set; }
public object id { get; set; }
public Result result { get; set; }
}
I was able to resolve this by adding the following to the foreach statement:
args.MyIndex = (ushort)(rootObject.TriplePlayResult.clients.IndexOf(item) + 1);
I have some problems deserializing the following JSON string. On all of my other responses it works really good but not for this one. I tried so many different things and I checked the Stream class about 100 times. I also have used a generated class from json2csharp but all my deserialized Data is NULL.
My code to get the response:
public Stream getStream(string userID)
{
var request = GetRequest("streams/{channelID}", Method.GET);
request.AddUrlSegment("channelID", userID);
var response = restClient.Execute<Stream>(request);
return response.Data;
}
response.Content shows me as example something like that:
{
"stream":
{
"_id":25649270464,
"game":"test",
"broadcast_platform":"other",
"community_id":"xxxxxxxxx",
"community_ids":["xxxxxx"],
"viewers":2421,
"video_height":1080,
"average_fps":61.7876424715,
"delay":0,
"created_at":"2017-07-02T10:01:28Z",
"is_playlist":false,
"stream_type":"live",
"preview":
{
"small":"https://static-cdn.jtvnw.net/previews-ttv/live_user_lostaiming-80x45.jpg",
"medium":"https://static-cdn.jtvnw.net/previews-ttv/live_user_lostaiming-320x180.jpg",
"large":"https://static-cdn.jtvnw.net/previews-ttv/live_user_lostaiming-640x360.jpg",
"template":"https://static-cdn.jtvnw.net/previews-ttv/live_user_lostaiming-{width}x{height}.jpg"
},
"channel":
{
"mature":false,
"status":"Test"
,"broadcaster_language":"de",
"display_name":"LOSTAIMING",
"game":"test",
"language":"en",
"_id":44281267,
"name":"lostaiming",
"created_at":"2013-06-02T16:42:19.329009Z",
"updated_at":"2017-07-02T13:05:11.555285Z",
"partner":true,
"logo":"https://static-cdn.jtvnw.net/jtv_user_pictures/lostaiming-profile_image-e9d7ea0893748d6a-300x300.png",
"video_banner":"https://static-cdn.jtvnw.net/jtv_user_pictures/cc34c6b909a435ae-channel_offline_image-1920x1080.png",
"profile_banner":"https://static-cdn.jtvnw.net/jtv_user_pictures/c187e8871c0f6a2b-profile_banner-480.png",
"profile_banner_background_color":"",
"url":"https://www.twitch.tv/lostaiming",
"views":2292173,
"followers":55672,
"broadcaster_type":"",
"description":"Blubb"
}
}
}
And my Stream class looks like this:
class Stream
{
[JsonProperty("stream")]
public SubStream stream { get; set; }
}
class SubStream
{
[JsonProperty("_id")]
public string ID { get; set; }
[JsonProperty("game")]
public string Game { get; set; }
[JsonProperty("broadcast_platform")]
public string BroadcastPlatform { get; set; }
[JsonProperty("community_id")]
public string CommunityID { get; set; }
[JsonProperty("community_ids")]
public List<object> CommunityIDS { get; set; }
[JsonProperty("viewers")]
public long Viewers { get; set; }
[JsonProperty("video_height")]
public long VideoHeigt { get; set; }
[JsonProperty("average_fps")]
public double AverageFps { get; set; }
[JsonProperty("delay")]
public long Delay { get; set; }
[JsonProperty("createt_at")]
public DateTime CreatetAt { get; set; }
[JsonProperty("is_playlist")]
public bool IsPlaylist { get; set; }
[JsonProperty("stream_type")]
public string StreamType { get; set; }
[JsonProperty("preview")]
public StreamPreview Preview { get; set; }
[JsonProperty("channel")]
public Channel channel { get; set; }
}
class StreamPreview
{
[JsonProperty("small")]
public string SmallPreview { get; set; }
[JsonProperty("medium")]
public string MediumPreview { get; set; }
[JsonProperty("large")]
public string LargPreview { get; set; }
[JsonProperty("template")]
public string TemplatePreview { get; set; }
}
public class Channel
{
[JsonProperty("mature")]
public bool Mature { get; set; }
[JsonProperty("status")]
public string Status { get; set; }
[JsonProperty("broadcaster_language")]
public string BroadcasterLanguage { get; set; }
[JsonProperty("display_name")]
public string DisplayName { get; set; }
[JsonProperty("game")]
public string Game { get; set; }
[JsonProperty("language")]
public string Language { get; set; }
[JsonProperty("_id")]
public string ID { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("created_at")]
public DateTime CreatedAt { get; set; }
[JsonProperty("updated_at")]
public DateTime UpdatedAt { get; set; }
[JsonProperty("partner")]
public bool Partner { get; set; }
[JsonProperty("logo")]
public string Logo { get; set; }
[JsonProperty("video_banner")]
public string VideoBanner { get; set; }
[JsonProperty("profile_banner")]
public string ProfileBanner { get; set; }
[JsonProperty("profile_banner_background_color")]
public string ProfileBannerBackgroundColor { get; set; }
[JsonProperty("url")]
public string Url { get; set; }
[JsonProperty("views")]
public long Views { get; set; }
[JsonProperty("followers")]
public long Followers { get; set; }
[JsonProperty("broadcaster_type")]
public string BroadcastType { get; set; }
[JsonProperty("stream_key")]
public string StreamKey { get; set; }
[JsonProperty("email")]
public string Email { get; set; }
}
1) use JSON Utils (https://jsonutils.com/) to generate your C# classes (for attributes select JsonProperty)
2) Newtonsoft.Json is pretty much the standard best library to work with JSON formats in .NET, you can get it from nuget.
3) The code should look something like this, and deserialization should work without any problems:
class Program
{
private static void Main(string[] args)
{
var myObj = JsonConvert.DeserializeObject<JsonDef>(json);
Console.Read();
}
}
public class Preview
{
[JsonProperty("small")]
public string small { get; set; }
[JsonProperty("medium")]
public string medium { get; set; }
[JsonProperty("large")]
public string large { get; set; }
[JsonProperty("template")]
public string template { get; set; }
}
public class Channel
{
[JsonProperty("mature")]
public bool mature { get; set; }
[JsonProperty("status")]
public string status { get; set; }
[JsonProperty("broadcaster_language")]
public string broadcaster_language { get; set; }
[JsonProperty("display_name")]
public string display_name { get; set; }
[JsonProperty("game")]
public string game { get; set; }
[JsonProperty("language")]
public string language { get; set; }
[JsonProperty("_id")]
public int _id { get; set; }
[JsonProperty("name")]
public string name { get; set; }
[JsonProperty("created_at")]
public DateTime created_at { get; set; }
[JsonProperty("updated_at")]
public DateTime updated_at { get; set; }
[JsonProperty("partner")]
public bool partner { get; set; }
[JsonProperty("logo")]
public string logo { get; set; }
[JsonProperty("video_banner")]
public string video_banner { get; set; }
[JsonProperty("profile_banner")]
public string profile_banner { get; set; }
[JsonProperty("profile_banner_background_color")]
public string profile_banner_background_color { get; set; }
[JsonProperty("url")]
public string url { get; set; }
[JsonProperty("views")]
public int views { get; set; }
[JsonProperty("followers")]
public int followers { get; set; }
[JsonProperty("broadcaster_type")]
public string broadcaster_type { get; set; }
[JsonProperty("description")]
public string description { get; set; }
}
public class Stream
{
[JsonProperty("_id")]
public long _id { get; set; }
[JsonProperty("game")]
public string game { get; set; }
[JsonProperty("broadcast_platform")]
public string broadcast_platform { get; set; }
[JsonProperty("community_id")]
public string community_id { get; set; }
[JsonProperty("community_ids")]
public IList<string> community_ids { get; set; }
[JsonProperty("viewers")]
public int viewers { get; set; }
[JsonProperty("video_height")]
public int video_height { get; set; }
[JsonProperty("average_fps")]
public double average_fps { get; set; }
[JsonProperty("delay")]
public int delay { get; set; }
[JsonProperty("created_at")]
public DateTime created_at { get; set; }
[JsonProperty("is_playlist")]
public bool is_playlist { get; set; }
[JsonProperty("stream_type")]
public string stream_type { get; set; }
[JsonProperty("preview")]
public Preview preview { get; set; }
[JsonProperty("channel")]
public Channel channel { get; set; }
}
public class JsonDef
{
[JsonProperty("stream")]
public Stream stream { get; set; }
}
It's because of the DateTime format of the JSON. It is not in a well-formed .Net DateTime. so you can get it as a string and then convert it the way you want or change its format into a readable .Net one.
I deserialize complex JSON (Spotify Playlist) and get root level values but I cannot get branches values. I Google problem, try different options without success but, I assume its silly mistake or lack of knowledge so therefore just ask for help what I am missing?
My classes are:
public class Playlist
{
public string collaborative { get; set; }
public string description { get; set; }
//public <ExternalUrls> external_urls { get; set; } //object
//public List<Followers> followers { get; set; } //object
public string href { get; set; }
public string id { get; set; }
//public List<Image> images { get; set; } //array
public string name { get; set; }
}
public class Tracks
{
public string href { get; set; }
public Item items { get; set; } //object
public string limit { get; set; }
public string next { get; set; }
public string offset { get; set; }
public string previous { get; set; }
public string total { get; set; }
}
And code to deserialize looks like that:
StreamReader responseFromServer = new StreamReader(myWebResponse.GetResponseStream());
var dataResponse = responseFromServer.ReadToEnd();
responseFromServer.Close();
var elements = new JavaScriptSerializer().Deserialize<Playlist>(dataResponse);
RootBuffer.AddRow();
RootBuffer.collaborative = elements.collaborative.ToString();
foreach (Tracks trs in elements.tracks)
{
TracksBuffer.AddRow();
TracksBuffer.href = trs.href.ToString()
}
I genereated the classes using this excellent site: json2csharp.com
And used your existing deserialization code successfully with the following classes. It populated all the data including the child collections (brace yourself, it's a long one):
public class Playlist
{
public bool collaborative { get; set; }
public string description { get; set; }
public ExternalUrls external_urls { get; set; }
public Followers followers { get; set; }
public string href { get; set; }
public string id { get; set; }
public List<Image> images { get; set; }
public string name { get; set; }
public Owner owner { get; set; }
public bool #public { get; set; }
public string snapshot_id { get; set; }
public Tracks tracks { get; set; }
public string type { get; set; }
public string uri { get; set; }
}
public class ExternalUrls
{
public string spotify { get; set; }
}
public class Followers
{
public object href { get; set; }
public int total { get; set; }
}
public class Image
{
public object height { get; set; }
public string url { get; set; }
public object width { get; set; }
}
public class ExternalUrls2
{
public string spotify { get; set; }
}
public class Owner
{
public ExternalUrls2 external_urls { get; set; }
public string href { get; set; }
public string id { get; set; }
public string type { get; set; }
public string uri { get; set; }
}
public class ExternalUrls3
{
public string spotify { get; set; }
}
public class AddedBy
{
public ExternalUrls3 external_urls { get; set; }
public string href { get; set; }
public string id { get; set; }
public string type { get; set; }
public string uri { get; set; }
}
public class ExternalUrls4
{
public string spotify { get; set; }
}
public class Image2
{
public int height { get; set; }
public string url { get; set; }
public int width { get; set; }
}
public class Album
{
public string album_type { get; set; }
public List<object> available_markets { get; set; }
public ExternalUrls4 external_urls { get; set; }
public string href { get; set; }
public string id { get; set; }
public List<Image2> images { get; set; }
public string name { get; set; }
public string type { get; set; }
public string uri { get; set; }
}
public class ExternalUrls5
{
public string spotify { get; set; }
}
public class Artist
{
public ExternalUrls5 external_urls { get; set; }
public string href { get; set; }
public string id { get; set; }
public string name { get; set; }
public string type { get; set; }
public string uri { get; set; }
}
public class ExternalIds
{
public string isrc { get; set; }
}
public class ExternalUrls6
{
public string spotify { get; set; }
}
public class Track
{
public Album album { get; set; }
public List<Artist> artists { get; set; }
public List<object> available_markets { get; set; }
public int disc_number { get; set; }
public int duration_ms { get; set; }
public bool #explicit { get; set; }
public ExternalIds external_ids { get; set; }
public ExternalUrls6 external_urls { get; set; }
public string href { get; set; }
public string id { get; set; }
public string name { get; set; }
public int popularity { get; set; }
public string preview_url { get; set; }
public int track_number { get; set; }
public string type { get; set; }
public string uri { get; set; }
}
public class Item
{
public string added_at { get; set; }
public AddedBy added_by { get; set; }
public bool is_local { get; set; }
public Track track { get; set; }
}
public class Tracks
{
public string href { get; set; }
public List<Item> items { get; set; }
public int limit { get; set; }
public object next { get; set; }
public int offset { get; set; }
public object previous { get; set; }
public int total { get; set; }
}
Hope this helps.
I`m new in programming winodws 8 app , i have a webservice when i try to connect it using httprequest (Using URL with variables), this service return this:
{"d":"{\"sessionid\":\"twzv50okccwvgggeesjje2wa\",\"VersionInfo\":{\"Rel\":0,\"Ver\":0,\"Patch\":0,\"ForceUpdate\":0,\"UpdateType\":0,\"Globals\":{\"MultiSessionsAllowed\":true,\"CommCalcType\":2,\"PriceChangedTimer\":25,\"ValidLotsLocation\":2,\"CustumizeTradeMsg\":false,\"FirstWhiteLabeledOffice\":null,\"DealerTreePriv\":0,\"ClientConnectTimer\":200,\"ClientTimeoutTimer\":500,\"DefaultLots\":0.01,\"WebSecurityID\":\"agagag\",\"ServerGMT\":3}},\"SystemLockInfo\":{\"MinutesRemaining\":0,\"HoursRemaining\":0,\"DaysRemaining\":0,\"Maintanance\":0,\"WillBeLocked\":1},\"FirstWhiteLabel\":\"VertexFX 10\",\"WLID\":\"3\",\"CheckWhiteLabel\":true,\"Password\":\"1444\",\"Username\":\"test\",\"LastTickTime\":\"\/Date(1396307573431)\/\",\"SelectedAccount\":78821860,\"Name\":0,\"ServicePath\":null,\"GWSessionID\":\"56630\",\"IP\":\"Web (212.35.90.211)\",\"SessionDateStart\":\"01/04/2014 02:12:53\",\"CompanyName\":\"Hybrid Solutions\",\"UserId\":6119,\"DemoClient\":\"0\",\"FName\":\"omqrstu\",\"SName\":\"\",\"TName\":\"\",\"LName\":\"\",\"Sms\":null,\"isReadOnly\":\"0\",\"SchSms\":\"2\",\"AlertSms\":\"2\",\"Temp\":null,\"GMTOffset\":\"2\",\"SvrGMT\":\"3\",\"ClientType\":null,\"EnableNews\":\"1\",\"PublicSlideNews\":\"\",\"PrivateSlideNews\":\"Welcome to V 10\",\"DealerTreePriv\":1}"}
i have simple windows app with one button when i click the button i send the url with variables and i got the obj above , i want to use content of this object like UserID in if statement but with no vain i dont know how to use it in C# , can and body help me??
I use this code. I know it has many errors but I need someone guide me.
private void Button_Click(object sender, RoutedEventArgs e)
{
String uriString = "url";
var uri = new Uri(uriString);
var httpWebRequest = HttpWebRequest.Create(uri);
httpWebRequest.BeginGetResponse(new AsyncCallback(OnGettingResponse), httpWebRequest);
}
private void OnGettingResponse(IAsyncResult ar)
{
var outerRoot = JsonConvert.DeserializeObject<OuterRootObject>( json );
var root = JsonConvert.DeserializeObject<RootObject>( outerRoot.d );
MessageBox.Show(root.UserId);
}
This is kind of a nasty situation. What you're getting back is a JSON object with a single property (i.e. d) and that property contains a string of JSON. So you basically need to unwrap the inner JSON from it's envelope. The following classes/code should work (using JSON.NET to do the deserialization).
public class OuterRootObject
{
public string d { get; set; }
}
public class Globals
{
public bool MultiSessionsAllowed { get; set; }
public int CommCalcType { get; set; }
public int PriceChangedTimer { get; set; }
public int ValidLotsLocation { get; set; }
public bool CustumizeTradeMsg { get; set; }
public object FirstWhiteLabeledOffice { get; set; }
public int DealerTreePriv { get; set; }
public int ClientConnectTimer { get; set; }
public int ClientTimeoutTimer { get; set; }
public double DefaultLots { get; set; }
public string WebSecurityID { get; set; }
public int ServerGMT { get; set; }
}
public class VersionInfo
{
public int Rel { get; set; }
public int Ver { get; set; }
public int Patch { get; set; }
public int ForceUpdate { get; set; }
public int UpdateType { get; set; }
public Globals Globals { get; set; }
}
public class SystemLockInfo
{
public int MinutesRemaining { get; set; }
public int HoursRemaining { get; set; }
public int DaysRemaining { get; set; }
public int Maintanance { get; set; }
public int WillBeLocked { get; set; }
}
public class RootObject
{
public string sessionid { get; set; }
public VersionInfo VersionInfo { get; set; }
public SystemLockInfo SystemLockInfo { get; set; }
public string FirstWhiteLabel { get; set; }
public string WLID { get; set; }
public bool CheckWhiteLabel { get; set; }
public string Password { get; set; }
public string Username { get; set; }
public DateTime LastTickTime { get; set; }
public int SelectedAccount { get; set; }
public int Name { get; set; }
public object ServicePath { get; set; }
public string GWSessionID { get; set; }
public string IP { get; set; }
public string SessionDateStart { get; set; }
public string CompanyName { get; set; }
public int UserId { get; set; }
public string DemoClient { get; set; }
public string FName { get; set; }
public string SName { get; set; }
public string TName { get; set; }
public string LName { get; set; }
public object Sms { get; set; }
public string isReadOnly { get; set; }
public string SchSms { get; set; }
public string AlertSms { get; set; }
public object Temp { get; set; }
public string GMTOffset { get; set; }
public string SvrGMT { get; set; }
public object ClientType { get; set; }
public string EnableNews { get; set; }
public string PublicSlideNews { get; set; }
public string PrivateSlideNews { get; set; }
public int DealerTreePriv { get; set; }
}
var outerRoot = JsonConvert.DeserializeObject<OuterRootObject>( json );
var root = JsonConvert.DeserializeObject<RootObject>( outerRoot.d );
I have the following XML that I am getting back from a WebRequest:
<?xml version="1.0" encoding="UTF-8"?>
<search>
<total_items>5</total_items>
<page_size>10</page_size>
<page_count>1</page_count>
<page_number>1</page_number>
<page_items></page_items>
<first_item></first_item>
<last_item></last_item>
<search_time>0.044</search_time>
<events>
<event id="E0-001-053379749-0">
<title>Antibalas</title>
<url>http://test.com</url>
<description>stuff</description>
<start_time>2013-01-30 20:00:00</start_time>
<stop_time></stop_time>
<tz_id></tz_id>
<tz_olson_path></tz_olson_path>
<tz_country></tz_country>
<tz_city></tz_city>
<venue_id>V0-001-000189211-5</venue_id>
<venue_url>http://blah.com</venue_url>
<venue_name>Troubadour</venue_name>
<venue_display>1</venue_display>
<venue_address>9081 Santa Monica Boulevard</venue_address>
<city_name>West Hollywood</city_name>
<region_name>California</region_name>
<region_abbr>CA</region_abbr>
<postal_code>90069</postal_code>
<country_name>United States</country_name>
<country_abbr2>US</country_abbr2>
<country_abbr>USA</country_abbr>
<latitude>34.0815917</latitude>
<longitude>-118.3892462</longitude>
<geocode_type>EVDB Geocoder</geocode_type>
<all_day>0</all_day>
<recur_string></recur_string>
<calendar_count></calendar_count>
<comment_count></comment_count>
<link_count></link_count>
<going_count></going_count>
<watching_count></watching_count>
<created>2012-12-24 11:40:43</created>
<owner>evdb</owner>
<modified>2013-01-14 21:08:04</modified>
<performers>
<performer>
<id>P0-001-000000517-4</id>
<url>http://test.com</url>
<name>Antibalas</name>
<short_bio>Afro-beat / Funk / Experimental</short_bio>
<creator>jfisher</creator>
<linker>evdb</linker>
</performer>
</performers>
<image>
<url>http://s4.evcdn.com/images/small/I0-001/000/070/311-5.jpeg_/antibalas-11.jpeg</url>
<width>48</width>
<height>48</height>
<caption></caption>
<thumb>
<url>http://s4.evcdn.com/images/thumb/I0-001/000/070/311-5.jpeg_/antibalas-11.jpeg</url>
<width>48</width>
<height>48</height>
</thumb>
<small>
<url>http://s4.evcdn.com/images/small/I0-001/000/070/311-5.jpeg_/antibalas-11.jpeg</url>
<width>48</width>
<height>48</height>
</small>
<medium>
<url>http://s4.evcdn.com/images/medium/I0-001/000/070/311-5.jpeg_/antibalas-11.jpeg</url>
<width>128</width>
<height>128</height>
</medium>
</image>
<privacy>1</privacy>
<calendars></calendars>
<groups></groups>
<going></going>
</event>
</events>
</search>
I have created the following classes:
public class EventSearch
{
public int total_items { get; set; }
public int page_size { get; set; }
public int page_count { get; set; }
public int page_number { get; set; }
public int page_items { get; set; }
public string first_item { get; set; }
public string last_item { get; set; }
public string search_time { get; set; }
public List<Event> events { get; set; }
}
public class Event
{
public string id { get; set; }
public string title { get; set; }
public string url { get; set; }
public string description { get; set; }
public DateTime start_time { get; set; }
public string venue_id { get; set; }
public string venue_url { get; set; }
public string venue_name { get; set; }
public string venue_address { get; set; }
public string city_name { get; set; }
public string region_name { get; set; }
public string region_abbr { get; set; }
public string postal_code { get; set; }
public string country_name { get; set; }
public string country_abbr { get; set; }
public string country_abbr2 { get; set; }
public double latitude { get; set; }
public double longitude { get; set; }
public List<Performer> performers { get; set; }
public EventImage image { get; set; }
}
public class Performer
{
public string id { get; set; }
public string url { get; set; }
public string name { get; set; }
public string short_bio { get; set; }
}
public class EventImage
{
public string url { get; set; }
public int width { get; set; }
public int height { get; set; }
public Image thumb { get; set; }
public Image small { get; set; }
public Image medium { get; set; }
}
public class Image
{
public string url { get; set; }
public int width { get; set; }
public int height { get; set; }
}
In the method that I am calling, I want to return a list of events. Here's what I have so far, which is giving me the error:
was not expected.
Code:
var request = WebRequest.Create(url);
var response = request.GetResponse();
if (((HttpWebResponse)response).StatusCode == HttpStatusCode.OK)
{
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader.
StreamReader reader = new StreamReader(dataStream);
XmlSerializer serializer = new XmlSerializer(typeof(EventSearch));
EventSearch deserialized = (EventSearch)serializer.Deserialize(reader);
return deserialized.events;
}
I'm not sure what to do next. Do I need to annotate my classes?
Yes, you will need to add some Attributes to your classes to map the xml elements to your objects.
This should work, However I had to change a few things, The DateTime in the Xml is in the wrong fromat so I made it a string(you can parse as needed), also page_items is an int but it is an empty element in the xml, you wont be able to deserialize this, you will have to change to a string if it has a chance of being empty.
[XmlType("search")]
public class EventSearch
{
public int total_items { get; set; }
public int page_size { get; set; }
public int page_count { get; set; }
public int page_number { get; set; }
// public int? page_items { get; set; }
public string first_item { get; set; }
public string last_item { get; set; }
public string search_time { get; set; }
public List<Event> events { get; set; }
}
[XmlType("event")]
public class Event
{
[XmlAttribute("id")]
public string id { get; set; }
public string title { get; set; }
public string url { get; set; }
public string description { get; set; }
public string start_time { get; set; }
public string venue_id { get; set; }
public string venue_url { get; set; }
public string venue_name { get; set; }
public string venue_address { get; set; }
public string city_name { get; set; }
public string region_name { get; set; }
public string region_abbr { get; set; }
public string postal_code { get; set; }
public string country_name { get; set; }
public string country_abbr { get; set; }
public string country_abbr2 { get; set; }
public double latitude { get; set; }
public double longitude { get; set; }
public List<Performer> performers { get; set; }
public EventImage image { get; set; }
}
[XmlType("performer")]
public class Performer
{
public string id { get; set; }
public string url { get; set; }
public string name { get; set; }
public string short_bio { get; set; }
}
[XmlType("image")]
public class EventImage
{
public string url { get; set; }
public int width { get; set; }
public int height { get; set; }
public Image thumb { get; set; }
public Image small { get; set; }
public Image medium { get; set; }
}
[XmlType("thumb")]
public class Image
{
public string url { get; set; }
public int width { get; set; }
public int height { get; set; }
}
I tested directly from file using:
using (FileStream stream = new FileStream("C:\\Test.xml", FileMode.Open))
{
XmlSerializer serializer = new XmlSerializer(typeof(EventSearch));
EventSearch deserialized = (EventSearch)serializer.Deserialize(stream);
}
But your Stream from the Webresponce should work the same as the FileStream
Hope this helps :)