/// <summary> /// Starts the authentication process. /// </summary> /// <param name="provider">The provider to authenticate with.</param> public async Task AuthenticateAsync(MobileServiceAuthenticationProvider provider) { try { var vault = new PasswordVault(); // Login with the identity provider. var user = await AzureAppService.Current .LoginAsync(provider); // Create and store the user credentials. var credential = new PasswordCredential(provider.ToString(), user.UserId, user.MobileServiceAuthenticationToken); vault.Add(credential); } catch (InvalidOperationException invalidOperationException) { if (invalidOperationException.Message .Contains("Authentication was cancelled by the user.")) { throw new AuthenticationCanceledException("Authentication canceled by user", invalidOperationException); } throw new AuthenticationException("Authentication failed", invalidOperationException); } catch (Exception e) { throw new AuthenticationException("Authentication failed", e); } }
private HttpClient client; // need to use same client to keep the cookies (for now) public MUConnector(PasswordCredential p) { user = p.UserName.ToLower(); //netid must be lowercase (yeah idk either) p.RetrievePassword(); password = p.Password; InitClient(); }
private async Task<bool> Login(string username, string password, bool storeCredentials, bool fromStored) { var content = new HttpFormUrlEncodedContent(new[] { new KeyValuePair<string,string>("email", username), new KeyValuePair<string, string>("password", password) }); try { var result = await client.PostAsync(new Uri("http://localhost:8002/api/login"), content); if( result.IsSuccessStatusCode ) { if (!fromStored) { // interactive login, clear current credentials, and if user wishes to store, do so RemoveStoredCredentials(); if (storeCredentials) { var cred = new PasswordCredential(LANGTUTORLOGIN_RES, username, password); passwordVault.Add(cred); } } return true; } else { return false; } } catch(Exception ex) { return false; } }
public static void SaveCredential(string userName, string password) { PasswordVault passwordVault = new PasswordVault(); PasswordCredential passwordCredential = new PasswordCredential(RESOURCE, userName, password); passwordVault.Add(passwordCredential); }
public static void SaveCredentialToLocker(MobileCredentials mobileCredentials) { // clean up var vault = new PasswordVault(); try { var credentialList = vault.FindAllByResource(ResourceName); foreach (var passwordCredential in credentialList) { vault.Remove(passwordCredential); } } // ReSharper disable once EmptyGeneralCatchClause catch (Exception) { } var credential = new PasswordCredential { Resource = ResourceName, UserName = mobileCredentials.MobileNumber, Password = mobileCredentials.Password }; vault.Add(credential); }
public void SaveCredentials(string resource, string username, string password) { // Create and store the user credentials. var credential = new PasswordCredential(resource, username, password); _vault.Add(credential); }
private void Save_Click(object sender, RoutedEventArgs e) { String result = ""; if (InputResourceValue.Text == "" || InputUserNameValue.Text == "" || InputPasswordValue.Password == "") { rootPage.NotifyUser("Inputs are missing. Resource, User name and Password are required", NotifyType.ErrorMessage); } else { try { //Add a credential to PasswordVault by supplying resource, username, and password PasswordVault vault = new PasswordVault(); PasswordCredential cred = new PasswordCredential(InputResourceValue.Text, InputUserNameValue.Text, InputPasswordValue.Password); vault.Add(cred); //Output credential added to debug spew rootPage.NotifyUser("Credential saved successfully. " + "Resource: " + cred.Resource.ToString() + " Username: "******" Password: "******".", NotifyType.StatusMessage); } catch (Exception Error) // No stored credentials, so none to delete { rootPage.NotifyUser(Error.Message, NotifyType.ErrorMessage); } } }
// Log the user in with specified provider (Microsoft Account or Facebook) private async Task AuthenticateAsync() { // Use the PasswordVault to securely store and access credentials. PasswordVault vault = new PasswordVault(); PasswordCredential credential = null; try { // Try to get an existing credential from the vault. credential = vault.FindAllByResource(provider).FirstOrDefault(); } catch (Exception) { // do nothing } if (credential != null) { // Create a user from the stored credentials. user = new MobileServiceUser(credential.UserName); credential.RetrievePassword(); user.MobileServiceAuthenticationToken = credential.Password; // Set the user from the stored credentials. App.MobileService.CurrentUser = user; try { // Try to return an item now to determine if the cached credential has expired. await App.MobileService.GetTable<Event>().Take(1).ToListAsync(); } catch (MobileServiceInvalidOperationException ex) { if (ex.Response.StatusCode == System.Net.HttpStatusCode.Unauthorized) { // Remove the credential with the expired token. vault.Remove(credential); credential = null; } } } else { try { // Login with the identity provider. user = await App.MobileService.LoginAsync(provider); // Create and store the user credentials. credential = new PasswordCredential(provider, user.UserId, user.MobileServiceAuthenticationToken); vault.Add(credential); } catch (MobileServiceInvalidOperationException ex) { Debug.WriteLine(ex.StackTrace); } } }
public void SaveCredentials(string resource, string userName, string password) { var vault = new PasswordVault(); RemoveAllCredentialsByResource(resource, vault); // Add the new credential var passwordCredential = new PasswordCredential(resource, userName, password); vault.Add(passwordCredential); }
public async Task<User> AuthenticateAsync(string userName, string password, bool useSecureLogin = false) { User user = null; if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password)) { var client = this.GetHttpClient(useSecureLogin); try { TokenResponse = await client.RequestResourceOwnerPasswordAsync(userName, password); if (TokenResponse != null) { if (TokenResponse.IsError) { throw new UnauthorizedAccessException(this.m_strUnauthorizedAccessExceptionMessage); } Windows.Storage.ApplicationData.Current.RoamingSettings.Values["username"] = userName; Windows.Storage.ApplicationData.Current.RoamingSettings.Values["usesecurelogin"] = useSecureLogin; Windows.Security.Credentials.PasswordVault vault = new Windows.Security.Credentials.PasswordVault(); PasswordCredential passwordCredential = new PasswordCredential(PasswordVaultResourceName, userName, password); vault.Add(passwordCredential); if (passwordCredential != null) { user = new User { UserName = userName, UseSecureLogin = useSecureLogin }; m_settingsService.User = user; } } } catch (UnauthorizedAccessException) { throw new UnauthorizedAccessException(this.m_strUnauthorizedAccessExceptionMessage); } catch (Exception exception) { NullReferenceException nullReferenceException = exception as NullReferenceException; if (nullReferenceException != null) { //there could be a nullreference exception at account change when the login is encrypted. throw new UnauthorizedAccessException(this.m_strEncryptedLoginException); } throw exception; } } else { throw new UnauthorizedAccessException(this.m_strUnauthorizedAccessExceptionMessage); } return user; }
public void AddCredentials(string username, string password) { // First clear all APAN App Credentials from the PasswordVault to ensure only one credential ever exists for the app. ClearAllCredentials(); if(!String.IsNullOrEmpty(username) && !String.IsNullOrEmpty(password)) { PasswordCredential credentials = new PasswordCredential(); credentials = new PasswordCredential("WANDAppCredentials", username, password); this._passwordVault.Add(credentials); } }
private async System.Threading.Tasks.Task AuthenticateAsync(String provider) { string message; // Use the PasswordVault to securely store and access credentials. PasswordVault vault = new PasswordVault(); PasswordCredential credential = null; while (credential == null) { try { // Try to get an existing credential from the vault. credential = vault.FindAllByResource(provider).FirstOrDefault(); } catch (Exception) { // When there is no matching resource an error occurs, which we ignore. } if (credential != null) { // Create a user from the stored credentials. _user = new MobileServiceUser(credential.UserName); credential.RetrievePassword(); _user.MobileServiceAuthenticationToken = credential.Password; // Set the user from the stored credentials. App.MobileService.CurrentUser = _user; try { // Try to return an item now to determine if the cached credential has expired. await App.MobileService.GetTable<TrainingItem>().Take(1).ToListAsync(); } catch (MobileServiceInvalidOperationException ex) { if (ex.Response.StatusCode == System.Net.HttpStatusCode.Unauthorized) { // Remove the credential with the expired token. vault.Remove(credential); credential = null; continue; } } } else { try { // Login with the identity provider. _user = await App.MobileService.LoginAsync(provider); // Create and store the user credentials. credential = new PasswordCredential(provider, _user.UserId, _user.MobileServiceAuthenticationToken); vault.Add(credential); } catch (MobileServiceInvalidOperationException ex) { message = "You must log in. Login Required"; } } message = string.Format("You are now logged in - {0}", _user.UserId); var dialog = new MessageDialog(message); dialog.Commands.Add(new UICommand("OK")); await dialog.ShowAsync(); } }
public void UpdateCredentialsInVault(PasswordCredential passwordCredential) { var vault = new PasswordVault(); var credentials = GetCredentialsFromVault(vault); if (credentials != null) { vault.Remove(credentials); } vault.Add(passwordCredential); }
public static void SaveCredential(string username, string password) { if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password)) return; //用于保证只存在一个用户信息 RemoveCredential(); PasswordVault vault = new PasswordVault(); PasswordCredential cred = new PasswordCredential(CredentialSource, username, password); vault.Add(cred); }
private static void SetPassword() { PasswordVault passwordVault = new PasswordVault(); var credentials = new PasswordCredential() { UserName = UserNameText, Resource = ResourceText, Password = PasswordGenerator.Next(PasswordLength) }; passwordVault.Add(credentials); }
// Define a method that performs the authentication process // using a Twitter sign-in. private async Task<bool> AuthenticateAsync() { string message; bool success = false; // This sample uses the Facebook provider. var provider = "Twitter"; // Use the PasswordVault to securely store and access credentials. PasswordVault vault = new PasswordVault(); PasswordCredential credential = null; try { // Try to get an existing credential from the vault. credential = vault.FindAllByResource(provider).FirstOrDefault(); } catch (Exception) { // When there is no matching resource an error occurs, which we ignore. } if (credential != null) { // Create a user from the stored credentials. user = new MobileServiceUser(credential.UserName); credential.RetrievePassword(); user.MobileServiceAuthenticationToken = credential.Password; // Set the user from the stored credentials. App.MobileService.CurrentUser = user; // Consider adding a check to determine if the token is // expired, as shown in this post: http://aka.ms/jww5vp. success = true; message = string.Format("Cached credentials for user - {0}", user.UserId); } else { try { // Login with the identity provider. user = await App.MobileService .LoginAsync(provider); // Create and store the user credentials. credential = new PasswordCredential(provider, user.UserId, user.MobileServiceAuthenticationToken); vault.Add(credential); success = true; } catch (MobileServiceInvalidOperationException) { message = "You must log in. Login Required"; } } return success; }
public async Task<bool> AuthenticateAsync() { this.CurrentUserId = null; PasswordCredential credential; if (TryGetCachedCredential(out credential)) { var user = new MobileServiceUser(credential.UserName); credential.RetrievePassword(); user.MobileServiceAuthenticationToken = credential.Password; this.serviceClient.CurrentUser = user; if (await HasTokenExpired()) { vault.Remove(credential); } else { this.CurrentUserId = user.UserId; this.IsAuthenticated = true; } } if (!this.IsAuthenticated) { try { var user = await this.serviceClient .LoginAsync(MobileServiceAuthenticationProvider.MicrosoftAccount); credential = new PasswordCredential( MobileServiceAuthenticationProvider.MicrosoftAccount.ToString(), user.UserId, user.MobileServiceAuthenticationToken); vault.Add(credential); this.CurrentUserId = user.UserId; this.IsAuthenticated = true; } catch (MobileServiceInvalidOperationException) { this.IsAuthenticated = false; } } return this.IsAuthenticated; }
public void PutSecret(string name, string value) { PasswordCredential existingCredential = GetCredential(name); if (existingCredential != null) { m_store.Remove(existingCredential); } if (string.IsNullOrEmpty(value)) { return; } var credential = new PasswordCredential(MakeResourceName(name), m_storeName, value); m_store.Add(credential); }
public WinRtHttpClientFactory(IWinRtHttpClientFactoryParameters parameters, IWebReaderManagerParameters webReaderManagerParameters, IHttpProductInfoHeaderValueFactory httpProductInfoFactory, Func<HttpBaseProtocolFilter> httpClientHandlerFactory) { if (null == parameters) throw new ArgumentNullException(nameof(parameters)); if (null == webReaderManagerParameters) throw new ArgumentNullException(nameof(webReaderManagerParameters)); if (null == httpProductInfoFactory) throw new ArgumentNullException(nameof(httpProductInfoFactory)); if (null == httpClientHandlerFactory) throw new ArgumentNullException(nameof(httpClientHandlerFactory)); _referrer = parameters.Referrer; _userAgent = httpProductInfoFactory.Create(); _credentials = parameters.Credentials; _webReaderManagerParameters = webReaderManagerParameters; _httpClientHandlerFactory = httpClientHandlerFactory; }
public async Task<IEnumerable<string>> GetSynonymsAsync(string term) { //List<string> synonyms = new List<string>(); //Uri uri = new Uri(string.Format(uriFormatString, Uri.EscapeDataString(term))); //ODataClientSettings odataSettings = new ODataClientSettings( // "https://api.datamarket.azure.com/Bing/Synonyms/v1/", // new NetworkCredential(apiKey, apiKey)); //var client = new ODataClient(odataSettings); //string command = string.Format("?Query=%27{0}%27", term); //var synonymsResponse = await client // .Unbound() // .Function("GetSynonyms") // .Set(new { Query = term}) // .ExecuteAsEnumerableAsync(); //foreach (var synonym in synonymsResponse) //{ // synonyms.Add((string)synonym); //} HttpBaseProtocolFilter handler = new HttpBaseProtocolFilter(); PasswordCredential credentials = new PasswordCredential("BingSynonymsAPIKey", apiKey, apiKey); handler.ServerCredential = credentials; handler.ProxyCredential = credentials; HttpClient client = new HttpClient(handler); client.DefaultRequestHeaders.Accept.TryParseAdd("application/json"); Uri uri = new Uri(string.Format(uriFormatString, Uri.EscapeDataString(term))); string responseJson = await client.GetStringAsync(uri); var response = Newtonsoft.Json.JsonConvert.DeserializeObject<BingSynonymsResponse>(responseJson); var synonyms = (from r in response.d.results select r.Synonym).ToList(); return (synonyms); }
public ICredentials GetCredentials() { PasswordCredential credentials = new PasswordCredential(); try { // If FindAllByResource returns no results an exception is thrown instead of return NULL so this must be in the try/catch credentials = this._passwordVault.FindAllByResource("WANDAppCredentials").FirstOrDefault(); credentials.RetrievePassword(); } catch (Exception e) { credentials = null; } if (credentials == null) return null; else return new NetworkCredential(credentials.UserName, credentials.Password); }
public static void Store(string userName, string password) { PasswordCredential pc = new PasswordCredential("redditAuth", userName, password); var vault = new PasswordVault(); try { IReadOnlyList<PasswordCredential> creds = vault.FindAllByResource("redditAuth"); if (creds == null) return; foreach (var cred in creds) { vault.Remove(cred); } } catch (Exception) { // The password vault is mildly retarded. } vault.Add(pc); }
private void SaveCredential() { var resource = InputResourceValue.Text; var userName = InputUserNameValue.Text; var password = InputPasswordValue.Password; if (resource == "" || userName == "" || password == "") { rootPage.NotifyUser("All fields are required when saving a credential.", NotifyType.ErrorMessage); } else { // Add a credential to PasswordVault with provided resource, user name, and password. // Replaces any existing credential with the same resource and user name. var vault = new PasswordVault(); var cred = new PasswordCredential(resource, userName, password); vault.Add(cred); rootPage.NotifyUser("Credential saved successfully. Resource: " + cred.Resource + " Username: "******" Password: " + cred.Password, NotifyType.StatusMessage); } }
// private const string bucketurl = "http://s3.amazonaws.com/"; // private const string bucketurl = "com.mf.carl-prototype.s3.amazonaws.com"; #region Upload public async Task UploadFile(IReadOnlyList<StorageFile> files) { try { basicAwsCredentials = new BasicAWSCredentials(accesskey, secretkey); List<BackgroundTransferContentPart> parts = new List<BackgroundTransferContentPart>(); for (int i = 0; i < files.Count; i++) { BackgroundTransferContentPart part = new BackgroundTransferContentPart(files[i].Name, files[i].Name); this.Filename = files[i].Name; part.SetFile(files[i]); parts.Add(part); } //Uri uri = new Uri(bucketurl + ExistingBucketName + "/"); //Uri uri = new Uri("https://com.mf.carl-prototype.s3-us-west-2.amazonaws.com/"); Uri uri = new Uri("https://s3.amazonaws.com/" + ExistingBucketName +"/"); // Uri uri = new Uri("https://"+ExistingBucketName+".s3-us-west-2.amazonaws.com/" ); BackgroundUploader uploader = new BackgroundUploader(); PasswordCredential pwdCredential = new PasswordCredential(); pwdCredential.UserName = accesskey; pwdCredential.Password = secretkey; uploader.ServerCredential = pwdCredential; // uploader.Method = "POST"; // uploader.SetRequestHeader("Content-Type", "multipart/form-data;boundary=34"); uploader.ServerCredential = new PasswordCredential{ UserName=accesskey, Password= secretkey}; UploadOperation upload = await uploader.CreateUploadAsync(uri, parts); // Attach progress and completion handlers. await HandleUploadAsync(upload, true); } catch(Exception ex) { } }
public async Task AuthenticateAsync(MobileServiceAuthenticationProvider provider) { var passwordVault = new PasswordVault(); PasswordCredential credential = null; var settings = ApplicationData.Current.RoamingSettings; try { await this.MobileService.LoginAsync(provider); credential = new PasswordCredential(provider.ToString(), this.MobileService.User.UserId, this.MobileService.User.MobileServiceAuthenticationToken); passwordVault.Add(credential); settings.Values[LastUsedProvider] = provider.ToString(); this.OnNavigate?.Invoke(Tasks, null); } catch (InvalidOperationException) { await this.OnShowErrorAsync?.Invoke("Authentication failed. Please try again."); } }
public void Add(PasswordCredential credential) { while (true) { var capture = _credentials; var existing = capture.FirstOrDefault(c => Comparer.Instance.Equals(c, credential)); ImmutableList <PasswordCredential> updated; if (existing == null) { updated = capture.Add(credential); } else { existing.RetrievePassword(); credential.RetrievePassword(); if (existing.Password == credential.Password) { // no change, abort update! return; } updated = capture.Replace(existing, credential); } lock (_updateGate) { if (capture == _credentials) { Persist(updated); _credentials = updated; return; } } } }
public async Task<IEnumerable<string>> GetSynonymsAsync(string term) { // Call synonyms OData service on Azure Marketplace at // "https://api.datamarket.azure.com/Bing/Synonyms/v1/", HttpBaseProtocolFilter handler = new HttpBaseProtocolFilter(); PasswordCredential credentials = new PasswordCredential("BingSynonymsAPIKey", apiKey, apiKey); handler.ServerCredential = credentials; handler.ProxyCredential = credentials; HttpClient client = new HttpClient(handler); client.DefaultRequestHeaders.Accept.TryParseAdd("application/json"); Uri uri = new Uri(string.Format(uriFormatString, Uri.EscapeDataString(term))); string responseJson = await client.GetStringAsync(uri); var response = JSONHelper.DeserializeObject<BingSynonymsResponse>(responseJson); var synonyms = (from r in response.d.results select r.Synonym).ToList(); return (synonyms); }
public void Remove(PasswordCredential credential) { while (true) { var capture = _credentials; var updated = capture.Remove(credential, Comparer.Instance); if (capture == updated) { return; } lock (_updateGate) { if (capture == _credentials) { Persist(updated); _credentials = updated; return; } } } }
public override async void LoginAsync() { string message; // This sample uses the Facebook provider. var provider = "AAD"; // Use the PasswordVault to securely store and access credentials. PasswordVault vault = new PasswordVault(); PasswordCredential credential = null; while (credential == null) { try { // Try to get an existing credential from the vault. credential = vault.FindAllByResource(provider).FirstOrDefault(); } catch (Exception) { // When there is no matching resource an error occurs, which we ignore. } if (credential != null) { // Create a user from the stored credentials. user = new MobileServiceUser(credential.UserName); credential.RetrievePassword(); user.MobileServiceAuthenticationToken = credential.Password; // Set the user from the stored credentials. App.MobileService.CurrentUser = user; try { // Try to return an item now to determine if the cached credential has expired. await App.MobileService.InvokeApiAsync("custom", HttpMethod.Get, new Dictionary<string,string>() ); } catch (MobileServiceInvalidOperationException ex) { if (ex.Response.StatusCode == System.Net.HttpStatusCode.Unauthorized) { // Remove the credential with the expired token. vault.Remove(credential); credential = null; continue; } } } else { try { // Login with the identity provider. user = await App.MobileService .LoginAsync(MobileServiceAuthenticationProvider.WindowsAzureActiveDirectory); // Create and store the user credentials. credential = new PasswordCredential(provider, user.UserId, user.MobileServiceAuthenticationToken); vault.Add(credential); } catch (MobileServiceInvalidOperationException ex) { message = "You must log in. Login Required"; } } message = string.Format("You are now logged in - {0}", user.UserId); var dialog = new MessageDialog(message); dialog.Commands.Add(new UICommand("OK")); await dialog.ShowAsync(); IsLoggedIn = true; } }
public async Task<TunesUser> SignInUser(string userName, string password) { TunesUser tunesUser = null; if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password)) { string strUrl = string.Format("{0}/token", this.ServiceUrl); var authClient = new OAuth2Client( new Uri(strUrl), "BSEtunes", OAuthClientSercret); try { this.TokenResponse = await authClient.RequestResourceOwnerPasswordAsync(userName, password); if (this.TokenResponse != null) { //if (this.TokenResponse..IsError) //{ // throw new UnauthorizedAccessException(this.m_strUnauthorizedAccessExceptionMessage); //} Windows.Storage.ApplicationData.Current.RoamingSettings.Values["username"] = userName; Windows.Security.Credentials.PasswordVault vault = new Windows.Security.Credentials.PasswordVault(); PasswordCredential passwordCredential = new PasswordCredential(PasswordVaultResourceName, userName, password); vault.Add(passwordCredential); if (passwordCredential != null) { tunesUser = this.User = new TunesUser { UserName = userName, Password = vault.Retrieve(PasswordVaultResourceName, passwordCredential.UserName).Password }; } } } catch (Exception) { throw new UnauthorizedAccessException(this.m_strUnauthorizedAccessExceptionMessage); } } else { throw new UnauthorizedAccessException(this.m_strUnauthorizedAccessExceptionMessage); } return tunesUser; }
private void NextButton_Clicked(object sender, RoutedEventArgs e) { var button = sender as Button; PasswordCredential credential; if (string.IsNullOrEmpty(CurrentPassword)) { credential = null; } else { credential = new PasswordCredential() { Password = CurrentPassword }; } var network = button.DataContext as WiFiAvailableNetwork; ConnectToWifi(network, credential, Window.Current.Dispatcher); }
private async void ConnectToWifi(WiFiAvailableNetwork network, PasswordCredential credential, CoreDispatcher dispatcher) { var didConnect = credential == null ? networkPresenter.ConnectToNetwork(network, Automatic) : networkPresenter.ConnectToNetworkWithPassword(network, Automatic, credential); await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { SwitchToItemState(network, WifiConnectingState, false); }); DataTemplate nextState = (await didConnect) ? WifiConnectedState : WifiInitialState; await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { var item = SwitchToItemState(network, nextState, false); item.IsSelected = false; }); }
private async Task <WifiConnectResult> ConnectWifi(string ssid, string password) { if (password == null) { password = ""; } var access = await WiFiAdapter.RequestAccessAsync(); if (access != WiFiAccessStatus.Allowed) { return(WifiConnectResult.WifiAccessDenied); } else { var allAdapters = await WiFiAdapter.FindAllAdaptersAsync(); if (allAdapters.Count >= 1) { var firstAdapter = allAdapters[0]; await firstAdapter.ScanAsync(); //0525 var network = firstAdapter.NetworkReport.AvailableNetworks.SingleOrDefault(n => n.Ssid == ssid);//0525 try { var network = firstAdapter.NetworkReport.AvailableNetworks.FirstOrDefault(n => n.Ssid == ssid); if (network != null) { WiFiConnectionResult wifiConnectionResult; if (network.SecuritySettings.NetworkAuthenticationType == Windows.Networking.Connectivity.NetworkAuthenticationType.Open80211) { wifiConnectionResult = await firstAdapter.ConnectAsync(network, WiFiReconnectionKind.Automatic); } else { // Only the password potion of the credential need to be supplied var credential = new Windows.Security.Credentials.PasswordCredential(); credential.Password = password; wifiConnectionResult = await firstAdapter.ConnectAsync(network, WiFiReconnectionKind.Automatic, credential); } //for get ip if (firstAdapter.NetworkAdapter.GetConnectedProfileAsync() != null) { var connectedProfile = await firstAdapter.NetworkAdapter.GetConnectedProfileAsync(); //WriteMessageText("\nconnectedProfile:" + connectedProfile.ProfileName + "\n"); if (connectedProfile != null && connectedProfile.ProfileName.Equals(savedProfileName)) { foreach (HostName localHostName in NetworkInformation.GetHostNames()) { if (localHostName.IPInformation != null) { if (localHostName.Type == HostNameType.Ipv4) { ipget = localHostName.ToString(); break; } } } // WriteMessageText("\nIP=localHostName.ToString:" + ipget); }// else { // WriteMessageText("\n !!!!< >" + Not connected to :"+connectedProfile.ProfileName+"\n"); } } if (wifiConnectionResult.ConnectionStatus == WiFiConnectionStatus.Success) { return(WifiConnectResult.Success); } else { if (wifiConnectionResult.ConnectionStatus == WiFiConnectionStatus.UnspecifiedFailure) { //return WifiConnectResult.UnspecifiedFailure; WriteMessageText("\nUnspecified Failure"); } else if (wifiConnectionResult.ConnectionStatus == WiFiConnectionStatus.AccessRevoked) { // return WifiConnectResult.AccessRevoked; WriteMessageText("\nAccess Revoked"); } else if (wifiConnectionResult.ConnectionStatus == WiFiConnectionStatus.InvalidCredential) { // return WifiConnectResult.InvalidCredential; WriteMessageText("\nInvalid Credential"); } else if (wifiConnectionResult.ConnectionStatus == WiFiConnectionStatus.NetworkNotAvailable) { // return WifiConnectResult.NetworkNotAvailable; WriteMessageText("\nNetwork NotAvailable"); } else if (wifiConnectionResult.ConnectionStatus == WiFiConnectionStatus.Timeout) { //return WifiConnectResult.Timeout; WriteMessageText("\nTimeout"); } else if (wifiConnectionResult.ConnectionStatus == WiFiConnectionStatus.UnsupportedAuthenticationProtocol) { //return WifiConnectResult.UnsupportedAuthenticationProtocol; */ WriteMessageText("\nUnsupported Authentication Protocol"); } return(WifiConnectResult.CouldNotConnect); } } else { return(WifiConnectResult.SsidNotFound); } //try 0706 } catch (Exception ex) { return(WifiConnectResult.SsidNotFound); } } else { return(WifiConnectResult.NoWifiDevice); } } }
/// <inheritdoc/> public void Store(string resource, Toolkit.Services.Core.PasswordCredential credentials) { var passwordCredential = new Windows.Security.Credentials.PasswordCredential(resource, credentials.UserName, credentials.Password); _vault.Add(passwordCredential); }