在此部分中,您将添加在用户日历上创建事件的能力。In this section you will add the ability to create events on the user's calendar.

新建事件选项卡Create the new event tab

  1. ./Pages 目录中新建一个名为 NewEvent.cshtml 的文件并添加以下代码。Create a new file in the ./Pages directory named NewEvent.cshtml and add the following code.

    @page
    <!-- Copyright (c) Microsoft Corporation.
         Licensed under the MIT License. -->
    @{
      ViewData["Title"] = "New event";
    }
    
    <div class="form-container">
      <form id="newEventForm">
        <div class="ms-Grid" dir="ltr">
          <div class="ms-Grid-row">
            <div class="ms-Grid-col ms-sm12">
              <label class="ms-fontWeight-semibold form-label" for="subject">Subject</label>
              <input class="form-input" type="text" id="subject" name="subject" />
            </div>
          </div>
          <div class="ms-Grid-row">
            <div class="ms-Grid-col ms-sm12">
              <label class="ms-fontWeight-semibold form-label" for="attendees">Attendees</label>
              <input class="form-input" type="text" id="attendees" name="attendees" placeholder="Enter email addresses of attendees. Separate multiple with ';'. Leave blank for no attendees." />
            </div>
          </div>
          <div class="ms-Grid-row">
            <div class="ms-Grid-col ms-sm6">
              <label class="ms-fontWeight-semibold form-label" for="start">Start</label>
              <input class="form-input" type="datetime-local" id="start" name="start" />
            </div>
            <div class="ms-Grid-col ms-sm6">
              <label class="ms-fontWeight-semibold form-label" for="end">End</label>
              <input class="form-input" type="datetime-local" id="end" name="end" />
            </div>
          </div>
          <div class="ms-Grid-row">
            <div class="ms-Grid-col ms-sm12">
              <label class="ms-fontWeight-semibold form-label" for="body">Body</label>
              <textarea class="form-input" id="body" name="body" rows="4"></textarea>
            </div>
          </div>
          <input class="form-button" type="submit" value="Create"/>
        </div>
      </form>
      <div class="ms-depth-16 result-panel"></div>
    </div>
    
    @section Scripts
    {
      <script>
        (function () {
          if (microsoftTeams) {
            microsoftTeams.initialize();
          }
    
          $('#newEventForm').on('submit', async (e) => {
            e.preventDefault();
            $('.result-panel').empty();
            $('.result-panel').hide();
    
            const formData = new FormData(newEventForm);
    
            // Basic validation
            // Require subject, start, and end
            const subject = formData.get('subject');
            const start = formData.get('start');
            const end = formData.get('end');
    
            if (subject.length <= 0 || start.length <= 0 || end.length <= 0) {
              $('<div/>', {
                class: 'error-msg',
                text: 'Subject, Start, and End are required.'
              }).appendTo('.result-panel');
              $('.result-panel').show();
              return;
            }
    
            // Get the auth token from Teams
            microsoftTeams.authentication.getAuthToken({
              successCallback: (token) => {
                createEvent(token, formData);
              },
              failureCallback: (error) => {
                $('<div/>', {
                  class: 'error-msg',
                  text: `Error getting token: ${error}`
                }).appendTo('.result-panel');
                $('.result-panel').show();
              }
            });
          });
        })();
    
        async function createEvent(token, formData) {
          // Convert the form to a JSON payload
          jsonFormData = formDataToJson();
    
          // Post the payload to the web API
          const response = await fetch('/calendar', {
            headers: {
              'Authorization': `Bearer ${token}`,
              'Content-Type': 'application/json'
            },
            method: 'POST',
            body: jsonFormData
          });
    
          if (response.ok) {
            $('<div/>', {
              class: 'success-msg',
              text: 'Event added to your calendar'
            }).appendTo('.result-panel');
            $('.result-panel').show();
          } else {
            const error = await response.text();
            $('<div/>', {
              class: 'error-msg',
              text: `Error creating event: ${error}`
            }).appendTo('.result-panel');
            $('.result-panel').show();
          }
        }
    
        // Helper method to serialize the form fields
        // as JSON
        function formDataToJson() {
          const array = $('#newEventForm').serializeArray();
          const jsonObj = {};
    
          array.forEach((kvp) => {
            jsonObj[kvp.name] = kvp.value;
          });
    
          return JSON.stringify(jsonObj);
        }
      </script>
    }
    

    这将实现一个简单的表单,并添加 JavaScript 以将表单数据张贴到 Web API。This implements a simple form, and adds JavaScript to post the form data to the Web API.

