Guest User

Untitled

a guest
Feb 8th, 2018
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.39 KB | None | 0 0
  1. using System;
  2. using System.Diagnostics;
  3. using System.Linq;
  4. using Windows.Devices.WiFi;
  5. using Windows.Foundation.Diagnostics;
  6. using Windows.ApplicationModel.Background;
  7. using Windows.Networking.Connectivity;
  8. using Windows.Security.Credentials;
  9. using System.Threading.Tasks;
  10.  
  11. namespace WiFiConnector {
  12.  
  13. public sealed class StartupTask : IBackgroundTask {
  14.  
  15. // network details & credentials.
  16. private string networkName = "YOUR_SSID";
  17. private string username = "user";
  18. private string domain = "domain"; // optional; may be required in your environment.
  19. private string password = "password";
  20.  
  21. // log to the ETW provider Microsoft-Windows-Diagnostics-LoggingChannel
  22. LoggingChannel lc = new LoggingChannel("WiFiConnector", null, new Guid("4bd2826e-54a1-4ba9-bf63-92b73ea1ac4a"));
  23.  
  24. public async void Run(IBackgroundTaskInstance taskInstance) {
  25. BackgroundTaskDeferral deferral = taskInstance.GetDeferral();
  26.  
  27. WiFiAdapter firstAdapter;
  28.  
  29. do {
  30. // Request access to WiFiAdapter
  31. WiFiAccessStatus access = await WiFiAdapter.RequestAccessAsync();
  32.  
  33. if (WiFiAccessStatus.Allowed != access) {
  34. lc.LogMessage("WiFi Access is denied: " + access.ToString(), LoggingLevel.Error);
  35. }
  36.  
  37. lc.LogMessage("starting do loop.", LoggingLevel.Verbose);
  38.  
  39. var result = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector());
  40.  
  41. lc.LogMessage("Testing if we're connected already.", LoggingLevel.Information);
  42. if (networkName != GetCurrentWifiNetwork()) {
  43. lc.LogMessage("Not already connected to network; continuing.", LoggingLevel.Information);
  44. // not already connected.
  45.  
  46. if (result.Count >= 1) {
  47. lc.LogMessage(result.Count + " wifi adapter(s) found. Using first.", LoggingLevel.Information);
  48. firstAdapter = await WiFiAdapter.FromIdAsync(result[0].Id);
  49.  
  50. // get the list of available networks:
  51. lc.LogMessage("Getting nearby Wi-Fi networks.", LoggingLevel.Information);
  52. await firstAdapter.ScanAsync();
  53.  
  54. // make sure that networkName is available:
  55. var availableNetworks = firstAdapter.NetworkReport;
  56. lc.LogMessage(availableNetworks.AvailableNetworks.Count + " networks found.", LoggingLevel.Information);
  57.  
  58. WiFiAvailableNetwork correctNetwork = null;
  59.  
  60. foreach (var wifinetwork in availableNetworks.AvailableNetworks) {
  61. if (wifinetwork.Ssid == networkName) {
  62. lc.LogMessage(networkName + " found.");
  63. correctNetwork = wifinetwork;
  64. break;
  65. }
  66. }
  67.  
  68. if (null == correctNetwork) {
  69. lc.LogMessage("network not found.", LoggingLevel.Error);
  70. return; // proper network not visible, no reason to continue.
  71. }
  72.  
  73. WiFiReconnectionKind reconnectionKind = WiFiReconnectionKind.Automatic;
  74.  
  75. var credential = new PasswordCredential {
  76. UserName = username,
  77. Resource = domain, // optional
  78. Password = password
  79. };
  80.  
  81. WiFiConnectionResult wifiResult = null;
  82.  
  83. Task<WiFiConnectionResult> didConnect = null;
  84.  
  85. didConnect = firstAdapter.ConnectAsync(correctNetwork, reconnectionKind, credential).AsTask<WiFiConnectionResult>();
  86.  
  87. if (didConnect != null) {
  88. lc.LogMessage("Attempting connection to " + networkName + ".");
  89. wifiResult = await didConnect;
  90. }
  91.  
  92. if (wifiResult != null && wifiResult.ConnectionStatus == WiFiConnectionStatus.Success) {
  93. // we've connected. yay.
  94. lc.LogMessage("Connected.", LoggingLevel.Information);
  95. } else {
  96. // ooh, we failed to connect. !? That shoudln't happen.
  97. // do nothing so we can try again.
  98. lc.LogMessage(".. uhh, failed to connect. Check your credentials?", LoggingLevel.Error);
  99. }
  100.  
  101. } else {
  102. // no wifi adapters.
  103. lc.LogMessage("No Wi-Fi adapters found. :(", LoggingLevel.Error);
  104. }
  105. } else {
  106. // already connected. do nothin.
  107. lc.LogMessage("Already connected to correct network. Nothing to do.", LoggingLevel.Information);
  108. }
  109.  
  110. // we're doing this in a loop because we're an iot background application.
  111. lc.LogMessage("30 second delay before we try again or reconnect if disconnected.", LoggingLevel.Information);
  112. await Task.Delay(30000);
  113.  
  114. } while (true);
  115. }
  116.  
  117. private string GetCurrentWifiNetwork() {
  118. var connectionProfiles = NetworkInformation.GetConnectionProfiles();
  119.  
  120. if (connectionProfiles.Count < 1) {
  121. return null;
  122. }
  123.  
  124. var validProfiles = connectionProfiles.Where(profile => {
  125. return (profile.IsWlanConnectionProfile && profile.GetNetworkConnectivityLevel() != NetworkConnectivityLevel.None);
  126. });
  127.  
  128. if (validProfiles.Count() < 1) {
  129. return null;
  130. }
  131.  
  132. ConnectionProfile firstProfile = validProfiles.First();
  133.  
  134. return firstProfile.ProfileName;
  135. }
  136.  
  137. private bool IsConnected(WiFiAvailableNetwork network) {
  138. if (network == null) {
  139. return false;
  140. }
  141.  
  142. string profileName = GetCurrentWifiNetwork();
  143.  
  144. if (!String.IsNullOrEmpty(network.Ssid) && !String.IsNullOrEmpty(profileName) && (network.Ssid == profileName)) {
  145. return true;
  146. }
  147.  
  148. return false;
  149. }
  150. }
  151. }
Add Comment
Please, Sign In to add comment