Giter VIP home page Giter VIP logo

Comments (9)

kelcho-spense avatar kelcho-spense commented on August 16, 2024 1

let me check it. I think I missed that.

from hack-together.

kelcho-spense avatar kelcho-spense commented on August 16, 2024 1

@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.

waldekmastykarz avatar waldekmastykarz commented on August 16, 2024

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.

waldekmastykarz avatar waldekmastykarz commented on August 16, 2024

👋 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.

kelcho-spense avatar kelcho-spense commented on August 16, 2024

Heey @waldekmastykarz am still working on the project, am doing some code refactoring which is a bit problematic .

from hack-together.

kelcho-spense avatar kelcho-spense commented on August 16, 2024

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.

waldekmastykarz avatar waldekmastykarz commented on August 16, 2024

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.

kelcho-spense avatar kelcho-spense commented on August 16, 2024

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.

waldekmastykarz avatar waldekmastykarz commented on August 16, 2024

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)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.