UWP Bluetooth LE InvalidCastException - c#

i want to connect the myo wristband to the hololens. This is the end goal, but I am anyway but close to that :-/
The idea is to set up a Bluetooth LE Connection with UWP.
I wanted to do this, as explanined in this Microsoft Document
The search for the devices workes fine, but when I try to connect to a device, this line (Point "Connecting to the device"
): GattDeviceServicesResult result = await device.GetGattServicesAsync();
raises the error:
System.InvalidCastException: "Unable to cast object of type
'Windows.Devices.Bluetooth.BluetoothLEDevice' to type
'Windows.Devices.Bluetooth.IBluetoothLEDevice3'."
I have no idea what the IBluetoothLEDevice3 has to do there :-)
I was not able to find a solution for this on the microsoft documentation or the internet :-/
I work on Visual Studio 2017, build for Windows 10 (15063) and Bluetooth is enabled in the manifest.
This is my code so fare. I added only one thing and that is the Task. I wanted to make sure, that the BluetoothLEDDevice is not null or anything, since it is not synchron. Without its not working either.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using System.Diagnostics;
using Windows.Devices.Enumeration;
using Windows.Devices.Bluetooth;
using Windows.Devices.Bluetooth.GenericAttributeProfile;
using System.Threading.Tasks;
using Windows.Devices.Bluetooth.Advertisement;
// Die Elementvorlage "Leere Seite" wird unter https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x407 dokumentiert.
namespace Bluetooth17
{
/// <summary>
/// Eine leere Seite, die eigenständig verwendet oder zu der innerhalb eines Rahmens navigiert werden kann.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
blue();
}
void blue()
{
// Query for extra properties you want returned
string[] requestedProperties = { "System.Devices.Aep.DeviceAddress", "System.Devices.Aep.IsConnected" };
DeviceWatcher deviceWatcher =
DeviceInformation.CreateWatcher(
BluetoothLEDevice.GetDeviceSelectorFromPairingState(false),
requestedProperties,
DeviceInformationKind.AssociationEndpoint);
// Register event handlers before starting the watcher.
// Added, Updated and Removed are required to get all nearby devices
deviceWatcher.Added += DeviceWatcher_Added;
deviceWatcher.Updated += DeviceWatcher_Updated;
deviceWatcher.Removed += DeviceWatcher_Removed;
// EnumerationCompleted and Stopped are optional to implement.
deviceWatcher.EnumerationCompleted += DeviceWatcher_EnumerationCompleted;
deviceWatcher.Stopped += DeviceWatcher_Stopped;
// Start the watcher.
deviceWatcher.Start();
}
private void DeviceWatcher_Stopped(DeviceWatcher sender, object args)
{
Debug.WriteLine("Stopped");
}
private void DeviceWatcher_EnumerationCompleted(DeviceWatcher sender, object args)
{
Debug.WriteLine("Enum complete");
}
private void DeviceWatcher_Removed(DeviceWatcher sender, DeviceInformationUpdate args)
{
Debug.WriteLine(args.Id + " Removed");
}
private void DeviceWatcher_Updated(DeviceWatcher sender, DeviceInformationUpdate args)
{
Debug.WriteLine(args.Id + " Update");
}
private void DeviceWatcher_Added(DeviceWatcher sender, DeviceInformation args)
{
Debug.WriteLine(args.Id + " " + args.Name);
if (args.Name.Equals("Myo"))
{
Debug.WriteLine("Try to connect to Myo");
getServices(args);
}
}
async Task<BluetoothLEDevice> ConnectDevice(DeviceInformation deviceInfo)
{
Debug.WriteLine("Asyc");
// Note: BluetoothLEDevice.FromIdAsync must be called from a UI thread because it may prompt for consent.
return await BluetoothLEDevice.FromIdAsync(deviceInfo.Id);
}
async void getServices(DeviceInformation deviceInfo)
{
Task<BluetoothLEDevice> task = ConnectDevice(deviceInfo);
task.Wait();
BluetoothLEDevice device = task.Result;
GattDeviceServicesResult result = await device.GetGattServicesAsync();
if (result.Status == GattCommunicationStatus.Success)
{
var services = result.Services;
// ...
}
}
}
}
Thank you

