Xamarin.forms ios MonoTouchException on Navigation.RemovePage - xamarin

In my xamarin.forms ios application I have 4 ContentPages and 1 Popup(Rg.Plugin)
My Navigation is like this
Page 1--> Page 2 --> Page 3 --> Page 4 --> Popup
I want to navigate to Page 1 from a button click in Popup by removing the pages(2,3,4 and Popup).
I done it like this.
private void OK_Clicked(object sender, EventArgs e)
{
try
{
var countPagesToRemove = 3;
var mainPage = (Application.Current.MainPage as NavigationPage);
for (var i = 1; i < countPagesToRemove; i++)
{
mainPage.Navigation.RemovePage(mainPage.Navigation.NavigationStack[mainPage.Navigation.NavigationStack.Count - 2]);
}
Navigation.PopAsync();
Task.Delay(5);
PopupNavigation.Instance.PopAsync();
}
catch (Exception ex)
{
DisplayAlert("Result", ex.Message, "ok");
}
}
This works perfectly on Android.In ios it throws me this exception.
Foundation.MonoTouchException
Message=Objective-C exception thrown. Name: CALayerInvalidGeometry Reason: CALayer bounds contains NaN: [0 0; 0 nan]
Native stack trace:
Source=Xamarin.iOS
StackTrace:
at ObjCRuntime.Runtime.ThrowNSException (System.IntPtr ns_exception) [0x00000] in /Library/Frameworks/Xamarin.iOS.framework/Versions/13.14.1.39/src/Xamarin.iOS/ObjCRuntime/Runtime.cs:406
at ObjCRuntime.Runtime.throw_ns_exception (System.IntPtr exc) [0x00000] in /Users/builder/jenkins/workspace/xamarin-macios/xamarin-macios/runtime/Delegates.generated.cs:128
at (wrapper native-to-managed) ObjCRuntime.Runtime.throw_ns_exception(intptr)
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 /Library/Frameworks/Xamarin.iOS.framework/Versions/13.14.1.39/src/Xamarin.iOS/UIKit/UIApplication.cs:86
at UIKit.UIApplication.Main (System.String[] args, System.String principalClassName, System.String delegateClassName) [0x0000e] in /Library/Frameworks/Xamarin.iOS.framework/Versions/13.14.1.39/src/Xamarin.iOS/UIKit/UIApplication.cs:65
I have no idea what does this mean. I have searched and many people got this issues in several situations.But I didn't something like my scenerio.How to solve this?Any help is appreciated.

Related

System.InvalidOperationException: Page must not already have a parent in Xamarin Forms

