Peerfinder.Start() gives System.UnauthorizedAccessException - c#

I just started playing with bluetooth communication on WP8.
I found a example here: http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj207007(v=vs.105).aspx
But as soon as Peerfinder.Start() is hit, i get this error:
A first chance exception of type 'System.UnauthorizedAccessException' occurred in PhoneApp3.DLL
public MainPage()
{
InitializeComponent();
PeerFinder.Start();
}
async private void AppToApp_Click(object sender, RoutedEventArgs e)
{
// PeerFinder.Start() is used to advertise our presence so that peers can find us.
// It must always be called before FindAllPeersAsync.
var peers = await PeerFinder.FindAllPeersAsync();
if (peers.Count == 0)
{
Debug.WriteLine("Peer not found.");
}
else
{
Debug.WriteLine(peers.Count + " peers found");
}
}

Make sure you've added the capabilities ID_CAP_PROXIMITY and ID_CAP_NETWORKING to your application manifest.

Related

Exception thrown when I pass the appropriate argument to method

I am reviewing source code of a voice chat application.
Here I want to run server program, so that any client can contact to server for voice chat. To run my server program I have to pass server name , port number and network interface that I am going to use for voice chat, after passing required arguments I have to call ServerStart method which is done by clicking on Start Checkbox in design view.If user has not passed appropriate type of arguments then it shows error by calling method ShowError().
Now, When I pass serverName, port number and Network Interface then serverName variable reference to null instead of the passed serverName argument.
Why An exception is thrown when I run server program that exception is "The source was not found, but some or all events logs could not be searched. Inaccessible logs: Security."
public partial class ServerWindow
{
private ChatServer server;
public delegate void SetListBoxItem(string str, string type);
public ServerWindow()
{
InitializeComponent();
ObtainNetworkInterfaces();
}
private void cbStartStop_Checked(object sender, RoutedEventArgs e)
{
if (cbStartStop.IsChecked == true)
{
// validate the port number
try
{
var port = Int32.Parse(tbPortNumber.Text);
server = new ChatServer(port, cbInterfaces.SelectedItem, tbServerName.Text);
server.ClientConnected += ServerOnClientConnected;
server.ClientDisconnected += ServerOnClientDisconnected;
var serverName = tbServerName.Text;
if (string.IsNullOrWhiteSpace(serverName))
{
ShowError();
}
else
{
server.StartServer();
SetControls(false);
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
else
{
if (server == null)
return;
server.StopServer();
SetControls(true);
}
}
private void ShowError()
{
MessageBox.Show(#"Please enter valid port number and/or server name");
cbStartStop.IsChecked = false;
}
The problem seems not to be in the code that you posted. After our chat I would suggest to look at this post try the accepted answer. I have the feeling it will solve your problem.
It is usually helpful to use the exception message in the catch clause. :)

Bing Maps GetRoute gives '0x8004231C' error

I'm trying to show a route from point-to-point on the bing-maps (testing on real device). I've entered 2 waypoints (GeoCoordinate) and I'm trying to get the route via the Windows PhoneToolKit using the await query.GetRouteAsync(). Unfortunately, I'm getting an unknown error:
The result of the async call:
'e.Result' threw an exception of type 'System.Reflection.TargetInvocationException'
The inner exception:
Exception from HRESULT: 0x8004231C
I've checked the MSDN website and noticed that this errorcode is not listed in the errorlist...
The related code is below. I've used the exact same code as in the sample set of the Windows Phone Toolkit, but removed the things which has nothing to do with getting the route:
private async void BtnShowRoute_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
try
{
RouteQuery query = new RouteQuery();
List<GeoCoordinate> wayPoints = new List<GeoCoordinate>();
wayPoints.Add(new GeoCoordinate(47.23449, -121.172447));
wayPoints.Add(new GeoCoordinate(47.062638, -120.691795));
query.Waypoints = wayPoints;
Route route = await query.GetRouteAsync();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
throw;
}
}
I have no idea what is going wrong here. Does anyone else experienced this issue? If so, did you resolve it? And how?
Note: I'm running Windows Phone 8.1. Dev Preview
This happens when the underlying service call times out before completing the query. Hopefully this will be fixed in next version , but for now you can use following code:
private async void BtnShowRoute_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
RouteQuery query = new RouteQuery();
List<GeoCoordinate> wayPoints = new List<GeoCoordinate>();
wayPoints.Add(new GeoCoordinate(47.23449, -121.172447));
wayPoints.Add(new GeoCoordinate(47.062638, -120.691795));
query.Waypoints = wayPoints;
query .QueryCompleted += geoQ_QueryCompleted;
query.GetRouteAsync();
}
private void geoQ_QueryCompleted(object sender, QueryCompletedEventArgs<Route> e)
{
try
{
Route myRoute = e.Result;
}
catch (TargetInvocationException)
{
Thread.Sleep(1000); // waiting for completing the query
geoQ_QueryCompleted(sender, e);
}
}

ircDotNet bot fails to get messages from IRC channel, long login/logout

I'm trying to write bot for irc channel, which will read messages from channel, recognize if they are commands to him and do some actions depends on command which was send.
I've choose ircDotNet because it was the only library that contains some examples how to use it, but they are actually very outdated, only half of them works. My lack of experience in C# and in programming at all don't allows me to understand stuff without good examples :(
So what my program does now:
logs in to server using password
joins channel
log-outs (very buggy)
I cant capture and send any messages from and to a channel and i cant log-out instantly.
Global classes that used for login and IrcClient class exemplar used everywhere in events
public IrcRegistrationInfo irc_iri
{
get
{
return new IrcUserRegistrationInfo()
{
NickName = "jsBot",
UserName = "jsBot",
RealName = "jsBot",
Password = "oauth:p4$$w0rdH3Re48324729214812489"
};
}
}
public IrcClient gIrcClient = new IrcClient();
Also all current events:
private void Form1_Load(object sender, EventArgs e)
{
try
{
gIrcClient.Connected += ircClient_Connected;
gIrcClient.Disconnected += gIrcClient_Disconnected;
gIrcClient.FloodPreventer = new IrcStandardFloodPreventer(1, 10000);
}
catch (Exception ex) { MessageBox.Show(ex.ToString());}
}
Login button code:
private void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
if (!gIrcClient.IsConnected)
{
button1.Text = "Connecting...";
gIrcClient.Connect("irc.twitch.tv", 6667, false, irc_iri);
}
else
{
button1.Text = "Disconnecting...";
gIrcClient.Quit(5000, "bye");
}
}
Logic is: program checks if ircClient connected or not, and do some action. Then after that action appropriate event will raise, enable that button again. But that Quit function works very slow or don't works at all, bot will stay at channel until i don't close my program (maybe i need to dispose ircclient?)
Connect and disconnect events. In connect event, bot will join channel. Bot appears at channel after ~30 seconds after i press connect button, but connected event raised after 2-3 seconds. And same for disconnect - disconnect event raises quickly, but bot stays on channel for much longer time (about 120 seconds).
void ircClient_Connected(object sender, EventArgs e)
{
try
{
if (button1.InvokeRequired)
{
MethodInvoker del = delegate {
button1.Text = "Disconnect";
button1.Enabled = true; };
button1.Invoke(del);
}
else
{
button1.Text = "Disconnect";
button1.Enabled = true;
}
gIrcClient.Channels.Join("#my_channel");
gIrcClient.LocalUser.JoinedChannel += LocalUser_JoinedChannel;
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
}
void gIrcClient_Disconnected(object sender, EventArgs e)
{
if (!gIrcClient.IsConnected)
{
try
{
if (button1.InvokeRequired)
{
MethodInvoker del = delegate
{
button1.Text = "Connect";
button1.Enabled = true;
};
button1.Invoke(del);
}
else
{
button1.Text = "Connect";
button1.Enabled = true;
}
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
}
else gIrcClient.Disconnect();
}
Join channel and message received events. They are never raising, have no idea why.
void LocalUser_JoinedChannel(object sender, IrcChannelEventArgs e)
{
try
{
gIrcClient.Channels[0].MessageReceived += Form1_MessageReceived;
gIrcClient.LocalUser.SendMessage(e.Channel, "test");
MessageBox.Show(gIrcClient.Channels[0].Users[0].User.NickName);
MessageBox.Show("bot_join_channel_event_raised");
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
}
void Form1_MessageReceived(object sender, IrcMessageEventArgs e)
{
try
{
if (e.Text.Equals("asd"))
gIrcClient.LocalUser.SendMessage(e.Targets, "received");
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
}
So main question is: how do i catch messages from channel and how do i send message to channel? I would appreciate any examples. You can find all code in one piece here: http://pastebin.com/TBkfL3Vq
Thanks
You try to join channel before adding an event.
gIrcClient.Channels.Join("#my_channel");
gIrcClient.LocalUser.JoinedChannel += LocalUser_JoinedChannel;
My suggestion is try adding event first like this:
gIrcClient.LocalUser.JoinedChannel += LocalUser_JoinedChannel;
gIrcClient.Channels.Join("#my_channel");
There is a bug in the IRC.NET library and twitch.tv is using a non-standard message reply that is tripping up IRC.NET.
I have created a bug here describing it. But basically twitch sends "Welcome, GLHF!" as the RPL_WELCOME message. The IRC RFC describes the format of the message to be "Welcome to the Internet Relay Network !#".
IRC.NET parses GLHF out of the welcome message as your nick name, which is used for things like firing the JoinedChannel and MessageRecieved events.
My solution is to download the source code and to comment out where it sets the nick name when receiving the RPL_WELCOME message. It sets the Nickname correctly from the IrcRegistrationInfo passed into the IrcClient constructor and doesn't need to be parsed from the welcome message from twitch. Not sure if this is the case for other IRC servers.
The function is called ProcessMessageReplyWelcome in IrcClientMessageProcessing.cs:
/// <summary>
/// Process RPL_WELCOME responses from the server.
/// </summary>
/// <param name="message">The message received from the server.</param>
[MessageProcessor("001")]
protected void ProcessMessageReplyWelcome(IrcMessage message)
{
Debug.Assert(message.Parameters[0] != null);
Debug.Assert(message.Parameters[1] != null);
this.WelcomeMessage = message.Parameters[1];
// Extract nick name, user name, and host name from welcome message. Use fallback info if not present.
var nickNameIdMatch = Regex.Match(this.WelcomeMessage.Split(' ').Last(), regexNickNameId);
//this.localUser.NickName = nickNameIdMatch.Groups["nick"].GetValue() ?? this.localUser.NickName;
this.localUser.UserName = nickNameIdMatch.Groups["user"].GetValue() ?? this.localUser.UserName;
this.localUser.HostName = nickNameIdMatch.Groups["host"].GetValue() ?? this.localUser.HostName;
this.isRegistered = true;
OnRegistered(new EventArgs());
}
A more involved solution might be to refine the nick name Regex so it does not match on GLHF!, which I think is not a valid nickname.
IRC.NET uses case sensitive string comparisons for finding users by nickname. So the value you pass into the IrcRegistrationInfo for the nickname must match the casing that twitch uses in messages pertaining to you. Which is all lowercase.

Windows Phone 8 Bluetooth Error HRESULT: 0x8007271D

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

IOException I can’t catch

I have an application talking to a USB-GPS. It’s working as a charm if nothing out of the ordinary happnes. But I have a big problem. If the USB gets pulled out, my program (some times) crashes. I have Try/Catch where I need them but this IOExeption doesn’t get caught. I just get "The device does not recognize the command" and the program stops. Here is the code that starts the port:
public LatLongFromGPS(Form1 parent)
{
this.parent = parent;
String port;
this.SPort = new SerialPort(port, 4800);
this.SPort.ReadTimeout = 500;
this.SPort.DataReceived += new SerialDataReceivedEventHandler(dataReceived);
}
public bool checkIfPortsOpen()
{
return (this.SPort.IsOpen);
}
public void openPort()
{
try
{
if (!this.SPort.IsOpen)
{
this.SPort.Open();
}
}
catch(Exception ex)
{
parent.LoggIt.WriteLogg("OPENPORT " + ex.ToString(), Logger.LoggType.Debug);
}
}
public void dataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
if (SPort.IsOpen)
{
String GPGGAString;
Thread.CurrentThread.Join(200);
buffert = new char[this.SPort.BytesToRead];
this.SPort.Read(buffert, 0, buffert.Length);
GPGGAString = findStringFromGPS();
if (GPGGAString != null)
{
getLatitudefromString(GPGGAString);
getLongitudefromString(GPGGAString);
getTimeFromString(GPGGAString);
this.newData = true;
}
}
}
catch(Exception ex)
{
parent.LoggIt.WriteLogg("GPSERROR " + ex.ToString(), Logger.LoggType.Debug);
}
}
Then I have this in a Timer to check the info
if (this.LatLong.newDataReceived())
{
//DOING STUFF
}
if (!this.LatLong.checkIfPortsOpen())
this.LatLong.openPort();
Anyone have any suggestions how to stop the crashes?
[EDIT] The stack:
at System.IO.Ports.InternalResources.WinIOError(Int32, System.String)
at System.IO.Ports.InternalResources.WinIOError()
at System.IO.Ports.SerialStream.Dispose(Boolean)
at System.IO.Ports.SerialStream.Finalize()
I'm not entirely sure if it applies here, but there are mechanisms to catch overall crashes at the appdomain level -
http://msdn.microsoft.com/en-GB/library/system.appdomain.unhandledexception.aspx
(not the section on other events, e.g. ThreadException - these may need their own handlers depending on the situation)
Although not a best practice, top-level exception handling might solve your problem. See http://richnewman.wordpress.com/2007/04/07/top-level-exception-handling-in-windows-forms-applications-%E2%80%93-code-listing-1/ for an example.

Categories