If you target your application to Build 15063 and you know the device you are connecting to than just use:
device = await BluetoothLEDevice.FromBluetoothAddressAsync(blueToothAddress);
This is much more stable than your code and no need for device watcher.
Here is an example that works for my device(not a MIO but a HM10) :
using System;
using System.Diagnostics;
using Windows.Devices.Bluetooth;
using Windows.Devices.Bluetooth.GenericAttributeProfile;
using Windows.UI.Xaml.Controls;
namespace App1
{
public sealed partial class MainPage : Page
{
private BluetoothLEDevice device;
GattDeviceServicesResult serviceResult = null;
public MainPage()
{
this.InitializeComponent();
StartDevice();
}
private async void StartDevice()
{
//To get your blueToothAddress add: ulong blueToothAddress = device.BluetoothAddress to your old code.
ulong blueToothAddress = 88396936323791; //fill in your device address!!
device = await BluetoothLEDevice.FromBluetoothAddressAsync(blueToothAddress);
if (device != null)
{
string deviceName = device.DeviceInformation.Name;
Debug.WriteLine(deviceName);
int servicesCount = 3;//Fill in the amount of services from your device!!
int tryCount = 0;
bool connected = false;
while (!connected)//This is to make sure all services are found.
{
tryCount++;
serviceResult = await device.GetGattServicesAsync();
if (serviceResult.Status == GattCommunicationStatus.Success && serviceResult.Services.Count >= servicesCount)
{
connected = true;
Debug.WriteLine("Connected in " + tryCount + " tries");
}
if (tryCount > 5)//make this larger if faild
{
Debug.WriteLine("Failed to connect to device ");
return;
}
}
}
}
}
}

Related

How to convert a script(Capture Packets and save it to log file) into Window Service?

