├── console-csharp-snippets-sample
├── App.config
├── packages.config
├── Constants.cs
├── Properties
│ └── AssemblyInfo.cs
├── Program.cs
├── console-csharp-snippets-sample.csproj
├── AuthenticationHelper.cs
├── AppMode.cs
└── UserMode.cs
├── console-csharp-snippets-sample.sln
├── LICENSE
├── README-localized
├── README-zh-cn.md
├── README-ja-jp.md
├── README-ru-ru.md
├── README-pt-br.md
├── README-es-es.md
└── README-fr-fr.md
├── .gitignore
├── README.md
└── CONTRIBUTING.md
/console-csharp-snippets-sample/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/console-csharp-snippets-sample/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/console-csharp-snippets-sample/Constants.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace console_csharp_snippets_sample
8 | {
9 | internal class Constants
10 | {
11 | public const string Tenant = "ENTER_YOUR_TENANT_NAME";
12 |
13 | // User consent flow
14 | public const string ClientIdForUserAuthn = "ENTER_YOUR_CLIENT_ID";
15 |
16 | // Admin consent flow
17 | public const string AuthorityUri = "https://login.microsoftonline.com/" + Tenant;
18 | public const string RedirectUriForAppAuthn = "https://login.microsoftonline.com";
19 | public const string ClientIdForAppAuthn = "ENTER_YOUR_APP_ONLY_CLIENT_ID";
20 | public const string ClientSecret = "ENTER_YOUR_CLIENT_SECRET";
21 | // Consent URI:
22 | // https://login.microsoftonline.com/{tenant name}/adminconsent?client_id={application id}&state=12345&redirect_uri=https://login.microsoftonline.com
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/console-csharp-snippets-sample.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 15
4 | VisualStudioVersion = 15.0.26430.4
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "console-csharp-snippets-sample", "console-csharp-snippets-sample\console-csharp-snippets-sample.csproj", "{6A3A724C-5985-494F-9FFE-2C1DD10E789F}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|Any CPU = Debug|Any CPU
11 | Release|Any CPU = Release|Any CPU
12 | EndGlobalSection
13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
14 | {6A3A724C-5985-494F-9FFE-2C1DD10E789F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15 | {6A3A724C-5985-494F-9FFE-2C1DD10E789F}.Debug|Any CPU.Build.0 = Debug|Any CPU
16 | {6A3A724C-5985-494F-9FFE-2C1DD10E789F}.Release|Any CPU.ActiveCfg = Release|Any CPU
17 | {6A3A724C-5985-494F-9FFE-2C1DD10E789F}.Release|Any CPU.Build.0 = Release|Any CPU
18 | EndGlobalSection
19 | GlobalSection(SolutionProperties) = preSolution
20 | HideSolutionNode = FALSE
21 | EndGlobalSection
22 | EndGlobal
23 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) Microsoft Corporation. All rights reserved.
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 |
--------------------------------------------------------------------------------
/console-csharp-snippets-sample/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("console-csharp-snippets-sample")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("console-csharp-snippets-sample")]
13 | [assembly: AssemblyCopyright("Copyright © 2017")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("6a3a724c-5985-494f-9ffe-2c1dd10e789f")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/console-csharp-snippets-sample/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Net;
5 | using System.Text;
6 | using System.Threading.Tasks;
7 |
8 | namespace console_csharp_snippets_sample
9 | {
10 | class Program
11 | {
12 | static void Main(string[] args)
13 | {
14 | // record start DateTime of execution
15 | string currentDateTime = DateTime.Now.ToUniversalTime().ToString();
16 |
17 | ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
18 |
19 | Console.WriteLine("Run operations for signed-in user, or in app-only mode.\n");
20 | Console.WriteLine("[a] - app-only\n[u] - as user\n[b] - both as user first, and then as app.\nPlease enter your choice:\n");
21 |
22 | ConsoleKeyInfo key = Console.ReadKey();
23 | switch (key.KeyChar)
24 | {
25 | case 'a':
26 | Console.WriteLine("\nRunning app-only mode.\n\n");
27 | AppMode.AppModeRequests();
28 | break;
29 | case 'u':
30 | Console.WriteLine("\nRunning in user mode.\n\n");
31 | UserMode.UserModeRequests();
32 | break;
33 | case 'b':
34 | Console.WriteLine("\nRunning user mode, followed by app-only mode.\n\n");
35 | UserMode.UserModeRequests();
36 | Console.WriteLine("\nFinished running user mode. Press any key to run app-only mode.\n\n");
37 | Console.ReadKey();
38 | AppMode.AppModeRequests();
39 | break;
40 | default:
41 | Console.WriteLine("\nSelection not recognized. Running in user mode.\n\n");
42 | UserMode.UserModeRequests();
43 | break;
44 | }
45 |
46 | //*********************************************************************************************
47 | // End of Demo Console App
48 | //*********************************************************************************************
49 |
50 | Console.WriteLine("\nCompleted at {0} \n Press Any Key to Exit.", currentDateTime);
51 | Console.ReadKey();
52 | }
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/console-csharp-snippets-sample/console-csharp-snippets-sample.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {6A3A724C-5985-494F-9FFE-2C1DD10E789F}
8 | Exe
9 | console_csharp_snippets_sample
10 | console-csharp-snippets-sample
11 | v4.5.2
12 | 512
13 | true
14 |
15 |
16 | AnyCPU
17 | true
18 | full
19 | false
20 | bin\Debug\
21 | DEBUG;TRACE
22 | prompt
23 | 4
24 |
25 |
26 | AnyCPU
27 | pdbonly
28 | true
29 | bin\Release\
30 | TRACE
31 | prompt
32 | 4
33 |
34 |
35 |
36 | ..\packages\Microsoft.Graph.1.7.0\lib\net45\Microsoft.Graph.dll
37 |
38 |
39 | ..\packages\Microsoft.Graph.Core.1.7.0\lib\net45\Microsoft.Graph.Core.dll
40 |
41 |
42 | ..\packages\Microsoft.Identity.Client.2.7.0\lib\net45\Microsoft.Identity.Client.dll
43 |
44 |
45 | ..\packages\Microsoft.OData.Client.6.11.0\lib\net40\Microsoft.OData.Client.dll
46 |
47 |
48 | ..\packages\Microsoft.OData.Core.6.11.0\lib\portable-net40+sl5+wp8+win8+wpa\Microsoft.OData.Core.dll
49 |
50 |
51 | ..\packages\Microsoft.OData.Edm.6.11.0\lib\portable-net40+sl5+wp8+win8+wpa\Microsoft.OData.Edm.dll
52 |
53 |
54 | ..\packages\Microsoft.OData.ProxyExtensions.1.0.35\lib\portable-net45+win+wpa81+wp80+MonoAndroid10+xamarinios10+MonoTouch10\Microsoft.OData.ProxyExtensions.dll
55 |
56 |
57 | ..\packages\Microsoft.Spatial.6.11.0\lib\portable-net40+sl5+wp8+win8+wpa\Microsoft.Spatial.dll
58 |
59 |
60 | ..\packages\Newtonsoft.Json.10.0.2\lib\net45\Newtonsoft.Json.dll
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 | Designer
85 |
86 |
87 | Designer
88 |
89 |
90 |
91 |
--------------------------------------------------------------------------------
/README-localized/README-zh-cn.md:
--------------------------------------------------------------------------------
1 | ---
2 | page_type: sample
3 | products:
4 | - ms-graph
5 | languages:
6 | - csharp
7 | description: "此 Windows 控制台应用演示如何使用具有委派权限和应用程序权限的 Microsoft Graph 客户端库执行各种操作。此示例使用 Microsoft 身份验证库 (MSAL) 在 Azure AD v2.0 终结点上进行身份验证。"
8 | extensions:
9 | contentType: samples
10 | technologies:
11 | - Microsoft Graph
12 | - Microsoft identity platform
13 | services:
14 | - Microsoft identity platform
15 | createdDate: 9/8/2017 1:33:44 PM
16 | ---
17 | # Microsoft Graph C# Console Snippets 应用程序
18 |
19 | ## 目录
20 |
21 | * [简介](#introduction)
22 | * [先决条件](#prerequisites)
23 | * [注册 **委派权限**应用程序](#Register-the-delegated-permissions-application )
24 | * [注册 **应用权限**应用程序](#Register-the-application-permissions-application )
25 | * [生成和运行示例](#build-and-run-the-sample)
26 | * [问题和意见](#questions-and-comments)
27 | * [参与](#contributing)
28 | * [其他资源](#additional-resources)
29 |
30 | ## 简介
31 |
32 | 此示例应用提供使用 Microsoft Graph 执行常见任务的代码段存储库,例如发送电子邮件、管理组和 Windows 控制台应用内的其他活动。它使用 [Microsoft Graph .NET Client SDK](https://github.com/microsoftgraph/msgraph-sdk-dotnet) 以结合使用由 Microsoft Graph 返回的数据。
33 |
34 | 此示例使用 Microsoft 身份验证库 (MSAL) 进行身份验证。此示例演示了委派权限和应用程序权限。
35 |
36 | **委派权限**供已有用户登录的应用使用。对于这些应用,用户或管理员同意应用请求的权限,并向应用委派调用 Microsoft Graph 时代表已登录用户的权限。某些委派权限可以由非管理用户同意,但一些较高特权权限需要管理员同意。此应用程序包含需要管理员许可的部分组相关操作,并默认备注执行操作的相关权限。
37 |
38 | **应用程序权限**由无需用户登录就可运行的应用程序使用,因此可针对应用程序使用这种类型的权限,以作为后台服务或守护程序运行,而且无需用户许可或需要用户许可。应用程序权限只能由租户管理员进行许可。务必了解,通过提供管理员许可,为此示例提供了诸多权限。例如,如果针对租户在**应用程序模式**中运行此示例,将创建组,添加并随后删除组成员,并随后删除组。
39 |
40 | 如果希望使用两种类型的权限,将需要在[Azure Active Directory 管理中心](https://aad.portal.azure.com)中创建并配置两个应用程序,一个用于**委派权限**,另一个用于**应用程序权限**。示例采用结构化设计,因此如果关注一种类型的权限,只能配置一个应用程序。如果只关注“**委派权限**”,使用“**用户模式**”,如果只关注“**应用程序权限**”,使用“**应用程序模式**”。
41 |
42 | 有关权限类型的更多信息,请参阅[“委派权限、应用程序权限和有效权限”](https://docs.microsoft.com/en-us/graph/permissions-reference#delegated-permissions-application-permissions-and-effective-permissions)。请参阅“[无用户访问](https://docs.microsoft.com/en-us/graph/auth-v2-service)”,具体了解有关“**应用程序权限**”的详细信息。
43 |
44 | ## 先决条件
45 |
46 | 此示例要求如下:
47 |
48 | * [Visual Studio](https://www.visualstudio.com/en-us/downloads)
49 |
50 | * [Office 365 商业版帐户](https://msdn.microsoft.com/en-us/office/office365/howto/setup-development-environment#bk_Office365Account)。需要 Office 365 管理员帐户才能运行管理员级别的操作以及许可应用程序权限。可以注册 [Office 365 开发人员订阅](https://msdn.microsoft.com/en-us/office/office365/howto/setup-development-environment#bk_Office365Account),其中包含开始生成应用所需的资源。
51 |
52 | ## 应用程序注册
53 |
54 | 此示例包含使用委派权限和应用程序权限的两个示例,因此需要针对每个方案分别注册应用程序。
55 |
56 |
57 | ### 注册**委派权限**应用程序
58 |
59 | 1. 导航至 [Azure Active Directory 管理中心](https://aad.portal.azure.com)。使用具有应用注册创建权限的**个人帐户**(也称为:“Microsoft 帐户”)或**工作/学校帐户**登录。
60 |
61 | 2. 选择左侧导航栏中的“**Azure Active Directory**,再选择“**管理**”下的“**应用注册(预览版)**”。
62 |
63 | 3. 选择“**新注册**”。在“**注册应用**”页上,按如下方式设置值。
64 |
65 | * 将“**名称**”设定为“`控制台代码片段示例(委派权限)`”。
66 | * 将“**受支持的帐户类型**”设置为“**任何组织目录中的帐户和个人 Microsoft 帐户**”。
67 | * 保留“**重定向 URI**”为空。
68 | ** 选择“**注册**”。
69 |
70 | 4. 在“**控制台代码片段示例(委派权限)**”页面上,复制“**应用程序(客户端)ID**”值和“**目录(租户)ID**”值。保存这两个值,因为随后需要它们。
71 |
72 | 5. 选择“**添加重定向 URI**” 链接。在“**重定向 URL**”页面上,找到“**建议用于公共客户端(移动、桌面)的重定向 URI**”部分。选择以 `msal` **为开头的 URL 和** **urn:ietf:wg:oauth:2.0:oob** URI。
73 |
74 | 6. 在 Visual Studio 中打开示例解决方案,然后打开 **Constants.cs** 文件。将“**租户**”字符串更改为之前复制的 “**目录(租户) ID**” 值。更改 **ClientIdForUserAuthn** 字符串为 “**应用程序(客户端)ID**”值。
75 |
76 |
77 | ### 注册**应用权限**应用程序
78 |
79 | 1. 导航至 [Azure Active Directory 管理中心](https://aad.portal.azure.com)。使用**工作或学校帐户**登录。
80 |
81 | 2. 选择左侧导航栏中的“**Azure Active Directory**,再选择“**管理**”下的“**应用注册(预览版)**”。
82 |
83 | 3. 选择“**新注册**”。在“**注册应用**”页上,按如下方式设置值。
84 |
85 | * 将“**名称**”设定为“`控制台代码片段示例(应用程序权限)`”。
86 | * 将**“受支持的帐户类型”**设置为**“任何组织目录中的帐户”**。
87 | * 保留“**重定向 URI**”为空。
88 | * 选择“**注册**”。
89 |
90 | 4. 在“**控制台代码片段示例(应用程序权限)**”页面上,复制并保存“**应用程序(客户端)ID**”值和“**目录(租户)ID**”值。在第 7 步上将需要它们。
91 |
92 | 5. 选择“**管理**”下的“**证书和密码**”。选择“**新客户端密码**”按钮。在“**说明**”中输入数值,随后选择任意“**过期**”选项并选择“**添加**”。
93 |
94 | 6. 离开页面前,先复制客户端密码值。将在下一步中用到它。
95 |
96 | 7. 在 Visual Studio 中打开示例解决方案,然后打开 **Constants.cs** 文件。将“**租户**”字符串更改为之前复制的 “**目录(租户) ID**” 值。同样,将 **ClientIdForAppAuthn** 字符串更改为 **应用程序(客户端) ID** 值,并将 **ClientSecret** 字符串更改为客户端密码值。
97 |
98 | 8. 返回 Azure Active Directory 管理中心。选择“**API 权限**”并随后选择“**添加权限**”。在出现的面板上,选择 **Microsoft Graph** 并随后选择“**应用程序权限”**。
99 |
100 | 9. 使用“**选择权限**”搜索框来搜索下列权限:Directory.Read.All、Group.ReadWrite.All、Mail.Read、Mail.ReadWrite、和 User.Read.All。在每个权限显示时,选择其复选框(请注意,选择每个权限后,它不会在列表中保持可见)。选择窗格下方选择“**添加权限**”。
101 |
102 | 10. 选择“**为\[租户名称]授予管理员许可**”按钮。选择“**是**”确认显示的内容。
103 |
104 | ## 生成和运行示例
105 |
106 | 1. 在 Visual Studio 中打开示例解决方案。
107 | 2. 按 F5 生成和运行此示例。这将还原 NuGet 包依赖项,并打开控制台应用程序。
108 | 3. 选择“用户模式”,以只使用“**委派权限**”运行应用程序。选择“应用程序模式”,以只使用“**应用程序权限**”运行应用程序。选择“两者”,以使用两种类型权限运行。
109 | 4. 运行“用户模式”时,系统将提示使用 Office 365 租户帐户登录,并同意应用程序请求的权限。如果以**用户模式**级运行组相关操作,需要对 UserMode.cs 文件中的 **GetDetailsForGroups** 方法和 AuthenticationHelper.cs 文件中的 **Group.Read.All** 范围取消注释。执行这些更改后,只有管理员才能登录并许可。否则,只能以非管理员用户登录并许可。
110 | 5. 运行“应用程序模式”时,应用程序开始运行大量只有管理员才能执行的组相关常规任务。由于已授权应用程序执行这些操作,因此不会提示登录和许可。
111 |
112 | ## 问题和意见
113 |
114 | 我们乐意倾听你有关 Microsoft Graph API Console 应用程序的反馈。你可以在该存储库中的“[问题](https://github.com/microsoftgraph/console-csharp-snippets-sample/issues)”部分将问题和建议发送给我们。
115 |
116 | 与 Microsoft Graph 开发相关的一般问题应发布到 [Stack Overflow](https://stackoverflow.com/questions/tagged/microsoftgraph)。请确保你的问题或意见标记有 \[microsoftgraph]。
117 |
118 | ## 参与
119 |
120 | 如果想要参与本示例,请参阅 [CONTRIBUTING.MD](/CONTRIBUTING.md)。
121 |
122 | 此项目已采用 [Microsoft 开放源代码行为准则](https://opensource.microsoft.com/codeofconduct/)。有关详细信息,请参阅[行为准则常见问题解答](https://opensource.microsoft.com/codeofconduct/faq/)。如有其他任何问题或意见,也可联系 [opencode@microsoft.com](mailto:opencode@microsoft.com)。
123 |
124 | ## 其他资源
125 |
126 | * [无用户访问](https://docs.microsoft.com/en-us/graph/auth-v2-service)
127 | * [委派权限、应用程序权限和有效权限](https://docs.microsoft.com/en-us/graph/permissions-reference#delegated-permissions-application-permissions-and-effective-permissions)
128 | * [Microsoft Graph](https://developer.microsoft.com/en-us/graph)
129 |
130 | ## 版权信息
131 |
132 | 版权所有 (c) 2017 Microsoft。保留所有权利。
133 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.suo
8 | *.user
9 | *.userosscache
10 | *.sln.docstates
11 |
12 | # User-specific files (MonoDevelop/Xamarin Studio)
13 | *.userprefs
14 |
15 | # Build results
16 | [Dd]ebug/
17 | [Dd]ebugPublic/
18 | [Rr]elease/
19 | [Rr]eleases/
20 | x64/
21 | x86/
22 | bld/
23 | [Bb]in/
24 | [Oo]bj/
25 | [Ll]og/
26 |
27 | # Visual Studio 2015 cache/options directory
28 | .vs/
29 | # Uncomment if you have tasks that create the project's static files in wwwroot
30 | #wwwroot/
31 |
32 | # MSTest test Results
33 | [Tt]est[Rr]esult*/
34 | [Bb]uild[Ll]og.*
35 |
36 | # NUNIT
37 | *.VisualState.xml
38 | TestResult.xml
39 |
40 | # Build Results of an ATL Project
41 | [Dd]ebugPS/
42 | [Rr]eleasePS/
43 | dlldata.c
44 |
45 | # .NET Core
46 | project.lock.json
47 | project.fragment.lock.json
48 | artifacts/
49 | **/Properties/launchSettings.json
50 |
51 | *_i.c
52 | *_p.c
53 | *_i.h
54 | *.ilk
55 | *.meta
56 | *.obj
57 | *.pch
58 | *.pdb
59 | *.pgc
60 | *.pgd
61 | *.rsp
62 | *.sbr
63 | *.tlb
64 | *.tli
65 | *.tlh
66 | *.tmp
67 | *.tmp_proj
68 | *.log
69 | *.vspscc
70 | *.vssscc
71 | .builds
72 | *.pidb
73 | *.svclog
74 | *.scc
75 |
76 | # Chutzpah Test files
77 | _Chutzpah*
78 |
79 | # Visual C++ cache files
80 | ipch/
81 | *.aps
82 | *.ncb
83 | *.opendb
84 | *.opensdf
85 | *.sdf
86 | *.cachefile
87 | *.VC.db
88 | *.VC.VC.opendb
89 |
90 | # Visual Studio profiler
91 | *.psess
92 | *.vsp
93 | *.vspx
94 | *.sap
95 |
96 | # TFS 2012 Local Workspace
97 | $tf/
98 |
99 | # Guidance Automation Toolkit
100 | *.gpState
101 |
102 | # ReSharper is a .NET coding add-in
103 | _ReSharper*/
104 | *.[Rr]e[Ss]harper
105 | *.DotSettings.user
106 |
107 | # JustCode is a .NET coding add-in
108 | .JustCode
109 |
110 | # TeamCity is a build add-in
111 | _TeamCity*
112 |
113 | # DotCover is a Code Coverage Tool
114 | *.dotCover
115 |
116 | # Visual Studio code coverage results
117 | *.coverage
118 | *.coveragexml
119 |
120 | # NCrunch
121 | _NCrunch_*
122 | .*crunch*.local.xml
123 | nCrunchTemp_*
124 |
125 | # MightyMoose
126 | *.mm.*
127 | AutoTest.Net/
128 |
129 | # Web workbench (sass)
130 | .sass-cache/
131 |
132 | # Installshield output folder
133 | [Ee]xpress/
134 |
135 | # DocProject is a documentation generator add-in
136 | DocProject/buildhelp/
137 | DocProject/Help/*.HxT
138 | DocProject/Help/*.HxC
139 | DocProject/Help/*.hhc
140 | DocProject/Help/*.hhk
141 | DocProject/Help/*.hhp
142 | DocProject/Help/Html2
143 | DocProject/Help/html
144 |
145 | # Click-Once directory
146 | publish/
147 |
148 | # Publish Web Output
149 | *.[Pp]ublish.xml
150 | *.azurePubxml
151 | # TODO: Comment the next line if you want to checkin your web deploy settings
152 | # but database connection strings (with potential passwords) will be unencrypted
153 | *.pubxml
154 | *.publishproj
155 |
156 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
157 | # checkin your Azure Web App publish settings, but sensitive information contained
158 | # in these scripts will be unencrypted
159 | PublishScripts/
160 |
161 | # NuGet Packages
162 | *.nupkg
163 | # The packages folder can be ignored because of Package Restore
164 | **/packages/*
165 | # except build/, which is used as an MSBuild target.
166 | !**/packages/build/
167 | # Uncomment if necessary however generally it will be regenerated when needed
168 | #!**/packages/repositories.config
169 | # NuGet v3's project.json files produces more ignorable files
170 | *.nuget.props
171 | *.nuget.targets
172 |
173 | # Microsoft Azure Build Output
174 | csx/
175 | *.build.csdef
176 |
177 | # Microsoft Azure Emulator
178 | ecf/
179 | rcf/
180 |
181 | # Windows Store app package directories and files
182 | AppPackages/
183 | BundleArtifacts/
184 | Package.StoreAssociation.xml
185 | _pkginfo.txt
186 |
187 | # Visual Studio cache files
188 | # files ending in .cache can be ignored
189 | *.[Cc]ache
190 | # but keep track of directories ending in .cache
191 | !*.[Cc]ache/
192 |
193 | # Others
194 | ClientBin/
195 | ~$*
196 | *~
197 | *.dbmdl
198 | *.dbproj.schemaview
199 | *.jfm
200 | *.pfx
201 | *.publishsettings
202 | orleans.codegen.cs
203 |
204 | # Since there are multiple workflows, uncomment next line to ignore bower_components
205 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
206 | #bower_components/
207 |
208 | # RIA/Silverlight projects
209 | Generated_Code/
210 |
211 | # Backup & report files from converting an old project file
212 | # to a newer Visual Studio version. Backup files are not needed,
213 | # because we have git ;-)
214 | _UpgradeReport_Files/
215 | Backup*/
216 | UpgradeLog*.XML
217 | UpgradeLog*.htm
218 |
219 | # SQL Server files
220 | *.mdf
221 | *.ldf
222 | *.ndf
223 |
224 | # Business Intelligence projects
225 | *.rdl.data
226 | *.bim.layout
227 | *.bim_*.settings
228 |
229 | # Microsoft Fakes
230 | FakesAssemblies/
231 |
232 | # GhostDoc plugin setting file
233 | *.GhostDoc.xml
234 |
235 | # Node.js Tools for Visual Studio
236 | .ntvs_analysis.dat
237 | node_modules/
238 |
239 | # Typescript v1 declaration files
240 | typings/
241 |
242 | # Visual Studio 6 build log
243 | *.plg
244 |
245 | # Visual Studio 6 workspace options file
246 | *.opt
247 |
248 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
249 | *.vbw
250 |
251 | # Visual Studio LightSwitch build output
252 | **/*.HTMLClient/GeneratedArtifacts
253 | **/*.DesktopClient/GeneratedArtifacts
254 | **/*.DesktopClient/ModelManifest.xml
255 | **/*.Server/GeneratedArtifacts
256 | **/*.Server/ModelManifest.xml
257 | _Pvt_Extensions
258 |
259 | # Paket dependency manager
260 | .paket/paket.exe
261 | paket-files/
262 |
263 | # FAKE - F# Make
264 | .fake/
265 |
266 | # JetBrains Rider
267 | .idea/
268 | *.sln.iml
269 |
270 | # CodeRush
271 | .cr/
272 |
273 | # Python Tools for Visual Studio (PTVS)
274 | __pycache__/
275 | *.pyc
276 |
277 | # Cake - Uncomment if you are using it
278 | # tools/**
279 | # !tools/packages.config
280 |
281 | # Telerik's JustMock configuration file
282 | *.jmconfig
283 |
284 | # BizTalk build output
285 | *.btp.cs
286 | *.btm.cs
287 | *.odx.cs
288 | *.xsd.cs
289 |
--------------------------------------------------------------------------------
/console-csharp-snippets-sample/AuthenticationHelper.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Diagnostics;
3 | using System.Net.Http.Headers;
4 | using System.Net.Http;
5 | using System.Linq;
6 | using System.Threading.Tasks;
7 | using Microsoft.Graph;
8 | using Microsoft.Identity.Client;
9 | using System.Collections.Generic;
10 |
11 | namespace console_csharp_snippets_sample
12 | {
13 | class AuthenticationHelper
14 | {
15 | // The Client ID is used by the application to uniquely identify itself to the v2.0 authentication endpoint.
16 | static string clientIdForUser = Constants.ClientIdForUserAuthn;
17 | static string clientIdForApp = Constants.ClientIdForAppAuthn;
18 | // The Group.Read.All permission is an admin-only scope, so authorization will fail if you
19 | // want to sign in with a non-admin account. Remove that permission and comment out the group operations in
20 | // the UserMode() method if you want to run this sample with a non-admin account.
21 | public static string[] Scopes = { "User.Read",
22 | "User.ReadWrite",
23 | "User.ReadBasic.All",
24 | "Calendars.ReadWrite",
25 | "Contacts.Read",
26 | "Mail.Send",
27 | "Mail.ReadWrite",
28 | "Files.ReadWrite",
29 | // Group.Read.All is an admin-only scope. It allows you to read Group details.
30 | // Uncomment this scope if you want to run the application with an admin account
31 | // and perform the group operations in the UserMode class.
32 | // You'll also need to uncomment the UserMode.UserModeRequests.GetDetailsForGroups() method.
33 | //"Group.Read.All"
34 | };
35 |
36 | public static PublicClientApplication IdentityClientApp = new PublicClientApplication(clientIdForUser);
37 | public static ConfidentialClientApplication IdentityAppOnlyApp = new ConfidentialClientApplication(clientIdForApp, Constants.AuthorityUri, Constants.RedirectUriForAppAuthn, new ClientCredential(Constants.ClientSecret), new TokenCache(), new TokenCache());
38 |
39 | private static GraphServiceClient graphClient = null;
40 |
41 | // Get an access token for the given context and resourceId. An attempt is first made to
42 | // acquire the token silently. If that fails, then we try to acquire the token by prompting the user.
43 | public static GraphServiceClient GetAuthenticatedClientForUser()
44 | {
45 | // Create Microsoft Graph client.
46 | try
47 | {
48 | graphClient = new GraphServiceClient(
49 | "https://graph.microsoft.com/v1.0",
50 | new DelegateAuthenticationProvider(
51 | async (requestMessage) =>
52 | {
53 | var token = await GetTokenForUserAsync();
54 | requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);
55 | // This header has been added to identify our sample in the Microsoft Graph service. If extracting this code for your project please remove.
56 | requestMessage.Headers.Add("SampleID", "console-csharp-snippets-sample");
57 |
58 | }));
59 | return graphClient;
60 | }
61 |
62 | catch (Exception ex)
63 | {
64 | Debug.WriteLine("Could not create a graph client: " + ex.Message);
65 | }
66 |
67 | return graphClient;
68 | }
69 |
70 |
71 | ///
72 | /// Get Token for User.
73 | ///
74 | /// Token for user.
75 | public static async Task GetTokenForUserAsync()
76 | {
77 | AuthenticationResult authResult;
78 | IEnumerable accounts = await IdentityClientApp.GetAccountsAsync();
79 | IAccount firstAccount = accounts.FirstOrDefault();
80 | try
81 | {
82 | authResult = await IdentityClientApp.AcquireTokenSilentAsync(Scopes, firstAccount);
83 | }
84 | catch (MsalUiRequiredException)
85 | {
86 | authResult = await IdentityClientApp.AcquireTokenAsync(Scopes);
87 | }
88 | return authResult.AccessToken;
89 | }
90 |
91 | public static GraphServiceClient GetAuthenticatedClientForApp()
92 | {
93 |
94 | // Create Microsoft Graph client.
95 | try
96 | {
97 | graphClient = new GraphServiceClient(
98 | "https://graph.microsoft.com/v1.0",
99 | new DelegateAuthenticationProvider(
100 | async (requestMessage) =>
101 | {
102 | var token = await GetTokenForAppAsync();
103 | requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);
104 | // This header has been added to identify our sample in the Microsoft Graph service. If extracting this code for your project please remove.
105 | requestMessage.Headers.Add("SampleID", "console-csharp-snippets-sample");
106 |
107 | }));
108 | return graphClient;
109 | }
110 |
111 | catch (Exception ex)
112 | {
113 | Debug.WriteLine("Could not create a graph client: " + ex.Message);
114 | }
115 |
116 |
117 | return graphClient;
118 | }
119 |
120 | ///
121 | /// Get Token for App.
122 | ///
123 | /// Token for app.
124 | public static async Task GetTokenForAppAsync()
125 | {
126 | AuthenticationResult authResult;
127 | authResult = await IdentityAppOnlyApp.AcquireTokenForClientAsync(new string[] { "https://graph.microsoft.com/.default" });
128 | return authResult.AccessToken;
129 | }
130 |
131 | ///
132 | /// Signs the user out of the service.
133 | ///
134 | public static async void SignOut()
135 | {
136 | IEnumerable accounts = await IdentityClientApp.GetAccountsAsync();
137 |
138 | foreach (var account in accounts.ToArray())
139 | {
140 | await IdentityClientApp.RemoveAsync(account);
141 | }
142 | graphClient = null;
143 | }
144 | }
145 | }
146 |
--------------------------------------------------------------------------------
/README-localized/README-ja-jp.md:
--------------------------------------------------------------------------------
1 | ---
2 | page_type: sample
3 | products:
4 | - ms-graph
5 | languages:
6 | - csharp
7 | description: "この Windows コンソール アプリは、委任されたアクセス許可とアプリケーションのアクセス許可の両方が付与されている Microsoft Graph クライアント ライブラリを使用して、各種操作を実行する方法を示します。このサンプルでは、Microsoft 認証ライブラリ (MSAL) を使用して、Azure AD v 2.0 エンドポイントの認証を行います。"
8 | extensions:
9 | contentType: samples
10 | technologies:
11 | - Microsoft Graph
12 | - Microsoft identity platform
13 | services:
14 | - Microsoft identity platform
15 | createdDate: 9/8/2017 1:33:44 PM
16 | ---
17 | # Microsoft Graph C# コンソール スニペット アプリ
18 |
19 | ## 目次
20 |
21 | * [はじめに](#introduction)
22 | * [前提条件](#prerequisites)
23 | * [**委任されたアクセス許可**アプリケーションを登録する](#Register-the-delegated-permissions-application )
24 | * [**アプリケーションのアクセス許可**アプリケーションを登録する](#Register-the-application-permissions-application )
25 | * [サンプルのビルドと実行](#build-and-run-the-sample)
26 | * [質問とコメント](#questions-and-comments)
27 | * [投稿](#contributing)
28 | * [その他のリソース](#additional-resources)
29 |
30 | ## はじめに
31 |
32 | このサンプル アプリケーションでは、Windows コンソール アプリ内からのメール送信、グループ管理、および他のアクティビティなどの一般的なタスクを実行するために Microsoft Graph を使用する、コード スニペットのリポジトリを提供しています。[Microsoft Graph .NET クライアント SDK](https://github.com/microsoftgraph/msgraph-sdk-dotnet) を使用して、Microsoft Graph が返すデータを操作します。
33 |
34 | サンプルでは Microsoft 認証ライブラリ (MSAL) を使用して認証を行います。このサンプルでは、委任されたアクセス許可とアプリケーションのアクセス許可の両方のデモンストレーションを行います。
35 |
36 | **委任されたアクセス許可**は、サインインしているユーザーがいるアプリで使用します。これに該当するアプリの場合は、ユーザーまたは管理者がアプリの要求するアクセス許可に同意します。アプリには、Microsoft Graph の呼び出し時に、サインインしているユーザーとして動作するためのアクセス許可が委任されます。一部の委任されたアクセス許可は非管理ユーザーの同意によって付与されますが、高度な特権が付与されるアクセス許可には管理者の同意が必要になります。このアプリケーションには、管理者の同意を必要とするグループ関連の操作およびこれらの操作用の関連付けられたアクセス許可がいくつか含まれており、コメントが付いています。
37 |
38 | **アプリケーションのアクセス許可**は、サインインしているユーザーなしで実行されるアプリで使用されます。この種類のアクセス許可は、バックグラウンド サービスまたはデーモンとして実行されるアプリで使用できます。このため、ユーザーの同意が付与されておらず、同意を必要ともしないアプリで使用できます。アプリケーションのアクセス許可への同意は、テナント管理者のみが行えます。このサンプルに管理者の同意を付与することにより、サンプルに大きな権限が付与されることを理解しておくことが重要です。たとえば、テナントに対してこのサンプルを **AppMode** で実行する場合、グループを作成し、グループのメンバーの追加に続いて削除を行い、グループの削除を行うことになります。
39 |
40 | 両方の種類のアクセス許可を使用する場合は、[Azure Active Directory 管理センター](https://aad.portal.azure.com)でアプリケーションを 2 つ (**委任されたアクセス許可**用に 1 つ、**アプリケーションのアクセス許可**用にもう 1 つ) 作成して構成する必要があります。このサンプルは、1 種類のアクセス許可のみを使用することを希望する場合は 1 つのアプリケーションのみを構成できる構造になっています。**委任されたアクセス許可**のみを希望する場合は **UserMode** クラスを使用し、**アプリケーションのアクセス許可**のみを希望する場合は **AppMode** クラスを使用します。
41 |
42 | これらのアクセス許可の種類の詳細については、「[委任されたアクセス許可、アプリケーションのアクセス許可、有効なアクセス許可](https://docs.microsoft.com/en-us/graph/permissions-reference#delegated-permissions-application-permissions-and-effective-permissions)」を参照してください。また、特に**アプリケーションのアクセス許可**については「[ユーザーなしでアクセスする](https://docs.microsoft.com/en-us/graph/auth-v2-service)」も参照してください。
43 |
44 | ## 前提条件
45 |
46 | このサンプルを実行するには次のものが必要です。
47 |
48 | * [Visual Studio](https://www.visualstudio.com/en-us/downloads)
49 |
50 | * [一般法人向け Office 365 のアカウント](https://msdn.microsoft.com/en-us/office/office365/howto/setup-development-environment#bk_Office365Account)。管理者レベルの操作を実行し、アプリケーションのアクセス許可に同意するには、Office 365 の管理者アカウントが必要です。アプリのビルドを開始するために必要なリソースを含む、[Office 365 Developer サブスクリプション](https://msdn.microsoft.com/en-us/office/office365/howto/setup-development-environment#bk_Office365Account)にサインアップできます。
51 |
52 | ## アプリケーションの登録
53 |
54 | このサンプルには、委任されたアクセス許可とアプリケーションのアクセス許可の両方を使用する例が含まれているため、シナリオごとにアプリを個別に登録する必要があります。
55 |
56 |
57 | ### **委任されたアクセス許可**アプリケーションを登録する
58 |
59 | 1. [Azure Active Directory 管理センター](https://aad.portal.azure.com)に移動します。アプリ登録を作成するためのアクセス許可が付与されている**個人用アカウント** (別名:Microsoft アカウントか**職場または学校のアカウント**を使用してログインします。
60 |
61 | 2. 左側のナビゲーションで [**Azure Active Directory**] を選択し、次に [**管理**] で [**アプリの登録 (プレビュー)**] を選択します。
62 |
63 | 3. [**新規登録**] を選択します。[**アプリケーションの登録**] ページで、次のように値を設定します。
64 |
65 | * [**名前**] を "`Console Snippets Sample (Delegated perms)`" に設定します。
66 | * [**サポート対象のアカウントの種類**] を [**任意の組織のディレクトリ内のアカウントと、個人用の Microsoft アカウント**] に設定します。
67 | * [**リダイレクト URI**] は空のままにします。.
68 | ** [**登録**] を選択します。
69 |
70 | 4. [**Console Snippets Sample (Delegate perms)**] ページで、[**アプリケーション (クライアント) ID**] と [**Directory (テナント) ID**] の両方の値をコピーします。これら 2 つの値は後で必要になるため、保存します。
71 |
72 | 5. [**リダイレクト URI の追加**] リンク を選択します。[**リダイレクト URI**] ページで [**パブリック クライアント (モバイル、デスクトップ) に推奨されるリダイレクト URI**] セクションを見つけます。"`msal`" から始まる URI **および** "**urn:ietf:wg:oauth:2.0:oob**" という URI を選択します。
73 |
74 | 6. サンプル ソリューションを Visual Studio で開き、ファイル **Constants.cs** を開きます。[**テナント**] 文字列を先ほどコピーした **Directory (テナント) ID** 値に変更します。[**ClientIdForUserAuthn**] 文字列を **アプリケーション (クライアント) ID** 値に変更します。
75 |
76 |
77 | ### **アプリケーションのアクセス許可**アプリケーションを登録する
78 |
79 | 1. [Azure Active Directory 管理センター](https://aad.portal.azure.com)に移動します。**職場または学校のアカウント**を使用してログインします。
80 |
81 | 2. 左側のナビゲーションで [**Azure Active Directory**] を選択し、次に [**管理**] で [**アプリの登録 (プレビュー)**] を選択します。
82 |
83 | 3. [**新規登録**] を選択します。[**アプリケーションの登録**] ページで、次のように値を設定します。
84 |
85 | * [**名前**] を "`Console Snippets Sample (Application perms)`" に設定します。
86 | * [**サポートされているアカウントの種類**] を [**任意の組織のディレクトリ内のアカウント**] に設定します。
87 | * [**リダイレクト URI**] は空のままにします。
88 | * [**登録**] を選択します。
89 |
90 | 4. [**Console Snippets Sample (Application perms)**] ページで、[**アプリケーション (クライアント) ID**] と [**Directory (テナント) ID**] の値をコピーして保存します。これらの値は、手順 7 で必要になります。
91 |
92 | 5. [**管理**] で [**証明書とシークレット**] を選択します。[**新しいクライアント シークレット**] ボタンを選択します。[**説明**] に値を入力し、[**有効期限**] で任意のオプションを選び、[**追加**] を選択します。
93 |
94 | 6. このページを離れる前に、クライアント シークレットの値をコピーします。この値は次の手順で必要になります。
95 |
96 | 7. サンプル ソリューションを Visual Studio で開き、ファイル **Constants.cs** を開きます。[**テナント**] 文字列を先ほどコピーした **Directory (テナント) ID** 値に変更します。同様に、[**ClientIdForAppAuthn**] 文字列を**アプリケーション (クライアント) ID** 値に変更し、[**ClientSecret**] 文字列をクライアント シークレット値に変更します。
97 |
98 | 8. Azure Active Directory 管理センターに戻ります。[**API のアクセス許可**]、[**アクセス許可の追加**] の順に選択します。表示されるパネルで、[**Microsoft Graph**] を選択し、[**アプリケーションのアクセス許可**] を選択します。
99 |
100 | 9. [**アクセス許可の選択**] 検索ボックスを使用して次のアクセス許可を検索します。Directory.Read.All、Group.ReadWrite.All、Mail.Read、Mail.ReadWrite、および User.Read.All。それぞれのアクセス許可が表示されるたびに、チェック ボックスをオンにします (それぞれのアクセス許可を選択すると、そのアクセス許可は一覧の表示から消えます)。パネル下部にある [**アクセス許可の追加**] ボタンを選択します。
101 |
102 | 10. [**[テナント名] に管理者の同意を与えます**] ボタンを選択します。確認メッセージが表示されたら、[**はい**] を選択します。
103 |
104 | ## サンプルのビルドと実行
105 |
106 | 1. サンプル ソリューションを Visual Studio で開きます。
107 | 2. F5 キーを押して、サンプルをビルドして実行します。これにより、NuGet パッケージの依存関係が復元され、コンソール アプリケーションが開きます。
108 | 3. **委任されたアクセス許可**のみでアプリケーションを実行するには [ユーザー] モードを選択します。**アプリケーションのアクセス許可**のみでアプリケーションを実行するには、[アプリ] モードを選択します。両方のアクセス許可の種類を使用する場合は、両方のモードを選択します。
109 | 4. ユーザー モードを実行すると、Office 365 テナントのアカウントでサインインして、アプリケーションが要求するアクセス許可に同意するように求められます。グループ関連の操作を **UserMode** クラスで実行する場合は、**GetDetailsForGroups** メソッドを UserMode.cs ファイルでコメント解除し、**Group.Read.All** スコープを AuthenticationHelper.cs ファイルでコメント解除する必要があります。変更後は、管理者のみがサインインと同意を行えるようになります。変更を行わない場合、管理者以外のユーザーがサインインと同意を行えます。
110 | 5. アプリ モードを実行すると、管理者のみが実行できる一般的なグループ関連のタスクをアプリケーションが実行し始めます。これらの操作をアプリケーションが行うことを既に承認しているため、サインインと同意を求めるメッセージは表示されません。
111 |
112 | ## 質問とコメント
113 |
114 | Microsoft Graph API コンソール アプリに関するフィードバックをぜひお寄せください。質問や提案は、このリポジトリの「[問題](https://github.com/microsoftgraph/console-csharp-snippets-sample/issues)」セクションで送信できます。
115 |
116 | Microsoft Graph 開発全般の質問については、「[Stack Overflow](https://stackoverflow.com/questions/tagged/microsoftgraph)」に投稿してください。質問やコメントには、必ず "microsoftgraph" とタグを付けてください。
117 |
118 | ## 投稿
119 |
120 | このサンプルに投稿する場合は、[CONTRIBUTING.MD](/CONTRIBUTING.md) を参照してください。
121 |
122 | このプロジェクトでは、[Microsoft Open Source Code of Conduct (Microsoft オープン ソース倫理規定)](https://opensource.microsoft.com/codeofconduct/) が採用されています。詳細については、「[Code of Conduct の FAQ](https://opensource.microsoft.com/codeofconduct/faq/)」を参照してください。また、その他の質問やコメントがあれば、[opencode@microsoft.com](mailto:opencode@microsoft.com) までお問い合わせください。
123 |
124 | ## その他のリソース
125 |
126 | * [ユーザーなしでアクセスする](https://docs.microsoft.com/en-us/graph/auth-v2-service)
127 | * [委任されたアクセス許可、アプリケーションのアクセス許可、有効なアクセス許可](https://docs.microsoft.com/en-us/graph/permissions-reference#delegated-permissions-application-permissions-and-effective-permissions)
128 | * [Microsoft Graph](https://developer.microsoft.com/en-us/graph)
129 |
130 | ## 著作権
131 |
132 | Copyright (c) 2017 Microsoft.All rights reserved.
133 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # [ARCHIVED] Microsoft Graph C# Console Snippets App
2 |
3 | ## IMPORTANT
4 |
5 | **This project is being archived and replaced with the [Build .NET Core apps with the Microsoft Graph SDK training](https://github.com/microsoftgraph/msgraph-training-dotnet-core). As part of the archival process, we're closing all open issues and pull requests.**
6 |
7 | **You can continue to use this sample "as-is", but it won't be maintained moving forward. We apologize for any inconvenience.**
8 |
9 | ## Table of contents
10 |
11 | * [Introduction](#introduction)
12 | * [Prerequisites](#prerequisites)
13 | * [Register the **delegated permissions** application](#Register-the-delegated-permissions-application )
14 | * [Register the **application permissions** application](#Register-the-application-permissions-application )
15 | * [Build and run the sample](#build-and-run-the-sample)
16 | * [Questions and comments](#questions-and-comments)
17 | * [Contributing](#contributing)
18 | * [Additional resources](#additional-resources)
19 |
20 | ## Introduction
21 |
22 | This sample application provides a repository of code snippets that use the Microsoft Graph to perform common tasks, such as sending email, managing groups, and other activities from within a Windows console application. It uses the [Microsoft Graph .NET Client SDK](https://github.com/microsoftgraph/msgraph-sdk-dotnet) to work with data returned by the Microsoft Graph.
23 |
24 | The sample uses the Microsoft Authentication Library (MSAL) for authentication. The sample demonstrates both delegated and application permissions.
25 |
26 | **Delegated permissions** are used by apps that have a signed-in user present. For these apps either the user or an administrator consents to the permissions that the app requests and the app is delegated permission to act as the signed-in user when making calls to Microsoft Graph. Some delegated permissions can be consented to by non-administrative users, but some higher-privileged permissions require administrator consent. This application contains some groups-related operations that require administrative consent, and the associated permissions required to do them, are commented by default.
27 |
28 | **Application permissions** are used by apps that run without a signed-in user present; you can use this type of permission for apps that run as background services or daemons and that therefore will neither have nor require user consent. Application permissions can only be consented to by a tenant administrator. It is important that you understand that you give this sample a lot of power by providing it admin consent. For example, if you run this sample in **AppMode** against your tenant, you will create a group, add and then remove members of the group, and then delete the group.
29 |
30 | If you want to use both types of permissions, you'll need to create and configure two applications in the [Azure Active Directory admin center](https://aad.portal.azure.com), one for **delegated permissions** and another for **application permissions**. The sample is structured so that you can configure only one application if you're interested in only one type of permission. Use the **UserMode** class if you're interested only in **delegated permissions** and the **AppMode** class if you're interested only in **application permissions**.
31 |
32 | See [Delegated permissions, Application permissions, and effective permissions](https://docs.microsoft.com/en-us/graph/permissions-reference#delegated-permissions-application-permissions-and-effective-permissions) for more information about these permission types. Also see [Get access without a user](https://docs.microsoft.com/en-us/graph/auth-v2-service) for more information on **application permissions** specifically.
33 |
34 | ## Prerequisites
35 |
36 | This sample requires the following:
37 |
38 | * [Visual Studio](https://www.visualstudio.com/en-us/downloads)
39 |
40 | * An [Office 365 for business account](https://msdn.microsoft.com/en-us/office/office365/howto/setup-development-environment#bk_Office365Account). An Office 365 administrator account is required to run admin-level operations and to consent to application permissions. You can sign up for [an Office 365 Developer subscription](https://msdn.microsoft.com/en-us/office/office365/howto/setup-development-environment#bk_Office365Account) that includes the resources that you need to start building apps.
41 |
42 | ## Application registration
43 |
44 | This sample contains examples that use both delegated permissions and application permissions, so you'll need register the app separately for each scenario.
45 |
46 |
47 | ### Register the **delegated permissions** application
48 |
49 | 1. Navigate to the [Azure Active Directory admin center](https://aad.portal.azure.com). Login using a **personal account** (aka: Microsoft Account) or **Work or School Account**.
50 |
51 | 2. Select **Azure Active Directory** in the left-hand navigation, then select **App registrations (Preview)** under **Manage**.
52 |
53 | 3. Select **New registration**. On the **Register an application** page, set the values as follows.
54 |
55 | * Set **Name** to `Console Snippets Sample (Delegated perms)`.
56 | * Set **Supported account types** to **Accounts in any organizational directory and personal Microsoft accounts**.
57 | * Leave **Redirect URI** empty.
58 | ** Choose **Register**.
59 |
60 | 4. On the **Console Snippets Sample (Delegate perms)** page, copy the values of both the **Application (client) ID** and the **Directory (tenant) ID**. Save these two values, since you will need them later.
61 |
62 | 5. Select the **Add a Redirect URI** link. On the **Redirect URIs** page, locate the **Suggested Redirect URIs for public clients (mobile, desktop)** section. Select the URI that begins with `msal` **and** the **urn:ietf:wg:oauth:2.0:oob** URI.
63 |
64 | 6. Open the sample solution in Visual Studio and then open the **Constants.cs** file. Change the **Tenant** string to the **Directory (tenant) ID** value you copied earlier. Change the **ClientIdForUserAuthn** string to the **Application (client) ID** value.
65 |
66 |
67 | ### Register the **application permissions** application
68 |
69 | 1. Navigate to the [Azure Active Directory admin center](https://aad.portal.azure.com). Login using a **Work or School Account**.
70 |
71 | 2. Select **Azure Active Directory** in the left-hand navigation, then select **App registrations (Preview)** under **Manage**.
72 |
73 | 3. Select **New registration**. On the **Register an application** page, set the values as follows.
74 |
75 | * Set **Name** to `Console Snippets Sample (Application perms)`.
76 | * Set **Supported account types** to **Accounts in any organizational directory**.
77 | * Leave **Redirect URI** empty.
78 | * Choose **Register**.
79 |
80 | 4. On the **Console Snippets Sample (Application perms)** page, copy and save the values for the **Application (client) ID** and the **Directory (tenant) ID**. You will need them in step 7.
81 |
82 | 5. Select **Certificates & secrets** under **Manage**. Select the **New client secret** button. Enter a value in **Description**, select any option for **Expires** and choose **Add**.
83 |
84 | 6. Copy the client secret value before leaving the page. You will need it in the next step.
85 |
86 | 7. Open the sample solution in Visual Studio and then open the **Constants.cs** file. Change the **Tenant** string to the **Directory (tenant) ID** value you copied earlier. Similarly, change the **ClientIdForAppAuthn** string to the **Application (client) ID** value and change the **ClientSecret** string to the client secret value.
87 |
88 | 8. Return to the Azure Active Directory management center. Select **API permisions** and then select **Add a permission**. On the panel that appears, choose **Microsoft Graph** and then choose **Application permissions**.
89 |
90 | 9. Use the **Select permissions** search box to search for the following permissions: Directory.Read.All, Group.ReadWrite.All, Mail.Read, Mail.ReadWrite, and User.Read.All. Select the check box for each permissions as it appears (note that the permissions will not remain visible in the list as you select each one). Select the **Add permissions** button at the bottom of the panel.
91 |
92 | 10. Choose the **Grant admin consent for [tenant name]** button. Select **Yes** for the confirmation that appears.
93 |
94 | ## Build and run the sample
95 |
96 | 1. Open the sample solution in Visual Studio.
97 | 2. Press F5 to build and run the sample. This will restore the NuGet package dependencies and open the console application.
98 | 3. Select User mode to run the application with **delegated permissions** only. Select App mode to run the application with **application permissions** only. Select both to run using both types of permissions.
99 | 4. When you run User mode, you'll be prompted to sign in with an account on your Office 365 tenant and consent to the permissions that the application requests. If you want to run the groups-related operations in the **UserMode** class, you'll need to uncomment the **GetDetailsForGroups** method in the UserMode.cs file and the **Group.Read.All** scope in the AuthenticationHelper.cs file. After you make those changes only an admin will be able to sign in and consent. Otherwise, you can sign in and consent with a non-admin user.
100 | 5. When you run App mode, the application will begin performing a number of common groups-related tasks that only an admin can do. Since you've already authorized the application to make these operations, you won't be prompted to sign in and consent.
101 |
102 | ## Questions and comments
103 |
104 | We'd love to get your feedback about the Microsoft Graph API Console App. You can send your questions and suggestions in the [Issues](https://github.com/microsoftgraph/console-csharp-snippets-sample/issues) section of this repository.
105 |
106 | Questions about Microsoft Graph development in general should be posted to [Stack Overflow](https://stackoverflow.com/questions/tagged/microsoftgraph). Make sure that your questions or comments are tagged with [microsoftgraph].
107 |
108 | ## Contributing
109 |
110 | If you'd like to contribute to this sample, see [CONTRIBUTING.MD](/CONTRIBUTING.md).
111 |
112 | This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.
113 |
114 | ## Additional resources
115 |
116 | * [Get access without a user](https://docs.microsoft.com/en-us/graph/auth-v2-service)
117 | * [Delegated permissions, Application permissions, and effective permissions](https://docs.microsoft.com/en-us/graph/permissions-reference#delegated-permissions-application-permissions-and-effective-permissions)
118 | * [Microsoft Graph](https://developer.microsoft.com/en-us/graph)
119 |
120 | ## Copyright
121 |
122 | Copyright (c) 2017 Microsoft. All rights reserved.
123 |
--------------------------------------------------------------------------------
/README-localized/README-ru-ru.md:
--------------------------------------------------------------------------------
1 | ---
2 | page_type: sample
3 | products:
4 | - ms-graph
5 | languages:
6 | - csharp
7 | description: "Это консольное приложение Windows демонстрирует выполнение различных операций при помощи клиентской библиотеки Microsoft Graph с разрешениями приложения и делегированными разрешениями. В этом примере для проверки подлинности в конечной точке Azure AD версии 2.0, используется библиотека проверки подлинности Майкрософт (MSAL)."
8 | extensions:
9 | contentType: samples
10 | technologies:
11 | - Microsoft Graph
12 | - Microsoft identity platform
13 | services:
14 | - Microsoft identity platform
15 | createdDate: 9/8/2017 1:33:44 PM
16 | ---
17 | # Консольное приложение фрагментов Microsoft Graph C#
18 |
19 | ## Содержание
20 |
21 | * [Введение](#introduction)
22 | * [Предварительные требования](#prerequisites)
23 | * [Регистрация ** ** приложения](#Register-the-delegated-permissions-application ) делегированных разрешений
24 | * [Регистрация ** ** приложения](#Register-the-application-permissions-application ) разрешений приложения
25 | * [Сборка и запуск примера](#build-and-run-the-sample)
26 | * [Вопросы и комментарии](#questions-and-comments)
27 | * [Участие](#contributing)
28 | * [Дополнительные ресурсы](#additional-resources)
29 |
30 | ## Введение
31 |
32 | В этом примере представлены фрагменты кода, использующие Microsoft Graph для отправки электронной почты, управления группами и выполнения других стандартных задач из консольного приложения Windows. Для работы с данными, возвращаемыми Microsoft Graph, используется [клиентский пакет SDK .NET Microsoft Graph](https://github.com/microsoftgraph/msgraph-sdk-dotnet).
33 |
34 | Для проверки подлинности в этом примере используется библиотека Microsoft Authentication Library (MSAL). В примере показаны как делегированные разрешения, так и разрешения приложений.
35 |
36 | **Делегированные разрешения** используются в приложениях, предусматривающих вход пользователя. Для таких приложений пользователь или администратор соглашается предоставить запрашиваемые разрешения. Приложение получает разрешение действовать от имени вошедшего пользователя, вызывая Microsoft Graph. Некоторые делегированные разрешения могут предоставлять пользователи, не являющиеся администраторами. Однако для разрешений высокого уровня требуется согласие администратора. Это приложение содержит операции, связанные с группами, требующие согласия администратора, а соответствующие разрешения, необходимые для их выполнения комментируются по умолчанию.
37 |
38 | **Разрешения приложений** используются приложениями, которые запускаются без пользователей; Этот тип разрешения используется для приложений, которые запускаются в качестве фоновых служб или управляющих программ, и не будут использовать или требовать согласия пользователя. Для таких разрешений согласие предоставляет только администратор клиента. Важно понимать, что вы даете множество полномочий этому приложению, предоставляя ему согласие администратора. Например, если запустить этот пример в **AppMode** по отношению к клиенту, нужно будет создать группу, добавить и удалить участников группы, а затем удалить группу.
39 |
40 | Чтобы использовать оба типа разрешений, вам потребуется создать и настроить два приложения в [центре администрирования Azure Active Directory](https://aad.portal.azure.com)— один для **делегированных разрешений** а другой — для **разрешений приложений**. Образец структурирован так, чтобы вы могли настроить только одно приложение, если вы хотите использовать только один тип разрешений. Используйте класс **UserMode**, если вы заинтересованы только в **делегированных разрешениях** и класс **AppMode**, если вы заинтересованы только в **разрешениях приложений**.
41 |
42 | Дополнительные сведения про типы разрешений см. в [Разрешения приложения, делегированные разрешения и действующие разрешения](https://docs.microsoft.com/en-us/graph/permissions-reference#delegated-permissions-application-permissions-and-effective-permissions). Дополнительные сведения о **разрешениях приложений** см. в [Получение доступа без пользователя](https://docs.microsoft.com/en-us/graph/auth-v2-service).
43 |
44 | ## Предварительные требования
45 |
46 | Для этого примера требуются следующие компоненты:
47 |
48 | * [Visual Studio](https://www.visualstudio.com/en-us/downloads)
49 |
50 | * [Учетная запись Office 365 для бизнеса](https://msdn.microsoft.com/en-us/office/office365/howto/setup-development-environment#bk_Office365Account). Для выполнения административных операций требуется учетная запись администратора Office 365. Вы можете подписаться на [план Office 365 для разработчиков](https://msdn.microsoft.com/en-us/office/office365/howto/setup-development-environment#bk_Office365Account), который включает ресурсы, необходимые для создания приложений.
51 |
52 | ## Регистрация приложения
53 |
54 | Здесь приведены примеры, которые используют делегированные разрешения и разрешения приложений, поэтому вам потребуется зарегистрировать приложение отдельно для каждого сценария.
55 |
56 |
57 | ### Регистрация приложения **делегированных разрешений**
58 |
59 | 1. Перейдите в [центр администрирования Azure Active Directory](https://aad.portal.azure.com). Войдите с помощью **личной учетной записи** (т. е. учетной записи Майкрософт) или **рабочей или учебной учетной записи**.
60 |
61 | 2. Выберите **Azure Active Directory** на панели навигации слева, затем выберите **Регистрация приложения (предварительная версия)** в разделе **Управление**.
62 |
63 | 3. Выберите **Новая регистрация**. На странице **Регистрация приложения** задайте необходимые значения следующим образом:
64 |
65 | * Задайте **Имя** для `примера консольных фрагментов (делегированных разрешений)`.
66 | * Установите **Поддерживаемые типы учетных записей** в **Учетные записи в любом каталоге организации и личных учетных записях Microsoft**.
67 | * Оставьте поле **URI перенаправления** пустым.
68 | ** Выберите **Регистрация**.
69 |
70 | 4. На странице **примера консольных фрагментов (делегированных разрешений)** скопируйте значения **Идентификатора приложения (клиента)** и **Идентификатора каталога (клиента)**. Сохраните эти два значения, так как они понадобятся позже.
71 |
72 | 5. Выберите ссылку **добавить URI перенаправления**. На странице **URI перенаправления** найдите раздел **Предлагаемые URI перенаправления для общедоступных клиентов (мобильные, настольные)**. Выберите URI которые начинается с `msal` **и** URI **urn:ietf:wg:oauth:2.0:oob**.
73 |
74 | 6. Откройте образец решения в Visual Studio и откройте файл **Constants.cs**. Измените строку **клиента** на значение **идентификатора каталога (клиента)**, которое вы скопировали ранее. Измените строку**ClientIdForUserAuthn** на значение **Идентификатор приложения (клиента)**.
75 |
76 |
77 | ### Регистрация приложения **разрешений приложения**
78 |
79 | 1. Перейдите в [центр администрирования Azure Active Directory](https://aad.portal.azure.com). Войдите с помощью **рабочей или учебной учетной записи**.
80 |
81 | 2. Выберите **Azure Active Directory** на панели навигации слева, затем выберите **Регистрация приложения (предварительная версия)** в разделе **Управление**.
82 |
83 | 3. Выберите **Новая регистрация**. На странице **Регистрация приложения** задайте необходимые значения следующим образом:
84 |
85 | * Задайте **Имя** для `примера консольных фрагментов (разрешений приложения)`.
86 | * Задайте для параметра **Поддерживаемые типы учетных записей** значение **Учетные записи в любом каталоге организации**.
87 | * Оставьте поле **URI перенаправления** пустым.
88 | * Нажмите кнопку **Зарегистрировать**.
89 |
90 | 4. На странице **примера консольных фрагментов (разрешений приложения)** скопируйте значения **Идентификатора приложения (клиента)** и **Идентификатора каталога (клиента)**. Они понадобятся вам на шаге 7.
91 |
92 | 5. Выберите **Сертификаты и секреты** в разделе **Управление**. Нажмите кнопку **Новый секрет клиента**. Введите значение в поле **Описание**, выберите любую опцию **Срок действия** и нажмите **Добавить**.
93 |
94 | 6. Скопируйте секретное значение клиента перед тем, как покинуть страницу. Оно понадобится вам на следующем шаге.
95 |
96 | 7. Откройте образец решения в Visual Studio и откройте файл **Constants.cs**. Измените строку **клиента** на значение **идентификатора каталога (клиента)**, которое вы скопировали ранее. Аналогичным образом измените строку **ClientIdForAppAuthn** на **значение идентификатора приложения (клиента)** и измените строку **ClientSecret** на секретное значение клиента.
97 |
98 | 8. Вернитесь в центр управления Azure Active Directory. Выберите **разрешения API**, а затем выберите **Добавить разрешение**. На появившейся панели выберите **Microsoft Graph**, а затем выберите **Права доступа к приложению**.
99 |
100 | 9. Используйте окно поиска **Выбор разрешений** для поиска следующих разрешений: Directory.Read.All, Group.ReadWrite.All, Mail.Read, Mail.ReadWrite, и User.Read.All. Установите флажок для каждого отображаемого разрешения (обратите внимание, что разрешения скрываются из списка после их выбора). Нажмите кнопку **добавить разрешения** в нижней части панели.
101 |
102 | 10. Нажмите кнопку **предоставить согласие администратора для \[имя клиента]**. В появившемся диалоговом окне нажмите кнопку **да**, чтобы подтвердить это.
103 |
104 | ## Сборка и запуск примера
105 |
106 | 1. Откройте пример решения в Visual Studio.
107 | 2. Нажмите клавишу F5 для сборки и запуска примера. Это восстановит зависимости пакета NuGet и откроет консольное приложение.
108 | 3. Выберите режим пользователя, чтобы запустить приложение только с **делегированными разрешениями**. Выберите режим приложения, чтобы запустить приложение только с **разрешениями приложений**. Чтобы использовать оба типа разрешений, выберите оба ражима.
109 | 4. При запуске пользовательского режима вам понадобится выполнить вход с помощью учетной записи в клиенте Office 365 и подтвердить разрешения, запрашиваемые приложением. Если вы хотите выполнить операции, связанные с группами, в классе **UserMode**, раскомментируйте метод **GetDetailsForGroups** в файле UserMode.cs и области **Group.Read.All** в файле AuthenticationHelper.cs. После внесения этих изменений только администратор сможет входить в систему и предоставлять согласие. В противном случае вы можете войти в систему и предоставить согласие, не используя учетную запись администратора.
110 | 5. При запуске режима приложения, приложение начинает выполнять ряд распространенных задач, связанных с группами, которые может выполнить только администратор. После проверки приложения на выполнение этих операций, вам не потребуется выполнять вход и предоставлять согласие.
111 |
112 | ## Вопросы и комментарии
113 |
114 | Мы будем рады получить ваши отзывы об API консольного приложения Microsoft Graph. Вы можете отправлять нам свои вопросы и предложения с помощью вкладки [Проблемы](https://github.com/microsoftgraph/console-csharp-snippets-sample/issues) этого репозитория.
115 |
116 | Общие вопросы о разработке решений для Microsoft Graph следует задавать на сайте [Stack Overflow](https://stackoverflow.com/questions/tagged/microsoftgraph). Обязательно помечайте свои вопросы и комментарии тегом \[microsoftgraph].
117 |
118 | ## Участие
119 |
120 | Если вы хотите добавить код в этот пример, просмотрите статью [CONTRIBUTING.MD](/CONTRIBUTING.md).
121 |
122 | Этот проект соответствует [Правилам поведения разработчиков открытого кода Майкрософт](https://opensource.microsoft.com/codeofconduct/). Дополнительные сведения см. в разделе [вопросов и ответов о правилах поведения](https://opensource.microsoft.com/codeofconduct/faq/). Если у вас возникли вопросы или замечания, напишите нам по адресу [opencode@microsoft.com](mailto:opencode@microsoft.com).
123 |
124 | ## Дополнительные ресурсы
125 |
126 | * [Получение доступа без пользователя](https://docs.microsoft.com/en-us/graph/auth-v2-service)
127 | * [Разрешения приложения, делегированные разрешения и действующие разрешения](https://docs.microsoft.com/en-us/graph/permissions-reference#delegated-permissions-application-permissions-and-effective-permissions)
128 | * [Microsoft Graph](https://developer.microsoft.com/en-us/graph)
129 |
130 | ## Авторские права
131 |
132 | (c) Корпорация Майкрософт (Microsoft Corporation), 2017. Все права защищены.
133 |
--------------------------------------------------------------------------------
/README-localized/README-pt-br.md:
--------------------------------------------------------------------------------
1 | ---
2 | page_type: sample
3 | products:
4 | - ms-graph
5 | languages:
6 | - csharp
7 | description: "Esse aplicativo de console do Windows mostra como executar várias operações usando a biblioteca de cliente do Microsoft Graph com ambos os tipos de permissões, tanto delegada quanto de aplicativo. Esta amostra usa a Biblioteca de Autenticação da Microsoft (MSAL) para autenticação do ponto de extremidade do Azure AD v2.0."
8 | extensions:
9 | contentType: samples
10 | technologies:
11 | - Microsoft Graph
12 | - Microsoft identity platform
13 | services:
14 | - Microsoft identity platform
15 | createdDate: 9/8/2017 1:33:44 PM
16 | ---
17 | # Aplicativo trechos de console C# do Microsoft Graph
18 |
19 | ## Sumário
20 |
21 | * [Introdução](#introduction)
22 | * [Pré-requisitos](#prerequisites)
23 | * [Registrar o **aplicativo** permissões delegadas](#Register-the-delegated-permissions-application )
24 | * [Registrar o **aplicativo** permissões de aplicativo](#Register-the-application-permissions-application )
25 | * [Criar e executar o exemplo](#build-and-run-the-sample)
26 | * [Perguntas e comentários](#questions-and-comments)
27 | * [Colaboração](#contributing)
28 | * [Recursos adicionais](#additional-resources)
29 |
30 | ## Introdução
31 |
32 | Este exemplo de projeto fornece um repositório de trechos de código que usa o Microsoft Graph para realizar tarefas comuns, como envio de emails, gerenciamento de grupos e outras atividades diretamente de um aplicativo de console do Windows. O exemplo usa o [SDK de cliente do Microsoft Graph .NET](https://github.com/microsoftgraph/msgraph-sdk-dotnet) para trabalhar com dados retornados pelo Microsoft Graph.
33 |
34 | O exemplo usa a Biblioteca de Autenticação da Microsoft (MSAL) para autenticação. O exemplo demonstra tanto as permissões delegadas quanto as do aplicativo.
35 |
36 | As **Permissões delegadas**são usadas pelos aplicativos que têm um usuário conectado presente. Para esses aplicativos, o usuário ou um administrador concorda com as permissões que o aplicativo solicita e o aplicativo tem permissão delegada para agir como se fosse o usuário conectado fazendo chamadas para o Microsoft Graph. Algumas permissões delegadas podem ser autorizadas por usuários não administrativos, mas algumas permissões com privilégios mais altos exigem o consentimento do administrador. Esse aplicativo contém algumas operações relacionadas a grupos que exigem consentimento administrativo e as permissões associadas necessárias para executá-las, são comentadas por padrão.
37 |
38 | As**permissões de aplicativo** são usadas por aplicativos que funcionam sem a presença de um usuário conectado. Você pode usar esse tipo de permissão para aplicativos executados como serviços de tela de fundo ou daemons, e que portanto, nem têm nem exigem consentimento do usuário. As permissões de aplicativo só podem ser concedidas por um administrador de locatários. É importante que você entenda que estará dando a esse aplicativo de exemplo um grande poder ao fornecer a ele consentimento de administrador de ti. Por exemplo, se você executar esse exemplo na **AppMode** no seu locatário, criará um grupo, adicionará e removerá os membros do grupo e, em seguida, excluirá o grupo.
39 |
40 | Caso pretenda usar os dois tipos de permissões, você precisará criar e configurar dois aplicativos na [centro de administração do Azure Active Directory](https://aad.portal.azure.com), um para **permissões delegadas** e outro para **permissões de aplicativo**. O aplicativo de amostra é estruturado para que você possa configurar somente um aplicativo caso estiver interessado em apenas um tipo de permissão. Use a classe **UserMode** se você estiver interessado apenas em **permissões delegadas** e a classe **AppMode** se você estiver interessado apenas em **permissões de aplicativo**.
41 |
42 | Para obter mais informações sobre esses tipos de permissões, confira [Permissões delegadas, Permissões de aplicativo e permissões efetivas](https://docs.microsoft.com/en-us/graph/permissions-reference#delegated-permissions-application-permissions-and-effective-permissions). Confira também [Obter acesso sem um usuário](https://docs.microsoft.com/en-us/graph/auth-v2-service) para obter mais informações especificamente sobre **permissões de aplicativo**.
43 |
44 | ## Pré-requisitos
45 |
46 | Este exemplo requer o seguinte:
47 |
48 | * [Visual Studio](https://www.visualstudio.com/en-us/downloads)
49 |
50 | * Uma [conta do Office 365 for business](https://msdn.microsoft.com/en-us/office/office365/howto/setup-development-environment#bk_Office365Account). Uma conta de administrador do Office 365 é necessária para executar operações de administrador e para dar o consentimento para as permissões de aplicativo. Você pode se inscrever para uma [assinatura de Desenvolvedor do Office 365](https://msdn.microsoft.com/en-us/office/office365/howto/setup-development-environment#bk_Office365Account)que inclui os recursos necessários para começar a criar aplicativos.
51 |
52 | ## Registro de aplicativo
53 |
54 | Este exemplo contém exemplos que usam tanto as permissões delegadas quanto as permissões do aplicativo, dessa forma você precisará registrar o aplicativo separadamente para cada cenário.
55 |
56 |
57 | ### Registre o aplicativo **permissões delegadas**
58 |
59 | 1. Acesse o [ centro de administração do Azure Active Directory](https://aad.portal.azure.com). Faça logon usando uma **conta pessoal** (também conhecida como: Conta Microsoft) **Conta Corporativa ou de Estudante**.
60 |
61 | 2. Selecione **Azure Active Directory** na navegação à esquerda e, em seguida, selecione **Registros de aplicativo (Visualizar)** em **Gerenciar**.
62 |
63 | 3. Selecione **Novo registro**. Na página **Registrar um aplicativo**, defina os valores da forma descrita abaixo.
64 |
65 | * Defina o **Nome** como `Exemplo de Trechos de Console (Permissões delegadas)`.
66 | * Defina **Tipos de contas com suporte** para **Contas em qualquer diretório organizacional e contas pessoais da Microsoft**.
67 | * Deixe o **URI de Redirecionamento** em branco.
68 | ** Escolha **Registrar**.
69 |
70 | 4. Na página **Exemplo de Trechos de Console (Permissões delegadas)**, copie os valores do **ID do aplicativo (cliente)** e do **ID do Diretório (locatário)**. Salve esses dois valores, porque você vai precisar deles mais tarde.
71 |
72 | 5. Selecione **adicionar uma URI de redirecionamento**. Na página **Redirecionamento de URIs**, localize a seção**URIs de redirecionamento sugeridas para clientes públicos (móvel, área de trabalho)**. Selecione a URI que começa com `msal` **e**a URI **urn:ietf:wg:oauth:2.0:oob**.
73 |
74 | 6. Abra a solução de exemplo no Visual Studio e, em seguida, abra o arquivo **Constants.cs**. Altere a cadeia de caracteres do**Locatário** para o valor do **ID de Directory (locatário)** que você copiou anteriormente. Altere a cadeia de caracteres de **ClientIdForUserAuthn**para o valor da ** ID do aplicativo (cliente)**.
75 |
76 |
77 | ### Registre o aplicativo **permissões de aplicativo**
78 |
79 | 1. Acesse o [ centro de administração do Azure Active Directory](https://aad.portal.azure.com). Faça logon usando uma **Conta Corporativa ou de Estudante**.
80 |
81 | 2. Selecione **Azure Active Directory** na navegação à esquerda e, em seguida, selecione **Registros de aplicativo (Visualizar)** em **Gerenciar**.
82 |
83 | 3. Selecione **Novo registro**. Na página **Registrar um aplicativo**, defina os valores da forma descrita abaixo.
84 |
85 | * Defina o **Nome** como `Exemplo de Trechos de Console (Permissões de aplicativo)`.
86 | * Defina os **Tipos de conta com suporte** para **Contas em qualquer diretório organizacional**.
87 | * Deixe o **URI de Redirecionamento** em branco.
88 | * Escolha **Registrar**.
89 |
90 | 4. Na página **Exemplo de Trechos de Console (Permissões de aplicativo)**, copie e salve os valores do **ID do aplicativo (cliente)** e do **ID do Diretório (locatário)**. Você precisará desses valores mais tarde na etapa 7.
91 |
92 | 5. Selecione **Certificados e segredos** em **Gerenciar**. Selecione o botão **Novo segredo do cliente**. Insira um valor em **Descrição**, selecione qualquer uma das opções para **Expira** e escolha **Adicionar**.
93 |
94 | 6. Copie o valor do segredo do cliente antes de sair desta página. Você precisará dele na próxima etapa.
95 |
96 | 7. Abra a solução de exemplo no Visual Studio e, em seguida, abra o arquivo **Constants.cs**. Altere a cadeia de caracteres do**Locatário** para o valor do **ID de Directory (locatário)** que você copiou anteriormente. Da mesma forma, altere a cadeia de caracteres **ClientIdForAppAuthn** para o valor da **ID do aplicativo (cliente)** e altere a cadeia de caracteres **ClientSecret** para o valor de segredo do cliente.
97 |
98 | 8. Retorne para o centro de gerenciamento do Azure Active Directory. Selecione **permissões para API** e, em seguida, selecione **Adicionar uma permissão**. No painel que se abre, escolha **Microsoft Graph**e, em seguida, escolha **Permissões de aplicativo**.
99 |
100 | 9. Use a caixa de pesquisa **Selecionar permissões** para pesquisar as seguintes permissões: Directory.Read.All, Group.ReadWrite.All, Mail.Read, Mail.ReadWrite e User.Read.All. Marque a caixa de seleção para cada permissão á medida que elas forem aparecendo (observe que as permissões vão desaparecendo da lista ao se selecionar cada uma delas). Selecione o botão **Adicionar permissões** na parte inferior do painel.
101 |
102 | 10. Escolha o botão **Conceder consentimento de administrador para \[nome do locatário]**. Marque **Sim** para a confirmação exibida.
103 |
104 | ## Criar e executar o exemplo
105 |
106 | 1. Abra a solução de exemplo no Visual Studio.
107 | 2. Pressione F5 para criar e executar o exemplo. Isso restaurará as dependências do pacote NuGet e abrirá o aplicativo de console.
108 | 3. Selecione o Modo de usuário para executar o aplicativo somente com **permissões delegadas**. Selecione o Modo de aplicativo para executar o aplicativo somente com **permissões de aplicativo**. Selecione ambos os modos para executar usando os dois tipos de permissões.
109 | 4. Ao executar o Modo de usuário, você será solicitado a entrar com uma conta do seu locatário do Office 365 e concordar com as permissões que o aplicativo solicitar. Se desejar executar as operações relacionadas a grupos da classe **UserMode**, você precisará remover o comentário do método **GetDetailsForGroups** no arquivo UserMode.cs e o escopo **Group.Read.All**no arquivo AuthenticationHelper.cs. Após fazer essas alterações, somente um administrador poderá entrar e dar consentimentos. Caso contrário, você pode entrar e concordar com um usuário não administrador.
110 | 5. Ao executar o Modo de aplicativo, o aplicativo começará a executar várias tarefas comuns relacionadas a grupos que somente um administrador pode fazer. Como você já autorizou o aplicativo a fazer essas operações, não será pedido para entrar e consentir.
111 |
112 | ## Perguntas e comentários
113 |
114 | Gostaríamos muito de saber sua opinião sobre ao Aplicativo de Console da API do Microsoft Graph. Você pode enviar perguntas e sugestões na seção [Problemas](https://github.com/microsoftgraph/console-csharp-snippets-sample/issues) deste repositório.
115 |
116 | As perguntas sobre o desenvolvimento do Microsoft Graph em geral devem ser postadas no [Stack Overflow](https://stackoverflow.com/questions/tagged/microsoftgraph). Não deixe de marcar as perguntas ou comentários com a tag \[microsoftgraph].
117 |
118 | ## Colaboração
119 |
120 | Se quiser contribuir para esse exemplo, confira [CONTRIBUTING.MD](/CONTRIBUTING.md).
121 |
122 | Este projeto adotou o [Código de Conduta de Código Aberto da Microsoft](https://opensource.microsoft.com/codeofconduct/). Para saber mais, confira as [Perguntas frequentes sobre o Código de Conduta](https://opensource.microsoft.com/codeofconduct/faq/) ou entre em contato pelo [opencode@microsoft.com](mailto:opencode@microsoft.com) se tiver outras dúvidas ou comentários.
123 |
124 | ## Recursos adicionais
125 |
126 | * [Obter acesso sem um usuário](https://docs.microsoft.com/en-us/graph/auth-v2-service)
127 | * [Permissões delegadas, Permissões de aplicativo e permissões efetivas](https://docs.microsoft.com/en-us/graph/permissions-reference#delegated-permissions-application-permissions-and-effective-permissions)
128 | * [Microsoft Graph](https://developer.microsoft.com/en-us/graph)
129 |
130 | ## Direitos autorais
131 |
132 | Copyright (c) 2017 Microsoft. Todos os direitos reservados.
133 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contribute to this code sample
2 |
3 | Thank you for your interest in our sample
4 |
5 | * [Ways to contribute](#ways-to-contribute)
6 | * [To contribute using Git](#To-contribute-using-Git)
7 | * [Contribute code](#Contribute-code)
8 | * [FAQ](#faq)
9 | * [More resources](#more-resources)
10 |
11 | ## Ways to contribute
12 |
13 | Here are some ways you can contribute to this sample:
14 |
15 | * Add better comments to the sample code.
16 | * Fix issues opened in GitHub against this sample.
17 | * Add a new feature to the sample.
18 |
19 | We want your contributions. Help the developer community by improving this sample.
20 | Contributions can include Bug fixes, new features, and better code documentation.
21 | Submit code comment contributions where you want a better explanation of what's going on.
22 | See a good example of [code commenting](https://github.com/OfficeDev/O365-Android-Microsoft-Graph-Connect/blob/master/app/src/main/java/com/microsoft/office365/connectmicrosoftgraph/AuthenticationManager.java).
23 |
24 | Another great way to improve the sample in this repository is to take on some of the open issues filed against the repository. You may have a solution to an bug in the sample code that hasn't been addressed. Fix the issue and then create a pull request following our [Contribute code](#Contribute-code) guidance.
25 |
26 | If you want to add a new feature to the sample, be sure you have the agreement of the repository owner before writing the code. Start by opening an issue in the repository. Use the new issue to propose the feature. The repository owner will respond and will usually ask you for more information. When the owner agrees to take the new feature, code it and submit a pull request.
27 |
28 | ## To contribute using Git
29 | For most contributions, you'll be asked to sign a Contribution License Agreement (CLA). For those contributions that need it, The Office 365 organization on GitHub will send a link to the CLA that we want you to sign via email.
30 | By signing the CLA, you acknowledge the rights of the GitHub community to use any code that you submit. The intellectual property represented by the code contribution is licensed for use by Microsoft open source projects.
31 |
32 | If Office 365 emails an CLA to you, you need to sign it before you can contribute large submissions to a project. You only need to complete and submit it once.
33 | Read the CLA carefully. You may need to have your employer sign it.
34 |
35 | Signing the CLA does not grant you rights to commit to the main repository, but it does mean that the Office Developer and Office Developer Content Publishing teams will be able to review and approve your contributions. You will be credited for your submissions.
36 |
37 | Pull requests are typically reviewed within 10 business days.
38 |
39 | ## Contribute code
40 |
41 | To make the contribution process as seamless as possible, follow these steps.
42 |
43 | ### To contribute code
44 |
45 | 1. Create a new branch.
46 | 2. Add new code or modify existing code.
47 | 3. Submit a pull request to the main repository.
48 | 4. Await notification of acceptance and merge.
49 | 5. Delete the branch.
50 |
51 |
52 | ### To create a new branch
53 |
54 | 1. Open Git Bash.
55 | 2. At the Git Bash command prompt, type `git pull upstream master:`. This creates a new branch locally that is copied from the latest OfficeDev master branch.
56 | 3. At the Git Bash command prompt, type `git push origin `. This alerts GitHub to the new branch. You should now see the new branch in your fork of the repository on GitHub.
57 | 4. At the Git Bash command prompt, type `git checkout ` to switch to your new branch.
58 |
59 | ### Add new code or modify existing code
60 |
61 | Navigate to the repository on your computer. On a Windows PC, the repository files are in `C:\Users\\`.
62 |
63 | Use the IDE of your choice to modify and build the sample. Once you have completed your change, commented your code, and run your unit tests, check the code
64 | into the remote branch on GitHub. Be sure to check in any unit tests you've written.
65 |
66 | #### Code contribution checklist
67 | Be sure to satisfy all of the requirements in the following list before submitting a pull request:
68 | - Follow the code style found in the cloned repository code. Our Android code follows the style conventions found in the [Code Style for Contributors](https://source.android.com/source/code-style.html) guide.
69 | - Code must be unit tested. Include the unit tests in the pull request.
70 | - Test the sample UI thoroughly to be sure nothing has been broken by your change.
71 | - Keep the size of your code change reasonable. if the repository owner cannot review your code change in 4 hours or less, your pull request may not be reviewed and approved quickly.
72 | - Avoid unnecessary changes to cloned or forked code. The reviewer will use a tool to find the differences between your code and the original code. Whitespace changes are called out along with your code. Be sure your changes will help improve the content.
73 |
74 | ### Push your code to the remote GitHub branch
75 | The files in `C:\Users\\` are a working copy of the new branch that you created in your local repository. Changing anything in this folder doesn't affect the local repository until you commit a change. To commit a change to the local repository, type the following commands in GitBash:
76 |
77 | git add .
78 | git commit -v -a -m ""
79 |
80 | The `add` command adds your changes to a staging area in preparation for committing them to the repository. The period after the `add` command specifies that you want to stage all of the files that you added or modified, checking subfolders recursively. (If you don't want to commit all of the changes, you can add specific files. You can also undo a commit. For help, type `git add -help` or `git status`.)
81 |
82 | The `commit` command applies the staged changes to the repository. The switch `-m` means you are providing the commit comment in the command line. The -v and -a switches can be omitted. The -v switch is for verbose output from the command, and -a does what you already did with the add command.
83 |
84 | You can commit multiple times while you are doing your work, or you can commit once when you're done.
85 |
86 | ### Submit a pull request to the master repository
87 |
88 | When you're finished with your work and are ready to have it merged into the master repository, follow these steps.
89 |
90 | #### To submit a pull request to the master repository
91 |
92 | 1. In the Git Bash command prompt, type `git push origin `. In your local repository, `origin` refers to your GitHub repository that you cloned the local repository from. This command pushes the current state of your new branch, including all commits made in the previous steps, to your GitHub fork.
93 | 2. On the GitHub site, navigate in your fork to the new branch.
94 | 3. Choose the **Pull Request** button at the top of the page.
95 | 4. Verify the Base branch is `OfficeDev/@master` and the Head branch is `/@`.
96 | 5. Choose the **Update Commit Range** button.
97 | 6. Add a title to your pull request, and describe all the changes you're making.
98 | 7. Submit the pull request.
99 |
100 | One of the site administrators will process your pull request. Your pull request will surface on the `OfficeDev/` site under Issues. When the pull request is accepted, the issue will be resolved.
101 |
102 | ### Repository owner code review
103 | The owner of the repository will review your pull request to be sure that all requirements are met. If the reviewer
104 | finds any issues, she will communicate with you and ask you to address them and then submit a new pull request. If your pull
105 | request is accepted, then the repository owner will tell you that your pull request is to be merged.
106 |
107 | ### Create a new branch after merge
108 |
109 | After a branch is successfully merged (that is, your pull request is accepted), don't continue working in that local branch. This can lead to merge conflicts if you submit another pull request. To do another update, create a new local branch from the successfully merged upstream branch, and then delete your initial local branch.
110 |
111 | For example, if your local branch X was successfully merged into the OfficeDev/O365-Android-Microsoft-Graph-Connect master branch and you want to make additional updates to the code that was merged. Create a new local branch, X2, from the OfficeDev/O365-Android-Microsoft-Graph-Connect branch. To do this, open GitBash and execute the following commands:
112 |
113 | cd microsoft-graph-docs
114 | git pull upstream master:X2
115 | git push origin X2
116 |
117 | You now have local copies (in a new local branch) of the work that you submitted in branch X. The X2 branch also contains all the work other developers have merged, so if your work depends on others' work (for example, a base class), it is available in the new branch. You can verify that your previous work (and others' work) is in the branch by checking out the new branch...
118 |
119 | git checkout X2
120 |
121 | ...and verifying the code. (The `checkout` command updates the files in `C:\Users\\O365-Android-Microsoft-Graph-Connect` to the current state of the X2 branch.) Once you check out the new branch, you can make updates to the code and commit them as usual. However, to avoid working in the merged branch (X) by mistake, it's best to delete it (see the following **Delete a branch** section).
122 |
123 | ### Delete a branch
124 |
125 | Once your changes are successfully merged into the main repository, delete the branch you used because you no longer need it. Any additional work should be done in a new branch.
126 |
127 | #### To delete a branch
128 |
129 | 1. In the Git Bash command prompt, type `git checkout master`. This ensures that you aren't in the branch to be deleted (which isn't allowed).
130 | 2. Next, at the command prompt, type `git branch -d `. This deletes the branch on your computer only if it has been successfully merged to the upstream repository. (You can override this behavior with the `–D` flag, but first be sure you want to do this.)
131 | 3. Finally, type `git push origin :` at the command prompt (a space before the colon and no space after it). This will delete the branch on your github fork.
132 |
133 | Congratulations, you have successfully contributed to the sample app!
134 |
135 |
136 | ## FAQ
137 |
138 | ### How do I get a GitHub account?
139 |
140 | Fill out the form at [Join GitHub](https://github.com/join) to open a free GitHub account.
141 |
142 | ### Where do I get a Contributor's License Agreement?
143 |
144 | You will automatically be sent a notice that you need to sign the Contributor's License Agreement (CLA) if your pull request requires one.
145 |
146 | As a community member, **you must sign the CLA before you can contribute large submissions to this project**. You only need complete and submit the CLA document once. Carefully review the document. You may be required to have your employer sign the document.
147 |
148 | ### What happens with my contributions?
149 |
150 | When you submit your changes, via a pull request, our team will be notified and will review your pull request. You will receive notifications about your pull request from GitHub; you may also be notified by someone from our team if we need more information. If your pull request is approved, we'll update the documentation on GitHub and on MSDN. We reserve the right to edit your submission for legal, style, clarity, or other issues.
151 |
152 | ### Who approves pull requests?
153 |
154 | The owner of the sample repository approves pull requests.
155 |
156 | ### How soon will I get a response about my change request?
157 |
158 | Pull requests are typically reviewed within 10 business days.
159 |
160 |
161 | ## More resources
162 |
163 | * For more information about Markdown, go to the Git creator's site [Daring Fireball].
164 | * For more information about using Git and GitHub, first check out the [GitHub Help section] [GitHub Help] and, if necessary, contact the site administrators.
165 |
166 | [GitHub Home]: http://github.com
167 | [GitHub Help]: http://help.github.com/
168 | [Set Up Git]: http://help.github.com/win-set-up-git/
169 | [Markdown Home]: http://daringfireball.net/projects/markdown/
170 | [Markdown Pad]: http://markdownpad.com/
171 | [OfficeDev/microsoft-graph-docs issues]: https://github.com/OfficeDev/microsoft-graph-docs/issues
172 | [Daring Fireball]: http://daringfireball.net/
173 |
--------------------------------------------------------------------------------
/README-localized/README-es-es.md:
--------------------------------------------------------------------------------
1 | ---
2 | page_type: sample
3 | products:
4 | - ms-graph
5 | languages:
6 | - csharp
7 | description: "Esta aplicación de consola de Windows muestra cómo realizar diversas tareas con permisos delegados y de aplicación en la Biblioteca cliente de Microsoft Graph. Este ejemplo utiliza la biblioteca de autenticación de Microsoft (MSAL) para la autenticación en el extremo de Azure AD v2.0."
8 | extensions:
9 | contentType: samples
10 | technologies:
11 | - Microsoft Graph
12 | - Microsoft identity platform
13 | services:
14 | - Microsoft identity platform
15 | createdDate: 9/8/2017 1:33:44 PM
16 | ---
17 | # Aplicación de fragmentos de consola para Microsoft Graph y C#
18 |
19 | ## Tabla de contenido
20 |
21 | * [Introducción](#introduction)
22 | * [Requisitos previos](#prerequisites)
23 | * [Registrar los **permisos delegados de** la aplicación](#Register-the-delegated-permissions-application )
24 | * [Registrar los **permisos de aplicación** de la aplicación](#Register-the-application-permissions-application )
25 | * [Compilar y ejecutar el ejemplo](#build-and-run-the-sample)
26 | * [Preguntas y comentarios](#questions-and-comments)
27 | * [Colaboradores](#contributing)
28 | * [Recursos adicionales](#additional-resources)
29 |
30 | ## Introducción
31 |
32 | Esta aplicación de ejemplo proporciona un repositorio de fragmentos de código que usa Microsoft Graph para realizar tareas comunes, como enviar correos electrónicos, administrar grupos y otras actividades desde una aplicación de consola de Windows. Usa el [SDK del cliente de Microsoft Graph .NET](https://github.com/microsoftgraph/msgraph-sdk-dotnet) para trabajar con los datos devueltos por Microsoft Graph.
33 |
34 | El ejemplo usa la biblioteca de autenticación de Microsoft (MSAL) para la autenticación. El ejemplo muestra tanto permisos delegados como de aplicación.
35 |
36 | Los **permisos delegados** se usan en las aplicaciones donde un usuario debe haber iniciado sesión. En estas aplicaciones, el usuario o un administrador dan su consentimiento a los permisos que solicita la aplicación, y se delega permiso a la aplicación para que actúe como usuario que ha iniciado sesión cuando se hacen llamadas a Microsoft Graph. En ocasiones, los usuarios no administrativos pueden recibir permisos delegados, pero existen permisos con privilegios mayores que requieren el consentimiento del administrador. Esta aplicación contiene algunas operaciones relacionadas con los grupos que requieren consentimiento administrativo. Los permisos asociados necesarios aparecen comentados de forma predeterminada.
37 |
38 | **Los permisos de la aplicación** se usan en aplicaciones que se ejecutan sin la presencia de un usuario que haya iniciado sesión. Puede usar este tipo de permisos para aplicaciones que se ejecutan como servicios en segundo plano o daemons y que, por lo tanto, no tendrán ni requerirán consentimiento por parte de los usuarios. Los permisos de aplicación solo pueden ser aceptados por un administrador de espacio empresarial. Tenga en cuenta que este ejemplo tiene mucho poder, al obtener consentimiento del administrador de TI. Por ejemplo, si ejecuta este ejemplo en **AppMode** en su espacio empresarial, creará un grupo, agregará y quitará a miembros del grupo y, a continuación, lo eliminará.
39 |
40 | Si desea usar ambos tipos de permisos, tendrá que crear y configurar dos aplicaciones en el [Centro de administración de Azure Active Directory](https://aad.portal.azure.com), una para **permisos delegados** y otra para **permisos de aplicación**. El ejemplo está estructurado para que solo pueda configurar una aplicación si está interesado en un solo tipo de permiso. Use la clase **UserMode** si solo le interesan **los permisos delegados** y la clase **AppMode** si le interesan **los permisos de aplicación**.
41 |
42 | Para obtener más información sobre estos tipos de permisos, vea [Permisos delegados, permisos de la aplicación y permisos efectivos](https://docs.microsoft.com/en-us/graph/permissions-reference#delegated-permissions-application-permissions-and-effective-permissions). Para obtener información más específica sobre los **permisos de aplicación**, vea [Obtener acceso sin un usuario](https://docs.microsoft.com/en-us/graph/auth-v2-service).
43 |
44 | ## Requisitos previos
45 |
46 | Este ejemplo necesita lo siguiente:
47 |
48 | * [Visual Studio](https://www.visualstudio.com/en-us/downloads)
49 |
50 | * Una cuenta de [Office 365 para Empresas.](https://msdn.microsoft.com/en-us/office/office365/howto/setup-development-environment#bk_Office365Account) Es necesaria una cuenta de administrador de Office 365 para ejecutar operaciones de nivel de administrador y autorizar los permisos de aplicación. Puede realizar [una suscripción a Office 365 Developer](https://msdn.microsoft.com/en-us/office/office365/howto/setup-development-environment#bk_Office365Account) que incluye los recursos que necesita para comenzar a crear aplicaciones.
51 |
52 | ## Registro de la aplicación
53 |
54 | En este ejemplo se usan permisos delegados y permisos de la aplicación, por lo que deberá registrar la aplicación por separado para cada escenario.
55 |
56 |
57 | ### Registrar los **permisos delegados** de la aplicación
58 |
59 | 1. Vaya al [Centro de administración de Azure Active Directory](https://aad.portal.azure.com). Inicie sesión con una **cuenta personal** (por ejemplo: una cuenta de Microsoft) o una **cuenta profesional o educativa**.
60 |
61 | 2. Seleccione **Azure Active Directory** en el panel de navegación izquierdo y, después, seleccione **Registros de aplicaciones (versión preliminar)** en **Administrar**.
62 |
63 | 3. Haga clic en **Nuevo registro**. En la página **Registrar una aplicación**, establezca los valores siguientes.
64 |
65 | * Establezca **Nombre** como `Ejemplo de fragmentos de la consola (permisos delegados)`.
66 | * Establezca **Tipos de cuenta admitidos** en **Cuentas en cualquier directorio de organización y cuentas personales de Microsoft**.
67 | * Deje vacía la opción de **URI de redirección**.
68 | **Seleccione **Registrar**.
69 |
70 | 4. En la página **Ejemplo de fragmentos de consola (permisos delegados)**, copie los valores de **Id. de aplicación (cliente)** e **Id. de directorio (espacio empresarial)**. Guarde estos dos valores, ya que los necesitará más adelante.
71 |
72 | 5. Haga clic en el vínculo **Agregar un URI de redirección**. En la página **URI de redirección**, localice la sección **URI de redirección sugeridos para clientes públicos (para dispositivos móviles o de escritorio)**. Seleccione el URI que comience por `msal` **y** el URI **urn:ietf:wg:oauth:2.0:oob**.
73 |
74 | 6. Abra la solución de ejemplo en Visual Studio y, a continuación, abra el archivo **Constants.cs**. Cambie la cadena de **Espacio empresarial** por el valor de la ID de directorio (espacio empresarial) que copió anteriormente. Cambie la cadena de ClientIdForUserAuthn por el **valor de la ID. de aplicación de (cliente) que copió antes**.
75 |
76 |
77 | ### Registrar los **permisos de aplicación** de la aplicación
78 |
79 | 1. Vaya al [Centro de administración de Azure Active Directory](https://aad.portal.azure.com). Inicie sesión con **una cuenta profesional o educativa**.
80 |
81 | 2. Seleccione **Azure Active Directory** en el panel de navegación izquierdo y, después, seleccione **Registros de aplicaciones (versión preliminar)** en **Administrar**.
82 |
83 | 3. Haga clic en **Nuevo registro**. En la página **Registrar una aplicación**, establezca los valores siguientes.
84 |
85 | * Establezca **Nombre** como `Ejemplo de fragmentos de la consola (permisos de aplicación)`.
86 | * Establezca **los tipos de cuenta compatibles** en las**cuentas en cualquier directorio de la organización**.
87 | * Deje vacía la opción de **URI de redirección**.
88 | * Elija **Registrar**.
89 |
90 | 4. En la página **Ejemplo de fragmentos de consola (permisos de aplicación)**, copie y guarde los valores de **Id. de aplicación (cliente)** e **Id. de directorio (espacio empresarial)**. Los necesitará más adelante en el paso 7.
91 |
92 | 5. Seleccione **Certificados y secretos** en **Administrar**. Seleccione el botón **Nuevo secreto de cliente**. Escriba un valor en **Descripción**, seleccione una opción para **Expira** y luego seleccione **Agregar**.
93 |
94 | 6. Copie el valor del secreto de cliente antes de salir de la página. Lo necesitará en el siguiente paso.
95 |
96 | 7. Abra la solución de ejemplo en Visual Studio y, a continuación, abra el archivo **Constants.cs**. Cambie la cadena de **Espacio empresarial** por el valor de la ID de directorio (espacio empresarial) que copió anteriormente. De forma similar, cambie la cadena de ClientIdForAppAuthn por el **valor identificador de la aplicación (cliente)** y cambie la cadena ClientSecret por el valor de secreto de cliente.
97 |
98 | 8. Volver al Centro de administración de Azure Active Directory Seleccione **Permisos de API** y después, seleccione **Agregar un permiso**. En el panel que se abre, elija **Microsoft Graph** y luego elija **Permisos de aplicación**.
99 |
100 | 9. Use el cuadro de búsqueda **Seleccionar permisos** para buscar los siguientes permisos: Directory.Read.All, Group.ReadWrite.All, Mail.Read, Mail.ReadWrite y User.Read.All. Seleccione la casilla de verificación para cada permiso a medida que aparece (tenga en cuenta que los permisos no permanecerán visibles en la lista al seleccionar cada uno). Seleccione el botón **Agregar permisos** de la parte inferior del cuadro de diálogo.
101 |
102 | 10. Elija el botón **Conceder permisos de administrador para \[nombre del espacio empresarial]**. Seleccione **Sí** para la confirmación que aparece.
103 |
104 | ## Compilar y ejecutar el ejemplo
105 |
106 | 1. Abra la solución del ejemplo en Visual Studio.
107 | 2. Pulse F5 para compilar y ejecutar el ejemplo. Esto restaurará las dependencias del paquete de NuGet y abrirá la aplicación de la consola.
108 | 3. Seleccione el modo de usuario para ejecutar la aplicación con solo **permisos delegados**. Seleccione el modo de aplicación para ejecutar la aplicación con solo **permisos de aplicación**. Seleccione ambos para ejecutar con ambos tipos de permisos.
109 | 4. Cuando ejecute el modo de usuario, se le pedirá que inicie sesión con una cuenta en su espacio empresarial de Office 365 y que autorice los permisos que la aplicación solicita. Si desea ejecutar las operaciones relacionadas con los grupos en la clase **UserMode**, tendrá que hacer que el código de GetDetailsForGroups en el archivo UserMode.cs y el ámbito Group.Read.All en el archivo AuthenticationHelper.cs no aparezcan como comentarios. Cuando haga estos cambios, solo un administrador podrá iniciar sesión y autorizar. De otro modo, tendrá que iniciar sesión y conceder permisos a un usuario que no sea administrador.
110 | 5. Cuando ejecute el modo de aplicación, la aplicación empezará a llevar a cabo una serie de tareas comunes relacionadas con los grupos que solo puede ejecutar un administrador. Como ya autorizó a la aplicación a que realice estas operaciones, no se le pedirá que inicie sesión y autorice.
111 |
112 | ## Preguntas y comentarios
113 |
114 | Nos encantaría recibir sus comentarios acerca de la aplicación de consola para la API de Microsoft Graph. Puede enviar sus preguntas y sugerencias en la sección de [Problemas](https://github.com/microsoftgraph/console-csharp-snippets-sample/issues) de este repositorio.
115 |
116 | Las preguntas sobre el desarrollo de Microsoft Graph en general deben enviarse a [Stack Overflow](https://stackoverflow.com/questions/tagged/microsoftgraph). Asegúrese de que sus preguntas o comentarios estén etiquetados con \[microsoftgraph].
117 |
118 | ## Colaboradores
119 |
120 | Si quiere hacer su aportación a este ejemplo, vea [CONTRIBUTING.MD](/CONTRIBUTING.md).
121 |
122 | Este proyecto ha adoptado el [Código de conducta de código abierto de Microsoft](https://opensource.microsoft.com/codeofconduct/). Para obtener más información, vea [Preguntas frecuentes sobre el código de conducta](https://opensource.microsoft.com/codeofconduct/faq/) o póngase en contacto con [opencode@microsoft.com](mailto:opencode@microsoft.com) si tiene otras preguntas o comentarios.
123 |
124 | ## Recursos adicionales
125 |
126 | * [Obtener acceso sin un usuario](https://docs.microsoft.com/en-us/graph/auth-v2-service)
127 | * [Permisos delegados, permisos de la aplicación y permisos efectivos](https://docs.microsoft.com/en-us/graph/permissions-reference#delegated-permissions-application-permissions-and-effective-permissions)
128 | * [Microsoft Graph](https://developer.microsoft.com/en-us/graph)
129 |
130 | ## Derechos de autor
131 |
132 | Copyright (c) 2017 Microsoft. Todos los derechos reservados.
133 |
--------------------------------------------------------------------------------
/README-localized/README-fr-fr.md:
--------------------------------------------------------------------------------
1 | ---
2 | page_type: sample
3 | products:
4 | - ms-graph
5 | languages:
6 | - csharp
7 | description: "Cette application de console Windows montre comment effectuer diverses opérations à l’aide de la bibliothèque cliente Microsoft Graph avec des autorisations d’application et des autorisations déléguées. Cet exemple utilise la Bibliothèque d'authentification Microsoft (MSAL) pour l’authentification sur le point de terminaison Azure AD v2.0."
8 | extensions:
9 | contentType: samples
10 | technologies:
11 | - Microsoft Graph
12 | - Microsoft identity platform
13 | services:
14 | - Microsoft identity platform
15 | createdDate: 9/8/2017 1:33:44 PM
16 | ---
17 | # Microsoft Graph C# : extraits de console de l'application
18 |
19 | ## Table des matières
20 |
21 | * [Introduction](#introduction)
22 | * [Conditions préalables](#prerequisites)
23 | * [Inscrire les **autorisations déléguées** de l'application](#Register-the-delegated-permissions-application )
24 | * [Inscrire les **autorisations d'application** de l'application](#Register-the-application-permissions-application )
25 | * [Créer et exécuter l’exemple](#build-and-run-the-sample)
26 | * [Questions et commentaires](#questions-and-comments)
27 | * [Contribution](#contributing)
28 | * [Ressources supplémentaires](#additional-resources)
29 |
30 | ## Introduction
31 |
32 | Cet exemple d'application constitue un référentiel des extraits de code qui utilisent Microsoft Graph pour effectuer des tâches courantes, telles que l’envoi de messages électroniques, la gestion de groupes et d’autres activités au sein d’une application de console Windows. Il utilise le [Kit de développement logiciel Microsoft Graph .NET Client](https://github.com/microsoftgraph/msgraph-sdk-dotnet) pour travailler avec les données renvoyées par Microsoft Graph.
33 |
34 | L’exemple utilise la Bibliothèque d’authentification Microsoft (MSAL) pour l’authentification. L’exemple illustre des autorisations déléguées et des autorisations d’application.
35 |
36 | Les **Autorisations déléguées** sont utilisées par les applications qui ont un utilisateur connecté présent. Pour ces applications, l’utilisateur ou un administrateur accepte les autorisations demandées par l’application et cette dernière obtient l’autorisation déléguée pour agir en tant qu’utilisateur connecté lors d'appels vers Microsoft Graph. Certaines autorisations déléguées peuvent être consenties par des utilisateurs non administrateurs, mais certaines autorisations ayant des privilèges plus élevés nécessitent le consentement de l’administrateur. Cette application inclut certaines opérations liées aux groupes nécessitant un consentement administratif et les autorisations associées requises pour les effectuer sont commentées par défaut.
37 |
38 | Les **Autorisations d’application** sont utilisées par des applications qui s’exécutent sans la présence d'une connexion utilisateur. Vous pouvez utiliser ce type d’autorisation pour des applications s'exécutant en tant que services en arrière-plan et qui, par conséquent, n’ont pas et n'exigent pas l'accord de l'utilisateur. Les autorisations d’application peuvent uniquement être accordées par un administrateur client. Il est important de prendre conscience que vous donnez beaucoup de pouvoir à cet échantillon en lui octroyant un accord de l’administrateur informatique. Par exemple, si vous exécutez cet exemple dans **AppMode** chez votre client, vous créez un groupe, ajoutez, puis supprimez des membres du groupe, et supprimez ensuite ce groupe.
39 |
40 | Si vous souhaitez utiliser ces deux types d’autorisations, vous devez créer et configurer deux applications dans le [Centre d'administration Azure Active Directory](https://aad.portal.azure.com), une pour les **autorisations déléguées** et une autre pour les **autorisations d’application**. L’exemple est organisé de sorte que vous ne puissiez configurer qu’une seule application si vous n’avez besoin que d’un type d’autorisation. Utilisez la classe **UserMode** si vous êtes uniquement intéressé par les **autorisation déléguées** et la classe **AppMode** si vous êtes seulement intéressé par les **autorisations d’application**.
41 |
42 | Pour plus d’informations sur ces types d'autorisation, reportez-vous aux [Autorisations déléguées, autorisations de l’application et aux autorisations effectives](https://docs.microsoft.com/en-us/graph/permissions-reference#delegated-permissions-application-permissions-and-effective-permissions). Consultez également [Obtenir un accès sans utilisateur](https://docs.microsoft.com/en-us/graph/auth-v2-service) pour plus d'informations spécifiques sur les **autorisations d'application**.
43 |
44 | ## Conditions préalables
45 |
46 | Cet exemple nécessite les éléments suivants :
47 |
48 | * [Visual Studio](https://www.visualstudio.com/en-us/downloads)
49 |
50 | * Un [compte professionnel Office 365](https://msdn.microsoft.com/en-us/office/office365/howto/setup-development-environment#bk_Office365Account). Un compte d’administrateur Office 365 est obligatoire pour exécuter des opérations de niveau administrateur et pour accorder des autorisations d'applications. Vous pouvez souscrire un [ abonnement pour développeur Office 365](https://msdn.microsoft.com/en-us/office/office365/howto/setup-development-environment#bk_Office365Account) incluant les ressources dont vous avez besoin pour commencer à créer des applications.
51 |
52 | ## Inscription de l’application
53 |
54 | Cet exemple comprend des exemples qui utilisent les autorisations déléguées et les autorisations d’application, vous devez donc inscrire l’application séparément pour chaque scénario.
55 |
56 |
57 | ### Inscription des **autorisations déléguées** de l'application
58 |
59 | 1. Accédez au [Centre d’administration Azure Active Directory](https://aad.portal.azure.com). Connectez-vous à l’aide d’un **compte personnel** (alias : compte Microsoft) ou d’un **compte professionnel ou scolaire**.
60 |
61 | 2. Sélectionnez **Azure Active Directory** dans le volet de navigation gauche, puis sélectionnez **Inscriptions d’applications (préversion)** sous **Gérer**.
62 |
63 | 3. Sélectionnez **Nouvelle inscription**. Sur la page **Inscrire une application**, définissez les valeurs comme suit.
64 |
65 | * Définissez le **Nom** pour l'`Exemple des extraits de console (autorisations déléguées)`.
66 | * Définissez les **Types de comptes pris en charge** sur les **Comptes figurant dans un annuaire organisationnel et comptes Microsoft personnels**.
67 | * Laissez **Redirect URI** vide.
68 | ** Choisissez **Inscrire**.
69 |
70 | 4. Sur la page **Exemple d'extraits de console (autorisations déléguées)**, copiez les valeurs de l' **ID d’application (client)** et de l'**ID Directory (locataire)**. Enregistrez ces deux valeurs, car vous en aurez besoin plus tard.
71 |
72 | 5. Sélectionnez le lien **Ajouter un URI de redirection**. Dans la page **URI de redirection** Recherchez la section des **URI de redirection suggérés pour les clients publics (mobile, bureau)**. Sélectionnez l’URI commençant par `msal` **et** l’URI **urn:ietf:wg:oauth:2.0:oob**.
73 |
74 | 6. Ouvrez la solution d'exemple dans Visual Studio, puis ouvrez le fichier **Constants.cs**. Remplacez la chaîne **Client **par la valeur d'**ID de Directory (locataire)** que vous avez précédemment copiée. Remplacez la chaîne **ClientIdForUserAuthn** par la valeur de l'**ID de l’application (client)**.
75 |
76 |
77 | ### Enregistrer les **Autorisations d'application** de l'application
78 |
79 | 1. Accédez au [Centre d’administration Azure Active Directory](https://aad.portal.azure.com). Connectez-vous en utilisant un **Compte professionnel ou scolaire**.
80 |
81 | 2. Sélectionnez **Azure Active Directory** dans le volet de navigation gauche, puis sélectionnez **Inscriptions d’applications (préversion)** sous **Gérer**.
82 |
83 | 3. Sélectionnez **Nouvelle inscription**. Sur la page **Inscrire une application**, définissez les valeurs comme suit.
84 |
85 | * Définissez le **Nom** pour l'`Exemple des extraits de console (autorisations d'application)`.
86 | * Définissez les **Types de comptes pris en charge** sur **Comptes figurant dans un annuaire organisationnel**.
87 | * Laissez **Redirect URI** vide.
88 | * Choisissez **Inscrire**.
89 |
90 | 4. Sur la page **Exemple d'extraits de console (autorisations d'applications)**, copiez et enregistrez les valeurs de l'**ID d’application (client)** et de l'**ID Directory (locataire)**. Vous en aurez besoin lors de l'étape 7.
91 |
92 | 5. Sélectionnez **Certificats & secrets** sous **Gérer**. Sélectionnez le bouton **Nouvelle clé secrète client**. Entrez une valeur dans la **Description**, sélectionnez une option pour **Expire le**, puis choisissez **Ajouter**.
93 |
94 | 6. Copiez la valeur de la clé secrète client avant de quitter cette page. Vous en aurez besoin à l’étape suivante.
95 |
96 | 7. Ouvrez la solution d'exemple dans Visual Studio, puis ouvrez le fichier **Constants.cs**. Remplacez la chaîne **Client **par la valeur d'**ID de Directory (locataire)** que vous avez précédemment copiée. De la même façon, remplacez la chaîne de **ClientIdForAppAuthn** par la valeur de l'**ID de l’application (client)** et remplacez la chaîne **ClientSecret** par la valeur de la clé secrète cliente.
97 |
98 | 8. Retournez au Portail de gestion Azure Active Directory. Sélectionnez **Autorisations API**, puis sélectionnez **Ajouter une autorisation**. Dans le volet qui apparaît, sélectionnez **Microsoft Graph**, puis choisissez **Autorisations d'application**.
99 |
100 | 9. Utilisez la zone de recherche **Sélectionnez les autorisations** pour trouver les autorisations qui suivent : Directory.Read.All, Group.ReadWrite.All, Mail.Read, Mail.ReadWrite, and User.Read.All. Sélectionnez la case à cocher pour chacune des autorisations lorsqu'elle apparaît (veuillez noter que les autorisations ne restent pas visibles dans la liste lorsque vous les sélectionnez). Sélectionner le bouton **Ajouter des autorisations** en bas de la boîte de dialogue.
101 |
102 | 10. Sélectionnez le bouton **Accorder l’autorisation administrateur pour \[nom du client]**. Sélectionnez **Oui** pour confirmer ce qui s’affiche.
103 |
104 | ## Créer et exécuter l’exemple
105 |
106 | 1. Ouvrez l’exemple de solution dans Visual Studio.
107 | 2. Appuyez sur F5 pour créer et exécuter l’exemple. Cela entraîne la restauration des dépendances du package NuGet et l’ouverture de l’application de la console.
108 | 3. Sélectionnez le mode Utilisateur pour exécuter l’application avec les **autorisations déléguées** uniquement. Sélectionnez le mode Application pour exécuter l’application avec les **autorisations d'application** uniquement. Sélectionnez les deux types d'autorisations pour les exécuter.
109 | 4. Lorsque vous exécutez le mode Utilisateur, vous êtes invité à vous connecter à l’aide d’un compte de votre client Office 365 et à accepter les autorisations exigées par l’application. Si vous voulez exécuter des opérations liées à des groupes dans la classe **UserMode**, vous devez supprimer les marques de commentaire de la méthode **GetDetailsForGroups** dans le fichier UserMode.cs et l'étendue **Group.Read.All** dans le fichier AuthenticationHelper.cs. Une fois que ces modifications sont effectuées, seul un administrateur pourra se connecter et donner son accord. Dans le cas contraire, vous pouvez vous connecter et donner votre consentement avec un utilisateur non-administrateur.
110 | 5. Lorsque vous exécutez le mode Application, celle-ci commence à effectuer un certain nombre de tâches courantes relatives à des groupes que seul un administrateur peut effectuer. Puisque vous avez déjà autorisé l’application à effectuer ces opérations, vous n’êtes pas invité à vous connecter et à donner votre accord.
111 |
112 | ## Questions et commentaires
113 |
114 | Nous serions ravis de connaître votre opinion sur l'application de console API Microsoft Graph. Vous pouvez nous faire part de vos questions et suggestions dans la rubrique [Problèmes](https://github.com/microsoftgraph/console-csharp-snippets-sample/issues) de ce référentiel.
115 |
116 | Les questions générales sur le développement de Microsoft Graph doivent être publiées sur [Stack Overflow](https://stackoverflow.com/questions/tagged/microsoftgraph). Veillez à poser vos questions ou à rédiger vos commentaires en utilisant la balise \[microsoftgraph].
117 |
118 | ## Contribution
119 |
120 | Si vous souhaitez contribuer à cet exemple, voir [CONTRIBUTING.MD](/CONTRIBUTING.md).
121 |
122 | Ce projet a adopté le [code de conduite Open Source de Microsoft](https://opensource.microsoft.com/codeofconduct/). Pour en savoir plus, reportez-vous à la [FAQ relative au code de conduite](https://opensource.microsoft.com/codeofconduct/faq/) ou contactez [opencode@microsoft.com](mailto:opencode@microsoft.com) pour toute question ou tout commentaire.
123 |
124 | ## Ressources supplémentaires
125 |
126 | * [Obtenir l’accès sans utilisateur](https://docs.microsoft.com/en-us/graph/auth-v2-service)
127 | * [Autorisations déléguées, autorisations de l’application et autorisations effectives](https://docs.microsoft.com/en-us/graph/permissions-reference#delegated-permissions-application-permissions-and-effective-permissions)
128 | * [Microsoft Graph](https://developer.microsoft.com/en-us/graph)
129 |
130 | ## Copyright
131 |
132 | Copyright (c) 2017 Microsoft. Tous droits réservés.
133 |
--------------------------------------------------------------------------------
/console-csharp-snippets-sample/AppMode.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 | using Microsoft.Graph;
7 |
8 | namespace console_csharp_snippets_sample
9 | {
10 | internal class AppMode
11 | {
12 | public static GraphServiceClient client;
13 | public static void AppModeRequests()
14 | {
15 | try
16 | {
17 | //*********************************************************************
18 | // setup Microsoft Graph Client for app-only.
19 | //*********************************************************************
20 | if (Constants.ClientIdForAppAuthn != "ENTER_YOUR_APP_ONLY_CLIENT_ID" &&
21 | Constants.Tenant != "ENTER_YOUR_TENANT_NAME" &&
22 | Constants.ClientSecret!= "ENTER_YOUR_CLIENT_SECRET" )
23 | {
24 | client = AuthenticationHelper.GetAuthenticatedClientForApp();
25 | }
26 | else
27 | {
28 | Console.ForegroundColor = ConsoleColor.Red;
29 | Console.WriteLine("You haven't configured a value for ClientIdForAppAuthn, Tenant, and/or ClientSecret in Constants.cs. Please follow the Readme instructions for configuring this application.");
30 | Console.ResetColor();
31 | Console.ReadKey();
32 | return;
33 | }
34 |
35 |
36 | }
37 | catch (Exception ex)
38 | {
39 | Console.ForegroundColor = ConsoleColor.Red;
40 | Console.WriteLine("Acquiring a token failed with the following error: {0}", ex.Message);
41 | if (ex.InnerException != null)
42 | {
43 | //You should implement retry and back-off logic per the guidance given here:http://msdn.microsoft.com/en-us/library/dn168916.aspx
44 | //InnerException Message will contain the HTTP error status codes mentioned in the link above
45 | Console.WriteLine("Error detail: {0}", ex.InnerException.Message);
46 | }
47 | Console.ResetColor();
48 | Console.ReadKey();
49 | return;
50 | }
51 |
52 | Console.WriteLine("\nStarting app-mode requests...");
53 | Console.WriteLine("\n=============================\n\n");
54 |
55 | // Get first page of users in a tenant
56 | try
57 | {
58 | IGraphServiceUsersCollectionPage users = client.Users.Request().GetAsync().Result;
59 | foreach (User user in users)
60 | {
61 | Console.WriteLine("Found user: " + user.Id);
62 | }
63 | }
64 |
65 | catch (Exception e)
66 | {
67 | Console.WriteLine("\nError getting users {0} {1}",
68 | e.Message, e.InnerException != null ? e.InnerException.Message : "");
69 | }
70 |
71 | // Get messages for a specific user (demonstrates $select operation)
72 | try
73 | {
74 | Console.WriteLine("\nEnter the email address of the user mailbox you want to retrieve:");
75 | String email = Console.ReadLine();
76 | List messages = client.Users[email].Messages.Request().Select("subject, receivedDateTime").GetAsync().Result.Take(3).ToList();
77 | if (messages.Count == 0)
78 | {
79 | Console.WriteLine(" no messages in mailbox");
80 | }
81 | foreach (Message message in messages)
82 | {
83 | Console.WriteLine(" Message: {0} received {1} ", message.Subject, message.ReceivedDateTime);
84 | }
85 | }
86 | catch (Exception e)
87 | {
88 | Console.WriteLine("\nError getting messages {0} {1}",
89 | e.Message, e.InnerException != null ? e.InnerException.Message : "");
90 | }
91 |
92 | // Get groups for a specific user
93 | try
94 | {
95 | Console.WriteLine("\nEnter the email address of the user whose groups you want to retrieve:");
96 | String email = Console.ReadLine();
97 |
98 | IUserMemberOfCollectionWithReferencesPage userGroups = client.Users[email].MemberOf.Request().GetAsync().Result;
99 |
100 | if (userGroups.Count == 0)
101 | {
102 | Console.WriteLine(" user is not a member of any groups");
103 | }
104 | foreach (DirectoryObject group in userGroups)
105 | {
106 | if (group is Group)
107 | {
108 | Group _group = group as Group;
109 | Console.WriteLine(" Id: {0} UPN: {1}", _group.Id, _group.DisplayName);
110 | }
111 | }
112 | }
113 |
114 | catch (Exception e)
115 | {
116 | Console.WriteLine("\nError getting group memberships {0} {1}",
117 | e.Message, e.InnerException != null ? e.InnerException.Message : "");
118 | }
119 |
120 | //*********************************************************************
121 | // People picker
122 | // Search for a user using text string and match against userPrincipalName, displayName, giveName, surname
123 | //*********************************************************************
124 | Console.WriteLine("\nSearch for user (enter search string):");
125 | String searchString = Console.ReadLine();
126 |
127 | IGraphServiceUsersCollectionPage userCollection = null;
128 | try
129 | {
130 | string startsWithFilter = "startswith(displayName%2C+ '"
131 | + searchString + "')+or+startswith(userPrincipalName%2C+ '"
132 | + searchString + "')+or+startswith(givenName%2C+ '"
133 | + searchString + "')+or+startswith(surname%2C+ '" + searchString + "')";
134 | userCollection = client.Users.Request().Filter(startsWithFilter).GetAsync().Result;
135 | }
136 | catch (Exception e)
137 | {
138 | Console.WriteLine("\nError getting User {0} {1}", e.Message,
139 | e.InnerException != null ? e.InnerException.Message : "");
140 | }
141 |
142 | if (userCollection != null && userCollection.Count > 0)
143 | {
144 |
145 | foreach (User u in userCollection)
146 | {
147 | Console.WriteLine("User: DisplayName: {0} UPN: {1}",
148 | u.DisplayName, u.UserPrincipalName);
149 | }
150 | }
151 | else
152 | {
153 | Console.WriteLine("User not found");
154 | }
155 |
156 |
157 | // Create a unified group
158 | Console.WriteLine("\nDo you want to create a new unified group? Click y/n\n");
159 | ConsoleKeyInfo key = Console.ReadKey();
160 | // We need two Group variables: one to pass to the AddAsync and another that stores the
161 | // created group returned by AddAsync(). The createdGroup variable will have a value for the Id
162 | // property. We'll need to use that value later.
163 | Group uGroup = null;
164 | Group createdGroup = null;
165 | if (key.KeyChar == 'y')
166 | {
167 | string suffix = GetRandomString(5);
168 | uGroup = new Group
169 | {
170 | GroupTypes = new List { "Unified" },
171 | DisplayName = "Unified group " + suffix,
172 | Description = "Group " + suffix + " is the best ever",
173 | MailNickname = "Group" + suffix,
174 | MailEnabled = true,
175 | SecurityEnabled = false
176 | };
177 | try
178 | {
179 | createdGroup = client.Groups.Request().AddAsync(uGroup).Result;
180 | Console.WriteLine("\nCreated unified group {0}", createdGroup.DisplayName);
181 | }
182 | catch (Exception)
183 | {
184 | Console.WriteLine("\nIssue creating the group {0}", uGroup.DisplayName);
185 | uGroup = null;
186 | }
187 | }
188 |
189 | // Add group members. If the user has chosen to create a group, use that one.
190 | // If the user has chosen not to create a group, find one in the tenant.
191 |
192 | Group groupToAddMembers = new Group();
193 | if (createdGroup != null)
194 | {
195 | groupToAddMembers = createdGroup;
196 | }
197 | else
198 | {
199 | string unifiedFilter = "groupTypes/any(gt:gt+eq+'Unified')";
200 | List unifiedGroups = client.Groups.Request().Filter(unifiedFilter).GetAsync().Result.Take(5).ToList();
201 | if (unifiedGroups != null && unifiedGroups.Count > 0)
202 | {
203 | groupToAddMembers = unifiedGroups.First();
204 | }
205 | }
206 |
207 | // Get a set of users to add
208 | List members = client.Users.Request().GetAsync().Result.Take(3).ToList();
209 |
210 | if (groupToAddMembers != null)
211 | {
212 | //Add users
213 | foreach (User user in members)
214 | {
215 | try
216 | {
217 | client.Groups[groupToAddMembers.Id].Members.References.Request().AddAsync(user);
218 | Console.WriteLine("\nAdding {0} to group {1}", user.UserPrincipalName, groupToAddMembers.DisplayName);
219 | }
220 |
221 | catch (Exception e)
222 | {
223 | Console.WriteLine("\nError assigning member to group. {0} {1}",
224 | e.Message, e.InnerException != null ? e.InnerException.Message : "");
225 | }
226 | }
227 |
228 | // Now remove the added users
229 | foreach (User user in members)
230 | {
231 | try
232 | {
233 | client.Groups[groupToAddMembers.Id].Members[user.Id].Reference.Request().DeleteAsync();
234 | Console.WriteLine("\nRemoved {0} from group {1}", user.UserPrincipalName, groupToAddMembers.DisplayName);
235 | }
236 | catch (Exception e)
237 | {
238 | Console.WriteLine("\nError removing member from group. {0} {1}",
239 | e.Message, e.InnerException != null ? e.InnerException.Message : "");
240 | }
241 | }
242 | }
243 |
244 | else
245 | {
246 | Console.WriteLine("\nCan't find any unified groups to add members to.\n");
247 | }
248 |
249 | // If we created a group, remove it.
250 | if (createdGroup != null)
251 | {
252 | try
253 | {
254 | client.Groups[createdGroup.Id].Request().DeleteAsync().Wait();
255 | Console.WriteLine("\nDeleted group {0}", createdGroup.DisplayName);
256 | }
257 | catch (Exception e)
258 | {
259 | Console.Write("Couldn't delete group. Error detail: {0}", e.InnerException.Message);
260 | }
261 | }
262 |
263 | // Get first five groups.
264 | try
265 | {
266 | List groups = client.Groups.Request().GetAsync().Result.Take(5).ToList();
267 |
268 | foreach (Group group in groups)
269 | {
270 | Console.WriteLine(" Group Id: {0} upn: {1}", group.Id, group.DisplayName);
271 | foreach (string type in group.GroupTypes)
272 | {
273 | if (type == "Unified")
274 | {
275 | Console.WriteLine(": This is a Unifed Group");
276 | }
277 | }
278 | }
279 | }
280 |
281 | catch (Exception e)
282 | {
283 | Console.Write("Couldn't get groups. Error detail: {0}", e.InnerException.Message);
284 | }
285 |
286 | }
287 |
288 |
289 | public static string GetRandomString(int length = 32)
290 | {
291 | //because GUID can't be longer than 32
292 | return Guid.NewGuid().ToString("N").Substring(0, length > 32 ? 32 : length);
293 | }
294 | }
295 | }
296 |
--------------------------------------------------------------------------------
/console-csharp-snippets-sample/UserMode.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IO;
4 | using System.Linq;
5 | using System.Text;
6 | using System.Threading.Tasks;
7 | using Microsoft.Graph;
8 |
9 | namespace console_csharp_snippets_sample
10 | {
11 | internal class UserMode
12 | {
13 | public static GraphServiceClient client;
14 | public static void UserModeRequests()
15 | {
16 | try
17 | {
18 | //*********************************************************************
19 | // setup Microsoft Graph Client for user.
20 | //*********************************************************************
21 | if (Constants.ClientIdForUserAuthn != "ENTER_YOUR_CLIENT_ID")
22 | {
23 | client = AuthenticationHelper.GetAuthenticatedClientForUser();
24 | }
25 | else
26 | {
27 | Console.ForegroundColor = ConsoleColor.Red;
28 | Console.WriteLine("You haven't configured a value for ClientIdForUserAuthn in Constants.cs. Please follow the Readme instructions for configuring this application.");
29 | Console.ResetColor();
30 | Console.ReadKey();
31 | return;
32 | }
33 |
34 |
35 | }
36 | catch (Exception ex)
37 | {
38 | Console.ForegroundColor = ConsoleColor.Red;
39 | Console.WriteLine("Acquiring a token failed with the following error: {0}", ex.Message);
40 | if (ex.InnerException != null)
41 | {
42 | //You should implement retry and back-off logic per the guidance given here:http://msdn.microsoft.com/en-us/library/dn168916.aspx
43 | //InnerException Message will contain the HTTP error status codes mentioned in the link above
44 | Console.WriteLine("Error detail: {0}", ex.InnerException.Message);
45 | }
46 | Console.ResetColor();
47 | Console.ReadKey();
48 | return;
49 | }
50 |
51 | Console.WriteLine("\nStarting user-mode requests...");
52 | Console.WriteLine("\n=============================\n\n");
53 |
54 | // GET current user
55 |
56 | try
57 | {
58 | User user = client.Me.Request().GetAsync().Result;
59 | Console.WriteLine("Current user: Id: {0} UPN: {1}", user.Id, user.UserPrincipalName);
60 | }
61 |
62 | catch (Exception e)
63 | {
64 | Console.WriteLine("\nError getting /me user {0} {1}",
65 | e.Message, e.InnerException != null ? e.InnerException.Message : "");
66 | }
67 |
68 | // Get current user photo (work or school accounts only). Returns an exception if no photo exists.
69 |
70 | try
71 | {
72 | Stream userPhoto = client.Me.Photo.Content.Request().GetAsync().Result;
73 | Console.WriteLine("Got stream photo");
74 | }
75 |
76 | catch (Exception e)
77 | {
78 | Console.WriteLine("\nError getting user photo {0} {1}",
79 | e.Message, e.InnerException != null ? e.InnerException.Message : "");
80 | }
81 |
82 | // Get current user's direct reports (work or school accounts only)
83 | try
84 | {
85 |
86 | IUserDirectReportsCollectionWithReferencesPage directReports = client.Me.DirectReports.Request().GetAsync().Result;
87 |
88 | if (directReports.Count == 0)
89 | {
90 | Console.WriteLine(" no reports");
91 | }
92 | else
93 | {
94 | foreach (User user in directReports)
95 | {
96 | Console.WriteLine(" Id: {0} UPN: {1}", user.Id, user.UserPrincipalName);
97 | }
98 | }
99 |
100 | }
101 |
102 | catch (Exception e)
103 | {
104 | Console.WriteLine("\nError getting directReports {0} {1}",
105 | e.Message, e.InnerException != null ? e.InnerException.Message : "");
106 | }
107 |
108 | // Get current user's manager (work or school accounts only). Returns an exception if no manager exists.
109 | try
110 | {
111 | DirectoryObject currentUserManager = client.Me.Manager.Request().GetAsync().Result;
112 |
113 | User user = client.Users[currentUserManager.Id].Request().GetAsync().Result;
114 | Console.WriteLine("\nManager Id: {0} UPN: {1}", user.Id, user.UserPrincipalName);
115 | }
116 |
117 | catch (Exception e)
118 | {
119 | Console.WriteLine("\nError getting manager {0} {1}",
120 | e.Message, e.InnerException != null ? e.InnerException.Message : "");
121 | }
122 |
123 | // Get current user's files
124 |
125 | try
126 | {
127 | List items = client.Me.Drive.Root.Children.Request().GetAsync().Result.Take(5).ToList();
128 |
129 | foreach (DriveItem item in items)
130 | {
131 |
132 | if (item.File != null)
133 | {
134 | Console.WriteLine(" This is a folder: Id: {0} WebUrl: {1}", item.Id, item.WebUrl);
135 | }
136 | else
137 | {
138 |
139 | Console.WriteLine(" File Id: {0} WebUrl: {1}", item.Id, item.WebUrl);
140 | }
141 | }
142 | }
143 |
144 | catch (Exception e)
145 | {
146 | Console.WriteLine("\nError getting files {0} {1}",
147 | e.Message, e.InnerException != null ? e.InnerException.Message : "");
148 | }
149 |
150 | // Get current user's messages
151 |
152 | try
153 | {
154 | List messages = client.Me.Messages.Request().GetAsync().Result.Take(5).ToList();
155 |
156 | if (messages.Count == 0)
157 | {
158 | Console.WriteLine(" no messages in mailbox");
159 | }
160 | foreach (Message message in messages)
161 | {
162 | Console.WriteLine(" Message: {0} received {1} ", message.Subject, message.ReceivedDateTime);
163 | }
164 | }
165 |
166 | catch (Exception e)
167 | {
168 | Console.WriteLine("\nError getting messages {0} {1}",
169 | e.Message, e.InnerException != null ? e.InnerException.Message : "");
170 | }
171 |
172 |
173 | // Get current user's events
174 | try
175 | {
176 | List events = client.Me.Events.Request().GetAsync().Result.Take(5).ToList();
177 |
178 | if (events.Count == 0)
179 | {
180 | Console.WriteLine(" no events scheduled");
181 | }
182 | foreach (Event _event in events)
183 | {
184 | Console.WriteLine(" Event: {0} starts {1} ", _event.Subject, _event.Start);
185 | }
186 | }
187 |
188 | catch (Exception e)
189 | {
190 | Console.WriteLine("\nError getting events {0} {1}",
191 | e.Message, e.InnerException != null ? e.InnerException.Message : "");
192 | }
193 |
194 | // Get current user's contacts
195 | try
196 | {
197 | List contacts = client.Me.Contacts.Request().GetAsync().Result.Take(5).ToList();
198 |
199 | if (contacts.Count == 0)
200 | {
201 | Console.WriteLine(" You don't have any contacts");
202 | }
203 | foreach (Contact contact in contacts)
204 | {
205 | Console.WriteLine(" Contact: {0} ", contact.DisplayName);
206 | }
207 | }
208 |
209 | catch (Exception e)
210 | {
211 | Console.WriteLine("\nError getting contacts {0} {1}",
212 | e.Message, e.InnerException != null ? e.InnerException.Message : "");
213 | }
214 |
215 | // Create a recipient list.
216 | IList messageToList = new List();
217 |
218 | // Get 10 users
219 | List users = client.Users.Request().GetAsync().Result.Take(10).ToList();
220 | foreach (User user in users)
221 | {
222 | Recipient messageTo = new Recipient();
223 | EmailAddress emailAdress = new EmailAddress();
224 | emailAdress.Address = user.UserPrincipalName;
225 | emailAdress.Name = user.DisplayName;
226 | messageTo.EmailAddress = emailAdress;
227 |
228 | // Only uncomment this next line if you want to send this mail to the
229 | // first 10 accounts returned by a call to the graph.microsoft.com/v1.0/users endpoint.
230 | // Otherwise, this email will only be sent to the current user.
231 |
232 | //messageToList.Add(messageTo);
233 | }
234 |
235 | // Get current user
236 | User currentUser = client.Me.Request().GetAsync().Result;
237 |
238 | Recipient currentUserRecipient = new Recipient();
239 | EmailAddress currentUserEmailAdress = new EmailAddress();
240 | currentUserEmailAdress.Address = currentUser.UserPrincipalName;
241 | currentUserEmailAdress.Name = currentUser.DisplayName;
242 | currentUserRecipient.EmailAddress = currentUserEmailAdress;
243 | messageToList.Add(currentUserRecipient);
244 |
245 | // Send mail to signed in user and the recipient list
246 |
247 | Console.WriteLine();
248 | Console.WriteLine("Sending mail....");
249 | Console.WriteLine();
250 |
251 | try
252 | {
253 | ItemBody messageBody = new ItemBody();
254 | messageBody.Content = "";
255 | messageBody.ContentType = BodyType.Text;
256 |
257 | Message newMessage = new Message();
258 | newMessage.Subject = "\nCompleted test run from console app.";
259 | newMessage.ToRecipients = messageToList;
260 | newMessage.Body = messageBody;
261 |
262 | client.Me.SendMail(newMessage, true).Request().PostAsync();
263 | Console.WriteLine("\nMail sent to {0}", currentUser.DisplayName);
264 | }
265 | catch (Exception)
266 | {
267 | Console.WriteLine("\nUnexpected Error attempting to send an email");
268 | throw;
269 | }
270 |
271 | // The operations in this method require admin-level consent. Uncomment this line
272 | // if you want to run the sample with a non-admin account.
273 | // You'll also need to uncomment the Group.Read.All permission scope in AuthenticationHelper.cs
274 | //GetDetailsForGroups();
275 |
276 | }
277 |
278 | public static void GetDetailsForGroups()
279 | {
280 | // Get the first 3 UNIFIED groups and view their associated content
281 | List unifiedGroupsForEnumerating = null;
282 | try
283 | {
284 | string unifiedFilter = "groupTypes/any(gt:gt+eq+'Unified')";
285 | unifiedGroupsForEnumerating = client.Groups.Request().Filter(unifiedFilter).GetAsync().Result.Take(3).ToList();
286 |
287 | foreach (Group group in unifiedGroupsForEnumerating)
288 | {
289 | Console.WriteLine(" Unified Group: {0}", group.DisplayName);
290 |
291 | // Get group members
292 | try
293 | {
294 | // get group members
295 | List unifiedGroupMembers = client.Groups[group.Id].Members.Request().GetAsync().Result.CurrentPage.ToList();
296 | if (unifiedGroupMembers.Count == 0)
297 | {
298 | Console.WriteLine(" no members for group");
299 | }
300 | foreach (DirectoryObject member in unifiedGroupMembers)
301 | {
302 | if (member is User)
303 | {
304 | User memberUser = (User)member;
305 | Console.WriteLine(" User: {0} ", memberUser.DisplayName);
306 | }
307 | }
308 | }
309 | catch (Exception e)
310 | {
311 | Console.Write("Unexpected exception when enumerating group members. Error detail: {0}", e.InnerException.Message);
312 | }
313 |
314 | // Get group files
315 | try
316 | {
317 | IList unifiedGroupFiles = client.Groups[group.Id].Drive.Root.Children.Request().GetAsync().Result.Take(5).ToList();
318 | if (unifiedGroupFiles.Count == 0)
319 | {
320 | Console.WriteLine(" no files for group");
321 | }
322 | foreach (DriveItem file in unifiedGroupFiles)
323 | {
324 | Console.WriteLine(" file: {0} url: {1}", file.Name, file.WebUrl);
325 | }
326 | }
327 | catch (Exception e)
328 | {
329 | Console.Write("Unexpected exception when enumerating group files. Error detail: {0}", e.InnerException.Message);
330 | }
331 |
332 | // Get group conversations
333 | try
334 | {
335 | List unifiedGroupConversations = client.Groups[group.Id].Conversations.Request().GetAsync().Result.CurrentPage.ToList();
336 | if (unifiedGroupConversations.Count == 0)
337 | {
338 | Console.WriteLine(" no conversations for group");
339 | }
340 | foreach (Conversation conversation in unifiedGroupConversations)
341 | {
342 | Console.WriteLine(" conversation topic: {0} ", conversation.Topic);
343 | }
344 | }
345 | catch (Exception e)
346 | {
347 | Console.Write("Unexpected exception when enumerating group conversations. Error detail: {0}", e.InnerException.Message);
348 | }
349 |
350 | // Get group events
351 | try
352 | {
353 | List unifiedGroupEvents = client.Groups[group.Id].Events.Request().GetAsync().Result.CurrentPage.ToList();
354 | if (unifiedGroupEvents.Count == 0)
355 | {
356 | Console.WriteLine(" no meeting events for group");
357 | }
358 | foreach (Event _event in unifiedGroupEvents)
359 | {
360 | Console.WriteLine(" meeting event subject: {0} ", _event.Subject);
361 | }
362 | }
363 | catch (Exception e)
364 | {
365 | Console.Write("Unexpected exception when enumerating group events. Error detail: {0}", e.InnerException.Message);
366 | }
367 |
368 | }
369 |
370 |
371 | }
372 |
373 | catch (Exception e)
374 | {
375 | Console.Write("Couldn't get unified groups. Error detail: {0}", e.InnerException.Message);
376 | }
377 | }
378 | }
379 | }
380 |
--------------------------------------------------------------------------------