json string downloaded with mising values c# webclient - missing-data

I'm conding a rent car asp.net mvc application and I have a strange problem.
I used the skyscanner api to get the available cars list but the json string downloaded is always missing the attribute cars or there is cars that exist and are available.
string datacar = "";
String ch = "http://partners.api.skyscanner.net/apiservices/carhire/liveprices/v2/UK/eur/fr/" + ids + "/" + ide + "/" + dstart + "T" + tstart + "/" + dend + "T" + tend + "/30?apiKey=dh219253907683824017371755201462&userip=127.0.0.1";
Uri url = new Uri(ch);
// Uri url2 = new Uri("http://partners.api.skyscanner.net/apiservices/carhire/liveprices/v2/UK/eur/fr/27539733/27539733/2016-09-10T17:45/2016-09-17T17:45/30?apiKey=dh219253907683824017371755201462&userip=127.0.0.1");
CarModel model = new CarModel();
// for (int i = 0; i <= 20; i++)
// {
using (WebClient wc = new WebClient())
{
wc.Headers.Set("Content-Type", "application/json");
datacar = wc.DownloadString(url);
//datacar = wc.DownloadString(url2);
model = JsonConvert.DeserializeObject<CarModel>(datacar);
}
and here it is the carModel defintion
namespace carrent.Models
{
public class SubmittedQuery
{
public string market { get; set; }
public string currency { get; set; }
public string locale { get; set; }
public string pickup_place { get; set; }
public string dropoff_place { get; set; }
public string pickup_date_time { get; set; }
public string drop_off_date_time { get; set; }
public string driver_age { get; set; }
}
public class Image
{
public int id { get; set; }
public string url { get; set; }
}
public class CarClass
{
public int id { get; set; }
public int sort_order { get; set; }
public string name { get; set; }
}
public class DebugItem
{
public string type { get; set; }
public string title { get; set; }
public string content { get; set; }
}
public class CarModel
{
public SubmittedQuery submitted_query { get; set; }
public List<object> cars { get; set; }
public List<object> websites { get; set; }
public List<Image> images { get; set; }
public List<CarClass> car_classes { get; set; }
public List<DebugItem> debug_items { get; set; }
}
}
Ps: the strange thing in this problem is when I initialize an url (the url2) the code run perfectly
please guys help me to get the solution and thanks

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

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

How to upload Pending Attachment to Yammer

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

MVC 4 EF5 Database First set Default Values in Partial Class

