public
static
class
SfdcTokenManager
{
private
DateTime _sessionLastAccessDate = DateTime.Now;
string
_sessionId =
.Empty;
GetSession(
oauthkey,
oauthsecret,
uname,
password,
token)
//get current date time
DateTime now = DateTime.Now;
//get the difference from the last time the token was accessed
TimeSpan diff = now.Subtract(_sessionLastAccessDate);
//if this is the first time we're calling class, or the token is stale, get a new token
if
(_sessionId ==
.Empty || (diff.TotalMinutes >= 60))
//refresh token
try
HttpClient authClient =
new
HttpClient();
//create login password value
loginPassword = password + token;
//create payload consisting of required values
HttpContent content =
FormUrlEncodedContent(
Dictionary<
,
>
"grant_type"
"password"
},
"client_id"
,oauthkey},
"client_secret"
,oauthsecret},
"username"
,uname},
,loginPassword}
}
);
//issue request to the Force.com login endpoint
//var response = authClient.PostAsync("https://login.salesforce.com/services/oauth2/token", content);
var response = authClient.PostAsync(
"https://test.salesforce.com/services/oauth2/token"
, content);
(response.Result.IsSuccessStatusCode)
//get the result
var responseContent = response.Result.Content;
responseString = responseContent.ReadAsStringAsync().Result;
//load result into JSON object
JObject obj = JObject.Parse(responseString);
//extract the access token
_sessionId = (
)obj[
"access_token"
];
System.Diagnostics.EventLog.WriteEntry(
"Application"
"New SFDC token acquired"
catch
(Exception ex)
"Error getting token: "
+ ex.ToString());
else
"Existing SFDC token returned"
//update last access time since session is good for an hour since last call
_sessionLastAccessDate = DateTime.Now;
//give the session ID to the caller
return
_sessionId;
_uname =
.Empty || (diff.TotalMinutes >= 60) || uname != _uname)
_uname = uname;
↑ Return to Top