Exception detected while using GetPositionAsync Geolocator - c#

I'm getting an exception error: System.Threading.Tasks.TaskCanceledException, while trying to get some geolocation informations using Plugin.Geolocator.
here 's the exception that I get : System.Threading.Tasks.TaskCanceledException: A task was canceled.
at Plugin.Geolocator.GeolocatorImplementation.GetPositionAsync (System.Nullable1[T] timeout, System.Nullable1[T] cancelToken, System.Boolean includeHeading) [0x004d3] in :0
at interface_test.MainPage.CreateMainPageAsync () [0x0018b] in /Users/khalidharkati/Projects/interface_test/interface_test/MainPage.xaml.cs:140
at interface_test.App.OnStart () [0x0001a] in /Users/khalidharkati/Projects/interface_test/interface_test/App.xaml.cs:23
at System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.b__6_0 (System.Object state) [0x00000] in <58604b4522f748968296166e317b04b4>:0
at Android.App.SyncContext+<>c__DisplayClass2_0.b__0 () [0x00000] in <788a34f7a7b84486905dfde786529d42>:0
at Java.Lang.Thread+RunnableImplementor.Run () [0x00008] in <788a34f7a7b84486905dfde786529d42>:0
at Java.Lang.IRunnableInvoker.n_Run (System.IntPtr jnienv, System.IntPtr native__this) [0x00009] in <788a34f7a7b84486905dfde786529d42>:0
at at (wrapper dynamic-method) Android.Runtime.DynamicMethodNameCounter.40(intptr,intptr)
To be able to use an async constructor, I made one with the position as an argument:
public MainPage(Plugin.Geolocator.Abstractions.Position position)
{
...
}
Then I added this method to get my position:
public static async Task<MainPage> CreateMainPageAsync()
{
var locator = CrossGeolocator.Current;
locator.DesiredAccuracy = 50;
var position = await locator.GetPositionAsync(TimeSpan.FromSeconds(10));
MainPage page = new MainPage(position);
return page;
}
In the app.xaml.cs file, I added this code to the OnStart() method:
protected override async void OnStart()
{
interface_test.MainPage main = await interface_test.MainPage.CreateMainPageAsync();
MainPage = main;
}
PS: Before I update some components, Xamarin and some packages, I start getting this error.

I solved it , actually , this might sound stupid , but I just forgot to turn my GPS on , on my phone . that's it .

Related

Firebase cloud functions "Error: System.AggregateException: One or more errors occurred."

