Can not find BLE device using 32feet.NET - c#

I use VS 2017 in windows 7 to write a hci tool for searching the BLE device.
I use bluetooth CSR 4.0 dongle(the driver is installed and works well) and BlueSoleil.
But when after the BLE device's advertising, the program can not find it. I have tried to use other app like lightblue for searching, the BLE device is findable.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using InTheHand.Net.Bluetooth;
using InTheHand.Net;
using InTheHand.Net.Sockets;
using System.Diagnostics;
using System.Net.Sockets;
namespace hcitool
{
partial class Program
{
static bool infoRatherThanName;
static BluetoothAddress _searchAddress;
static int Main(string[] args)
{
if (args.Length < 1)
{
Console.WriteLine("Please specify command.");
return 2;
}
var cmd = args[0];
switch (cmd)
{
case "name":
infoRatherThanName = false;
break;
case "info":
infoRatherThanName = true;
break;
//-
case "dev":
return ShowRadios();
//case "auth":
// return CauseAuth(GETADDRESS());
default:
throw new NotImplementedException("Command: '" + cmd +
"'");
}
if (args.Length < 2)
{
Console.WriteLine("Please specify device address.");
return 2;
}
var addrS = args[1];
_searchAddress = BluetoothAddress.Parse(addrS);
//
var dev = new BluetoothDeviceInfo(_searchAddress);
bool isInRange = GetCanConnectTo(dev);
if (isInRange)
{
PrintDevice(dev);
}
else
{
Console.WriteLine("Can't see that device.");
}
//
Console.WriteLine("simple");
return Simple();
//return Fancier();
}
When I run the program using:“hcitool.exe name 123456654321(the BLE address)” , it shows: can't see that device.
The return value of GetCanConnectTo() is false so it shows: can't see that device.
I do not know how I could connect to the ble device using my code.

Related

Need to copy OTP

My use case is that my user has an outlook account and I am doing automation so when a person login a 2FA is required,
so I need to copy the OTP and paste it into my application
I m writing code in c#, is there any way to connect to outlook?
my code is below but nothing showing in console
using Microsoft.Office.Interop.Outlook;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace new project
{
internal class Program
{
static void Main(string[] args)
{
Microsoft.Office.Interop.Outlook.Application outlookApp = new Microsoft.Office.Interop.Outlook.Application();
NameSpace outlookNS = outlookApp.GetNamespace("MAPI");
MAPIFolder inbox = outlookNS.GetDefaultFolder(OlDefaultFolders.olFolderInbox);
Items items = inbox.Items;
foreach(object item in items)
{
if (item is MailItem mailItem)
{
if (mailItem.Subject.Contains("One-Time Password for Your Account"))
{
string body = mailItem.Body;
int startIndex = body.IndexOf("OTP:") + 4;
int length = 6;
string otp = body.Substring(startIndex, length);
Console.WriteLine("OTP: " + otp);
break;
}
}
}
}
}
}
I need to copy the OTP and paste it into my application

The type or namespace name 'BluetoothAddress' could not be found

I use vs 2017 and windows 7.
I have installed 32feet.NET following this: Looking to write Bluetooth 'hcitool' equivelant in Windows.
But I get the errors:
The type or namespace name 'BluetoothAddress' could not be found
The type or namespace name 'BluetoothClient' could not be found
The type or namespace name 'BluetoothSecurity' could not be found
The type or namespace name 'BluetoothDeviceInfo' could not be found
The type or namespace name 'ServiceRecord' could not be found
I have successfully installed InTheHand.Devices.Bluetooth and There is no warning in the using sentence so the namespace is successfully referenced.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using InTheHand.Devices.Bluetooth;
using InTheHand.Networking;
using InTheHand.Networking.Sockets;
using InTheHand;
using System.Diagnostics;
using System.Net.Sockets;
namespace hcitool
{
partial class Program
{
static bool infoRatherThanName;
static BluetoothAddress _searchAddress;
static int Main(string[] args)
{
if (args.Length < 1)
{
Console.WriteLine("Please specify command.");
return 2;
}
var cmd = args[0];
switch (cmd)
{
case "name":
infoRatherThanName = false;
break;
case "info":
infoRatherThanName = true;
break;
//-
case "dev":
return ShowRadios();
//case "auth":
// return CauseAuth(GETADDRESS());
default:
throw new NotImplementedException("Command: '" + cmd + "'");
}
if (args.Length < 2)
{
Console.WriteLine("Please specify device address.");
return 2;
}
var addrS = args[1];
_searchAddress = BluetoothAddress.Parse(addrS);
//
//var dev = new BluetoothDeviceInfo(_searchAddress);
var dev = new BluetoothDevice();
bool isInRange = GetCanConnectTo(dev);
if (isInRange)
{
PrintDevice(dev);
}
else
{
Console.WriteLine("Can't see that device.");
}
//
Console.WriteLine("simple");
return Simple();
//return Fancier();
}
//----
private static int ShowRadios()
{
BluetoothRadio[] list;
try
{
list = BluetoothRadio.AllRadios;
}
catch (Exception)
{
return 1;
}
Debug.Assert(list.Length != 0, "Expect zero radios case to raise an error.");
foreach (var curR in list)
{
Console.WriteLine("* {0} '{1}'", curR.LocalAddress, curR.Name);
Console.WriteLine("{0}", curR.SoftwareManufacturer);
Console.WriteLine("{0}", curR.Manufacturer);
Console.WriteLine("{0}", curR.Mode);
}//for
return 0;
}
private static int CauseAuth(BluetoothAddress addr)
{
BluetoothSecurity.PairRequest(addr, null);
return 0;
}
//----
static int Simple()
{
BluetoothDeviceInfo[] devices;
BluetoothDeviceInfo foundDev = null;
var cli = new BluetoothClient();
// Fast: Remembered/Authenticated
devices = cli.DiscoverDevices(255, true, true, false, false);
SimpleCheckDevice(devices, ref foundDev);
if (foundDev == null)
{
// Slow: Inquiry
cli.DiscoverDevices(255, false, false, true, false);
SimpleCheckDevice(devices, ref foundDev);
}
//
if (foundDev != null)
{
return 0;
}
else
{
return 1;
}
}
private static void SimpleCheckDevice(IEnumerable<BluetoothDeviceInfo> devices,
ref BluetoothDeviceInfo foundDev)
{
foreach (var cur in devices)
{
if (cur.DeviceAddress == _searchAddress)
{
foundDev = cur;
PrintDevice(cur);
}
}//for
}
private static void PrintDevice(BluetoothDeviceInfo cur)
{
Console.WriteLine("* Found device: '{0}' ", cur.DeviceName);
if (infoRatherThanName)
{
try
{
var vs = cur.GetVersions();
Console.WriteLine(vs.Manufacturer);
Console.WriteLine(vs.LmpVersion);
Console.WriteLine(vs.LmpSubversion);
Console.WriteLine(vs.LmpSupportedFeatures);
}
catch (Exception ex)
{
Console.WriteLine("Failed to get remote device versions info: "
+ ex.Message);
}
}
}
//----
private static bool GetCanConnectTo(BluetoothDeviceInfo device)
{
bool inRange;
Guid fakeUuid = new Guid("{F13F471D-47CB-41d6-9609-BAD0690BF891}");
try
{
ServiceRecord[] records = device.GetServiceRecords(fakeUuid);
Debug.Assert(records.Length == 0, "Why are we getting any records?? len: " + records.Length);
inRange = true;
}
catch (SocketException)
{
inRange = false;
}
return inRange;
}
}
}
The BluetoothAddress is in the 32feet.NET nuget package.
You're using the preview version of InTheHand which is missing the BluetoothAddress, the BluetoothRadio, BluetoothDeviceInfo and others.
I think you're referencing the wiki for the 32feet.NET, which is the legacy nuget package.
If you install 32feet.NET v3.5.0.0, you will find all your missing bindings.
Adding 32feet.NET and changing a couple of things:
var dev = new BluetoothDevice();
//this becomes this:
var dev = new BluetoothDeviceInfo(_searchAddress);
it will compile succesfully.
Try to add the following namespaces to your code:
using InTheHand.Net;
using InTheHand.Net.Sockets;
using InTheHand.Net.Bluetooth;

GooglePlus Authentication in Windows Phone 8.1

I am writing a Windows Phone 8.1 App (WINRT).
How to do GooglePlus Authentication (SignIn via GooglePlus) in Windows Phone 8.1 App** without using MVVM/MVC**?
I used Web Authentication via Webbrowser control in Windows Phone 8.0 App but Windows Phone 8.1 WebView Control does not have Navigating event.
Can anyone help me?
According to Mr. Filip Skakun, I wrote:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.ApplicationModel.Activation;
using Windows.Data.Json;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Security.Authentication.Web;
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 Windows.Web.Http;
namespace webbrokerFinal
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
Connect();
this.NavigationCacheMode = NavigationCacheMode.Required;
}
string FacebookClientIDString = "000000000000";
string FacebookCallbackUrlString = " https://www.facebook.com/connect/login_success.html";
private void Connect()
{
try
{
String FacebookURL = "https://www.facebook.com/dialog/oauth?client_id=" + FacebookClientIDString + "&redirect_uri=" + Uri.EscapeUriString(FacebookCallbackUrlString) + "&scope=read_stream&display=popup&response_type=token";
System.Uri StartUri = new Uri(FacebookURL);
System.Uri EndUri = new Uri(FacebookCallbackUrlString);
WebAuthenticationBroker.AuthenticateAndContinue(StartUri, EndUri, null, WebAuthenticationOptions.None);
}
catch (Exception Error) >> The remote procedure call failed. (Exception from HRESULT: 0x800706BE)
{
//
// Bad Parameter, SSL/TLS Errors and Network Unavailable errors are to be handled here.
//
}
}
public async void ContinueWebAuthentication(WebAuthenticationBrokerContinuationEventArgs args)
{
WebAuthenticationResult result = args.WebAuthenticationResult;
if (result.ResponseStatus == WebAuthenticationStatus.Success)
{
await GetFacebookUserNameAsync(result.ResponseData.ToString());
}
else if (result.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
{
}
else
{
}
}
private async Task GetFacebookUserNameAsync(string webAuthResultResponseData)
{
//Get Access Token first
string responseData = webAuthResultResponseData.Substring(webAuthResultResponseData.IndexOf("access_token"));
String[] keyValPairs = responseData.Split('&');
string access_token = null;
string expires_in = null;
for (int i = 0; i < keyValPairs.Length; i++)
{
String[] splits = keyValPairs[i].Split('=');
switch (splits[0])
{
case "access_token":
access_token = splits[1]; //you may want to store access_token for further use. Look at Scenario5 (Account Management).
break;
case "expires_in":
expires_in = splits[1];
break;
}
}
//Request User info.
HttpClient httpClient = new HttpClient();
string response = await httpClient.GetStringAsync(new Uri("https://graph.facebook.com/me?access_token=" + access_token));
JsonObject value = JsonValue.Parse(response).GetObject();
string facebookUserName = value.GetNamedString("name");
}
}
}
But giving me error:
The remote procedure call failed. (Exception from HRESULT: 0x800706BE)
I'd start with WebAuthenticationBroker. It's a sort of wrapper around WebView you use for all OAuth.

