Get list of playlists in Xamarin.iOS - xamarin.ios

I am having difficulty in obtaining a collection of playlists for the iPhone with Xamarin.iOS. I want to populate a list of my custom objects with the playlist descriptions. I found a page in Apple documentation on how to do it in Obj-C. However, whatever I do in Xamarin I either get invalid cast exceptions or some other error.
Getting the playlists into a collection is OK. However, it is getting the name of the playlist after that where the problem lies.
private List<Playlist> GetPlaylists()
{
MPMediaQuery mq = MPMediaQuery.playlistsQuery;
// At this point mq.Collections has a reference to the playlists. However I have no way of getting the Name/Description of the playlist.
// Thats why I was attempting to use MPMediaPlaylist
// MPMediaPlaylist[] mp1 = mq.Collections as MPMediaPlaylist[]; - doesn't work - results in mp1 being null
List<Playlist> playlists = (from p in mq.Collections
select new Playlist () { PlaylistDescription = ((MPMediaPlaylist)p).ValueForProperty("MPMediaPlaylistPropertyName").ToString()}
).ToList();
return playlists;
}
Another variation I had was as follows (but again received an invalid cast exception in the iteration of the forearch i.e. MediaPlaylist in mp1):
MPMediaQuery mq = MPMediaQuery.playlistsQuery;
Array mp1 = mq.Collections as Array;
List<Playlist> playlists = new List<Playlist> ();
foreach (MPMediaPlaylist playlist in mp1) {
playlists.Add (new Playlist () { PlaylistDescription = playlist.ValueForProperty ("MPMediaPlaylistPropertyName").ToString() });
}
As I have commented i the code, I can get a handle on the playlists through the collections property on the query. However, I cannot get the Name/Title/Description of the playlist. That is why I was attempting to use the MPMediaPlaylist casting.
In the immediate window and watch window I tried to cast (MPMediaPlaylist)mq.collections[0] but again got an invalid cast exception.
I came across the following documentation in apple documentation for Obj-C but I have been unsuccessful in reproducing it as you can see above. I'd be very grateful if someone could cast an eye over what I have above and also this Objective-C link and advise.
Many thanks,
Tomás

I am just going to put this here.... if someone runs in to this problem in the future!
So to get list of playlists you should do the following:
MPMediaQuery playlistQuery = MPMediaQuery.PlaylistsQuery;
MPMediaItemCollection[] playlistCollection = playlistQuery.Collections;
foreach(MPMediaItemCollection collection in playlistCollection){
NSString key = MPMediaPlaylistProperty.Name;
string name = collection.ValueForKey(key).ToString();
//Do whatever you need with the info
}

Related

Application Insights - Tracking user and session across schemas

Following https://learn.microsoft.com/en-us/azure/application-insights/app-insights-usage-send-user-context, I thought it would be easy to get cross-schema tracking of a user. However, I'm finding the absolute opposite.
I created the telemetry initializer (which the document has bugs in it hardcore):
public void Initialize(ITelemetry telemetry)
{
if (HttpContext.Current?.Session == null)
return;
if (HttpContext.Current.Session["UserId"] == null)
{
HttpContext.Current.Session["UserId"] = Guid.NewGuid().ToString();
}
telemetry.Context.User.Id = (string)HttpContext.Current.Session["UserId"];
telemetry.Context.Session.Id = HttpContext.Current.Session.SessionID;
var authUser = _sessionManager.GetAuthenticatedUser<UserDetails>();
if (authUser != null)
{
telemetry.Context.User.AuthenticatedUserId = authUser.UserId;
}
}
Then I went and added it to App Insights
TelemetryConfiguration.Active.TelemetryInitializers.Add(new UserTrackingTelemetryInitializer());
I then played with my site, expecting this stuff to start showing up. It did not. I continued to get random strings for user_Id and session_Id (things like NVhLF and what not). So, I thought, okay, maybe it's logging before I update those values? I went and inserted my initializer first:
TelemetryConfiguration.Active.TelemetryInitializers.Insert(0, new UserTrackingTelemetryInitializer());
Same thing. So I started to look at schemas I don't usually look at. Nothing. So I pulled up traces and I found it. Finally, there is where my data is going. But the other schemas don't have the updated values, so what use is this? While traces is showing the expected values for user_Id and session_Id, the others continue to show garbage. Am I doing something wrong?
The document you followed does not work indeed, a feedback has been submitted here.
Just for your reference, the way I can find to set these values is that use such TrackEvent() / TrackRequest() or other Trackxxx() methods after implemented your own telemetry initializer

Table-Scraper Not Returning Data Before Function Returns

