public async Task <WiFiAdapter> Load() { if (!_hasLoaded) { _hasLoaded = true; if (!File.Exists(_settingsFilePath)) { return(null); } try { using (var reader = new BinaryReader(new FileStream(_settingsFilePath, FileMode.Open))) { ReconnectionKind = (WiFiReconnectionKind)reader.ReadByte(); Password = reader.ReadString(); DeviceId = reader.ReadString(); Bssid = reader.ReadString(); Ssid = reader.ReadString(); } } catch (Exception e) { Debug.WriteLine("Could not load WiFiSettings"); return(null); } } return(await WiFiConnector.Instance.GetAdapter(DeviceId));; }
/// <summary> /// Connect this Wi-Fi device to the specified network, with the specified passphrase and reconnection policy. /// </summary> /// <param name="availableNetwork">Describes the Wi-Fi network to be connected.</param> /// <param name="reconnectionKind">Specifies how to reconnect if the connection is lost.</param> /// <param name="passwordCredential">The passphrase to be used to connect to the access point.</param> /// <returns> /// On successful conclusion of the operation, returns an object that describes the result of the connect operation. /// </returns> public WiFiConnectionResult Connect(WiFiAvailableNetwork availableNetwork, WiFiReconnectionKind reconnectionKind, string passwordCredential) { lock (_syncLock) { return(new WiFiConnectionResult(NativeConnect(availableNetwork.Ssid, passwordCredential, reconnectionKind))); } }
public async Task <WiFiConnectionResult> ConnectAsync(WiFiNetworkDisplay network, WiFiReconnectionKind reconnectionKind, string password) { WiFiConnectionResult result; ReconnectionKind = reconnectionKind; if (network.AvailableNetwork.SecuritySettings.NetworkAuthenticationType == Windows.Networking.Connectivity.NetworkAuthenticationType.Open80211) { result = await _firstAdapter.ConnectAsync(network.AvailableNetwork, reconnectionKind); } else { // Only the password potion of the credential need to be supplied var credential = new PasswordCredential { Password = password }; result = await _firstAdapter.ConnectAsync(network.AvailableNetwork, reconnectionKind, credential); } // Since a connection attempt was made, update the connectivity level displayed for each foreach (var net in NetworkCollection) { net.UpdateConnectivityLevel(); } return(result); }
private async void btnConnect_Click(object sender, RoutedEventArgs e) { var access = await WiFiAdapter.RequestAccessAsync(); var wifiAdapterResults = await DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector()); WiFiAdapter wa = await WiFiAdapter.FromIdAsync(wifiAdapterResults[0].Id); WiFiReconnectionKind reconnectionKind = WiFiReconnectionKind.Automatic; WiFiConnectionResult result; foreach (var availableNetwork in _report.AvailableNetworks) { if (availableNetwork.Ssid == _selectedSSID) { if (txtPassword.Text.Length > 1) { var credential = new PasswordCredential(); credential.Password = txtPassword.Text; result = await wa.ConnectAsync(availableNetwork, reconnectionKind, credential); } else { result = await wa.ConnectAsync(availableNetwork, reconnectionKind); } } } }
private async void ConnectButton_Click(object sender, RoutedEventArgs e) { var selectedNetwork = ResultsListView.SelectedItem as WiFiNetworkDisplay; if (selectedNetwork == null || firstAdapter == null) { rootPage.NotifyUser("Network not selcted", NotifyType.ErrorMessage); return; } WiFiReconnectionKind reconnectionKind = WiFiReconnectionKind.Manual; if (IsAutomaticReconnection.IsChecked.HasValue && IsAutomaticReconnection.IsChecked == true) { reconnectionKind = WiFiReconnectionKind.Automatic; } WiFiConnectionResult result; if (selectedNetwork.AvailableNetwork.SecuritySettings.NetworkAuthenticationType == Windows.Networking.Connectivity.NetworkAuthenticationType.Open80211 && selectedNetwork.AvailableNetwork.SecuritySettings.NetworkEncryptionType == NetworkEncryptionType.None) { result = await firstAdapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind); } else { // Only the password potion of the credential need to be supplied var credential = new PasswordCredential(); credential.Password = NetworkKey.Password; result = await firstAdapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind, credential); } if (result.ConnectionStatus == WiFiConnectionStatus.Success) { rootPage.NotifyUser(string.Format("Successfully connected to {0}.", selectedNetwork.Ssid), NotifyType.StatusMessage); // refresh the webpage webViewGrid.Visibility = Visibility.Visible; toggleBrowserButton.Content = "Hide Browser Control"; refreshBrowserButton.Visibility = Visibility.Visible; } else { rootPage.NotifyUser(string.Format("Could not connect to {0}. Error: {1}", selectedNetwork.Ssid, result.ConnectionStatus), NotifyType.ErrorMessage); } // Since a connection attempt was made, update the connectivity level displayed for each foreach (var network in ResultCollection) { network.UpdateConnectivityLevel(); } }
public async Task <bool> ConnectAsync() { if (string.IsNullOrWhiteSpace(Setting.SSID)) { throw new InvalidOperationException("SSID can not be null!"); } await ScanAsync(); if (Networks.Count > 0) { var network = Networks.FirstOrDefault(n => n.Ssid == Setting.SSID); if (network != null) { availableNetwork = network; WiFiConnectionResult result; WiFiReconnectionKind kind = Setting.AutoReconnect ? WiFiReconnectionKind.Automatic : WiFiReconnectionKind.Manual; if (string.IsNullOrWhiteSpace(Setting.Password)) { result = await WiFiAdapter.ConnectAsync(network, kind); } else { var password = new PasswordCredential("Tello", "admin", Setting.Password); result = await WiFiAdapter.ConnectAsync(network, kind, password); } if (result.ConnectionStatus == WiFiConnectionStatus.Success) { IsConnected = true; return(true); } else { return(false); } } else { logger.LogError($"Can not find SSID:{Setting.SSID}."); throw new InvalidOperationException($"Can not find SSID:{Setting.SSID}."); } } else { logger.LogError("Can not find any WiFi signal."); throw new InvalidOperationException("Can not find any WiFi signal."); } }
private async void ConnectButton_Click(object sender, RoutedEventArgs e) { var selectedNetwork = ResultsListView.SelectedItem as WiFiNetworkDisplay; if (selectedNetwork == null || firstAdapter == null) { rootPage.NotifyUser("Network not selcted", NotifyType.ErrorMessage); return; } WiFiReconnectionKind reconnectionKind = WiFiReconnectionKind.Manual; if (IsAutomaticReconnection.IsChecked.HasValue && IsAutomaticReconnection.IsChecked == true) { reconnectionKind = WiFiReconnectionKind.Automatic; } WiFiConnectionResult result; if (selectedNetwork.AvailableNetwork.SecuritySettings.NetworkAuthenticationType == NetworkAuthenticationType.Open80211 && selectedNetwork.AvailableNetwork.SecuritySettings.NetworkEncryptionType == NetworkEncryptionType.None) { result = await firstAdapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind); } else { // Only the password portion of the credential need to be supplied var credential = new PasswordCredential(); // Make sure Credential.Password property is not set to an empty string. // Otherwise, a System.ArgumentException will be thrown. // The default empty password string will still be passed to the ConnectAsync method, // which should return an "InvalidCredential" error if (!string.IsNullOrEmpty(NetworkKey.Password)) { credential.Password = NetworkKey.Password; } result = await firstAdapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind, credential); } if (result.ConnectionStatus == WiFiConnectionStatus.Success) { rootPage.NotifyUser(string.Format("Successfully connected to {0}.", selectedNetwork.Ssid), NotifyType.StatusMessage); } else { rootPage.NotifyUser(string.Format("Could not connect to {0}. Error: {1}", selectedNetwork.Ssid, result.ConnectionStatus), NotifyType.ErrorMessage); } }
private async void OnItemClick(object sender, ItemClickEventArgs e) { var selectedNetwork = (WiFiNetworkDisplay)e.ClickedItem; WiFiReconnectionKind reconnectionKind = WiFiReconnectionKind.Automatic; WiFiConnectionResult result; if (selectedNetwork.AvailableNetwork.SecuritySettings.NetworkAuthenticationType == NetworkAuthenticationType.Open80211) { result = await firstAdapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind); ConnectResult(result); } else { if (selectedNetwork.ConnectivityLevel == "已连接") { firstAdapter.Disconnect(); await selectedNetwork.UpdateConnectivityLevel(); return; } if (selectedNetwork.Pwd.Length >= 8) { var credential = new PasswordCredential(); credential.Password = selectedNetwork.Pwd; result = await firstAdapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind, credential); ConnectResult(result); } else { var message = new PwdControl(async(x) => { var credential = new PasswordCredential(); credential.Password = x; result = await firstAdapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind, credential); ConnectResult(result); }); await message.ShowAsync(); } } }
public async Task ConnectWifiAsync(string bssid, string pwd) { var selectedNetwork = _wifisOriginals.First(w => w.Bssid == bssid); if (selectedNetwork == null || _firstAdapter == null) { //Network not selected" return; } WiFiReconnectionKind reconnectionKind = WiFiReconnectionKind.Automatic; WiFiConnectionResult result; if (selectedNetwork.AvailableNetwork.SecuritySettings.NetworkAuthenticationType == NetworkAuthenticationType.Open80211 && selectedNetwork.AvailableNetwork.SecuritySettings.NetworkEncryptionType == NetworkEncryptionType.None) { result = await _firstAdapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind); } else { // Only the password portion of the credential need to be supplied var credential = new PasswordCredential(); // Make sure Credential.Password property is not set to an empty string. // Otherwise, a System.ArgumentException will be thrown. // The default empty password string will still be passed to the ConnectAsync method, // which should return an "InvalidCredential" error //if (!string.IsNullOrEmpty(NetworkKey.Password)) //{ // credential.Password = NetworkKey.Password; //} result = await _firstAdapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind, credential); } if (result.ConnectionStatus == WiFiConnectionStatus.Success) { //string.Format("Successfully connected to {0}.", selectedNetwork.Ssid) } else { //string.Format("Could not connect to {0}. Error: {1}", selectedNetwork.Ssid, result.ConnectionStatus) } }
public void Save(WiFiReconnectionKind reconnectionKind, WiFiNetworkDisplay network, string deviceId, string password) { try { using (var writer = new BinaryWriter(new FileStream(_settingsFilePath, FileMode.Create))) { writer.Write((byte)reconnectionKind); writer.Write(password); writer.Write(deviceId); writer.Write(network.AvailableNetwork.Bssid); writer.Write(network.AvailableNetwork.Ssid); } } catch (Exception e) { Debug.WriteLine("Could not save WiFiSettings"); } }
/// <summary> /// This class initiates the GPIO pin output for relay control /// <param name="gpio"> Parameter description for s goes here.</param> /// </summary> public async void Connack() { //raw.Text = hoe.ToString(); //hoe++; if (!first) { var result = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector()); firstAdapter = await WiFiAdapter.FromIdAsync(result[0].Id); first = true; } if (!connacking) { try { connacking = true; try { await firstAdapter.ScanAsync(); } catch { } report = firstAdapter.NetworkReport; foreach (var network in report.AvailableNetworks) { if (network.Bssid == "00:1e:2a:0c:6a:9a") { WiFiReconnectionKind reKind = WiFiReconnectionKind.Automatic; PasswordCredential credential = new PasswordCredential(); credential.Password = "******"; WiFiConnectionResult results = await firstAdapter.ConnectAsync( network, reKind, credential); } } } catch { } connacking = false; } }
public async Task ConnectToWifi() { try { if ((adapterStatus = await GetWifiAdaptors()) == AdaptersStatus.hasAdapters) { await wifiAdapter.ScanAsync(); var network = wifiAdapter.NetworkReport.AvailableNetworks.Where(y => y.Ssid == SSID).FirstOrDefault(); var credential = new PasswordCredential { Password = this.Password }; WiFiReconnectionKind reconnectionKind = WiFiReconnectionKind.Automatic; await wifiAdapter.ConnectAsync(network, reconnectionKind, credential); } } catch (Exception ex) { Debug.WriteLine("ConnectToWifi() Exception: " + ex.Message); throw; } }
private async void ConnectToNetwork_ButtonClick(object sender, RoutedEventArgs e) { VirtualKeyboard.Visibility = Visibility.Collapsed; var selectedNetwork = ResultsListView.SelectedItem as WiFiNetworkDisplay; if (selectedNetwork == null) { //await UIMessager.Instance.ShowMessageAndWaitForFeedback("Network empty", "Network has not been selected!", UIMessageButtons.OK, UIMessageType.Information); return; } if (string.IsNullOrEmpty(NetworkPassword.Text)) { //await UIMessager.Instance.ShowMessageAndWaitForFeedback("Password empty", "Password cannot be empty!", UIMessageButtons.OK, UIMessageType.Information); return; } WiFiReconnectionKind reconnectionKind = WiFiReconnectionKind.Manual; //if (IsAutomaticReconnection) //always reconnect automatically { reconnectionKind = WiFiReconnectionKind.Automatic; } WiFiConnectionResult result = await WiFiConnector.Instance.ConnectAsync(selectedNetwork, reconnectionKind, NetworkPassword.Text); if (result.ConnectionStatus == WiFiConnectionStatus.Success) { WiFiSettings.Instance.Save(reconnectionKind, selectedNetwork, WiFiConnector.Instance.DeviceId, NetworkPassword.Text); //await UIMessager.Instance.ShowMessageAndWaitForFeedback("WiFi connected successfully!", string.Format("Successfully connected to {0}.", selectedNetwork.Ssid), UIMessageButtons.OK, UIMessageType.Information); } else { //await UIMessager.Instance.ShowMessageAndWaitForFeedback("WiFi connection error!", // string.Format("Could not connect to {0}. Error: {1}", selectedNetwork.Ssid, result.ConnectionStatus), // UIMessageButtons.OK, UIMessageType.Error); } }
private async void ConnectButton_Click(object sender, RoutedEventArgs e) { WiFiReconnectionKind reconnectionKind = WiFiReconnectionKind.Manual; if (ConnectAutomatically.IsChecked.HasValue && ConnectAutomatically.IsChecked.Value) { reconnectionKind = WiFiReconnectionKind.Automatic; } if (availableNetwork.SecuritySettings.NetworkAuthenticationType == NetworkAuthenticationType.Open80211) { await wifiAdapter.ConnectAsync(availableNetwork, reconnectionKind); } else { var credential = new PasswordCredential(); if (!string.IsNullOrEmpty(securityKey.Password)) { credential.Password = securityKey.Password; } await wifiAdapter.ConnectAsync(availableNetwork, reconnectionKind, credential); } }
protected override async void OnActivated(IActivatedEventArgs args) { Messages parameters = new Messages(); Frame rootFrame = Window.Current.Content as Frame; WiFiAdapter firstAdapter; WiFiConnectionResult result1; ObservableCollection <WiFiNetworkDisplay> ResultCollection = new ObservableCollection <WiFiNetworkDisplay>(); // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); rootFrame.NavigationFailed += OnNavigationFailed; if (args.PreviousExecutionState == ApplicationExecutionState.Terminated) { //TODO: Load state from previously suspended application } // Place the frame in the current Window Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter rootFrame.Navigate(typeof(WiFiConfigPage)); } // Ensure the current window is active Window.Current.Activate(); if (args.Kind == ActivationKind.Protocol) { ProtocolActivatedEventArgs eventArgs = args as ProtocolActivatedEventArgs; // Handle URI activation // The received URI is eventArgs.Uri.AbsoluteUri Uri myUri1 = new Uri(eventArgs.Uri.AbsoluteUri); WwwFormUrlDecoder decoder = new WwwFormUrlDecoder(myUri1.Query); String token = decoder.GetFirstValueByName("token"); String identifier = decoder.GetFirstValueByName("identifier"); String Ssid; String password; int numVal = Int32.Parse(identifier); WiFiProfile z = new WiFiProfile(); try { z = await OnboardingService.getInstance().getWiFiProfileAsync(token, identifier); } catch { parameters.Clear(); parameters.Notification = "Cannot get network profile "; parameters.Result = "Net or system error!"; rootFrame.Navigate(typeof(WiFiConfigPage), parameters); return; } Ssid = z.getUser_policies().getSsid(); parameters.Notification = "Start connecting to " + z.getUser_policies().getEap_type() + " network."; rootFrame.Navigate(typeof(WiFiConfigPage), parameters); System.Threading.Tasks.Task.Delay(TimeSpan.FromSeconds(5)); WiFiConfiguration wc = z.getWifiConfiguration(); Window.Current.Activate(); await CertificateEnrollmentManager.UserCertificateEnrollmentManager.ImportPfxDataAsync( z.getUser_policies().getPublic_ca(), "", ExportOption.NotExportable, KeyProtectionLevel.NoConsent, InstallOptions.None, "Test"); var access = await WiFiAdapter.RequestAccessAsync(); if (access != WiFiAccessStatus.Allowed) { parameters.Clear(); parameters.Notification = "No WiFi Adapter. Or access is denied!"; parameters.Result = "System error!"; rootFrame.Navigate(typeof(WiFiConfigPage), parameters); return; } else { switch (numVal) { case 2: { //////////////////////////////////////////////////////////////////// //EAP-TTLS var result = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector()); if (result.Count >= 1) { firstAdapter = await WiFiAdapter.FromIdAsync(result[0].Id); await firstAdapter.ScanAsync(); var report = firstAdapter.NetworkReport; // var message = string.Format("Network Report Timestamp: { 0}", report.Timestamp); var message = "Find "; ResultCollection.Clear(); foreach (var network in report.AvailableNetworks) { //Format the network information message += string.Format("NetworkName: {0}\n ", network.Ssid); ResultCollection.Add(new WiFiNetworkDisplay(network, firstAdapter)); } var q = ResultCollection.Where(X => X.Ssid == "ALCATEL1").FirstOrDefault(); if (q == null) { parameters.Clear(); parameters.Notification = "Cannot find network with ssid: " + Ssid; parameters.Result = "Net error!"; rootFrame.Navigate(typeof(WiFiConfigPage), parameters); return; } WiFiNetworkDisplay selectedNetwork = q; WiFiConnectionResult result0; WiFiReconnectionKind reconnectionKind = WiFiReconnectionKind.Manual; if (selectedNetwork.AvailableNetwork.SecuritySettings.NetworkAuthenticationType == Windows.Networking.Connectivity.NetworkAuthenticationType.Open80211) { result0 = await firstAdapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind); } else { var credential = new PasswordCredential(); String Password = z.getUser_policies().getPassword(); String Username = z.getUser_policies().getUsername(); credential.Password = "******"; // Password; credential.UserName = Username; parameters.Clear(); parameters.Notification = message; parameters.Result = string.Format("!!Connecting to {0} ", Ssid); rootFrame.Navigate(typeof(WiFiConfigPage), parameters); System.Threading.Tasks.Task.Delay(TimeSpan.FromSeconds(5)); result0 = await firstAdapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind, credential); } if (result0.ConnectionStatus == WiFiConnectionStatus.Success) { parameters.Clear(); parameters.Notification = string.Format("Successfully connected to {0}.", selectedNetwork.Ssid); parameters.Result = "Success!"; rootFrame.Navigate(typeof(WiFiConfigPage), parameters); // refresh the webpage // webViewGrid.Visibility = Visibility.Visible; // toggleBrowserButton.Content = "Hide Browser Control"; // refreshBrowserButton.Visibility = Visibility.Visible; } else { parameters.Clear(); parameters.Result = "Error!"; parameters.Notification = string.Format("Could not connect to {0}. Error: {1}", selectedNetwork.Ssid, result0.ConnectionStatus); rootFrame.Navigate(typeof(WiFiConfigPage), parameters); } } else { parameters.Clear(); parameters.Notification = "No WiFi Adapter. Or access is denied!"; parameters.Result = "System error!"; rootFrame.Navigate(typeof(WiFiConfigPage), parameters); return; } break; } /////////////////////////// case 1: { parameters.Clear(); parameters.Notification = "Not implemented yet"; parameters.Result = "System warning!"; rootFrame.Navigate(typeof(WiFiConfigPage), parameters); break; } case 3: { parameters.Clear(); parameters.Notification = "Not implemented yet"; parameters.Result = "System waninbg!"; rootFrame.Navigate(typeof(WiFiConfigPage), parameters); break; } case 4: { //////////////////////////////////////////////////////////////////// //EAP-PEAP var result = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector()); if (result.Count >= 1) { firstAdapter = await WiFiAdapter.FromIdAsync(result[0].Id); await firstAdapter.ScanAsync(); var report = firstAdapter.NetworkReport; // var message = string.Format("Network Report Timestamp: { 0}", report.Timestamp); var message = "Find "; ResultCollection.Clear(); foreach (var network in report.AvailableNetworks) { //Format the network information message += string.Format("NetworkName: {0}\n ", network.Ssid); ResultCollection.Add(new WiFiNetworkDisplay(network, firstAdapter)); } var q = ResultCollection.Where(X => X.Ssid == Ssid).FirstOrDefault(); if (q == null) { parameters.Clear(); parameters.Notification = "Cannot find network with ssid: " + Ssid; parameters.Result = "Net error!"; rootFrame.Navigate(typeof(WiFiConfigPage), parameters); return; } WiFiNetworkDisplay selectedNetwork = q; WiFiConnectionResult result0; WiFiReconnectionKind reconnectionKind = WiFiReconnectionKind.Manual; if (selectedNetwork.AvailableNetwork.SecuritySettings.NetworkAuthenticationType == Windows.Networking.Connectivity.NetworkAuthenticationType.Open80211) { result0 = await firstAdapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind); } else { var credential = new PasswordCredential(); String Password = z.getUser_policies().getPassword(); String Username = z.getUser_policies().getUsername(); credential.Password = Password; credential.UserName = Username; parameters.Clear(); parameters.Notification = message; parameters.Result = string.Format("Connecting to {0} ", Ssid); rootFrame.Navigate(typeof(WiFiConfigPage), parameters); System.Threading.Tasks.Task.Delay(TimeSpan.FromSeconds(5)); result0 = await firstAdapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind, credential); } if (result0.ConnectionStatus == WiFiConnectionStatus.Success) { parameters.Clear(); parameters.Notification = string.Format("Successfully connected to {0}.", selectedNetwork.Ssid); parameters.Result = "Success!"; rootFrame.Navigate(typeof(WiFiConfigPage), parameters); // refresh the webpage // webViewGrid.Visibility = Visibility.Visible; // toggleBrowserButton.Content = "Hide Browser Control"; // refreshBrowserButton.Visibility = Visibility.Visible; } else { parameters.Clear(); parameters.Result = "Error!"; parameters.Notification = string.Format("Could not connect to {0}. Error: {1}", selectedNetwork.Ssid, result0.ConnectionStatus); rootFrame.Navigate(typeof(WiFiConfigPage), parameters); } } else { parameters.Clear(); parameters.Notification = "No WiFi Adapter. Or access is denied!"; parameters.Result = "System error!"; rootFrame.Navigate(typeof(WiFiConfigPage), parameters); return; } break; } /////////////////////////// default: { break; } }//switch end } } }
private async void DoWifiConnect(object sender, RoutedEventArgs e, bool pushButtonConnect) { var selectedNetwork = ResultsListView.SelectedItem as WiFiNetworkDisplay; if (selectedNetwork == null || firstAdapter == null) { rootPage.NotifyUser("Network not selected", NotifyType.ErrorMessage); return; } var ssid = selectedNetwork.AvailableNetwork.Ssid; if (string.IsNullOrEmpty(ssid)) { if (string.IsNullOrEmpty(selectedNetwork.HiddenSsid)) { rootPage.NotifyUser("Ssid required for connection to hidden network.", NotifyType.ErrorMessage); return; } else { ssid = selectedNetwork.HiddenSsid; } } WiFiReconnectionKind reconnectionKind = WiFiReconnectionKind.Manual; if (selectedNetwork.ConnectAutomatically) { reconnectionKind = WiFiReconnectionKind.Automatic; } Task <WiFiConnectionResult> didConnect = null; WiFiConnectionResult result = null; if (pushButtonConnect) { if (ApiInformation.IsApiContractPresent("Windows.Foundation.UniversalApiContract", 5, 0)) { didConnect = firstAdapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind, null, string.Empty, WiFiConnectionMethod.WpsPushButton).AsTask(); } } else { PasswordCredential credential = new PasswordCredential(); if (selectedNetwork.IsEapAvailable && selectedNetwork.UsePassword) { if (!String.IsNullOrEmpty(selectedNetwork.Domain)) { credential.Resource = selectedNetwork.Domain; } credential.UserName = selectedNetwork.UserName ?? ""; credential.Password = selectedNetwork.Password ?? ""; } else if (!String.IsNullOrEmpty(selectedNetwork.Password)) { credential.Password = selectedNetwork.Password; } if (selectedNetwork.IsHiddenNetwork) { // Hidden networks require the SSID to be supplied didConnect = firstAdapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind, credential, ssid).AsTask(); } else { didConnect = firstAdapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind, credential).AsTask(); } } SwitchToItemState(selectedNetwork, WifiConnectingState, false); if (didConnect != null) { result = await didConnect; } if (result != null && result.ConnectionStatus == WiFiConnectionStatus.Success) { rootPage.NotifyUser(string.Format("Successfully connected to {0}.", selectedNetwork.Ssid), NotifyType.StatusMessage); // refresh the webpage webViewGrid.Visibility = Visibility.Visible; toggleBrowserButton.Content = "Hide Browser Control"; refreshBrowserButton.Visibility = Visibility.Visible; ResultCollection.Remove(selectedNetwork); ResultCollection.Insert(0, selectedNetwork); ResultsListView.SelectedItem = ResultsListView.Items[0]; ResultsListView.ScrollIntoView(ResultsListView.SelectedItem); SwitchToItemState(selectedNetwork, WifiConnectedState, false); } else { // Entering the wrong password may cause connection attempts to timeout // Disconnecting the adapter will return it to a non-busy state if (result.ConnectionStatus == WiFiConnectionStatus.Timeout) { firstAdapter.Disconnect(); } rootPage.NotifyUser(string.Format("Could not connect to {0}. Error: {1}", selectedNetwork.Ssid, (result != null ? result.ConnectionStatus : WiFiConnectionStatus.UnspecifiedFailure)), NotifyType.ErrorMessage); SwitchToItemState(selectedNetwork, WifiConnectState, false); } // Since a connection attempt was made, update the connectivity level displayed for each foreach (var network in ResultCollection) { var task = network.UpdateConnectivityLevelAsync(); } }
private extern WiFiConnectionStatus NativeConnect(string Ssid, string passwordCredential, WiFiReconnectionKind reconnectionKind);
private async void DoWifiConnect(object sender, RoutedEventArgs e, bool pushButtonConnect) { var selectedNetwork = ResultsListView.SelectedItem as WiFiNetworkDisplay; if (selectedNetwork == null || firstAdapter == null) { rootPage.NotifyUser("Network not selected", NotifyType.ErrorMessage); return; } WiFiReconnectionKind reconnectionKind = WiFiReconnectionKind.Manual; if (selectedNetwork.ConnectAutomatically) { reconnectionKind = WiFiReconnectionKind.Automatic; } Task <WiFiConnectionResult> didConnect = null; WiFiConnectionResult result = null; if (pushButtonConnect) { if (ApiInformation.IsApiContractPresent("Windows.Foundation.UniversalApiContract", 5, 0)) { didConnect = firstAdapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind, null, String.Empty, WiFiConnectionMethod.WpsPushButton).AsTask <WiFiConnectionResult>(); } } else if (selectedNetwork.IsEapAvailable) { if (selectedNetwork.UsePassword) { var credential = new PasswordCredential(); if (!String.IsNullOrEmpty(selectedNetwork.Domain)) { credential.Resource = selectedNetwork.Domain; } credential.UserName = selectedNetwork.UserName ?? ""; credential.Password = selectedNetwork.Password ?? ""; didConnect = firstAdapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind, credential).AsTask <WiFiConnectionResult>(); } else { didConnect = firstAdapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind).AsTask <WiFiConnectionResult>(); } } else if (selectedNetwork.AvailableNetwork.SecuritySettings.NetworkAuthenticationType == Windows.Networking.Connectivity.NetworkAuthenticationType.Open80211 && selectedNetwork.AvailableNetwork.SecuritySettings.NetworkEncryptionType == NetworkEncryptionType.None) { didConnect = firstAdapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind).AsTask <WiFiConnectionResult>(); } else { // Only the password potion of the credential need to be supplied if (String.IsNullOrEmpty(selectedNetwork.Password)) { didConnect = firstAdapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind).AsTask <WiFiConnectionResult>(); } else { var credential = new PasswordCredential(); credential.Password = selectedNetwork.Password ?? ""; didConnect = firstAdapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind, credential).AsTask <WiFiConnectionResult>(); } } SwitchToItemState(selectedNetwork, WifiConnectingState, false); if (didConnect != null) { result = await didConnect; } if (result != null && result.ConnectionStatus == WiFiConnectionStatus.Success) { rootPage.NotifyUser(string.Format("Successfully connected to {0}.", selectedNetwork.Ssid), NotifyType.StatusMessage); // refresh the webpage webViewGrid.Visibility = Visibility.Visible; toggleBrowserButton.Content = "Hide Browser Control"; refreshBrowserButton.Visibility = Visibility.Visible; ResultCollection.Remove(selectedNetwork); ResultCollection.Insert(0, selectedNetwork); ResultsListView.SelectedItem = ResultsListView.Items[0]; ResultsListView.ScrollIntoView(ResultsListView.SelectedItem); SwitchToItemState(selectedNetwork, WifiConnectedState, false); } else { rootPage.NotifyUser(string.Format("Could not connect to {0}. Error: {1}", selectedNetwork.Ssid, result.ConnectionStatus), NotifyType.ErrorMessage); SwitchToItemState(selectedNetwork, WifiConnectState, false); } // Since a connection attempt was made, update the connectivity level displayed for each foreach (var network in ResultCollection) { network.UpdateConnectivityLevel(); } }
private async void Connect_Click(object sender, RoutedEventArgs e) { var selectedNetwork = ResultsListView.SelectedItem as WiFiNetworkDisplay; if (selectedNetwork == null || adapter == null) { ConnectionStatusText.Text = "No network selected"; return; } WiFiReconnectionKind reconnectionKind = IsAutomaticReconnection.IsChecked.GetValueOrDefault() ? WiFiReconnectionKind.Automatic : WiFiReconnectionKind.Manual; WiFiConnectionResult result; if (selectedNetwork.AvailableNetwork.SecuritySettings.NetworkAuthenticationType == NetworkAuthenticationType.Open80211 && selectedNetwork.AvailableNetwork.SecuritySettings.NetworkEncryptionType == NetworkEncryptionType.None) { result = await adapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind); } else { // Only the password potion of the credential need to be supplied var credential = new PasswordCredential(); try { credential.Password = NetworkKey.Password; } catch (ArgumentException) { ConnectionStatusText.Text = "Password is invalid."; return; } result = await adapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind, credential); } var requiresWebview = false; if (result.ConnectionStatus == WiFiConnectionStatus.Success) { var connectedProfile = await adapter.NetworkAdapter.GetConnectedProfileAsync(); var level = connectedProfile.GetNetworkConnectivityLevel(); if (level == NetworkConnectivityLevel.ConstrainedInternetAccess || level == NetworkConnectivityLevel.LocalAccess) { ConnectionStatusText.Text = string.Format("Limited access on {0}.", selectedNetwork.Ssid); requiresWebview = true; } else { ConnectionStatusText.Text = string.Format("Successfully connected to {0}.", selectedNetwork.Ssid); } } else { ConnectionStatusText.Text = string.Format("Could not connect to {0}. Error: {1}", selectedNetwork.Ssid, result.ConnectionStatus); } webView.Visibility = requiresWebview ? Visibility.Visible : Visibility.Collapsed; // Since a connection attempt was made, update the connectivity level displayed for each foreach (var network in networks) { network.UpdateConnectivityLevel(); } }
public async Task ConnectAsync() { if (SelectedWiFiNetwork == null) { OnError?.Invoke(this, new ArgumentException("Network not selected")); return; } WiFiReconnectionKind reconnectionKind = WiFiReconnectionKind.Manual; if (SelectedWiFiNetwork.ConnectAutomatically) { reconnectionKind = WiFiReconnectionKind.Automatic; } Task <WiFiConnectionResult> didConnect = null; WiFiConnectionResult result = null; if (SelectedWiFiNetwork.IsEapAvailable) { if (SelectedWiFiNetwork.UsePassword) { var credential = new PasswordCredential(); if (!String.IsNullOrEmpty(SelectedWiFiNetwork.Domain)) { credential.Resource = SelectedWiFiNetwork.Domain; } credential.UserName = SelectedWiFiNetwork.UserName ?? ""; credential.Password = SelectedWiFiNetwork.Password ?? ""; didConnect = _wifiAdapter.ConnectAsync(SelectedWiFiNetwork.AvailableNetwork, reconnectionKind, credential).AsTask(); } else { didConnect = _wifiAdapter.ConnectAsync(SelectedWiFiNetwork.AvailableNetwork, reconnectionKind).AsTask(); } } else if (SelectedWiFiNetwork.AvailableNetwork.SecuritySettings.NetworkAuthenticationType == NetworkAuthenticationType.Open80211 && SelectedWiFiNetwork.AvailableNetwork.SecuritySettings.NetworkEncryptionType == NetworkEncryptionType.None) { didConnect = _wifiAdapter.ConnectAsync(SelectedWiFiNetwork.AvailableNetwork, reconnectionKind).AsTask(); } else { // Only the password potion of the credential need to be supplied if (String.IsNullOrEmpty(SelectedWiFiNetwork.Password)) { didConnect = _wifiAdapter.ConnectAsync(SelectedWiFiNetwork.AvailableNetwork, reconnectionKind).AsTask(); } else { var credential = new PasswordCredential(); credential.Password = SelectedWiFiNetwork.Password ?? ""; didConnect = _wifiAdapter.ConnectAsync(SelectedWiFiNetwork.AvailableNetwork, reconnectionKind, credential).AsTask(); } } OnConnecting?.Invoke(this, EventArgs.Empty); if (didConnect != null) { result = await didConnect; } if (result != null && result.ConnectionStatus == WiFiConnectionStatus.Success) { WiFiNetworks.Remove(SelectedWiFiNetwork); WiFiNetworks.Insert(0, SelectedWiFiNetwork); OnSelect?.Invoke(this, EventArgs.Empty); OnConnected?.Invoke(this, EventArgs.Empty); } else { OnError?.Invoke(this, new Exception("Could not connect to network")); OnDisconnected?.Invoke(this, EventArgs.Empty); } // Since a connection attempt was made, update the connectivity level displayed for each foreach (var network in WiFiNetworks) { await network.UpdateConnectivityLevel(); } }