How to get microsoft account profile photo after login with application in mvc - asp.net-mvc-4

With the help of claimprincipal, I'm able to get the details of signedin user as below but its not giving any pic related information as google does:
https://apis.live.net/v5.0/{USER_ID}/picture?type=large
which says The URL contains the path '{user_id}', which isn't supported.
Even tried
https://graph.microsoft.com/v1.0/me/photo/$value
which is asking for access token, but I am not sure what have to be passed
string userName = ClaimsPrincipal.Current.FindFirst("name").Value;
string userEmail = ClaimsPrincipal.Current.FindFirst(ClaimTypes.Email).Value;
string userId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
Wanted an image which was added in any outlook account

For Image to show.. We have to use beared token and have to convert the image into memory stream and then have to used it.. I have done it in below ways. Hope this help ...
var client = new RestClient("https://login.microsoftonline.com/common/oauth2/token");
var request = new RestRequest(Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddParameter("application/x-www-form-urlencoded", $"code={code}&client_id={OutClientId}&client_secret={SecretKey}&redirect_uri={OutRedirectUrl}&grant_type=authorization_code", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Token jsonContent = JsonConvert.DeserializeObject<Token>(response.Content);
var Token = jsonContent.AccessToken;
var TokenType = jsonContent.TokenType;
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Token);
HttpResponseMessage response1 = await httpClient.GetAsync("https://graph.microsoft.com/v1.0/me/photos/96x96/$value");
if (response1.StatusCode == HttpStatusCode.OK)
{
using (Stream responseStream = await response1.Content.ReadAsStreamAsync())
{
MemoryStream ms = new MemoryStream();
responseStream.CopyTo(ms);
byte[] buffer = ms.ToArray();
string result = Convert.ToBase64String(buffer);
HttpContext.Session[AppConstants.UserImage] = String.Format("data:image/gif;base64,{0}", result);
responseStream.Close();
}
}

Is there any reason you are using the live.net apis? Instead of the Microsoft Graph APIs? Microsoft Graph APIs are the future for all user data within Microsoft 365 consumer and commercial accounts.
You can get the Users photo very easily as described here https://learn.microsoft.com/en-us/graph/api/profilephoto-get?view=graph-rest-1.0
GET /me/photo/$value
As you are using ASP.NET MVC, there is an SDK you can use that makes this very easy too.
https://learn.microsoft.com/en-us/graph/sdks/sdks-overview?context=graph%2Fapi%2F1.0&view=graph-rest-1.0

Related

Trying to upload media to the Whatsapp Cloud API using VB but returning error

Here is my json data which am trying to send :
{""file"":""C:\\Users\\DE\\Desktop\\logo.png"",""type"":""image/png"",""messaging_product"":""whatsapp""}
And response is:
{""error"":{""message"":""An unknown error has occurred."",""type"":""OAuthException"",""code"":1,""fbtrace_id"":""AujK_b8gN__AK4aKnrCcTCF""}}
Code is:
Dim clientHandler = New HttpClientHandler()
client = New HttpClient(clientHandler)
url = "https://graph.facebook.com/v15.0/user_code/media"
client.DefaultRequestHeaders.Authorization = New AuthenticationHeaderValue("Bearer",token)
client.Timeout = TimeSpan.FromSeconds(300)
vxml = New StringContent(jsonString, Encoding.UTF8, "application/json")
response = Await client.PostAsync(url, vxml)
content = response.Content
Am trying to upload image to whatsApp API i am expecting an image ID response from the API

'Restclient' does not contain a 'BaseUrl' Error

I am working on Asp.net core project. trying to send mail using mailgun. used mailgun C# code given in https://documentation.mailgun.com/en/latest/user_manual.html#sending-via-api
But getting an error "RestClient" does not contain a "BaseUrl" error.
I saw your Comment Code, I think You have to Change this to get the Output.
var client = new RestClient();
client.BaseUrl = "https://api.mailgun.net/v3";
client.Authenticator = new HttpBasicAuthenticator("api", "YOUR_API_KEY");
var request = new RestRequest();
request.Resource = "/address/validate";
request.AddParameter("address", "address#domain.com");
//Change Resource and AddParameter as per need
var response = client.Execute(request);
dynamic content = Json.Decode(response.Content);
var client = new RestClient(new Uri("yourbaseurl"));

Get image by client request in Blazor

I try to get a Base64 from a image-URL in my hosted Blazor Webassambly. The URL contains a link to a picture.
using (var client = new HttpClient())
{
var bytes = await client.GetByteArrayAsync(url); // there are other methods if you want to get involved with stream processing etc
var base64String = Convert.ToBase64String(bytes);
return base64String;
}
Throws Exception:
TypeError: Failed to fetch
The Exception is thrown with any client method.
var result = await client.[X](url);
Why its impossible to make a request with he http client?
I would try it with first retrieving the link to the picture and then downloading the bytes from there.
string pictureLink = await client.GetStringAsync(url);
var base64String = Convert.ToBase64String(await client.GetByteArrayAsync(pictureLink));

I'm getting error 401 (unauthorized) while trying to make a GET request from my API that has a JWT token

Here is my GETRequest method...
HttpClient client = new HttpClient();
var dashboardEndpoint = Helper.GetUsersurl;
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Add("Authorization", "Bearer"+Helper.userprofile.token);
var result = await client.GetStringAsync(dashboardEndpoint);
var UsersList = JsonConvert.DeserializeObject<AddedUsers>(result);
//Users = new ObservableCollection<AddedUsers>(UsersList);
Emplist.ItemsSource = UsersList.data;
}
I've tried different method but the token isn't being sent alongside my request and therefore the API is throwing an error 401 at me. Any help will be gladly appreciated please...
So, i later studied the pattern and also the response on postman then i realize I'm supposed to pass only the key and the value. In this context,
HttpClient client = new HttpClient();
var dashboardEndpoint = Helper.GetUsersurl;
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Add("Authorization", Helper.userprofile.token);
var result = await client.GetStringAsync(dashboardEndpoint);
var UsersList = JsonConvert.DeserializeObject<AddedUsers>(result);
//Users = new ObservableCollection<AddedUsers>(UsersList);
Emplist.ItemsSource = UsersList.data;
I only needed to pass Authorization as the key and token as the value. thanks everyone
As #jason said, try to add a space between Bearer and the Token
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + Helper.userprofile.token);

