List of available wifi connections using Xamarin Forms - xamarin

I am looking for an example to list all wifi connections that are availables by using Xamarin Forms.
All of examples that I found was to check if the current connection is on or off. But I'd like to list all avaliable connections and get all of information about them.
I am not sure if this plugin "Plugin.Connectivity" could help me but it was the more close I got from my goal.

The Connectivity (which is now part of Xamarin.Essentials) plugin is not going to help with this, unfortunately. It only allows you to see if you have a connection and tells you something about that.
As far as I know, there is no library for this and you will have to write custom code for this. I'm not sure what platforms you are targeting, I'll assume iOS and Android.
For iOS, you probably want to look at the NEHotspotHelper and list the SupportedNetworkInterfaces property. And do something like this:
foreach (var network in NEHotspotHelper.SupportedNetworkInterfaces)
Console.WriteLine(network.Ssid);
Don't forget to enable the NetworkExtensions entitlement in the Entitlements.plist
For Android, the code could look something like this:
WlanClient client = new WlanClient();
foreach ( WlanClient.WlanInterface wlanIface in client.Interfaces )
{
// Lists all networks
Wlan.WlanAvailableNetwork[] networks = wlanIface.GetAvailableNetworkList( 0 );
foreach ( Wlan.WlanAvailableNetwork network in networks )
{
Console.WriteLine( "Found network with SSID {0}.", GetStringForSSID(network.dot11Ssid));
}
}
On Android, you will need an extra permission to be able to do this.
To make it suitable for Forms, wrap it into a DependencyService and move back and forth the information you need.

Related

NSNetService says it is published, but it isn't visible on the network