How to monitor the network bandwidth usage of a specific application?

I am trying to learn how to monitor the network bandwidth usage of a specific application. I am looking at IPv4InterfaceStatistics, but that seems to monitor an NIC card's performance.
I'd like to monitor a specific application to see how much bandwidth is consumed every second.
Does anyone know of an example of how this can be done?
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Text;
using System.Threading;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
while (true)
{
var bytesSentPerformanceCounter = new PerformanceCounter();
bytesSentPerformanceCounter.CategoryName = ".NET CLR Networking";
bytesSentPerformanceCounter.CounterName = "Bytes Sent";
bytesSentPerformanceCounter.InstanceName = GetInstanceName();
bytesSentPerformanceCounter.ReadOnly = true;
var bytesReceivedPerformanceCounter = new PerformanceCounter();
bytesReceivedPerformanceCounter.CategoryName = ".NET CLR Networking";
bytesReceivedPerformanceCounter.CounterName = "Bytes Received";
bytesReceivedPerformanceCounter.InstanceName = GetInstanceName();
bytesReceivedPerformanceCounter.ReadOnly = true;
Console.WriteLine("Bytes sent: {0}", bytesSentPerformanceCounter.RawValue);
Console.WriteLine("Bytes received: {0}", bytesReceivedPerformanceCounter.RawValue);
Thread.Sleep(1000);
}
}
private static string GetInstanceName()
{
string returnvalue = "not found";
//Checks bandwidth usage for CUPC.exe..Change it with your application Name
string applicationName = "CUPC";
PerformanceCounterCategory[] Array = PerformanceCounterCategory.GetCategories();
for (int i = 0; i < Array.Length; i++)
{
if (Array[i].CategoryName.Contains(".NET CLR Networking"))
foreach (var item in Array[i].GetInstanceNames())
{
if (item.ToLower().Contains(applicationName.ToString().ToLower()))
returnvalue = item;
}
}
return returnvalue;
}
}
}
Here is a modified version using PerformanceCounter:
var processFileName = Path.GetFileName(Process.GetCurrentProcess().MainModule.FileName);
var bytesReceivedPerformanceCounter = new PerformanceCounter();
bytesReceivedPerformanceCounter.CategoryName = ".NET CLR Networking 4.0.0.0";
bytesReceivedPerformanceCounter.CounterName = "Bytes Received";
bytesReceivedPerformanceCounter.InstanceName = VersioningHelper.MakeVersionSafeName(processFileName, ResourceScope.Machine, ResourceScope.AppDomain);
bytesReceivedPerformanceCounter.ReadOnly = true;
Console.WriteLine("Bytes received: {0}", bytesReceivedPerformanceCounter.RawValue);
If you are familiar with the OSI model http://en.wikipedia.org/wiki/OSI_model you see that you try to interact with layer 3 where you should be interacting with layer 7.
I your connection with what ever class you are using you are able to measure bytes sent, specially if you are transporting the individual bytes, (this is since i have no idea how your code is looking), you should be able to calculate the amount of bytes over a time divide with number of seconds and you will have your result.