I want to write a window service for keep capturing the network traffic and save the packets info into a log file, but I can't start it.
"Error 1064: An exception occurred in the service when handling the control request."
References:
Capturing And Parsing Packets
Save Output to Log
Create Window Service
Here's the code for Windows Service(failed):
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using CapturingAndParsingPackets;
using PacketDotNet;
using SharpPcap;
namespace CaptureService
{
public partial class Service1 : ServiceBase
{
private static bool _stopCapturing;
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);//Get the desktop path
string filename = DateTime.Now.ToString("yyyy-MM-dd--HH-mm-ss");//Use date to name the file
public Service1()
{
InitializeComponent();
var devices = CaptureDeviceList.Instance; //Get the local devices
if (devices.Count < 1)
{
OnStop();
return;
}
}
protected override void OnStart(string[] args)
{
var devices = CaptureDeviceList.Instance; //Get the local devices
//set output type
var defaultOutputType = StringOutputType.Normal;
var outputTypeValues = Enum.GetValues(typeof(StringOutputType));
StringOutputType selectedOutputType = defaultOutputType;
int userSelectedOutputType;
userSelectedOutputType = 3;
selectedOutputType = (StringOutputType)userSelectedOutputType;
//read local device
var device = devices[3];
//read packets
var readTimeoutMilliseconds = 1000;
device.Open(DeviceModes.Promiscuous, readTimeoutMilliseconds);
//set filter
string filter = "host 192.168.0.212";
device.Filter = filter;
PacketCapture e;
var status = device.GetNextPacket(out e);
var rawCapture = e.GetPacket();
// use PacketDotNet to parse this packet and print out
// its high level information
var p = Packet.ParsePacket(rawCapture.GetLinkLayers(), rawCapture.Data);
// Create a log file to desktop and write the log into the log file
using (StreamWriter w = File.AppendText(path + "\\" + filename + ".log"))
{
Log(p.ToString(selectedOutputType) + p.PrintHex(), w);
}
device.Close();
}
public static void Log(string logMessage, TextWriter txtWriter)
{
try
{
txtWriter.Write("\r\nLog Entry : ");
txtWriter.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),
DateTime.Now.ToLongDateString());
txtWriter.WriteLine();
txtWriter.WriteLine(logMessage);
txtWriter.WriteLine("============================================================================================================");
}
catch (Exception)
{
}
}
protected override void OnStop()
{
using (StreamWriter w = File.AppendText(path + "\\" + filename + ".log"))
{
Log("Service is stopped at " + DateTime.Now, w);
}
}
}
}
And Here is the script for just running it in VS(works fine):
using System;
using PacketDotNet;
using SharpPcap;
using System.IO;
using System.Reflection;
using log4net;
using log4net.Config;
namespace CapturingAndParsingPackets
{
class MainClass
{
// used to stop the capture loop
private static bool _stopCapturing;
public static void Main(string[] args)
{
// Print SharpPcap version
var ver = SharpPcap.Pcap.SharpPcapVersion;
Console.WriteLine("PacketDotNet example using SharpPcap {0}", ver);
// Retrieve the device list
var devices = CaptureDeviceList.Instance;
// If no devices were found print an error
if (devices.Count < 1)
{
Console.WriteLine("No devices were found on this machine");
return;
}
Console.WriteLine();
Console.WriteLine("The following devices are available on this machine:");
Console.WriteLine("----------------------------------------------------");
Console.WriteLine();
var i = 0;
// Print out the devices
foreach (var dev in devices)
{
/* Description */
Console.WriteLine("{0}) {1} {2}", i, dev.Name, dev.Description);
i++;
}
Console.WriteLine();
Console.Write("-- Please choose a device to capture: ");
Console.WriteLine();
Console.WriteLine("Output Verbosity Options");
Console.WriteLine("----------------------------------------------------");
Console.WriteLine();
var defaultOutputType = StringOutputType.Normal;
var outputTypeValues = Enum.GetValues(typeof(StringOutputType));
foreach (StringOutputType outputType in outputTypeValues)
{
Console.Write("{0} - {1}", (int)outputType, outputType);
if (outputType == defaultOutputType)
{
Console.Write(" (default)");
}
Console.WriteLine("");
}
Console.WriteLine();
Console.Write("-- Please choose a verbosity (or press enter for the default): ");
StringOutputType selectedOutputType = defaultOutputType;
int userSelectedOutputType;
//Fixed
userSelectedOutputType = 3;
selectedOutputType = (StringOutputType)userSelectedOutputType;
// Register a cancel handler that lets us break out of our capture loop
Console.CancelKeyPress += HandleCancelKeyPress;
//Fixed
var device = devices[3];
// Open the device for capturing
var readTimeoutMilliseconds = 1000;
device.Open(DeviceModes.Promiscuous, readTimeoutMilliseconds);
//filter host 192.168.0.212
//or you can set it to "filter = 'ip'; " for default
string filter = "host 192.168.0.212";
device.Filter = filter;
Console.WriteLine();
Console.WriteLine("-- Listening on {0}, hit 'ctrl-c' to stop...",
device.Name);
while (_stopCapturing == false)
{
PacketCapture e;
var status = device.GetNextPacket(out e);
// null packets can be returned in the case where
// the GetNextRawPacket() timed out, we should just attempt
// to retrieve another packet by looping the while() again
if (status != GetPacketStatus.PacketRead)
{
// go back to the start of the while()
continue;
}
var rawCapture = e.GetPacket();
// use PacketDotNet to parse this packet and print out
// its high level information
var p = Packet.ParsePacket(rawCapture.GetLinkLayers(), rawCapture.Data);
Console.WriteLine(p.ToString(selectedOutputType) + p.PrintHex());
Console.WriteLine("============================================================================================================");
using (StreamWriter w = File.AppendText("networkTraffic.log"))
{
Log(p.ToString(selectedOutputType), w);
Log(p.PrintHex(), w);
}
}
Console.WriteLine("-- Capture stopped");
// Print out the device statistics
Console.WriteLine(device.Statistics.ToString());
// Close the pcap device
device.Close();
}
static void Log(string logMessage, TextWriter txtWriter)
{
try
{
txtWriter.Write("\r\nLog Entry : ");
txtWriter.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),
DateTime.Now.ToLongDateString());
txtWriter.WriteLine();
txtWriter.WriteLine(logMessage);
txtWriter.WriteLine("============================================================================================================");
}
catch (Exception)
{
}
}
static void HandleCancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
Console.WriteLine("-- Stopping capture");
_stopCapturing = true;
// tell the handler that we are taking care of shutting down, don't
// shut us down after we return because we need to do just a little
// bit more processing to close the open capture device etc
e.Cancel = true;
}
}
}
The error that shows in Event Viewer(1064):
Application: CaptureTrafficService.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.IO.FileNotFoundException
at CaptureTrafficService.Service1.OnStart(System.String[])
at System.ServiceProcess.ServiceBase.ServiceQueuedMainCallback(System.Object)
at System.ServiceProcess.ServiceBase.Run(System.ServiceProcess.ServiceBase[])
at CaptureTrafficService.Program.Main()
Service cannot be started. System.IO.FileNotFoundException: Could not load file or assembly 'netstandard, Version=2.1.0.0, Culture=neutral, PublicKeyToken=cc7b1xxxxxxxxxxx' or one of its dependencies. The system cannot find the file specified.
File name: 'netstandard, Version=2.1.0.0, Culture=neutral, PublicKeyToken=cc7b1xxxxxxxxxxx'
at CaptureTrafficService.Service1.OnStart(String[] args)
at System.ServiceProcess.ServiceBase.ServiceQueuedMainCallback(Object state)
After I remove the while loop in OnStart method, It shows up another error(1053):
Application: CaptureTrafficService.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.IO.FileNotFoundException
Exception Info: System.IO.FileNotFoundException
at CaptureService.Service1..ctor()
at CaptureService.Program.Main()
The answer by #Sam1916 might lessen the frustration of FileNotFoundException.
The "System.IO.FileNotFoundException" caught my attention - but missing info on what files.
As Windows services run in "their own context" the files referenced (Through "using") might not exists in a readable directory, hench "FileNotFoundException"
Is the logfile placed in a directory where your service credentials are allowed to write?
There are too many unnecessary references that may affect each other in the solution so that it will return a lot of errors & warnings when building it. Just add them one by one if it is necessary, rebuild it when you added a new reference(for checking the compatibility) and not just copying all of them to the solution.
Too many unnecessary references(Before)
Just add the references you need(After)
Here's the code that works with windows service:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using SharpPcap;
using PacketDotNet;
namespace Capture
{
public partial class Capture : ServiceBase
{
Timer timer = new Timer();
public Capture()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
Log("Service started at " + DateTime.Now);
timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
//timer.Interval = 5000;
timer.Enabled = true;
}
protected override void OnStop()
{
Log("Service is stopped at " + DateTime.Now);
}
private void OnElapsedTime(object source, ElapsedEventArgs e)
{
var devices = CaptureDeviceList.Instance;
//set output type
var defaultOutputType = StringOutputType.Normal;
StringOutputType selectedOutputType = defaultOutputType;
int userSelectedOutputType;
userSelectedOutputType = ? ;//? = 0-3
selectedOutputType = (StringOutputType)userSelectedOutputType;
//read local device
var device = devices[?];//? is mean num 0-4 or more(depends on your device)
//read packets
var readTimeoutMilliseconds = 1000;
device.Open(DeviceModes.Promiscuous, readTimeoutMilliseconds);
PacketCapture d;
var status = device.GetNextPacket(out d);
var rawCapture = d.GetPacket();
var p = Packet.ParsePacket(rawCapture.LinkLayerType, rawCapture.Data);
Log(p.ToString(selectedOutputType) +p.PrintHex());//write to log file
device.Close();
}
public static void Log(string logMessage)
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);+ "\\Logs" ;
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string filepath =Environment.GetFolderPath(Environment.SpecialFolder.Desktop); + "\\Logs\\ServiceLog_" +
DateTime.Now.Date.ToShortDateString().Replace('/','_') + ".log";
using (StreamWriter sw = File.AppendText(filepath))
{
sw.WriteLine(logMessage);
sw.WriteLine("============================================================================================================");
}
}
}
}

