I have this code that throws "Sequence contains no elements" exception:
autoRefreshWorker = new AutoRefreshWorker(AutoRefreshData, () => {
var items = ((DocumentListDataSource)TableView.Source).Items;
return items.Any()
? items.Aggregate((i1, i2) => i1.Id > i2.Id ? i1 : i2)
: items.FirstOrDefault();
},
AutoRefreshIntervalMs);
I was not able to reproduce the error myself. But on AppCenter I can see that lots of users experience this error very often and the stack trace shows the following:
Enumerable.Aggregate[TSource] (System.Collections.Generic.IEnumerable`1[T] source, System.Func`3[T1,T2,TResult] func)
DocumentsListViewController.<ViewDidAppear>b__38_0 ()
DocumentsListViewController+AutoRefreshWorker.<Start>b__6_1 ()
AsyncHelpers+<>c__DisplayClass0_0.<InvokeOnMainThreadAsync>b__0 ()
AsyncMethodBuilderCore+<>c.<ThrowAsync>b__7_0 (System.Object state)
NSAsyncSynchronizationContextDispatcher.Apply ()
(wrapper managed-to-native) UIKit.UIApplication.UIApplicationMain(int,string[],intptr,intptr)
UIApplication.Main (System.String[] args, System.String principalClassName, System.String delegateClassName)
Application.Main (System.String[] args)
I know that calling Aggregate() on empty set throws that exception. But in my code I check if items contains any element before calling Aggregate. So it is not clear to me what can cause this exception in my code. Any ideas?
Related
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 .
So, I go to run the build in unity and I get this!
InvalidOperationException: Operation is not valid due to the current
state of the object System.Collections.Stack.Peek () (at
/Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Collections/Stack.cs:321)
UnityEngine.GUILayoutUtility.EndLayoutGroup () (at
C:/buildslave/unity/build/Runtime/IMGUI/Managed/GUILayoutUtility.cs:280)
UnityEngine.GUILayout.EndScrollView (Boolean handleScrollWheel) (at
C:/buildslave/unity/build/Runtime/IMGUI/Managed/GUILayout.cs:427)
UnityEditor.EditorGUILayout.EndScrollView () (at
C:/buildslave/unity/build/Editor/Mono/EditorGUI.cs:7090)
UnityEditor.ListViewShared+ListViewElementsEnumerator.MoveNext () (at
C:/buildslave/unity/build/Editor/Mono/GUI/ListViewShared.cs:654)
UnityEditor.ConsoleWindow.OnGUI () (at
C:/buildslave/unity/build/Editor/Mono/ConsoleWindow.cs:409)
System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags
invokeAttr, System.Reflection.Binder binder, System.Object[]
I've never seen such an exception before and so I figured I'd ask about it and then investigate.
Do not invoke Peek or Pop on an empty Stack<T>.
Stack<GameObject> stack = new Stack<GameObject> ();
if (stack.Count > 0) {
var top = stack.Peek ();
}
In Xamarin.Forms:
I have a ListView which is being populated with certain objects. In each of the rows of the ListView I also have a Switch, which the user can use to select or deselect that item.
My problem is that I can't figure out how to pass the specific item in the ListView to the toggled event of the Switch, so that the users' preferences can then be saved.
i.e. How does each Switch know which object it shares a row with in the ListView? (In the code below, the objects I am trying to pass are the Survey objects.)
What I found so far:
I have found this question which is exactly what I am after, but I can't quite understand the answer:
https://forums.xamarin.com/discussion/64197/switch-inside-listview-get-listview-item-on-toggle
Following the post above, I have tried the following:
Extended the Switch class:
public class ListSwitch : Switch
{
public static BindableProperty SurveyItemProperty = BindableProperty.Create(
propertyName: "SurveyItem",
returnType: typeof(Survey),
declaringType: typeof(ListSwitch),
defaultValue: null);
public Survey SurveyItem
{
get { return (Survey)GetValue(SurveyItemProperty); }
set { SetValue(SurveyItemProperty, value); }
}
}
Added this to my View codebehind:
mySwitch.SetBinding(ListSwitch.SurveyItemProperty, "SurveyItem");
mySwitch.Toggled += (sender, e) =>
{
var item = (Survey)((ListSwitch)sender).SurveyItem;
_vm.WatchSurveyCommand.Execute(item);
};
When I try this I get the following error:
System.NullReferenceException: Object reference not set to an instance of an object
at ConsensusCloud.MainViewModel+<ExecuteWatchSurveyCommand>c__async1.MoveNext () [0x00033] in /Users/Lambros/Dropbox/XamarinProjects/ConsensusCloud/ConsensusCloud/ViewModels/MainViewModel.cs:65
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in /Users/builder/data/lanes/3426/6c3fee4d/source/xamarin-macios/_ios-build/Library/Frameworks/Xamarin.iOS.framework/Versions/git/src/mono/mcs/class/referencesource/mscorlib/system/runtime/exceptionservices/exceptionservicescommon.cs:143
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x00047] in /Users/builder/data/lanes/3426/6c3fee4d/source/xamarin-macios/_ios-build/Library/Frameworks/Xamarin.iOS.framework/Versions/git/src/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:187
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x0002e] in /Users/builder/data/lanes/3426/6c3fee4d/source/xamarin-macios/_ios-build/Library/Frameworks/Xamarin.iOS.framework/Versions/git/src/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:156
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x0000b] in /Users/builder/data/lanes/3426/6c3fee4d/source/xamarin-macios/_ios-build/Library/Frameworks/Xamarin.iOS.framework/Versions/git/src/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:128
at System.Runtime.CompilerServices.TaskAwaiter.GetResult () [0x00000] in /Users/builder/data/lanes/3426/6c3fee4d/source/xamarin-macios/_ios-build/Library/Frameworks/Xamarin.iOS.framework/Versions/git/src/mono/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:113
at ConsensusCloud.MainViewModel+<>c__async6.MoveNext () [0x00021] in /Users/Lambros/Dropbox/XamarinProjects/ConsensusCloud/ConsensusCloud/ViewModels/MainViewModel.cs:57
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/3426/6c3fee4d/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/3426/6c3fee4d/source/xamarin-macios/src/UIKit/UIApplication.cs:63
at ConsensusCloud.iOS.Application.Main (System.String[] args) [0x00008] in /Users/Lambros/Dropbox/XamarinProjects/ConsensusCloud/iOS/Main.cs:17
What is "SurveyItem"? It would have to be a public property on the individual items that are contained in your list's ItemsSource. If you want to access the current item, just bind to ".", which is the current item.
In ListView, the binding context for the template that is used for the items, is the currently processed item. See the documentation for more details on this topic.
I'm running Arch Linux with the following version of mcs:
>mcs --version
Mono C# compiler version 4.0.4.0
And the following version of dbus-sharp
>pacman -Ss dbus-sharp
extra/dbus-sharp 0.8.1-1 [installed] C# implementation of D-Bus
extra/dbus-sharp-glib 0.6.0-1 [installed] C# GLib implementation of D-Bus
This is my test program, based on the example code found here: https://gist.github.com/Ummon/4317268
I'm just trying to access the settings of the currently active connection, which should be returned as a 'Dict of {String, Dict of {String, Variant}}' as I've checked in the d-feet tool for the org.freedesktop.NetworkManager.Settings.Connection interface
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using DBus;
namespace NetworkManagerDictTest {
public class MyTest {
[Interface("org.freedesktop.NetworkManager.Settings.Connection")]
public interface IConnection {
IDictionary<string, IDictionary<string, object>> GetSettings();
}
readonly static string BUS_NAME = "org.freedesktop.NetworkManager";
public static void Main(string[] argv) {
org.freedesktop.DBus.Properties NetworkManagerProps = Bus.System.GetObject<org.freedesktop.DBus.Properties>(BUS_NAME, new ObjectPath("/org/freedesktop/NetworkManager"));
ObjectPath[] activeConnections = NetworkManagerProps.Get(BUS_NAME, "ActiveConnections") as ObjectPath[];
if (activeConnections.Length > 0) {
org.freedesktop.DBus.Properties ActiveConnectionProperties = Bus.System.GetObject<org.freedesktop.DBus.Properties>(BUS_NAME, activeConnections[0]);
ObjectPath ActiveConnectionPath = ActiveConnectionProperties.Get("org.freedesktop.NetworkManager.Connection.Active", "Connection") as ObjectPath;
Console.WriteLine("Using connection path: " + ActiveConnectionPath);
IConnection connection = Bus.System.GetObject<IConnection>(BUS_NAME, ActiveConnectionPath);
Console.WriteLine("Connection Object ok");
IDictionary<string, IDictionary<string, object>> settings = connection.GetSettings();
Console.WriteLine(settings);
}
}
}
}
Compilation went without errors nor warnings:
mcs Test.cs -r:/usr/lib/mono/dbus-sharp-2.0/dbus-sharp.dll -r:/usr/lib/mono/dbus-sharp-glib-2.0/dbus-sharp-glib.dll
However my program crashes during execution with the following output:
>mono Test.exe
Using connection path: /org/freedesktop/NetworkManager/Settings/0
Connection Object ok
Unhandled Exception:
DBus.Protocol.MessageReader+PaddingException: Read non-zero byte at position 28 while expecting padding. Value given: 200
at DBus.Protocol.MessageReader.ReadPad (Int32 alignment) [0x00000] in <filename unknown>:0
at DBus.Protocol.MessageReader.ReadStruct (System.Type type) [0x00000] in <filename unknown>:0
at DBus.Protocol.MessageReader.ReadValue (System.Type type) [0x00000] in <filename unknown>:0
at DBus.Protocol.MessageReader.ReadDictionary[String,IDictionary`2] () [0x00000] in <filename unknown>:0
at NetworkManagerDictTest.MyTest+IConnectionProxy.GetSettings () [0x00000] in <filename unknown>:0
at NetworkManagerDictTest.MyTest.Main (System.String[] argv) [0x00000] in <filename unknown>:0
[ERROR] FATAL UNHANDLED EXCEPTION: DBus.Protocol.MessageReader+PaddingException: Read non-zero byte at position 28 while expecting padding. Value given: 200
at DBus.Protocol.MessageReader.ReadPad (Int32 alignment) [0x00000] in <filename unknown>:0
at DBus.Protocol.MessageReader.ReadStruct (System.Type type) [0x00000] in <filename unknown>:0
at DBus.Protocol.MessageReader.ReadValue (System.Type type) [0x00000] in <filename unknown>:0
at DBus.Protocol.MessageReader.ReadDictionary[String,IDictionary`2] () [0x00000] in <filename unknown>:0
at NetworkManagerDictTest.MyTest+IConnectionProxy.GetSettings () [0x00000] in <filename unknown>:0
at NetworkManagerDictTest.MyTest.Main (System.String[] argv) [0x00000] in <filename unknown>:0
What can I do to work around this problem? Am I making a mistake when working with the DBus? It seems that all the method calls up to GetSettings went without issues. I've also encountered a similar problem while trying to fix a bug in another project where dbus-sharp would throw an exception when calling GetSettings. Could this be an issue of dbus-sharp instead?
Taking a look at the source code it seems that dbus-sharp infers the return type directly from the signature of the declared method. Unfortunately it doesn't check if I'm using a parent class or interface of Dictionary, eventually it tries to read a DBus struct because of a fallback case which causes the exception as DBus structs are 8 byte padded while dicts use 4 bytes
Replacing all the IDictionary types with Dictionary worked fine and solved my problem.
I have a storyboard. Because I load a view in code (depending on conditions) I haven't used the segue anymore. Now I want to load another view but I'm getting the following error:
System.Reflection.TargetInvocationException was thrown
Exception has been thrown by the target of an invocation.
ListButton.TouchUpInside += (object sender, EventArgs e) => {
MyListController myListController = this.Storyboard.InstantiateViewController ("MyListController") as MyListController;
myListController.EdgesForExtendedLayout = UIRectEdge.None;
if (myListController != null) {
this.NavigationController.PushViewController (myListController, true);
}
};
When the button (ListButton) is pressed the view should be loaded onto the navigation stack. The error occurs with InstantiateViewController.
How can I solve that?
Edit:
I went into MyListController and if I comment the following out the view gets loaded:
public MyListController (IntPtr handle) : base (handle)
{
TableView.RegisterClassForCellReuse (typeof(UITableViewCell), listCellId);
TableView.Source = new MyListDataSource (this);
MyList = new List<string> ();
}
Log:
System.Reflection.TargetInvocationException: Exception has been thrown
by the target of an invocation. ---> System.Exception: Object
reference not set to an instance of an object at
TestApp.MyListController.ViewDidLoad () [0x0004c] in
/Users/xxx/Projects/TestApp/TestApp/TestApp/MyListController.cs:78
at at (wrapper managed-to-native)
MonoTouch.ObjCRuntime.Messaging:IntPtr_objc_msgSendSuper
(intptr,intptr) at
MonoTouch.UIKit.UITableViewController.get_TableView () [0x00000] in
:0 at TestApp.MyListController..ctor (IntPtr
handle) [0x00009] in
/Users/xxx/Projects/TestApp/TestApp/TestApp/MyListController.cs:17
at at (wrapper managed-to-native)
System.Reflection.MonoCMethod:InternalInvoke
(System.Reflection.MonoCMethod,object,object[],System.Exception&) at
System.Reflection.MonoCMethod.InternalInvoke (System.Object obj,
System.Object[] parameters) [0x00002] in
/Developer/MonoTouch/Source/mono/mcs/class/corlib/System.Reflection/MonoMethod.cs:537
--- End of inner exception stack trace --- at System.Reflection.MonoCMethod.InternalInvoke (System.Object obj,
System.Object[] parameters) [0x00016] in
/Developer/MonoTouch/Source/mono/mcs/class/corlib/System.Reflection/MonoMethod.cs:543
at System.Reflection.MonoCMethod.DoInvoke (System.Object obj,
BindingFlags invokeAttr, System.Reflection.Binder binder,
System.Object[] parameters, System.Globalization.CultureInfo culture)
[0x00095] in
/Developer/MonoTouch/Source/mono/mcs/class/corlib/System.Reflection/MonoMethod.cs:528
at System.Reflection.MonoCMethod.Invoke (BindingFlags invokeAttr,
System.Reflection.Binder binder, System.Object[] parameters,
System.Globalization.CultureInfo culture) [0x00000] in
/Developer/MonoTouch/Source/mono/mcs/class/corlib/System.Reflection/MonoMethod.cs:556
at System.Reflection.ConstructorInfo.Invoke (System.Object[]
parameters) [0x00000] in
/Developer/MonoTouch/Source/mono/mcs/class/corlib/System.Reflection/ConstructorInfo.cs:62
at MonoTouch.ObjCRuntime.Runtime.ConstructNSObject[NSObject] (IntPtr
ptr, System.Type type, MissingCtorResolution missingCtorResolution)
[0x00000] in :0 at
MonoTouch.ObjCRuntime.Runtime.ConstructNSObject (IntPtr ptr, IntPtr
klass, MissingCtorResolution missingCtorResolution) [0x00000] in
:0 at MonoTouch.ObjCRuntime.Runtime.GetNSObject
(IntPtr ptr, MissingCtorResolution missingCtorResolution) [0x00000] in
:0 at MonoTouch.ObjCRuntime.Runtime.GetNSObject
(IntPtr ptr) [0x00000] in :0 at
MonoTouch.UIKit.UIStoryboard.InstantiateViewController (System.String
identifier) [0x00000] in :0 at
TestApp.StartScreenViewController.m__1 (System.Object
sender, System.EventArgs e) [0x0000c] in
/Users/xxx/Projects/TestApp/TestApp/TestApp/StartScreenViewController.cs:57
at MonoTouch.UIKit.UIControlEventProxy.Activated () [0x00000] in
:0 at at (wrapper managed-to-native)
MonoTouch.UIKit.UIApplication:UIApplicationMain
(int,string[],intptr,intptr) at MonoTouch.UIKit.UIApplication.Main
(System.String[] args, System.String principalClassName, System.String
delegateClassName) [0x00000] in :0 at
TestApp.Application.Main (System.String[] args) [0x00008] in
/Users/xxx/Projects/TestApp/TestApp/TestApp/Main.cs:17
Try:
Hmm, now I added a new UITableViewController to the storyboard, changed some classes to public, changed variable names to starting with lower case. Also the old UITableviewController had a problem with an added SearchController. Now I made everything new and the problem only relied in the viewDidLoad but that was not the original problem. It was one of these steps (perhaps the SearchController problem).
Problematic Code:
this.NavigationController.ToolbarHidden = false;
It seems that he can't find the NavigationController ... How do I addd the navigation controller to the new created view?