StackOverflow exception - exception

I am using DDE client to attach and listen stock market prices. That client has a callback method I implemented what to do when it receives price changes. The problem is that I get StackOverflowException (periodically and not at the same time interval). I found something about Thread.BeginCriticalRegion(), but I'm not sure if it would help. I have a few more hours until market opening when I can test it.
I would be more than greatful if someone could give me an idea how to override this exception.
Thanks in advance,
Aleksandar
IList<SymbolObject> _symbols; //initialized when the app runs for the first time
void _ddeClient_Advise(object sender, DdeAdviseEventArgs args)
{
if (!IsReady)
return;
if (string.IsNullOrEmpty(args.Text))
{
_logMessages.LogMessagesAdd("advise dde symbol", string.Format("args.Text is empty or NULL for {0}", args.Item), true);
return;
}
try
{
string[] argsArray = args.Text.Replace("\0", "").Replace('\0'.ToString(), "").Split(' '); // sometimes happens here
var list = _symbols.Where(s => s.DDESymbol == args.Item).ToList();
if (list.Count == 0)
return;
decimal? val = null;
try
{
var stringParts = StringUtils.CleanProphitXUrl(argsArray[0]).Split('.');
argsArray = null;
if (stringParts.Length >= 2)
val = decimal.Parse(stringParts[0] + "." + (stringParts[1].Length > 2 ? stringParts[1].Substring(0, 2) : stringParts[1]));
else
val = decimal.Parse(stringParts[0]);
stringParts = null;
}
catch (Exception ex)
{
_logMessages.LogMessagesAdd("call Price Alerts application service", ex.Message, true);
return;
}
foreach (var l in list)
{
if (_lastPrices[l.DDESymbol] == null)
continue;
if (_lastPrices[l.DDESymbol].ToString() != val.ToString())
{
try
{
_quotePublishingService.PublishQuote(l.DDESymbolId, l.Symbol, args.Item, val, WebSyncPublisherUrl,
PublishingChannel); // a call to wcf service
}
catch (Exception ex)
{
_logMessages.LogMessagesAdd("call the service", ex.Message, true); // save to sql db
return;
}
_lastPrices[l.DDESymbol] = val.ToString();
}
}
list = null;
val = null;
}
catch
{
}
}
public static string CleanProphitXUrl(string value) // StringUtils.CleanProphitXUrl snippet
{
StringBuilder sb = new StringBuilder();
sb.Append(value.Substring(0, value.LastIndexOf(".") + 1));
try
{
value = value.Replace('\r'.ToString(), "").Replace('\t'.ToString(), "").Replace('\n'.ToString(), "");
for (int i = sb.Length; i < value.Length; i++)
{
if (char.IsNumber(value[i]))
sb.Append(value[i]);
}
}
catch
{
}
return sb.ToString();
}

A StackOverflowException is caused by making to many method calls usually resulting from unintended recursion. Based on a cursory check of the code you posted I do not believe it is the culprit. The problem likely lies somewhere else.

Related

How to send JSON objects to another computer?

