System.Net.WebException on YoutubeExtractor when downloading a video - c#

Environment
Windows 8.1
Visual Studio 2017 Community
C#
WPF application
Issue
YoutubeExtractor throws System.Net.WebException when downloading a video.
I got YoutubeExtractor by Nuget and it doesn't work. The VideoInfo object isn't null. I tried several videos on Youtube and the same exceptions popped up. I googled the issue and it didn't give me much help.
Here's the code.
var videos = DownloadUrlResolver.GetDownloadUrls(#"https://www.youtube.com/watch?v=M1wLtAXDgqg");
VideoInfo video = videos
.First(info => info.VideoType == VideoType.Mp4 && info.Resolution == 360);
if (video.RequiresDecryption)
DownloadUrlResolver.DecryptDownloadUrl(video);
var videoDownloader = new VideoDownloader(video, System.IO.Path.Combine("D:", video.Title + video.VideoExtension));
videoDownloader.DownloadProgressChanged += (sender_, args) => Console.WriteLine(args.ProgressPercentage);
videoDownloader.Execute(); // I got the exception here.
How can I solve this issue? Thanks.
EDIT : 2017/10/26 13:42 GMT
Alexey 'Tyrrrz' Golub's answer helped so much! I corrected his original code and here it is.
using YoutubeExplode;
using YoutubeExplode.Models.MediaStreams;
var client = new YoutubeClient();
var video = await client.GetVideoAsync("bHzHlSLhtmM");
// double equal signs after s.VideoQuality instead of one
var streamInfo = video.MuxedStreamInfos.First(s => s.Container == Container.Mp4 && s.VideoQuality == VideoQuality.Medium360);
// "D:\\" instead of "D:"
var pathWithoutExtension = System.IO.Path.Combine("D:\\", video.Title);
// streamInfo.Container.GetFileExtension() instead of video.VideoExtension (video doesn't have the property)
var path = System.IO.Path.ChangeExtension(pathWithoutExtension, streamInfo.Container.GetFileExtension());
// new Progress<double>() instead of new Progress()
await client.DownloadMediaStreamAsync(streamInfo, path, new Progress<double>(d => Console.WriteLine(d.ToString("p2"))));

Related

How to get last system shutdown\boot time (Win10)

I try to get last system shutdown and\or reboot.
But it not works for me.
I make reboot my machine yeasterday and make shutdown-power on 10 minutes ago.
But code says me about last shutdown - it is yeasterday.
I read this questions:
Get the date-time of last windows shutdown event using .NET
How to know when was Windows started or shutdown?
But it is not work for my machine.
I try this code:
var _rebootPerformanceCounter = new global::System.Diagnostics.PerformanceCounter("System", "System Up Time");
_rebootPerformanceCounter.NextValue();
var uptimeSpan = TimeSpan.FromSeconds(_rebootPerformanceCounter.NextValue());
var uptime = uptimeSpan.ToString();
And this:
string sKey = #"System\CurrentControlSet\Control\Windows";
using (Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(sKey))
{
string sValueName = "ShutdownTime";
byte[] val = (byte[]) key.GetValue(sValueName);
long valueAsLong = BitConverter.ToInt64(val, 0);
var shutdownTime= DateTime.FromFileTime(valueAsLong);
Console.WriteLine(shutdownTime); //THIS
}
And this:
if (EventLog.Exists("System"))
{
var log = new EventLog("System", Environment.MachineName, "EventLog");
var entries = new EventLogEntry[log.Entries.Count];
log.Entries.CopyTo(entries, 0);
var startupTimes = entries.Where(x => x.InstanceId == 2147489653).Select(x => x.TimeGenerated);
var shutdownTimes = entries.Where(x => x.InstanceId == 2147489654).Select(x => x.TimeGenerated);
var shutdownEvents = entries.Where(x => x.InstanceId == 2147484722);
}
So, the values are same: it says that i reboot my machine last evening and do not show last power off time.
I try this code on PC and notebook with same results.
At my PC i have uninterrupted power supply unit and i turned it off.
So I'm confused. What am I doing wrong?
Solution is very simple: i should off "clever power management" with -
powercfg -h off
And code works!

Sometimes taken picture not get from device

I am creating Project in Xamarin Form PCL. The issue is sometimes and some device picture are not getting back from Android device. I am using Plugin.Media.CrossMedia to take a picture. The first user can take multiple pictures and then, I am uploading the pictures.
Pic:
if (RPic == null)
{
RPic = new List<RImage>();
}
RImage ri = new RImage();
var photo = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions()
{
CompressionQuality = 92,
PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium
});
if (photo != null)
{
ri.OrderID_ = _OrderId;
ri.Gid_ = 0;
ri.Latitude_ = Lat;
ri.Longitude_ = Long;
ri.ImagePath_ = photo.Path;
ri.dateTime_ = dateTime;
RPic.Add(ri);
}
After this code, i am getting pictures from ri.ImagePath_. But some device this code miss to take the picture from the device. Maybe somebody faces the same issue so, I can get the suggestions. Thanks for your suggestion and rectified code.

