C# WPF MediaElement MyToolKit Youtube - c#

I would like to run youtube videos in a media element. This morning, everything worked well but now I have an error saying that an object is null. I've tried to find the object but there is not. An other group has the same case as mine. I didn't change anything.
private async void runYoutubeVideo(String youtubeId)
{
try
{
Console.WriteLine(youtubeId);
var url = await YouTube.GetVideoUriAsync(youtubeId, YouTubeQuality.Quality480P);
_mediaElementObject.Source = url.Uri;
_modelPlayer.CurrentMedia = new Media(url.Uri, YoutubeURLString);
TitleFile = _modelPlayer.CurrentMedia.FileName;
YoutubeURLString = null;
Uri tmp = new Uri(_modelPlayer.CurrentMedia.FilePath);
this._mediaElementObject.Source = tmp;
this.SliderVideoObject = 0;
createTimerTrick();
_mediaElementObject.Play();
}
catch
{
Console.WriteLine("Youtube Runner Error");
new NullReferenceException("Error");
return;
}
}

Related

C# WUApiLib know if a windows update needs a restart

I use this code to get pending windows updates and also most of the informations of the update:
static List<PendingUpdate> GetPendingUpdates()
{
var updateSession = new UpdateSession();
var updateSearcher = updateSession.CreateUpdateSearcher();
updateSearcher.Online = false; //set to true if you want to search online
List<PendingUpdate> pendingUpdates = new List<PendingUpdate>();
try
{
var searchResult = updateSearcher.Search("IsInstalled=0 And IsHidden=0");
if (searchResult.Updates.Count > 0)
{
Console.WriteLine("There are updates available for installation");
foreach (IUpdate windowsUpdate in searchResult.Updates)
{
PendingUpdate update = new PendingUpdate();
update.Title = windowsUpdate.Title;
update.Description = windowsUpdate.Description;
update.Downloaded = windowsUpdate.IsDownloaded;
update.Urls = new List<string>();
foreach (string url in windowsUpdate.MoreInfoUrls)
{
update.Urls.Add(url);
}
foreach (dynamic category in windowsUpdate.Categories)
{
update.Categories += category.Name + ", ";
}
pendingUpdates.Add(update);
}
}
}
catch (Exception ex)
{
Console.WriteLine("ERROR");
throw ex;
}
return pendingUpdates;
}
I also use this code to get to know if the computer currently needs a restart to finish installed updates:
static bool needsRestart()
{
ISystemInformation systemInfo = new SystemInformation();
return systemInfo.RebootRequired;
}
Now my question is, is it possible to get to know if an pending update needs a computer restart to finish? In the first code I get a IUpdate object but I dont see informations about a needed restart after installing this update. I there a way to get this information?
For the asynchronous installation I use something like this:
rebootRequired = false;
UpdateSession updateSession = new UpdateSession();
updateSession.ClientApplicationID = SusClientID;
IUpdateInstaller updatesInstaller = updateSession.CreateUpdateInstaller();
IInstallationJob job = updatesInstaller.BeginInstall(InstallProgressCallback, installComplete, installState);
// here is your installer code and the checking if the installation is completed
IInstallationProgress jobProgress = job.GetProgress();
for (int updateindex = 0; updateindex < updatesInstaller.Updates.Count; updateindex++)
{
IUpdateInstallationResult updateInstallResult = jobProgress.GetUpdateResult(updateindex);
rebootRequired |= updateInstallResult.RebootRequired;
}
if(rebootRequired)
{
// any of the updates need a reboot
}

Unable to cast object of type Mediaplayer to type IMediaPlayerSource2

I try to add a Playlist to the BackgroundMediaPlayer like this. So it looks like this:
try
{
Progr.IsActive = true;
ErrorMessage.Visibility = Visibility.Collapsed;
//This fills the ObservableCollection timeLine with Tracks
await UserAuthed.PopulateTimelineTracksAsync(timeLine);
//This should create the Playlist
CreatePlaylist(timeLine);
Progr.IsActive = false;
}
catch (Exception ex)
{
Progr.IsActive = false;
ErrorMessage.Visibility = Visibility.Visible;
}
private void CreatePlaylist(ObservableCollection<Collection> TrackCollection)
{
foreach (var item in TrackCollection)
{
MediaSource ms = MediaSource.CreateFromUri(new Uri(item.origin.uri));
ms.CustomProperties.Add("Title", item.origin.title);
ms.CustomProperties.Add("Artist", item.origin.user.username);
MPL.Items.Add(new MediaPlaybackItem(ms));
}
BackgroundMediaPlayer.Current.Source = MPL;
}
But at BackgroundMediaPlayer.Current.Source = MPL; he fails with {"Unable to cast object of type 'Windows.Media.Playback.MediaPlayer' to type 'Windows.Media.Playback.IMediaPlayerSource2'."}
What is this exception meaning? How can i fix it?
Edit: MPL is MediaPlaybackList.
Please update your code, with this:
private void CreatePlaylist(ObservableCollection<Collection> TrackCollection)
{
// Make a new list
MPL = new MediaPlaybackList();
foreach (var item in TrackCollection)
{
MediaSource ms = MediaSource.CreateFromUri(new Uri(item.origin.uri));
ms.CustomProperties.Add("Title", item.origin.title);
ms.CustomProperties.Add("Artist", item.origin.user.username);
MPL.Items.Add(new MediaPlaybackItem(ms));
}
BackgroundMediaPlayer.Current.Source = MPL;
}
Here is complete GitHub link for your reference. At the end you can find the CreatePlaybackList function.
Thank You!