Using Websockets, I am able to use 1 computer and 1 kinect v2.0 to generate JSON objects of the joints x,y, and z coordinates in real-time. The next steps is to have this data transferred to another computer, using possibly TCP/IP network. My question is to anyone who knows how this is done. Having this data transferred to another computer.
Output that needs to be transferred to another computer in real-time
namespace WebSockets.Server
{
class Program
{
// Store the subscribed clients.
static List<IWebSocketConnection> clients = new List<IWebSocketConnection>();
// Initialize the WebSocket server connection.
static Body[] bodies = new Body[6];
//static KinectSensor kinectSensor = null;
static CoordinateMapper _coordinateMapper;
static Mode _mode = Mode.Color;
static void Main(string[] args)
{
//const string SkeletonStreamName = "skeleton";
//SkeletonStreamMessage skeletonStreamMessage;// = new SkeletonStreamMessage { stream = SkeletonStreamName };
KinectSensor kinectSensor = KinectSensor.GetDefault();
BodyFrameReader bodyFrameReader = null;
bodyFrameReader = kinectSensor.BodyFrameSource.OpenReader();
ColorFrameReader colorFrameReader = null;
colorFrameReader = kinectSensor.ColorFrameSource.OpenReader();
_coordinateMapper = kinectSensor.CoordinateMapper;
kinectSensor.Open();
WebSocketServer server = new WebSocketServer("ws://localhost:8001");
server.Start(socket =>
{
socket.OnOpen = () =>
{
// Add the incoming connection to our list.
clients.Add(socket);
};
socket.OnClose = () =>
{
// Remove the disconnected client from the list.
clients.Remove(socket);
};
socket.OnMessage = message =>
{
if (message == "get-video")
{
int NUMBER_OF_FRAMES = new DirectoryInfo("Video").GetFiles().Length;
// Send the video as a list of consecutive images.
for (int index = 0; index < NUMBER_OF_FRAMES; index++)
{
foreach (var client in clients)
{
string path = "Video/" + index + ".jpg";
byte[] image = ImageUtil.ToByteArray(path);
client.Send(image);
}
// We send 30 frames per second, so sleep for 34 milliseconds.
System.Threading.Thread.Sleep(270);
}
}
else if (message == "get-bodies")
{
if (kinectSensor.IsOpen)
{
if (bodyFrameReader != null)
{
bodyFrameReader.FrameArrived += bodyFrameReader_FrameArrived;
}
}
}
else if (message == "get-color")
{
if (kinectSensor.IsOpen)
{
if (colorFrameReader != null)
{
colorFrameReader.FrameArrived += colorFrameReader_FrameArrived;
}
}
}
};
});
// Wait for a key press to close...
Console.ReadLine();
kinectSensor.Close();
}
private static void colorFrameReader_FrameArrived(object sender, ColorFrameArrivedEventArgs e)
{
//throw new NotImplementedException();
using (ColorFrame colorFrame = e.FrameReference.AcquireFrame()) {
if (colorFrame != null) {
var blob = colorFrame.Serialize();
foreach (var client in clients)
{
if (blob != null)
{
client.Send(blob);
Console.WriteLine("After color Blob sent");
}
}
}
}
}
private static void bodyFrameReader_FrameArrived(object sender, BodyFrameArrivedEventArgs e)
{
//throw new NotImplementedException();
bool dataReceived = false;
using (BodyFrame bodyFrame = e.FrameReference.AcquireFrame())
{
if (bodyFrame != null)
{
if (bodies == null)
{
bodies = new Body[bodyFrame.BodyCount];
}
// The first time GetAndRefreshBodyData is called, Kinect will allocate each Body in the array.
// As long as those body objects are not disposed and not set to null in the array,
// those body objects will be re-used.
bodyFrame.GetAndRefreshBodyData(bodies);
dataReceived = true;
}
}
if (dataReceived)
{
foreach (var client in clients)
{
var users = bodies.Where(s => s.IsTracked.Equals(true)).ToList();
if (users.Count>0){
string json = users.Serialize(_coordinateMapper, _mode);
Console.WriteLine("jsonstring: " + json);
Console.WriteLine("After body serialization and to send");
}
}
}
}
}
}
Try changing it from
WebSocketServer server = new WebSocketServer("ws://localhost:8001");
to
WebSocketServer server = new WebSocketServer(" ws://192.168.X.X:8001");
on the client end. Enter the IP address of the client computer and make sure both server and client are on the same network.

Smack - Request MAM faling

I'm using this code with ejabberd 15 and now is updated to 17.04 and now when I ask for MAM this just fails.
private MamQueryResult queryArchive(MamQueryIQ mamQueryIq, long extraTimeout) throws NoResponseException, XMPPErrorException, NotConnectedException {
if (extraTimeout < 0) {
throw new IllegalArgumentException("extra timeout must be zero or positive");
}
final XMPPConnection connection = connection();
MamFinExtension mamFinExtension;
PacketCollector finMessageCollector = connection.createPacketCollector(new MamMessageFinFilter(
mamQueryIq));
PacketCollector.Configuration resultCollectorConfiguration = PacketCollector.newConfiguration().setStanzaFilter(
new MamMessageResultFilter(mamQueryIq)).setCollectorToReset(
finMessageCollector);
PacketCollector resultCollector = connection.createPacketCollector(resultCollectorConfiguration);
try {
//this line works fine. send and IQ and the response is received
connection.createPacketCollectorAndSend(mamQueryIq).nextResultOrThrow();
//This line trigger an exceptions NoResponseException
Message mamFinMessage = finMessageCollector.nextResultOrThrow(connection.getPacketReplyTimeout() + extraTimeout);
mamFinExtension = MamFinExtension.from(mamFinMessage);
}
catch(Exception e) {
Log.d(Constants.TAG_DEBUG, e.getMessage(), e);
throw e;
}
finally {
resultCollector.cancel();
finMessageCollector.cancel();
}
List<Forwarded> messages = new ArrayList<>(resultCollector.getCollectedCount());
for (Message resultMessage = resultCollector.pollResult(); resultMessage != null; resultMessage = resultCollector.pollResult()) {
// XEP-313 ยง 4.2
MamResultExtension mamResultExtension = MamResultExtension.from(resultMessage);
messages.add(mamResultExtension.getForwarded());
}
return new MamQueryResult(messages, mamFinExtension, DataForm.from(mamQueryIq));
}