Play audio url using xamarin MediaPlayer

Why xamarin MediaPlayer (on Xamarin.Android) can play audio as a stream from a link like this (mediaUrl1) :
https://ia800806.us.archive.org/15/items/Mp3Playlist_555/AaronNeville-CrazyLove.mp3
But can't do it from a link like this (mediaUrl2):
http://api-streaming.youscribe.com/v1/products/2919465/documents/3214936/audio/stream
private MediaPlayer player;
//..
player = new MediaPlayer();
player.SetAudioStreamType(Stream.Music);
//..
await player.SetDataSourceAsync(ApplicationContext, Android.Net.Uri.Parse(mediaUrl));
//..
player.PrepareAsync();
//..
Is there a way to play the link above (mediaUrl2) without (of course) downloading the file first?
Here is the full source of the sample i am using. Any help would be appreciated.
http://api-streaming.youscribe.com/v1/products/2919465/documents/3214936/audio/stream
That is an HTTP mpga stream and is not directly supported by any of the Android APIs that I know of and thus is not supported by MediaPlayer (consult the Android Support Media Formats for further reading).
You can review the logcat output of your MediaPlayer code and you will see output like:
[MediaPlayerNative] start called in state 4, mPlayer(0x8efb7240)
[MediaPlayerNative] error (-38, 0)
[MediaPlayer] Error (-38,0)
[MediaHTTPConnection] readAt 1161613 / 32768 => java.net.ProtocolException
[MediaHTTPConnection] readAt 1161613 / 32768 => java.net.ProtocolException
[MediaPlayerNative] error (1, -2147483648)
[MediaPlayer] Error (1,-2147483648)
Google's Android ExoPlayer can stream that media format properly.
This is a really simple and very crude example of ExoPlayer, but it will show you that it does play that stream:
ExoPlayer Example:
var mediaUrl = "http://api-streaming.youscribe.com/v1/products/2919465/documents/3214936/audio/stream";
var mediaUri = Android.Net.Uri.Parse(mediaUrl);
var userAgent = Util.GetUserAgent(this, "ExoPlayerDemo");
var defaultHttpDataSourceFactory = new DefaultHttpDataSourceFactory(userAgent);
var defaultDataSourceFactory = new DefaultDataSourceFactory(this, null, defaultHttpDataSourceFactory);
var extractorMediaSource = new ExtractorMediaSource(mediaUri, defaultDataSourceFactory, new DefaultExtractorsFactory(), null, null);
var defaultBandwidthMeter = new DefaultBandwidthMeter();
var adaptiveTrackSelectionFactory = new AdaptiveTrackSelection.Factory(defaultBandwidthMeter);
var defaultTrackSelector = new DefaultTrackSelector(adaptiveTrackSelectionFactory);
exoPlayer = ExoPlayerFactory.NewSimpleInstance(this, defaultTrackSelector);
exoPlayer.Prepare(extractorMediaSource);
exoPlayer.PlayWhenReady = true;
Note: exoPlayer is a class-level variable of SimpleExoPlayer type
Note: this is using the Xamarin.Android binding libraries from the Xam.Plugins.Android.ExoPlayer package
ExoPlayer Docs:
https://developer.android.com/guide/topics/media/exoplayer

Filter EC2 Instance with "DescribeInstanceStatus" routine - AWS SDK

