Xamarin.Forms(Android) Crashes when injecting Android native HttpClient into YoutubeClient constructor
Dear Tyrrrz!
I am very impressed by your work and enthusiasm. I am already doing my second learning project which builds on your lib. And this time a serious one :)
Recently I have encountered the following issue when using YoutubeExplode in my Xamarin.Forms(Android) project:
when injecting the native Android HttpClient into the YoutubeExplode client (ytE), the ytE client throws "System.InvalidOperationException Message=Sequence contains no elements" exception at the first call on the ytE client.
when using YoutubeExplode() default constructor without passing an HttpClient, the ytE client works.
The problem here is, that the managed HttpClient implementation (which ytE is using by default) has a very-very subpar performance on Android. Microsoft documentation and also my experience says that whenever possible one should use the native andoid HttpClient implementation in Xamarin. The difference between native and managed HttpClient is day and night no matter what small query you are doing.
Here is the code: App1.Android (platform specific project): MainActivity.cs (getting the native HattpClient and injecting it into the shared code) HttpClient httpClient = new HttpClient(new Xamarin.Android.Net.AndroidClientHandler());
LoadApplication(new App(httpClient));
App1.App.xaml.cs (shared code): public partial class App : Application { public YoutubeClient Ytclient { get; private set; }
public App(HttpClient httpClient)
{
InitializeComponent();
Ytclient = new YoutubeClient(httpClient);
MainPage = new MainPage();
}
protected override async void OnStart()
{
// Handle when your app starts
var result = await Ytclient.GetVideoAsync("WXv31OmnKqQ");
}
}
If required I can share code required to reproduce the error. If not, the procedure is as follows:
- Latest Visual Studio, Latest Xamarin.Forms
- New Xamarin.Forms(Android) project
- copy the above code segments to your Android.MainActivity.cs and the shared project
Best Regards Janos
Hey there, Any chance you can give me the full stack trace of the exception you're describing?
Unlike the other, good behaving MS platforms, Xamarin.Forms(Android) is really unhelpful with its exception propagation.
In debug mode when I reproduce the crash I get the following empty Exception:
**System.InvalidOperationException:** 'Sequence contains no elements'
from which no information can be extracted.
After hitting the continue execution button, the Debug Output window shows the following log:
**System.InvalidOperationException:** 'Sequence contains no elements'
Thread finished: <Thread Pool> #8
The thread 0x8 has exited with code 0 (0x0).
08-08 13:30:40.044 D/Mono ( 4835): DllImport attempting to load: '/system/lib/liblog.so'.
08-08 13:30:40.045 D/Mono ( 4835): DllImport loaded library '/system/lib/liblog.so'.
08-08 13:30:40.045 D/Mono ( 4835): DllImport searching in: '/system/lib/liblog.so' ('/system/lib/liblog.so').
08-08 13:30:40.045 D/Mono ( 4835): Searching for '__android_log_print'.
08-08 13:30:40.045 D/Mono ( 4835): Probing '__android_log_print'.
08-08 13:30:40.045 D/Mono ( 4835): Found as '__android_log_print'.
08-08 13:30:40.046 I/MonoDroid( 4835): UNHANDLED EXCEPTION:
08-08 13:30:40.051 I/MonoDroid( 4835): System.InvalidOperationException: Sequence contains no elements
08-08 13:30:40.051 I/MonoDroid( 4835): at System.Linq.Enumerable.First[TSource] (System.Collections.Generic.IEnumerable`1[T] source) [0x00010] in <0161b1a13afc4a1cb4192212e415ad60>:0
08-08 13:30:40.051 I/MonoDroid( 4835): at YoutubeExplode.YoutubeClient.GetVideoAsync (System.String videoId) [0x00230] in <4673477efbbe419a9d4ae878a0cccaf8>:0
08-08 13:30:40.051 I/MonoDroid( 4835): at App1.App.OnStart () [0x0002a] in C:\PROG\_MISC\Unnamed junk\YTExplodeHttpClientError\App1\App1\App.xaml.cs:24
08-08 13:30:40.051 I/MonoDroid( 4835): at System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.<ThrowAsync>b__7_0 (System.Object state) [0x00000] in <ff07eae8184a40a08e79049bbcb31a0e>:0
08-08 13:30:40.051 I/MonoDroid( 4835): at Android.App.SyncContext+<>c__DisplayClass2_0.<Post>b__0 () [0x00000] in <b62c3fba3fe848f3bb323dbe33464223>:0
08-08 13:30:40.051 I/MonoDroid( 4835): at Java.Lang.Thread+RunnableImplementor.Run () [0x00008] in <b62c3fba3fe848f3bb323dbe33464223>:0
08-08 13:30:40.051 I/MonoDroid( 4835): at Java.Lang.IRunnableInvoker.n_Run (System.IntPtr jnienv, System.IntPtr native__this) [0x00009] in <b62c3fba3fe848f3bb323dbe33464223>:0
08-08 13:30:40.051 I/MonoDroid( 4835): at (wrapper dynamic-method) Android.Runtime.DynamicMethodNameCounter.42(intptr,intptr)
08-08 13:30:40.064 W/zygote ( 4835): JNI RegisterNativeMethods: attempt to register 0 native methods for android.runtime.JavaProxyThrowable
08-08 13:30:40.068 D/Mono ( 4835): DllImport searching in: '__Internal' ('(null)').
08-08 13:30:40.069 D/Mono ( 4835): Searching for 'java_interop_jnienv_throw'.
08-08 13:30:40.069 D/Mono ( 4835): Probing 'java_interop_jnienv_throw'.
08-08 13:30:40.069 D/Mono ( 4835): Found as 'java_interop_jnienv_throw'.
**System.InvalidOperationException:** 'Sequence contains no elements'
08-08 13:30:42.844 E/mono ( 4835):
08-08 13:30:42.844 E/mono ( 4835): Unhandled Exception:
08-08 13:30:42.844 E/mono ( 4835): System.InvalidOperationException: Sequence contains no elements
08-08 13:30:42.844 E/mono ( 4835): at System.Linq.Enumerable.First[TSource] (System.Collections.Generic.IEnumerable`1[T] source) [0x00010] in <0161b1a13afc4a1cb4192212e415ad60>:0
08-08 13:30:42.844 E/mono ( 4835): at YoutubeExplode.YoutubeClient.GetVideoAsync (System.String videoId) [0x00230] in <4673477efbbe419a9d4ae878a0cccaf8>:0
08-08 13:30:42.844 E/mono ( 4835): at App1.App.OnStart () [0x0002a] in C:\PROG\_MISC\Unnamed junk\YTExplodeHttpClientError\App1\App1\App.xaml.cs:24
08-08 13:30:42.844 E/mono ( 4835): at (wrapper dynamic-method) Android.Runtime.DynamicMethodNameCounter.42(intptr,intptr)
08-08 13:30:42.844 E/mono ( 4835): at (wrapper native-to-managed) Android.Runtime.DynamicMethodNameCounter.42(intptr,intptr)
08-08 13:30:42.844 E/mono-rt ( 4835): [ERROR] FATAL UNHANDLED EXCEPTION: System.InvalidOperationException: Sequence contains no elements
08-08 13:30:42.844 E/mono-rt ( 4835): at System.Linq.Enumerable.First[TSource] (System.Collections.Generic.IEnumerable`1[T] source) [0x00010] in <0161b1a13afc4a1cb4192212e415ad60>:0
08-08 13:30:42.844 E/mono-rt ( 4835): at YoutubeExplode.YoutubeClient.GetVideoAsync (System.String videoId) [0x00230] in <4673477efbbe419a9d4ae878a0cccaf8>:0
08-08 13:30:42.844 E/mono-rt ( 4835): at App1.App.OnStart () [0x0002a] in C:\PROG\_MISC\Unnamed junk\YTExplodeHttpClientError\App1\App1\App.xaml.cs:24
08-08 13:30:42.844 E/mono-rt ( 4835): at (wrapper dynamic-method) Android.Runtime.DynamicMethodNameCounter.42(intptr,intptr)
08-08 13:30:42.844 E/mono-rt ( 4835): at (wrapper native-to-managed) Android.Runtime.DynamicMethodNameCounter.42(intptr,intptr)
08-08 13:30:42.845 D/ ( 4835): HostConnection::get() New Host Connection established 0x8b8dbcc0, tid 4835
Hi Alexey!
I created a minimal "working" example of the crash
https://github.com/j4ni/YoutubeExplodeAndroidHttpClientCrash
I have registered at GH only because of this bugreport :)
Thanks for the good work in advance!
My guess is that the injected HttpClient somehow causes YouTube to return a different response, one which doesn't have the data YoutubeExplode is looking for. I'm assuming First() in the stack trace is this one: https://github.com/Tyrrrz/YoutubeExplode/blob/909a50f93cc59faff84adf0f9e5b7891cfd5d2bc/YoutubeExplode/YoutubeClient.Video.cs#L329-L332
I don't have the workload to test this with Xamarin, can you take a look at the response in fiddler?
Or maybe there's a way I can debug it without installing Xamarin workload?
Hi there,
I have flattened your YtE project and the Xamarin.Forms project into a single assembly, so I could do some debugging:
I call GetVideo():
var result = await Ytclient.GetVideoAsync("WXv31OmnKqQ");
This causes the exception:
//// Extract upload date
//var videoUploadDate = videoWatchPageHtml.GetElementsBySelector("meta[itemprop=\"datePublished\"]")
// .First().GetAttribute("content").Value.ParseDateTimeOffset("yyyy-MM-dd");
I have taken the above fluent syntax apart to step by step:
e1 is already empty, so .First() will throw:
var e1 = videoWatchPageHtml.GetElementsBySelector("meta[itemprop=\"datePublished\"]").ToList();
var body = HtmlRenderer.Default.RenderNode(videoWatchPageHtml.GetBody());
this returns (I dont know how to de-escape it):
"<body id=\"body\" class=\"atom fusion-tn invert\">\n <script>\n var ytcfg = {d: function() {return (window.yt && yt.config_) || ytcfg.data_ || (ytcfg.data_ = {});},get: function(k, o) {return (k in ytcfg.d()) ? ytcfg.d()[k] : o;},set: function() {var a = arguments;if (a.length > 1) {ytcfg.d()[a[0]] = a[1];} else {for (var k in a[0]) {ytcfg.d()[k] = a[0][k];}}}};\n ytcfg.set({\"EXPERIMENT_FLAGS\":{\"send_ad_playback_context_on_promoted_video_for_web\":true,\"mweb_autonav_idle_time\":1800000,\"enable_website_actions_on_mweb\":true,\"pass_biscotti_id_in_header_ajax\":true,\"add_border_to_bulleit_mweb_skip\":true,\"mweb_add_ad_info_button_on_fullscreen_only_devices\":true,\"mweb_font_prominent\":true,\"enable_static_font_size_on_text_only_preview\":true,\"lact_disable_scroll_mweb\":true,\"mweb_async_late_modules\":true,\"king_crimson_player_redux\":true,\"browse_frontend_w2w_mweb_small_single_video_renderer\":true,\"mweb_cougar\":true,\"web_use_beacon_api_for_ad_click_server_pings\":true,\"mweb_enable_instream_ui_refresh\":true,\"mweb_preload_related_imgs_num\":0,\"log_window_onerror_fraction\":0.1,\"web_memory_bloat_mb\":0,\"html5_serverside_pagead_id_sets_cookie\":true,\"mweb_blazer_reset_lact_on_popstate\":true,\"enable_instream_companion_on_mweb\":true,\"use_full_timing_library\":true,\"suggest_exp_str\":\"\",\"lact_mobile_listeners\":true,\"w2w_mweb_small_single_video_renderer\":true,\"mweb_autonav\":true,\"mweb_blazer_disable_my_videos_edit\":true,\"mweb_rename_csi_actions\":true,\"lact_local_listeners\":true,\"enable_brand_companion_on_mweb\":true,\"mweb_thumbnail_prominent\":true},\"EXPERIMENT_INFO\":{\"ids\":[23723208,23735276,23784900,23796352,23804955,23810058,23811609,23821261,23823457,23824202,23828083,23829626,23829996,23830086,23830090,23832863,23834153,23834195,24630101],\"fexp\":\"23718632,23723208,23735276,23735348,23744176,23751767,23784900,23788875,23793834,23796352,23804281,23804955,23805410,23810058,23811609,23818122,23818585,23821261,23823457,23824202,23827174,23828083,23829626,23829996,23830086,23830090,23832308,23832863,23834153,23834195,24630101,9449243\"}});\n </script>\n <script>\n var original_url = encodeURIComponent(encodeURIComponent(encodeURIComponent(document.location.href)));\n var iframe_url = 'https://accounts.google.com/ServiceLogin?passive=true&hl=en&continue=https%3A%2F%2Fwww.youtube.com%2Fsignin%3Fnext%3Dhttps%253A%252F%252Fm.youtube.com%252Fsignin_passive%253Foriginal_url%253DORIGINAL_URL_PLACE_HOLDER%26feature%3Dmobile_passive%26hl%3Den%26action_handle_signin%3Dtrue%26noapp%3D1%26app%3Dm&uilel=3&service=youtube'.replace('ORIGINAL_URL_PLACE_HOLDER', original_url);\n document.write('<iframe src=\\\"' + iframe_url + '\\\" style=\\\"display:none;\\\"></iframe>');\n </script>\n <div id=\"player\">\n </div>\n <div id=\"guide-layout-container\">\n <div id=\"guide-container\">\n </div>\n <div id=\"content-container\">\n <div id=\"content\">\n </div>\n </div>\n <div id=\"guide-overlay\">\n </div>\n <div id=\"lightbox\">\n </div>\n <div id=\"toast\">\n </div>\n <div id=\"content-overlay\">\n </div>\n <div id=\"fullscreen-overlay\">\n </div>\n </div>\n <div id=\"_yt_orientation_detect\">\n </div>\n <div id=\"unicorn-iframe-container\" class=\"hid\">\n <div id=\"unicorn-iframe\">\n </div>\n </div>\n</body>"
This results in 77 nodes:
var descendingNodes = videoWatchPageHtml.GetDescendants().ToList();
- Does the above info help or should I try to do some additional debugging?
- Also is there a method which extracts from LtGt.HtmlDocument the string representation of a Html document?
- I dont know how to cut the native Android HttpClient out o Xamarin. There probably is some way which I am not aware of.
- Xamarin can be annoying but it also could be one of the more important platforms Your video scraper is used on. :)
- Tell me where you need further support on this bug!
BR Janos
Hmm, it looks like there's something definitely wrong with the content, but it could be that it's parsed incorrectly.
Does the above info help or should I try to do some additional debugging?
If you put a breakpoint here (https://github.com/Tyrrrz/YoutubeExplode/blob/909a50f93cc59faff84adf0f9e5b7891cfd5d2bc/YoutubeExplode/YoutubeClient.Video.cs#L44) you can inspect the raw HTML in the raw variable. Can you copy it for me?
Also is there a method which extracts from LtGt.HtmlDocument the string representation of a Html document?
No but see above, it should be enough.
Hi, I put a breakpoint on line 44 and did two runs with two different videos. The youtube-VideoId is the Pastebin title.
https://pastebin.com/zsGT45xs
https://pastebin.com/qbTCzgc0
Regarding Fiddler, I installed it but couldn't catch the Android emulator's traffic. All webbrowser traffic was visible end decoded though.
I don't know whether it makes any difference for YtE, but MS states that the android Http client has less functionality than the managed client. https://docs.microsoft.com/en-us/xamarin/android/app-fundamentals/http-stack?tabs=windows
Ok so I see what's the problem now, YouTube responds with the mobile version of the site.
I'm suspecting Android HttpClient sets some default headers to represent the device as an Android device, can you override them? Most likely the User-Agent header needs to be set to something that conforms to a normal PC browser.
I have added some browser UA string and now it works, which is a great news, thank You very much!
I have posted the details under: https://pastebin.com/UE3UHHsV
- How do you plan to go with the situation of requiring custom ua-string? (whose responsibility will be in the future to configure the ua-sting in android environment when consuming YtE)
- I have now looked into HttpClientEx.cs. And what strikes me is, that I can not see any configuration targeting the user agent string configuration. And despite that if I just use the default YoutubeClient() constructor, it gives a working configuration (but ofc. the original problem was, that I wanted to inject the native Android HttpClient ). How is that?
I have done some follow up testing and can confirm that with the above settings (last comment, Pastebin) both x86 Android emulator and mobile device work with the injected HttpClient!
Yay, great :)
How do you plan to go with the situation of requiring custom ua-string? (whose responsibility will be in the future to configure the ua-sting in android environment when consuming YtE)
YtE can enforce some of the headers after receiving an HttpClient.
I have now looked into HttpClientEx.cs. And what strikes me is, that I can not see any configuration targeting the user agent string configuration. And despite that if I just use the default YoutubeClient() constructor, it gives a working configuration (but ofc. the original problem was, that I wanted to inject the native Android HttpClient ). How is that?
I'm guessing YouTube treats unset User-Agent as desktop user agent. Android HttpClient has User-Agent set automatically while regular HttpClient doesn't.