I'm new to MVC and trying to figure out how to set default values for partial classes. I have been searching for 2 days now, and can't get anything to work. Here is a supposed solution, but it doesn't work for me. I also tried the [DefaultValue(10)] data annotation.
Here is the auto generated partial class created from the edmx file
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace OTIS.Models.Admin
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public partial class Company
{
public Company()
{
this.Facilities = new HashSet<Facility>();
}
public int CompanyID { get; set; }
[Required]
[Display(Name = "Company Name")]
public string CompanyName { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string PostalCode { get; set; }
public decimal ItemMargin { get; set; }
public decimal ServicesMargin { get; set; }
public decimal InvoiceTimeIncrement { get; set; }
public decimal CashDiscountPct { get; set; }
public decimal BaseServiceHourlyRate { get; set; }
public decimal HourlyPremiumRush { get; set; }
public decimal HourlyPremiumLate { get; set; }
public decimal HourlyPremiumCustomerMaterial { get; set; }
public int CreatedByID { get; set; }
public System.DateTime CreatedOn { get; set; }
public int ModifiedBy { get; set; }
public System.DateTime ModifiedOn { get; set; }
public virtual UserProfile UserProfile { get; set; }
public virtual UserProfile UserProfile1 { get; set; }
public virtual ICollection<Facility> Facilities { get; set; }
}
}
Here is my partial class I created to add annotations.
namespace OTIS.Models.Admin
{
[MetadataType(typeof(CompanyMD))]
public partial class Company
{
//public Company()
//{
// //private System.DateTime _currentDateTime = DateTime.Now;
// ////Set Default Values
// //CreatedByID = (int)Membership.GetUser().ProviderUserKey;
// //CreatedOn = _currentDateTime;
// //ModifiedBy = (int)Membership.GetUser().ProviderUserKey;
// //ModifiedOn = _currentDateTime;
//}
public string FullAddress
{
get
{
return this.City + ", " + this.State + " " + this.PostalCode;
}
}
public class CompanyMD
{
private System.DateTime _currentDateTime = DateTime.Now;
private int _currentUser = (int)Membership.GetUser().ProviderUserKey;
[Display(Name = "Company ID")]
public int CompanyID { get; set; }
[Required]
[Display(Name = "Company Name")]
public string CompanyName { get; set; }
[Display(Name = "Address")]
public string Address1 { get; set; }
[Display(Name = "Address 2")]
public string Address2 { get; set; }
public string City { get; set; }
public string State { get; set; }
[Display(Name = "Zip")]
public string PostalCode { get; set; }
[Display(Name = "Address")]
public string FullAddress { get; set; }
[Display(Name = "Material Margin")]
public decimal ItemMargin { get; set; }
[Display(Name = "Overtime Margin")]
public decimal ServicesMargin { get; set; }
[Display(Name = "Invoice Hour Increment")]
public decimal InvoiceTimeIncrement { get; set; }
private decimal _cashDiscountPct;
[Display(Name = "Cash Discount %")]
[DisplayFormat(DataFormatString = "{0:P2}")]
public decimal CashDiscountPct
{
get { return _cashDiscountPct; }
set { _cashDiscountPct = value/100; }
}
[Display(Name = "Base Hourly Rate ($/Hr)")]
[DataType(DataType.Currency), DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = true)]
public decimal BaseServiceHourlyRate { get; set; }
[Display(Name = "Rush Premium ($/Hr)")]
[DataType(DataType.Currency), DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = true)]
public decimal HourlyPremiumRush { get; set; }
[Display(Name = "Late Premium ($/Hr)")]
[DataType(DataType.Currency), DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = true)]
[DefaultValue(75)]
public decimal HourlyPremiumLate { get; set; }
[Display(Name = "Cust Material Premium ($/Hr)")]
[DataType(DataType.Currency), DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = true)]
public decimal HourlyPremiumCustomerMaterial { get; set; }
[Display(Name = "Created By")]
public int CreatedByID { get; set; }
//{
// get { return _currentUser; }
// set { _currentUser = value; }
//}
[Display(Name = "Created On")]
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
//[DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public System.DateTime CreatedOn
{
get { return _currentDateTime; }
set { _currentDateTime = value; }
}
[Display(Name = "Modified By")]
public int ModifiedBy { get; set; }
//{
// get { return _currentUser; }
// set { _currentUser = value; }
//}
[Display(Name = "Modified On")]
public System.DateTime ModifiedOn
{
get { return _currentDateTime; }
set { _currentDateTime = value; }
}
}
}
}
And then in my controller, I instantiate a new instance of the class to initialize it, but the values I set don't get set.
//
// GET: /Company/Create
public ActionResult Create()
{
ViewBag.CreatedByID = new SelectList(db.UserProfiles, "UserId", "UserName");
ViewBag.ModifiedBy = new SelectList(db.UserProfiles, "UserId", "UserName");
Company newCompany = new Company();
return View(newCompany);
}
Sorry this is so late, but I just solved a similar scenario myself.
I think the problem is how you refer to the partial class. It should be an empty reference to the partial class with no code. EF uses this "declaration" to link your partial class to your metadata class. So, your metadata class should look like this:
namespace OTIS.Models.Admin
{
[MetadataType(typeof(CompanyMD))]
public partial class Company
{} // <-- note the close bracket!
public class CompanyMD
{
private System.DateTime _currentDateTime = DateTime.Now;
private int _currentUser = (int)Membership.GetUser().ProviderUserKey;
public string FullAddress
{
get
{
return this.City + ", " + this.State + " " + this.PostalCode;
}
}
[Display(Name = "Company ID")]
public int CompanyID { get; set; }
[Required]
[Display(Name = "Company Name")]
public string CompanyName { get; set; }
// ....etc.... removed for brevity
} // close metadata class
} // close namespace
Hope this helps!
I found I needed to handle this in my Repository Class in a GetNew() method that would populate the default values of a new instance of the class.