I'm trying to filter EC2 instances using the AWS SDK in .NET and, although I have seen inumerous threads on SO and on other websites of people resolving this issue, nothing I've tried on my end worked.
So, as a last resource, I'm coming to you guys for help. Can anyone shed some light on what I'm missing ? I know it's very likely that I'm doing something stupid, but I can't afford to waste too much time solving this issue.
This is the chunk of code I'm using to filter an EC2 instance (get it's metadata) by it's tag name:
DescribeInstanceStatusRequest req = new DescribeInstanceStatusRequest ();
req.Filters.Add (new Filter() { Name = "tag:Name", Values = new List <string> () { "some_random_name" } });
// Executing request & fetching response
DescribeInstanceStatusResponse resp = m_ec2Client.DescribeInstanceStatus (req);
But I keep on running into this exception:
The filter 'tag:Name' is invalid
I have replaced the filter name ("tag:Name" in the example) by several filters listed in the documentation (e.g. "tag-key", "tag-value", "tag:key=value"), but nothing works.
Thank you all in advance :)
After a more thorough research, I found out that the "DescribeInstanceStatus" routine doesn't support searching by tag, but I found a somewhat "simple" way of doing so. I'll post it in here in case anyone goes through the same situation.
Here's how:
DescribeInstancesRequest req = new DescribeInstancesRequest ();
req.Filters.Add (new Filter () { Name = "tag-value", Values = new List <string> () { "something" }});
// Executing request & fetching response
DescribeInstancesResponse resp = m_ec2Client.DescribeInstances (req);
return resp.Reservations.SelectMany (x => x.Instances).Where (y => y.State.Name == InstanceStateName.Pending || y.State.Name == InstanceStateName.Running).ToList (); {code}
In theory, with this routine you can use any of the filters listed under the "Supported Filters" table in the documentation.
Getting Number of running instance from AWS EC2
DescribeInstancesRequest req = new DescribeInstancesRequest();
req.Filters.Add(new Filter {
Name = "instance-state-name",
Values = new List<string>() { "running" }
});
DescribeInstancesResponse resp = _amazonEC2Client.DescribeInstances(req);
It's may be...
// Executing request & fetching response
DescribeInstancesResponse resp = m_ec2Client.DescribeInstances (
new DescribeInstancesRequest()
{
Filters = new List<Filter>()
{
new Filter("tag:Name", new List<string>(){"some_random_name"})
}
});

Tweetsharp - Oauthaccestoken overflowexception

I've been stuck for a while on the following problem when I debug the following code:
TwitterService service = new TwitterService("_consumerkey", "_consumersecret");
OAuthRequestToken requestToken = service.GetRequestToken();
Uri uri = service.GetAuthorizationUri(requestToken);
Process.Start(uri.ToString());
Console.Write("Verificatiecode? ");
string verifier = Console.ReadLine();
OAuthAccessToken access = service.GetAccessToken(requestToken, verifier);
service.AuthenticateWith(access.Token, access.TokenSecret);
TwitterUser twitterUser = service.GetUserProfile(new GetUserProfileOptions());
ListFriendsOptions friends_options = new ListFriendsOptions();
friends_options.UserId = twitterUser.Id;
friends_options.Cursor = -1;
var friends = service.ListFriends(friends_options);
do
{
if (friends_options.Cursor != null)
{
foreach (var friend in friends) {Console.WriteLine(friend.ScreenName);}
friends_options.Cursor = friends.NextCursor;
}
} while (friends_options.Cursor != null);
Console.ReadKey(true);
I always get an overflow exception after filling in the verification code here:
OAuthAccessToken access = service.GetAccessToken(requestToken, verifier);
Anyone who can help me?
Thanks in advance
Looking at the source, it seems like the problem is when it tries to return the results inside GetAccessToken:
return new OAuthAccessToken()
{
Token = nameValueCollection["oauth_token"] ?? "?",
TokenSecret = nameValueCollection["oauth_token_secret"] ?? "?",
//this is the only place a conversion to int is occurring that I've found
UserId = Convert.ToInt32(nameValueCollection["user_id"] ?? "0"),
ScreenName = nameValueCollection["screen_name"] ?? "?"
};
Looking on Github, it seems this update might solve the problem.
Download the last version of TweetSharp, old version has user_id as Int32, but new version as Int64 https://github.com/danielcrenna/tweetsharp
This happens because Twitter introduced 64bit user ids a while back.
Older Twitter accounts still have the 32-bit Ids and TweetSharp works just fine with them. But if you opened an account recently you already might have a 64 bit ID and Tweet Sharp fails.
I fixed the problem by getting the tweetsharp-unofficial package from NuGet.

Categories