I want to populate my background player playlist with tracks saved in database table.
How can i do that in my windows phone 8 app?
The BackgroundAudioPlayer can only play files from isolated storage or from a remote URI. All you need to do is to have a list of audio tracks as playlist for the player.
These are only sample examples modify as per your need.
//get the uri to tracks using IsolatedStorageFileStream Name property of file.
reference
private static string GetAbsolutePath(string filename)
{
IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
string absoulutePath = null;
if (isoStore.FileExists(filename))
{
IsolatedStorageFileStream output = new IsolatedStorageFileStream(filename, FileMode.Open, isoStore);
absoulutePath = output.Name;
output.Close();
output = null;
}
return absoulutePath;
}
//now instantiate list of audio track with the uri to track
List<AudioTrack> = new List<AudioTrack>
{
new AudioTrack(new Uri("URI TO FILE IN ISOLATED STORAGE", UriKind.Relative),
"title",
"artist",
"album",
"Uri To albumArt or null"),
new AudioTrack(new Uri("URI TO FILE IN ISOLATED STORAGE", UriKind.Relative),
"title",
"artist",
"album",
"Uri To albumArt or null")
};
For further reading: http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh202978(v=vs.105).aspx
Related
I am rewriting an app that used Google Contacts API (RIP) to use People API. I already have a refresh token. Previously, I created an instance of the OAuth2Parameters object, and used it to create an instance of the RequestSettings class to be passed to the ContactsRequest constructor
OAuth2Parameters oparams = new OAuth2Parameters
{
AccessToken = tokenData.access_token,
RefreshToken = tokenData.refresh_token,
ClientId = ClientId,
ClientSecret = ClientSecret,
AccessType = "offline",
ApprovalPrompt = "force",
Scope = _contactScope
};
if (string.IsNullOrWhiteSpace(oparams.AccessToken))
{
oparams.AccessToken = "xyz"; //it doesn't matter what this token is, it just can't be blank, it will get refreshed
OAuthUtil.RefreshAccessToken(oparams);
dataStore._storedResponse.access_token = oparams.AccessToken;
}
var settings = new RequestSettings("My App")
{
OAuth2Parameters = oparams
};
if (paging)
{
settings.PageSize = 50;
settings.AutoPaging = true;
}
return new ContactsRequest(settings);
I cannot figure out how to do the same in the new world of People API. I obviously need to use PeopleServiceService object, but its constructor takes an instance of the Initializer object, and I don't know out how I can initialize it with the refresh token and (possibly) access token.
Here's the official tutorial on how to do authentication with the .NET library for all Google APIs:
https://developers.google.com/api-client-library/dotnet/guide/aaa_oauth
Here's a useful snippet from it that will also help with persisting the refresh token to a file and use it in future authentication attempts:
UserCredential credential;
using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
{
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
new[] { BooksService.Scope.Books },
"user", CancellationToken.None, new FileDataStore("Books.ListMyLibrary"));
}
// Create the service.
var service = new BooksService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Books API Sample",
});
var bookshelves = await service.Mylibrary.Bookshelves.List().ExecuteAsync();
I'm choosing a file this way:
Future<String> getFile() {
final completer = new Completer<String>();
final InputElement input = document.createElement('input');
input
..type = 'file'
..accept = 'image/*';
input.onChange.listen((e) async {
final List<File> files = input.files;
final reader = new FileReader();
reader.readAsDataUrl(files[0]);
reader.onError.listen((error) => completer.completeError(error));
await reader.onLoad.first;
completer.complete(reader.result as String);
});
input.click();
return completer.future;
}
I would typically display the file using the widget returned by Image.file(...) but this accepts a dart:io File, not a dart:html one. What's the best way to display dart:html in Flutter web?
As a bonus question, are there any known browser limitations? I'm worried this solution will only work on Chrome.
I am using this code to let users to choose where to save a file:
var fileSavePicker = new FileSavePicker();
fileSavePicker.FileTypeChoices.Add("Pdf", new List<string>(){".pdf"});
fileSavePicker.SuggestedFileName = $"{pdfFile.Name}";
fileSavePicker.SuggestedSaveFile = pdfFile;
fileSavePicker.PickSaveFileAndContinue();
This code works fine on Windows Phone 8.1 but give me an exception (System.UnauthorizedAccessException) when running on Windows 10 mobile. How can I solve this?
When I use FileSavePicker.PickSaveFileAndContinue method in the visual, there is an error “ The FileSavePicker.PickSaveFileAndContinue() is obsolete: instead, use PickSaveFileAsync() ”. So you can use FileSavePicker.PickSaveFileAsync() method in Windows 10 mobile.
Update:
I have test Windows Phone 8.1 on Windows 10 Mobile, it was ok. The code of my project below , you can refer to.
You can also refer to this sample about FileSavePicker.
private void SaveFileButton_Click(object sender, RoutedEventArgs e)
{
// Clear previous returned file name, if it exists, between iterations of this scenario
OutputTextBlock.Text = "";
FileSavePicker savePicker = new FileSavePicker();
savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
// Dropdown of file types the user can save the file as
savePicker.FileTypeChoices.Add("Plain Text", new List<string>() { ".txt" });
// Default file name if the user does not type one in or select a file to replace
savePicker.SuggestedFileName = "New Document";
savePicker.PickSaveFileAndContinue();
}
/// <summary>
/// Handle the returned file from file picker
/// This method is triggered by ContinuationManager based on ActivationKind
/// </summary>
/// <param name="args">File save picker continuation activation argment. It cantains the file user selected with file save picker </param>
public async void ContinueFileSavePicker(FileSavePickerContinuationEventArgs args)
{
StorageFile file = args.File;
if (file != null)
{
// Prevent updates to the remote version of the file until we finish making changes and call CompleteUpdatesAsync.
CachedFileManager.DeferUpdates(file);
// write to file
await FileIO.WriteTextAsync(file, file.Name);
// Let Windows know that we're finished changing the file so the other app can update the remote version of the file.
// Completing updates may require Windows to ask for user input.
FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);
if (status == FileUpdateStatus.Complete)
{
OutputTextBlock.Text = "File " + file.Name + " was saved.";
}
else
{
OutputTextBlock.Text = "File " + file.Name + " couldn't be saved.";
}
}
else
{
OutputTextBlock.Text = "Operation cancelled.";
}
}
I need to write a windows console program that will take the results from a SQL query, and dump the results into a excel sheet. We are moving away from Microsoft, and towards Google technology. So I need to create a worksheet, dump the results in that file, and store on drive.
Is the sdk the best way to go on this? Am I going to need the SDK for Drive and for Worksheetes? I also need to have the console run on it's own, no user interaction at all. I have been working with this sample below, and got it to work. I'm not sure if I'm going in the right direction with this. Any advice would be great!
using System;
using System.Threading;
using System.Threading.Tasks;
using Google;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v2;
using Google.Apis.Drive.v2.Data;
using Google.Apis.Services;
using Google.Apis.Discovery;
using Google.GData.Client;
using Google.GData.Extensions;
namespace GoogleDriveSamples
{
class DriveCommandLineSample
{
static void Main(string[] args)
{
UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets
{
ClientId = "xxxxxxxxxx-bn0vi796pn7tog7utb9pt6pmptl8cpsq.apps.googleusercontent.com",
ClientSecret = "FwuyHxBAj2Z1",
},
new[] { DriveService.Scope.Drive },
"user",
CancellationToken.None).Result;
// Create the service.
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Credit Q",
});
File body = new File();
body.Title = "My document";
body.Description = "A test document";
body.MimeType = "text/plain";
byte[] byteArray = System.IO.File.ReadAllBytes("FTP.txt");
System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, "text/plain");
request.Upload();
File file = request.ResponseBody;
Console.WriteLine("File id: " + file.Id);
Console.WriteLine("Press Enter to end this process.");
Console.ReadLine();
}
}
}
You can do it in google apps script in about 5 lines of code.
Lok at the official samples. Basically use spreadsheetApp and jdbc.
I have an wp8 app using PeriodicTask background Agent.
The task update the information of multiple live tiles,
using POST Client to get title and image url from my server to update the live tile.
Background agent works just fine in debugging and releasing mode. When the .xap file was deployed into my device using XAPDeployement tool, the background Agent also works perfectly.
However, it won't work after submitted to wp app store, no matter it's beta version or not.
If the app is downloaded from store, the background agent has never worked, and it is blocked by system after a few minutes.
How come it goes wrong since the XAP files are the same?
part of code:
public static Task<string> jsonPostClientTask(Dictionary<string, object> parameters, string url)
{
var results = new TaskCompletionSource<string>();
PostClient proxy = new PostClient(parameters);
try
{
proxy.DownloadStringCompleted += (sender, e) =>
{
if (e.Error == null)
{
string response = e.Result.ToString();
results.TrySetResult(response);
}
else
{
results.TrySetResult("");
results.TrySetException(e.Error);
}
};
proxy.DownloadStringAsync(new Uri(url));
}
catch
{
results.TrySetResult("");
}
return results.Task;
}
ScheduledAgent class:
protected override void OnInvoke(ScheduledTask task)
{
foreach (var tile in tileList)
{
string dataString = jsonPostClientTask(parameters, url);
//update tile in used
FlipTileData tileData = new FlipTileData()
{
BackContent = "string content",
WideBackContent = "string back content",
BackBackgroundImage = new Uri("http://xxxx.xxx/xxx.png", UriKind.RelativeOrAbsolute),
WideBackBackgroundImage = new Uri("http://xxxx.xxx/xxx.png", UriKind.RelativeOrAbsolute),
};
ShellTile primaryTile = ShellTile.ActiveTiles.First();
if (primaryTile != null)
primaryTile.Update(tileData);
}
}