Using Gpio on Raspberry Pi 4 B with uno-platform

I realy hope im not the only one having this problem
(i deleted my previous Question because it seems kinda missleading so heres my secont attempt)
I try to use the Rasbpery pi 4b GPIO Pins using a Uno app:
my setup:
i tried it before with a consol APP and it works:
Console APP Code:
using System;
using System.Device.Gpio;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Startet");
int pin = 17;
GpioController controller = new GpioController();
controller.OpenPin(pin, PinMode.Output);
Console.WriteLine("Enter to Turn HIGH");
Console.Read();
Console.WriteLine("is HIGH");
controller.Write(pin, PinValue.High);
Console.WriteLine("Enter to Turn LOW");
Console.Read();
Console.WriteLine("is LOW");
controller.Write(pin, PinValue.Low);
}
}
}
The code above works fine. Now my attempt in UNO:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using System.Device.Gpio;
namespace App1
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
bool SwitchOnOffReminder;
private void Test_Click(object sender, RoutedEventArgs e)
{
int pin = 17;
GpioController controller = new GpioController();
controller.OpenPin(pin, PinMode.Output);
Ausgabe.Text = "Meldung\n";
Ausgabe.Text = Ausgabe.Text + controller.GetPinMode(pin).ToString();
if (SwitchOnOffReminder== false)
{
SwitchOnOffReminder= true;
Ausgabe.Text = Ausgabe.Text + "Pin HIGH";
controller.Write(pin, PinValue.High);
}
else
{
SwitchOnOffReminder= false;
Ausgabe.Text = Ausgabe.Text + "Pin LOW";
controller.Write(pin, PinValue.Low);
}
}
}
}
The Result: it does not work and the Raspberry console is displaying:
Uno.UI.Runtime.skia.GtkCoreWindowsExtension[0] Pointer capture release is not supported on Gtk"
can someone Help me with that?
As #JérômeLaban answered in the comment:
you can find the solution here:
github.com/unoplatform/uno/issues/3813

