I'm using Xamarin.iOS for an application using AVAudioEngine.
Sometimes I get this exception :
AVFoundation_AVAudioPlayerNode_Play
Terminating app due to uncaught exception 'com.apple.coreaudio.avfaudio', reason: 'required condition is false: _engine->IsRunning()'
This point to my code:
private Dictionary<AudioTrack, AVAudioPlayerNode> _dicPlayerNodes;
private void PlayAudio()
{
try
{
NSError err;
if (Engine.StartAndReturnError(out err))
{
foreach (var audioTrack in _dicPlayerNodes)
{
AVAudioPlayerNode node = audioTrack.Value;
node.Play();
}
}
else
{
Messenger.Publish(new AudioErrorMessage(this) { Platform = "IOS", Code = Convert.ToInt32(err.Code), Message = err.LocalizedDescription ?? err.Description });
_exceptionHandlerService.PostHockeyApp(new Exception($"{err.Code} {err.Description}"));
}
}
catch (Exception ex)
{
_exceptionHandlerService.PostExceptionAsync(ex).Forget();
}
}
I don't understand how is it possible to have this exception that engine is not running, because in my code I Start it and get error if it failed to start ... Then play it.
Also I have a try catch that's not working in this case :( so my applicaton just crashed.
Any advices or idea ?
I comes to this thread but it doesn't help me to understand:
https://forums.developer.apple.com/thread/27980
versions:
IOS version : 10.3.3
Device: ipad 2
Xamarin.ios: 11.2.0.11
Thanks
Related
I have a WCF Service hosted in a Windows service as described here.
I have scheduled nightly restart of the service, but sometimes the restart fails and the service remains/hangs in Stopping state and the EXE process has to be killed manually. It looks likely that it hangs on line _ESSServiceHost.Close();, because nothing after that line is logged it the log file. It is possible but not very likely that the service gets the stop request when it is busy.
Moreover the underlying process cannot be killed because it is dependent on services.exe, so only server restart works.
What could be wrong with this approach?
protected override void OnStop()
{
try
{
if (_ESSServiceHost != null)
{
_ESSServiceHost.Close();
_ESSServiceHost = null;
//Never reaches the following line
Tools.LogInfo("Services stopped.");
}
}
catch (Exception ex)
{
Tools.LogError(ex.Message);
}
This is how I stop the service:
private bool StopService(ServiceController scESiftServer)
{
int i = 0;
if (scESiftServer.Status == ServiceControllerStatus.Running)
{
try
{
scESiftServer.Stop();
}
catch (Exception ex)
{
Tools.LogEvent("Exception ...");
return false;
}
while (scESiftServer.Status != ServiceControllerStatus.Stopped && i < 120)
{
Thread.Sleep(1000);
scESiftServer.Refresh();
i++;
}
}
if (scESiftServer.Status != ServiceControllerStatus.Stopped)
{
//This line gets executed
Tools.LogEvent("Failed within 120 sec...");
return false;
}
else
{
Tools.LogEvent("OK ...");
}
return true;
}
Could something like this help?
var task = Task.Run(() => _ESSServiceHost.Close(TimeSpan.FromSeconds(299)));
if (!task.Wait(TimeSpan.FromSeconds(300)))
{
_ESSServiceHost.Abort();
}
But _ESSServiceHost.Abort() should be called internally by the Close method if needed.
Target framework is 4.5, installed is .NET 4.7.2.
Found out that probably the service hangs after series of malformed requests. Expected record type 'Version', found '71'. etc.
I have found in the svclog file that my service hangs after series of malformed request that happen on Saturday and Sunday at approx. 5:15 AM. The error messages were Expected record type 'Version', found '71'., Error while reading message framing format at position 0 of stream (state: ReadingVersionRecord). But I could not find the cause of theese malformed request series, so I tried to fix the service to withstand the "attack".
I have modified the OnStop method as follows:
protected override void OnStop()
{
try
{
if (_ESSServiceHost != null)
{
Tools.LogInfo("Stopping ESService.");
var abortTask = Task.Run(() => _ESSServiceHost.Abort());
var closeTask = Task.Run(() => _ESSServiceHost.Close(TimeSpan.FromSeconds(300)));
try
{
if (_ESSServiceHost.State == CommunicationState.Faulted)
{
Tools.LogInfo("ESSServiceHost.State == CommunicationState.Faulted");
if (!abortTask.Wait(TimeSpan.FromSeconds(60)))
Tools.LogInfo("Failed to Abort.");
}
else
{
if (!closeTask.Wait(TimeSpan.FromSeconds(301)))
{
Tools.LogInfo("Failed to Close - trying Abort.");
if (!abortTask.Wait(TimeSpan.FromSeconds(60)))
Tools.LogInfo("Failed to Abort.");
}
}
}
catch (Exception ex)
{
Tools.LogException(ex, "ESSServiceHost.Close");
try
{
Tools.LogInfo("Abort.");
if (!abortTask.Wait(TimeSpan.FromSeconds(60)))
Tools.LogInfo("Failed to Abort.");
}
catch (Exception ex2)
{
Tools.LogException(ex2, "ESSServiceHost.Abort");
}
}
_ESSServiceHost = null;
Tools.LogInfo("ESService stopped.");
}
}
catch (Exception ex)
{
Tools.LogException(ex,"OnStop");
}
}
Today on Monday I have checked the svclog and the "attacks" with malformed request remained there but my service lived happily through it. So it seemed to be fixed. Moreover only:
Stopping ESService.
ESService stopped.
events were logged in my log file. No aborts etc. So I guess that putting the Close call on a separate thread fixed the problem but absolutely do not know why.
I still getting the same error on every device I have while using SQLite:
"System.DllNotFoundException: /system/lib/libsqlite.so occurred"
It always happens on this line:
var r = SQLite3.Open (databasePathAsBytes, out handle, (int) openFlags, IntPtr.Zero);
What can I do?
EDIT: Is this function correct used???:
public bool CreateDatabase()
{
try
{
using (var connection = new SQLiteConnection(System.IO.Path.Combine(folder, "CryptoSimulator.db")))
{
connection.CreateTable<Portfolio>();
connection.CreateTable<Wallet>();
connection.CreateTable<Assignments>();
return true;
}
}
catch(SQLiteException ex)
{
Log.Info("SQLiteEx", ex.Message);
return false;
}
}
i did have a same problem try to downgrade your Xamarin if you are on Windows but mac seems to be stable
I am using the Map functionality of Windows Phone 8.1 to find a route with the following code:
MapRouteFinderResult routeResult = null;
try
{
if (true == typeOfTransport.Equals(GlobalDeclarations.TypeOfTransport.Walk))
{
routeResult = await MapRouteFinder.GetWalkingRouteAsync(startPoint, endPoint);
}
else
{
routeResult = await MapRouteFinder.GetDrivingRouteAsync(startPoint, endPoint, MapRouteOptimization.Time, MapRouteRestrictions.None, 290);
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
The problem is that despite the try-catch, this MapRouteFinder.GetWalkingRouteAsync method crashes with an exception: Object not set to an instance of an object. Both startPoint and endPoint params are obviously not null, and filled with data. Why is this? And why the whole app crashes instead of catching the exception in the try-catch section?
using IPC over local TCP to communicate from Client to a Server thread. The connection itself doesn't seem to be throwing any errors, but every time I try to make one of the associated calls, I get this message:
System.Runtime.Remoting.RemotingException: Could not connect to an IPC Port: The System cannot Find the file specified
What I am attempting to figure out is WHY. Because this WAS working correctly, until I transitioned the projects in question (yes, both) from .NET 3.5 to .NET 4.0.
Listen Code
private void ThreadListen()
{
_listenerThread = new Thread(Listen) {Name = "Listener Thread", Priority = ThreadPriority.AboveNormal};
_listenerThread.Start();
}
private void Listen()
{
_listener = new Listener(this);
LifetimeServices.LeaseTime = TimeSpan.FromDays(365);
IDictionary props = new Hashtable();
props["port"] = 63726;
props["name"] = "AGENT";
TcpChannel channel = new TcpChannel(props, null, null);
ChannelServices.RegisterChannel(channel, false);
RemotingServices.Marshal(_listener, "Agent");
Logger.WriteLog(new LogMessage(MethodBase.GetCurrentMethod().Name, "Now Listening for commands..."));
LogEvent("Now Listening for commands...");
}
Selected Client Code
private void InitializeAgent()
{
try
{
_agentController =
(IAgent)RemotingServices.Connect(typeof(IAgent), IPC_URL);
//Note: IPC_URL was originally "ipc://AGENT/AGENT"
// It has been changed to read "tcp://localhost:63726/Agent"
SetAgentPid();
}
catch (Exception ex)
{
HandleError("Unable to initialize the connected agent.", 3850244, ex);
}
}
//This is the method that throws the error
public override void LoadTimer()
{
// first check to see if we have already set the agent process id and set it if not
if (_agentPid < 0)
{
SetAgentPid();
}
try
{
TryStart();
var tries = 0;
while (tries < RUNCHECK_TRYCOUNT)
{
try
{
_agentController.ReloadSettings();//<---Error occurs here
return;
} catch (RemotingException)
{
Thread.Sleep(2000);
tries++;
if (tries == RUNCHECK_TRYCOUNT)
throw;
}
}
}
catch (Exception ex)
{
HandleError("Unable to reload the timer for the connected agent.", 3850243, ex);
}
}
If you need to see something I haven't shown, please ask, I'm pretty much flying blind here.
Edit: I think the issue is the IPC_URL String. It is currently set to "ipc://AGENT/AGENT". The thing is, I have no idea where that came from, why it worked before, or what might be stopping it from working now.
Update
I was able to get the IPC Calls working correctly by changing the IPC_URL String, but I still lack understanding of why what I did worked. Or rather, why the original code stopped working and I needed to change it in the first place.
The string I am using now is "tcp://localhost:63726/Agent"
Can anyone tell me, not why the new string works, I know that...but Why did the original string work before and why did updating the project target to .NET 4.0 break it?
I have been trying to develop my Windows Phone 8 app to access a paired Bluetooth device (a printer) and send over some print data.
I'm developing on Windows 8 64bit and using VS2012 Express.
Due to the Emulator not supporting Bluetooth I have been uploading the build to a Nokia Lumia 820 for testing purposes.
I have used the following two sites for references:
http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj207007(v=vs.105).aspx
http://www.geekchamp.com/articles/getting-started-with-bluetooth-in-windows-phone-8
The App finds the pair device and ouputs the printer name by the Debug command.
The code works up until the point:
await socket.ConnectAsync(selectedDevice.HostName, "1");
And then it breaks with the following exception:
********** EXCEPTION OCCURED **********
Data: System.Collections.ListDictionaryInternal
InnerException:
Message: An attempt was made to access a socket in a way forbidden by its access permissions. (Exception from HRESULT: 0x8007271D)
StackTrace: at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
at mobility.PrinterSettings.<AppToDevice>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<ThrowAsync>b__0(Object state)
********** EXCEPTION OCCURED **********
If a remove "await" before socket.ConnectAsync(selectedDevice.HostName, "1"); then the code will continue without any errors but no Bluetooth connection is made?
I have tried every number from 1 to 30 as it states in the tutorials and I have also made sure that ID_CAP_NETWORKING is enabled in WMAppManifest.xml.
Please does anybody have any idea's?
Full code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Windows.Networking.Proximity;
using System.Diagnostics;
using Windows.Networking.Sockets;
using Microsoft.Phone.Tasks;
using System.Text;
using Windows.Storage.Streams;
namespace mobility
{
public partial class PrinterSettings : PhoneApplicationPage
{
public PrinterSettings()
{
InitializeComponent();
PrinterName.Text = App.loadString("PrinterName");
if (PrinterName.Text == null || PrinterName.Text == "")
{
PrinterName.Text = "QL420";
}
}
private void Save_Click(object sender, RoutedEventArgs e)
{
if (PrinterName.Text != null && PrinterName.Text != "")
{
App.saveString(PrinterName.Text, "PrinterName");
MessageBox.Show("Printer Name has been saved.");
}
else
{
MessageBox.Show("Error: The Printer Name appears to be missing.");
}
}
private async void AppToDevice()
{
try
{
// Configure PeerFinder to search for all paired devices.
PeerFinder.AlternateIdentities["Bluetooth:Paired"] = "";
var pairedDevices = await PeerFinder.FindAllPeersAsync();
if (pairedDevices.Count == 0)
{
MessageBox.Show("No paired devices were found.");
}
else
{
// Select a paired device. In this example, just pick the first one.
PeerInformation selectedDevice = pairedDevices[0];
// Attempt a connection
Debug.WriteLine(selectedDevice.DisplayName); // Make sure we are trying to connect to the correct device.
//Debug.WriteLine(selectedDevice.HostName.RawName);
//Debug.WriteLine(selectedDevice.HostName.IPInformation.NetworkAdapter.NetworkAdapterId.ToString());
//Debug.WriteLine(selectedDevice.ServiceName);
StreamSocket socket = new StreamSocket();
// Make sure ID_CAP_NETWORKING is enabled in your WMAppManifest.xml, or the next
// line will throw an Access Denied exception.
// In this example, the second parameter of the call to ConnectAsync() is the RFCOMM port number, and can range
// in value from 1 to 30.
await socket.ConnectAsync(selectedDevice.HostName, "1");
string newLabel = App.loadString("Template");
newLabel = newLabel.Replace("$n", "\n");
string epl = App.loadString("PrintHeader");
epl = epl + newLabel;
Debug.WriteLine(epl);
var data = GetBufferFromByteArray(Encoding.UTF8.GetBytes(epl));
//socket.OutputStream.WriteAsync(data);
MessageBox.Show("Device Found.");
}
}
catch (Exception ex)
{
if ((uint)ex.HResult == 0x8007048F)
{
var result = MessageBox.Show("Bluetooth is turned off. To see the current Bluetooth settings tap 'ok'", "Bluetooth Off", MessageBoxButton.OKCancel);
if (result == MessageBoxResult.OK)
{
ShowBluetoothcControlPanel();
}
}
else if ((uint)ex.HResult == 0x80070005)
{
MessageBox.Show("To run this app, you must have ID_CAP_PROXIMITY enabled in WMAppManifest.xaml");
}
else
{
MessageBox.Show(ex.Message);
Debug.WriteLine(ex.StackTrace);
Debug.WriteLine(ex.HResult);
}
}
}
private IBuffer GetBufferFromByteArray(byte[] package)
{
using (DataWriter dw = new DataWriter())
{
dw.WriteBytes(package);
return dw.DetachBuffer();
}
}
private void ShowBluetoothcControlPanel()
{
ConnectionSettingsTask connectionSettingsTask = new ConnectionSettingsTask();
connectionSettingsTask.ConnectionSettingsType = ConnectionSettingsType.Bluetooth;
connectionSettingsTask.Show();
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
this.Dispatcher.BeginInvoke(() =>
{
AppToDevice();
});
}
}
}
After much playing around and resetting the phone back to its original state with no success.
I ticked "ID_CAP_PROXIMITY" in WMAppManifest.xml and it started working straight away!
It looks like the Error Code I had for "ID_CAP_PROXIMITY" was maybe wrong so here is an update in code plus a few more error messages I have come across since.
I hope this might help somebody that is having a similar issue.
catch (Exception ex)
{
if ((uint)ex.HResult == 0x8007048F)
{
var result = MessageBox.Show("Bluetooth is turned off.\nTo see the current Bluetooth settings tap 'ok'", "Bluetooth Off", MessageBoxButton.OKCancel);
if (result == MessageBoxResult.OK)
{
ShowBluetoothcControlPanel();
}
}
else if ((uint)ex.HResult == 0x8007271D)
{
//0x80070005 - previous error code that may be wrong?
MessageBox.Show("To run this app, you must have ID_CAP_PROXIMITY enabled in WMAppManifest.xaml");
}
else if ((uint)ex.HResult == 0x80072740)
{
MessageBox.Show("The Bluetooth port is already in use.");
}
else if ((uint)ex.HResult == 0x8007274C)
{
MessageBox.Show("Could not connect to the selected Bluetooth Device.\nPlease make sure it is switched on.");
}
else
{
//App.handleException(ex);
MessageBox.Show(ex.Message);
}
}