«Лучший» способ сохранить его зависит от того, что вы хотите с ним делать:
кучу дополнительных свойств, которые вы можете сохранить / восстановить, если вы сделаете это вручную (высота, горизонтальная точность, вертикальная точность, метка времени). Есть еще кое-что, что вы не можете (скорость, заголовок); CLLocation не предоставляет подходящий init-метод, и свойства доступны только для чтения.
Все дополнительные свойства полезны, если вы записываете дорожку. Высота важна, если вы записываете POI на горной местности («нам еще нужно подняться на 100 м»). горизонтальная / вертикальная точность может использоваться для представления того, насколько велика POI (например, город может иметь «горизонтальную точность» в несколько километров и отображаться как большой круг).
Это функция, которую я использую для привязки к каталогу LDAP с использованием системных учетных данных, поиска предоставленного идентификатора пользователя и затем проверки предоставленных учетных данных пользователя. Для использования функции с Active Directory 'strUIDAttr' - это sAMAccountName.
protected string ldapAuthTest(string strLDAPServer, string strSuppliedUser, string strSuppliedPwd, string strSystemUID, string strSystemPwd, string strLDAPUserBase, string strUIDAttr)
{
strSuppliedUser = strSuppliedUser.Trim();
string strResults = "";
string strLDAPUserHost = strLDAPServer + strLDAPUserBase;
// Establish LDAP connection and bind with system ID
System.DirectoryServices.DirectoryEntry dirEntry = new System.DirectoryServices.DirectoryEntry();
dirEntry.Path = strLDAPUserHost;
dirEntry.Username = strSystemUID;
dirEntry.Password = strSystemPwd;
//dirEntry.AuthenticationType = System.DirectoryServices.AuthenticationTypes.None;
dirEntry.AuthenticationType = System.DirectoryServices.AuthenticationTypes.SecureSocketsLayer;
try
{
dirEntry.RefreshCache();
// Search directory for the user logging on
string strLDAPFilter = "(&(" + strUIDAttr + "=" + strSuppliedUser + "))";
System.DirectoryServices.DirectorySearcher ldapSearch = new System.DirectoryServices.DirectorySearcher(dirEntry);
ldapSearch.ServerTimeLimit = new TimeSpan(0, 0, 30);
ldapSearch.Filter = strLDAPFilter;
ldapSearch.SearchScope = System.DirectoryServices.SearchScope.Subtree;
System.DirectoryServices.SearchResultCollection searchResults = ldapSearch.FindAll();
if (searchResults.Count == 1)
{
string strLogonUserBase = searchResults[0].GetDirectoryEntry().Path;
// get rid of strLDAPServer from directory entry path
string strLogonUserFQDN = strLogonUserBase.Replace(strLDAPServer, "");
dirEntry.Close();
// Attempt to bind as the user
System.DirectoryServices.DirectoryEntry userAuthAttempt = new System.DirectoryServices.DirectoryEntry();
userAuthAttempt.Path = strLDAPUserHost;
userAuthAttempt.Username = strLogonUserFQDN;
userAuthAttempt.Password = strSuppliedPwd;
//userAuthAttempt.AuthenticationType = System.DirectoryServices.AuthenticationTypes.None;
userAuthAttempt.AuthenticationType = System.DirectoryServices.AuthenticationTypes.SecureSocketsLayer;
try
{
userAuthAttempt.RefreshCache();
userAuthAttempt.Close();
strResults = "<td><font color='green'>User " + UserName.Value + " has authenticated successfully.</font></td>";
}
catch (Exception e)
{
string strAuthError = e.Message;
string strLockedOut = "A constraint violation occurred.\r\n";
string strBadPwd = "Logon failure: unknown user name or bad password.\r\n";
string strNSAccountLock = "The server is unwilling to process the request.\r\n";
if (String.Compare(strAuthError, strBadPwd) == 0)
strResults = "<td><font color='red'>Logon failure for user " + UserName.Value + " - password is invalid.</font></td></tr>"; ;
}
else if (String.Compare(strAuthError, strLockedOut) == 0)
{
strResults = "<td><font color='red'>Logon failure for user " + UserName.Value + " - account is locked out.</font></td>"; ;
}
else if (String.Compare(strAuthError, strNSAccountLock) == 0)
{
strResults = "<td><font color='red'>Logon failure for user " + UserName.Value + " - password has expired.</font></td>"; ;
}
else
{
strResults = "<td><font color='red'>Logon failure for user " + UserName.Value + " (" + strLogonUserFQDN + ") :" + strAuthError + "</font></td>"; ;
}
}
}
else if (searchResults.Count > 1)
{
strResults = "<td><font color='red'>Account " + UserName.Value + " was found in the directory " + searchResults.Count + " times. Please contact the Help Desk to have this issue corrected.</font></td>"; ;
}
else
{
strResults = "<td><font color='red'>Account " + UserName.Value + " was not found in the directory.</font></td>"; ;
}
return strResults;
}
catch(Exception e)
{
string strAuthError = e.Message;
string strConnectFail = "The server is not operational.\r\n";
if (String.Compare(strAuthError, strConnectFail) == 0)
{
strResults = "<td><font color='red'>Transient connection failure, please try again.</font></td>"; ;
}
else
{
strResults = "<td><font color='red'>Transient failure (" + strAuthError + "), please try again.</font></td>";
}
return strResults;
}
}