OpenTween.Api.MicrosoftTranslatorApi.ParseOAuthCredential C# (CSharp) Method

ParseOAuthCredential() static private method

static private ParseOAuthCredential ( byte responseBytes ) : TimeSpan>.Tuple
responseBytes byte
return TimeSpan>.Tuple
        internal static Tuple<string, TimeSpan> ParseOAuthCredential(byte[] responseBytes)
        {
            using (var jsonReader = JsonReaderWriterFactory.CreateJsonReader(responseBytes, XmlDictionaryReaderQuotas.Max))
            {
                var xElm = XElement.Load(jsonReader);

                var tokenTypeElm = xElm.Element("token_type");
                if (tokenTypeElm == null)
                    throw new WebApiException("Property `token_type` required");

                var accessTokenElm = xElm.Element("access_token");
                if (accessTokenElm == null)
                    throw new WebApiException("Property `access_token` required");

                var expiresInElm = xElm.Element("expires_in");

                int expiresInSeconds;
                if (expiresInElm != null)
                {
                    if (!int.TryParse(expiresInElm.Value, out expiresInSeconds))
                        throw new WebApiException("Invalid number: expires_in = " + expiresInElm.Value);
                }
                else
                {
                    // expires_in が省略された場合は有効期間が不明なので、
                    // 次回のリクエスト時は経過時間に関わらずアクセストークンの再発行を行う
                    expiresInSeconds = 0;
                }

                return Tuple.Create(accessTokenElm.Value, TimeSpan.FromSeconds(expiresInSeconds));
            }
        }
    }

Usage Example

        public void ParseOAuthCredential_OmittedExpiresInTest()
        {
            var jsonBytes = Encoding.UTF8.GetBytes(@"
{
  ""access_token"": ""12345acbde"",
  ""token_type"": ""bearer""
}
");
            var expected  = (@"12345acbde", TimeSpan.Zero);

            Assert.Equal(expected, MicrosoftTranslatorApi.ParseOAuthCredential(jsonBytes));
        }
All Usage Examples Of OpenTween.Api.MicrosoftTranslatorApi::ParseOAuthCredential