实现 Web APIImplement the Web API

  1. 在项目的根目录中新建一个名为 Models 的目录。Create a new directory named Models in the root of the project.

  2. 在名为 NewEvent.cs 的 ./Models 目录中 创建新文件,并添加以下代码。Create a new file in the ./Models directory named NewEvent.cs and add the following code.

    namespace GraphTutorial.Models
    {
        public class NewEvent
        {
            public string Subject { get; set; }
            public string Attendees { get; set; }
            public string Start { get; set; }
            public string End { get; set; }
            public string Body { get; set; }
        }
    }
    
  3. 打开 ./Controllers/CalendarController.cs, 在文件顶部 using 添加以下语句。Open ./Controllers/CalendarController.cs and add the following using statement at the top of the file.

    using GraphTutorial.Models;
    
  4. 将以下函数添加到 CalendarController 类。Add the following function to the CalendarController class.

    [HttpPost]
    public async Task<string> Post(NewEvent newEvent)
    {
        HttpContext.VerifyUserHasAnyAcceptedScope(apiScopes);
    
        try
        {
            // Get the user's mailbox settings
            var me = await _graphClient.Me
                .Request()
                .Select(u => new {
                    u.MailboxSettings
                })
                .GetAsync();
    
            // Create a Graph Event
            var graphEvent = new Event
            {
                Subject = newEvent.Subject,
                Start = new DateTimeTimeZone
                {
                    DateTime = newEvent.Start,
                    TimeZone = me.MailboxSettings.TimeZone
                },
                End = new DateTimeTimeZone
                {
                    DateTime = newEvent.End,
                    TimeZone = me.MailboxSettings.TimeZone
                }
            };
    
            // If there are attendees, add them
            if (!string.IsNullOrEmpty(newEvent.Attendees))
            {
                var attendees = new List<Attendee>();
                var emailArray = newEvent.Attendees.Split(';');
                foreach (var email in emailArray)
                {
                    attendees.Add(new Attendee
                    {
                        Type = AttendeeType.Required,
                        EmailAddress = new EmailAddress
                        {
                            Address = email
                        }
                    });
                }
    
                graphEvent.Attendees = attendees;
            }
    
            // If there is a body, add it
            if (!string.IsNullOrEmpty(newEvent.Body))
            {
                graphEvent.Body = new ItemBody
                {
                    ContentType = BodyType.Text,
                    Content = newEvent.Body
                };
            }
    
            // Create the event
            await _graphClient.Me
                .Events
                .Request()
                .AddAsync(graphEvent);
    
            return "success";
        }
        catch (Exception ex)
        {
            await HandleGraphException(ex);
            return null;
        }
    }
    

    这允许对包含表单字段的 Web API 进行 HTTP POST。This allows an HTTP POST to the Web API with the fields of the form.

  5. 保存所有更改并重新启动应用程序。Save all of your changes and restart the application. 在 Microsoft Teams 中刷新应用,然后选择"创建 事件" 选项卡。填写表单,然后选择" 创建 "将事件添加到用户的日历。Refresh the app in Microsoft Teams, and select the Create event tab. Fill out the form and select Create to add an event to the user's calendar.

    "创建事件"选项卡的屏幕截图