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";
}
}
}
}
Related
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;
}
}
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.
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.
I'm trying to make a simple query to a elasticsearch on AWS. However, when I execute it my .fsx file on OSX using VSCode + Ionide, it fails with the following exception:
Elasticsearch.Net.UnexpectedElasticsearchClientException: The method or operation is not implemented. ---> System.NotImplementedException: The method or operation is not implemented.
at Elasticsearch.Net.HttpConnection.CreateHttpClientHandler (Elasticsearch.Net.RequestData requestData) [0x00032] in <d540c1f0c16e460aacd9aea9af6a6562>:0
at Elasticsearch.Net.HttpConnection+<>c__DisplayClass2_0.<GetClient>b__0 (System.Int32 h) [0x00000] in <d540c1f0c16e460aacd9aea9af6a6562>:0
at System.Collections.Concurrent.ConcurrentDictionary`2[TKey,TValue].GetOrAdd (TKey key, System.Func`2[T,TResult] valueFactory) [0x00034] in <98fac219bd4e453693d76fda7bd96ab0>:0
at Elasticsearch.Net.HttpConnection.GetClient (Elasticsearch.Net.RequestData requestData) [0x00044] in <d540c1f0c16e460aacd9aea9af6a6562>:0
at Elasticsearch.Net.HttpConnection.Request[TResponse] (Elasticsearch.Net.RequestData requestData) [0x00000] in <d540c1f0c16e460aacd9aea9af6a6562>:0
at Elasticsearch.Net.RequestPipeline.CallElasticsearch[TResponse] (Elasticsearch.Net.RequestData requestData) [0x000b9] in <d540c1f0c16e460aacd9aea9af6a6562>:0
at Elasticsearch.Net.Transport`1[TConnectionSettings].Request[TResponse] (Elasticsearch.Net.HttpMethod method, System.String path, Elasticsearch.Net.PostData data, Elasticsearch.Net.IRequestParameters requestParameters) [0x000bc] in <d540c1f0c16e460aacd9aea9af6a6562>:0
--- End of inner exception stack trace ---
at Elasticsearch.Net.Transport`1[TConnectionSettings].Request[TResponse] (Elasticsearch.Net.HttpMethod method, System.String path, Elasticsearch.Net.PostData data, Elasticsearch.Net.IRequestParameters requestParameters) [0x00162] in <d540c1f0c16e460aacd9aea9af6a6562>:0
at Elasticsearch.Net.ElasticLowLevelClient.DoRequest[TResponse] (Elasticsearch.Net.HttpMethod method, System.String path, Elasticsearch.Net.PostData data, Elasticsearch.Net.IRequestParameters requestParameters) [0x00006] in <d540c1f0c16e460aacd9aea9af6a6562>:0
at Elasticsearch.Net.ElasticLowLevelClient.Search[TResponse] (System.String index, System.String type, Elasticsearch.Net.PostData body, Elasticsearch.Net.SearchRequestParameters requestParameters) [0x0003f] in <d540c1f0c16e460aacd9aea9af6a6562>:0
at Nest.LowLevelDispatch.SearchDispatch[TResponse] (Nest.IRequest`1[TParameters] p, Elasticsearch.Net.SerializableData`1[T] body) [0x00100] in <2d6368be93f64ed8850fcce912986a0e>:0
at Nest.ElasticClient.<Search>b__546_0[T,TResult] (Nest.ISearchRequest p, Elasticsearch.Net.SerializableData`1[T] d) [0x00006] in <2d6368be93f64ed8850fcce912986a0e>:0
at Nest.ElasticClient.Nest.IHighLevelToLowLevelDispatcher.Dispatch[TRequest,TQueryString,TResponse] (TRequest request, System.Func`3[T1,T2,TResult] responseGenerator, System.Func`3[T1,T2,TResult] dispatch) [0x00038] in <2d6368be93f64ed8850fcce912986a0e>:0
at Nest.ElasticClient.Nest.IHighLevelToLowLevelDispatcher.Dispatch[TRequest,TQueryString,TResponse] (TRequest request, System.Func`3[T1,T2,TResult] dispatch) [0x00006] in <2d6368be93f64ed8850fcce912986a0e>:0
at Nest.ElasticClient.Search[T,TResult] (Nest.ISearchRequest request) [0x00013] in <2d6368be93f64ed8850fcce912986a0e>:0
at Nest.ElasticClient.Search[T] (Nest.ISearchRequest request) [0x00000] in <2d6368be93f64ed8850fcce912986a0e>:0
at <StartupCode$FSI_0003>.$FSI_0003.main# () [0x000ab] in <fc8857ba43db4f62b17453fbedc15b9f>:0
at (wrapper managed-to-native) System.Reflection.MonoMethod.InternalInvoke(System.Reflection.MonoMethod,object,object[],System.Exception&)
at System.Reflection.MonoMethod.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x0003b] in <98fac219bd4e453693d76fda7bd96ab0>:0
I'm using
NEST (6.4) and Elasticsearch.Net.Aws (6.0)
here is my code
#I "../.paket/load/netstandard2.0/"
#r "netstandard"
#load "NEST.fsx"
#load "Elasticsearch.Net.Aws.fsx"
open System
open Nest
open Elasticsearch.Net
open Elasticsearch.Net.Aws
type Payload = {latitude: double; longitude: double}
type Telemetry = {payload: Payload}
let credentialsProvider = new AwsCredentials(AccessKey = "my AccessKey", SecretKey = "my SecretKey")
let staticCredentialsProvider = new StaticCredentialsProvider(credentialsProvider)
let httpConnection = new AwsHttpConnection("ap-southeast-2", staticCredentialsProvider)
let pool = new SingleNodeConnectionPool(new Uri("https://search-MY_INDEX-SOME_ID.ap-southeast-2.es.amazonaws.com"))
let config = new ConnectionSettings(pool, httpConnection)
config.DefaultIndex("MY_INDEX") |> ignore
let client = new ElasticClient(config)
let result = client.Search<Telemetry>(new SearchRequest<Telemetry>())
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.