Object Synchronization method was called from unsynchronized block while using Mutex

I am Trying to create a Windows Universal App with a Background Task.
I am trying to Write a Background task that Triggers Upon an Incoming bluetooth connection.
To prevent both the foreground and background from creating a connection. I am trying to implement the Same Mutex in Both the Foreground and Background.
When I read the Data from the Bluetooth Device I am getting the Following Error.
Object Synchronization method was called from unsynchronized block
To my Surprise this Error comes Occasionally . Am I missing Something ?
Here's My Code :
public sealed class RFBackgroundTask : IBackgroundTask
{
.... Variable declarations
public async void Run(IBackgroundTaskInstance taskInstance)
{
BackgroundTaskDeferral deferral = taskInstance.GetDeferral();
try
{
taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);
Debug.WriteLine("RFComm Task Running");
hotwatchConnection = taskInstance.TriggerDetails as RfcommConnectionTriggerDetails;
socket = hotwatchConnection.Socket;
reader = new DataReader(socket.InputStream);
// n = new Notification(hotwatchConnection.RemoteDevice.HostName);
await Read();
}
catch (System.Exception e)
{
Debug.WriteLine("RFComm Task Error: {0}", e.Message);
if (ismutexReleased == false)
{
Debug.WriteLine("Releaseing mutex because of error {0}:", e.Message);
connectionMutex.ReleaseMutex();
ismutexReleased = true;
}
}
finally
{
if (ismutexReleased == false)
{
Debug.WriteLine("Releasing Mutex 2");
connectionMutex.ReleaseMutex();
}
ismutexReleased = true;
}
deferral.Complete();
}
public IAsyncAction Read()
{
return Task.Run(async () =>
{
try
{
connectionMutex = new Mutex(false, CONNECTION_MUTEX_NAME);
// Attempt to wait for the mutex
var waitResult = connectionMutex.WaitOne();
if (waitResult)
{
Debug.WriteLine("Aquired Mutex Successfully");
}
// If the wait was not successful, fail the connect operation
if (!waitResult) { throw new TimeoutException(); }
if (reader != null)
{
uint length = 500;
reader.InputStreamOptions = InputStreamOptions.Partial;
uint len = await reader.LoadAsync(length);
String message = reader.ReadString(len);
Debug.WriteLine("Read " + message + " In the First Attemnpt");
var roamingSettings = Windows.Storage.ApplicationData.Current.RoamingSettings;
roamingSettings.Values["COMMAND"] = message;
//if(!message.StartsWith("01"))
//{
// await ProcessCommand(message);
//}
}
reader.Dispose();
socket.Dispose();
socket = null;
if (waitResult == true)
connectionMutex.ReleaseMutex();
ismutexReleased = true;
Debug.WriteLine("Released Mutex successfully after reading data");
}
catch (Exception e)
{
Debug.WriteLine(e.Message);
if (ismutexReleased == false)
{
Debug.WriteLine("Releaseing mutex because of error {0}:", e.Message);
connectionMutex.ReleaseMutex();
ismutexReleased = true;
}
throw;
}
finally
{
if (ismutexReleased == false)
{
connectionMutex.ReleaseMutex();
Debug.WriteLine("Releasing Mutex");
}
ismutexReleased = true;
}
}).AsAsyncAction();
}
}
The Mutex must be released on the same thread that it was acquired.
When you await an async method you are returned to the same context, you are not guaranteed to be returned to the same thread.
Use a Semaphore instead.

How to do page navigation from non-derived PhoneApplicationPage Windows phone 8

