Last active
January 2, 2016 06:55
-
-
Save Elrashid/8b3a78cd21f56ec4edfe to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using Windows.Security.Credentials; | |
namespace utilities | |
{ | |
class PasswordVault_Utility | |
{ | |
const int ElementNotFound = unchecked((int)0x80070490); | |
//private resource = "www.example.com"; | |
//private userName = "userName"; | |
//private password = "password"; | |
//private vault = new PasswordVault(); | |
static public void SaveCredential(string resource, | |
string userName, | |
string password) | |
{ | |
var vault = new PasswordVault(); | |
var cred = new PasswordCredential(resource, userName, password); | |
//Add credential or Replaces any existing credential with the same | |
//resource and user name. | |
vault.Add(cred); | |
} | |
static public IReadOnlyList<PasswordCredential> | |
RetrieveCredentials(string resource, | |
string userName) | |
{ | |
var vault = new PasswordVault(); | |
IReadOnlyList<PasswordCredential> creds = null; | |
try | |
{ | |
if (resource == "" && userName == "") | |
{ | |
// Both resource and user name are empty: | |
//Use retrieveAll(). | |
creds = vault.RetrieveAll(); | |
} | |
else if (userName == "") | |
{ | |
// Resource is provided but no user name: | |
//Use findAllByResource(). | |
creds = vault.FindAllByResource(resource); | |
} | |
else if (resource == "") | |
{ | |
// User name is provided but no resource: | |
//Use findByUserName(). | |
creds = vault.FindAllByUserName(userName); | |
} | |
else | |
{ | |
// Both resource and user name are provided: | |
// Use retrieve(). | |
PasswordCredential cred = vault.Retrieve(resource, userName); | |
// Add it to our results if the retrieval was successful. | |
if (cred != null) | |
{ | |
creds = new List<PasswordCredential>() { cred }; | |
} | |
} | |
} | |
catch (Exception e) | |
{ | |
// The credential retrieval functions raise an | |
//"Element not found" exception if there were no matches. | |
if (e.HResult != ElementNotFound) throw; else creds = | |
new List<PasswordCredential>(); | |
} | |
return creds; | |
} | |
static public bool RemoveCredentials(PasswordCredential cred) | |
{ | |
var vault = new PasswordVault(); | |
bool doen = false; | |
try | |
{ | |
vault.Remove(cred); | |
doen = true; | |
} | |
catch (Exception e) | |
{ | |
// Ignore exception if the credential was already removed. | |
if (e.HResult != ElementNotFound) | |
{ | |
throw; | |
} | |
} | |
return doen; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment