Last active
February 13, 2022 23:47
-
-
Save mabster/70cb40c904f9774b7b70b8a87e6281fb to your computer and use it in GitHub Desktop.
UserPhoto Blazor Component
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@inject GraphServiceClient GraphClient | |
<AuthorizeView> | |
<Authorized> | |
<img src="@_src" | |
title="@_title" | |
onerror="this.src = '@DEFAULT';" | |
class="rounded-circle img-fluid" | |
@attributes="AdditionalAttributes" /> | |
</Authorized> | |
<NotAuthorized> | |
<img src="@DEFAULT" | |
title="Sign In" | |
class="rounded-circle img-fluid" | |
@attributes="AdditionalAttributes" /> | |
</NotAuthorized> | |
</AuthorizeView> | |
@code { | |
[Parameter] | |
public string? Id { get; set; } | |
[Parameter(CaptureUnmatchedValues = true)] | |
public Dictionary<string, object> AdditionalAttributes { get; set; } = new(); | |
const string DEFAULT = "<img in project or data uri>"; | |
string _src = DEFAULT; | |
string _title = "Unknown User"; | |
static Dictionary<string, (string src, string title)> _cache = new(); | |
protected async override Task OnInitializedAsync() | |
{ | |
if (String.IsNullOrEmpty(Id)) return; | |
if (_cache.TryGetValue(Id, out var cache)) | |
{ | |
_src = cache.src; | |
_title = cache.title; | |
return; | |
} | |
var photo = await GraphClient.Users[Id].Photo.Content.Request().GetAsync(); | |
if (photo != null) | |
{ | |
var ms = new System.IO.MemoryStream(); | |
await photo.CopyToAsync(ms); | |
byte[] buffer = ms.ToArray(); | |
string result = Convert.ToBase64String(buffer); | |
_src = string.Format("data:image/png;base64,{0}", result); | |
} | |
var user = await GraphClient.Users[Id].Request().GetAsync(); | |
_title = user?.DisplayName ?? "Unknown User"; | |
_cache.TryAdd(Id, (_src, _title)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Interestingly, the "border-radius: 50%" style works if it's in UserPhoto.razor.css, but doesn't seem to work if it's inline like this.