Windows Phone Silverlight request does not update

I'm quite new to the Windows Phone dev and I have to do an application to communicate with a Restful API. Everything works fine to get the informations back from the API but my problem occurs when I try to update the content. For example, I have a profile and I try to update the user's information (change the city let's say). On the server side I can see that my update worked properly but when I go back to my profile in my WP app nothing has changed, the city is still the same as the old one. This is my code :
public MainPage()
{
InitializeComponent();
this.ApplicationBar = this.Resources["HomeBar"] as ApplicationBar;
Requester requester = new Requester();
requester.initGetRequest("/me/", GetResponseCallback, true);
}
private void GetResponseCallback(IAsyncResult asynchronousResult)
{
try
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string read = streamRead.ReadToEnd();
GlobalData.GetInstance().user = JsonConvert.DeserializeObject<MeClass>(read);
Dispatcher.BeginInvoke(() =>
{
MessageBox.Show(read);
});
//Create the profile and stuff
streamResponse.Close();
streamRead.Close();
response.Close();
}
catch (WebException webException)
{
HttpStatusCode status = ((HttpWebResponse)webException.Response).StatusCode;
Dispatcher.BeginInvoke(() =>
{
MessageBox.Show(status.ToString());
});
}
}
I figured out that the string 'read' is always equal to the old one, even after the update so this is why the content is not updated but how can the response be exactly the same as before, even if the update worked fine on the server side (if I check in Postman after my update, I can see that my city is the new one). If I restart my app I can see the update.
I can also show you my initGetRequest() :
public void initGetRequest(String endPoint, Action<IAsyncResult> callback, Boolean header)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url + endPoint);
if (header == true)
request.Headers["Authorization"] = GlobalData.GetInstance().Header;
request.BeginGetResponse(new AsyncCallback(callback), request);
}
Thank you for your help !
I finally found why my request was still the same even after the update. The HttpWebRequest uses a cache by default. I only added a small bit of code before calling my request :
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url + endPoint);
if (header == true)
request.Headers["Authorization"] = GlobalData.GetInstance().Header;
request.Headers[HttpRequestHeader.IfModifiedSince] = DateTime.UtcNow.ToString();
request.BeginGetResponse(new AsyncCallback(callback), request);
I had no idea about that cache so I hope this answer will help someone having the same issue !