How to use Azure Mobile Services from Xamarin.Forms? - c#

I try to use the Azure Mobile Services from my simple Forms app and it don't work. The last command just run forever. I checked the internet connection with a WebClient and it is okay. The code works fine in a simple Windows console application.
var ms = new MobileServiceClient(
#"https://xxx.azure-mobile.net/",
#"xxx"
);
IMobileServiceTable<TodoItem> todoTable =
ms.GetTable<TodoItem>();
List<TodoItem> items = todoTable
.Where(todoItem => todoItem.Complete == false).ToListAsync().Result;
Edit:
I use Xamarin Studio because I only have indie license. For the debug I tried a Samsung Galaxy S3 and a Huawei Ascend P7, the result was same. I have updated the Xamarin and now it produces an interesting exception if I use async-await to get the result.
Java.Lang.RuntimeException: java.lang.reflect.InvocationTargetException
at --- End of managed exception stack trace ---
at java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:675)
at at dalvik.system.NativeStart.main(Native Method)
at Caused by: java.lang.reflect.InvocationTargetException
at at java.lang.reflect.Method.invokeNative(Native Method)
at at java.lang.reflect.Method.invoke(Method.java:515)
at at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:859)
at ... 2 more
at Caused by: md52ce486a14f4bcd95899665e9d932190b.JavaProxyThrowable: System.NullReferenceException: Object reference not set to an instance of an object
at at Xamarin.Forms.Platform.Android.FormsApplicationActivity.OnPrepareOptionsMenu (Android.Views.IMenu) <IL 0x00007, 0x00050>
at Android.App.Activity.n_OnPrepareOptionsMenu_Landroid_view_Menu_ (intptr,intptr,intptr) [0x00011] in /Users/builder/data/lanes/monodroid-mavericks-monodroid-5.1-series/d23da369/source/monodroid/src/Mono.Android/platforms/android-21/src/generated/Android.App.Activity.cs:4151
at at (wrapper dynamic-method) object.fcd55d8e-49be-4c8f-b3a6-37be6bdb988f (intptr,intptr,intptr) <IL 0x00017, 0x0005b>
at at md5530bd51e982e6e7b340b73e88efe666e.FormsApplicationActivity.n_onPrepareOptionsMenu(Native Method)
at at md5530bd51e982e6e7b340b73e88efe666e.FormsApplicationActivity.onPrepareOptionsMenu(FormsApplicationActivity.java:110)
at at android.app.Activity.onPreparePanel(Activity.java:2612)
at at com.android.internal.policy.impl.PhoneWindow.preparePanel(PhoneWindow.java:518)
at at com.android.internal.policy.impl.PhoneWindow.doInvalidatePanelMenu(PhoneWindow.java:872)
at at com.android.internal.policy.impl.PhoneWindow$1.run(PhoneWindow.java:243)
at at android.view.Choreographer$CallbackRecord.run(Choreographer.java:780)
at at android.view.Choreographer.doCallbacks(Choreographer.java:593)
at at android.view.Choreographer.doFrame(Choreographer.java:561)
at at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:766)
at at android.os.Handler.handleCallback(Handler.java:733)
at at android.os.Handler.dispatchMessage(Handler.java:95)
at at android.os.Looper.loop(Looper.java:136)
at at android.app.ActivityThread.main(ActivityThread.java:5290)
at ... 5 more

Are you sure you are not blocking your UI with a combination of async / await (deadlock)?
Modify your code as follows:
IMobileServiceTable<TodoItem> todoTable = await ms.GetTable<TodoItem>();
List<TodoItem> items = todoTable.Where(todoItem => todoItem.Complete == false).ToListAsync().ConfigureAwait(false);
See here for more Information about this specific problem: http://blog.stephencleary.com/2012/07/dont-block-on-async-code.html
For further informations about a deadlock, Stephen Clary has an excellent blog about this: http://blog.stephencleary.com/2012/02/async-and-await.html

Related

