How to filter audio podcasts from iTunes Search API? - 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

Related

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

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

Getting error when adding new object with HTTP POST in .NETCore

I am new to .NetCore and Blazor. I am trying to do a POST of an new Anime, but I am allways getteing the error "The Genre field is required." I have added the genreId to the JSON Object but still the same error -> Screenshot of the error
It's one to many relation, where one animal can have only one genre but one genre can have many enemies.
I don't know if it's useful but here are screenshots of my two tables in the DB -> Anime table and the Genre tab
Here are my to Models:
Anime model
public class Anime
{
public int Id { get; set; }
public string Title { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
public string CoverImage { get; set; } = string.Empty;
public string Author { get; set; } = string.Empty;
public Genre Genre { get; set; }
public string Studio { get; set; } = string.Empty;
public DateTime? ReleaseDate { get; set; }
public DateTime? EndDate { get; set; }
}
Genre model
public class Genre
{
public int Id { get; set; }
public string Title { get; set; } = string.Empty;
[JsonIgnore]
public List<Anime> Animes { get; set; }
}
AnimeService where I am adding the new anime to the DB
public async Task<ServiceResponse<List<Anime>>> AddAnime(Anime NewAnime)
{
ServiceResponse<List<Anime>> serviceResponse = new ServiceResponse<List<Anime>>();
_dataContext.Animes.Add(NewAnime);
await _dataContext.SaveChangesAsync();
var animes = await _dataContext.Animes
.Include(a => a.Genre)
.ToListAsync();
if (animes == null)
{
serviceResponse.Success = false;
serviceResponse.Message = "Animes could be found!";
}
serviceResponse.Data = animes;
return serviceResponse;
}
AnimeController
[HttpPost]
[Route("AddAnime")]
public async Task<ActionResult<ServiceResponse<List<Anime>>>> AddAnime(Anime NewAnime)
{
return Ok(await _animeService.AddAnime(NewAnime));
}
As we discussed on Discord:
You're using .NET 6 with nullables enabled.
As an Anime can exist before it has Genre assigned I would configure the tables like this:
public class Anime
{
public int Id { get; set; }
public string Title { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
public string CoverImage { get; set; } = string.Empty;
public string Author { get; set; } = string.Empty;
public int? GenreId { get; set; }
[ForeignKey(nameof(GenreId))]
public Genre? Genre { get; set; }
public string Studio { get; set; } = string.Empty;
public DateTime? ReleaseDate { get; set; }
public DateTime? EndDate { get; set; }
}
public class Genre
{
public int Id { get; set; }
public string Title { get; set; } = string.Empty;
[JsonIgnore]
[InverseProperty(nameof(Anime.Genre))]
public List<Anime> Animes { get; set; }
}
It seems that your Anime instance don't habe a Genre object but it is requiered in your db context
You have to add navigation property GenreId as nullable if you think that Genre is optional
public class Anime
{
public int Id { get; set; }
... another properties
public int? GenreId { get; set; }
public virtual Genre Genre { get; set; }
}
after this you will have to make a new database migration

Why is my Viewmodel that I am returning to my POST method in MVC returning a null ViewModel

I really thought I understood what I was doing, but here goes. I decided I need more properties in my View so I created a ViewModel called ViewDataset and replaced the original Dataset model in the View. On my HttpGet TestDataset the View Model is populated correctly with data from the Viewmodel:
My original dataset that was working is below:
public class Dataset
{
public int Dataset_ID { get; set; }
public int Category_ID { get; set; }
public string Provider { get; set; }
public string Name { get; set; }
public string Institution { get; set; }
public string Description { get; set; }
public string Location { get; set; }
public bool Domestic { get; set; }
public bool International { get; set; }
public bool Includes_PHI { get; set; }
public bool PHI_Limited { get; set; }
public bool Includes_PIL { get; set; }
public bool PIL_Limited { get; set; }
public bool Citation_Requirements { get; set; }
public string Citation_Comments { get; set; }
public Nullable<System.DateTime> Availability_Beg_DT { get; set; }
public Nullable<System.DateTime> Availability_End_DT { get; set; }
public bool Subscription_Renewal { get; set; }
public Nullable<System.DateTime> Subscription_Renewal_DT { get; set; }
public bool Retention_Expiry { get; set; }
public Nullable<System.DateTime> Retention_Expiry_DT { get; set; }
public bool Data_Destruction { get; set; }
public Nullable<System.DateTime> Data_Destruction_DT { get; set; }
public string Data_Destruction_Instructions { get; set; }
public Nullable<int> Contract_ID { get; set; }
public bool Draft_Status { get; set; }
public bool Admin_Only { get; set; }
public string Dataset_Alias { get; set; }
public bool Loc_Amazon { get; set; }
public bool Loc_IT_Research { get; set; }
public bool Loc_Research_Proj { get; set; }
public bool Loc_Secure_Data { get; set; }
public bool Loc_Mercury { get; set; }
public bool Loc_Research_CC { get; set; }
public bool Loc_Research_VM { get; set; }
public bool Loc_External { get; set; }
public bool Access_Url { get; set; }
public bool Access_Download_App { get; set; }
public bool Access_Lab_Terminal { get; set; }
public bool Access_Email_Req { get; set; }
public bool Access_File_Download { get; set; }
public bool Access_Other { get; set; }
public string Location_Notes { get; set; }
public string Access_Notes { get; set; }
public Nullable<System.DateTime> Date_Added { get; set; }
public Nullable<System.DateTime> Date_Modified { get; set; }
public string Added_By_User { get; set; }
public string Updated_By_User { get; set; }
public bool External_Collaborators
{
get; set;
}
}
Here is my new ViewDataset (viewmodel)
public class ViewDataset
{
public Dataset dataset;
public List<SelectListItem> categories_list;
}
Here is my is a sample of my view ... couple of lines, but the view is populated correctly with data from the ViewDataset model
#model ResearchDataInventoryWeb.Models.ViewDataset
<td>
#Html.TextBoxFor(model => model.dataset.Institution, new { placeholder = "<Institution>", #class = "input-box" })
</td>
<td>
#Html.TextBoxFor(model => model.dataset.Name, new { placeholder = "<Dataset Name>", #class = "input-box" })
</td>
#Html.CheckBoxFor(model => model.dataset.Domestic) <span class="display-checkbox">Domestic</span>
#Html.CheckBoxFor(model => model.dataset.International) <span class="display-checkbox">International</span>
#Html.CheckBoxFor(model => model.dataset.Includes_PHI) <span class="display-checkbox">Includes PHI </span>
#Html.CheckBoxFor(model => model.dataset.Includes_PIL) <span class="display-checkbox">Includes PII </span><br />
#Html.CheckBoxFor(model => model.dataset.External_Collaborators) <span class="display-checkbox">External Collaborators Allowed (Sharable)</span>
#Html.CheckBoxFor(model => model.dataset.Citation_Requirements) <span class="display-checkbox">Citation Requirements</span>
<input type="submit" value="TestPost" />
Here is my HttpPost TestDataset : The model Viewdataset (dataset, categories_list) properties that I am passing back from the view are NULL, am I missing something?
[HttpPost]
public ActionResult TestDataset(ViewDataset viewdataset)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:4251/");
//HTTP POST
viewdataset.dataset.Category_ID = 2;
viewdataset.dataset.Dataset_ID = 1;
viewdataset.dataset.Location = "Fingers Crossed";
viewdataset.dataset.Institution = "Not Null";
var dataset = viewdataset.dataset;
// var postTask = client.PostAsJsonAsync<Dataset>("api/datasets/1", dataset);
var postTask = client.PostAsJsonAsync("api/datasets/1", dataset);
postTask.Wait();
var result = postTask.Result;
if (result.IsSuccessStatusCode)
{
return RedirectToAction("Index");
}
}
ModelState.AddModelError(string.Empty, "Server Error. Please contact administrator.");
return View(viewdataset);
}
Here if my HttpGet TestDataset in case you need to see it
public async Task<ActionResult> TestDataset()
{
//Hosted web API REST Service base url
string Baseurl = "http://localhost:4251/";
List<Dataset> dataset = new List<Dataset>();
List<Category> categories = new List<Category>();
var parm = "1";
var returned = new Dataset();
var ViewDataset = new ViewDataset();
using (var client = new HttpClient())
{
//Passing service base url
client.BaseAddress = new Uri(Baseurl);
client.DefaultRequestHeaders.Clear();
//Define request data format
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//Sending request to find web api REST service resource GetAllEmployees using HttpClient
HttpResponseMessage Res = await client.GetAsync("api/Datasets/" + parm);
HttpResponseMessage Res2 = await client.GetAsync("api/Categories");
//Checking the response is successful or not which is sent using HttpClient
if (Res.IsSuccessStatusCode)
{
//Storing the response details recieved from web api
var EmpResponse = Res.Content.ReadAsStringAsync().Result;
//Deserializing the response recieved from web api and storing into the Employee list
returned = JsonConvert.DeserializeObject<Dataset>(EmpResponse);
}
if (Res2.IsSuccessStatusCode)
{
//Storing the response details recieved from web api
var CatResp = Res2.Content.ReadAsStringAsync().Result;
//Deserializing the response recieved from web api and storing into the Employee list
categories = JsonConvert.DeserializeObject<List<Category>>(CatResp);
}
// Create the Categories Select List
var categoryList = new List<SelectListItem>();
foreach (Category c in categories)
{
categoryList.Add(new SelectListItem
{
Value = c.Category_ID.ToString(),
Text = c.Description,
Selected = (c.Category_ID == returned.Category_ID ? true : false)
});
}
ViewDataset.dataset = returned;
ViewDataset.categories_list = categoryList;
//returned.External_Collaborators = returned.External_Collaborators == null || false ? false : true;
//returning the employee list to view
return View(ViewDataset);
}
}
Try to change
public class ViewDataset
{
public Dataset dataset;
public List<SelectListItem> categories_list;
}
to
public class ViewDataset
{
public Dataset dataset { get; set; }
public List<SelectListItem> categories_list { get; set; }
}

