How to do page navigation from non-derived PhoneApplicationPage Windows phone 8 - 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(...)

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.

How to print Arabic Text using bluetooth printer in windows phone 8 silver light app?

We need to print Arabic text using Bluetooth Printer in windows phone 8 silver light app. Printing is working fine for English When we are trying to print Arabic text it is not printing as expected? Sample code is given Below:
Public async void PrintTest(string text)
{
var isConnected= await RefreshPairedDevicesList()
if (isConnected)
{
try
{
if (_socket != null)
{
DataWriter writer = new DataWriter(_socket.OutputStream);
writer.WriteString(text);
writer.WriteBytes(Cmd_ESC_JN); // byte[] Cmd_ESC_JN = new byte[] { 27, 74, 230 };
writer.StoreAsync();
}
}
catch { }
}
}
public async Task<bool> RefreshPairedDevicesList()
{
try
{
PeerFinder.AlternateIdentities["Bluetooth:Paired"] = "";
var peers = await PeerFinder.FindAllPeersAsync();
if (peers == null && peers.Count == 0)
{
MessageBox.Show("NoPairedDevices");
return false;
}
else
{
// Found paired devices.
foreach (var peer in peers)
{
_pairedDevices.Add(new PairedDeviceInfo(peer));
}
PairedDeviceInfo connectedDeive = _pairedDevices.FirstOrDefault();
var issuccess = await ConnectToDevice(connectedDeive.PeerInfo);
return issuccess;
}
}
catch (Exception ex)
{
if ((uint)ex.HResult == 0x8007048F || (int)ex.HResult == -2147467259)
{
var result = MessageBox.Show(MyStoreWP8AppConstants.Msg_BluetoothOff, "Bluetooth Off", MessageBoxButton.OKCancel);
if (result == MessageBoxResult.OK)
{
ShowBluetoothcControlPanel();
}
return false;
}
else if ((uint)ex.HResult == 0x80070005)
{
MessageBox.Show(MyStoreWP8AppConstants.Msg_MissingCaps);
return false;
}
else
{
MessageBox.Show(ex.Message);
return false;
}
}
}
private async Task<bool> ConnectToDevice(PeerInformation peer)
{
if (_socket != null)
{
_socket.Dispose();
_socket = null;
}
try
{
_socket = new StreamSocket();
string serviceName = peer.ServiceName;
serviceName = String.IsNullOrWhiteSpace(serviceName) ? "1" : serviceName;
await _socket.ConnectAsync(peer.HostName, serviceName);
return true;
}
catch (TaskCanceledException taskEx)
{
return false;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
if (_socket != null)
_socket.Dispose();
_socket = null;
return false;
}
}
Could anyone please help us.
Thanks and Regards,
WinitWindowsTeam.

how to reconnect proximity on windows phone

i have two page...mainpage and proximitypage
first i goto proximitypage from mainpage.. and than i can create connection with anoher phone WP8,
if i go back to mainpage and than goto proximitypage again, i cant connect again..
im using code like this :
public asyc void proximity()
{
this._proximitydevice = ProximityDevice.GetDefault();
if (this._proximitydevice == null)
{
MessageBox.Show("Ponsel anda tidak didukung NFC!!!");
return;
}
PeerFinder.TriggeredConnectionStateChanged += PeerFinder_TriggeredConnectionStateChanged;
PeerFinder.Start();
}
void PeerFinder_TriggeredConnectionStateChanged(object sender, TriggeredConnectionStateChangedEventArgs args)
{
if (args.State == TriggeredConnectState.PeerFound)
{
WriteMessageText("Peer found. Keep your devices together until the connection is established.\n");
}
else if (args.State == TriggeredConnectState.Completed)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
PhoneApplicationService.Current.State["RemoteHostName"] = args.Socket.Information.RemoteHostName.RawName;
PhoneApplicationService.Current.State["RemoteServiceName"] = args.Socket.Information.RemoteServiceName;
LaunchGame(args.Socket);
});
}
else if (args.State == TriggeredConnectState.Failed || args.State == TriggeredConnectState.Canceled)
{
MessageBoxResult mb = MessageBox.Show("Tidak dapat terhubung dengan ponsel lain. \nIngin menghubungkan kembali ??", "Incuqu", MessageBoxButton.OKCancel);
if (mb != MessageBoxResult.OK)
{
//e.Cancel = true;
NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
}
else
{
PlayMultiplayer();
//Application.Current.Terminate();
}
}
}
i hope somebody can help...thanks

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.