Programatically Switch Off/On Wi-Fi from WPF App

I have a WPF app that has a control(checkbox /toggle switch) . I want to turn Wi-Fi On/Off by using those buttons. I have tried the following code but it doesnt seem to help
I am using Windows 10 and Visual Studio 2015
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApplication4
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
// string name = "Hello World";
}
static void Enable(string interfaceName)
{
System.Diagnostics.ProcessStartInfo psi =
new System.Diagnostics.ProcessStartInfo("netsh", "interface set interface \"" + interfaceName + "\" enable");
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo = psi;
p.Start();
}
static void Disable(string interfaceName)
{
System.Diagnostics.ProcessStartInfo psi =
new System.Diagnostics.ProcessStartInfo("netsh", "interface set interface \"" + interfaceName + "\" disable");
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo = psi;
p.Start();
}
private void checkBox_Checked(object sender, RoutedEventArgs e)
{
string interfaceName = "Local Area Connection";
Disable(interfaceName);
}
}
}
I went through the following link with the first answer but there is no help .
I need some help so that I can programatically turn off/On Wi-Fi with the click of a button.
You can turn on/off Wi-Fi by changing software radio state (not hardware radio state) by Native Wifi API. Using some codes of Managed Wifi API project, I wrote a sample.
using System;
using System.Linq;
using System.Runtime.InteropServices;
using NativeWifi;
public static class WlanRadio
{
public static string[] GetInterfaceNames()
{
using (var client = new WlanClient())
{
return client.Interfaces.Select(x => x.InterfaceName).ToArray();
}
}
public static bool TurnOn(string interfaceName)
{
var interfaceGuid = GetInterfaceGuid(interfaceName);
if (!interfaceGuid.HasValue)
return false;
return SetRadioState(interfaceGuid.Value, Wlan.Dot11RadioState.On);
}
public static bool TurnOff(string interfaceName)
{
var interfaceGuid = GetInterfaceGuid(interfaceName);
if (!interfaceGuid.HasValue)
return false;
return SetRadioState(interfaceGuid.Value, Wlan.Dot11RadioState.Off);
}
private static Guid? GetInterfaceGuid(string interfaceName)
{
using (var client = new WlanClient())
{
return client.Interfaces.FirstOrDefault(x => x.InterfaceName == interfaceName)?.InterfaceGuid;
}
}
private static bool SetRadioState(Guid interfaceGuid, Wlan.Dot11RadioState radioState)
{
var state = new Wlan.WlanPhyRadioState
{
dwPhyIndex = (int)Wlan.Dot11PhyType.Any,
dot11SoftwareRadioState = radioState,
};
var size = Marshal.SizeOf(state);
var pointer = IntPtr.Zero;
try
{
pointer = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(state, pointer, false);
var clientHandle = IntPtr.Zero;
try
{
uint negotiatedVersion;
var result = Wlan.WlanOpenHandle(
Wlan.WLAN_CLIENT_VERSION_LONGHORN,
IntPtr.Zero,
out negotiatedVersion,
out clientHandle);
if (result != 0)
return false;
result = Wlan.WlanSetInterface(
clientHandle,
interfaceGuid,
Wlan.WlanIntfOpcode.RadioState,
(uint)size,
pointer,
IntPtr.Zero);
return (result == 0);
}
finally
{
Wlan.WlanCloseHandle(
clientHandle,
IntPtr.Zero);
}
}
finally
{
Marshal.FreeHGlobal(pointer);
}
}
public static string[] GetAvailableNetworkProfileNames(string interfaceName)
{
using (var client = new WlanClient())
{
var wlanInterface = client.Interfaces.FirstOrDefault(x => x.InterfaceName == interfaceName);
if (wlanInterface == null)
return Array.Empty<string>();
return wlanInterface.GetAvailableNetworkList(Wlan.WlanGetAvailableNetworkFlags.IncludeAllManualHiddenProfiles)
.Select(x => x.profileName)
.Where(x => !string.IsNullOrEmpty(x))
.ToArray();
}
}
public static void ConnectNetwork(string interfaceName, string profileName)
{
using (var client = new WlanClient())
{
var wlanInterface = client.Interfaces.FirstOrDefault(x => x.InterfaceName == interfaceName);
if (wlanInterface == null)
return;
wlanInterface.Connect(Wlan.WlanConnectionMode.Profile, Wlan.Dot11BssType.Any, profileName);
}
}
}
Check available interface names by GetInterfaceNames and then call TurnOn/TurnOff with one of the names. According to MSDN, it should require administrator priviledge but it doesn't on my environment.
SUPPLEMENT
I added two more methods to this class. So the sequence will be something like this.
Get existing Wi-Fi interface names by GetInterfaceNames.
Select an interface and turn it on by TurnOn.
Get profile names associated to available Wi-Fi networks through the interface by GetAvailableNetworkProfileNames.
Select a profile and connect to the network by ConnectNetwork.
After finished using the network, turn the interface off by TurnOff.
You could use the device library from windows universal apps.
Documentation:
https://msdn.microsoft.com/en-us/library/windows/apps/windows.devices.wifi.aspx
Microsoft sample:
https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples
In order to use this library with WPF application you could add
< TargetPlatformVersion > 8.0< / TargetPlatformVersion >
to your .csproj file between
< PropertyGroup>.... < /PropertyGroup>

