I have written a function that should give me an Identifier for iOS devices... But now I have to do the same for Android...
Is there an Id witch is on both devices?
Actually im using the AdvertisingIdentifier.
private static string GetIdentifier()
{
if (ASIdentifierManager.SharedManager.IsAdvertisingTrackingEnabled)
{
return ASIdentifierManager.SharedManager.AdvertisingIdentifier.ToString();
}
return null;
}
Since I don't know which ID do you want exactly, I wrote three block of code as follow:
//get unique number through TelephonyManager
//use this method, we need to add android.permission.READ_PHONE_STATE permission
var telephonymanager = this.GetSystemService(Context.TelephonyService) as TelephonyManager;
var imsid = telephonymanager.SubscriberId;
System.Diagnostics.Debug.WriteLine("imsid: " + imsid);
//get mac address through WifiManager
//use this method, we need to add android.permission.ACCESS_WIFI_STATE permission
var wifimanager = this.GetSystemService(Context.WifiService) as WifiManager;
var info = wifimanager.ConnectionInfo;
var macaddress = info.MacAddress;
System.Diagnostics.Debug.WriteLine("mac address: " + macaddress);
//get Android_ID use Android Provider
var deviceid = Android.Provider.Settings.Secure.GetString(this.ContentResolver,
Android.Provider.Settings.Secure.AndroidId);
System.Diagnostics.Debug.WriteLine("device id: " + deviceid);
First one is to get the IMEI, MEID, ESN and IMSI of the phone, which is unique to that piece of hardware. Second one is to get mac address of the device and the last one is to get device id.
All of them can be used to identify the device, you can choose the right one for your scenario. By the way, for the permissions which are needed, I've commented in the code block.
Related
I'm looking for a working and not deprecated solution for getting the phone number on any Android phone.
I already tried different methods that I found on StackOverflow, but most of them don't work because the majority reads the phone number from the device info. My device, and many others, doesn't have the number stored in the SIM so when using that method it returns null or empty string.
Is there another way to get the phone number, for example using the Google account you have logged in and checking if there is a number associated with it or from Whatsapp?
Things that I have already tried.
IList<string> numeri = new List<string>();
//RETURNS THE NUMBER ON EMULATOR, NOTHING ON MY DEVICE
TelephonyManager telephonyManager = Application.Context.GetSystemService(TelephonyService) as TelephonyManager;
numeri.Add(telephonyManager.Line1Number);
//RETURNS THE NUMBER ON EMULATOR, NOTHING ON MY DEVICE
SubscriptionManager subscriptionManager = (SubscriptionManager)GetSystemService(TelephonySubscriptionService);
IList<SubscriptionInfo> subsInfoList = subscriptionManager.ActiveSubscriptionInfoList;
foreach (SubscriptionInfo item in subsInfoList) {
numeri.Add(item.Number);
}
//ACCOUNTS ARRAY IS EMPTY ON EMULATOR AND MY DEVICE
Java.Util.Regex.Pattern pattern = Patterns.Phone;
Account[] accounts = AccountManager.Get(this).GetAccounts();
foreach (Account account in accounts) {
if (pattern.Matcher(account.Name).Matches()) {
numeri.Add(account.Name);
}
}
I hope somebody can help me with this. Thanks.
EDIT
I've decided to work with the IMEI of the device, for what I need to do, I don't necessarily need the phone number.
TelephonyManager telephonyManager = Application.Context.GetSystemService(TelephonyService) as TelephonyManager;
string IMEIDevice = telephonyManager.Imei;
Edit for removing the possible duplicate message. Thanks to everyone.
You can try the foollowing code:
TelephonyManager tMgr = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String MyPhoneNumber = "0000000000";
try
{
MyPhoneNumber = tMgr.getLine1Number();
}
catch (NullPointerException ex)
{
}
if (MyPhoneNumber.equals(""))
{
MyPhoneNumber = tMgr.getSubscriberId();
}
Here is the case:
getLine1Number() Returns blank, not null
I've decided to work with the IMEI of the device, for what I need to do, I don't necessarily need the phone number.
TelephonyManager telephonyManager = Application.Context.GetSystemService(TelephonyService) as TelephonyManager;
string IMEIDevice = telephonyManager.Imei;
If some of you guys shows me another way of getting the number, reading the chip of the SIM maybe (?), let me know. Thanks.
From : Programmatically obtain the phone number of the Android phone
The answer is
Code:
TelephonyManager tMgr =(TelephonyManager)mAppContext.getSystemService(Context.TELEPHONY_SERVICE);
String mPhoneNumber = tMgr.getLine1Number();
Required Permission:
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
I have two USB receivers for bar-code scanners connected to a raspberry pi3 (Windows IOT Core).
I can connect to them and list the USB Virtual COM devices and connect to them and receive data. But I can't differentiate between the two, the IDs are identical and the system is not providing Port numbers.
When I call Current.portnumber.ToString() the string is empty.
I am hoping to assign each device to a person and have them scan a bar-code for their username and would like to display which scanner is associated with which person (Such as Com5 = Bill Com6 = Dave) but just can't find a unique identifier for each virtual com
private async void ListAvailablePorts()
{
try
{
string aqs = SerialDevice.GetDeviceSelector();
var infos = await DeviceInformation.FindAllAsync(aqs);
foreach (var info in infos)
{
var serialDevice = await SerialDevice.FromIdAsync(info.Id);
DeviceInformation Current = info as DeviceInformation;
if (serialDevice != null && Current.Name == "USB Virtual COM")
{
listOfDevices.Add(Current);
ComList.Items.Add(Current.Name.ToString());
}
}
DeviceList.ItemsSource = listOfDevices;
ComList.SelectedIndex = -1;
DeviceList.SelectedIndex = -1;
}
catch (Exception ex)
{
txtUser.Text = ex.Message;
}
}
After additional scrutiny I found that the ID fields are different on a single digit within an 86 character string.
\\?\USB#VID_0416&PID_5011#5&3753427a&0&5#{86e0d1e0-8089-11d0-9ce4-08003e301f73}
VS
\\?\USB#VID_0416&PID_5011#5&3753427a&0&2#{86e0d1e0-8089-11d0-9ce4-08003e301f73}
Thanks
I am trying to connect to wifi using simplewifi. Currently, I have tried:
Wifi wifi = new Wifi();
// get list of access points
IEnumerable<AccessPoint> accessPoints = wifi.GetAccessPoints();
// for each access point from the list
foreach (AccessPoint ap in accessPoints)
{
Console.WriteLine("ap: {0}\r\n", ap.Name);
//check if SSID is desired
if (ap.Name.StartsWith("z"))
{
//verify connection to desired SSID
Console.WriteLine("connected: {0}, password needed: {1}, has profile: {2}\r\n", ap.Name, ap.IsConnected, ap.HasProfile);
if (!ap.IsConnected)
{
//connect if not connected
Console.WriteLine("\r\n{0}\r\n", ap.ToString());
Console.WriteLine("Trying to connect..\r\n");
AuthRequest authRequest = new AuthRequest(ap);
authRequest.Password = "123456789";
var x=ap.Connect(authRequest);
}
}
}
Here I am not able to pass the password if I have the password hardcoded like
var password="abc123"
How can I pass the password and connect?
Also, the connect method always returns false, even if I have to connect to a wifi with no password.
You need to set authRequest.Password = "yourpassword";
before your ap.connect(authRequest);
Add in following console.write() from https://github.com/DigiExam/simplewifi
Place at the top of your file
using SimpleWifi;
Then in your function
// Wifi object
Wifi wifi = new Wifi();
// get list of access points
IEnumerable<AccessPoint> accessPoints = wifi.GetAccessPoints();
// for each access point from list
foreach (AccessPoint ap in accessPoints){
Console.WriteLine("ap: {0}\r\n", ap.Name);
//check if SSID is desired
if (ap.Name.StartsWith("ardrone_")){
//verify connection to desired SSID
Console.WriteLine("connected: {0}, password needed: {1}, has profile: {2}\r\n", ap.Name, ap.IsConnected, ap.HasProfile);
if (!ap.IsConnected){
//connect if not connected
Console.WriteLine("\r\n{0}\r\n", ap.ToString());
Console.WriteLine("Trying to connect..\r\n");
AuthRequest authRequest = new AuthRequest(ap);
ap.Connect(authRequest);
}
}
}
Adding overwriteProfile set to "true" to parameters of the AccessPoint.Connect method solved the problem for me.
F# example:
open SimpleWifi
[<EntryPoint>]
let main argv =
let wifi = Wifi()
let accessPoint = wifi.GetAccessPoints()
|> Seq.find (fun (i:AccessPoint) -> i.Name = "Tpkl6" )
let try1 = accessPoint.Connect( AuthRequest(accessPoint, Password="12345678"), true )
let try2 = accessPoint.Connect( AuthRequest(accessPoint, Password="markvirchenko20"), true )
printfn "%b\n%b" try1 try2
0 // return an integer exit code
By the way, you asked about ispasswordvalid function in the comments:
I disconnected all internet and tried to connect, ispasswordvalid verification gives true, but while connecting it fails
ispasswordvalid doesn't actually check if the password is correct i.e matching the one set on the wifi. It simply checks if the password has a valid structure, e.g at least 8 symbols length.
We have several devices where I work (mostly Datalogic 4420 Falcon), and someone is always leaving one off the base. The battery runs dry, then they bring them back to get setup all over. (There's supposed to be a way to configure a file on the SD card to reload upon such an error, but it doesn't work very well)
When someone saves changes on the device (using my app that writes data to the SQL Server), the Serial Number is sent along with it so we can track what devices are in use where.
Each device has a Serial Number, and I have to physically (i.e. manually) write that into the Device name field, which I can read. Working code here if anyone wants to know how:
static string deviceId = null;
public static string DeviceName {
get {
if (String.IsNullOrEmpty(deviceId)) {
using (RegistryKey key = Registry.LocalMachine.OpenSubKey("Ident", true)) {
try {
deviceId = key.GetValue("Name", "[Unnamed]").ToString();
} catch (Exception e) {
ErrorWrapper("GetDeviceName", e);
deviceId = Dns.GetHostName();
} finally {
key.Flush();
key.Close();
}
}
}
return deviceId;
}
}
I do not like the manual (i.e. Fat Finger prone) Serial Number entry. Is there some call to query the device's Serial Number, or is that vendor specific?
Datamax does make an SDK that is specific to their devices, but we don't want our applications tied down to any one manufacturer (we are already tied down to VS2008).
I'd start by trying to P/Invoke to get the device ID (KerneIoControl with IOCTL_HAL_GET_DEVICEID) and see if it matches the serial number you're after. Here's an example.
I don't know about your Datalogic 4420 Falcon device, but I work with Intermec CK30 & CK60 and I have their itc50.dll file.
Here is snippet:
[DllImport("itc50.dll")]public static extern int ITCGetSerialNumber(StringBuilder Snumber, int buffSize);
StringBuilder hwSN = new StringBuilder(12);
if (ITCGetSerialNumber(hwSN, hwSN.Capacity) >= 0)
{
;
;
}
My company developed a device that communicates with a PC via Bluetooth using a virtual COM port.
Now we need a user to pair a device with a PC (MS Windows OS) first and then enter it's com port number manually into our application(I bet 95% of users will fail on this taks).
So I'd like my application to present a user with a list of paired bluetooth devices (a list of their "friendly names") and after that I'd like to find out the selecded device's COM port number automatically.
How can I do it in c#? (a solution independent of installed bluetooth stack is appreciated).
Thanks in advance.
See my answer at Widcomm bluetooth : how to open the virtual COM for my understanding of the licence: using the binary version is free for commercial use. And, also that I'm maintainer of the library.
So a brief slight digression. I'm not a big fan of virtual COM ports. It always seems much easier to use a direct 'sockets' connection, rather than attempt to setup a COM port, and try to find what name it was created as (see below!), and then have to open a SerialPort to use it, and then if the connection is lost one doesn't know and have simply to keep retrying... With the library its so much easier to just to create and use that direct Bluetooth connection!
However you may want a solution to your current task at the moment. :-) So, use WMI to find the current COM ports in place and see if any of them are for your device. For example in PowerShell:
C:\> Get-WmiObject -query "select DeviceID,PNPDeviceID from Win32_SerialPort"
...
...
DeviceID : COM66
PNPDeviceID : BTHENUM\{00001101-0000-1000-8000-00805F9B34FB}\7&1D80ECD3&0&00803A686519_C00000003
In that big long string one sees the address of the target device: 00803A686519. One can use WMI from .NET, run that query, filter the ones with "BTHENUM", and then parse out the address.
If you the do need to create a new Bluetooth virtual COM port, use 32feet.NET's BluetoothDeviceInfo.SetServiceState(BluetoothService.SerialPort) API. See the "Bluetooth Serial Ports" section in the User Guide e.g. at http://www.alanjmcf.me.uk/comms/bluetooth/32feet.NET%20--%20User%20Guide.html, and the class documentation in the release.
Unfortunately the native Win32 API we call does not tell what name of COM port it created! :-( So run the WMI query before and after the call to see what new name appeared (or use System.IO.Ports.SerialPort.GetPortNames as its simpler).
That's all specific to the Microsoft Bluetooth stack. I haven't investigated how other stacks behave in this regard. After a brief check Widcomm's serial ports appear in SerialPort.GetPortNames but not in the WMI query...
First, create a Management Object Searcher to search the WMI database:
ManagementObjectSearcher serialSearcher =
new ManagementObjectSearcher("root\\CIMV2",
"SELECT * FROM Win32_SerialPort");
Next, use LINQ to get all the serial ports into a query:
var query = from ManagementObject s in serialSearcher.Get()
select new { Name = s["Name"], DeviceID = s["DeviceID"], PNPDeviceID = s["PNPDeviceID"] }; // DeviceID -- > PNPDeviceID
You can now print all the COM ports, their friendly names and you can even filter through their PNPDeviceID's to find the bluetooth device address. Here's an example:
foreach (var port in query)
{
Console.WriteLine("{0} - {1}", port.DeviceID, port.Name);
var pnpDeviceId = port.PNPDeviceID.ToString();
if(pnpDeviceId.Contains("BTHENUM"))
{
var bluetoothDeviceAddress = pnpDeviceId.Split('&')[4].Split('_')[0];
if (bluetoothDeviceAddress.Length == 12 && bluetoothDeviceAddress != "000000000000")
{
Console.WriteLine(" - Address: {0}", bluetoothDeviceAddress);
}
}
}
I manage to get the bluetooth name and the COM port by fiddling the registry key
The pseudo code to obtain the bluetooth information is below:
enumerate all the COM port available in the PNP
obtain the device classGuid
search the bluetooth address from the classGuid
when the bluetooth address is known, the bluetooth name can be obtained from the this registry SYSTEM\CurrentControlSet\Services\BTHPORT\Parameters\Devices
The code is below, just call the GetBluetoothPort(), it will return a list of bluetooth devices, and you could connect them by passing the COM port number to the SerialPort class
public static string[] GetBluetoothPort()
{
Regex regexPortName = new Regex(#"(COM\d+)");
List<string> portList = new List<string>();
ManagementObjectSearcher searchSerial = new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity");
foreach (ManagementObject obj in searchSerial.Get()) {
string name = obj["Name"] as string;
string classGuid = obj["ClassGuid"] as string;
string deviceID = obj["DeviceID"] as string;
if (classGuid != null && deviceID != null) {
if (String.Equals(classGuid, "{4d36e978-e325-11ce-bfc1-08002be10318}", StringComparison.InvariantCulture)) {
string[] tokens = deviceID.Split('&');
if (tokens.Length >= 4) {
string[] addressToken = tokens[4].Split('_');
string bluetoothAddress = addressToken[0];
Match m = regexPortName.Match(name);
string comPortNumber = "";
if (m.Success) {
comPortNumber = m.Groups[1].ToString();
}
if (Convert.ToUInt64(bluetoothAddress, 16) > 0) {
string bluetoothName = GetBluetoothRegistryName(bluetoothAddress);
portList.Add(String.Format("{0} {1} ({2})", bluetoothName, bluetoothAddress, comPortNumber));
}
}
}
}
}
return portList.ToArray();
}
private static string GetBluetoothRegistryName(string address)
{
string deviceName = "";
string registryPath = #"SYSTEM\CurrentControlSet\Services\BTHPORT\Parameters\Devices";
string devicePath = String.Format(#"{0}\{1}", registryPath, address);
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(devicePath)) {
if (key != null) {
Object o = key.GetValue("Name");
byte[] raw = o as byte[];
if (raw != null) {
deviceName = Encoding.ASCII.GetString(raw);
}
}
}
return deviceName;
}
Maybe it is not what you are looking for, and maybe you already found your answer...
I just found a question not exactly like yours but worked for me.. With this one you can find out which one of your COM Ports are from a Bluetooth device:
StackOverflow - Determine if serial port is normal COM or SPP
I hope it helps somehow. If you find out how to do what you wanted, please let me know. Thanks.
So, to get the information about a remote device including its name, using 32feet.NET do:
BluetoothAddress addr = ... ...
BluetoothDeviceInfo info = new BluetoothDeviceInfo(addr);
string name = info.DeviceName;
If not using the library you'll have to P/Invoke Win32's BluetoothGetDeviceInfo.
private static string FindSerialPortForRFIDReaderCore()
{
string serialPort = "";
List<string> ports = new List<string>();
System.Management.ManagementObjectSearcher Searcher = new System.Management.ManagementObjectSearcher("Select * from WIN32_SerialPort");
foreach (System.Management.ManagementObject Port in Searcher.Get())
{
if (Port["PNPDeviceID"].ToString().ToUpper().Contains("MacAddress"))
ports.Add(Port["DeviceID"].ToString());
}
if (ports.Count > 1) // There are more than one Serial Ports created for the bluetooth device.
serialPort = ports.OrderByDescending(p => p).FirstOrDefault();
else if(ports.Count == 1)
serialPort = ports[0];
return serialPort;
}