Get user profile pic from O365 - microsoft graph api - angularjs

I have tried to get user profile pic from O365 using Microsoft Graph API. When I used following API it returns only the metadata related to the profile pic.
https://graph.microsoft.com/beta/me/photo
Through https://graph.microsoft.com/beta/me/photo/$value returns a gibberish object which doesn't make any sense. However, I believe that it is the data related to the user profile. Need help to extract those data into base64.

The returned data is the binary data of the image type. If you use JavaScript to retrieve the user photo, please get the photo data as blob type in a XMLHttpRequest, and then retrieve the blob URL from the response. For your reference:
var request = new XMLHttpRequest;
var photoUri=config.endpoints.graphApiUri + "/v1.0/me/photo/$value";
request.open("GET",photoUri);
request.setRequestHeader("Authorization","Bearer "+token);
request.responseType = "blob";
request.onload = function (){
if(request.readyState == 4 && request.status == 200){
var image = document.createElement("img");
var url = window.URL || window.webkitURL;
var blobUrl = url.createObjectURL(request.response);
image.src = blobUrl;
document.getElementById("UserShow").appendChild(image);
}
};
request.send(null);

For making that photo viewable in view we have to convert the response in 64 byte.
I have make this done in by project by below code. Hope this answer useful for someone..
HttpResponseMessage response1 = await httpClient.GetAsync("https://graph.microsoft.com/v1.0/me/photos/96x96/$value");
using (Stream responseStream = await response1.Content.ReadAsStreamAsync())
{
using (FileStream fs = new FileStream(#"D:\image.jpg", FileMode.Create))
{
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();
}
}

Related

Flutter Monitor FileUpload progress using the http package

I have been using the following code to upload files on my server as it is doing the job but i want to monitor the Upload Progress Percentage during the opration and Update the UI accordingly to reflect the prgress to the user
uploadFile({File imageFile, String refCode}) async {
// open a bytestream
var stream =
new http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
// get file length
var length = await imageFile.length();
// string to uri
var uri = Uri.parse(
'http://-------------/api/FilesUploadB/?refCode=$refCode');
// create multipart request
var request = new http.MultipartRequest("POST", uri);
// multipart that takes file
var multipartFile = new http.MultipartFile('file', stream, length,
filename: basename(imageFile.path));
// add file to multipart
request.files.add(multipartFile);
// send
var response = await request.send();
// listen for response
response.stream.transform(utf8.decoder).listen((value) {
print(value);
});
//return response.
}
NOTE that the value in the listen is getting me the final return from the WebAPI on the server.
how to achieve that?
Take a look at this example on GitHub. It demonstrates how you can access the current upload progress of your file.

401 When passing the token using graphic onenote api

I am new to Microsoft graph so this might be a dumb question.
So I am writing a command line application trying to update a page in our team onenote. (enterprise onenote)
Here is the code I got work getting the token.
https://login.microsoftonline.com/common/oauth2/authorize?client_id=my_client_Id&response_type=code&redirect_uri=Some_uri&resource=https://graph.microsoft.com&scope=Notes.ReadWrite.All
I got the token as strCode and trying to retrieve all the notes under this account by these codes:
var baseAddress = new Uri("https://graph.microsoft.com/v1.0/me/onenote");
using (var httpClient = new HttpClient { BaseAddress = baseAddress })
{
var request = new HttpRequestMessage(HttpMethod.Get, #"/pages");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", strCode);
using (var response = httpClient.SendAsync(request).Result)
{
string responseData = response.Content.ReadAsStringAsync().Result;
}
}
And in the response data I got
"{ \"error\": { \"code\": \"InvalidAuthenticationToken\", \"message\": \"CompactToken parsing failed with error code: -2147184105\", \"innerError\": { \"request-id\": \"*********************", \"date\": \"2017-06-08T18:25:06\" } } }"
Any idea how to fix this..?
Problem resolved .
I need to convert the authentication code into a "real" access token..
The one that I got is not an access token.

How to automatically download a xlsx file(in angularjs 1) sent by server

The HTTP response for a POST request that I am getting from server side is a xlsx file.How do I download the file in angularjs 1?
Note: res.download() won't work here,since its a POST request that I am making,and res.download() works only for GET request
The following shall work :
$http.post("url_here", post_data_to_send, {responseType: 'arraybuffer'})
.success(function (data,status,headers) {
var blob = new Blob([data]);
var objectUrl = URL.createObjectURL(blob);
var a = document.createElement("a");
a.style = "display:none";
a.href = objectUrl;
a.download = headers().filename;
a.click();
console.log("Report downloaded");
}).error(function (err) {
console.log(err);
});
You can do it directly on Client Side, you may have some cross-browser compatibility issues (the best way is always to provide a download stream via server, for large files for example).
// this example uses a JSON String
// but you can do it with any valid blob argument
const fileContent = [JSON.stringify(
['something', 'to', 'download'], null, 2
)];
const downloader = document.createElement('a');
// set the filename here
downloader.download = 'filename.json';
const blob = new Blob(fileContent, {type: 'text/plain'});
downloader.href = window.URL.createObjectURL(blob);
// trigger the download
downloader.click();
In my opinion, a redirect to the downloadable resource could be the best choice.

Web api large file download with HttpClient

I have a problem with large file download from the web api to the win forms app. On the win form app I'm using HttpClient for grabbing data. I have following code on server side:
[HttpPost]
[Route]
public async Task<HttpResponseMessage> GetBackup(BackupRequestModel request)
{
HttpResponseMessage response;
try
{
response = await Task.Run<HttpResponseMessage>(() =>
{
var directory = new DirectoryInfo(request.Path);
var files = directory.GetFiles();
var lastCreatedFile = files.OrderByDescending(f => f.CreationTime).FirstOrDefault();
var filestream = lastCreatedFile.OpenRead();
var fileResponse = new HttpResponseMessage(HttpStatusCode.OK);
fileResponse.Content = new StreamContent(filestream);
fileResponse.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return fileResponse;
});
}
catch (Exception e)
{
logger.Error(e);
response = Request.CreateResponse(HttpStatusCode.InternalServerError);
}
return response;
}
on client side:
private async void btnStart_Click(object sender, EventArgs e)
{
var requestModel = new BackupRequestModel();
requestModel.Username = txtUsername.Text;
requestModel.Password = txtPassword.Text;
requestModel.Path = txtServerPath.Text;
var client = new HttpClient();
var result = await client.PostAsJsonAsync("http://localhost:50116/api/backup", requestModel);
var stream = await result.Content.ReadAsStreamAsync();
var localPath = #"d:\test\filenew.bak";
var fileStream = File.Create(localPath);
stream.CopyTo(fileStream);
fileStream.Close();
stream.Close();
fileStream.Dispose();
stream.Dispose();
client.Dispose();
}
}
This is actually working, but the purpose of this program is to grab large files over 3GB and save it to the client.
I have tried this on files sized 630MB what I notice is: When I call web api with http client, http client actually loads 630MB in the memory stream, and from the memory stream to the file stream, but when I try to load a different file I'm getting OutOfMemoryException. This is happening because the application doesn't release memory from the previous loaded file. I can see in task manager that it is holding 635MB of ram memory.
My question is how can I write data directly from HttpClient to file without using memory stream, or in other words how can I write data to file while HttpClient is downloading data?
To make the request, use a SendAsync overload that allows you to specify a HttpCompletionOption and use ResponseHeadersRead. You'll have to manually build the request though, without using the PostAsJsonAsync convenience method.

Post to and display web page from Silverlight

I want to post to a web page from my Silverlight application and have the web page appear in a new window.
I can show a web page in a new window using the GET method, using the following code:
var options = new HtmlPopupWindowOptions();
HtmlPage.PopupWindow(new Uri("http://localhost:12345/test.aspx"), "_blank", options);
I can post to a web page and get the resulting data back using this code:
var request = (HttpWebRequest)WebRequest.Create(new Uri("http://localhost:12345/test.aspx"));
request.Method = "POST";
request.ContentType = "text/xml";
request.BeginGetRequestStream(requestResult =>
{
using (var stream = request.EndGetRequestStream(requestResult))
{
using (var writer = new StreamWriter(stream))
{
writer.Write("hello");
}
}
request.BeginGetResponse(responseResult =>
{
var response = request.EndGetResponse(responseResult);
using (var stream = response.GetResponseStream())
{
using (var reader = new StreamReader(stream))
{
var str = reader.ReadToEnd();
}
}
}, null);
}, null);
But what I can't do is the two together - post to the page but instead of getting the data back have the resulting page shown in a browser window. I don't know if this is possible, but any help to achieve this would be much appreciated.

Resources