C# UDP Chat receive no message

I try to write a UDP-Chat in C#.
I have some unexpected behavoir in my Chat Programm, when I start the programm on two different machines connected to the same Network. At the first mashine the programm works fine it can send and recive messages properly, but on the second machine it can just send messages but it can't recive them.
I testet this with a 3rd mashine too(a VM with a bridged networkinterface), but with the same result, it just can send messages without recieving.
is there a error in my code or is it a desing error?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Net.Sockets;
using System.Net;
using System.Diagnostics;
using System.Threading;
using System.Net.NetworkInformation;
using System.ComponentModel;
using System.Data;
namespace CScharpChat
{
/// <summary>
/// Interaktionslogik für Chat_window.xaml
/// </summary>
public partial class Chat_window : Window
{
string name = "testuser";
UdpClient receiveClient = new UdpClient(1800);
IPEndPoint receiveEndPint = new IPEndPoint(IPAddress.Any, 0);
public Chat_window(string name)
{
this.name = name;
fileWriter("Chat started", false); // write the initial start date in the errorfile
InitializeComponent();
Message_Load(); // starts the listen server theread
}
private void Message_Load()
{
lb_chat.Items.Add(name + " Joined the room...");
Thread rec = new Thread(ReceiveMessageFn);
rec.Start();
}
private void ReceiveMessageFn()
{
try
{
while (true)
{
Byte[] receve = receiveClient.Receive(ref receiveEndPint);
string message = Encoding.UTF8.GetString(receve);
if (message == name + " logged out...")
{
break;
}
else
{
if (message.Contains(name + " says >>"))
{
message = message.Replace(name + " says >>", "Me says >>");
}
ShowMessage(message);
}
}
//Thread.CurrentThread.Abort();
//Application.Current.Shutdown();
}
catch (Exception e)
{
//errorHandler(e);
}
}
private void ShowMessage(string message)
{
if (lb_chat.Dispatcher.CheckAccess())
{
lb_chat.Items.Add(message);// add Item to list-box
lb_chat.ScrollIntoView(lb_chat.Items[lb_chat.Items.Count - 1]);// scroll down to current Item
lb_chat.UpdateLayout();
}
else {
lb_chat.Dispatcher.BeginInvoke(
new Action<string>(ShowMessage), message); // if list-box is not access able get access
return;
}
}
private void tb_eingabe_GotFocus(object sender, RoutedEventArgs e)
{
tb_eingabe.Text = "";
}
private void btn_submit_Click(object sender, RoutedEventArgs e)
{
submit_message();
}
private void tb_eingabe_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Return)
{
submit_message();
}
}
void submit_message()
{
if (tb_eingabe.Text != "")
{
string data = name + " says >> " + tb_eingabe.Text;
SendMessage(data);
tb_eingabe.Clear(); // clear the textbox-values
tb_eingabe.Focus(); // get focus on tb if the submit button was used, the tb lost the focus
}
}
private void SendMessage(string data)
{
try{
UdpClient sendClient = new UdpClient();
Byte[] message = Encoding.UTF8.GetBytes(data); // use UTF8 for international encoding
IPEndPoint endPoint = new IPEndPoint(IPAddress.Broadcast, 1800); // use a broadcast with the given port
sendClient.Send(message, message.Length, endPoint);
sendClient.Close();
}
catch (Exception e)
{
errorHandler(e);
}
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
string data = name + " logged out...";
SendMessage(data); // send a logout message to the other chat peers
}
// debugging functions
static void errorHandler(Exception errorMsg)
{
MessageBox.Show(errorMsg.ToString()); // create a error-message-box
fileWriter(errorMsg.ToString(), true); // call the file-writer function to write the error in a file
}
static void fileWriter(string fileText, bool append)
{
System.IO.StreamWriter file = new System.IO.StreamWriter(".\\Errorfile.txt", append); // locate the error next to the chat.exe
file.WriteLine(GetTime(DateTime.Now) + "\n " + fileText); // append the date
file.Close();
}
public static String GetTime(DateTime val)
{
return val.ToString("yyyyMMddHHmmssffff"); // return the current date as string
}
}
}
Instead of IPAddress.Broadcast(255.255.255.255) provide your local network broadcast address. See the example below:
IPAddress broadcast = IPAddress.Parse("192.168.1.255"); //replace the address with your local network.
IPEndPoint endPoint = new IPEndPoint(broadcast, 11000);
sendClient.Send(message, message.Length, endPoint);
IPAddress.Broadcast doesn't work in some network.