I am currently working on a Discord bot, which uses node.js, to scrape info from Dododex.com, a database of creatures from the game ARK. I found a very useful library called table-scraper which scrapes tables from web pages and returns the data as an object (or array of objects for multiple tables). In the background, table-scraper uses another library called x-ray, along with the common web request-maker request. Keep in mind that I don't know that much about node or how request works.
What I have working is asking the user for the name of a creature to get the data for. I then check that name against a list of creatures (that I have in a file/JSON object) to see if that name is valid.
Now, what I want to get working is to scrape the relevant data from the dododex page belonging to that creature using table-scraper. Table-scraper is definitely working with dododex, but when I call it to gather the data and put it into an object, it seems to start scraping, but then lets the function return with an empty object. If the program didn't crash right after the return (caused by the attempt to access an empty object), I know from testing that it would finish scraping, even though the function the scraping was called in has already finished.
Here's where the relevant code starts:
const creature = getDinoFromName(args[0].toLowerCase(), arkdata); //Function explained below
if(creature.health.base == 404) //If the creature's name is invalid, getDinoFromName() will return a creature with health.base = 404
{
console.log("unknown");
unknownCreature(args, msg); //Tells the user that the creature is unknown
return;
}
else
{
//Outputs the data
}
And here's where the data gets gathered:
function getDinoFromName(name, arkdata)
{
for(let i = 0; i < arkdata.creatures.length; i++) //Loops through arkdata, a json object with the possible names of all the creatures
{
if(arkdata.creatures[i].possible_names.includes(name)) //If the name the user provided matches one of the possible names of a creature (creatures can have multiple possible names, i.e. rex, t-rex, tyrannosaurus rex)
{
var creature;
console.log("found");
tableScraper.get("http://www.dododex.com/taming/" + arkdata.creatures[i].possible_names[0]).then(function(tableData)
{
console.log("scraped");
var stats = tableData[1]; //tableData is an array of 3 tables matching the 3 html tables found on the site, tableData[1] is the one with the creature's stats. It looks like this: http://ronsoros.github.io/?31db928bc662538a80bd25dd1207ac080e5ebca7
creature = //Now the actual creature object, parsed from tableData[1]
{
"health":
{
"base": stats[0]["Base (Lvl 1)"], //
"perwild": stats[0]["Increase Per Lvl (Wild)"],
"pertamed": stats[0]["Increase Per Lvl (Tamed)"]
}
//There is more data to parse but I only included hp as an example
}
});
return creature;
}
}
//If the creature name is not found to be one of the possible names, returns this to signify the creature was not found
return {"health":{"base":404}};
}
Running the code result in node crashing and the error
/app/server.js:320
if(creature.health.base == 404)
TypeError: Cannot read property 'health' of undefined
at stats (/app/server.js:320:15)
at Client.client.on.msg (/app/server.js:105:7)
Something wonky is going on here, and I really can't figure it out. Any help is appreciated.

MS Dynamics CRM 2011, Get subgrid elements from other form

I am new to jscript and have problems to get all elements in a subgrid.
I tried the code from this sites,
Retrieve rows in crm2011 subgrid with JScript
https://lakshmanindian.wordpress.com/2012/05/25/retrieve-subgrid-rows-in-crm-2011-using-jscript/
but get every time the error message:
(Translated)
Error in the user defined event of the field
Field:window
Event: onload
Error: The preference "control" of a undefined or null reference can not be called.
The last code I tried:
var grid = document.getElementById("accountContactsGrid").control;
for (var rowNo = 0; rowNo<grid.getRecordsFromInnerGrid().length; rowNo++)
for (var cellNo = 0; cellNo<grid.getRecordsFromInnerGrid()[rowNo][3].cells.length; cellNo++)
alert(grid.getRecordsFromInnerGrid()[rowNo][3].cells[cellNo].outerText);
I tried it in the entity Account(Company) with the subgrid "accountContactsGrid".
My main goal would be to catch all the assigned elements in the account form and list it under the contacts form. But only if the checkbox "Eko" is activated.
This is my working code so far:
var chkEko = Xrm.Page.getAttribute("testcrm_ekonomi").getValue();
if (chkEko === true)
{
alert("Eko active: " + chkEko);
}
else
{
alert("Eko not active: " + chkEko);
}
After a time and the help of some threads I was able to get information of this grid. But now I have the problem to catch the elements.
I looked up the variable "grid" and found out that variable is an Object.
Since I don't really know the properties of the objects I tried to get it all.
But it seems, that my code doesn't work and I can not understand why.
Here is the code so far:
function subgridItemCount() {
// Get the Subgrid Control
var grid = Xrm.Page.ui.controls.get('accountContactsGrid')._control;
var keys = Object.keys(grid);
var getKeys = function(obj){
var keys = [];
for(var key in obj){
keys.push(key);
}
return keys;
}
for(var i = 0; i<keys.length; i++) {
document.write(keys[i]);
}
}
First I wanted to get the property of the object and then the propertyValue.
Or is there an other way to get all values of an object?
It seems like I am on the wrong way. This is what I try to do:
In the account/company form is an existing grid which is called Contacts. In this field are some Contacts assigned (with the button "add existing contact").
Now when I open some Contact there should be a box/grid/iframe with a list of all companies this contact is assigned too.
This list should be linked to the Companies (When i click on them CRM should open the form).
Maybe someone can give me a tip?
My plan was first to look for all companies and then to compare the assigned contacts to the opened one with some Jscript. Then the script should list all matching contacts in the contact form.
This way is not really performant since the script needs to read all companies first. But I don't know an other way...

