19 | Swapping to the Development environment displays detailed information about the error that occurred.
20 |
21 |
22 | The Development environment shouldn't be enabled for deployed applications.
23 | It can result in displaying sensitive information from exceptions to end users.
24 | For local debugging, enable the Development environment by setting the ASPNETCORE_ENVIRONMENT environment variable to Development
25 | and restarting the app.
26 |
27 |
--------------------------------------------------------------------------------
/FlightScheduleManager/ClientApp/src/utilities/utils.js:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE in the project root for license information.
3 |
4 | import { Providers } from '@microsoft/mgt';
5 | import moment from 'moment';
6 |
7 | export class Utilities {
8 |
9 | static formatDate(date) {
10 | return moment(date).format('MMM D, h:mm A');
11 | }
12 |
13 | static async getTokenForAPI() {
14 | let scopes = ['api://805f28c8-4a55-462b-b065-004c78ece8b9/.default'];
15 |
16 | console.log(`Provider state: ${Providers.globalProvider.state}`);
17 |
18 | try
19 | {
20 | let token = await Providers.globalProvider.getAccessToken(...scopes);
21 |
22 | if (token === null) {
23 | token = await Providers.globalProvider.getAccessToken(...scopes);
24 | }
25 | console.log(`Token: ${token}`);
26 | return token;
27 | }
28 | catch (error)
29 | {
30 | console.log(`Token error: ${JSON.stringify(error)}`);
31 | }
32 | }
33 | }
--------------------------------------------------------------------------------
/FlightScheduleManager/Controllers/UsersController.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE in the project root for license information.
3 |
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Linq;
7 | using System.Threading.Tasks;
8 | using Microsoft.AspNetCore.Mvc;
9 | using FlightScheduleManager.Graph;
10 | using FlightScheduleManager.Models;
11 |
12 | namespace FlightScheduleManager.Controllers
13 | {
14 | [Route("api/[controller]")]
15 | public class UsersController : Controller
16 | {
17 | // GET /api/users
18 | public async Task> GetScheduleUser([FromHeader] string authorization)
19 | {
20 | var token = await GraphService.ValidateBearerToken(authorization);
21 | if (string.IsNullOrEmpty(token))
22 | {
23 | return new UnauthorizedResult();
24 | }
25 |
26 | return await GraphService.GetUserInfo(token);
27 | }
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/FlightScheduleManager/ClientApp/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "FlightScheduleManager",
3 | "version": "0.1.0",
4 | "private": true,
5 | "dependencies": {
6 | "@microsoft/mgt": "^1.0.0",
7 | "bootstrap": "^4.3.1",
8 | "jquery": "^3.5.0",
9 | "moment": "^2.24.0",
10 | "office-ui-fabric-react": "^6.166.1",
11 | "react": "^16.8.6",
12 | "react-dom": "^16.8.6",
13 | "react-router-bootstrap": "^0.24.4",
14 | "react-router-dom": "^4.3.1",
15 | "react-scripts": "^2.1.8",
16 | "reactstrap": "^6.5.0",
17 | "rimraf": "^2.6.3"
18 | },
19 | "devDependencies": {
20 | "ajv": "^6.10.0",
21 | "cross-env": "^5.2.0"
22 | },
23 | "eslintConfig": {
24 | "extends": "react-app"
25 | },
26 | "scripts": {
27 | "start": "rimraf ./build && react-scripts start",
28 | "build": "react-scripts build",
29 | "test": "cross-env CI=true react-scripts test --env=jsdom",
30 | "eject": "react-scripts eject",
31 | "lint": "eslint ./src/"
32 | },
33 | "browserslist": [
34 | ">0.2%",
35 | "not dead",
36 | "not ie <= 11",
37 | "not op_mini all"
38 | ]
39 | }
40 |
--------------------------------------------------------------------------------
/.vscode/tasks.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "2.0.0",
3 | "tasks": [
4 | {
5 | "label": "build",
6 | "command": "dotnet",
7 | "type": "process",
8 | "args": [
9 | "build",
10 | "${workspaceFolder}/FlightScheduleManager/FlightScheduleManager.csproj"
11 | ],
12 | "problemMatcher": "$tsc"
13 | },
14 | {
15 | "label": "publish",
16 | "command": "dotnet",
17 | "type": "process",
18 | "args": [
19 | "publish",
20 | "${workspaceFolder}/FlightScheduleManager/FlightScheduleManager.csproj"
21 | ],
22 | "problemMatcher": "$tsc"
23 | },
24 | {
25 | "label": "watch",
26 | "command": "dotnet",
27 | "type": "process",
28 | "args": [
29 | "watch",
30 | "run",
31 | "${workspaceFolder}/FlightScheduleManager/FlightScheduleManager.csproj"
32 | ],
33 | "problemMatcher": "$tsc"
34 | }
35 | ]
36 | }
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2019 Microsoft
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/FlightScheduleManager/ClientApp/src/App.js:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE in the project root for license information.
3 |
4 | import React, { Component } from 'react';
5 | import { Route } from 'react-router';
6 | import { Layout } from './components/Layout';
7 | import { Home } from './components/Home';
8 | import { Providers, MsalProvider } from '@microsoft/mgt';
9 | import { initializeIcons } from 'office-ui-fabric-react/lib/Icons';
10 |
11 | initializeIcons();
12 |
13 | export default class App extends Component {
14 | static displayName = App.name;
15 |
16 | constructor(props) {
17 | super(props);
18 |
19 | let config = {
20 | clientId: process.env.REACT_APP_AZURE_APP_ID,
21 | authority: process.env.REACT_APP_AZURE_AUTHORITY,
22 | scopes: [`api://${process.env.REACT_APP_AZURE_WEB_APP_ID}/.default`]
23 | };
24 |
25 | Providers.globalProvider = new MsalProvider(config);
26 | }
27 |
28 | render() {
29 | return (
30 |
31 |
32 |
33 | );
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/.vscode/launch.json:
--------------------------------------------------------------------------------
1 | {
2 | // Use IntelliSense to learn about possible attributes.
3 | // Hover to view descriptions of existing attributes.
4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
5 | "version": "0.2.0",
6 | "configurations": [
7 | {
8 | "name": ".NET Core Launch (web)",
9 | "type": "coreclr",
10 | "request": "launch",
11 | "preLaunchTask": "build",
12 | "program": "${workspaceFolder}/FlightScheduleManager/bin/Debug/netcoreapp2.2/FlightScheduleManager.dll",
13 | "args": [],
14 | "cwd": "${workspaceFolder}/FlightScheduleManager",
15 | "stopAtEntry": false,
16 | "launchBrowser": {
17 | "enabled": true
18 | },
19 | "console": "integratedTerminal",
20 | "env": {
21 | "ASPNETCORE_ENVIRONMENT": "Development"
22 | },
23 | "sourceFileMap": {
24 | "/Views": "${workspaceFolder}/FlightScheduleManager/Views"
25 | }
26 | },
27 | {
28 | "name": ".NET Core Attach",
29 | "type": "coreclr",
30 | "request": "attach",
31 | "processId": "${command:pickProcess}"
32 | }
33 | ]
34 | }
--------------------------------------------------------------------------------
/FlightScheduleManager/Models/Schedule.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE in the project root for license information.
3 |
4 | using Newtonsoft.Json;
5 | using Newtonsoft.Json.Serialization;
6 | using System;
7 | using System.Collections.Generic;
8 | using Microsoft.Graph;
9 |
10 | namespace FlightScheduleManager.Models
11 | {
12 | [JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))]
13 | public class Schedule
14 | {
15 | public string ScheduleId { get; set; }
16 | public List Availability { get; set; }
17 |
18 | public Schedule(ScheduleInformation scheduleInfo)
19 | {
20 | this.ScheduleId = scheduleInfo.ScheduleId;
21 | LoadAvailabilityMap(scheduleInfo.AvailabilityView);
22 | }
23 |
24 | private void LoadAvailabilityMap(string map)
25 | {
26 | var mapArray = map.ToCharArray();
27 | this.Availability = new List();
28 |
29 | foreach(var value in mapArray)
30 | {
31 | this.Availability.Add((FreeBusyStatus)int.Parse(value.ToString()));
32 | }
33 | }
34 | }
35 | }
--------------------------------------------------------------------------------
/FlightScheduleManager/ClientApp/src/components/FlightCrewMember.js:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE in the project root for license information.
3 |
4 | import React, { Component } from 'react';
5 | import { IconButton } from 'office-ui-fabric-react/lib/Button';
6 | import 'office-ui-fabric-react/dist/css/fabric.min.css';
7 | import './FlightCrewMember.css';
8 |
9 | function RemoveButtonIfNeeded(props) {
10 | if (props.buttonNeeded) {
11 | return (
12 |
13 | )
14 | }
15 |
16 | return null;
17 | }
18 |
19 | /*
20 | * This component renders a flight crew "slot" in the
21 | * flight editor. If the slot is empty, it renders a red box.
22 | */
23 |
24 | export class FlightCrewMember extends Component {
25 | render() {
26 | return (
27 |
150 | );
151 | }
152 | }
--------------------------------------------------------------------------------
/FlightScheduleManager/Graph/GraphService.cs:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved.
2 | // Licensed under the MIT license. See LICENSE in the project root for license information.
3 |
4 | using FlightScheduleManager.Models;
5 | using Microsoft.Extensions.Configuration;
6 | using Microsoft.Extensions.Configuration.FileExtensions;
7 | using Microsoft.Extensions.Configuration.Json;
8 | using Microsoft.Identity.Client;
9 | using Microsoft.Graph;
10 | using Microsoft.Graph.Auth;
11 | using System;
12 | using System.Collections.Generic;
13 | using System.Linq;
14 | using System.Net.Http.Headers;
15 | using System.Threading.Tasks;
16 |
17 | namespace FlightScheduleManager.Graph
18 | {
19 | public static class GraphService
20 | {
21 | private static GraphServiceClient userClient;
22 | private static GraphServiceClient appClient;
23 | private static string flightAdminSite;
24 | private static string flightList;
25 | private static Dictionary userLookupIds;
26 |
27 | static GraphService()
28 | {
29 | var graphConfig = LoadAppSettings();
30 | var oboSettings = graphConfig.GetSection("onBehalfClientSettings");
31 |
32 | var scopes = oboSettings["scopes"];
33 | var scopesArray = scopes.Split(',');
34 |
35 | // Initialize the Graph client to make calls on behalf of the user
36 | var userClientCreds = new ClientCredential(oboSettings["appSecret"]);
37 | var oboMsalClient = OnBehalfOfProvider.CreateClientApplication(
38 | oboSettings["appId"],
39 | oboSettings["redirect"],
40 | userClientCreds, null,
41 | graphConfig["tenantId"]);
42 |
43 | var oboAuthProvider = new OnBehalfOfProvider(oboMsalClient, scopesArray);
44 |
45 | userClient = new GraphServiceClient(oboAuthProvider);
46 |
47 | var appOnlySettings = graphConfig.GetSection("appOnlyClientSettings");
48 |
49 | // Initialize the Graph client to make app-only calls
50 | var appClientCreds = new ClientCredential(appOnlySettings["appSecret"]);
51 | var appMsalClient = ClientCredentialProvider.CreateClientApplication(
52 | appOnlySettings["appId"], appClientCreds, null, graphConfig["tenantId"]);
53 | var appAuthProvider = new ClientCredentialProvider(appMsalClient);
54 |
55 | appClient = new GraphServiceClient(appAuthProvider);
56 |
57 | flightAdminSite = graphConfig["flightAdminSite"];
58 | flightList = graphConfig["flightList"];
59 | }
60 |
61 | private static IConfigurationRoot LoadAppSettings()
62 | {
63 | try
64 | {
65 | var config = new ConfigurationBuilder()
66 | .SetBasePath(System.IO.Directory.GetCurrentDirectory())
67 | .AddJsonFile("graphsettings.json", false, true)
68 | .Build();
69 |
70 | return config;
71 | }
72 | catch (System.IO.FileNotFoundException)
73 | {
74 | return null;
75 | }
76 | }
77 |
78 | public static async Task ValidateBearerToken(string authorization)
79 | {
80 | try
81 | {
82 | // Make sure that the Authorization header is in the correct format
83 | var authHeader = AuthenticationHeaderValue.Parse(authorization);
84 |
85 | // Make sure it uses the Bearer scheme
86 | if (authHeader.Scheme.ToLower() != "bearer")
87 | {
88 | return null;
89 | }
90 |
91 | // Simple test, can we get user's profile with this token?
92 | var user = await userClient.Me.Request()
93 | .WithUserAssertion(new UserAssertion(authHeader.Parameter))
94 | .GetAsync();
95 |
96 | return user == null ? null : authHeader.Parameter;
97 | }
98 | // Return null, causing controllers to return 401
99 | catch (FormatException) { return null; }
100 | catch (ArgumentNullException) { return null; }
101 | catch (ServiceException) { return null; }
102 | }
103 |
104 | public static async Task GetUserInfo(string userToken)
105 | {
106 | var scheduleUser = new ScheduleUser{ EmailAddress = "", IsFlightAdmin = false, IsFlightAttendant = false };
107 | try
108 | {
109 | // Get the user
110 | var user = await userClient.Me.Request()
111 | .WithUserAssertion(new UserAssertion(userToken))
112 | .GetAsync();
113 |
114 | scheduleUser.EmailAddress = user.Mail.ToLower();
115 |
116 | // Reading a user's groups requires admin permissions, so
117 | // use the app-only client here
118 | var groups = await appClient.Users[user.Id].MemberOf.Request().GetAsync();
119 | foreach (var obj in groups.CurrentPage)
120 | {
121 | if (obj.ODataType == "#microsoft.graph.group")
122 | {
123 | var group = obj as Group;
124 | if (group.DisplayName == "Flight Admins")
125 | {
126 | scheduleUser.IsFlightAdmin = true;
127 | }
128 |
129 | if (group.DisplayName == "Flight Attendants")
130 | {
131 | scheduleUser.IsFlightAttendant = true;
132 | }
133 |
134 | if (scheduleUser.IsFlightAdmin && scheduleUser.IsFlightAttendant)
135 | {
136 | break;
137 | }
138 | }
139 | }
140 | }
141 | catch(Exception ex)
142 | {
143 | Console.WriteLine($"GetUserInfo - Exception: {ex.ToString()}");
144 | }
145 |
146 | return scheduleUser;
147 | }
148 |
149 | public static async Task> GetAllFlightsFromList()
150 | {
151 | var flights = new List();
152 |
153 | try
154 | {
155 | // Get the items from the SharePoint list
156 | var items = await GetFlightListItems();
157 |
158 | // Parse the items into flights
159 | foreach (var item in items.CurrentPage)
160 | {
161 | flights.Add(Flight.FromListItem(item));
162 | }
163 | }
164 | catch (Exception ex)
165 | {
166 | Console.WriteLine($"GetAllFlightsFromList - Exception: {ex.ToString()}");
167 | }
168 |
169 | // SharePoint lists do not support OrderBy via Graph, so sort
170 | // results here
171 | var sortedFlights = flights.OrderBy(f => f.DepartureTime).ToList();
172 | return sortedFlights;
173 | }
174 |
175 | public static async Task> GetOpenFlightsFromList(string userEmail)
176 | {
177 | var flights = new List();
178 |
179 | try
180 | {
181 | // Get the items from the SharePoint list
182 | var items = await GetFlightListItems();
183 |
184 | foreach (var item in items.CurrentPage)
185 | {
186 | // Parse the item into a flight
187 | var flight = Flight.FromListItem(item);
188 |
189 | // Remove full flights and any flights that the user is already
190 | // assigned to
191 | if (flight.FlightCrew.Count < 3 && !flight.FlightCrew.Contains(userEmail))
192 | {
193 | flights.Add(flight);
194 | }
195 | }
196 | }
197 | catch (Exception ex)
198 | {
199 | Console.WriteLine($"GetOpenFlightsFromList - Exception: {ex.ToString()}");
200 | }
201 |
202 | // SharePoint lists do not support OrderBy via Graph, so sort
203 | // results here
204 | var sortedFlights = flights.OrderBy(f => f.DepartureTime).ToList();
205 | return sortedFlights;
206 | }
207 |
208 | public static async Task> GetAssignedFlights(string userToken)
209 | {
210 | var flights = new List();
211 |
212 | try
213 | {
214 | // Get the Flight Attendants group members
215 | var flightAttendants = await GetGroupMembers("Flight Attendants");
216 |
217 | var today = DateTime.UtcNow.Date;
218 |
219 | // Get the flight events from the user's calendar
220 | var flightEvents = await userClient.Me.Events.Request()
221 | .WithUserAssertion(new UserAssertion(userToken))
222 | .Filter($"start/dateTime ge '{today.ToString("yyyy-MM-ddTHH:mm:ss")}' and categories/any(c:c eq 'Assigned Flight')")
223 | .OrderBy("start/dateTime ASC")
224 | .Expand("extensions($filter=id eq 'com.contoso.flightData')")
225 | .Top(50)
226 | .GetAsync();
227 |
228 | // Parse the events into flights
229 | foreach (var flightEvent in flightEvents.CurrentPage)
230 | {
231 | flights.Add(Flight.FromEvent(flightEvent, flightAttendants.CurrentPage));
232 | }
233 | }
234 | catch (Exception ex)
235 | {
236 | Console.WriteLine($"GetAssignedFlights - Exception: {ex.ToString()}");
237 | }
238 |
239 | return flights;
240 | }
241 |
242 | public static async Task UpdateFlight(Flight updatedFlight)
243 | {
244 | if (updatedFlight.IdType == FlightIdType.SharePointList)
245 | {
246 | await UpdateFlightInSharePoint(updatedFlight);
247 | }
248 | }
249 |
250 | public static async Task UpdateFlightInSharePoint(Flight updatedFlight)
251 | {
252 | var crewLookupIds = new List();
253 |
254 | // Updating Person fields in SharePoint require a lookup ID,
255 | // which is unique to each site.
256 | foreach (var email in updatedFlight.FlightCrew)
257 | {
258 | var lookup = await GetUserLookupId(email);
259 | if (!string.IsNullOrEmpty(lookup))
260 | {
261 | crewLookupIds.Add(lookup);
262 | }
263 | }
264 |
265 | // Format the field as a lookup field
266 | var flightAttendantField = new FieldValueSet
267 | {
268 | AdditionalData = new Dictionary
269 | {
270 | { "FlightAttendantsLookupId@odata.type", "Collection(Edm.String)" },
271 | { "FlightAttendantsLookupId", crewLookupIds }
272 | }
273 | };
274 |
275 | var spIds = updatedFlight.Id.Split('/');
276 |
277 | await appClient.Drives[spIds[0]].Items[spIds[1]].ListItem.Fields.Request().UpdateAsync(flightAttendantField);
278 | }
279 |
280 | public static async Task GetCalendarView(string userToken, string start, string end)
281 | {
282 | try
283 | {
284 | // Use QueryOption to pass "custom" query parameters
285 | // ?startDateTime=2019-04-22T08:00:00&endDateTime=2019-04-29T08:00:00
286 | var queryOptions = new List {
287 | new QueryOption("startDateTime", start),
288 | new QueryOption("endDatetime", end)
289 | };
290 |
291 | return await userClient.Me.CalendarView
292 | .Request(queryOptions)
293 | .WithUserAssertion(new UserAssertion(userToken))
294 | .Select("subject,start,end,categories")
295 | .Top(25).GetAsync();
296 | }
297 | catch (Exception ex)
298 | {
299 | Console.WriteLine($"GetCalendarView - Exception: {ex.ToString()}");
300 | return null;
301 | }
302 | }
303 |
304 | public static async Task GetSchedules(string userToken, string start, string end)
305 | {
306 | try
307 | {
308 | // Set the start and end times of the availability window
309 | var startTime = new DateTimeTimeZone { DateTime = start, TimeZone = "UTC" };
310 | var endTime = new DateTimeTimeZone { DateTime = end, TimeZone = "UTC" };
311 |
312 | // Get all flight attendants
313 | var flightAttendants = await GetGroupMembers("Flight Attendants");
314 |
315 | // Build a list of flight attendant emails
316 | var flightAttendantEmails = new List();
317 |
318 | foreach (var flightAttendant in flightAttendants)
319 | {
320 | flightAttendantEmails.Add((flightAttendant as User).Mail);
321 | }
322 |
323 | // Call getSchedule API to get availability map
324 | return await userClient.Me.Calendar
325 | .GetSchedule(flightAttendantEmails, endTime, startTime)
326 | .Request()
327 | .WithUserAssertion(new UserAssertion(userToken))
328 | .PostAsync();
329 | }
330 | catch (Exception ex)
331 | {
332 | Console.WriteLine($"GetSchedules - Exception: {ex.ToString()}");
333 | return null;
334 | }
335 |
336 | }
337 |
338 | private static async Task GetFlightListItems()
339 | {
340 | // Get the root site
341 | var rootSite = await appClient.Sites["root"].Request().GetAsync();
342 |
343 | // Get the flight admin site
344 | var adminSite = await appClient
345 | .Sites[$"{rootSite.SiteCollection.Hostname}:/sites/{flightAdminSite}"]
346 | .Request().GetAsync();
347 |
348 | // Get the flight list
349 | var lists = await appClient.Sites[adminSite.Id]
350 | .Lists.Request().Top(50).GetAsync();
351 |
352 | foreach(var list in lists.CurrentPage)
353 | {
354 | if (list.Name == flightList)
355 | {
356 | // Get items from the list
357 | return await appClient.Sites[adminSite.Id].Lists[list.Id]
358 | .Items.Request()
359 | // Filter on Departure Time field, only get items with a departure
360 | // later than today
361 | .Filter($"fields/DepartureTime ge '{DateTime.UtcNow.Date.ToString("yyyy-MM-ddTHH:mm:ss")}'")
362 | // Expand the fields (where all custom fields are returned) and
363 | // the driveItem (to make it easier to update this item if needed) properties
364 | .Expand("driveItem,fields")
365 | .GetAsync();
366 | }
367 | }
368 |
369 | Console.WriteLine($"GetFlightListItems - Could not find list named {flightList}");
370 | return null;
371 | }
372 |
373 | private static async Task GetGroupMembers(string groupName)
374 | {
375 | var group = await appClient.Groups.Request()
376 | .Filter($"displayName eq '{groupName}'").GetAsync();
377 |
378 | if (group == null || group.CurrentPage.Count <= 0)
379 | {
380 | Console.WriteLine($"GetGroupMembers - No group named {groupName} found.");
381 | return null;
382 | }
383 |
384 | return await appClient.Groups[group.CurrentPage[0].Id]
385 | .Members.Request().GetAsync();
386 | }
387 |
388 | private static async Task GetUserLookupId(string userEmail)
389 | {
390 | if (userLookupIds == null)
391 | {
392 | await BuildUserLookupDictionary();
393 | }
394 |
395 | return userLookupIds[userEmail];
396 | }
397 |
398 | private static async Task BuildUserLookupDictionary()
399 | {
400 | try
401 | {
402 | userLookupIds = new Dictionary();
403 |
404 | // Get the root site
405 | var rootSite = await appClient.Sites["root"].Request().GetAsync();
406 |
407 | // Get the flight admin site
408 | var adminSite = await appClient
409 | .Sites[$"{rootSite.SiteCollection.Hostname}:/sites/{flightAdminSite}"]
410 | .Request().GetAsync();
411 |
412 | // Get all lists including the "system" lists
413 | // This is needed to see the User Information List
414 | var lists = await appClient.Sites[adminSite.Id].Lists.Request()
415 | .Select(x => new { x.System, x.DisplayName, x.Id }).GetAsync();
416 |
417 | // Find the User Information List
418 | Microsoft.Graph.List userList = null;
419 | foreach(var list in lists.CurrentPage)
420 | {
421 | if (string.Compare(list.DisplayName, "User Information List", true) == 0)
422 | {
423 | userList = list;
424 | break;
425 | }
426 | }
427 |
428 | if (userList == null)
429 | {
430 | return;
431 | }
432 |
433 | var users = await appClient.Sites[adminSite.Id].Lists[userList.Id].Items.Request()
434 | .Expand(x => new { x.Fields }).GetAsync();
435 |
436 | foreach (var user in users)
437 | {
438 | object email = null;
439 | if (user.Fields.AdditionalData.TryGetValue("EMail", out email))
440 | {
441 | if (!userLookupIds.TryAdd((email as string).ToLower(), user.Id))
442 | {
443 | Console.WriteLine($"Duplicate entry for {email}, ignored.");
444 | }
445 | }
446 | }
447 | }
448 | catch (Exception ex)
449 | {
450 | Console.WriteLine(ex.Message);
451 | userLookupIds = null;
452 | }
453 | }
454 | }
455 | }
456 |
--------------------------------------------------------------------------------
/FlightScheduleManager/ClientApp/README.md:
--------------------------------------------------------------------------------
1 | This project was bootstrapped with [Create React App](https://github.com/facebookincubator/create-react-app).
2 |
3 | Below you will find some information on how to perform common tasks.
4 | You can find the most recent version of this guide [here](https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md).
5 |
6 | ## Table of Contents
7 |
8 | - [Updating to New Releases](#updating-to-new-releases)
9 | - [Sending Feedback](#sending-feedback)
10 | - [Folder Structure](#folder-structure)
11 | - [Available Scripts](#available-scripts)
12 | - [npm start](#npm-start)
13 | - [npm test](#npm-test)
14 | - [npm run build](#npm-run-build)
15 | - [npm run eject](#npm-run-eject)
16 | - [Supported Language Features and Polyfills](#supported-language-features-and-polyfills)
17 | - [Syntax Highlighting in the Editor](#syntax-highlighting-in-the-editor)
18 | - [Displaying Lint Output in the Editor](#displaying-lint-output-in-the-editor)
19 | - [Debugging in the Editor](#debugging-in-the-editor)
20 | - [Formatting Code Automatically](#formatting-code-automatically)
21 | - [Changing the Page ``](#changing-the-page-title)
22 | - [Installing a Dependency](#installing-a-dependency)
23 | - [Importing a Component](#importing-a-component)
24 | - [Code Splitting](#code-splitting)
25 | - [Adding a Stylesheet](#adding-a-stylesheet)
26 | - [Post-Processing CSS](#post-processing-css)
27 | - [Adding a CSS Preprocessor (Sass, Less etc.)](#adding-a-css-preprocessor-sass-less-etc)
28 | - [Adding Images, Fonts, and Files](#adding-images-fonts-and-files)
29 | - [Using the `public` Folder](#using-the-public-folder)
30 | - [Changing the HTML](#changing-the-html)
31 | - [Adding Assets Outside of the Module System](#adding-assets-outside-of-the-module-system)
32 | - [When to Use the `public` Folder](#when-to-use-the-public-folder)
33 | - [Using Global Variables](#using-global-variables)
34 | - [Adding Bootstrap](#adding-bootstrap)
35 | - [Using a Custom Theme](#using-a-custom-theme)
36 | - [Adding Flow](#adding-flow)
37 | - [Adding Custom Environment Variables](#adding-custom-environment-variables)
38 | - [Referencing Environment Variables in the HTML](#referencing-environment-variables-in-the-html)
39 | - [Adding Temporary Environment Variables In Your Shell](#adding-temporary-environment-variables-in-your-shell)
40 | - [Adding Development Environment Variables In `.env`](#adding-development-environment-variables-in-env)
41 | - [Can I Use Decorators?](#can-i-use-decorators)
42 | - [Integrating with an API Backend](#integrating-with-an-api-backend)
43 | - [Node](#node)
44 | - [Ruby on Rails](#ruby-on-rails)
45 | - [Proxying API Requests in Development](#proxying-api-requests-in-development)
46 | - ["Invalid Host Header" Errors After Configuring Proxy](#invalid-host-header-errors-after-configuring-proxy)
47 | - [Configuring the Proxy Manually](#configuring-the-proxy-manually)
48 | - [Configuring a WebSocket Proxy](#configuring-a-websocket-proxy)
49 | - [Using HTTPS in Development](#using-https-in-development)
50 | - [Generating Dynamic `` Tags on the Server](#generating-dynamic-meta-tags-on-the-server)
51 | - [Pre-Rendering into Static HTML Files](#pre-rendering-into-static-html-files)
52 | - [Injecting Data from the Server into the Page](#injecting-data-from-the-server-into-the-page)
53 | - [Running Tests](#running-tests)
54 | - [Filename Conventions](#filename-conventions)
55 | - [Command Line Interface](#command-line-interface)
56 | - [Version Control Integration](#version-control-integration)
57 | - [Writing Tests](#writing-tests)
58 | - [Testing Components](#testing-components)
59 | - [Using Third Party Assertion Libraries](#using-third-party-assertion-libraries)
60 | - [Initializing Test Environment](#initializing-test-environment)
61 | - [Focusing and Excluding Tests](#focusing-and-excluding-tests)
62 | - [Coverage Reporting](#coverage-reporting)
63 | - [Continuous Integration](#continuous-integration)
64 | - [Disabling jsdom](#disabling-jsdom)
65 | - [Snapshot Testing](#snapshot-testing)
66 | - [Editor Integration](#editor-integration)
67 | - [Developing Components in Isolation](#developing-components-in-isolation)
68 | - [Getting Started with Storybook](#getting-started-with-storybook)
69 | - [Getting Started with Styleguidist](#getting-started-with-styleguidist)
70 | - [Making a Progressive Web App](#making-a-progressive-web-app)
71 | - [Opting Out of Caching](#opting-out-of-caching)
72 | - [Offline-First Considerations](#offline-first-considerations)
73 | - [Progressive Web App Metadata](#progressive-web-app-metadata)
74 | - [Analyzing the Bundle Size](#analyzing-the-bundle-size)
75 | - [Deployment](#deployment)
76 | - [Static Server](#static-server)
77 | - [Other Solutions](#other-solutions)
78 | - [Serving Apps with Client-Side Routing](#serving-apps-with-client-side-routing)
79 | - [Building for Relative Paths](#building-for-relative-paths)
80 | - [Azure](#azure)
81 | - [Firebase](#firebase)
82 | - [GitHub Pages](#github-pages)
83 | - [Heroku](#heroku)
84 | - [Netlify](#netlify)
85 | - [Now](#now)
86 | - [S3 and CloudFront](#s3-and-cloudfront)
87 | - [Surge](#surge)
88 | - [Advanced Configuration](#advanced-configuration)
89 | - [Troubleshooting](#troubleshooting)
90 | - [`npm start` doesn’t detect changes](#npm-start-doesnt-detect-changes)
91 | - [`npm test` hangs on macOS Sierra](#npm-test-hangs-on-macos-sierra)
92 | - [`npm run build` exits too early](#npm-run-build-exits-too-early)
93 | - [`npm run build` fails on Heroku](#npm-run-build-fails-on-heroku)
94 | - [`npm run build` fails to minify](#npm-run-build-fails-to-minify)
95 | - [Moment.js locales are missing](#momentjs-locales-are-missing)
96 | - [Something Missing?](#something-missing)
97 |
98 | ## Updating to New Releases
99 |
100 | Create React App is divided into two packages:
101 |
102 | * `create-react-app` is a global command-line utility that you use to create new projects.
103 | * `react-scripts` is a development dependency in the generated projects (including this one).
104 |
105 | You almost never need to update `create-react-app` itself: it delegates all the setup to `react-scripts`.
106 |
107 | When you run `create-react-app`, it always creates the project with the latest version of `react-scripts` so you’ll get all the new features and improvements in newly created apps automatically.
108 |
109 | To update an existing project to a new version of `react-scripts`, [open the changelog](https://github.com/facebookincubator/create-react-app/blob/master/CHANGELOG.md), find the version you’re currently on (check `package.json` in this folder if you’re not sure), and apply the migration instructions for the newer versions.
110 |
111 | In most cases bumping the `react-scripts` version in `package.json` and running `npm install` in this folder should be enough, but it’s good to consult the [changelog](https://github.com/facebookincubator/create-react-app/blob/master/CHANGELOG.md) for potential breaking changes.
112 |
113 | We commit to keeping the breaking changes minimal so you can upgrade `react-scripts` painlessly.
114 |
115 | ## Sending Feedback
116 |
117 | We are always open to [your feedback](https://github.com/facebookincubator/create-react-app/issues).
118 |
119 | ## Folder Structure
120 |
121 | After creation, your project should look like this:
122 |
123 | ```
124 | my-app/
125 | README.md
126 | node_modules/
127 | package.json
128 | public/
129 | index.html
130 | favicon.ico
131 | src/
132 | App.css
133 | App.js
134 | App.test.js
135 | index.css
136 | index.js
137 | logo.svg
138 | ```
139 |
140 | For the project to build, **these files must exist with exact filenames**:
141 |
142 | * `public/index.html` is the page template;
143 | * `src/index.js` is the JavaScript entry point.
144 |
145 | You can delete or rename the other files.
146 |
147 | You may create subdirectories inside `src`. For faster rebuilds, only files inside `src` are processed by Webpack.
148 | You need to **put any JS and CSS files inside `src`**, otherwise Webpack won’t see them.
149 |
150 | Only files inside `public` can be used from `public/index.html`.
151 | Read instructions below for using assets from JavaScript and HTML.
152 |
153 | You can, however, create more top-level directories.
154 | They will not be included in the production build so you can use them for things like documentation.
155 |
156 | ## Available Scripts
157 |
158 | In the project directory, you can run:
159 |
160 | ### `npm start`
161 |
162 | Runs the app in the development mode.
163 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
164 |
165 | The page will reload if you make edits.
166 | You will also see any lint errors in the console.
167 |
168 | ### `npm test`
169 |
170 | Launches the test runner in the interactive watch mode.
171 | See the section about [running tests](#running-tests) for more information.
172 |
173 | ### `npm run build`
174 |
175 | Builds the app for production to the `build` folder.
176 | It correctly bundles React in production mode and optimizes the build for the best performance.
177 |
178 | The build is minified and the filenames include the hashes.
179 | Your app is ready to be deployed!
180 |
181 | See the section about [deployment](#deployment) for more information.
182 |
183 | ### `npm run eject`
184 |
185 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!**
186 |
187 | If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
188 |
189 | Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
190 |
191 | You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
192 |
193 | ## Supported Language Features and Polyfills
194 |
195 | This project supports a superset of the latest JavaScript standard.
196 | In addition to [ES6](https://github.com/lukehoban/es6features) syntax features, it also supports:
197 |
198 | * [Exponentiation Operator](https://github.com/rwaldron/exponentiation-operator) (ES2016).
199 | * [Async/await](https://github.com/tc39/ecmascript-asyncawait) (ES2017).
200 | * [Object Rest/Spread Properties](https://github.com/sebmarkbage/ecmascript-rest-spread) (stage 3 proposal).
201 | * [Dynamic import()](https://github.com/tc39/proposal-dynamic-import) (stage 3 proposal)
202 | * [Class Fields and Static Properties](https://github.com/tc39/proposal-class-public-fields) (part of stage 3 proposal).
203 | * [JSX](https://facebook.github.io/react/docs/introducing-jsx.html) and [Flow](https://flowtype.org/) syntax.
204 |
205 | Learn more about [different proposal stages](https://babeljs.io/docs/plugins/#presets-stage-x-experimental-presets-).
206 |
207 | While we recommend using experimental proposals with some caution, Facebook heavily uses these features in the product code, so we intend to provide [codemods](https://medium.com/@cpojer/effective-javascript-codemods-5a6686bb46fb) if any of these proposals change in the future.
208 |
209 | Note that **the project only includes a few ES6 [polyfills](https://en.wikipedia.org/wiki/Polyfill)**:
210 |
211 | * [`Object.assign()`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) via [`object-assign`](https://github.com/sindresorhus/object-assign).
212 | * [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) via [`promise`](https://github.com/then/promise).
213 | * [`fetch()`](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) via [`whatwg-fetch`](https://github.com/github/fetch).
214 |
215 | If you use any other ES6+ features that need **runtime support** (such as `Array.from()` or `Symbol`), make sure you are including the appropriate polyfills manually, or that the browsers you are targeting already support them.
216 |
217 | ## Syntax Highlighting in the Editor
218 |
219 | To configure the syntax highlighting in your favorite text editor, head to the [relevant Babel documentation page](https://babeljs.io/docs/editors) and follow the instructions. Some of the most popular editors are covered.
220 |
221 | ## Displaying Lint Output in the Editor
222 |
223 | >Note: this feature is available with `react-scripts@0.2.0` and higher.
224 | >It also only works with npm 3 or higher.
225 |
226 | Some editors, including Sublime Text, Atom, and Visual Studio Code, provide plugins for ESLint.
227 |
228 | They are not required for linting. You should see the linter output right in your terminal as well as the browser console. However, if you prefer the lint results to appear right in your editor, there are some extra steps you can do.
229 |
230 | You would need to install an ESLint plugin for your editor first. Then, add a file called `.eslintrc` to the project root:
231 |
232 | ```js
233 | {
234 | "extends": "react-app"
235 | }
236 | ```
237 |
238 | Now your editor should report the linting warnings.
239 |
240 | Note that even if you edit your `.eslintrc` file further, these changes will **only affect the editor integration**. They won’t affect the terminal and in-browser lint output. This is because Create React App intentionally provides a minimal set of rules that find common mistakes.
241 |
242 | If you want to enforce a coding style for your project, consider using [Prettier](https://github.com/jlongster/prettier) instead of ESLint style rules.
243 |
244 | ## Debugging in the Editor
245 |
246 | **This feature is currently only supported by [Visual Studio Code](https://code.visualstudio.com) and [WebStorm](https://www.jetbrains.com/webstorm/).**
247 |
248 | Visual Studio Code and WebStorm support debugging out of the box with Create React App. This enables you as a developer to write and debug your React code without leaving the editor, and most importantly it enables you to have a continuous development workflow, where context switching is minimal, as you don’t have to switch between tools.
249 |
250 | ### Visual Studio Code
251 |
252 | You would need to have the latest version of [VS Code](https://code.visualstudio.com) and VS Code [Chrome Debugger Extension](https://marketplace.visualstudio.com/items?itemName=msjsdiag.debugger-for-chrome) installed.
253 |
254 | Then add the block below to your `launch.json` file and put it inside the `.vscode` folder in your app’s root directory.
255 |
256 | ```json
257 | {
258 | "version": "0.2.0",
259 | "configurations": [{
260 | "name": "Chrome",
261 | "type": "chrome",
262 | "request": "launch",
263 | "url": "http://localhost:3000",
264 | "webRoot": "${workspaceRoot}/src",
265 | "sourceMapPathOverrides": {
266 | "webpack:///src/*": "${webRoot}/*"
267 | }
268 | }]
269 | }
270 | ```
271 | >Note: the URL may be different if you've made adjustments via the [HOST or PORT environment variables](#advanced-configuration).
272 |
273 | Start your app by running `npm start`, and start debugging in VS Code by pressing `F5` or by clicking the green debug icon. You can now write code, set breakpoints, make changes to the code, and debug your newly modified code—all from your editor.
274 |
275 | Having problems with VS Code Debugging? Please see their [troubleshooting guide](https://github.com/Microsoft/vscode-chrome-debug/blob/master/README.md#troubleshooting).
276 |
277 | ### WebStorm
278 |
279 | You would need to have [WebStorm](https://www.jetbrains.com/webstorm/) and [JetBrains IDE Support](https://chrome.google.com/webstore/detail/jetbrains-ide-support/hmhgeddbohgjknpmjagkdomcpobmllji) Chrome extension installed.
280 |
281 | In the WebStorm menu `Run` select `Edit Configurations...`. Then click `+` and select `JavaScript Debug`. Paste `http://localhost:3000` into the URL field and save the configuration.
282 |
283 | >Note: the URL may be different if you've made adjustments via the [HOST or PORT environment variables](#advanced-configuration).
284 |
285 | Start your app by running `npm start`, then press `^D` on macOS or `F9` on Windows and Linux or click the green debug icon to start debugging in WebStorm.
286 |
287 | The same way you can debug your application in IntelliJ IDEA Ultimate, PhpStorm, PyCharm Pro, and RubyMine.
288 |
289 | ## Formatting Code Automatically
290 |
291 | Prettier is an opinionated code formatter with support for JavaScript, CSS and JSON. With Prettier you can format the code you write automatically to ensure a code style within your project. See the [Prettier's GitHub page](https://github.com/prettier/prettier) for more information, and look at this [page to see it in action](https://prettier.github.io/prettier/).
292 |
293 | To format our code whenever we make a commit in git, we need to install the following dependencies:
294 |
295 | ```sh
296 | npm install --save husky lint-staged prettier
297 | ```
298 |
299 | Alternatively you may use `yarn`:
300 |
301 | ```sh
302 | yarn add husky lint-staged prettier
303 | ```
304 |
305 | * `husky` makes it easy to use githooks as if they are npm scripts.
306 | * `lint-staged` allows us to run scripts on staged files in git. See this [blog post about lint-staged to learn more about it](https://medium.com/@okonetchnikov/make-linting-great-again-f3890e1ad6b8).
307 | * `prettier` is the JavaScript formatter we will run before commits.
308 |
309 | Now we can make sure every file is formatted correctly by adding a few lines to the `package.json` in the project root.
310 |
311 | Add the following line to `scripts` section:
312 |
313 | ```diff
314 | "scripts": {
315 | + "precommit": "lint-staged",
316 | "start": "react-scripts start",
317 | "build": "react-scripts build",
318 | ```
319 |
320 | Next we add a 'lint-staged' field to the `package.json`, for example:
321 |
322 | ```diff
323 | "dependencies": {
324 | // ...
325 | },
326 | + "lint-staged": {
327 | + "src/**/*.{js,jsx,json,css}": [
328 | + "prettier --single-quote --write",
329 | + "git add"
330 | + ]
331 | + },
332 | "scripts": {
333 | ```
334 |
335 | Now, whenever you make a commit, Prettier will format the changed files automatically. You can also run `./node_modules/.bin/prettier --single-quote --write "src/**/*.{js,jsx}"` to format your entire project for the first time.
336 |
337 | Next you might want to integrate Prettier in your favorite editor. Read the section on [Editor Integration](https://github.com/prettier/prettier#editor-integration) on the Prettier GitHub page.
338 |
339 | ## Changing the Page ``
340 |
341 | You can find the source HTML file in the `public` folder of the generated project. You may edit the `` tag in it to change the title from “React App” to anything else.
342 |
343 | Note that normally you wouldn’t edit files in the `public` folder very often. For example, [adding a stylesheet](#adding-a-stylesheet) is done without touching the HTML.
344 |
345 | If you need to dynamically update the page title based on the content, you can use the browser [`document.title`](https://developer.mozilla.org/en-US/docs/Web/API/Document/title) API. For more complex scenarios when you want to change the title from React components, you can use [React Helmet](https://github.com/nfl/react-helmet), a third party library.
346 |
347 | If you use a custom server for your app in production and want to modify the title before it gets sent to the browser, you can follow advice in [this section](#generating-dynamic-meta-tags-on-the-server). Alternatively, you can pre-build each page as a static HTML file which then loads the JavaScript bundle, which is covered [here](#pre-rendering-into-static-html-files).
348 |
349 | ## Installing a Dependency
350 |
351 | The generated project includes React and ReactDOM as dependencies. It also includes a set of scripts used by Create React App as a development dependency. You may install other dependencies (for example, React Router) with `npm`:
352 |
353 | ```sh
354 | npm install --save react-router
355 | ```
356 |
357 | Alternatively you may use `yarn`:
358 |
359 | ```sh
360 | yarn add react-router
361 | ```
362 |
363 | This works for any library, not just `react-router`.
364 |
365 | ## Importing a Component
366 |
367 | This project setup supports ES6 modules thanks to Babel.
368 | While you can still use `require()` and `module.exports`, we encourage you to use [`import` and `export`](http://exploringjs.com/es6/ch_modules.html) instead.
369 |
370 | For example:
371 |
372 | ### `Button.js`
373 |
374 | ```js
375 | import React, { Component } from 'react';
376 |
377 | class Button extends Component {
378 | render() {
379 | // ...
380 | }
381 | }
382 |
383 | export default Button; // Don’t forget to use export default!
384 | ```
385 |
386 | ### `DangerButton.js`
387 |
388 |
389 | ```js
390 | import React, { Component } from 'react';
391 | import Button from './Button'; // Import a component from another file
392 |
393 | class DangerButton extends Component {
394 | render() {
395 | return ;
396 | }
397 | }
398 |
399 | export default DangerButton;
400 | ```
401 |
402 | Be aware of the [difference between default and named exports](http://stackoverflow.com/questions/36795819/react-native-es-6-when-should-i-use-curly-braces-for-import/36796281#36796281). It is a common source of mistakes.
403 |
404 | We suggest that you stick to using default imports and exports when a module only exports a single thing (for example, a component). That’s what you get when you use `export default Button` and `import Button from './Button'`.
405 |
406 | Named exports are useful for utility modules that export several functions. A module may have at most one default export and as many named exports as you like.
407 |
408 | Learn more about ES6 modules:
409 |
410 | * [When to use the curly braces?](http://stackoverflow.com/questions/36795819/react-native-es-6-when-should-i-use-curly-braces-for-import/36796281#36796281)
411 | * [Exploring ES6: Modules](http://exploringjs.com/es6/ch_modules.html)
412 | * [Understanding ES6: Modules](https://leanpub.com/understandinges6/read#leanpub-auto-encapsulating-code-with-modules)
413 |
414 | ## Code Splitting
415 |
416 | Instead of downloading the entire app before users can use it, code splitting allows you to split your code into small chunks which you can then load on demand.
417 |
418 | This project setup supports code splitting via [dynamic `import()`](http://2ality.com/2017/01/import-operator.html#loading-code-on-demand). Its [proposal](https://github.com/tc39/proposal-dynamic-import) is in stage 3. The `import()` function-like form takes the module name as an argument and returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) which always resolves to the namespace object of the module.
419 |
420 | Here is an example:
421 |
422 | ### `moduleA.js`
423 |
424 | ```js
425 | const moduleA = 'Hello';
426 |
427 | export { moduleA };
428 | ```
429 | ### `App.js`
430 |
431 | ```js
432 | import React, { Component } from 'react';
433 |
434 | class App extends Component {
435 | handleClick = () => {
436 | import('./moduleA')
437 | .then(({ moduleA }) => {
438 | // Use moduleA
439 | })
440 | .catch(err => {
441 | // Handle failure
442 | });
443 | };
444 |
445 | render() {
446 | return (
447 |
448 |
449 |
450 | );
451 | }
452 | }
453 |
454 | export default App;
455 | ```
456 |
457 | This will make `moduleA.js` and all its unique dependencies as a separate chunk that only loads after the user clicks the 'Load' button.
458 |
459 | You can also use it with `async` / `await` syntax if you prefer it.
460 |
461 | ### With React Router
462 |
463 | If you are using React Router check out [this tutorial](http://serverless-stack.com/chapters/code-splitting-in-create-react-app.html) on how to use code splitting with it. You can find the companion GitHub repository [here](https://github.com/AnomalyInnovations/serverless-stack-demo-client/tree/code-splitting-in-create-react-app).
464 |
465 | ## Adding a Stylesheet
466 |
467 | This project setup uses [Webpack](https://webpack.js.org/) for handling all assets. Webpack offers a custom way of “extending” the concept of `import` beyond JavaScript. To express that a JavaScript file depends on a CSS file, you need to **import the CSS from the JavaScript file**:
468 |
469 | ### `Button.css`
470 |
471 | ```css
472 | .Button {
473 | padding: 20px;
474 | }
475 | ```
476 |
477 | ### `Button.js`
478 |
479 | ```js
480 | import React, { Component } from 'react';
481 | import './Button.css'; // Tell Webpack that Button.js uses these styles
482 |
483 | class Button extends Component {
484 | render() {
485 | // You can use them as regular CSS styles
486 | return ;
487 | }
488 | }
489 | ```
490 |
491 | **This is not required for React** but many people find this feature convenient. You can read about the benefits of this approach [here](https://medium.com/seek-ui-engineering/block-element-modifying-your-javascript-components-d7f99fcab52b). However you should be aware that this makes your code less portable to other build tools and environments than Webpack.
492 |
493 | In development, expressing dependencies this way allows your styles to be reloaded on the fly as you edit them. In production, all CSS files will be concatenated into a single minified `.css` file in the build output.
494 |
495 | If you are concerned about using Webpack-specific semantics, you can put all your CSS right into `src/index.css`. It would still be imported from `src/index.js`, but you could always remove that import if you later migrate to a different build tool.
496 |
497 | ## Post-Processing CSS
498 |
499 | This project setup minifies your CSS and adds vendor prefixes to it automatically through [Autoprefixer](https://github.com/postcss/autoprefixer) so you don’t need to worry about it.
500 |
501 | For example, this:
502 |
503 | ```css
504 | .App {
505 | display: flex;
506 | flex-direction: row;
507 | align-items: center;
508 | }
509 | ```
510 |
511 | becomes this:
512 |
513 | ```css
514 | .App {
515 | display: -webkit-box;
516 | display: -ms-flexbox;
517 | display: flex;
518 | -webkit-box-orient: horizontal;
519 | -webkit-box-direction: normal;
520 | -ms-flex-direction: row;
521 | flex-direction: row;
522 | -webkit-box-align: center;
523 | -ms-flex-align: center;
524 | align-items: center;
525 | }
526 | ```
527 |
528 | If you need to disable autoprefixing for some reason, [follow this section](https://github.com/postcss/autoprefixer#disabling).
529 |
530 | ## Adding a CSS Preprocessor (Sass, Less etc.)
531 |
532 | Generally, we recommend that you don’t reuse the same CSS classes across different components. For example, instead of using a `.Button` CSS class in `` and `` components, we recommend creating a `