public async Task <JsonResult> GetAADUserImageAsync(string EMail) { JsonResult ret = null; string tenantID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value; try { string graphResourceID = "https://graph.windows.net/"; UserProfileController userProfileController = new UserProfileController(); Uri servicePointUri = new Uri(graphResourceID); Uri serviceRoot = new Uri(servicePointUri, tenantID); ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient(serviceRoot, async() => await userProfileController.GetTokenForApplication()); // use the token for querying the graph to get the user details var result1 = await activeDirectoryClient.Users.ExecuteAsync();; var result = await activeDirectoryClient.Users .Where(u => u.UserPrincipalName.Equals(EMail)) .ExecuteAsync(); //var result = await activeDirectoryClient.Users // .Where(u => u.ObjectId.Equals(userObjectID)) // .ExecuteAsync(); IUser user = result.CurrentPage.ToList().First(); DataServiceStreamResponse photo = await user.ThumbnailPhoto.DownloadAsync(); using (MemoryStream s = new MemoryStream()) { photo.Stream.CopyTo(s); var encodedImage = Convert.ToBase64String(s.ToArray()); ret = Json(new { Success = true, Base64StringImage = String.Format("data:image/gif;base64,{0}", encodedImage) }); } } catch (AdalException e) { ret = Json(new { Success = false, Message = e.Message }); } // if the above failed, the user needs to explicitly re-authenticate for the app to obtain the required token catch (Exception e) { ret = Json(new { Success = false, Message = e.Message }); } return(ret); }
public async Task <ActionResult> ShowThumbnail(string id) { try { ActiveDirectoryClient client = AuthenticationHelper.GetActiveDirectoryClient(); IUser user = await client.Users.GetByObjectId(id).ExecuteAsync(); try { DataServiceStreamResponse response = await user.ThumbnailPhoto.DownloadAsync(); if (response != null) { return(File(response.Stream, "image/jpeg")); } } catch { var file = Server.MapPath("~/Images/user-placeholder.png"); return(File(file, "image/png", Path.GetFileName(file))); } } catch { } return(View()); }
private void employeesComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { // Get the currently selected employee. currentEmployee = (Employees)this.employeesComboBox.SelectedItem; try { //<snippetGetReadStreamClient> // Get the read stream for the Media Resource of the currently selected // entity (Media Link Entry). using (DataServiceStreamResponse response = context.GetReadStream(currentEmployee, "image/bmp")) { // Use the returned binary stream to create a bitmap image that is // the source of the image control. employeeImage.Source = CreateBitmapFromStream(response.Stream); } //</snippetGetReadStreamClient> //<snippetGetReadStreamClientUri> // Get the read stream URI for the Media Resource of the currently selected // entity (Media Link Entry), and use it to create a bitmap image that is // the source of the image control. employeeImage.Source = new BitmapImage(context.GetReadStreamUri(currentEmployee)); //</snippetGetReadStreamClientUri> } catch (DataServiceRequestException ex) { MessageBox.Show(ex.InnerException.Message); } }
private void gvlODataV3Service_FocusedRowChanged(object sender, FocusedRowChangedEventArgs e) { pictureBox.Image = null; if (ListObjects == null || !(ListObjects[0] is Categories)) { return; } ColumnView view = gclODataV3ServiceMain.FocusedView as ColumnView; if (view.Columns.Count < 1 || view.FocusedRowHandle < 0) { return; } object value = view.GetRowCellValue(view.FocusedRowHandle, view.Columns["CategoryID"]); if (value == null) { pictureBox.Image = null; } else { int categoryID = (int)value; DataServiceStreamResponse resp = context.GetReadStream(context.Categories.Where(i => i.CategoryID == categoryID).Single(), "StreamPicture", new DataServiceRequestArgs()); pictureBox.Image = Image.FromStream(resp.Stream); } }
public async Task <ActionResult> ShowThumbnail(string id) { try { ActiveDirectoryClient client = AuthenticationHelper.GetActiveDirectoryClient(); IUser user = await client.Users.GetByObjectId(id).ExecuteAsync(); DataServiceStreamResponse dataServiceStreamResponse = null; dataServiceStreamResponse = await user.ThumbnailPhoto.DownloadAsync(); if (dataServiceStreamResponse != null) { return(File(dataServiceStreamResponse.Stream, "image/jpeg")); } } catch (Exception e) { if (Request.QueryString["reauth"] == "True") { // // Send an OpenID Connect sign-in request to get a new set of tokens. // If the user still has a valid session with Azure AD, they will not be prompted for their credentials. // The OpenID Connect middleware will return to this controller after the sign-in response has been handled. // HttpContext.GetOwinContext() .Authentication.Challenge(OpenIdConnectAuthenticationDefaults.AuthenticationType); } // // The user needs to re-authorize. Show them a message to that effect. // ViewBag.ErrorMessage = "AuthorizationRequired"; } return(View()); }
public void OpenRunbook() { #if !DEBUG try { #endif if (activeRunbook == null) { return; } Connect(); var runbookId = activeRunbook.Id; var runbook = api.Runbooks.Where(x => x.RunbookID == runbookId).First(); var serviceRequestArgs1 = new DataServiceRequestArgs(); serviceRequestArgs1.AcceptContentType = "application/octet-stream"; var serviceRequestArgs2 = serviceRequestArgs1; var versionId = runbook.DraftRunbookVersionID == null?runbook.Edit(api) : runbook.DraftRunbookVersionID; var runbookVersion = api.RunbookVersions.Where(x => x.RunbookVersionID == versionId).First(); var parameters = api.RunbookParameters.Where(x => x.RunbookVersionID == runbook.DraftRunbookVersionID).ToArray(); RunbookParameters = parameters.Select(x => new RunbookParameterDefinition { Name = x.Name, IsMandatory = x.IsMandatory, Type = x.Type, Value = string.Empty }).ToList(); string content; using (DataServiceStreamResponse readStream = ((DataServiceContext)api).GetReadStream((object)runbookVersion, serviceRequestArgs2)) { using (var streamReader = new StreamReader(readStream.Stream)) content = streamReader.ReadToEnd(); } var tempFile = activeRunbooks.FirstOrDefault(x => x.Value == runbook.RunbookID).Key; if (string.IsNullOrEmpty(tempFile)) { tempFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("D") + ".ps1"); activeRunbooks[tempFile] = runbook.RunbookID; } File.WriteAllText(tempFile, content); View.Open(tempFile); #if !DEBUG } catch (Exception ex) { MessageBox.Show(GetErrorMessage(ex), "Error", MessageBoxButton.OK, MessageBoxImage.Error); } #endif }
public async Task <string> GetThumbnailAsync(string userPrincipal) { var user = await activeDirectoryClient.Users.Where(x => x.UserPrincipalName == userPrincipal).ExecuteSingleAsync(); DataServiceStreamResponse photo = await user.ThumbnailPhoto.DownloadAsync(); using (MemoryStream s = new MemoryStream()) { photo.Stream.CopyTo(s); return(Constants.Base64Prefix + Convert.ToBase64String(s.ToArray())); } }
internal DataServiceStreamResponse End() { if (this.response != null) { DataServiceStreamResponse streamResponse = new DataServiceStreamResponse(this.response); return streamResponse; } else { return null; } }
// GET: UserProfile public async Task <ActionResult> Index() { string tenantID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value; string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value; ViewBag.FullName = ClaimsPrincipal.Current.FindFirst(ClaimTypes.GivenName).Value + " " + ClaimsPrincipal.Current.FindFirst(ClaimTypes.Surname).Value; try { Uri servicePointUri = new Uri(graphResourceID); Uri serviceRoot = new Uri(servicePointUri, tenantID); ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient(serviceRoot, async() => await GetTokenForApplication()); // use the token for querying the graph to get the user details var result = await activeDirectoryClient.Users .Where(u => u.ObjectId.Equals(userObjectID)) .ExecuteAsync(); IUser user = result.CurrentPage.ToList().First(); try { if (user.ThumbnailPhoto.ContentType != null) { DataServiceStreamResponse photo = await user.ThumbnailPhoto.DownloadAsync(); using (MemoryStream s = new MemoryStream()) { photo.Stream.CopyTo(s); string encodedImage = Convert.ToBase64String(s.ToArray()); ViewBag.imageUrl = string.Format("data:image/png;base64,{0}", encodedImage); } } } catch (Exception ex) { } return(View(user)); } catch (AdalException) { // Return to error page. return(View("Error")); } // if the above failed, the user needs to explicitly re-authenticate for the app to obtain the required token catch (Exception) { return(View("Relogin")); } }
/// <summary> /// Ends the request and creates the response object. /// </summary> /// <returns>The response object for this request.</returns> internal DataServiceStreamResponse End() { if (this.responseMessage != null) { // update the etag if the response contains the etag this.streamDescriptor.ETag = this.responseMessage.GetHeader(XmlConstants.HttpResponseETag); // update the content type of the stream for named stream. this.streamDescriptor.ContentType = this.responseMessage.GetHeader(XmlConstants.HttpContentType); DataServiceStreamResponse streamResponse = new DataServiceStreamResponse(this.responseMessage); return(streamResponse); } else { return(null); } }
/// <summary> /// Verifies the streams data. /// </summary> /// <param name="expectedStreamValue">The expected stream value.</param> /// <param name="response">The stream response.</param> /// <returns>The result of stream verification</returns> protected bool VerifyStreams(AstoriaQueryStreamValue expectedStreamValue, DataServiceStreamResponse response) { var expectedBytes = new byte[0]; if (!expectedStreamValue.IsNull) { expectedBytes = expectedStreamValue.Value; } var expectedStream = new MemoryStream(expectedBytes); try { ExceptionUtilities.Assert(response.Stream.CanRead, "Cannot read from the stream"); return(StreamHelpers.CompareStream(response.Stream, expectedStream)); } finally { response.Stream.Dispose(); expectedStream.Dispose(); } }
private static void UpdateStreamValueFromHeaders(AstoriaQueryStreamValue expectedStreamValue, DataServiceStreamResponse response) { expectedStreamValue.ContentType = response.Headers[HttpHeaders.ContentType]; string etag; response.Headers.TryGetValue(HttpHeaders.ETag, out etag); expectedStreamValue.ETag = etag; }
private void OnGetReadStreamComplete(IAsyncResult result) { // Obtain the virtual store for the application. IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication(); Title title = result.AsyncState as Title; if (title != null) { // Use the Dispatcher to ensure that the // asynchronous call returns in the correct thread. Deployment.Current.Dispatcher.BeginInvoke(() => { try { // Get the response. DataServiceStreamResponse response = _context.EndGetReadStream(result); // Construct the file name from the entity ID. string fileStorageName = string.Format("{0}\\{1}.png", isoPathName, title.Id); // Specify the file path and options. using (var isoFileStream = new IsolatedStorageFileStream(fileStorageName, FileMode.Create, isoStore)) { //Write the data using (var fileWriter = new BinaryWriter(isoFileStream)) { byte[] buffer = new byte[1000]; int count = 0; // Read the returned stream into the new file stream. while (response.Stream.CanRead && (0 < ( count = response.Stream.Read(buffer, 0, buffer.Length)))) { fileWriter.Write(buffer, 0, count); } } } using (var bitmapFileStream = new IsolatedStorageFileStream(fileStorageName, FileMode.Open, isoStore)) { // Return the image as a BitmapImage. // Create a new bitmap image using the memory stream. BitmapImage imageFromStream = new BitmapImage(); imageFromStream.SetSource(bitmapFileStream); // Return the bitmap. title.DefaultImage = imageFromStream; } } catch (DataServiceClientException) { // We need to eat this exception so that loading can continue. // Plus there is a bug where the binary stream gets /// written to the message. } }); } }
protected override bool AuthorizeCore(HttpContextBase httpContext) { if (httpContext == null || httpContext.Session == null) { throw new ArgumentNullException("httpContext"); } if (base.AuthorizeCore(httpContext)) { if (httpContext.Session[Config.IsAuthorized] == null) { if (AuthorizedUsersCache.Instance.Contains(GraphHelper.UserObjectId)) { httpContext.Session.Add(Config.IsAuthorized, true); httpContext.Session.Add(Config.Role, AuthorizedUsersCache.Instance[GraphHelper.UserObjectId]); return(true); } else { try { ActiveDirectoryClient activeDirectoryClient = GraphHelper.ActiveDirectoryClient(); // user thumbnail photo var users = Task.Run(async() => await activeDirectoryClient.Users.Where(u => u.ObjectId.Equals(GraphHelper.UserObjectId)).ExecuteAsync()).Result; IUser user = users.CurrentPage.ToList().First(); if (user.ThumbnailPhoto.ContentType != null) { DataServiceStreamResponse response = Task.Run(async() => await user.ThumbnailPhoto.DownloadAsync()).Result; using (var ms = new MemoryStream()) { response.Stream.CopyTo(ms); string imageBase64 = Convert.ToBase64String(ms.ToArray()); string image = string.Format("data:image/gif;base64,{0}", imageBase64); httpContext.Session.Add(Config.ThumbnailPhoto, image); httpContext.Response.Cookies.Add(new HttpCookie(Config.ThumbnailPhotoCookie) { Secure = true, Value = HttpUtility.UrlEncode(image) }); } } List <string> userRoles = new List <string>(); // earnit-admin security group bool?isUserInRole = Task.Run(async() => await activeDirectoryClient.IsMemberOfAsync(Config.SecurityGroups[Config.Roles.Admin], GraphHelper.UserObjectId)).Result; if (isUserInRole.GetValueOrDefault(false)) { userRoles.Add(Config.Roles.Admin); } // earnit security group isUserInRole = Task.Run(async() => await activeDirectoryClient.IsMemberOfAsync(Config.SecurityGroups[Config.Roles.User], GraphHelper.UserObjectId)).Result; if (isUserInRole.GetValueOrDefault(false)) { userRoles.Add(Config.Roles.User); } // earnit-support security group isUserInRole = Task.Run(async() => await activeDirectoryClient.IsMemberOfAsync(Config.SecurityGroups[Config.Roles.Support], GraphHelper.UserObjectId)).Result; if (isUserInRole.GetValueOrDefault(false)) { userRoles.Add(Config.Roles.Support); } if (userRoles.Any()) { httpContext.Session.Add(Config.IsAuthorized, true); httpContext.Session.Add(Config.Role, userRoles); AuthorizedUsersCache.Instance.AddToCache(GraphHelper.UserObjectId, userRoles); return(true); } } catch (Exception ex) { if (Config.IsProduction) { Log.Critical(ex, "ActiveDirectoryClient failed in AuthorizeSGAttribute"); TelemetryClient telemetry = new TelemetryClient(); telemetry.TrackException(ex); } else { List <string> admin = new List <string> { Config.Roles.Admin }; httpContext.Session.Add(Config.IsAuthorized, true); httpContext.Session.Add(Config.Role, admin); AuthorizedUsersCache.Instance.AddToCache(GraphHelper.UserObjectId, admin); return(true); } } httpContext.Session.Add(Config.IsAuthorized, false); httpContext.Session.Add(Config.Role, new List <string> { Config.Roles.Visitor }); AuthorizedUsersCache.Instance.Remove(GraphHelper.UserObjectId); } } return((bool)httpContext.Session[Config.IsAuthorized]); } if (!string.IsNullOrWhiteSpace(this.Roles)) { string[] authorizedRoles = this.Roles.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); List <string> userRoles = (List <string>)httpContext.Session[Config.Role]; return(authorizedRoles.Intersect(userRoles).Any()); } return(false); }