Background Agent Not Performing.: Windows Phone 8

NEED A SOLUTION
Background agent is working only once. After There is no occurrence of a background agent. It works at the first time and it works perfectly as soon as the page opens. however, after that it takes forever and ever to do that again. sometimes page close and open doesn't work. that would probably because of not removing the agenet
My background Agent Code:
#define DEBUG_AGENT
using System;
using System.Windows;
using Microsoft.Phone.Scheduler;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Info;
using System.Linq;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using System.Threading;
using Microsoft.Xna.Framework.Media;
using System.Windows.Input;
using Microsoft.Devices;
using System.IO;
using System.IO.IsolatedStorage;
using System.Windows.Media.Imaging;
using System.Net.Sockets;
using System.Text;
using System.Net;
namespace ScheduledTaskAgent1
{
public class ScheduledAgent : ScheduledTaskAgent
{
private static volatile bool _classInitialized;
//private DispatcherTimer s;
Socket _socket = null;
ManualResetEvent _clientDone = new ManualResetEvent(false);
const int TIMEOUT_MILLISECONDS = 5000;
const int MAX_BUFFER_SIZE = 2048;
double lat = 7.16126666666667;
static ScheduledAgent()
{
// Subscribe to the managed exception handler
Deployment.Current.Dispatcher.BeginInvoke(delegate
{
Application.Current.UnhandledException += UnhandledException;
});
}
/// Code to execute on Unhandled Exceptions
private static void UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
if (System.Diagnostics.Debugger.IsAttached)
{
// An unhandled exception has occurred; break into the debugger
System.Diagnostics.Debugger.Break();
}
}
protected override void OnInvoke(ScheduledTask task)
{
//TODO: Add code to perform your task in background
string toastTitle = "";
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
lat += 0.001;
string snmea = DD2NMEA(lat, 80.44506);
string dates = DateTime.UtcNow.ToString("ddMMyy");
string UTCTime = DateTime.UtcNow.ToString("hhmmss") + ".000";
string s1 = Checksum("$FRCMD,869444005499999,_SendMessage,,0809.67600,N,8050.70360,E,1.0,1.08,3.0,141013,055642.000,1,Button1=1,Button2=0,Switch1=1,Switch2=0,Analog1=4.00,Analog2=5.00,SosButton=0,BatteryLow=0,Text1=Text1,Text2=Text2*00");
string s = Send("$FRCMD,869444005499999,_SendMessage,," + snmea + ",1.0,1.08,3.0," + dates + "," + UTCTime + ",1,Button1=1,Button2=0,Switch1=1,Switch2=0,Analog1=4.00,Analog2=5.00,SosButton=0,BatteryLow=0,Text1=Text1,Text2=Text2*00");
startToastTask(task, toastTitle);
}
private void startToastTask(ScheduledTask task, string toastTitle)
{
#if DEBUG_AGENT
ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(10));
#endif
// Call NotifyComplete to let the system know the agent is done working.
NotifyComplete();
}
}
}
My Page from app which calls the agent
PeriodicTask toastPeriodicTask;
const string toastTaskName = "ToastPeriodicAgent";
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
toastPeriodicTask = ScheduledActionService.Find(toastTaskName) as PeriodicTask;
StartPeriodicAgent(toastTaskName);
}
private void StartPeriodicAgent(string taskName)
{
toastPeriodicTask = ScheduledActionService.Find(taskName) as PeriodicTask;
if (toastPeriodicTask != null)
{
RemoveAgent(taskName);
}
toastPeriodicTask = new PeriodicTask(taskName);
toastPeriodicTask.Description = periodicTaskDesc;
try
{
ScheduledActionService.Add(toastPeriodicTask);
#if(DEBUG_AGENT)
ScheduledActionService.LaunchForTest(taskName, TimeSpan.FromSeconds(2));
#endif
}
catch (InvalidOperationException exception)
{
if (exception.Message.Contains("BNS Error: The action is disabled"))
{
MessageBox.Show("Background agents for this application have been disabled by the user.");
}
else if (exception.Message.Contains("BNS Error: The maximum number of ScheduledActions of this type have already been added."))
{
MessageBox.Show("BNS Error: The maximum number of ScheduledActions of this type have already been added.");
}
else
{
MessageBox.Show("An InvalidOperationException occurred.");
}
}
catch (SchedulerServiceException)
{
}
}
Ensure that your project has DEBUG_AGENT defined. This is a setting within your project properties. To set this flag, follow these steps
Right click the project within VS and select Properties
Select the Build tab
Add DEBUG_AGENT to the "Conditional compilation symbols" field.
If that is set, I've found it's best to give at least 30 seconds in the LaunchForTest. Sometimes it doesn't quite schedule it when you tell it to.

Categories