public static async Task <SharepointSite[]> SearchSharepointSitesAsync(this MicrosoftGraphHelper mgh, string query) { HttpRequestMessage req = mgh.PrepareHttpRequestMessage(); req.Method = HttpMethod.Get; req.RequestUri = new Uri("https://graph.microsoft.com/v1.0/sites?search=" + HttpUtility.UrlEncode(query)); HttpClient hc = new HttpClient(); HttpResponseMessage msg = await hc.SendAsync(req); string content = await msg.Content.ReadAsStringAsync(); if (msg.StatusCode != HttpStatusCode.OK) { throw new Exception("Search of Sharepoint Sites failed with code \"" + msg.StatusCode.ToString() + "\". Body: " + content); } JObject jo = JObject.Parse(content); //Get them JArray ja_value = JArray.Parse(jo.Property("value").Value.ToString()); List <SharepointSite> Sites = new List <SharepointSite>(); foreach (JObject jo_ss in ja_value) { SharepointSite ss = new SharepointSite(jo_ss.ToString()); Sites.Add(ss); } return(Sites.ToArray()); }
public static async Task <SharepointList[]> ListSharepointListsAsync(this MicrosoftGraphHelper mgh, Guid site_id) { HttpRequestMessage req = mgh.PrepareHttpRequestMessage(); req.Method = HttpMethod.Get; req.RequestUri = new Uri("https://graph.microsoft.com/v1.0/sites/" + site_id.ToString() + "/lists"); HttpClient hc = new HttpClient(); HttpResponseMessage msg = await hc.SendAsync(req); string content = await msg.Content.ReadAsStringAsync(); if (msg.StatusCode != HttpStatusCode.OK) { throw new Exception("Listing lists from sharepoint site '" + site_id.ToString() + "' failed with code \"" + msg.StatusCode.ToString() + "\". Body: " + content); } JObject jo = JObject.Parse(content); //Get them JArray ja_value = JArray.Parse(jo.Property("value").Value.ToString()); List <SharepointList> Lists = new List <SharepointList>(); foreach (JObject jo_sl in ja_value) { SharepointList sl = SharepointList.ParseFromJsonPayload(jo_sl.ToString()); Lists.Add(sl); } return(Lists.ToArray()); }
public static void BrowseFilesLibrary() { // Create a PnP AuthenticationManager object AuthenticationManager am = new AuthenticationManager(); // Authenticate against SPO with a delegated access token using (ClientContext context = am.GetAzureADWebApplicationAuthenticatedContext( O365ProjectsAppContext.CurrentSiteUrl, (url) => { return(MicrosoftGraphHelper.GetAccessTokenForCurrentUser(url)); })) { Web web = context.Web; var targetLibrary = web.GetListByTitle(O365ProjectsAppSettings.LibraryTitle); context.Load(targetLibrary.RootFolder, fld => fld.ServerRelativeUrl, fld => fld.Files.Include(f => f.Title, f => f.ServerRelativeUrl)); context.ExecuteQueryRetry(); foreach (var file in targetLibrary.RootFolder.Files) { // Handle each file object ... this is just a sample ... } } }
/// <summary> /// This method retrieves the photo of a single user from Azure AD /// </summary> /// <param name="upn">The UPN of the user</param> /// <returns>The user's photo retrieved from Azure AD</returns> private static Stream GetUserPhoto(String upn) { String contentType = "image/png"; var result = MicrosoftGraphHelper.MakeGetRequestForStream( String.Format("{0}users/{1}/photo/$value", MicrosoftGraphHelper.MicrosoftGraphV1BaseUri, upn), contentType); return(result); }
public ActionResult Index() { // Just fire the OAuth access token request var token = MicrosoftGraphHelper.GetAccessTokenForCurrentUser(); var model = new IndexViewModel(); if (System.Security.Claims.ClaimsPrincipal.Current != null && System.Security.Claims.ClaimsPrincipal.Current.Identity != null && System.Security.Claims.ClaimsPrincipal.Current.Identity.IsAuthenticated) { model.CurrentUserPrincipalName = System.Security.Claims.ClaimsPrincipal.Current.Identity.Name; } return(View(model)); }
public ActionResult StartNewProject() { Guid groupId = Guid.NewGuid(); var groupNameId = groupId.ToString().Replace("-", ""); MemoryStream memPhoto = new MemoryStream(); using (FileStream fs = new FileStream(Server.MapPath("~/AppIcon.png"), FileMode.Open, FileAccess.Read, FileShare.Read)) { Byte[] newPhoto = new Byte[fs.Length]; fs.Read(newPhoto, 0, (Int32)(fs.Length - 1)); memPhoto.Write(newPhoto, 0, newPhoto.Length); memPhoto.Position = 0; } GroupCreationInformation job = new GroupCreationInformation { AccessToken = MicrosoftGraphHelper.GetAccessTokenForCurrentUser( O365ProjectsAppSettings.MicrosoftGraphResourceId), JobId = groupId, Name = groupNameId, Members = new String[] { "*****@*****.**", "*****@*****.**" }, Photo = memPhoto.ToArray(), }; try { // Get the storage account for Azure Storage Queue CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["AzureWebJobsStorage"].ConnectionString); // Get queue ... and create if it does not exist CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient(); CloudQueue queue = queueClient.GetQueueReference(O365ProjectsAppConstants.Blob_Storage_Queue_Name); queue.CreateIfNotExists(); // Add entry to queue queue.AddMessage(new CloudQueueMessage(JsonConvert.SerializeObject(job))); } catch (Exception) { // TODO: Handle any exception thrown by the object of type CloudQueue } return(View()); }
/// <summary> /// This method retrieves the current user from Azure AD /// </summary> /// <returns>The user retrieved from Azure AD</returns> public static LightGraphUser GetCurrentUser() { String jsonResponse = MicrosoftGraphHelper.MakeGetRequestForString( String.Format("{0}me", MicrosoftGraphHelper.MicrosoftGraphV1BaseUri)); if (jsonResponse != null) { var user = JsonConvert.DeserializeObject <LightGraphUser>(jsonResponse); return(user); } else { return(null); } }
public ActionResult Create(IndexViewModel model) { AntiForgery.Validate(); if (ModelState.IsValid) { // Set the current SPO Admin Site URL model.SPORootSiteUrl = ConfigurationManager.AppSettings["SPORootSiteUrl"]; // Set the current user's access token model.UserAccessToken = MicrosoftGraphHelper.GetAccessTokenForCurrentUser(model.SPORootSiteUrl); // Get the JSON site creation information String modernSiteCreation = JsonConvert.SerializeObject(model); String targetQueue = String.Empty; // Determine the target asynchronous creation technique switch (model.AsyncTech) { case AsynchronousTechnique.AzureFunction: targetQueue = ConfigurationManager.AppSettings["AzureFunctionQueue"]; break; case AsynchronousTechnique.AzureWebJob: default: targetQueue = ConfigurationManager.AppSettings["AzureWebJobQueue"]; break; } // Get the storage account for Azure Storage Queue CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["StorageQueue"].ConnectionString); // Get queue ... and create if it does not exist CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient(); CloudQueue queue = queueClient.GetQueueReference(targetQueue); queue.CreateIfNotExists(); // Add entry to queue queue.AddMessage(new CloudQueueMessage(modernSiteCreation)); } return(View(model)); }
public ActionResult Index() { var me = MicrosoftGraphHelper.MakeGetRequestForString(MicrosoftGraphHelper.MicrosoftGraphV1BaseUri + "me"); try { SPORemoteActions.ProvisionArtifactsByCode(); SPORemoteActions.BrowseFilesLibrary(); // PlayWithGroupsViaGraphAPI(); } catch { // Skip exception for training purposes only } ViewBag.Current = "Index"; return(View()); }
/// <summary> /// This method retrieves the photo of a single user from Azure AD /// </summary> /// <param name="upn">The UPN of the user</param> /// <returns>The user's photo retrieved from Azure AD</returns> private static Stream GetUserPhoto(String upn) { String contentType = "image/png"; Stream result = null; try { result = HttpHelper.MakeGetRequestForStream( String.Format("{0}users/{1}/photo/$value", MicrosoftGraphConstants.MicrosoftGraphV1BaseUri, upn), contentType, MicrosoftGraphHelper.GetAccessTokenForCurrentUser(MicrosoftGraphConstants.MicrosoftGraphResourceId)); } catch (Exception) { // Ignore any exception related to image download, // in order to get the default icon with user's initials } return(result); }
public static async Task SendOutlookEmailMessageAsync(this MicrosoftGraphHelper mgh, OutlookEmailMessage msg) { await mgh.RefreshAccessTokenIfExpiredAsync(); //Make the request HttpRequestMessage reqmsg = new HttpRequestMessage(); reqmsg.Method = HttpMethod.Post; reqmsg.RequestUri = new Uri("https://graph.microsoft.com/v1.0/me/sendMail"); reqmsg.Headers.Add("Authorization", "Bearer " + mgh.LastReceivedTokenPayload.AccessToken); reqmsg.Content = new StringContent(msg.ToPayload(), Encoding.UTF8, "application/json"); //Make the call HttpClient hc = new HttpClient(); HttpResponseMessage hrm = await hc.SendAsync(reqmsg); if (hrm.StatusCode != HttpStatusCode.Accepted) { string errcontent = await hrm.Content.ReadAsStringAsync(); throw new Exception("Response from graph server was \"" + hrm.StatusCode.ToString() + "\". Response body: " + errcontent); } }
public static async Task CreateItemAsync(this MicrosoftGraphHelper mgh, Guid site_id, Guid list_id, JObject fields) { HttpRequestMessage req = mgh.PrepareHttpRequestMessage(); req.Method = HttpMethod.Post; req.RequestUri = new Uri("https://graph.microsoft.com/v1.0/sites/" + site_id.ToString() + "/lists/" + list_id.ToString() + "/items"); //Create the body JObject jo = new JObject(); jo.Add("fields", fields); req.Content = new StringContent(jo.ToString(), System.Text.Encoding.UTF8, "application/json"); //Send! HttpClient hc = new HttpClient(); HttpResponseMessage resp = await hc.SendAsync(req); if (resp.StatusCode != HttpStatusCode.Created) { string msg = await resp.Content.ReadAsStringAsync(); throw new Exception("Creation of new record failed. Msg: " + msg); } }
public static async Task <SharepointListItem[]> GetAllItemsFromSharepointListAsync(this MicrosoftGraphHelper mgh, Guid site_id, Guid list_id) { HttpRequestMessage req = mgh.PrepareHttpRequestMessage(); req.Method = HttpMethod.Get; req.RequestUri = new Uri("https://graph.microsoft.com/v1.0/sites/" + site_id.ToString() + "/lists/" + list_id.ToString() + "/items?expand=fields"); HttpClient hc = new HttpClient(); HttpResponseMessage msg = await hc.SendAsync(req); string content = await msg.Content.ReadAsStringAsync(); if (msg.StatusCode != HttpStatusCode.OK) { throw new Exception("Getting all items from sharepoint list '" + list_id.ToString() + "' failed with code \"" + msg.StatusCode.ToString() + "\". Body: " + content); } JObject jo = JObject.Parse(content); //Get them JArray ja_value = JArray.Parse(jo.Property("value").Value.ToString()); List <SharepointListItem> SPitems = new List <SharepointListItem>(); foreach (JObject jo_li in ja_value) { SharepointListItem spli = SharepointListItem.ParseFromJsonPayload(jo_li.ToString()); SPitems.Add(spli); } return(SPitems.ToArray()); }
public ActionResult Index() { var result = MicrosoftGraphHelper.MakeGetRequestForString("https://graph.microsoft.com/v1.0/me"); return(View()); }
public ActionResult Index() { var result = MicrosoftGraphHelper.MakeGetRequestForString(MSGraphAPIDemoSettings.MicrosoftGraphResourceId + "/v1.0/me"); return(View()); }