BLE Scanning Devices - c#

I have this WinForms project which utilizes the 32feet library. The following code snippet is supposed to detect the BLE devices (Bluetooth Low Energy Devices) however, it returns the normal Bluetooth devices only.
Any idea?
private void blescan()
{
{
lsb_device.Items.Clear();
BluetoothRadio.PrimaryRadio.Mode = RadioMode.Connectable;
BluetoothClient client = new BluetoothClient();
BluetoothDeviceInfo[] devices = client.DiscoverDevices();
BluetoothClient bluetoothClient = new BluetoothClient();
String authenticated;
String classOfDevice;
String connected;
String deviceAddress;
String deviceName;
String installedServices;
String lastSeen;
String lastUsed;
String remembered;
String rssi;
foreach (BluetoothDeviceInfo device in devices)
{
lbl_status.Visible = true;
authenticated = device.Authenticated.ToString();
classOfDevice = device.ClassOfDevice.ToString();
connected = device.Connected.ToString();
deviceAddress = device.DeviceAddress.ToString();
deviceName = device.DeviceName.ToString();
installedServices = device.InstalledServices.ToString();
lastSeen = device.LastSeen.ToString();
lastUsed = device.LastUsed.ToString();
remembered = device.Remembered.ToString();
rssi = device.Rssi.ToString();
string[] row = new string[] { authenticated, classOfDevice, connected, deviceAddress, deviceName, installedServices, lastSeen, lastUsed, remembered, rssi };
lsb_device.Items.Add("Device Name:" + row[4] + " || MAC Address:" + row[3]);
}
lbl_status.Text = "Scan completed.";
}
}
Here's a screenshot for the scanning Form:

Related

getting serial number for usb using the usb name

I have winform application working on USB, I distribute the application on USB for the clients, I'm checking the the USB serial number if the application moved to another USB the application shows a message to the user that he cant run this app because he is not registered, I have a method getting the USB serial number by USB letter, but the problem is windows changing the USB letter dynamically, so its hard to get the USB letter and I cannot make the letter fixed so I can't read it.
I'm looking for a way to get the serial number for the USB by the USB Name is That possible ?? and if not what is the best way to manage my problem ??
Here is the Class I use to get the USB serial number :
class USBSerialNumber
{
string _serialNumber;
string _driveLetter;
public string getSerialNumberFromDriveLetter(string driveLetter)
{
this._driveLetter = driveLetter.ToUpper();
if (!this._driveLetter.Contains(":"))
{
this._driveLetter += ":";
}
matchDriveLetterWithSerial();
return this._serialNumber;
}
private void matchDriveLetterWithSerial()
{
string[] diskArray;
string driveNumber;
string driveLetter;
ManagementObjectSearcher searcher1 = new ManagementObjectSearcher("SELECT * FROM Win32_LogicalDiskToPartition");
foreach (ManagementObject dm in searcher1.Get())
{
diskArray = null;
driveLetter = getValueInQuotes(dm["Dependent"].ToString());
diskArray = getValueInQuotes(dm["Antecedent"].ToString()).Split(',');
driveNumber = diskArray[0].Remove(0, 6).Trim();
if (driveLetter == this._driveLetter)
{
/* This is where we get the drive serial */
ManagementObjectSearcher disks = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");
foreach (ManagementObject disk in disks.Get())
{
if (disk["Name"].ToString() == ("\\\\.\\PHYSICALDRIVE" + driveNumber) & disk["InterfaceType"].ToString() == "USB")
{
this._serialNumber = parseSerialFromDeviceID(disk["PNPDeviceID"].ToString());
}
}
}
}
}
private string parseSerialFromDeviceID(string deviceId)
{
string[] splitDeviceId = deviceId.Split('\\');
string[] serialArray;
string serial;
int arrayLen = splitDeviceId.Length - 1;
serialArray = splitDeviceId[arrayLen].Split('&');
serial = serialArray[0];
return serial;
}
private string getValueInQuotes(string inValue)
{
string parsedValue = "";
int posFoundStart = 0;
int posFoundEnd = 0;
posFoundStart = inValue.IndexOf("\"");
posFoundEnd = inValue.IndexOf("\"", posFoundStart + 1);
parsedValue = inValue.Substring(posFoundStart + 1, (posFoundEnd - posFoundStart) - 1);
return parsedValue;
}
}

