SkyDrive API access code sometime works sometime does not works - windows-8

I am trying to access skydrive content from my code. the following code worked before but suddently it stopped executing the second result. Not sure what microsoft has done in behind! Please help. Please not that the scopes are valid and my app for win8 has got the access.
var authClient = new LiveAuthClient();
var scopes = new[] { "wl.signin", "wl.skydrive", "wl.basic" };
Task<LiveLoginResult> resultTask = authClient.LoginAsync(scopes);
var client = new LiveConnectClient(resultTask.Result.Session);
dynamic result1 = client.GetAsync("me/skydrive");
dynamic result2 = result1.Result;
result1 = client.GetAsync("me/skydrive");
result2 = result1.Result;
Thanks
Kajal

Your code is lacking async/await.
If your code is within an event body then use async void as return type otherwise async Task<T> where T class name of return type data.
var authClient = new LiveAuthClient();
var scopes = new[] { "wl.signin", "wl.skydrive", "wl.basic" };
Task resultTask = await authClient.LoginAsync(scopes);
var client = new LiveConnectClient(resultTask.Result.Session);
dynamic result1 = await client.GetAsync("me/skydrive");
dynamic result2 = result1.Result;
result1 = await client.GetAsync("me/skydrive");
result2 = result1.Result;

Related

Stripe.StripeException: 'The Issuing API is currently in private beta. Please visit https://stripe.com/issuing for more information.'

Error is coming while returning list of payment history in stripe, below is the code and image is attached:
public TransactionService StripeGetListTransaction()
{
ResponseModel response = new ResponseModel();
StripeConfiguration.ApiKey = _paymentSettings.Value.SecretKey;
var options = new TransactionListOptions
{
Limit = 3,
};
var service = new TransactionService();
service.List(options);
return service;
}
enter image description here
I think you are using the wrong service class.
For listing balance transactions, you should use BalanceTransactionService instead
var options = new BalanceTransactionListOptions
{
Limit = 3,
};
var service = new BalanceTransactionService();
service.List(options);
See the doc for more information

Email confirmation - strange behavior

Does anyone have an idea why this is happening to me?
In this case, 'result' is 'Success':
public async Task<IActionResult> TestConfirmInSameRequest(string userId)
{
var user = await this._userManager.FindByIdAsync(userId);
var code = await this._userManager.GenerateEmailConfirmationTokenAsync(user);
var result = await this._userManager.ConfirmEmailAsync(user, code);
var newLocation = ...
return Redirect(newLocation);
}
And in this case, 'result' always is 'InvalidToken' (even when I manually copy the original code and test with it)
public async Task<IActionResult> ConfirmEmail(string userId, string code)
{
var user = await this._userManager.FindByIdAsync(userId);
var result = await this._userManager.ConfirmEmailAsync(user, code);
var newLocation = ...;
return Redirect(newLocation);
}
protected async Task SendConfirmationEmail(string userId, bool originMobile)
{
var user = await this._userManager.FindByIdAsync(userId);
var code = await this._userManager.GenerateEmailConfirmationTokenAsync(user);
var encodedCode = HttpUtility.UrlEncode(code);
var callbackUrl = $"https://.../api/account/confirmemail?userId={userId}&code={encodedCode}";
await this._userService.SendConfirmationEmailAsync(userId, callbackUrl);
}
When sending (SendConfirmationEmail) the e-mail you urlencode the token, but in ConfirmEmail you are not decoding the token.
Encoding it just makes sure it can be used in a URL and no breaking characters are in the URL. However, the token you should validate is not the encoded one, its still the token you got before encoding. In other words; you need to decode the token again so its back to the way it was when it got generated.

Asp.Net Core - Making API calls from backend

I have an application which is calling API's from a backend cs class, using IHostedService. With basic API calls ("http://httpbin.org/ip") it is working fine and returning the correct value, however I now need to call a Siemens API which requires me to set an Authorization header, and place "grant_type=client_credentials" in the body.
public async Task<string> GetResult()
{
string data = "";
string baseUrl = "https://<space-name>.mindsphere.io/oauth/token";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", {ServiceCredentialID: ServiceCredentialSecret});
using (HttpResponseMessage res = await client.GetAsync(baseUrl))
{
using (HttpContent content = res.Content)
{
data = await content.ReadAsStringAsync();
}
}
}
I think I have the header set up correctly but I won't know for sure until the full request gets formatted. Is it even possible to set the the body of the request to "grant_type=client_credentials"?
As far as I can see from Siemens API documentation they expect Form data, so it should be like:
public async Task<string> GetResult()
{
string data = "";
string baseUrl = "https://<space-name>.mindsphere.io/oauth/token";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", {ServiceCredentialID: ServiceCredentialSecret});
var formContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("grant_type", "client_credentials")
});
using (HttpResponseMessage res = await client.PostAsync(baseUrl, formContent))
{
using (HttpContent content = res.Content)
{
data = await content.ReadAsStringAsync();
}
}
}
}

How to implement the await keyword?

