how to reconnect proximity on windows phone - windows-phone-8

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

Related

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.

Windows phone 8 LongListMultiSelector dynamically select items

How to dynamically (in code behind) select few items in Windows Phone Toolkit's LongListMultiSelector. The property SelectedItems has no setter.
My code:
private async void GetGenres()
{
var genres = await App.MusClient.GetGenresAsync();
var preferencedGenresIdsList = App.GetFromIsoStorage<List<string>>(App.GENRES_IDS_KEY_STRING);
GenresListBox.ItemsSource = genres;
foreach (var item in GenresListBox.ItemsSource)
{
if (preferencedGenresIdsList.Contains(((Genre)item).Id))
{
LongListMultiSelectorItem container = GenresListBox.ContainerFromItem(item) as LongListMultiSelectorItem;
if (container != null)
{
container.IsSelected = true;
}
}
}
if (genres.Result == null || genres.Count == 0)
{
MessageBox.Show("No results available");
}
}
I found solution
private async void GetGenres()
{
var genres = await App.MusClient.GetGenresAsync();
var preferencedGenresIdsList = App.GetFromIsoStorage<List<string>>(App.GENRES_IDS_KEY_STRING);
GenresListBox.ItemsSource = genres;
foreach (var item in GenresListBox.ItemsSource)
{
if (preferencedGenresIdsList.Contains(((Genre)item).Id))
{
GenresListBox.ScrollTo(item);
LongListMultiSelectorItem container = GenresListBox.ContainerFromItem(item) as LongListMultiSelectorItem;
if (container != null)
{
container.IsSelected = true;
}
}
}
GenresListBox.ScrollTo(GenresListBox.ItemsSource[0]);
if (genres.Result == null || genres.Count == 0)
{
MessageBox.Show("No results available");
}
}
Reason it didn't work is because item is not created on UI yet.
GenresListBox.ScrollTo(item); - forces UI to create element!

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.