I'm new to Windows phone 8 development. I'm trying to navigate from my AzureFunctions class to another page but I always get this error
Object reference not set to an instance of an object.
I have googled but still can't find any solution. Do you guys have any idea how to achieve this?
My RegisterPage (where I called InsertData method in AzureFunctions class)
private void signUp_button_Click(object sender, RoutedEventArgs e)
{
if (email_validation && password_validation && confirmPassword_validation == true)
{
new AzureFunctions().InsertData(new UserInfo_Table_Azure()
{
Email = regisEmail_textBox.Text,
Password = regisPassword_textBox.Password,
DOB = (DateTime)DOB_picker.Value,
UserCancerInfo = (Boolean)userCancerInfo_checkBox.IsChecked,
FamilyCancerInfo = (Boolean)userFamilyCancerInfo_checkBox.IsChecked
});
}
else
{
String errorMsg = "";
if (email_validation == false)
{
errorMsg += "Your email is not valid\r\n";
regisEmail_textBox.BorderBrush = new SolidColorBrush(Colors.Red);
}
if (password_validation == false)
{
errorMsg += "Your password can't be empty\r\n";
regisPassword_textBox.BorderBrush = new SolidColorBrush(Colors.Red);
}
if (confirmPassword_validation == false)
{
errorMsg += "Your Confirm password and password aren't matched";
comfirmPassword_textBox.BorderBrush = new SolidColorBrush(Colors.Red);
}
MessageBox.Show(errorMsg);
}
}
My AzureFunctions Class
public async void InsertData(object data)
{
try
{
SystemFunctions.SetProgressIndicatorProperties(true);
SystemTray.ProgressIndicator.Text = "Registering...";
//Check type of data
if (IsUserInfo_Data(data))
{
//Insert data into UserInfo_Table
await azure_userInfo_table.InsertAsync((UserInfo_Table_Azure)data);
Debug.WriteLine("Success inserting data to azure");
SystemFunctions.SetProgressIndicatorProperties(false);
MessageBoxResult result = MessageBox.Show(AppResources.RegisterSuccessfully, AppResources.Congratulation, MessageBoxButton.OK);
if (result == MessageBoxResult.OK)
{
try
{
new RegisterPage().NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
}
catch (NullReferenceException e)
{
Debug.WriteLine(e.Message);
}
}
}
else if (IsPoop_Data(data))
{
//Insert data into Poop_Table
await azure_poop_table.InsertAsync((Poop_Table_Azure)data);
Debug.WriteLine("Success");
}
}
catch (MobileServiceInvalidOperationException e)
{
SystemFunctions.SetProgressIndicatorProperties(false);
Debug.WriteLine("Failed: " + e.Message);
}
}
Not really a good idea to do navigation from a non-Page, but this should work
App.RootFrame.Navigate(...)

Receive data from arduino through bluetooth in windows phone 8

i found this example(https://developer.nokia.com/Community/Wiki/Windows_Phone_8_communicating_with_Arduino_using_Bluetooth) in my research to develop a bluetooth console to windows phone 8. This example work very well, except for the TERMINATE function. When i call TERMINATE function, the ReceiveMessages function still trying receive data, but there is no more socket available and it generate a system.exception. I tried a lot of workaround, but i dont have enough experience with C#, this is my first APP. Anyone know how can i workaround this situation or have a better example?
i did only 1 modificiation:
private async void AppToDevice()
{
if (!connected)
{
ConnectAppToDeviceButton.Content = "Connecting...";
PeerFinder.AlternateIdentities["Bluetooth:Paired"] = "";
var pairedDevices = await PeerFinder.FindAllPeersAsync();
if (pairedDevices.Count == 0)
{
Debug.WriteLine("No paired devices were found.");
}
else
{
foreach (var pairedDevice in pairedDevices)
{
if (pairedDevice.DisplayName == DeviceName.Text)
{
connectionManager.Connect(pairedDevice.HostName);
ConnectAppToDeviceButton.Content = "Disconnect";
DeviceName.IsReadOnly = true;
//ConnectAppToDeviceButton.IsEnabled = false;
continue;
}
}
}
}
else
{
connectionManager.Terminate();
ConnectAppToDeviceButton.Content = "Connect";
}
}
I found a solution here:
WinRT: DataReader.LoadAsync Exception with StreamSocket TCP
I did only a few modifications:
public void Terminate()
{
try
{
if (socket != null)
{
taskLoadLength.Cancel();
taskLoadLength.Close();
taskLoadMessage.Cancel();
taskLoadMessage.Close();
socket.Dispose();
dataReadWorker.CancelAsync();
dataReader.Dispose();
dataWriter.Dispose();
isInicialized = false;
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
private void ReceiveMessages(object sender, DoWorkEventArgs ev)
{
while (true)
{
try
{
// Read first byte (length of the subsequent message, 255 or less).
//uint sizeFieldCount = await dataReader.LoadAsync(1);
taskLoadLength = dataReader.LoadAsync(1);
taskLoadLength.AsTask().Wait();
uint sizeFieldCount = taskLoadLength.GetResults();
if (sizeFieldCount != 1)
{
// The underlying socket was closed before we were able to read the whole data.
return;
}
// Read the message.
uint messageLength = dataReader.ReadByte();
taskLoadMessage = dataReader.LoadAsync(messageLength);
taskLoadMessage.AsTask().Wait();
uint actualMessageLength = taskLoadMessage.GetResults();
//uint actualMessageLength = await dataReader.LoadAsync(messageLength);
if (messageLength != actualMessageLength)
{
// The underlying socket was closed before we were able to read the whole data.
return;
}
// Read the message and process it.
string message = dataReader.ReadString(actualMessageLength);
MessageReceived(message);
}
catch (AggregateException ae)
{
MessageBox.Show(ae.Message);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
}