Windows phone Argument Exception - windows-phone-8

I Got Error as "An exception of type 'System.ArgumentException' occurred in System.Windows.ni.dll but was not handled in user code"
void Touch_FrameReported(object sender, TouchFrameEventArgs e)
{
int pointsNumber = e.GetTouchPoints(img1).Count; \\ I got the Exception in this Line
TouchPointCollection pointCollection = e.GetTouchPoints(img1);
for (int i = 0; i < pointsNumber; i++)
{
if (pointCollection[i].Action == TouchAction.Down)
{
preXArray[i] = pointCollection[i].Position.X;
preYArray[i] = pointCollection[i].Position.Y;
}
if (pointCollection[i].Action == TouchAction.Move)
{
line = new Line();
line.X1 = preXArray[i];
line.Y1 = preYArray[i];
line.X2 = pointCollection[i].Position.X;
line.Y2 = pointCollection[i].Position.Y;
line.Stroke = new SolidColorBrush(Colors.White);
line.StrokeStartLineCap = PenLineCap.Round;
line.StrokeEndLineCap = PenLineCap.Round;
line.StrokeThickness = 20;
img1.Children.Add(line);
preXArray[i] = pointCollection[i].Position.X;
preYArray[i] = pointCollection[i].Position.Y;
}
}
}
How to Handle This Exception in Windows Phone 8

You need a try catch with catch blocks like this...
try { ... }
catch(System.ArgumentNullException ane) { ... }
catch(System.NotSupportedException nse) { ... }
catch(System.IO.PathTooLongException ple) { ... }
catch(System.IO.SecurityException se) { ... }
catch(System.ArgumentException ae) { ... }
Make sure your 'System.ArgumentException' is your last catch. Use the 4 above if need be, you might not need path handler...

Related

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);
}
}
}

StackOverflow 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.