Adding gsm sms to textbox or listbox (WinForm)

I have these codes for receiving sms from my gsm modem. It works but I want the messages to be viewed on a listbox or textbox. Can someone help me on how to do this?
public void Read()
{
gsmPort.WriteLine("AT+CMGF=1"); // Set mode to Text(1) or PDU(0)
Thread.Sleep(1000); // Give a second to write
gsmPort.WriteLine("AT+CPMS=\"SM\""); // Set storage to SIM(SM)
Thread.Sleep(1000);
gsmPort.WriteLine("AT+CMGL=\"ALL\""); // What category to read ALL, REC READ, or REC UNREAD
Thread.Sleep(1000);
gsmPort.Write("\r");
Thread.Sleep(1000);
string response = gsmPort.ReadExisting();
if (response.EndsWith("\r\nOK\r\n"))
{
Console.WriteLine(response);
// add more code here to manipulate reponse string.
}
else
{
// add more code here to handle error.
Console.WriteLine(response);
}
This is how I communicate with my modem using these codes. It works but only on console. I want add these to my winform
class GSMsms
{
private SerialPort gsmPort = null;
private bool IsDeviceFound { get; set; } = false;
public bool IsConnected { get; set; } = false;
public GSMsms()
{
gsmPort = new SerialPort();
}
public GSMcom[] List()
{
List<GSMcom> gsmCom = new List<GSMcom>();
ConnectionOptions options = new ConnectionOptions();
options.Impersonation = ImpersonationLevel.Impersonate;
options.EnablePrivileges = true;
string connString = $#"\\{Environment.MachineName}\root\cimv2";
ManagementScope scope = new ManagementScope(connString, options);
scope.Connect();
ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_POTSModem");
ManagementObjectSearcher search = new ManagementObjectSearcher(scope, query);
ManagementObjectCollection collection = search.Get();
foreach (ManagementObject obj in collection)
{
string portName = obj["AttachedTo"].ToString();
string portDescription = obj["Description"].ToString();
if (portName != "")
{
GSMcom com = new GSMcom();
com.Name = portName;
com.Description = portDescription;
gsmCom.Add(com);
}
}
return gsmCom.ToArray();
}

Get value from a list and work with it

I am trying to build an application sends emails by socks, messages will be sent per message if the first message is sent through a socks, the second should use a different socks, what I do in my application if I as I Recuper the information from a txt file and I add to list :
try
{
SmtpServer oServer = new SmtpServer("");
var list = new List<string>();
var input = File.ReadAllText(#"C:\New folder\SendMail6\socks-list.txt");
var r = new Regex(#"(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d{1,5})");
foreach (Match match in r.Matches(input))
{
string ip = match.Groups[1].Value;
string port = match.Groups[2].Value;
list.Add(ip);
list.Add(port);
}
foreach (string ip in list)
{
}
}
catch(Exception)
{
}
what I want that
oServer.SocksProxyServer = "37.187.118.174";
oServer.SocksProxyPort = 14115;
takes the values from the list I completed by ip values and port, and
if the first mail is sent by an ip the second mail is use another ip in list dont send tow email which follow by same ip
Thanks
You need to create a class for IP and Port
public class IpAndPort
{
public string IpAddress { get; set; }
public string Port { get; set; }
}
Now use ConcurrentBag
using System.Collections.Concurrent;
//------
var ips = new ConcurrentBag<IpAndPort>();
var input = File.ReadAllText(#"C:\New folder\SendMail6\socks-list.txt");
var r = new Regex(#"(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d{1,5})");
foreach (Match match in r.Matches(input))
{
string ip = match.Groups[1].Value;
string port = match.Groups[2].Value;
if(ips.Any(x => x.IpAddress.Trim() == ip.Trim()))
continue;
ips.Add(new IpAndPort { IpAddress = ip, Port = port});
}
Now send message by taking values from ConcurrentBag
while (!ips.IsEmpty)
{
IpAndPort ipAndPort;
if (!ips.TryTake(out ipAndPort)) continue;
try
{
//code here to send message using below IP and Port
var ip = ipAndPort.IpAddress;
var port = ipAndPort.Port;
/----
oServer = new SmtpServer("");
oServer.SocksProxyServer = ip;
oServer.SocksProxyPort = port;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}

How to connect WPA2-Enterprise authentication network in window application?

I have created wifi scanner in .net c# window application. Right now i'm able to connect to WPA2-Personal authentication network.Now i want to connect with WPA-Enterprise Network but i'm not getting any idea how to connect to it.
Please if you have any solution so let me know
Below is my code for WPA2-Personal which is working
WlanClient client = new WlanClient();
foreach (WlanClient.WlanInterface wlanIface in client.Interfaces)
{
Wlan.WlanAvailableNetwork[] networks = wlanIface.GetAvailableNetworkList(0);
foreach (Wlan.WlanAvailableNetwork network in networks)
{
Wlan.Dot11Ssid ssid = network.dot11Ssid;
string networkName = Encoding.ASCII.GetString(ssid.SSID, 0, (int)ssid.SSIDLength);
ListViewItem item = new ListViewItem(networkName);
item.SubItems.Add(network.dot11DefaultCipherAlgorithm.ToString());
item.SubItems.Add(network.wlanSignalQuality + "%");
item.SubItems.Add(network.dot11DefaultAuthAlgorithm.ToString());
listView1.Items.Add(item);
}
string profileName = "Network"; // this is also the SSID
string macA = "MAC_ADDRESS";
string key = "PASSWORD";
string profileXml = string.Format("<?xml version=\"1.0\" encoding=\"US-ASCII\"?><WLANProfile xmlns=\"http://www.microsoft.com/networking/WLAN/profile/v1\"><name>{0}</name><SSIDConfig><SSID><name>{0}</name></SSID></SSIDConfig><connectionType>ESS</connectionType><connectionMode>auto</connectionMode><autoSwitch>false</autoSwitch><MSM><security><authEncryption><authentication>WPAPSK</authentication><encryption>TKIP</encryption><useOneX>false</useOneX></authEncryption><sharedKey><keyType>passPhrase</keyType><protected>false</protected><keyMaterial>{1}</keyMaterial></sharedKey></security></MSM></WLANProfile>", profileName, key); //WPA-PSK
wlanIface.SetProfile(Wlan.WlanProfileFlags.AllUser, profileXml, true);
wlanIface.Connect(Wlan.WlanConnectionMode.Profile, Wlan.Dot11BssType.Any, profileName);
}

Simple Net Scanner Only works Wireless but not wired

I found this C# code for simple IP net scanner which scans the connected hosts in the network and displays its physical address and IP address.It works well but only when connected with the network via WIFI. It doesn't work when connected through the network via wires.
[DllImport("iphlpapi.dll", ExactSpelling = true)]
At first, iphlpapi.dll has been imported. So, can you explain it? the rest of the code is given below.
// Use Your work Group WinNT://&&&&(Work Group Name)
DirectoryEntry DomainEntry = new DirectoryEntry("WinNT://" + this.TxtWorkGroup.Text.Trim());
DomainEntry.Children.SchemaFilter.Add("computer");
// To Get all the System names And Display with the Ip Address
foreach (DirectoryEntry machine in DomainEntry.Children)
{
string[] Ipaddr = new string[3];
Ipaddr[0] = machine.Name;
System.Net.IPHostEntry Tempaddr = null;
try
{
Tempaddr = (System.Net.IPHostEntry)Dns.GetHostByName(machine.Name);
}
catch (Exception)
{
MessageBox.Show("Unable to connect with the system :" + machine.Name);
continue;
}
IPAddress[] TempAd = Tempaddr.AddressList;
foreach (IPAddress TempA in TempAd)
{
Ipaddr[1] = TempA.ToString();
byte[] ab = new byte[6];
int len = ab.Length;
// This Function Used to Get The Physical Address
int r = SendARP((int)TempA.Address, 0, ab, ref len);
string mac = BitConverter.ToString(ab, 0, 6);
Ipaddr[2] = mac;
}
ListViewItem TempItem = new ListViewItem(Ipaddr);
this.ListHostIP.Items.Add(TempItem);
}
}
Turn off the WIFI adapter and try it again.

Categories