In Appcenter this exception is happend. i am not able to reproduce this crash.
please help me
App Center Log:
NavigationProxy.PushModalAsync (Xamarin.Forms.Page modal, System.Boolean animated)
ShellSection.GoToAsync (Xamarin.Forms.NavigationRequest request, System.Collections.Generic.IDictionary`2[TKey,TValue] queryData, System.Nullable`1[T] animate)
Shell.GoToAsync (Xamarin.Forms.ShellNavigationState state, System.Nullable`1[T] animate, System.Boolean enableRelativeShellRoutes)
AtCustomerScanPage.CheckForCompletion (System.String containerId)
AsyncMethodBuilderCore+<>c.<ThrowAsync>b__7_0 (System.Object state)
SyncContext+<>c__DisplayClass2_0.<Post>b__0 ()
Thread+RunnableImplementor.Run ()
IRunnableInvoker.n_Run (System.IntPtr jnienv, System.IntPtr native__this)
(wrapper dynamic-method) Android.Runtime.DynamicMethodNameCounter.60(intptr,intptr)
Existing code:
public async void CheckForCompletion(string containerId)
{
if (ViewModel.CanContinue)
{
await Shell.Current.GoToAsync(nameof(AtCustomerPage));
return;
}
}

ImageRender exception on BindingContext when updating a high rate

I am getting the following exception when drawing an image in iOS UI at a very high rate. I have ensure that I am updating the image source from the main thread. We have BLE devices broadcasting signal strength at a 750ms interval and I have ~ 50 around me. So as you could imagine, I am updating that image object often and quickly. It works for a bit, then crashes with this exception.
Here is the exception on crash:
at Xamarin.Forms.BindableObject.SetValueCore (Xamarin.Forms.BindableProperty property, System.Object value, Xamarin.Forms.Internals.SetValueFlags attributes, Xamarin.Forms.BindableObject+SetValuePrivateFlags privateAttributes) [0x00199] in D:\a\1\s\Xamarin.Forms.Core\BindableObject.cs:454
at Xamarin.Forms.BindableObject.SetValue (Xamarin.Forms.BindableProperty property, System.Object value, System.Boolean fromStyle, System.Boolean checkAccess) [0x0004d] in D:\a\1\s\Xamarin.Forms.Core\BindableObject.cs:374
at Xamarin.Forms.BindableObject.SetValue (Xamarin.Forms.BindablePropertyKey propertyKey, System.Object value) [0x0000e] in D:\a\1\s\Xamarin.Forms.Core\BindableObject.cs:356
at Xamarin.Forms.Image.SetIsLoading (System.Boolean isLoading) [0x00000] in D:\a\1\s\Xamarin.Forms.Core\Image.cs:81
at Xamarin.Forms.Platform.iOS.ImageRenderer.TrySetImage (Xamarin.Forms.Image previous) [0x000a4] in D:\a\1\s\Xamarin.Forms.Platform.iOS\Renderers\ImageRenderer.cs:104
at Xamarin.Forms.Platform.iOS.ImageRenderer.OnElementPropertyChanged (System.Object sender, System.ComponentModel.PropertyChangedEventArgs e) [0x00055] in D:\a\1\s\Xamarin.Forms.Platform.iOS\Renderers\ImageRenderer.cs:85
at System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.b__7_0 (System.Object state) [0x00000] in /Library/Frameworks/Xamarin.iOS.framework/Versions/Current/src/Xamarin.iOS/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/AsyncMethodBuilder.cs:1021
at Foundation.NSAsyncSynchronizationContextDispatcher.Apply () [0x00000] in /Users/builder/azdo/_work/1/s/xamarin-macios/src/Foundation/NSAction.cs:178
at (wrapper managed-to-native) UIKit.UIApplication.UIApplicationMain(int,string[],intptr,intptr)
at UIKit.UIApplication.Main (System.String[] args, System.String principalClassName, System.String delegateClassName) [0x00013] in /Users/builder/azdo/_work/1/s/xamarin-macios/src/UIKit/UIApplication.cs:73
Here is the code that updates the value, its nothing crazy... just an update to the set. I put a breakpoint in the IsMainTread just to make sure its not that, it never hits that.
Looking into the Xamarin Forms code based on the call stack, but best guess is that the BindingContext is becoming null somehow. Is there a way to make this safe or not update if it is?
Any reason I shouldn't be able to update an image at this rate?
private int signalStrength;
public int SignalStrength
{
get
{
return signalStrength;
}
set
{
if (value != signalStrength)
{
if (!MainThread.IsMainThread)
{
Console.WriteLine("not here");
}
signalStrength = value;
if (Data.IsDownload)
{
SignalStrengthImage = "App.Resources.Images.TTSVGIcons.TTsignal_white_" +signalStrength+".png";
}
else
{
SignalStrengthImage = "App.Resources.Images.TTSVGIcons.TTsignal_" + signalStrength + ".png";
}
}
}
}

System.ArgumentException: Couldn't bind to method 'GetGetDefaultCipherSuitesHandler'

I am testing an app and seeing crashes on certain Android devices. The error we are seeing in the device logs (and Crashlytics):
Fatal Exception: android.runtime.JavaProxyThrowable: System.ArgumentException: Couldn't bind to method 'GetGetDefaultCipherSuitesHandler'.
at System.Delegate.GetCandidateMethod (System.Type type, System.Type target, System.String method, System.Reflection.BindingFlags bflags, System.Boolean ignoreCase, System.Boolean throwOnBindFailure) [0x000f9] in <e5404a7cbaab472a85c87c8c593feada>:0
at System.Delegate.CreateDelegate (System.Type type, System.Type target, System.String method, System.Boolean ignoreCase, System.Boolean throwOnBindFailure) [0x00014] in <e5404a7cbaab472a85c87c8c593feada>:0
at System.Delegate.CreateDelegate (System.Type type, System.Type target, System.String method) [0x00000] in <e5404a7cbaab472a85c87c8c593feada>:0
at Android.Runtime.AndroidTypeManager.RegisterNativeMembers (Java.Interop.JniType jniType, System.Type type, System.String methods) [0x00123] in <b9d3dca3be2f48d1874313a7a497190a>:0
at Android.Runtime.JNIEnv.RegisterJniNatives (System.IntPtr typeName_ptr, System.Int32 typeName_len, System.IntPtr jniClass, System.IntPtr methods_ptr, System.Int32 methods_len) [0x00115] in <b9d3dca3be2f48d1874313a7a497190a>:0
at (wrapper managed-to-native) Java.Interop.NativeMethods.java_interop_jnienv_alloc_object(intptr,intptr&,intptr)
at Java.Interop.JniEnvironment+Object.AllocObject (Java.Interop.JniObjectReference type) [0x00027] in <55c8950cd1f2461e9c76bad39e8fc8a4>:0
at Java.Interop.JniType.AllocObject () [0x0000c] in <55c8950cd1f2461e9c76bad39e8fc8a4>:0
at Java.Interop.JniPeerMembers+JniInstanceMethods.StartCreateInstance (System.String constructorSignature, System.Type declaringType, Java.Interop.JniArgumentValue* parameters) [0x00044] in <55c8950cd1f2461e9c76bad39e8fc8a4>:0
at Javax.Net.Ssl.SSLSocketFactory..ctor () [0x00034] in <b9d3dca3be2f48d1874313a7a497190a>:0
at Xamarin.Android.Net.OldAndroidSSLSocketFactory..ctor () [0x00010] in <b9d3dca3be2f48d1874313a7a497190a>:0
at Xamarin.Android.Net.AndroidClientHandler.SetupSSL (Javax.Net.Ssl.HttpsURLConnection httpsConnection) [0x00027] in <b9d3dca3be2f48d1874313a7a497190a>:0
at Xamarin.Android.Net.AndroidClientHandler.SetupRequestInternal (System.Net.Http.HttpRequestMessage request, Java.Net.URLConnection conn) [0x0007b] in <b9d3dca3be2f48d1874313a7a497190a>:0
at Xamarin.Android.Net.AndroidClientHandler.SendAsync (System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) [0x00236] in <b9d3dca3be2f48d1874313a7a497190a>:0
at System.Net.Http.HttpClient.SendAsyncWorker (System.Net.Http.HttpRequestMessage request, System.Net.Http.HttpCompletionOption completionOption, System.Threading.CancellationToken cancellationToken) [0x000ca] in <0029d260a26b48288c90ea4fe946b24c>:0
at MyObfuscatedAppName.Services.CharacterEmbeddedResourceDriver.<LoadCharacters>b__1_0 (System.IObserver`1[T] observer) [0x000ca] in <446b676d44a2438aa46540b6f67c24f8>:0
at System.Reactive.PlatformServices.ExceptionServicesImpl.Rethrow (System.Exception exception) [0x00006] in <9ce90c81f389405fa2d38b0e75e8871b>:0
at System.Reactive.ExceptionHelpers.Throw (System.Exception exception) [0x0000a] in <99f8205c51c44bb480747b577b8001ff>:0
at System.Reactive.Stubs+<>c.<.cctor>b__2_1 (System.Exception ex) [0x00000] in <99f8205c51c44bb480747b577b8001ff>:0
at System.Reactive.AnonymousSafeObserver`1[T].OnError (System.Exception error) [0x0000e] in <99f8205c51c44bb480747b577b8001ff>:0
at System.Reactive.Concurrency.ObserveOn`1+ObserveOnSink[TSource].OnErrorPosted (System.Object error) [0x00000] in <99f8205c51c44bb480747b577b8001ff>:0
at Android.App.SyncContext+<>c__DisplayClass2_0.<Post>b__0 () [0x00000] in <b9d3dca3be2f48d1874313a7a497190a>:0
at Java.Lang.Thread+RunnableImplementor.Run () [0x00008] in <b9d3dca3be2f48d1874313a7a497190a>:0
at Java.Lang.IRunnableInvoker.n_Run (System.IntPtr jnienv, System.IntPtr native__this) [0x00009] in <b9d3dca3be2f48d1874313a7a497190a>:0
at (wrapper dynamic-method) Android.Runtime.DynamicMethodNameCounter.31(intptr,intptr)
at mono.java.lang.RunnableImplementor.n_run(RunnableImplementor.java)
at mono.java.lang.RunnableImplementor.run(RunnableImplementor.java:30)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5479)
at java.lang.reflect.Method.invokeNative(Method.java)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(NativeStart.java)
It would seem that the part of this stack trace that relates to our code:
at System.Net.Http.HttpClient.SendAsyncWorker (System.Net.Http.HttpRequestMessage request, System.Net.Http.HttpCompletionOption completionOption, System.Threading.CancellationToken cancellationToken) [0x000ca] in <0029d260a26b48288c90ea4fe946b24c>:0
at MyObfuscatedAppName.Services.CharacterEmbeddedResourceDriver.<LoadCharacters>b__1_0 (System.IObserver`1[T] observer) [0x000ca] in <446b676d44a2438aa46540b6f67c24f8>:0
Is probably happening when our LoadCharacters() method begins:
public IObservable<CharacterJsonRoot> LoadCharacters()
{
Debug.WriteLine("MyApp :: Load Characters");
return Observable.Create<CharacterJsonRoot>(async observer =>
{
if (CrossConnectivity.Current.IsConnected)
{
var client = new HttpClient();
client.BaseAddress = new Uri("https://myapp.obfuscated.com");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync("/my/path/to/file/data.json");
if (response.IsSuccessStatusCode)
{
Debug.WriteLine("Loaded from server");
var data = await response.Content.ReadAsStringAsync();
var characters = DeserializeJson(data);
observer.OnNext(characters);
observer.OnCompleted();
}
else
{
Debug.WriteLine("Loaded from fallback");
var assembly = typeof(CharacterEmbeddedResourceDriver).GetTypeInfo().Assembly;
var stream = assembly.GetManifestResourceStream("MyApp.Services.Data.data.json");
using (var reader = new StreamReader(stream))
{
string result = await reader.ReadToEndAsync();
var characters = DeserializeJson(result);
observer.OnNext(characters);
observer.OnCompleted();
}
}
}
else
{
// write your code if there is no Internet available
Debug.WriteLine("Loaded from fallback & NO Internet available ");
var assembly = typeof(CharacterEmbeddedResourceDriver).GetTypeInfo().Assembly;
var stream = assembly.GetManifestResourceStream("MyApp.Services.Data.data.json");
using (var reader = new StreamReader(stream))
{
string result = await reader.ReadToEndAsync();
var characters = DeserializeJson(result);
observer.OnNext(characters);
observer.OnCompleted();
}
}
}).SubscribeOn(System.Reactive.Concurrency.TaskPoolScheduler.Default).ObserveOn(SynchronizationContext.Current);
}
Other than that, I really have no idea why this error is happening only on certain devices. We are testing using App Live in Browser Stack and it always crashes for Galaxy Note 3 and Samsung Tab 4. Yet it will never crash on the Samsung Galaxy S7, for example.
UPDATE:
It's only happening on Android 4.4 and lower. So I've updated my Android project by setting the minimum Android version required to be 5. However, I would still like to know why this error occurs and what it means, so I'm leaving this open.
I came across this issue too. Turns out it was overzealous Linking. Adding Mono.Android to Skip linking assemblies fixed it for me.

Xam.Plugin.Geolocator iOS app crashes if user rejects location permissions

I am currently on version 4.2.0 of the Geolocator Plugin.
Upon installing the app, the following prompt appears:
However, if the user selects Don't Allow, the app crashes with the following error:
Plugin.Geolocator.Abstractions.GeolocationException: A geolocation error occured: Unauthorized
at Plugin.Geolocator.GeolocatorImplementation+<StartListeningAsync>d__33.MoveNext () [0x000eb] in <51c894f634a24ed2b17b19807ba0f99e>:0
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in <cf9013b38a4e4129bd64785080dd2844>:0
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0003e] in <cf9013b38a4e4129bd64785080dd2844>:0
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in <cf9013b38a4e4129bd64785080dd2844>:0
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in <cf9013b38a4e4129bd64785080dd2844>:0
at System.Runtime.CompilerServices.TaskAwaiter`1[TResult].GetResult () [0x00000] in <cf9013b38a4e4129bd64785080dd2844>:0
at Divco.App+<StartListening>d__11.MoveNext () [0x000b5] in <a1469ede5dd148df922c3455ac848705>:0
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in <cf9013b38a4e4129bd64785080dd2844>:0
at System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.<ThrowAsync>b__6_0 (System.Object state) [0x00000] in <cf9013b38a4e4129bd64785080dd2844>:0
at UIKit.UIKitSynchronizationContext+<Post>c__AnonStorey0.<>m__0 () [0x00000] in <b7935acd70e343049845d6fd73e5ec44>:0
at Foundation.NSAsyncActionDispatcher.Apply () [0x00000] in <b7935acd70e343049845d6fd73e5ec44>:0
--- End of stack trace from previous location where exception was thrown ---
It continues to throw this error when you reopen the app.
I have included my code for App.xaml.cs to see if I am missing a piece. I followed the tutorial on the Geolocator plugin site linked previously.
App.xaml.cs
async void StartListening()
{
if (CrossGeolocator.Current.IsListening)
return;
CrossGeolocator.Current.DesiredAccuracy = 10;
await CrossGeolocator.Current.StartListeningAsync(TimeSpan.FromSeconds(Settings.PingDurationSeconds), 1, true, new Plugin.Geolocator.Abstractions.ListenerSettings
{
AllowBackgroundUpdates = true,
PauseLocationUpdatesAutomatically = false
});
CrossGeolocator.Current.PositionChanged += PositionChanged;
CrossGeolocator.Current.PositionError += PositionError;
}
async void PositionChanged(object sender, PositionEventArgs e)
{
//If updating the UI, ensure you invoke on main thread
var position = e.Position;
if (!Settings.IsLoggedIn)
return;
else if (Settings.IsAuthExpired)
await loginStore.Refresh();
var output = "Full: Lat: " + $"{position.Latitude}" + " Long: " + $"{position.Longitude}";
output += "\n" + $"Time: {position.Timestamp}";
output += "\n" + $"Heading: {position.Heading}";
output += "\n" + $"Speed: {position.Speed}";
output += "\n" + $"Accuracy: {position.Accuracy}";
output += "\n" + $"Altitude: {position.Altitude}";
output += "\n" + $"Altitude Accuracy: {position.AltitudeAccuracy}";
Settings.CurrentPosition = position;
await dataStore.UpdateLocation(position.Latitude, position.Longitude);
Debug.WriteLine(output);
}
private void PositionError(object sender, PositionErrorEventArgs e)
{
Debug.WriteLine(e.Error);
//Handle event here for errors
}
async void StopListening()
{
if (!CrossGeolocator.Current.IsListening)
return;
await CrossGeolocator.Current.StopListeningAsync();
CrossGeolocator.Current.PositionChanged -= PositionChanged;
CrossGeolocator.Current.PositionError -= PositionError;
}
Ideally, I would like to alert the user that they must enable location tracking to use our app (as it is a major part of our service).

Need Help Exception at Public Game1() in MonoGame on OSX

So I'm trying to create this program that works perfect in Visual Studio 2012 at School.
But when I'm at home it's giving me this Thrown Exception error at Public Game1().
Hopefully someone can help me out with this so that way i can actually run my program and finish it.
The Call Stack is:
System.NullReferenceException: Object reference not set to an instance
of an object at Microsoft.Xna.Framework.OpenTKGameWindow.Initialize
() [0x00000] in :0 at
Microsoft.Xna.Framework.OpenTKGameWindow..ctor () [0x00000] in
:0 at
Microsoft.Xna.Framework.OpenTKGamePlatform..ctor
(Microsoft.Xna.Framework.Game game) [0x00000] in :0
at Microsoft.Xna.Framework.GamePlatform.Create
(Microsoft.Xna.Framework.Game game) [0x00000] in :0
at Microsoft.Xna.Framework.Game..ctor () [0x00000] in :0 at MonoGameTest.Game1..ctor () [0x00023] in
/Users/sebnabt/Projects/MonoGameTest/MonoGameTest/Game1.cs:38 at
MonoGameTest.Program.Main () [0x00001] in
/Users/sebnabt/Projects/MonoGameTest/MonoGameTest/Program.cs:19
And my code:
<!-- language: lang-cs -->
region Using Statements
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Storage;
using Microsoft.Xna.Framework.Input;
endregion
namespace MonoGameTest
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
// Maps user keys to display colors
Dictionary<Keys, Color> key_to_color = new Dictionary<Keys, Color>();
// these are the colors guessed by the user, so far.
List<Color>[] player_colors = new List<Color>[10];
// these are the keys that correspond to a dot color
List<Keys> color_letters = new List<Keys>();
Texture2D dot_picture;
KeyboardState old_keyboard_state;
int row;
public Game1() : base()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
base.Initialize ();
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
///
/// // screen constants
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;
protected override void Initialize()
{
row = 0;
// back buffer
graphics.PreferredBackBufferHeight = SCREEN_HEIGHT;
graphics.PreferredBackBufferWidth = SCREEN_WIDTH;
graphics.PreferMultiSampling = false;
graphics.ApplyChanges();
base.Initialize();
// initialize the color dictionary
key_to_color.Add(Keys.R, Color.Red);
key_to_color.Add(Keys.G, Color.Green);
key_to_color.Add(Keys.B, Color.Blue);
key_to_color.Add(Keys.Y, Color.Yellow);
color_letters = new List<Keys>();
foreach (Keys letter in key_to_color.Keys)
{
color_letters.Add(letter);
}
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
// load our textures
dot_picture = Content.Load<Texture2D>(#"media\ball");
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
// get keyboard state once per frame
KeyboardState keyState = Keyboard.GetState();
// exit the game?
if (keyState.IsKeyDown(Keys.Escape))
{
this.Exit();
}
// erase list of player colors?
else if (keyState.IsKeyDown(Keys.Space))
{
player_colors[this.row].Clear();
}
// player pressed a color key?
else {
foreach (Keys letter in color_letters)
{
if (key_was_released(letter, keyState))
{
add_color(letter);
}
if (this.player_colors [row].Count () >= 4) {
this.row = this.row + 1;
}
}
}
old_keyboard_state = keyState;
base.Update(gameTime);
}
protected override void UnloadContent() {
}
bool key_was_released(Keys key, KeyboardState new_state)
{
return old_keyboard_state.IsKeyDown(key) &&
new_state. IsKeyUp (key);
}
void add_color(Keys key)
{
Color color = key_to_color[key];
if (player_colors[this.row].Count() < 4)
{
player_colors[this.row].Add(color);
}
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
graphics.GraphicsDevice.Clear (Color.CornflowerBlue);
// draw typical sprites
spriteBatch.Begin ();
draw_player_colors (spriteBatch);
spriteBatch.End ();
base.Draw (gameTime);
}
protected void draw_player_colors(SpriteBatch batch)
{
for (int current_row = 0; current_row < 10; current_row++) {
for (int column = 0; column < player_colors[current_row].Count(); column++) {
int x = 100 + column * 70;
int y = 100 + column * 70;
Vector2 loc = new Vector2 (x, y);
Color c = player_colors[current_row].ElementAt (column);
batch.Draw (dot_picture, loc, c);
}
}
}
}
}
Newest Error:
It looks as though I have gotten it to slightly work however I'm now getting an error in the Basic Template on: logoTexture = Content.Load<Texture2D>("logo");
The error will be below
Microsoft.Xna.Framework.Content.ContentLoadException: Could not load
logo asset as a non- content file! ---> System.Exception: The
directory was not found. ---> System.Exception: Could not find a
part of the path
"/Users/sebnabt/Projects/BSMac/BSMac/bin/Debug/BSMac.app/Contents/Resources/Content/logo.xnb".
at System.IO.FileStream..ctor (System.String path, FileMode mode,
FileAccess access, FileShare share, Int32 bufferSize, Boolean
anonymous, FileOptions options) [0x001c6] in
/private/tmp/source/bockbuild-xamarin/profiles/mono-mac-xamarin-no-pcl/build-root/mono-3.2.0/mcs/class/corlib/System.IO/FileStream.cs:266
at System.IO.FileStream..ctor (System.String path, FileMode mode,
FileAccess access, FileShare share) [0x00000] in
/private/tmp/source/bockbuild-xamarin/profiles/mono-mac-xamarin-no-pcl/build-root/mono-3.2.0/mcs/class/corlib/System.IO/FileStream.cs:132
at at (wrapper remoting-invoke-with-check) System.IO.FileStream:.ctor
(string,System.IO.FileMode,System.IO.FileAccess,System.IO.FileShare)
at System.IO.File.OpenRead (System.String path) [0x00000] in
/private/tmp/source/bockbuild-xamarin/profiles/mono-mac-xamarin-no-pcl/build-root/mono-3.2.0/mcs/class/corlib/System.IO/File.cs:341
at Microsoft.Xna.Framework.TitleContainer.OpenStream (System.String
name) [0x00000] in :0 at
Microsoft.Xna.Framework.Content.ContentManager.OpenStream
(System.String assetName) [0x00000] in :0 --- End
of inner exception stack trace --- at
Microsoft.Xna.Framework.Content.ContentManager.OpenStream
(System.String assetName) [0x00000] in :0 at
Microsoft.Xna.Framework.Content.ContentManager.ReadAsset[Texture2D]
(System.String assetName, System.Action1 recordDisposableObject)
[0x00000] in <filename unknown>:0 --- End of inner exception stack
trace --- at at
Microsoft.Xna.Framework.Content.ContentManager.ReadAsset<Microsoft.Xna.Framework.Graphics.Texture2D>
(string,System.Action1) <0x0076b> at at
Microsoft.Xna.Framework.Content.ContentManager.Load
(string) <0x0020b> at BSMac.Game1.LoadContent () [0x00023] in
/Users/sebnabt/Projects/BSMac/BSMac/Game1.cs:70 at at
Microsoft.Xna.Framework.Game.Initialize () at
BSMac.Game1.Initialize () [0x00002] in
/Users/sebnabt/Projects/BSMac/BSMac/Game1.cs:57 at at
Microsoft.Xna.Framework.Game.DoInitialize ()
at at Microsoft.Xna.Framework.Game.Run
(Microsoft.Xna.Framework.GameRunBehavior) at
at Microsoft.Xna.Framework.Game.Run () at
BSMac.AppDelegate.FinishedLaunching (MonoMac.Foundation.NSObject)
[0x00012] in /Users/sebnabt/Projects/BSMac/BSMac/Main.cs:34 at at
(wrapper dynamic-method) object.[BSMac.AppDelegate.Void
FinishedLaunching(MonoMac.Foundation.NSObject)]
(MonoMac.Foundation.NSObject,MonoMac.ObjCRuntime.Selector,MonoMac.Foundation.NSObject)
at at (wrapper native-to-managed)
object.[BSMac.AppDelegate.Void
FinishedLaunching(MonoMac.Foundation.NSObject)]
(MonoMac.Foundation.NSObject,MonoMac.ObjCRuntime.Selector,MonoMac.Foundation.NSObject)
at at (wrapper managed-to-native)
MonoMac.AppKit.NSApplication.NSApplicationMain (int,string[])
<0x00003> at at MonoMac.AppKit.NSApplication.Main (string[]) at BSMac.Program.Main (string[]) [0x0001d] in
/Users/sebnabt/Projects/BSMac/BSMac/Main.cs:20 at
Are you building in Xamarin Studio? I believe you are experiencing the same problem described in a question from a couple days ago; see my answer there: https://stackoverflow.com/a/18798311/793449
To recap, Xamarin Studio is picking the WindowsGL framework assembly instead of the mac assembly. You should build MonoGame yourself from the latest source (the MonoGame.Framework.MacOS project) and change the reference out in your game.

Resources