I made a 2ยบ gen function on cloud functions.
const functions = require('#google-cloud/functions-framework');
functions.http('canplace', (req, res) => {
print("hi mark");
});
When i try call it.
functions = FirebaseFunctions.DefaultInstance;
functions.GetHttpsCallable("canplace").CallAsync().ContinueWith(task => {
if (task.IsCompletedSuccessfully) {
Debug.Log("finished");
Debug.Log(task.Result.Data);
}else if (task.IsFaulted) {
Debug.Log("Error: " + task.Exception.Message);
}else if (task.IsCanceled) {
Debug.Log("Canceled ");
}
});
I get that error:
Error: System.AggregateException: One or more errors occurred. (INTERNAL) ---> Firebase.Functions.FunctionsException: INTERNAL
at Firebase.Functions.HttpsCallableReference.<CallAsync>b__9_0 (System.Threading.Tasks.Task`1[TResult] task) [0x00057] in /Users/runner/work/firebase-unity-sdk/firebase-unity-sdk/functions/src/HttpsCallableReference.cs:88
at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2[TAntecedentResult,TResult].InnerInvoke () [0x00024] in <8f06425e63004caf99a79845675f751e>:0
at System.Threading.Tasks.Task.Execute () [0x00000] in <8f06425e63004caf99a79845675f751e>:0
--- End of inner exception stack trace ---
---> (Inner Exception #0) Firebase.Functions.FunctionsException: INTERNAL
at Firebase.Functions.HttpsCallableReference.<CallAsync>b__9_0 (System.Threading.Tasks.Task`1[TResult] task) [0x00057] in /Users/runner/work/firebase-unity-sdk/firebase-unity-sdk/functions/src/HttpsCallableReference.cs:88
at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2[TAntecedentResult,TResult].InnerInvoke () [0x00024] in <8f06425e63004caf99a79845675f751e>:0
at System.Threading.Tasks.Task.Execute () [0x00000] in <8f06425e63004caf99a79845675f751e>:0 <---
UnityEngine.Debug:Log (object)
FirebaseManager/<>c:<InitializeFirebase>b__15_0 (System.Threading.Tasks.Task`1<Firebase.Functions.HttpsCallableResult>) (at Assets/Scripts/FirebaseManager.cs:56)
System.Threading._ThreadPoolWaitCallback:PerformWaitCallback ()
I tryed debug the code both on unity and on firebase but still no sucess, i also tryed look videos and similar problems but didnt find any answer, not even on the API.

Xamrin Forms NavigationPage System.InvalidCastException

I can not figure out why it is returning this error, I am beginning to think that there is some bug in Visual Studio for Mac that keeps something in memory, I have dumped the Bin and obj folders and that did not make a difference I have all my packages up to date.
Stack Trace...
System.InvalidCastException: Specified cast is not valid.
at at (wrapper castclass) System.Object:__castclass_with_cache (object,intptr,intptr)
at Xamarin.Forms.Internals.Registrar1[TRegistrable].GetHandler (System.Type type) [0x0001b] in D:\agent_work\2\s\Xamarin.Forms.Core\Registrar.cs:37 at Xamarin.Forms.Internals.Registrar1[TRegistrable].GetHandlerForObject[TOut] (System.Object obj) [0x0002c] in D:\agent_work\2\s\Xamarin.Forms.Core\Registrar.cs:81
at Xamarin.Forms.Platform.iOS.Platform.CreateRenderer (Xamarin.Forms.VisualElement element) [0x00005] in <9a5948fff8254b13a3d593c76c73b9b1>:0
at Xamarin.Forms.Platform.iOS.VisualElementPackager.OnChildAdded (Xamarin.Forms.VisualElement view) [0x0002a] in <9a5948fff8254b13a3d593c76c73b9b1>:0
at Xamarin.Forms.Platform.iOS.VisualElementPackager.Load () [0x0001e] in <9a5948fff8254b13a3d593c76c73b9b1>:0
at Xamarin.Forms.Platform.iOS.VisualElementRenderer1[TElement].SetElement (TElement element) [0x000cc] in <9a5948fff8254b13a3d593c76c73b9b1>:0 at Xamarin.Forms.Platform.iOS.VisualElementRenderer1[TElement].Xamarin.Forms.Platform.iOS.IVisualElementRenderer.SetElement (Xamarin.Forms.VisualElement element) [0x00000] in <9a5948fff8254b13a3d593c76c73b9b1>:0
at Xamarin.Forms.Platform.iOS.Platform.CreateRenderer (Xamarin.Forms.VisualElement element) [0x00014] in <9a5948fff8254b13a3d593c76c73b9b1>:0
at Xamarin.Forms.Platform.iOS.VisualElementPackager.OnChildAdded (Xamarin.Forms.VisualElement view) [0x0002a] in <9a5948fff8254b13a3d593c76c73b9b1>:0
at Xamarin.Forms.Platform.iOS.VisualElementPackager.Load () [0x0001e] in <9a5948fff8254b13a3d593c76c73b9b1>:0
at Xamarin.Forms.Platform.iOS.VisualElementRenderer1[TElement].SetElement (TElement element) [0x000cc] in <9a5948fff8254b13a3d593c76c73b9b1>:0 at Xamarin.Forms.Platform.iOS.VisualElementRenderer1[TElement].Xamarin.Forms.Platform.iOS.IVisualElementRenderer.SetElement (Xamarin.Forms.VisualElement element) [0x00000] in <9a5948fff8254b13a3d593c76c73b9b1>:0
at Xamarin.Forms.Platform.iOS.Platform.CreateRenderer (Xamarin.Forms.VisualElement element) [0x00014] in <9a5948fff8254b13a3d593c76c73b9b1>:0
at Xamarin.Forms.Platform.iOS.VisualElementPackager.OnChildAdded (Xamarin.Forms.VisualElement view) [0x0002a] in <9a5948fff8254b13a3d593c76c73b9b1>:0
at Xamarin.Forms.Platform.iOS.VisualElementPackager.Load () [0x0001e] in <9a5948fff8254b13a3d593c76c73b9b1>:0
at Xamarin.Forms.Platform.iOS.PageRenderer.ViewDidLoad () [0x00086] in <9a5948fff8254b13a3d593c76c73b9b1>:0
at at (wrapper managed-to-native) ObjCRuntime.Messaging:IntPtr_objc_msgSendSuper (intptr,intptr)
at UIKit.UIViewController.get_View () [0x00030] in /Users/builder/data/lanes/5520/51128b8c/source/xamarin-macios/src/build/ios/native/UIKit/UIViewController.g.cs:2983
at Xamarin.Forms.Platform.iOS.PageRenderer.get_NativeView () [0x00008] in <9a5948fff8254b13a3d593c76c73b9b1>:0
at Xamarin.Forms.Platform.iOS.PageRenderer.SetElement (Xamarin.Forms.VisualElement element) [0x0004f] in <9a5948fff8254b13a3d593c76c73b9b1>:0
at Xamarin.Forms.Platform.iOS.Platform.CreateRenderer (Xamarin.Forms.VisualElement element) [0x00014] in <9a5948fff8254b13a3d593c76c73b9b1>:0
at Xamarin.Forms.Platform.iOS.NavigationRenderer.CreateViewControllerForPage (Xamarin.Forms.Page page) [0x00008] in <9a5948fff8254b13a3d593c76c73b9b1>:0
at Xamarin.Forms.Platform.iOS.NavigationRenderer+d__45.MoveNext () [0x00016] in <9a5948fff8254b13a3d593c76c73b9b1>:0
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in /Library/Frameworks/Xamarin.iOS.framework/Versions/11.3.0.47/src/mono/mcs/class/referencesource/mscorlib/system/runtime/exceptionservices/exceptionservicescommon.cs:151
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x00037] in /Library/Frameworks/Xamarin.iOS.framework/Versions/11.3.0.47/src/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:187
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in /Library/Frameworks/Xamarin.iOS.framework/Versions/11.3.0.47/src/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:156
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in /Library/Frameworks/Xamarin.iOS.framework/Versions/11.3.0.47/src/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:128
at System.Runtime.CompilerServices.TaskAwaiter`1[TResult].GetResult () [0x00000] in /Library/Frameworks/Xamarin.iOS.framework/Versions/11.3.0.47/src/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:357
at Xamarin.Forms.Platform.iOS.NavigationRenderer+d.MoveNext () [0x00067] in <9a5948fff8254b13a3d593c76c73b9b1>:0
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in /Library/Frameworks/Xamarin.iOS.framework/Versions/11.3.0.47/src/mono/mcs/class/referencesource/mscorlib/system/runtime/exceptionservices/exceptionservicescommon.cs:151
at System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.b__6_0 (System.Object state) [0x00000] in /Library/Frameworks/Xamarin.iOS.framework/Versions/11.3.0.47/src/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/AsyncMethodBuilder.cs:1018
at UIKit.UIKitSynchronizationContext+c__AnonStorey0.<>m__0 () [0x00000] in /Users/builder/data/lanes/5520/51128b8c/source/xamarin-macios/src/UIKit/UIKitSynchronizationContext.cs:24
at Foundation.NSAsyncActionDispatcher.Apply () [0x00000] in /Users/builder/data/lanes/5520/51128b8c/source/xamarin-macios/src/Foundation/NSAction.cs:163
at at (wrapper managed-to-native) UIKit.UIApplication:UIApplicationMain (int,string[],intptr,intptr)
at UIKit.UIApplication.Main (System.String[] args, System.IntPtr principal, System.IntPtr delegate) [0x00005] in /Users/builder/data/lanes/5520/51128b8c/source/xamarin-macios/src/UIKit/UIApplication.cs:79
at UIKit.UIApplication.Main (System.String[] args, System.String principalClassName, System.String delegateClassName) [0x00038] in /Users/builder/data/lanes/5520/51128b8c/source/xamarin-macios/src/UIKit/UIApplication.cs:63
at EssentialsProMobile.iOS.Application.Main (System.String[] args) [0x00001] in /Users/odisharkins/Projects/EssentialsProMobile/iOS/Main.cs:17
This is the MainPage.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:SignaturePadDemo"
xmlns:signatures="clr-namespace:SignaturePad.Forms;assembly=SignaturePad.Forms"
x:Class="EssentialsProMobile.MainPage"
Title="Draw Signature">
<Grid Padding="20" RowSpacing="20">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<signatures:SignaturePadView
x:Name="signaturePad"
VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand"
Grid.Row="0" />
<Button
HorizontalOptions="FillAndExpand"
Text="Show Image"
Clicked="OnShowImage"
Grid.Row="1" />
</Grid>
MainPage.xaml.cs
using System;
using Xamarin.Forms;
using SignaturePad.Forms;
using PCLStorage;
namespace EssentialsProMobile
{
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
private async void OnShowImage(object sender, EventArgs e)
{
// get the file name
var folder = FileSystem.Current.LocalStorage;
var file = await folder.CreateFileAsync($"signature.jpg", CreationCollisionOption.GenerateUniqueName);
// create some settings to control the output
var settings = new ImageConstructionSettings
{
BackgroundColor = Color.White,
StrokeColor = Color.Black,
};
// write the signature stream to the file stream
using (var stream = await signaturePad.GetImageStreamAsync(SignatureImageFormat.Jpeg, settings))
using (var fileStream = await file.OpenAsync(FileAccess.ReadAndWrite))
{
// copy the bytes
await stream.CopyToAsync(fileStream);
}
// success
await DisplayAlert("Signature Saved", "Signature file saved successfully.\nLoading preview...", "OK");
// show the image preview
var previewPage = new ContentPage
{
Title = "View Signature",
Content = new Image
{
Source = ImageSource.FromFile(file.Path),
Margin = new Thickness(20)
}
};
await Navigation.PushAsync(previewPage);
}
}
}
And the App.xaml.cs
namespace EssentialsProMobile
{
public partial class App : Application
{
readonly Services.IAuthenticationService _AuthenticationService;
static Application app;
static Data.EssentialsProDatabase database;
public static Application CurrentApp
{
get { return app; }
}
public App()
{
InitializeComponent();
app = this;
_AuthenticationService = DependencyService.Get<Services.IAuthenticationService>();
// If the App.IsAuthenticated property is false, modally present the SplashPage.
if (!_AuthenticationService.IsAuthenticated)
{
//Load Login Page
var page = new SplashPage();
//Testing....
//var page = new Services.SignaturePadView();
NavigationPage.SetHasNavigationBar(page, false);
MainPage = new NavigationPage(new MainPage());
}
else
{
GoToRoot();
}

MVVX Failed to initialize ViewModel from MvxDefaultViewModelLocator

I am trying to create a mobile application using MVVX.
get below error when trying to run the Droid application.
MvvmCross.Platform.Exceptions.MvxException: Failed to construct and initialize ViewModel for type ThoughtOfTheDay.ViewModels.LoginViewModel from locator MvxDefaultViewModelLocator - check InnerException for more information
Below is the detail of inner exception.
MvvmCross.Platform.Exceptions.MvxException: Failed to construct and initialize ViewModel for type ThoughtOfTheDay.ViewModels.LoginViewModel from locator MvxDefaultViewModelLocator - check InnerException for more information ---> MvvmCross.Platform.Exceptions.MvxException: Problem creating viewModel of type LoginViewModel ---> MvvmCross.Platform.Exceptions.MvxIoCResolveException: Failed to resolve parameter for parameter messenger of type IMvxMessenger when creating ThoughtOfTheDay.ViewModels.LoginViewModel
at MvvmCross.Platform.IoC.MvxSimpleIoCContainer.GetIoCParameterValues (System.Type type, System.Reflection.ConstructorInfo firstConstructor) [0x00036] in D:\git\MvvmCross\MvvmCross\Platform\Platform\IoC\MvxSimpleIoCContainer.cs:504
at MvvmCross.Platform.IoC.MvxSimpleIoCContainer.IoCConstruct (System.Type type) [0x0002a] in D:\git\MvvmCross\MvvmCross\Platform\Platform\IoC\MvxSimpleIoCContainer.cs:314
at MvvmCross.Platform.Mvx.IocConstruct (System.Type t) [0x00005] in D:\git\MvvmCross\MvvmCross\Platform\Platform\Mvx.cs:170
at MvvmCross.Core.ViewModels.MvxDefaultViewModelLocator.Load (System.Type viewModelType, MvvmCross.Core.ViewModels.IMvxBundle parameterValues, MvvmCross.Core.ViewModels.IMvxBundle savedState) [0x00000] in <69bce0378e8e413982d3b552d7e387a8>:0
--- End of inner exception stack trace ---
at MvvmCross.Core.ViewModels.MvxDefaultViewModelLocator.Load (System.Type viewModelType, MvvmCross.Core.ViewModels.IMvxBundle parameterValues, MvvmCross.Core.ViewModels.IMvxBundle savedState) [0x00027] in <69bce0378e8e413982d3b552d7e387a8>:0
at MvvmCross.Core.ViewModels.MvxViewModelLoader.LoadViewModel (MvvmCross.Core.ViewModels.MvxViewModelRequest request, MvvmCross.Core.ViewModels.IMvxBundle savedState, MvvmCross.Core.ViewModels.IMvxViewModelLocator viewModelLocator) [0x00015] in <69bce0378e8e413982d3b552d7e387a8>:0
--- End of inner exception stack trace ---
at MvvmCross.Core.ViewModels.MvxViewModelLoader.LoadViewModel (MvvmCross.Core.ViewModels.MvxViewModelRequest request, MvvmCross.Core.ViewModels.IMvxBundle savedState, MvvmCross.Core.ViewModels.IMvxViewModelLocator viewModelLocator) [0x00046] in <69bce0378e8e413982d3b552d7e387a8>:0
at MvvmCross.Core.ViewModels.MvxViewModelLoader.LoadViewModel (MvvmCross.Core.ViewModels.MvxViewModelRequest request, MvvmCross.Core.ViewModels.IMvxBundle savedState) [0x00020] in <69bce0378e8e413982d3b552d7e387a8>:0
at MvvmCross.Droid.Views.MvxAndroidViewsContainer.ViewModelFromRequest (MvvmCross.Core.ViewModels.MvxViewModelRequest viewModelRequest, MvvmCross.Core.ViewModels.IMvxBundle savedState) [0x00005] in :0
at MvvmCross.Droid.Views.MvxAndroidViewsContainer.CreateViewModelFromIntent (Android.Content.Intent intent, MvvmCross.Core.ViewModels.IMvxBundle savedState) [0x00027] in :0
at MvvmCross.Droid.Views.MvxAndroidViewsContainer.Load (Android.Content.Intent intent, MvvmCross.Core.ViewModels.IMvxBundle savedState, System.Type viewModelTypeHint) [0x00089] in :0
at MvvmCross.Droid.Views.MvxActivityViewExtensions.LoadViewModel (MvvmCross.Droid.Views.IMvxAndroidView androidView, MvvmCross.Core.ViewModels.IMvxBundle savedState) [0x0006a] in :0
at MvvmCross.Droid.Views.MvxActivityViewExtensions+<>c__DisplayClass1_0.b__1 () [0x0000a] in :0
at MvvmCross.Core.Views.MvxViewExtensionMethods.OnViewCreate (MvvmCross.Core.Views.IMvxView view, System.Func1[TResult] viewModelLoader) [0x00012] in <69bce0378e8e413982d3b552d7e387a8>:0
at MvvmCross.Droid.Views.MvxActivityViewExtensions.OnViewCreate (MvvmCross.Droid.Views.IMvxAndroidView androidView, Android.OS.Bundle bundle) [0x00062] in <f6aebf863dc84be7b380cfec8d459508>:0
at MvvmCross.Droid.Views.MvxActivityAdapter.EventSourceOnCreateCalled (System.Object sender, MvvmCross.Platform.Core.MvxValueEventArgs1[T] eventArgs) [0x0000c] in :0
at (wrapper delegate-invoke) System.EventHandler1[MvvmCross.Platform.Core.MvxValueEventArgs1[Android.OS.Bundle]]:invoke_void_object_TEventArgs (object,MvvmCross.Platform.Core.MvxValueEventArgs1<Android.OS.Bundle>)
at MvvmCross.Platform.Core.MvxDelegateExtensionMethods.Raise[T] (System.EventHandler1[TEventArgs] eventHandler, System.Object sender, T value) [0x00000] in D:\git\MvvmCross\MvvmCross\Platform\Platform\Core\MvxDelegateExtensionMethods.cs:21
at MvvmCross.Platform.Droid.Views.MvxEventSourceActivity.OnCreate (Android.OS.Bundle bundle) [0x00014] in <4230cf00b647458f9b3e211590e6cc9d>:0
at ThoughtOfTheDay.Droid.Views.LoginView.OnCreate (Android.OS.Bundle bundle) [0x00002] in C:\Work\MobileDev\ThoughtOfTheDay\ThoughtOfTheDay\ThoughtOfTheDay.Droid\Views\LoginView.cs:15
I am trying to pass IMvxMessenger to the view model. Inner exception message above shows there is a problem resolving IMvxMessenger. Do I need to include something for it in the app.cs\Initialize() ? Let me know if you need more info. Thanks a lot for your time and help.
public LoginViewModel(IMvxMessenger messenger,
IDialogService dialogService,
IUserService userService)
: base(messenger)
{
_userService = userService;
_dialogService = dialogService;
}
Solution: Installed Nuget package for MvvmCross.Plugin.Messenger in the Android project as well.
Earlier I had it installed only in the PCL project.
Solution: Installed Nuget package for MvvmCross.Plugin.Messenger in the Android project as well. Earlier I had it installed only in the PCL project.
Sounds like you are missing the bootstrap for the plugin.
Make sure a class inside of the Bootstrap folder has been made with the following contents:
using MvvmCross.Platform.Plugins;
namespace your.name.space.Bootstrap
{
public class MessengerPluginBootstrap
: MvxPluginBootstrapAction<MvvmCross.Plugins.Messenger.PluginLoader>
{
}
}
This will register the plugin with the IoC container.
Alternatively you can register it yourself in InitializeLastChance in your Setup.cs file:
Mvx.RegisterSingleton<IMvxMessenger>(() => new MvxMessengerHub());

SignalR Owin Self-Host on Linux/Mono SocketException when clients lose connection

I'm running very simple signalr server self-hosted via Owin on ubuntu server 14.04, mono 3.2.8. (code below).
Connecting/Disconnecting works fine on both a remote windows server and when I deploy the bits to the linux server. But when a client dies unexpectedly instead of telling signalr that he's disconnecting, that's when I get a never-ending SocketException only on the linux server only. The windows server disconnects the client after about 30 seconds or so, but the linux server spews the socketexception (also below) every 10 seconds or so, forever.
How can I make the linux server behave like the windows server when running the same code, disconnect the user after a set timeout and not throw socketexceptions?
Server Code:
using System;
using System.Threading.Tasks;
using Microsoft.AspNet.SignalR;
using Owin;
namespace signalrtestserver
{
class Program
{
static void Main(string[] args)
{
var uri = System.Configuration.ConfigurationManager.AppSettings["startup_uri"] ?? "http://*:7890";
using (Microsoft.Owin.Hosting.WebApp.Start<Startup>(uri))
{
Console.WriteLine(string.Format("Server started on {0}. Press enter to close.", uri));
Console.ReadLine();
}
}
}
class Startup
{
static Hub hub;
public void Configuration(IAppBuilder app)
{
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
var configuration = new HubConfiguration();
configuration.EnableDetailedErrors = true;
app.MapSignalR("/signalr", configuration);
hub = new MyHub();
}
}
public class MyHub : Hub
{
public override Task OnConnected() { Console.WriteLine(Context.ConnectionId + " connected"); return base.OnConnected(); }
public override Task OnDisconnected() { Console.WriteLine(Context.ConnectionId + " disconnected"); return base.OnDisconnected(); }
public override Task OnReconnected() { Console.WriteLine(Context.ConnectionId + " reconnected"); return base.OnReconnected(); }
}
}
Client Code:
using System;
using System.Net;
using Microsoft.AspNet.SignalR.Client;
namespace signalrconnection
{
class Program
{
static void Main(string[] args)
{
var uri = System.Configuration.ConfigurationManager.AppSettings["signalr_uri"] ?? "http://localhost:7890/signalr";
ServicePointManager.DefaultConnectionLimit = 10;
var hubConnection = new HubConnection(uri, false);
hubConnection.StateChanged += stateChange => Console.WriteLine(string.Format("SignalR {0} >> {1} ({2})", stateChange.OldState, stateChange.NewState, hubConnection.Transport == null ? "<<null>>" : hubConnection.Transport.Name));
var hubProxy = hubConnection.CreateHubProxy("MyHub");
hubConnection.Start();
Console.WriteLine("Press enter to die...");
Console.ReadLine();
//hubConnection.Dispose(); //uncomment this to simulate a graceful disconnect which works on both windows and linux
}
}
}
Never-Ending Mono Exception:
{path-to-project}/Microsoft.AspNet.SignalR.Core.dll Error : 0 : SignalR exception thrown by Task: System.AggregateException: One or more errors occured ---> System.IO.IOException: Write failure ---> System.Net.Sockets.SocketException: Connection reset by peer
at System.Net.Sockets.Socket.Send (System.Byte[] buf, Int32 offset, Int32 size, SocketFlags flags) [0x00000] in <filename unknown>:0
at System.Net.Sockets.NetworkStream.Write (System.Byte[] buffer, Int32 offset, Int32 size) [0x00000] in <filename unknown>:0
--- End of inner exception stack trace ---
at System.Net.Sockets.NetworkStream.Write (System.Byte[] buffer, Int32 offset, Int32 size) [0x00000] in <filename unknown>:0
at System.Net.ResponseStream.InternalWrite (System.Byte[] buffer, Int32 offset, Int32 count) [0x00000] in <filename unknown>:0
at System.Net.ResponseStream.Write (System.Byte[] buffer, Int32 offset, Int32 count) [0x00000] in <filename unknown>:0
at Microsoft.Owin.Host.HttpListener.RequestProcessing.ExceptionFilterStream.Write (System.Byte[] buffer, Int32 offset, Int32 count) [0x00000] in <filename unknown>:0
--- End of inner exception stack trace ---
--> (Inner exception 0) System.IO.IOException: Write failure ---> System.Net.Sockets.SocketException: Connection reset by peer
at System.Net.Sockets.Socket.Send (System.Byte[] buf, Int32 offset, Int32 size, SocketFlags flags) [0x00000] in <filename unknown>:0
at System.Net.Sockets.NetworkStream.Write (System.Byte[] buffer, Int32 offset, Int32 size) [0x00000] in <filename unknown>:0
--- End of inner exception stack trace ---
at System.Net.Sockets.NetworkStream.Write (System.Byte[] buffer, Int32 offset, Int32 size) [0x00000] in <filename unknown>:0
at System.Net.ResponseStream.InternalWrite (System.Byte[] buffer, Int32 offset, Int32 count) [0x00000] in <filename unknown>:0
at System.Net.ResponseStream.Write (System.Byte[] buffer, Int32 offset, Int32 count) [0x00000] in <filename unknown>:0
at Microsoft.Owin.Host.HttpListener.RequestProcessing.ExceptionFilterStream.Write (System.Byte[] buffer, Int32 offset, Int32 count) [0x00000] in <filename unknown>:0
Any help would be much appreciated. Thanks in advance!
The problem is this line static Hub hub, and this one hub = new MyHub() in your Startup method.
You do not need to explicitly create instances of the Hub class, neither do you need to keep a reference around. The hub class is instantiated on every request to the server. See
http://www.asp.net/signalr/overview/signalr-20/hubs-api/hubs-api-guide-server#transience the section on Hub object lifetime.
This means that whenever there is a disconnection, Mono in Linux is throwing a different exception than MS.NET in Windows. SignalR was implemented by people which were most likely using MS.NET and therefore SignalR must be expecting certain exception and be religious about this.
The best way to fix this is debug the code stepping into SignalR implementation (when running on Linux with Mono) to see where is the exception being caught, and compare to what happens in SignalR under MS.NET in Windows. Then create a minimal testcase about the difference and submit a bug in http://bugzilla.xamarin.com/, they will probably fix it soon (or you can assign it to me and I'll look at it, because I have interest in running SignalR under mono).
I had the same issue on Raspberry Pi with simple Owin self hosted demo app. Requesting "welcome" page from single browser by holding F5 was enough to kill the host within 15 seconds. I have not done any automated stress testing yet, as my "user acceptance" test was failing right away.
The reliable solution I found is to create custom OwinMiddleware to catch and jam the socket exception:
class CustomExceptionMiddleware : OwinMiddleware
{
public CustomExceptionMiddleware(OwinMiddleware next)
: base(next)
{
}
public override async Task Invoke(IOwinContext context)
{
try
{
await Next.Invoke(context);
}
catch (IOException ex)
{
Console.WriteLine(ex.Message);
}
}
}
The Owin startup will need to be updated to use the middleware:
using Owin;
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.Use<OwnExceptionMiddleware>()
.UseNancy();
}
}
It was inspired by http://dhickey.ie/2014/02/bubbling-exceptions-in-nancy-up-the-owin-pipeline/
Here is my exception for reference:
Unhandled Exception:
System.IO.IOException: Write failure ---> System.Net.Sockets.SocketException: The socket has been shut down
at System.Net.Sockets.Socket.Send (System.Byte[] buf, Int32 offset, Int32 size, SocketFlags flags) [0x00000] in <filename unknown>:0
at System.Net.Sockets.NetworkStream.Write (System.Byte[] buffer, Int32 offset, Int32 size) [0x00000] in <filename unknown>:0
--- End of inner exception stack trace ---
at System.Net.Sockets.NetworkStream.Write (System.Byte[] buffer, Int32 offset, Int32 size) [0x00000] in <filename unknown>:0
at System.Net.ResponseStream.InternalWrite (System.Byte[] buffer, Int32 offset, Int32 count) [0x00000] in <filename unknown>:0
at System.Net.ResponseStream.Close () [0x00000] in <filename unknown>:0
at System.Net.HttpConnection.Close (Boolean force_close) [0x00000] in <filename unknown>:0
at System.Net.HttpListenerResponse.Close (Boolean force) [0x00000] in <filename unknown>:0
at System.Net.HttpListenerResponse.Abort () [0x00000] in <filename unknown>:0
at Microsoft.Owin.Host.HttpListener.RequestProcessing.OwinHttpListenerResponse.End () [0x00000] in <filename unknown>:0
at Microsoft.Owin.Host.HttpListener.RequestProcessing.OwinHttpListenerContext.End () [0x00000] in <filename unknown>:0
at Microsoft.Owin.Host.HttpListener.RequestProcessing.OwinHttpListenerContext.End (System.Exception ex) [0x00000] in <filename unknown>:0
at Microsoft.Owin.Host.HttpListener.OwinHttpListener+<ProcessRequestAsync>d__5.MoveNext () [0x00000] in <filename unknown>:0
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x00000] in <filename unknown>:0
at System.Runtime.CompilerServices.TaskAwaiter.GetResult () [0x00000] in <filename unknown>:0
at Microsoft.Owin.Host.HttpListener.OwinHttpListener+<ProcessRequestsAsync>d__0.MoveNext () [0x00000] in <filename unknown>:0
Consider being specific in what exceptions you intercept:
public override async Task Invoke(IOwinContext context)
{
try
{
await Next.Invoke(context);
}
catch (IOException ex)
{
if (ex.HResult == -2146233087) // The socket has been shut down
{
NLog.LogManager.GetLogger("OwinExceptionHandler").Trace(ex);
}
else
{
throw;
}
}
}
I think I have the same problem. I described it:
https://katanaproject.codeplex.com/workitem/438
https://bugzilla.xamarin.com/show_bug.cgi?id=33254#c4
I've found solution for my situation. I set HttpListener.IgnoreWriteExceptions property to 'true' in OWIN configuration method and then register middlewares. For example:
internal class Startup
{
public void Configuration(IAppBuilder app)
{
object httpListener;
if (app.Properties.TryGetValue(typeof(HttpListener).FullName, out httpListener)
&& httpListener is HttpListener)
{
// HttpListener should not return exceptions that occur
// when sending the response to the client
((HttpListener)httpListener).IgnoreWriteExceptions = true;
}
app.Use<TestOwinMiddleware>();
}
}
I hope this may help you.