I'm working on a little iOS app for my own use (initially, at least) and I thought I would use Bonjour to configure networking between two iOS devices.
My server's interface defines
NSNetService *netService;
and the implementation uses the following code to advertise its existence:
const NSString *kSEBonjourServiceDomain = #""; //use defaults
const NSString *kSEBonjourServiceName = #"_test._tcp.";
//...
netService = [[NSNetService alloc] initWithDomain:(NSString *)kSEBonjourServiceDomain type:(NSString *)kSEBonjourServiceName name:#"" port:sin.sin_port];
if (netService)
{
netService.delegate = self;
netService.includesPeerToPeer = YES;
[netService publish];
}
else NSLog(#"Failed to create NSNetService");
When I start the server, my NSNetService object does call the -netServiceDidPublish: delegate method, but when I use Discovery to browse the bonjour services on my network, my service doesn't appear. Apart from the const strings, this code is the same as some code in one of my Mac apps (which works as expected) and also very similar to Apple's sample code.
I've gone through all the options in Xcode's capabilities tab in case I needed to add something there, but I can't see anything relevant. I've also read a bunch of documents and tutorials that don't mention having to do anything more than that, but it wouldn't surprise me to learn that this only works on iOS if you set an obscure build setting to a string that you had to learn about by reading the Human Interface Guidelines for watchOS last September.
So, can anyone enlighten me? What am I missing?
Thanks in advance!
It turned out that due to a silly error elsewhere in my code, sin.sin_port was set to 0 by the time I was registering my NSNetService. Although NSNetService doesn't see this as a problem, it was causing the service to be ignored by service browsers.
So the answer is, a service with a port of 0 will register without error, but won't work.
Thanks to gaige for the assistance.

Waiting on input from Socket in Xamarin Froms

GOAL
The application needs to constantly read from a socket - and when it receives a line that is not empty it needs to do an appropriate action.
Issue
From what I researched you can't do services in Xamarin Forms, since each service is platform dependent. (IOS, Andoird, Windows). So what I am looking for as a way to constantly monitor inputs from a Bluetooth port in this case, simply by calling a already defined function.
Tried
I tried using a Refresh view. But there were issues with that from a code point of view and a visual point of view.
Current Code
This is what I have tried, but unfortuntately it has mixed results. The socket seems to connect when first pairing but then closed if I try to read:
Device.StartTimer(TimeSpan.FromMilliseconds(miliseconds), () =>
{
command.Execute(null);
return true;
});

How to check internet connection one time i.e. not continuously?

I am building Xamarin.Forms app that pretty much works offline except a few calls to a web-service. Now I need to check internet connection just before I make a request, but I cannot find a solution or an answer that would allow checking internet connection only once not continuously
You could use Xamarin.Essentials and specifically Connectivity class as CrossConnectivity features have been consolidated into Xamarin.Essentials toolkit.
var connect = Connectivity.NetworkAccess;
if (connect != NetworkAccess.Internet) Message = "Device does not have internet access.";
else { // api call }
You can use the ConnectivityPlugin by James Montemagno
Nuget can be found here
For check the internet you just have to do this:
if(CrossConnectivity.Current.IsConnected)
{
//You are connected to the internet!!!
}
You might wanna check this: https://jamesmontemagno.github.io/ConnectivityPlugin/CheckingConnectivity.html
Xamarin Essentials Connectivity is also an option.
if (Connectivity.NetworkAccess == NetworkAccess.Internet)
{
//You are connected to the internet!!!
}

Wifi WPS client start in Windows 10 in script or code

I can not find how to start WPS client in Windows 10 from command prompt or powershell. When I used Linux, everything was really ease with wla_supplicant (wpa_cli wps_pbc). Is there something similar in Windows?
Does anyone know how to set up Wi-Fi network (over WPS) key without human input in Windows?
I also tried WCN (Windows Connect Now) from Microsoft as it implements WPS features. I got also samples from Windows SDK on WCN, but they could not get key by WPS (it faild). But if I use Windows user interface to connect wiothout PIN, everyting seems to be pretty fine.
I am sure that there is possibility to do that, it is very important to perform Wifi Protected Setup by button start from the command prompt or app (C++/C#) without human intrusion or input (once WPS is on air, Windows should automatically get the network key and connect then).
I don't know if it's too late to answer, just put what I know in here and hope it can help.
First, if your system has updated to 16299(Fall Creator Update), you can just simply use new wifi api from UWP.
Install newest Windows SDK, create a C# console project, target C# version to at least 7.1, then add two reference to the project.
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETCore\v4.5\System.Runtime.WindowsRuntime.dll
C:\Program Files (x86)\Windows Kits\10\UnionMetadata\10.0.16299.0\Windows.winmd
After all of that , code in below should work.
using System;
using System.Threading.Tasks;
using Windows.Devices.Enumeration;
using Windows.Devices.WiFi;
class Program
{
static async Task Main(string[] args)
{
var dic = await DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector());
if (dic.Count > 0)
{
var adapter = await WiFiAdapter.FromIdAsync(dic[0].Id);
foreach (var an in adapter.NetworkReport.AvailableNetworks)
{
if (an.Ssid == "Ssid which you want to connect to.")
{
// Fouth parameter which is ssid can not be set to null even if we provided
// first one, or an exception will be thrown.
await adapter.ConnectAsync(an, WiFiReconnectionKind.Manual, null, "",
WiFiConnectionMethod.WpsPushButton);
}
}
}
}
}
Build and run the exe, then push your router's button, your pc will be connect to the router.
But if you can not update to 16299, WCN will be your only choice. You may already notice that if call IWCNDevic::Connect frist with push-button method, the WSC(Wifi Simple Configuration) session will fail. That's because WNC would not start a push-button session as a enrollee, but only as a registrar. That means you have to ensure that router's button has been pushed before you call IWCNDevic::Connect. The way to do that is using Native Wifi api to scan your router repeatedly, analyse the newest WSC information element from the scan result, confirm that Selected Registrar attribute has been set to true and Device Password Id attribute has been set to 4. After that, query the IWCNDevice and call Connect function will succeed. Then you can call IWCNDevice::GetNetworkProfile to get a profile that can use to connect to the router. Because it's too much of code, I will only list the main wifi api that will be used.
WlanEnuminterfaces: Use to get a available wifi interface.
WlanRegisterNotification: Use to register a callback to handle scan an connect results.
WlanScan: Use to scan a specified wifi BSS.
WlanGetNetworkBsslist: Use to get newest BSS information after scan.
WlanSetProfile: Use to save profile for a BSS.
WlanConnect: Use to connect to a BSS.
And about the WSC information element and it's attributes, you can find all the information from Wi-Fi Simple Configuration Technical Specification v2.0.5.
For Krisz. About timeout.
You can't cast IAsyncOperation to Task directly. The right way to do that is using AsTask method. And also, you should cancel ConnectAsync after timeout.
Sample code:
var t = adapter.ConnectAsync(an, WiFiReconnectionKind.Manual, null, "",
WiFiConnectionMethod.WpsPushButton).AsTask();
if (!t.Wait(10000))
t.AsAsyncOperation().Cancel();

How can I save some user data locally on my Xamarin Forms app?

I have a simple Xamarin Forms app. I've now got a simple POCO object (eg. User instance or an list of the most recent tweets or orders or whatever).
How can I store this object locally to the device? Lets imagine I serialize it as JSON.
Also, how secure is this data? Is it part of Keychains, etc? Auto backed up?
cheers!
You have a couple options.
SQLite. This option is cross-platform and works well if you have a lot of data. You get the added bonus of transaction support and async support as well. EDIT: In the past I suggested using SQLite.Net-PCL. Due to issues involving Android 7.0 support (and an apparent sunsetting of support) I now recommend making use of the project that was originally forked from: sqlite-net
Local storage. There's a great nuget that supports cross-platform storage. For more information see PCLStorage
There's also Application.Current.Properties implemented in Xamarin.Forms that allow simple Key-Value pairs of data.
I think you'll have to investigate and find out which route serves your needs best.
As far as security, that depends on where you put your data on each device. Android stores app data in a secure app folder by default (not all that secure if you're rooted). iOS has several different folders for data storage based on different needs. Read more here: iOS Data Storage
Another option is the Xamarin Forms settings plugin.
E.g. If you need to store a user instance, just serialize it to json when storing and deserialize it when reading.
Uses the native settings management
Android: SharedPreferences
iOS: NSUserDefaults
Windows Phone: IsolatedStorageSettings
Windows RT / UWP: ApplicationDataContainer
public User CurrentUser
{
get
{
User user = null;
var serializedUser = CrossSettings.Current.GetValueOrDefault<string>(UserKey);
if (serializedUser != null)
{
user = JsonConvert.DeserializeObject<User>(serializedUser);
}
return user;
}
set
{
CrossSettings.Current.AddOrUpdateValue(UserKey, JsonConvert.SerializeObject(value));
}
}
EDIT:
There is a new solution for this. Just use Xamarin.Essentials.
Preferences.Set(UserKey, JsonConvert.SerializeObject(value));
var user= JsonConvert.DeserializeObject<User>(Preferences.Get(UserKey, "default_value");
Please use Xamarin.Essentials
The Preferences class helps to store application preferences in a key/value store.
To save a value:
Preferences.Set("my_key", "my_value");
To get a value:
var myValue = Preferences.Get("my_key", "default_value");
If you want to store a simple value, such as a string, follow this Example code.
setting the value of the "totalSeats.Text" to the "SeatNumbers" key from page1
Application.Current.Properties["SeatNumbers"] = totalSeats.Text;
await Application.Current.SavePropertiesAsync();
then, you can simply get the value from any other page (page2)
var value = Application.Current.Properties["SeatNumbers"].ToString();
Additionally, you can set that value to another Label or Entry etc.
SeatNumbersEntry.Text = value;
If it's Key value(one value) data storage, follow below code
Application.Current.Properties["AppNumber"] = "123"
await Application.Current.SavePropertiesAsync();
Getting the same value
var value = Application.Current.Properties["AppNumber"];

Resources