Comments (9)
let me check it. I think I missed that.
from hack-together.
@waldekmastykarz Since I will not make it for the deadline. I have submitted console app for the hackathon #182 . I will work on this project till it works.
from hack-together.
Thank you for sharing your hack with us, @kelcho-spense. It seems like you're not using the Microsoft Graph .NET SDK to connect to Microsoft Graph, which is one of the qualifying criteria for this hackathon. Could you please update your code to use the SDK? 😊
from hack-together.
👋 Hey @kelcho-spense, are you going to update your project to use the Microsoft Graph .NET SDK and make a chance to win one of the cool prizes we've got in the hackathon?
from hack-together.
Heey @waldekmastykarz am still working on the project, am doing some code refactoring which is a bit problematic .
from hack-together.
I have integrated the login system with the app consuming the graph SDK, am having some issues with fetching the token to enable me to add an event to the calendar.
from hack-together.
Sorry to hear that. Do you have any code that you could share so that we can see what's wrong and what's the best way forward?
from hack-together.
Heey @waldekmastykarz sorry, I was a bit late, machine issues. My previous code which was adding events to graph via http client was using this function AddEventAsync and this function to GetEventsInMonthAsync to get events in a month.
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using BlazorCalendar.Models;
using Microsoft.AspNetCore.Components.WebAssembly.Authentication;
using Newtonsoft.Json;
namespace BlazorCalendar.Services
{
public class MicrosoftCalendarEventsProvider : ICalendarEventsProvider
{
// Get Access token
private readonly IAccessTokenProvider _accessTokenProvider;
private readonly HttpClient _httpClient;
private const string BASE_URL = "https://graph.microsoft.com/v1.0/me/events";
public MicrosoftCalendarEventsProvider(IAccessTokenProvider accessTokenProvider, HttpClient httpClient)
{
_accessTokenProvider = accessTokenProvider;
_httpClient = httpClient;
}
public async Task<IEnumerable<CalendarEvent>> GetEventsInMonthAsync(int year, int month)
{
// 1- Get Token
var accessToken = await GetAccessTokenAsync();
if(accessToken == null)
return null;
// 2- Set the access token in the authorization header
_httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", accessToken);
// 3- Send the request
var response = await _httpClient.GetAsync(ConstructGraphUrl(year, month));
if(!response.IsSuccessStatusCode)
{
return null;
}
// 4- Read the content
var contentAsString = await response.Content.ReadAsStringAsync();
var microsoftEvents = JsonConvert.DeserializeObject<GraphEventsResponse>(contentAsString);
// Convert the Microsoft Event object into CalendarEvent object
var events = new List<CalendarEvent>();
foreach (var item in microsoftEvents.Value)
{
events.Add(new CalendarEvent
{
Subject = item.Subject,
StartDate = item.Start.ConvertToLocalDateTime(),
EndDate = item.End.ConvertToLocalDateTime()
});
}
return events;
}
public async Task AddEventAsync(CalendarEvent calendarEvent)
{
// 1- Get Token
var accessToken = await GetAccessTokenAsync();
if(accessToken == null)
{
Console.WriteLine("Access Token is not available");
return;
}
// 2- Set the access token in the authorization header
_httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", accessToken);
// 3- Initialize the content of the post request
string eventAsJson = JsonConvert.SerializeObject(new MicrosoftGraphEvent
{
Subject = calendarEvent.Subject,
Start = new DateTimeTimeZone
{
DateTime = calendarEvent.StartDate.ToString(),
TimeZone = TimeZoneInfo.Local.Id
},
End = new DateTimeTimeZone
{
DateTime = calendarEvent.EndDate.ToString(),
TimeZone = TimeZoneInfo.Local.Id,
}
});
var content = new StringContent(eventAsJson);
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
// Send the request
var response = await _httpClient.PostAsync(BASE_URL, content);
if(response.IsSuccessStatusCode)
Console.WriteLine("Event has been added successfully!");
else
Console.WriteLine(response.StatusCode);
}
private async Task<string> GetAccessTokenAsync()
{
var tokenRequest = await _accessTokenProvider.RequestAccessToken(new AccessTokenRequestOptions
{
Scopes = new[] { "https://graph.microsoft.com/Calendars.ReadWrite" }
});
// Try to fetch the token
if(tokenRequest.TryGetToken(out var token))
{
if(token != null)
{
return token.Value;
}
}
return null;
}
private string ConstructGraphUrl(int year, int month)
{
return $"{BASE_URL}?$filter=start/datetime ge '{year}-{month}-01T00:00' and end/dateTime le '{year}-{month}-31T00:00'&$select=subject,start,end";
}
}
}
currently am stuck on updating the code to consume graph. My currrent code with issues
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using BlazorCalendar.Models;
using Microsoft.AspNetCore.Components.WebAssembly.Authentication;
using Microsoft.Graph;
using Microsoft.Kiota.Abstractions.Authentication;
using Newtonsoft.Json;
namespace BlazorCalendar.Services
{
public class MicrosoftCalendarEventsProvider : ICalendarEventsProvider
{
// Get Access token
private readonly Microsoft.AspNetCore.Components.WebAssembly.Authentication.IAccessTokenProvider _accessTokenProvider;
// private readonly HttpClient _httpClient;
private const string BASE_URL = "https://graph.microsoft.com/v1.0/me/events";
// public MicrosoftCalendarEventsProvider(Microsoft.AspNetCore.Components.WebAssembly.Authentication.IAccessTokenProvider accessTokenProvider, HttpClient httpClient)
// {
// _accessTokenProvider = accessTokenProvider;
// _httpClient = httpClient;
// }
public async Task<IEnumerable<CalendarEvent>> GetEventsInMonthAsync(int year, int month)
{
// 3- Send the request
var graphClient = await BuildGraphClientAsync();
var microsoftEvents = await graphClient.Me.Events.GetAsync((requestConfiguration) =>
{
requestConfiguration.QueryParameters.Filter = "startsWith(subject,'All')";
});
var events = new List<CalendarEvent>();
foreach (var item in microsoftEvents.Value)
{
events.Add(new CalendarEvent
{
Subject = item.Subject,
StartDate = item.Start.ConvertToLocalDateTime(),
EndDate = item.End.ConvertToLocalDateTime()
});
}
return events;
}
public async Task AddEventAsync(CalendarEvent calendarEvent)
{
var graphClient = await BuildGraphClientAsync();
// Send the request
var requestBody = new Microsoft.Graph.Models.Event
{
Subject = calendarEvent.Subject,
Start = new DateTimeTimeZone
{
DateTime = calendarEvent.StartDate.ToString(),
TimeZone = TimeZoneInfo.Local.Id
},
End = new DateTimeTimeZone
{
DateTime = calendarEvent.EndDate.ToString(),
TimeZone = TimeZoneInfo.Local.Id,
}
};
var response = await graphClient.Me.Events.PostAsync(requestBody);
Console.WriteLine(response);
}
private async Task<GraphServiceClient> BuildGraphClientAsync()
{
var token = await GetAccessTokenAsync();
var tokenProvider = new GraphTokenProvider(token);
var authProvider = new BaseBearerTokenAuthenticationProvider(tokenProvider);
return new GraphServiceClient(authProvider);
}
private async Task<string> GetAccessTokenAsync()
{
var tokenRequest = await _accessTokenProvider.RequestAccessToken(new AccessTokenRequestOptions
{
Scopes = new[] { "https://graph.microsoft.com/Calendars.ReadWrite" }
});
// Try to fetch the token
if (tokenRequest.TryGetToken(out var token))
{
if (token != null)
{
return token.Value;
}
}
return null;
}
private string ConstructGraphUrl(int year, int month)
{
var daysInMonth = DateTime.DaysInMonth(year, month);
return $"{BASE_URL}?$filter=start/dateTime ge '{year}-{month}-01T00:00' and end/dateTime le '{year}-{month}-{daysInMonth}T00:00'&$select=subject,start,end";
}
}
internal class GraphTokenProvider : Microsoft.Kiota.Abstractions.Authentication.IAccessTokenProvider
{
public AllowedHostsValidator AllowedHostsValidator { get; }
private readonly string _accessToken;
public GraphTokenProvider(string accessToken)
{
_accessToken = accessToken;
}
public Task<string> GetAuthorizationTokenAsync(Uri uri, Dictionary<string, object> additionalAuthenticationContext = null, CancellationToken cancellationToken = default)
{
return Task.FromResult(_accessToken);
}
}
}
from hack-together.
Have you looked at our template app for Blazor and the linked tutorial at the end? https://github.com/microsoft/hack-together/tree/main/templates/dotnet-blazor-server-app-microsoft-graph. It seems like you're doing a lot of manual work around retrieving the token and calling Microsoft Graph, which should be already handled by the Identity and Microsoft Graph SDK.
from hack-together.
Related Issues (20)
- Project: Summarize an email (Use Cognitive Services for the summarization) and send the summary to a Teams channel. HOT 4
- Project: [Microsoft Learn Tutorial] Build dotNET apps with Microsoft Graph SDK HOT 4
- Project: Graph SDK to get calendar items and send mail HOT 1
- Project: Create Teams Meeting HOT 1
- Project: Gets a specified attributes of a signed in users profile information HOT 1
- Project: This is a sample app that get user info using the Microsoft GraphApi HOT 1
- Project: Automation in Hazardous Jobs HOT 5
- Project: An app for aggregating and sharing files from all drives in an organization HOT 6
- Project: Microsoft Teams Bot - Schedule Meetings for a Team and send the meeting link by e-mail for all members HOT 2
- Project: Financial Control HOT 6
- Project: This Web Portal Displays TeamsUser details along with their Current Availability Status HOT 5
- Project: Console app using GraphApi to see next events and create new ones HOT 5
- A helper in need on Microsoft Teams HOT 5
- Project: Convert users' meeting recordings to summarized text and send summary by email HOT 2
- Project: What was I doing again? HOT 3
- SharePoint Large File Downloader & Uploader Toolkit for the Modern Workplace HOT 4
- https://nam06.safelinks.protection.outlook.com/ap/p-59584e83/?url=https%3A%2F%2F1drv.ms%2Fp%2Fs!AuNMtEjxAns_gQpFYBenRALwSV5B%3Fe%3DXDO5eJ&data=05%7C01%7CDaisy.Chaussee%40microsoft.com%7C0c6c70c7cabf42360ca708db2616a024%7C72f988bf86f141af91ab2d7cd011db47%7C1%7C0%7C638145651782668569%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C2000%7C%7C%7C&sdata=FQhX00ygwuDCoYdb%2BDtO3ts6Y3gMn4MzceXEQa1chvo%3D&reserved=0: <short description> HOT 1
- It will be possible to write a comment in a specific cell in an excel file? HOT 1
- Project: Summarize videos hosted in Drive HOT 1
- Project: <Hack-together> HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from hack-together.