Remembering log in credentials/permissions UWP/C# (Microsoft Cloud API)

I'm creating an app that access the Microsoft Cloud API to get health data. It uses OAuth to log in when you hit the Sign In Button
private void signinButton_Click(object sender, RoutedEventArgs e)
{
UriBuilder uri = new UriBuilder("https://login.live.com/oauth20_authorize.srf");
var query = new StringBuilder();
query.AppendFormat("redirect_uri={0}", Uri.EscapeDataString(RedirectUri));
query.AppendFormat("&client_id={0}", Uri.EscapeDataString(ClientId));
query.AppendFormat("&scope={0}", Uri.EscapeDataString(Scopes));
query.Append("&response_type=code");
uri.Query = query.ToString();
this.webView.Visibility = Visibility.Visible;
this.webView.Navigate(uri.Uri);
}
This brings up a webView with the page to log in using Microsoft credentials. Once completed, it leads to this:
private async void WebView_NavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)
{
//
// When the web view navigates to our redirect URI, extract the authorization code from
// the URI and use it to fetch our access token. If no authorization code is present,
// we're completing a sign-out flow.
//
if (args.Uri.LocalPath.StartsWith("/oauth20_desktop.srf", StringComparison.OrdinalIgnoreCase))
{
WwwFormUrlDecoder decoder = new WwwFormUrlDecoder(args.Uri.Query);
var code = decoder.FirstOrDefault((entry) => entry.Name.Equals("code", StringComparison.OrdinalIgnoreCase));
var error = decoder.FirstOrDefault((entry) => entry.Name.Equals("error", StringComparison.OrdinalIgnoreCase));
var errorDesc = decoder.FirstOrDefault((entry) => entry.Name.Equals("error_description", StringComparison.OrdinalIgnoreCase));
// Check the code to see if this is sign-in or sign-out
if (code != null)
{
// Hide the browser again, no matter what happened...
sender.Visibility = Visibility.Collapsed;
if (error != null)
{
this.responseText.Text = string.Format("{0}\r\n{1}", error.Value, errorDesc.Value);
return;
}
var tokenError = await this.GetToken(code.Value, false);
if (string.IsNullOrEmpty(tokenError))
{
this.responseText.Text = "Successful sign-in!";
this.signoutButton.IsEnabled = true;
this.signinButton.IsEnabled = false;
this.getProfileButton.IsEnabled = true;
this.getDevicesButton.IsEnabled = true;
this.getActivitiesButton.IsEnabled = true;
this.getDailySummaryButton.IsEnabled = true;
this.getHourlySummaryButton.IsEnabled = true;
}
else
{
this.responseText.Text = tokenError;
}
}
else
{
this.responseText.Text = "Successful sign-out!";
this.signoutButton.IsEnabled = false;
this.signinButton.IsEnabled = true;
this.getProfileButton.IsEnabled = false;
this.getDevicesButton.IsEnabled = false;
this.getActivitiesButton.IsEnabled = false;
this.getDailySummaryButton.IsEnabled = true;
this.getHourlySummaryButton.IsEnabled = false;
}
}
}
private async Task<string> GetToken(string code, bool isRefresh)
{
UriBuilder uri = new UriBuilder("https://login.live.com/oauth20_token.srf");
var query = new StringBuilder();
query.AppendFormat("redirect_uri={0}", Uri.EscapeDataString(RedirectUri));
query.AppendFormat("&client_id={0}", Uri.EscapeDataString(ClientId));
query.AppendFormat("&client_secret={0}", Uri.EscapeDataString(ClientSecret));
if (isRefresh)
{
query.AppendFormat("&refresh_token={0}", Uri.EscapeDataString(code));
query.Append("&grant_type=refresh_token");
}
else
{
query.AppendFormat("&code={0}", Uri.EscapeDataString(code));
query.Append("&grant_type=authorization_code");
}
uri.Query = query.ToString();
var request = WebRequest.Create(uri.Uri);
try
{
using (var response = await request.GetResponseAsync())
{
using (var stream = response.GetResponseStream())
{
using (var streamReader = new StreamReader(stream))
{
var responseString = streamReader.ReadToEnd();
var jsonResponse = JObject.Parse(responseString);
this.creds.AccessToken = (string)jsonResponse["access_token"];
this.creds.ExpiresIn = (long)jsonResponse["expires_in"];
this.creds.RefreshToken = (string)jsonResponse["refresh_token"];
string error = (string)jsonResponse["error"];
return error;
}
}
}
}
catch (Exception ex)
{
return ex.Message;
}
}
I don't want users to have to accept the permissions every time the app is launched. Is there a way to save credentials locally so that it automatically authenticates on launch? Thanks!
You can use
Windows.Storage.ApplicationData.Current.LocalSettings
This process good described by this answer Best Way to keep Settings for a WinRT App?
The code in link identity to UWP
Store the needed oauth parts in the credential locker API. Never store these kind of information in the normal settings API.
On start read the oauth information and use the refreshtoken to get a new access token.
More Information here.
https://msdn.microsoft.com/en-us/library/windows/apps/mt270189.aspx