json string downloaded with mising values c# webclient

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

Losing data on .Where(expression) to list()

Func<View_Album_Search, bool> expressionAlbum = Al => Al.name.Contains(text) || Al.soundName.Contains(text) || Al.artist.Contains(text);
var query = view_Album_SearchRepository.Where(expressionAlbum);
var b = query.Count(); (*Count = 1440*)
(*Lose data *)
var a = query.ToList(); (*Count = 154*)
/***************************************************\
public IEnumerable<TEntity> Where(Func<TEntity, bool> predicate)
{
return _context.Set<TEntity>().Where(predicate);
}
MODEL
public partial class View_Album_Search
{
public string name { get; set; }
public decimal id_album { get; set; }
public string soundName { get; set; }
public string artist { get; set; }
public byte feature { get; set; }
public Nullable<System.DateTime> album_date { get; set; }
public Nullable<decimal> hits { get; set; }
public string artist_twitter { get; set; }
public Nullable<int> feature_order { get; set; }
public string video_url { get; set; }
}
I dont understand, if I do it on get all works fine.
Aditional information
On debug mode when he do .toList() he execute the exrpessionAlbum again
Func<View_Album_Search, bool> expressionAlbum = Al => Al.name.ToLower().Contains(text.ToLower()) || Al.artist.ToLower().Contains(text.ToLower());