I have written a code to get the projects from the TFS 2013 server using the tfs web api. As the methord is taking too long to execute i.e like 1.5 minutes, so i wanted to make this methord as async. So i added the async and task in the return type. When i see in visual studio is shows a message that the methord does not have await keyword. where should i add the await keyword. I am very new to async programming.
public override async Task<List<Project>> GetProjects()
{
List<Project> retunResult = new List<Project>();
using (var http = new HttpClient(GetHttpHandler()))
{
var response = http.GetAsync(_baseUrl + "_apis/projectCollections?" + tfsWebApiVersionSring).Result;
if (response.IsSuccessStatusCode)
{
response.EnsureSuccessStatusCode();
TFS2013TeamProjectCollection.Rootobject obj = JsonConvert.DeserializeObject<TFS2013TeamProjectCollection.Rootobject>(response.Content.ReadAsStringAsync().Result);
if (obj != null)
{
foreach (TFS2013TeamProjectCollection.Value projColl in obj.value)
{
if (projColl.state == "Started")
{
var responseProj = http.GetAsync(_baseUrl + projColl.name + "/_apis/projects?" + tfsWebApiVersionSring).Result;
if (responseProj.IsSuccessStatusCode)
{
responseProj.EnsureSuccessStatusCode();
TFS2013TeamProject.Rootobject obj1 = JsonConvert.DeserializeObject<TFS2013TeamProject.Rootobject>(responseProj.Content.ReadAsStringAsync().Result);
if (obj1 != null)
{
Project p;
foreach (TFS2013TeamProject.Value TeamProj in obj1.value)
{
p = new Project();
p.collectionName = TeamProj.collection.name;
p.description = TeamProj.description;
p.id = TeamProj.id;
p.name = TeamProj.name;
p.collectionName = TeamProj.collection.name;
p.url = TeamProj.url;
retunResult.Add(p);
}
}
}
}
}
return retunResult;
}
}
}
return null;
}
You could refer to this code snippet about using TFS REST API to get something in async way.
public static async void RESTAPIMethod()
{
HttpClientHandler authtHandler = new HttpClientHandler()
{
Credentials = CredentialCache.DefaultNetworkCredentials
};
using (HttpClient client = new HttpClient(authtHandler))
{
client.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
using (HttpResponseMessage response = client.GetAsync(
"Put the REST API URL here").Result)
{
response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync();
}
}
}
Another method about using TFS REST API:
You could also install this Nuget package for your project. Then using these assemblies in this package to run a REST API with C#. This is different with the method above, it's much more convenient. Here is an example about get a build information using Microsoft.TeamFoundation.Build.WebApi assembly in Async method.
Example:
What object returns from TFS2015 RestAPI
You shouldn't use Result at all. Every place in your code where you have:
var resp = http.GetAsync(url).Result;
you should have:
var resp = await http.GetAsync(url);

Multiple HTTP Requests in WinRT / Win8

Is it possible to send more than two HTTP requests concurrently in WinRT? I'm trying to load multiple JSON documents from a server and HttpWebRequest fails to respond after the second call. Here is a sample snippet that illustrates this:
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
const string url = "http://www.bom.gov.au/fwo/IDV60901/IDV60901.94868.json";
const int iterations = 3;
var tasks = new List<Task>();
var ticks = DateTime.Now.Ticks;
for (var i = 0; i < iterations; i++)
{
// Create unique URL by appending a generated number.
var uniqueUrl = string.Format("{0}?v={1}", url, (i + ticks));
// Create the request.
var request = WebRequest.CreateHttp(uniqueUrl);
// Create the async task and store it for later.
var task = request.GetResponseAsync();
tasks.Add(task);
}
// Await all tasks in collection.
await Task.WhenAll(tasks);
Debugger.Break(); // <----- This will never break when iterations > 2
}
Put this code in a blank MainPage.xaml.cs and play around with the iterations value. If you set it to 2, then it works. Anything above that, it will fail.
NOTE :: Do not use Fiddler when testing this. Fiddler does something funny and it allows all these connections to go through. I don't know how nor why. You can test this yourself. If you run the code above with fiddler open, then success.
NOTE :: This is not real code. I'm only using this example to illustrate the issue.
I haven't tried using the WebClient API in WinRT, I've only used the HttpClient API (which I'm using quite extensively in my application).
This code works:
const string url = "http://www.bom.gov.au/fwo/IDV60901/IDV60901.94868.json";
const int iterations = 10;
var tasks = new List<Task<HttpResponseMessage>>();
var ticks = DateTime.Now.Ticks;
for (var i = 0; i < iterations; i++)
{
// Create unique URL by appending a generated number.
var uniqueUrl = string.Format("{0}?v={1}", url, (i + ticks));
var handler = new HttpClientHandler();
var client = new HttpClient(handler)
{
BaseAddress = new Uri(uniqueUrl)
};
var task = client.GetAsync(client.BaseAddress);
tasks.Add(task);
}
// Await all tasks in collection.
await Task.WhenAll(tasks);
It is a bit more tedious to get out the response body though as you need to do an async read of all the responses like so:
var responseTasks = tasks.Select(task => task.Result.Content.ReadAsStringAsync());
await Task.WhenAll(responseTasks);
Then you can iterate through the responseTask objects and take their result.