WPF Dispatcher ListBox.Items.Add out of order

(Excuse, I'm Japanese. So I don't know so much about English.)
I have made a twitter client software with WPF, C#. I try to make streaming home timeline with a thread. But only the method Listbox.Items.Add is out of order.
If I try to do this method, Listbox.Items.Add does nothing. I wish you to tell me the mistake in the following code.
private void TLStreamingReflect(OAuth oauth)
{
string APIURL = "https://userstream.twitter.com/1.1/user.json";
StreamGETRequest(oauth, APIURL, "");
trd = new Thread(threading);
trd.Start();
}
public void threading()
{
//Mode MTA
//endless loop
while (true)
{
//this part is in order
string result = Streamreader.ReadLine();
DynamicJson JsonData = null;
Status status = new Status();
try
{
JsonData = DynamicJson.Parse(result);
status = new Status();
//Json→Status
VarTo.VarToStatus(status, JsonData);
}
catch { }
if (status.Text != null)
{
//↓this code is out of order
this.Dispatcher.Invoke(new Action(() => { TimeLineAdd(status); }));
}
}
}
public void TimeLineAdd(Status status)
{
//Abbreviation
(this part work DockPanel molding)
//↓ Only this code is out of order
tweetarea.Items.Add(Listboxitem);
// tweetarea is a ListBox object
}
Thank you for looking.

using C# to get an ec2-instance tag

I'm not a developer so maybe the answer is out there for a different solution but I can't really translate it from python or something else.
I'm trying to use the AWS .NET SDK to find an instance and then get the instance's tags. I've gotten as far as being able to determine if an instance is up and running or not. I also see how I can create and delete tags (not in code example below). But I don't see an easy way to actually check if a tag exists and get the value of the tag if it does exist.
Sorry if I'm missing the obvious but this is all new to me. Here's an example of the code I'm using to check if an instance is running.
instanceID = "i-myInstanceID";
do {
var myrequest = new DescribeInstanceStatusRequest();
DescribeInstanceStatusResponse myresponse = ec2.DescribeInstanceStatus(myrequest);
int isCount = myresponse.DescribeInstanceStatusResult.InstanceStatuses.Count;
for (int isc=0; isc < isCount; isc++) {
InstanceStatus instanceStatus = myresponse.DescribeInstanceStatusResult.InstanceStatuses[isc];
if (instanceStatus.InstanceId.Contains(instanceID)) {
Console.WriteLine("It looks like instance "+instanceID+" is running.");
idIdx = isc;
foundID = true;
break;
}
}
if ((foundID==false) && (secondCounter==1)) {
Console.Write("Looking for instance "+instanceID);
} else {
Console.Write(".");
}
Thread.Sleep(1000);
secondCounter++;
if (secondCounter > 5) {
break;
}
} while (foundID == false) ;
First send a DescribeInstancesRequest to get the list of Instances:
public DescribeInstancesResult GetInstances(Ec2Key ec2Key)
{
_logger.Debug("GetInstances Start.");
AmazonEC2 ec2 = CreateAmazonEc2Client(ec2Key);
var ec2Request = new DescribeInstancesRequest();
DescribeInstancesResponse describeInstancesResponse = ec2.DescribeInstances(ec2Request);
DescribeInstancesResult result = describeInstancesResponse.DescribeInstancesResult;
_logger.Debug("GetInstances End.");
return result;
}
Then loop through the instances until you find the one you want, and then use the Tag.GetTagValueByKey method:
// This just calls the above code
DescribeInstancesResult ec2Instances = _ec2ResourceAccess.GetInstances(ec2Key);
var returnInstances = new List<Ec2UtilityInstance>();
foreach (var reservation in ec2Instances.Reservation)
{
foreach (var runningInstance in reservation.RunningInstance)
{
var returnInstance = new Ec2UtilityInstance();
returnInstance.InstanceId = runningInstance.InstanceId;
returnInstance.InstanceName = runningInstance.Tag.GetTagValueByKey("Name");
returnInstance.Status = (Ec2UtilityInstanceStatus)Enum.Parse(typeof(Ec2UtilityInstanceStatus), runningInstance.InstanceState.Name, true);
returnInstance.DefaultIp = runningInstance.Tag.GetTagValueByKey("DefaultIp");
returnInstance.InstanceType = runningInstance.InstanceType;
returnInstance.ImageId = runningInstance.ImageId;
returnInstances.Add(returnInstance);
}
}
Here is the link for full source that this was taken from:
https://github.com/escherrer/EC2Utilities
Common\Manager
and
Common\ResourceAccess

Categories

Resources