How to filter audio podcasts from iTunes Search API?

By searching for podcasts with the iTunes API (http://www.apple.com/itunes/affiliates/resources/documentation/itunes-store-web-service-search-api.html) the result contains both audio and video podcasts. Is there any way to retrieve only audio podcasts from the API?
Thanks in advance :-)
From the documentation it doesn’t seem as if filtering audio and video podcasts is possible; however, you could loop through the resulting items and check whether each item is audio or video for filtering. You can do that be finding additional information from the RSS feed or by making another call to iTunes using the subscribePodcast url (see example).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Web.Script.Serialization;
using System.Xml.Linq;
using System.IO;
namespace ConsoleTest
{
class Program
{
static void Main(string[] args)
{
//Searching for Windows Weekly
string url = "https://itunes.apple.com/search?term=Windows%20Weekly&media=podcast&attibute=audio";
string json = FetchHTML(url);
JavaScriptSerializer s = new JavaScriptSerializer();
var result = s.Deserialize(json);
var audioOnly = new List();
foreach (var item in result.Results)
{
if (!IsVideo(item.TrackId))
{
audioOnly.Add(item);
}
}
foreach (var au in audioOnly)
{
Console.WriteLine(au.TrackName);
}
Console.ReadLine();
}
static bool IsVideo(string id)
{
string req = "https://buy.itunes.apple.com/WebObjects/MZFinance.woa/wa/com.apple.jingle.app.finance.DirectAction/subscribePodcast?id=" + id + "&wasWarnedAboutPodcasts=true";
string xml = FetchHTML(req,true);
bool isVideo = false;
var re = XElement.Load(new StringReader(xml)).Elements("dict").Elements("dict");
bool next = false;
foreach (var e in re.Elements())
{
if (next)
{
//This is the is video value
isVideo = e.Name.LocalName.Trim().ToLower() == "true";
next = false;
break;
}
if (e.Value == "is-video")
{
next = true;
}
}
return isVideo;
}
static string FetchHTML(string url,bool doItAsITunes = false)
{
string htmlCode = "";
using (WebClient client = new WebClient())
{
if (doItAsITunes)
{
client.Headers.Add("user-agent", "iTunes/9.1.1");
}
htmlCode = client.DownloadString(url);
}
return htmlCode;
}
}
public class SearchResult
{
public SearchResult()
{
Results = new List();
}
public int ResultCount { set; get; }
public List Results { set; get; }
}
public class Item
{
public Item()
{
GenreIDs = new List();
Genres = new List();
}
public string WrapperType { set; get; }
public string Kind { set; get; }
public string ArtistID { set; get; }
public string CollectionID { set; get; }
public string TrackId { set; get; }
public string ArtistName { set; get; }
public string CollectionName { set; get; }
public string TrackName { set; get; }
public string CollectionCensoredName { set; get; }
public string TrackCensoredName { set; get; }
public string ArtistViewUrl { set; get; }
public string FeedUrl { set; get; }
public string TrackViewUrl { set; get; }
public string PreviewUrl { set; get; }
public string ArtworkUrl60 { set; get; }
public string ArtworkUrl100 { set; get; }
public float CollectionPrice { set; get; }
public float TrackPrice { set; get; }
public string CollectionExplicitness { set; get; }
public string TrackExplicitness { set; get; }
public string DiscCount { set; get; }
public string DiscNumber { set; get; }
public string TrackCount { set; get; }
public string TrackNumber { set; get; }
public string TrackTimeMillis { set; get; }
public string Country { set; get; }
public string Currency { set; get; }
public string PrimaryGenreName { set; get; }
public List GenreIDs { set; get; }
public List Genres { set; get; }
}
}
Yes. In regular serach you get everything:
https://itunes.apple.com/search?term=jack+johnson
But you can add some params to request for example (for your case)
&entity=song
So the request will be:
https://itunes.apple.com/search?term=jack+johnson&entity=song
For more look at Searching seaction in this docs