Getting "NotImplementedException" when attempting Azure connection with Unity (c#)

I'm using Unity 2019.3.6f1. I have created a simple DLL for connecting to Azure and uploading a file. However, when I call this DLL to attemp connecting to the Azure blob storage I get the following stack trace:
NotImplementedException: The method or operation is not implemented.
System.Net.Http.HttpClientHandler.get_MaxConnectionsPerServer () (at
<7ebf3529ba0e4558a5fa1bc982aa8605>:0)
Azure.Core.Pipeline.ServicePointHelpers.SetLimits
(System.Net.Http.HttpMessageHandler messageHandler) (at
:0)
Azure.Core.Pipeline.HttpClientTransport.CreateDefaultClient () (at
:0)
Azure.Core.Pipeline.HttpClientTransport..ctor () (at
:0)
Azure.Core.Pipeline.HttpClientTransport..cctor () (at
:0) Rethrow as
TypeInitializationException: The type initializer for
'Azure.Core.Pipeline.HttpClientTransport' threw an exception.
Azure.Core.ClientOptions..ctor () (at
:0)
Azure.Storage.Blobs.BlobClientOptions..ctor
(Azure.Storage.Blobs.BlobClientOptions+ServiceVersion version) (at
:0)
Azure.Storage.Blobs.BlobServiceClient..ctor (System.String
connectionString, Azure.Storage.Blobs.BlobClientOptions options) (at
:0)
Azure.Storage.Blobs.BlobServiceClient..ctor (System.String
connectionString) (at :0)
Cineon.UnityToAzureConnection+d__1.MoveNext () (at
<5252723c79f94a8cb77bb25e3b9f0396>:0)
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () (at
<437ba245d8404784b9fbab9b439ac908>:0)
System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.b__6_0
(System.Object state) (at <437ba245d8404784b9fbab9b439ac908>:0)
UnityEngine.UnitySynchronizationContext+WorkRequest.Invoke () (at
:0)
UnityEngine.UnitySynchronizationContext:ExecuteTasks()
Here is my DLL code (in line with this Microsoft quickstart guide):
public class UnityToAzureConnection
{
private readonly static string m_connectionString = "CENSORED";
public static async void CreateConnection(string _path, string _fileName)
{
BlobServiceClient blobServiceClient = new BlobServiceClient(m_connectionString);
BlobContainerClient containerClient = await blobServiceClient.CreateBlobContainerAsync("imagetest");
BlobClient blobClient = containerClient.GetBlobClient(_fileName);
using (FileStream _fs = File.Open(Path.Combine(_path, _fileName), FileMode.Open))
{
await blobClient.UploadAsync(_fs, true);
}
}
}
I simply call this DLL's CreateConnection method and pass in my "Application.dataPath" and a filename. However, I then get the above exception.
I have pulled all other needed DLL's from the project build folder into the plugin folder, so am unsure why this is occuring.
Any assistance would be greatly appreciated.
Please note that I am just starting to move out of my comfort zone here, so I'm hoping that my post is to StackOverflow's standard of questions.
[P.S.] Obviously "CENSORED" isn't my actual connection string, just keeping sensitive info hidden.
UPDATE 29/05/2021 I have confirmed that my connection code DOES work when used in a simple .net console app (however, I did have to adjust the containername to be all lowercase). This error only occurs in Unity. Again, any and all help would be appreciated.
As I mentioned here, try it once.
If you have a lower version of Unity, Azure.Core ver. 1.19.0 may be better.
https://forum.unity.com/threads/attempting-to-connec-to-azure-blobs-results-in-notimplementedexception.1117705/
I have experienced the same exception in BlobServiceClient constructor in my mobile project.
The problem was in the version of Azure.Storage.Blobs package. I used the most recent version 12.12.0, and it caused the exception.
When I downgraded Azure.Storage.Blobs package to 12.9.1 all things worked fine.

PlatformNotSupportedException with NAudio WaveOut in Unity

I am trying to play sounds on a secondary soundcard using NAudio in a Unity project.
It works successfuly using the Play button in the editor, but not in the executable build.
Here is the error i get :
System.PlatformNotSupportedException: Operation is not supported on this platform.
at System.Windows.Forms.Form..ctor () [0x00000] in <0b0c181c86c84da989ad80998d3a0a84>:0
at NAudio.Wave.WaveWindow.OnMdiChildActivate (System.EventArgs e) [0x00000] in <554b80148c284b99953f098db496ebd4>:0
at (wrapper remoting-invoke-with-check) NAudio.Wave.WaveWindow..ctor(NAudio.Wave.WaveInterop/WaveCallback)
at NAudio.Wave.WaveCallbackInfo.Connect (NAudio.Wave.WaveInterop+WaveCallback callback) [0x00009] in <554b80148c284b99953f098db496ebd4>:0
at NAudio.Wave.WaveOut..ctor (NAudio.Wave.WaveCallbackInfo callbackInfo) [0x0004e] in <554b80148c284b99953f098db496ebd4>:0
at NAudio.Wave.WaveOut..ctor () [0x00014] in <554b80148c284b99953f098db496ebd4>:0
at MainVideoScript.playSound (System.Int32 deviceNumber) [0x0002e] in <0d2c0b09fee74d5099fd910768d58ea9>:0
I am running on Windows 10, and the Target platform=Windows, so why the platform doesn't support what I am trying to do? What can I change?
Here is the code i am trying to run:
string soundPath = System.IO.Path.Combine(Application.streamingAssetsPath, #"clic2.wav");
waveReader = new NAudio.Wave.WaveFileReader(soundPath);
var wave = new NAudio.Wave.WaveOut();
wave.DeviceNumber = deviceNumber;
wave.Init(waveReader);
wave.Play();
I am using 2019.2.8f1
You need to make sure the Api compatibility Level is correct in Edit \ Project Settings \ Player

Xamarin.Forms "App has stopped working" on android

So I encounterd this error just now and this causes my android application not to work on the device. Whenever I debug my application for android it crashes for some reasont. . As a new user to Xamarin I'm clueless.
Here is the error I`m getting:
[art] Late-enabling -Xcheck:jni
[ContextImpl] Unable to create files subdir /data/data/com.comhuis.saleskicker.sales_kicker/cache
[ContextImpl] Unable to create files subdir /data/data/com.comhuis.saleskicker.sales_kicker/files
[AndroidRuntime] Shutting down VM
[AndroidRuntime] FATAL EXCEPTION: main
[AndroidRuntime] Process: com.comhuis.saleskicker.sales_kicker, PID: 5035
[AndroidRuntime] java.lang.RuntimeException: Unable to get provider mono.MonoRuntimeProvider: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.io.File.getAbsolutePath()' on a null object reference
[AndroidRuntime] at android.app.ActivityThread.installProvider(ActivityThread.java:5015)
[AndroidRuntime] at android.app.ActivityThread.installContentProviders(ActivityThread.java:4607)
[AndroidRuntime] at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4547)
[AndroidRuntime] at android.app.ActivityThread.access$1500(ActivityThread.java:148)
[AndroidRuntime] at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
[AndroidRuntime] at android.os.Handler.dispatchMessage(Handler.java:102)
[AndroidRuntime] at android.os.Looper.loop(Looper.java:135)
[AndroidRuntime] at android.app.ActivityThread.main(ActivityThread.java:5272)
[AndroidRuntime] at java.lang.reflect.Method.invoke(Native Method)
[AndroidRuntime] at java.lang.reflect.Method.invoke(Method.java:372)
[AndroidRuntime] at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:909)
[AndroidRuntime] at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:704)
[AndroidRuntime] Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.io.File.getAbsolutePath()' on a null object reference
[AndroidRuntime] at mono.MonoPackageManager.LoadApplication(MonoPackageManager.java:27)
[AndroidRuntime] at mono.MonoRuntimeProvider.attachInfo(MonoRuntimeProvider.java:42)
[AndroidRuntime] at android.app.ActivityThread.installProvider(ActivityThread.java:5012)
[AndroidRuntime] ... 11 more
[Process] Sending signal. PID: 5035 SIG: 9
I haven't really got something special in my project. I can't upload a screenshot of my solution just yet but I`ll try and describe it:
My solution exists out of SalesKicker and SalesKicker.Droid. SalesKicker has 3 files MainPage.Xaml MainPage.Xaml.cs SalesKicker.cs.
and SalesKicker.Droid contains the usual stuff plus 1 image called delogo.png which I`m using as appicon. This is my MainActivity.cs code:
namespace SalesKicker.Droid
{
[Activity (Label = #"Sales Kicker", Icon = "#drawable/delogo", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity
{
protected override void OnCreate (Bundle bundle)
{
Xamarin.Insights.Initialize (global::SalesKicker.Droid.XamarinInsights.ApiKey, this);
base.OnCreate (bundle);
global::Xamarin.Forms.Forms.Init (this, bundle);
LoadApplication (new App ());
}
}
I've also been trying to set some breakpoints. I've tried it on every line and still got the same error over and over again. I also tried to set my "Target Version" to Lollipop 5.0, which is the current software version on my LG G3, and it didn't really have any effect. And I also have every single Android SDK installed. Since I'm quite new to Xamarin I'm clueless. Can someone please tell me what I'm doing wrong here?
I got it after looking at another thread: Why does my Xamarin Android application suddenly require external storage permissions?
I just had to go to: AndroidManifest.xml and set 'Install location' to internalOnly. This worked for me.
Create this folder on your android device if you can.
/data/data/{your.apps.package.name}
Otherwise, uninstall your app then re-install it again.
You may noticed that the exception is rise by "File.getAbsolutePath()".
After decompile my app's .apk package, i found this is cause by getFilesDir() returning null.
// MonoPackageManager.java
String str1 = context.getFilesDir().getAbsolutePath(); // <- Exception
String str2 = context.getCacheDir().getAbsolutePath();

RestSharp is crashing with Unity3d when running on iPhone

I'm trying to attach RestSharp to Unity3d.
Original RestSharp mono lib works fine in Editor, but on device its crashing with callstack
ArgumentOutOfRangeException: Argument is out of range.
Parameter name: options
at System.Security.Cryptography.X509Certificates.X509CertificateCollection.GetEnumerator () [0x00000] in <filename unknown>:0
at System.Text.RegularExpressions.Regex.validate_options (RegexOptions options) [0x00000] in <filename unknown>:0
at System.Text.RegularExpressions.Regex..ctor (System.String pattern, RegexOptions options) [0x00000] in <filename unknown>:0
at RestSharp.RestClient..ctor () [0x00000] in <filename unknown>:0
at RestSharp.RestClient..ctor (System.String baseUrl) [0x00000] in <filename unknown>:0
That means, exception appears inside of ctor RestClient(string), which is a wrapper around default ctor. And inside of default ctor, there is
public RestClient()
{
#if WINDOWS_PHONE
this.UseSynchronizationContext = true;
#endif
this.ContentHandlers = new Dictionary<string, IDeserializer>();
this.AcceptTypes = new List<string>();
this.DefaultParameters = new List<Parameter>();
// register default handlers
this.AddHandler("application/json", new JsonDeserializer());
this.AddHandler("application/xml", new XmlDeserializer());
this.AddHandler("text/json", new JsonDeserializer());
this.AddHandler("text/x-json", new JsonDeserializer());
this.AddHandler("text/javascript", new JsonDeserializer());
this.AddHandler("text/xml", new XmlDeserializer());
this.AddHandler("*+json", new JsonDeserializer());
this.AddHandler("*+xml", new XmlDeserializer());
this.AddHandler("*", new XmlDeserializer());
this.FollowRedirects = true;
}
At this point, i dont see where next step with Regex ctor appears. Any ideas?
We have encountered the same issue while building a standalone Windows project with Unity 5.2.1. In the editor it all works fine, until you create a build.
I believe the problem has something to do with the 'structuredSyntaxSuffixWildcardRegex' used in the 'AddHandler' method. While I don't know exactly why it fails, I do know a previous version of RestSharp does work for us.
I guess you're also using the latest RestSharp version, so could you give RestSharp v105.1.0 a try?
It seemed to stop functioning from Restshap v105.2.1, I am going through the commits to see a possible culprit. I will fork and fix it if I have found a solution.
Also I must inform you that in our case GZIP decompression also wasn't working due to missing Mono.Posix libraries. This problem occurred when the server returned a gzipped response and the RestClient allowed it. We had to work around that by using 'Fabman08's fix which made decompression configurable.
I have forked the RestSharp repository in an attempt to fix the above and other Unity related issues. It's located at: https://github.com/eamonwoortman/RestSharp.Unity.
Your and other issues have already been fixed and were tested against a 64bit standalone Windows build.
Could you verify if these fixes also work on your iOS project? Make sure you build the RestSharp.Net35.Unity project.

How can I create an audio context with OpenAL in monodroid?

Whenever I try to create a new audio context in monodroid, it fallls over telling me that openal32.dll is missing; which naturally doesn't make sense, being as this is monodroid, and openal is included as part of OpenTK.
I can only assume i'm doing something wrong, but i've used OpenTK/OpenAL before under windows and have managed just fine with similar code.
anyway here is the offending code:
public Audio()
{
if (Loaded == false)
{
Loaded = true;
try
{
try {Console.WriteLine ("Current: " + AudioContext.CurrentContext.ToString());} catch { Console.WriteLine ("no current context"); }
try {Console.WriteLine ("Default: " + AudioContext.DefaultDevice);} catch { Console.WriteLine ("no default device"); }
Context = new AudioContext();
ValidContext = true; //we have a valid audio context!
}
catch (Exception ex)
{
Console.WriteLine ("Loading the audio context failed.");
Console.WriteLine (ex.ToString ());
Console.WriteLine (ex.Message);
ValidContext = false; //Loading the audio context failed :(
}
}
}
And here is the output:
I/monodroid-gc(24762): environment supports jni NewWeakGlobalRef
D/AndroidGameView(24762): SurfaceCreated
D/libEGL (24762): egl.cfg not found, using default config
D/libEGL (24762): loaded /system/lib/egl/libGLES_android.so
I/mono-stdout(24762): no current context
I/mono-stdout(24762): no default device
I/mono-stdout(24762): Loading the audio context failed.
I/mono-stdout(24762): System.TypeInitializationException: An exception was thrown by the type initializer for OpenTK.Audio.AudioContext ---> System.TypeInitializationException: An exception was thrown by the type initializer for OpenTK.Audio.AudioDeviceEnumerator ---> System.DllNotFoundException: openal32.dll
I/mono-stdout(24762): at (wrapper managed-to-native) OpenTK.Audio.OpenAL.Alc:MakeContextCurrent (intptr)
I/mono-stdout(24762): at OpenTK.Audio.OpenAL.Alc.MakeContextCurrent (ContextHandle context) [0x00000] in <filename unknown>:0
I/mono-stdout(24762): at OpenTK.Audio.AudioDeviceEnumerator..cctor () [0x00000] in <filename unknown>:0
I/mono-stdout(24762): --- End of inner exception stack trace ---
I/mono-stdout(24762): at OpenTK.Audio.AudioContext..cctor () [0x00000] in <filename unknown>:0
I/mono-stdout(24762): --- End of inner exception stack trace ---
I/mono-stdout(24762): at Hardware.Audio..ctor () [0x00000] in <filename unknown>:0
I/mono-stdout(24762): An exception was thrown by the type initializer for OpenTK.Audio.AudioContext
I/ARMAssembler(24762): generated scanline__00000177:03545444_00009001_00000000 [159 ipp] (215 ins) at [0x4fc138:0x4fc494] in 4168381 ns
openal32.dll is not included as part of OpenTK. OpenTK just has bindings for OpenAL. Just like opengl32.dll, which is included as part of your graphics card drivers, openal32.dll must be installed through audio card drivers (or a software implementation of it).
After a quick search, it looks like you need to compile a software implementation of OpenAL for Android: http://pielot.org/2010/12/14/openal-on-android/
Edit: It looks like Android prefers to use the newer OpenSL ES. If you've got a bit of time on your hands, you could try to get OpenTK's generator to generate OpenSL ES bindings for you.
This other StackOverflow question has a few other options for using OpenSL.

Categories

Resources