Editing Time Field in a Spotify App Playlist

I am having trouble removing the time field from a playlist in the Spotify App. I only want to display Song title, Artist and Album. Any help on this topic would be truly helpful.
You can specify which track attributes to display using the List object. An example is here: http://deceptacle.com/2011/12/26/spotify-app-api-some-things/
var list = new views.List(playlist, function (track) {
return new views.Track(track, views.Track.FIELD.NAME |
views.Track.FIELD.ARTIST |
views.Track.FIELD.ALBUM);
});
$("#playlist").append(list.node);
Update
More fleshed out example:
var pl = m.Playlist.fromURI("spotify:user:rhino_records:playlist:6sSFeKDgDxVR81YqNOuPf2");
var list = new v.List(pl, function (track) {
return new views.Track(track, views.Track.FIELD.NAME |
views.Track.FIELD.ARTIST |
views.Track.FIELD.ALBUM);
});
document.body.appendChild(list.node);
m is the models namespace, v is the views namespace. For some reason, it's not quite working for me. It seems like the observer methods aren't being called at the moment. Seems to be a spotify backend thing though. It seems to get called eventually after some prodding

Sending ArrayCollections via P2P Flex

I have a question regarding P2P with flex.
When passing data between two applications using P2P. I get the following error:
warning: unable to bind to property 'piece' on class 'Object' (class is not an IEventDispatcher)
I've spent a few days using Google to try and find a solution, but a can't get rid of that error. I've tried using ObjectUtils, direct assignment, and creating a new ArrayCollection WITH the ObjectUtils inside the parenthesis and still can't solve the problem.
Purpose of code:
-> Two users connect via P2P
-> 1st user can manipulate pictures (stored as objects in the array collection).
-> 1st user sends updated ArrayCollection (with changed pictures) to 2nd user
-> 2nd user's ArrayCollection gets updated and now sees manipulated pics
As far as my knowledge of Flex goes (fairly new to it), I properly Binded what needed to be binded. Using pop-ups and trace, I was able to see that the data from the ArrayCollection gets copied in properly, but it just doesn't want to display.
Here are some snippets of my code:
[Bindable]
public var taken:ArrayCollection = new ArrayCollection ([
new picLayout(1,'sky.png'),
new picLayout(2,'bird.png')
])
public function receiveSomeData(pass:ArrayCollection):void
{
// Want to replace current version of variable "taken" with
// the one passed in using P2P
this.taken= new ArrayCollection(pass.source);
}
public function sendSomeData(free:ArrayCollection):void
{
sendStream.send("receiveSomeData",free);
}
<s:Button click="sendSomeData(taken)" label="Update" />
Thank You for your help and time!
I figured out what the problem was and how to fix it - with partial thanks to these pages:
Unable to Bind warning: class is not an IEventDispatcher
Flex Warning: Unable to bind to property 'foo' on class 'Object' (class is not an IEventDispatcher)
I knew that the information was being successfully sent to the other peer, but the problem was that the objects INSIDE the ArrayCollection weren't made bindable.
My solution to the problem was as follows:
Create a loop that sends each object in the ArrayCollection along with an index that tells you what value in the ArrayCollection you are streaming.
Now, since you are "streaming" the data, overwrite the current ArrayCollection, using the setItemAt() function with first field as "new ObjectProxy(passedObject)" and the second field as the passedIndex (Note): the ObjectProxy() function forces the passed object to be bindable.
Here is an updated snippet of my code:
[Bindable]
public var takenPics:ArrayCollection = new ArrayCollection ([
new picLayout(1,'sky.png'),
new picLayout(2,'bird.png')
])
private function sendSomeData(data:Object, index:int):void
{
sendStream.send("receiveSomeData",data,index);
}
private function receiveSomeData(passedPic:Object,ix:int):void
{
// ObjectProxy needed to force a bindable object
takenPics.setItemAt(new ObjectProxy(passedPic),ix);
}
public function sendPictures():void
{
// ix < 2 because size of ArrayCollection is 2
for (var ix:int = 0; ix<2; ix++)
sendSomeData(takenPics[ix],ix);
}

Resources