How can I correctly use Mono.Unix.UnixPipes.CreatePipes?

I want to communicate with a subprocess using a pipe other than stdin, stdout and stderr. I'm trying to use Mono.Unix.UnixPipes.CreatePipes for this. However, I can't find any examples and my best guess of how to use it isn't working. It seems that the child process I create with Process.Start cannot write to the inherited file handle. I am wondering if perhaps it has not actually inherited the handle at all. Here's my (reduced) code:
using System;
using System.Diagnostics;
using System.IO;
using System.IO.Pipes;
using System.Threading;
using System.Collections.Generic;
using Mono.Unix;
class Program
{
static void Main(string[] args)
{
if (args.Length==0)
{
InvokeChildProcess(args);
}
else
{
RunAsChildProcess(args);
}
}
static int InvokeChildProcess(string[] aArgs)
{
var childToParentPipe = Mono.Unix.UnixPipes.CreatePipes();
var childToParentStream = childToParentPipe.Reading;
string childHandle = childToParentPipe.Writing.Handle.ToString();
var startInfo = new ProcessStartInfo(
System.Reflection.Assembly.GetExecutingAssembly().Location,
childHandle)
{
UseShellExecute = false,
};
Process childProcess = Process.Start(startInfo);
childToParentPipe.Writing.Close();
using (var reader = new StreamReader(childToParentStream))
{
Console.WriteLine("[PARENT] Waiting for child output...");
string output = reader.ReadToEnd();
Console.Write("[PARENT] Received output ({0} chars): ", output.Length);
Console.WriteLine(output);
Console.WriteLine("[PARENT] Waiting for child to exit...");
childProcess.WaitForExit();
Console.WriteLine("[PARENT] Saw child exit with code {0}.", childProcess.ExitCode);
return childProcess.ExitCode;
}
}
static void RunAsChildProcess(string[] args)
{
int handle=int.Parse(args[0]);
Console.WriteLine("[CHILD] Writing to file handle {0}.", handle);
var pipeToParent = new Mono.Unix.UnixStream(handle);
Thread.Sleep(2000);
using (var writer = new StreamWriter(pipeToParent))
{
writer.WriteLine("Message from child.");
writer.Flush();
Environment.Exit(123);
}
}
}
Here's the output when it runs:
weeble#weeble-vm-oneiric32:~/dev$ mono MinimalPipeTest.exe
[PARENT] Waiting for child output...
[PARENT] Received output (0 chars):
[PARENT] Waiting for child to exit...
[CHILD] Writing to file handle 4.
Unhandled Exception: System.ArgumentException: Can not write to stream
at System.IO.StreamWriter..ctor (System.IO.Stream stream, System.Text.Encoding encoding, Int32 bufferSize) [0x00000] in <filename unknown>:0
at System.IO.StreamWriter..ctor (System.IO.Stream stream) [0x00000] in <filename unknown>:0
at (wrapper remoting-invoke-with-check) System.IO.StreamWriter:.ctor (System.IO.Stream)
at Program.RunAsChildProcess (System.String[] args) [0x00000] in <filename unknown>:0
at Program.Main (System.String[] args) [0x00000] in <filename unknown>:0
[ERROR] FATAL UNHANDLED EXCEPTION: System.ArgumentException: Can not write to stream
at System.IO.StreamWriter..ctor (System.IO.Stream stream, System.Text.Encoding encoding, Int32 bufferSize) [0x00000] in <filename unknown>:0
at System.IO.StreamWriter..ctor (System.IO.Stream stream) [0x00000] in <filename unknown>:0
at (wrapper remoting-invoke-with-check) System.IO.StreamWriter:.ctor (System.IO.Stream)
at Program.RunAsChildProcess (System.String[] args) [0x00000] in <filename unknown>:0
at Program.Main (System.String[] args) [0x00000] in <filename unknown>:0
[PARENT] Saw child exit with code 1.
weeble#weeble-vm-oneiric32:~/dev$
This example was compiled and run with Mono 2.10 as distributed in Ubuntu Oneiric.
What am I doing wrong? How can I ensure that the child process will be able to write to the pipe?
EDIT - It looks like Process.Start does indeed close all file descriptors in the child process except for 0, 1 and 2. See here in CreateProcess:
https://github.com/mono/mono/blob/master/mono/io-layer/processes.c#L988
for (i = getdtablesize () - 1; i > 2; i--) {
close (i);
}
I guess that means I can't use UnixPipes and Process.Start. Is there another way?
As I understand it, you cannot use a pipe bi-directionally here. In other words, you cannot read and write with the same pipe. You need two.

Categories

Resources