.net remoting, How to reconnect if the connect is lost?

I have this working but i don't understand how to predict when the connection has dropped and needs to reconnect to the server.
what i want to do is have the client connect right away to the .net remoting server if it drops out, sort of like keep trying to connect and disregard if it does not need to.
help appreciated.
here is my code:
namespace TaskClient
{
using System;
using System.Reflection;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using System.Threading;
using TaskShared;
class Program
{
static void Main(string[] args)
{
TcpChannel chan = new TcpChannel();
ChannelServices.RegisterChannel(chan, false);
Connections remObject = (Connections)Activator.GetObject(typeof(Connections), "tcp://localhost:8085/TaskServer");
if (remObject == null)
{
Console.WriteLine("Could not connect to TaskServer. (tcp://localhost:8085/TaskServer)");
}
else
{
Console.WriteLine("Connected to Task Server.");
var rt = new TestTask()
{
ApplicationName = Assembly.GetExecutingAssembly().FullName,
ComputerName = Environment.MachineName,
VersionInfo = "1.0.0",
JobRunning = "None"
};
remObject.Add(rt);
}
while (true)
{
//TODO:
//Check if connected.. how?
//Re-create the connection... how?
//doing this simple won't work:
if (remObject == null)
remObject = (Connections)Activator.GetObject(typeof(Connections), "tcp://localhost:8085/TaskServer");
remObject.Invalidate(remObject[rt]);
Thread.Sleep(1000);
}
}
}
}

Categories

Resources