Skip to content

Instantly share code, notes, and snippets.

@kenny-evitt
Last active February 3, 2017 16:30
Show Gist options
  • Save kenny-evitt/8221cf4723c21cd00e127741979e6ac7 to your computer and use it in GitHub Desktop.
Save kenny-evitt/8221cf4723c21cd00e127741979e6ac7 to your computer and use it in GitHub Desktop.
C# example of reading a (single) result-set of data returned by executing a (T-)SQL command
public AccessTokenInfo GetWebApiAccessToken(string webApiUserName)
{
object tokenObject = null;
object expirationObject = null;
string tokenString;
DateTime? expirationDateTime;
using (SqlConnection dbConnection = new SqlConnection(_connectionString))
using (SqlCommand dbCommand = new SqlCommand("dynamics.GetWebApiAccessToken"))
{
dbCommand.Connection = dbConnection;
dbCommand.CommandType = CommandType.StoredProcedure;
dbCommand.Parameters.AddWithValue("@WebApiUserName", webApiUserName);
dbConnection.Open();
using (SqlDataReader reader = dbCommand.ExecuteReader())
{
// Read only the first row (if it exists)
if (reader.Read())
{
tokenObject = reader["DecryptedToken"];
expirationObject = reader["ExpiresOnUtc"];
}
}
dbConnection.Close();
}
tokenString = (tokenObject == DBNull.Value) ? (string)null : (string)tokenObject;
expirationDateTime = (expirationObject == DBNull.Value) ? (DateTime?)null : (DateTime?)expirationObject;
return new AccessTokenInfo(tokenString, expirationDateTime);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment