├── .gitignore ├── CONTRIBUTING.md ├── LICENSE ├── README-localized ├── README-es-es.md ├── README-fr-fr.md ├── README-ja-jp.md ├── README-pt-br.md ├── README-ru-ru.md └── README-zh-cn.md ├── README.md ├── console-csharp-connect-sample.sln ├── console-csharp-connect-sample ├── App.config ├── AuthenticationConfig.cs ├── Constants.cs ├── GraphClientFactory.cs ├── Helpers │ ├── AuthHandler.cs │ └── MsalAuthenticationProvider.cs ├── MailHelper.cs ├── Program.cs ├── Properties │ └── AssemblyInfo.cs ├── appsettings.json.example ├── console-csharp-connect-sample.csproj ├── packages.config └── test.jpg └── readme-images ├── ID.png ├── client.png ├── client.xcf ├── redirect.png ├── registrations.png └── registrations.xcf /.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 | 7 | # Config file 8 | appsettings.json 9 | 10 | # User-specific files 11 | *.suo 12 | *.user 13 | *.userosscache 14 | *.sln.docstates 15 | 16 | # User-specific files (MonoDevelop/Xamarin Studio) 17 | *.userprefs 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | bld/ 27 | [Bb]in/ 28 | [Oo]bj/ 29 | [Ll]og/ 30 | 31 | # Visual Studio 2015 cache/options directory 32 | .vs/ 33 | # Uncomment if you have tasks that create the project's static files in wwwroot 34 | #wwwroot/ 35 | 36 | # MSTest test Results 37 | [Tt]est[Rr]esult*/ 38 | [Bb]uild[Ll]og.* 39 | 40 | # NUNIT 41 | *.VisualState.xml 42 | TestResult.xml 43 | 44 | # Build Results of an ATL Project 45 | [Dd]ebugPS/ 46 | [Rr]eleasePS/ 47 | dlldata.c 48 | 49 | # .NET Core 50 | project.lock.json 51 | project.fragment.lock.json 52 | artifacts/ 53 | **/Properties/launchSettings.json 54 | 55 | *_i.c 56 | *_p.c 57 | *_i.h 58 | *.ilk 59 | *.meta 60 | *.obj 61 | *.pch 62 | *.pdb 63 | *.pgc 64 | *.pgd 65 | *.rsp 66 | *.sbr 67 | *.tlb 68 | *.tli 69 | *.tlh 70 | *.tmp 71 | *.tmp_proj 72 | *.log 73 | *.vspscc 74 | *.vssscc 75 | .builds 76 | *.pidb 77 | *.svclog 78 | *.scc 79 | 80 | # Chutzpah Test files 81 | _Chutzpah* 82 | 83 | # Visual C++ cache files 84 | ipch/ 85 | *.aps 86 | *.ncb 87 | *.opendb 88 | *.opensdf 89 | *.sdf 90 | *.cachefile 91 | *.VC.db 92 | *.VC.VC.opendb 93 | 94 | # Visual Studio profiler 95 | *.psess 96 | *.vsp 97 | *.vspx 98 | *.sap 99 | 100 | # TFS 2012 Local Workspace 101 | $tf/ 102 | 103 | # Guidance Automation Toolkit 104 | *.gpState 105 | 106 | # ReSharper is a .NET coding add-in 107 | _ReSharper*/ 108 | *.[Rr]e[Ss]harper 109 | *.DotSettings.user 110 | 111 | # JustCode is a .NET coding add-in 112 | .JustCode 113 | 114 | # TeamCity is a build add-in 115 | _TeamCity* 116 | 117 | # DotCover is a Code Coverage Tool 118 | *.dotCover 119 | 120 | # Visual Studio code coverage results 121 | *.coverage 122 | *.coveragexml 123 | 124 | # NCrunch 125 | _NCrunch_* 126 | .*crunch*.local.xml 127 | nCrunchTemp_* 128 | 129 | # MightyMoose 130 | *.mm.* 131 | AutoTest.Net/ 132 | 133 | # Web workbench (sass) 134 | .sass-cache/ 135 | 136 | # Installshield output folder 137 | [Ee]xpress/ 138 | 139 | # DocProject is a documentation generator add-in 140 | DocProject/buildhelp/ 141 | DocProject/Help/*.HxT 142 | DocProject/Help/*.HxC 143 | DocProject/Help/*.hhc 144 | DocProject/Help/*.hhk 145 | DocProject/Help/*.hhp 146 | DocProject/Help/Html2 147 | DocProject/Help/html 148 | 149 | # Click-Once directory 150 | publish/ 151 | 152 | # Publish Web Output 153 | *.[Pp]ublish.xml 154 | *.azurePubxml 155 | # TODO: Comment the next line if you want to checkin your web deploy settings 156 | # but database connection strings (with potential passwords) will be unencrypted 157 | *.pubxml 158 | *.publishproj 159 | 160 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 161 | # checkin your Azure Web App publish settings, but sensitive information contained 162 | # in these scripts will be unencrypted 163 | PublishScripts/ 164 | 165 | # NuGet Packages 166 | *.nupkg 167 | # The packages folder can be ignored because of Package Restore 168 | **/packages/* 169 | # except build/, which is used as an MSBuild target. 170 | !**/packages/build/ 171 | # Uncomment if necessary however generally it will be regenerated when needed 172 | #!**/packages/repositories.config 173 | # NuGet v3's project.json files produces more ignorable files 174 | *.nuget.props 175 | *.nuget.targets 176 | 177 | # Microsoft Azure Build Output 178 | csx/ 179 | *.build.csdef 180 | 181 | # Microsoft Azure Emulator 182 | ecf/ 183 | rcf/ 184 | 185 | # Windows Store app package directories and files 186 | AppPackages/ 187 | BundleArtifacts/ 188 | Package.StoreAssociation.xml 189 | _pkginfo.txt 190 | 191 | # Visual Studio cache files 192 | # files ending in .cache can be ignored 193 | *.[Cc]ache 194 | # but keep track of directories ending in .cache 195 | !*.[Cc]ache/ 196 | 197 | # Others 198 | ClientBin/ 199 | ~$* 200 | *~ 201 | *.dbmdl 202 | *.dbproj.schemaview 203 | *.jfm 204 | *.pfx 205 | *.publishsettings 206 | orleans.codegen.cs 207 | 208 | # Since there are multiple workflows, uncomment next line to ignore bower_components 209 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 210 | #bower_components/ 211 | 212 | # RIA/Silverlight projects 213 | Generated_Code/ 214 | 215 | # Backup & report files from converting an old project file 216 | # to a newer Visual Studio version. Backup files are not needed, 217 | # because we have git ;-) 218 | _UpgradeReport_Files/ 219 | Backup*/ 220 | UpgradeLog*.XML 221 | UpgradeLog*.htm 222 | 223 | # SQL Server files 224 | *.mdf 225 | *.ldf 226 | *.ndf 227 | 228 | # Business Intelligence projects 229 | *.rdl.data 230 | *.bim.layout 231 | *.bim_*.settings 232 | 233 | # Microsoft Fakes 234 | FakesAssemblies/ 235 | 236 | # GhostDoc plugin setting file 237 | *.GhostDoc.xml 238 | 239 | # Node.js Tools for Visual Studio 240 | .ntvs_analysis.dat 241 | node_modules/ 242 | 243 | # Typescript v1 declaration files 244 | typings/ 245 | 246 | # Visual Studio 6 build log 247 | *.plg 248 | 249 | # Visual Studio 6 workspace options file 250 | *.opt 251 | 252 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 253 | *.vbw 254 | 255 | # Visual Studio LightSwitch build output 256 | **/*.HTMLClient/GeneratedArtifacts 257 | **/*.DesktopClient/GeneratedArtifacts 258 | **/*.DesktopClient/ModelManifest.xml 259 | **/*.Server/GeneratedArtifacts 260 | **/*.Server/ModelManifest.xml 261 | _Pvt_Extensions 262 | 263 | # Paket dependency manager 264 | .paket/paket.exe 265 | paket-files/ 266 | 267 | # FAKE - F# Make 268 | .fake/ 269 | 270 | # JetBrains Rider 271 | .idea/ 272 | *.sln.iml 273 | 274 | # CodeRush 275 | .cr/ 276 | 277 | # Python Tools for Visual Studio (PTVS) 278 | __pycache__/ 279 | *.pyc 280 | 281 | # Cake - Uncomment if you are using it 282 | # tools/** 283 | # !tools/packages.config 284 | 285 | # Telerik's JustMock configuration file 286 | *.jmconfig 287 | 288 | # BizTalk build output 289 | *.btp.cs 290 | *.btm.cs 291 | *.odx.cs 292 | *.xsd.cs 293 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 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 | -------------------------------------------------------------------------------- /README-localized/README-es-es.md: -------------------------------------------------------------------------------- 1 | --- 2 | page_type: sample 3 | products: 4 | - office-outlook 5 | - ms-graph 6 | languages: 7 | - csharp 8 | description: "En este ejemplo se muestra cómo conectar una aplicación de consola de Windows a una cuenta de Microsoft profesional o educativa (Azure Active Directory) o a una cuenta personal (Microsoft) usando la API de Microsoft Graph para enviar un correo electrónico" 9 | extensions: 10 | contentType: samples 11 | technologies: 12 | - Microsoft Graph 13 | - Microsoft identity platform 14 | services: 15 | - Microsoft identity platform 16 | - Outlook 17 | createdDate: 12/11/2017 1:55:47 PM 18 | --- 19 | # Ejemplo de conexión de consola con Microsoft Graph y C# 20 | 21 | ## Tabla de contenido 22 | 23 | * [Introducción](#introduction) 24 | * [Requisitos previos](#prerequisites) 25 | * [Clonar o descargar el repositorio](#cloning-or-downloading-repo) 26 | * [Configurar el inquilino de Azure AD](#configuring-Azure-AD-tenant ) 27 | * [Configurar el ejemplo para usar el inquilino de Azure AD](#configuring-sample-to-use-Azure-AD-tenant) 28 | * [Compilar y ejecutar el ejemplo](#build-and-run-sample) 29 | * [Preguntas y comentarios](#questions-and-comments) 30 | * [Colaboradores](#contributing) 31 | * [Recursos adicionales](#additional-resources) 32 | 33 | ## Introducción 34 | 35 | En este ejemplo se muestra cómo conectar una aplicación de consola de Windows a una cuenta de Microsoft profesional o educativa (Azure Active Directory) o a una cuenta personal (Microsoft) usando la API de Microsoft Graph. Se usa la API de Microsoft Graph para recuperar la imagen de perfil de un usuario, cargarla a OneDrive, crear un vínculo de uso compartido y enviar un correo electrónico que contenga la foto como archivo adjunto y el vínculo de uso compartido en el texto. Usa la biblioteca cliente de .NET de Microsoft Graph para trabajar con los datos devueltos por Microsoft Graph. En el ejemplo se usa el punto de conexión de Azure AD v2.0, que permite a los usuarios iniciar sesión con sus cuentas Microsoft personales, o bien con sus cuentas Microsoft profesionales o educativas. 36 | 37 | El ejemplo usa la Biblioteca de autenticación de Microsoft (MSAL) para la autenticación. 38 | 39 | ## Requisitos previos 40 | 41 | Este ejemplo necesita lo siguiente: 42 | 43 | - [Visual Studio](https://www.visualstudio.com/en-us/downloads) con la versión 7 de C# o superior. 44 | - Una cuenta [Microsoft](www.outlook.com) o una [cuenta de Office 365 para empresas](https://msdn.microsoft.com/en-us/office/office365/howto/setup-development-environment#bk_Office365Account). 45 | - Inquilino de Azure Active Directory (Azure AD) Para obtener más información sobre cómo conseguir un inquilino de Azure AD, consulte [cómo obtener un inquilino de Azure AD](https://azure.microsoft.com/en-us/documentation/articles/active-directory-howto-tenant/). 46 | 47 | ## Cómo ejecutar este ejemplo 48 | 49 | 50 | ### Paso 1: Clonar o descargar el repositorio. 51 | 52 | Desde la línea de comandos o shell: 53 | 54 | `git clone https://github.com/microsoftgraph/console-csharp-connect-sample` 55 | 56 | 57 | ### Paso 2: Configurar el inquilino de Azure AD 58 | 59 | 1. Inicie sesión en [Microsoft Azure Portal](https://portal.azure.com) con una cuenta personal, profesional o educativa de Microsoft. 60 | 2. Si la cuenta proporciona acceso a más de un inquilino, haga clic en la cuenta en la esquina superior derecha y establezca la sesión del portal en el inquilino de Azure AD deseado (mediante **Cambiar directorio**). 61 | 3. En el panel de navegación izquierdo, seleccione el servicio **Azure Active Directory** y, después, seleccione **Registros de aplicaciones 62 | (versión preliminar)**. 63 | 64 | #### Registro de la aplicación cliente 65 | ![](https://github.com/nicolesigei/console-csharp-connect-sample/blob/master/readme-images/registrations.png) 66 | 1. En la página **Registros de aplicaciones**, seleccione **Registrar una aplicación**. 67 | 1. En la página **Registros de aplicaciones (versión preliminar)**, seleccione **Registrar una aplicación**. 68 | 2. Cuando aparezca la **página Registrar una aplicación**, escriba la información de registro de la aplicación: 69 | - En la sección **Nombre**, escriba un nombre de aplicación significativo, que será el que se muestre a los usuarios. Por ejemplo: `Aplicación de consola para Microsoft Graph` 70 | - En la sección **Tipos de cuenta admitidos**, seleccione **Cuentas en cualquier directorio de organización y cuentas de Microsoft personales (por ejemplo, Skype, Xbox, Outlook.com)**. 71 | - Seleccione **Registrar** para crear la aplicación. 72 | 3. En la página **Información general** de la aplicación, busque el valor **Id. de la aplicación (cliente)** y guárdelo para más tarde. Lo necesitará para configurar el archivo de configuración de Visual Studio para este proyecto. 73 | 4. En la lista de páginas de la aplicación, seleccione **Autenticación**. 74 | 75 | - Use *urn:ietf:wg:oauth:2.0:oob* en el cuadro de texto **URI de redirección** y seleccione el **Tipo** como cliente público (móvil y escritorio) 76 | ![](https://github.com/nicolesigei/console-csharp-connect-sample/blob/master/readme-images/redirect.png) 77 | - En los *URI de redirección sugeridos para clientes públicos (móvil, escritorio)*, marque el segundo cuadro para que la aplicación pueda funcionar con las bibliotecas de MSAL utilizadas en la aplicación. (El cuadro debe contener la opción *urn:ietf:wg:oauth:2.0:oob*). 78 | 5. En la lista de páginas de la aplicación, seleccione **Permisos de API** 79 | - Haga clic en el botón **Agregar un permiso** y 80 | - Asegúrese de está seleccionada la pestaña **API de Microsoft**. 81 | - En la sección *API de Microsoft más usadas*, haga clic en **Microsoft Graph**. 82 | - En la sección **Permisos delegados**, asegúrese de que están marcados los permisos correctos: **User.Read**, **Mail.Send** y **Files.ReadWrite**. Use el cuadro de búsqueda si es necesario. 83 | - Seleccione el botón **Agregar permisos**. 84 | 85 | 86 | ### Paso 3: Configurar el ejemplo para usar el inquilino de Azure AD 87 | 88 | En los pasos que se indican a continuación, *Id. de cliente* es lo mismo que *Id. de la aplicación* o *Id. de aplicación*. 89 | 90 | Abra la solución en Visual Studio para configurar los proyectos. 91 | 92 | #### Configurar la aplicación cliente 93 | 94 | 1. En la carpeta *console-csharp-connect-sample*, cambie el nombre del archivo `appsettings.json.example` a `appsettings.json`. 95 | 1. Abra y edite el archivo `appsettings.json` para hacer el siguiente cambio: 96 | 1. Busque la línea en la que `ClientId` se ha establecido como `YOUR_CLIENT_ID_HERE` y reemplace el valor existente con el Id. de aplicación (cliente) de la aplicación `Aplicación de consola para Microsoft Graph` que se había copiado desde Microsoft Azure Portal. 97 | 98 | 99 | ### Paso 4: Compilar y ejecutar el ejemplo 100 | 101 | 1. Abra la solución del ejemplo en Visual Studio. 102 | 2. Pulse F5 para compilar y ejecutar el ejemplo. Esto restaurará las dependencias del paquete de NuGet y abrirá la aplicación de consola. 103 | 3. Cuando se le solicite, autentíquese con su cuenta de Microsoft y conceda los permisos que necesita la aplicación. 104 | 4. Siga las indicaciones para enviar un mensaje desde su cuenta a su propio correo o al de otra persona. 105 | 106 | ## Preguntas y comentarios 107 | 108 | 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-connect-sample/issues) de este repositorio. 109 | 110 | 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]. 111 | 112 | ## Colaboradores ## 113 | 114 | Si quiere hacer su aportación a este ejemplo, vea [CONTRIBUTING.MD](/CONTRIBUTING.md). 115 | 116 | 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. 117 | 118 | ## Recursos adicionales 119 | 120 | - [Otros ejemplos de Microsoft Graph Connect](https://github.com/MicrosoftGraph?utf8=%E2%9C%93&query=-Connect) 121 | - [Microsoft Graph](https://developer.microsoft.com/en-us/graph) 122 | 123 | ## Derechos de autor 124 | Copyright (c) 2019 Microsoft. Todos los derechos reservados. 125 | -------------------------------------------------------------------------------- /README-localized/README-fr-fr.md: -------------------------------------------------------------------------------- 1 | --- 2 | page_type: sample 3 | products: 4 | - office-outlook 5 | - ms-graph 6 | languages: 7 | - csharp 8 | description: "Cet exemple présente la connexion entre une application de console Windows et un compte professionnel, scolaire (Azure Active Directory) ou personnel (Microsoft) utilisant l’API Microsoft Graph pour envoyer un e-mail." 9 | extensions: 10 | contentType: samples 11 | technologies: 12 | - Microsoft Graph 13 | - Microsoft identity platform 14 | services: 15 | - Microsoft identity platform 16 | - Outlook 17 | createdDate: 12/11/2017 1:55:47 PM 18 | --- 19 | # Exemple de connexion avec la console Microsoft Graph C# 20 | 21 | ## Table des matières 22 | 23 | * [Introduction](#introduction) 24 | * [Conditions préalables](#prerequisites) 25 | * [Clonage ou téléchargement de ce référentiel](#cloning-or-downloading-repo) 26 | * [Configuration de votre client Azure AD](#configuring-Azure-AD-tenant ) 27 | * [Configuration de l’échantillon pour utiliser votre client Azure AD](#configuring-sample-to-use-Azure-AD-tenant) 28 | * [Créer et exécuter l’exemple](#build-and-run-sample) 29 | * [Questions et commentaires](#questions-and-comments) 30 | * [Contribution](#contributing) 31 | * [Ressources supplémentaires](#additional-resources) 32 | 33 | ## Introduction 34 | 35 | Cet exemple montre comment connecter une application de console Windows à un compte professionnel ou scolaire Microsoft (Azure Active Directory) ou un compte personnel (Microsoft) à l’aide de l’API Microsoft Graph. Il utilise l’API Microsoft Graph pour récupérer l’image de profil d’un utilisateur, charger l’image sur OneDrive, créer un lien de partage et envoyer un courrier e-mail contenant la photo sous forme de pièce jointe et le lien de partage dans son texte. Il utilise la bibliothèque cliente Microsoft Graph .NET pour exploiter les données renvoyées par Microsoft Graph. L’exemple utilise le point de terminaison Azure AD v 2.0, qui permet aux utilisateurs de se connecter avec leurs comptes Microsoft personnels, professionnels ou scolaires. 36 | 37 | L’exemple utilise la Bibliothèque d’authentification Microsoft (MSAL) pour l’authentification. 38 | 39 | ## Conditions préalables 40 | 41 | Cet exemple nécessite les éléments suivants : 42 | 43 | - [Visual Studio](https://www.visualstudio.com/en-us/downloads) avec C# version 7 et les versions ultérieures. 44 | - Soit un compte [Microsoft](www.outlook.com), soit un [compte Office 365 pour entreprise](https://msdn.microsoft.com/en-us/office/office365/howto/setup-development-environment#bk_Office365Account). 45 | - Un client Azure Active Directory (Azure AD). Pour plus d’informations sur la façon d’obtenir un client Azure AD, voir [Obtention d’un client Azure AD](https://azure.microsoft.com/en-us/documentation/articles/active-directory-howto-tenant/). 46 | 47 | ## Exécution de cet exemple 48 | 49 | 50 | ### Étape 1 : Clonage ou téléchargement de ce référentiel. 51 | 52 | À partir de votre shell ou de la ligne de commande : 53 | 54 | `git clone https://github.com/microsoftgraph/console-csharp-connect-sample` 55 | 56 | 57 | ### Étape 2 : [Configuration de votre client Azure AD](#configuring-Azure-AD-tenant ) 58 | 59 | 60 | 1. Connectez-vous au [portail Microsoft Azure](https://portal.azure.com) à l’aide d’un compte professionnel ou scolaire, ou d’un compte Microsoft personnel. 61 | 2. Si votre compte vous propose un accès à plusieurs locataires, sélectionnez votre compte en haut à droite et définissez votre session de portail sur le client Azure AD souhaité (à l’aide de **Changer de répertoire**). 62 | 3. Dans le volet de navigation gauche, sélectionnez le service **Azure Active Directory**, puis sélectionnez **Inscriptions d’applications (préversion)**. 63 | 64 | #### Inscription de l’application cliente 65 | ![](https://github.com/nicolesigei/console-csharp-connect-sample/blob/master/readme-images/registrations.png) 66 | 1. À la page **Inscriptions des applications**, sélectionnez **Inscrire une application**. 67 | 1. À la page **Inscriptions des applications (préversion)**, sélectionnez **Inscrire une application**. 68 | 2. Lorsque la **page Inscrire une application** s’affiche, entrez les informations relatives à l’inscription de votre application : 69 | - dans la **section Nom**, entrez un nom d’application significatif qui sera présenté aux utilisateurs de l’application, par exemple `Application console pour Microsoft Graph` 70 | - dans la section **Types de comptes pris en charge**, sélectionnez **Comptes dans un annuaire organisationnel et comptes personnels Microsoft (par exemple, Skype, Xbox, Outlook.com)**. 71 | - Sélectionnez **Inscrire** pour créer l’application. 72 | 3. Sur la page **Vue d’ensemble** de l’application, notez la valeur **ID d’application (client)** et conservez-la pour plus tard. Vous en aurez besoin pour paramétrer le fichier de configuration de Visual Studio pour ce projet. 73 | 4. Dans la liste des pages de l’application, sélectionnez **Authentification**. 74 | 75 | - Utilisez *urn:ietf:wg:oauth:2.0:oob* dans la zone de texte **Redirect URI** et sélectionnez le **Type** en tant que client public (mobile et ordinateur de bureau) 76 | ![](https://github.com/nicolesigei/console-csharp-connect-sample/blob/master/readme-images/redirect.png) 77 | - Dans la boîte de dialogue *URI de redirection suggérés pour les clients publics (mobile, bureau)*, cochez la deuxième zone pour que l’application puisse utiliser les bibliothèques MSAL utilisées dans l’application. (La zone doit contenir l’option *urn:ietf:wg:oauth:2.0:oob*). 78 | 5. Dans la liste des pages de l’application, sélectionnez **Autorisations de l’API** 79 | - Cliquez sur le bouton **Ajouter une autorisation**, puis : 80 | - assurez-vous que l’onglet **API Microsoft** est sélectionné. 81 | - Dans la section *API Microsoft couramment utilisées*, cliquez sur **Microsoft Graph**. Dans la section **Autorisations déléguées**, assurez 82 | -vous que les autorisations appropriées sont cochées : **User.Read**, **Mail.Send** et **Files.ReadWrite**. Utilisez la zone de recherche, le cas échéant. 83 | - Sélectionnez le bouton **Ajouter des autorisations**. 84 | 85 | 86 | ### Étape 3 : Configuration de l’échantillon pour utiliser votre client Azure AD 87 | 88 | Dans les étapes ci-dessous, *ID client* est identique à *ID de l’application*.** 89 | 90 | Ouvrez la solution dans Visual Studio pour configurer les projets. 91 | 92 | #### Configurer le projet client 93 | 94 | 1. Dans le dossier *console-csharp-connect-sample*, renommez le fichier `appsettings.json.example` en `appsettings.json`. 95 | 1. Ouvrez et modifiez le fichier `appSettings.json` pour apporter la modification suivante : 96 | 1. Recherchez la ligne dans laquelle `ClientId` est défini comme `YOUR_CLIENT_ID_HERE` et remplacez la valeur existante par l’ID (client) de `l’application console pour Microsoft Graph` copié à partir du portail Azure. 97 | 98 | 99 | ### Étape 4 : Créer et exécuter l’exemple 100 | 101 | 1. Ouvrez l’exemple de solution dans Visual Studio. 102 | 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. 103 | 3. À l’invite, authentifiez-vous avec votre compte Microsoft et acceptez les autorisations requises par l’application. 104 | 4. Suivez les invites pour envoyer un message de votre compte à vous-même ou à un autre utilisateur. 105 | 106 | ## Questions et commentaires 107 | 108 | 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-connect-sample/issues) de ce référentiel. 109 | 110 | 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]. 111 | 112 | ## Contribution ## 113 | 114 | Si vous souhaitez contribuer à cet exemple, voir [CONTRIBUTING.MD](/CONTRIBUTING.md). 115 | 116 | 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. 117 | 118 | ## Ressources supplémentaires 119 | 120 | - [Autres exemples de connexion avec Microsoft Graph](https://github.com/MicrosoftGraph?utf8=%E2%9C%93&query=-Connect) 121 | - [Microsoft Graph](https://developer.microsoft.com/en-us/graph) 122 | 123 | ## Copyright 124 | Copyright (c) 2019 Microsoft. Tous droits réservés. 125 | -------------------------------------------------------------------------------- /README-localized/README-ja-jp.md: -------------------------------------------------------------------------------- 1 | --- 2 | page_type: sample 3 | products: 4 | - office-outlook 5 | - ms-graph 6 | languages: 7 | - csharp 8 | description: "このサンプルでは、Microsoft Graph API を使用して Windows コンソール アプリケーションを Microsoft の職場または学校 (Azure Active Directory) アカウントまたは個人 (Microsoft) アカウントに接続してメールを送信する方法を示します。" 9 | extensions: 10 | contentType: samples 11 | technologies: 12 | - Microsoft Graph 13 | - Microsoft identity platform 14 | services: 15 | - Microsoft identity platform 16 | - Outlook 17 | createdDate: 12/11/2017 1:55:47 PM 18 | --- 19 | # Microsoft Graph C# コンソール Connect のサンプル 20 | 21 | ## 目次 22 | 23 | * [はじめに](#introduction) 24 | * [前提条件](#prerequisites) 25 | * [このリポジトリの複製またはダウンロード](#cloning-or-downloading-repo) 26 | * [Azure AD テナントを構成する](#configuring-Azure-AD-tenant ) 27 | * [Azure AD テナントを使用するようにサンプルを構成する](#configuring-sample-to-use-Azure-AD-tenant) 28 | * [サンプルのビルドと実行](#build-and-run-sample) 29 | * [質問とコメント](#questions-and-comments) 30 | * [投稿](#contributing) 31 | * [その他のリソース](#additional-resources) 32 | 33 | ## 概要 34 | 35 | このサンプルは、Microsoft Graph API を使用して、Microsoft の職場または学校 (Azure Active Directory) アカウント、あるいは個人用 (Microsoft) アカウントに Windows コンソール アプリケーションを接続する方法を示します。Microsoft Graph API を使用してユーザーのプロファイル画像を取得し、その画像を OneDrive にアップロードし、共有リンクを作成し、画像を添付ファイルおよびテキスト内の共有リンクとして含むメールを送信します。Microsoft Graph が返すデータを操作するために、Microsoft Graph .NET クライアント ライブラリを使用します。このサンプルは Azure AD v2.0 エンドポイントを使用します。このエンドポイントにより、ユーザーは個人用か、職場または学校の Microsoft アカウントでサインインできます。 36 | 37 | サンプルでは Microsoft 認証ライブラリ (MSAL) を使用して認証を行います。 38 | 39 | ## 前提条件 40 | 41 | このサンプルを実行するには次のものが必要です。 42 | 43 | - C# バージョン 7 以降の [Visual Studio](https://www.visualstudio.com/en-us/downloads)。 44 | - [Microsoft](www.outlook.com) または [Office 365 for Business アカウント](https://msdn.microsoft.com/en-us/office/office365/howto/setup-development-environment#bk_Office365Account)のいずれか。 45 | - Azure Active Directory (Azure AD) テナント。Azure AD テナントを取得する方法の詳細については、「[Azure AD テナントを取得する方法](https://azure.microsoft.com/en-us/documentation/articles/active-directory-howto-tenant/)」を参照してください。 46 | 47 | ## このサンプルの実行方法 48 | 49 | 50 | ### 手順 1: このリポジトリのクローンを作成するか、ダウンロードします 51 | 52 | シェルまたはコマンド ラインから: 53 | 54 | `git clone https://github.com/microsoftgraph/console-csharp-connect-sample` 55 | 56 | 57 | ### 手順 2:Azure AD テナントを構成する 58 | 59 | 1. 職場または学校のアカウントか、個人の Microsoft アカウントを使用して、[Azure portal](https://portal.azure.com)にサインインします。 60 | 2. ご利用のアカウントで複数のテナントにアクセスできる場合は、右上隅でアカウントを選択し、ポータルのセッションを目的の Azure AD テナントに設定します (**Switch Directory** を使用)。 61 | 3. 左側のナビゲーション ウィンドウで、[**Azure Active Directory**] サービスを選択し、[**アプリの登録 (プレビュー)**] を選択します。 62 | 63 | #### クライアント アプリの登録 64 | ![](https://github.com/nicolesigei/console-csharp-connect-sample/blob/master/readme-images/registrations.png) 65 | 1.[**アプリの登録**] ページで、[**アプリケーションを登録する**] を選択します。 66 | 1.[**アプリの登録 (プレビュー)**] ページで、[**アプリケーションを登録する**] を選択します。 67 | 2.[**アプリケーションの登録] ページ**が表示されたら、アプリケーションの登録情報を入力します。 68 | - [**名前**] セクションで、アプリのユーザーに表示される意味のあるアプリケーション名を入力します。たとえば、`Microsoft Graph 用のコンソール アプリ`などです 69 | - [**サポートされているアカウントの種類**] セクションで、**任意の組織のディレクトリ内のアカウントと個人用の Microsoft アカウント (例: Skype、 Xbox、Outlook.com)** を選択します。 70 | - [**登録**] を選択して、アプリケーションを作成します。 71 | 3.アプリの [**概要**] ページで、[**Application (client) ID**] (アプリケーション (クライアント) ID) の値を確認し、後で使用するために記録します。この情報は、このプロジェクトで Visual Studio 構成ファイルを設定するのに必要になります。 72 | 4.アプリのページの一覧から [**認証**] を選択します 73 | 74 | - **リダイレクト URI** テキスト ボックスで *urn:ietf:wg:oauth:2.0:oob* を使用し、**種類** をパブリック クライアント (モバイルおよびデスクトップ) として選択します 75 | ![](https://github.com/nicolesigei/console-csharp-connect-sample/blob/master/readme-images/redirect.png) 76 | - [*パブリック クライアント (モバイル、デスクトップ) に推奨されるリダイレクト URI*] で、アプリケーションで使用されている MSAL ライブラリをアプリが利用できるように、2 番目のボックスをオンにします。(ボックスには、オプション *urn:ietf:wg:oauth:2.0:oob* を含める必要があります)。 77 | 5.アプリのページの一覧で、[**API アクセス許可**] を選択し、[**アクセス許可を追加する**] ボタンをクリックしてから、[**Microsoft API**] タブが選択されていることを確認します。 78 | - [*よく使用される Microsoft API*] セクションで、 79 | - [**Microsoft Graph**] をクリックします。 80 | - [**委任されたアクセス許可**] セクションで、適切なアクセス許可がチェックされていることを確認します。**User.Read**、**Mail.Send** および **Files.ReadWrite**。必要に応じて検索ボックスを使用します。 81 | - [**アクセス許可を追加する**] ボタンを選択します。 82 | 83 | 84 | ### 手順 3:Azure AD テナントを使用するようにサンプルを構成する 85 | 86 | 次の手順では、*クライアント ID* は*アプリケーション ID* または*アプリ ID* と同じです。 87 | 88 | Visual Studio でソリューションを開き、プロジェクトを構成します。 89 | 90 | #### クライアント プロジェクトを構成する 91 | 92 | 1. *console-csharp-connect-sample* フォルダーで、`appsettings.json.example` ファイルの名前を `appsettings.json` に変更します 93 | 1. `appsettings.json` ファイルを開いて編集し、次の変更を加えます 94 | 1. `ClientId` が `YOUR_CLIENT_ID_HERE` として設定されている行を見つけ、既存の値を Azure ポータルからコピーされた `Microsoft Graph アプリケーションのコンソール アプリ`のアプリケーション (クライアント) ID に置き換えます。 95 | 96 | 97 | ### 手順 4: サンプルのビルドと実行 98 | 99 | 1. サンプル ソリューションを Visual Studio で開きます。 100 | 2. F5 キーを押して、サンプルをビルドして実行します。これにより、NuGet パッケージの依存関係が復元され、コンソール アプリケーションが開きます。 101 | 3. プロンプトが表示されたら、Microsoft アカウントで認証し、アプリケーションが必要とするアクセス許可に同意します。 102 | 4. プロンプトに従って、アカウントから自分自身または他のユーザーにメッセージを送信します。 103 | 104 | ## 質問とコメント 105 | 106 | Microsoft Graph API コンソール アプリに関するフィードバックをぜひお寄せください。質問や提案は、このリポジトリの「[問題](https://github.com/microsoftgraph/console-csharp-connect-sample/issues)」セクションで送信できます。 107 | 108 | Microsoft Graph 開発全般の質問については、「[Stack Overflow](https://stackoverflow.com/questions/tagged/microsoftgraph)」に投稿してください。質問やコメントには、必ず "microsoftgraph" とタグを付けてください。 109 | 110 | ## 投稿 ## 111 | 112 | このサンプルに投稿する場合は、[CONTRIBUTING.MD](/CONTRIBUTING.md) を参照してください。 113 | 114 | このプロジェクトでは、[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) までお問い合わせください。 115 | 116 | ## その他の技術情報 117 | 118 | - [その他の Microsoft Graph Connect のサンプル](https://github.com/MicrosoftGraph?utf8=%E2%9C%93&query=-Connect) 119 | - [Microsoft Graph](https://developer.microsoft.com/en-us/graph) 120 | 121 | ## 著作権 122 | Copyright (c) 2019 Microsoft.All rights reserved. 123 | -------------------------------------------------------------------------------- /README-localized/README-pt-br.md: -------------------------------------------------------------------------------- 1 | --- 2 | page_type: sample 3 | products: 4 | - office-outlook 5 | - ms-graph 6 | languages: 7 | - csharp 8 | description: "Este exemplo mostra como conectar um aplicativo de console do Windows a uma conta corporativa ou de estudante da Microsoft ou a uma conta pessoal (Microsoft) usando a API do Microsoft para enviar um email." 9 | extensions: 10 | contentType: samples 11 | technologies: 12 | - Microsoft Graph 13 | - Microsoft identity platform 14 | services: 15 | - Microsoft identity platform 16 | - Outlook 17 | createdDate: 12/11/2017 1:55:47 PM 18 | --- 19 | # Exemplo de conexão de aplicativo de console C# usando o Microsoft Graph 20 | 21 | ## Sumário 22 | 23 | * [Introdução](#introduction) 24 | * [Pré-requisitos](#prerequisites) 25 | * [Clonar ou baixar este repositório](#cloning-or-downloading-repo) 26 | * [Configurar o seu locatário do Azure AD](#configuring-Azure-AD-tenant ) 27 | * [Configurar o exemplo para usaro seu locatário do Azure AD](#configuring-sample-to-use-Azure-AD-tenant) 28 | * [Criar e executar o exemplo](#build-and-run-sample) 29 | * [Perguntas e comentários](#questions-and-comments) 30 | * [Colaboração](#contributing) 31 | * [Recursos adicionais](#additional-resources) 32 | 33 | ## Introdução 34 | 35 | Este exemplo mostra como conectar um aplicativo de console do Windows a uma conta corporativa ou de estudante da Microsoft (Azure Active Directory) ou uma conta pessoal (Microsoft) usando a API do Microsoft Graph. Ele usa a API do Microsoft Graph para recuperar a imagem de perfil de um usuário, carregar a imagem para o OneDrive, criar um link de compartilhamento e enviar um email que contenha a foto como um anexo e o link de compartilhamento no texto. O exemplo usa a Biblioteca de Clientes do Microsoft Graph para .NET para trabalhar com dados retornados pelo Microsoft Graph. O exemplo utiliza o ponto de extremidade do Azure AD versão 2.0, que permite que os usuários entrem com a conta pessoal, corporativa ou de estudante da Microsoft. 36 | 37 | O exemplo usa a Biblioteca de Autenticação da Microsoft (MSAL) para autenticação. 38 | 39 | ## Pré-requisitos 40 | 41 | Requisitos para o exemplo são os seguintes: 42 | 43 | - [ Visual Studio](https://www.visualstudio.com/en-us/downloads) com a versão C# 7 e posterior. 44 | - Uma conta [Microsoft](www.outlook.com) ou uma conta [Office 365 for business](https://msdn.microsoft.com/en-us/office/office365/howto/setup-development-environment#bk_Office365Account). 45 | - Um locatário do Active Directory do Azure (Azure AD). Para obter mais informações sobre como obter um locatário do Azure AD, confira [como obter um locatário do Azure AD](https://azure.microsoft.com/en-us/documentation/articles/active-directory-howto-tenant/). 46 | 47 | ## Como executar esse exemplo 48 | 49 | 50 | ### Etapa 1: Clone ou baixe este repositório 51 | 52 | A partir de seu shell ou linha de comando: 53 | 54 | `git clone https://github.com/microsoftgraph/console-csharp-connect-sample` 55 | 56 | 57 | ### Etapa 2: Configurar o seu locatário do Azure AD 58 | 59 | 1. Entrar no [portal do Azure](https://portal.azure.com)usando uma conta corporativa, de estudante ou uma conta Microsoft pessoal. 60 | 2. Se sua conta permitir o acesso a mais de um locatário, clique na sua conta no canto superior direito e configure sua sessão do portal ao locatário do Azure AD desejado (usando **Mudar Diretório**). 61 | 3. No painel de navegação à esquerda, selecione o serviço **Azure Active Directory**e, em seguida, selecione **Registros de aplicativo (Visualização)**. 62 | 63 | #### Registro do aplicativo cliente 64 | ![](https://github.com/nicolesigei/console-csharp-connect-sample/blob/master/readme-images/registrations.png) 65 | 1. Na página **Registros de aplicativo**, selecione **Registrar um aplicativo**. 66 | 1. Na página **Registros de aplicativo (Visualização)**, selecione **Registrar um aplicativo**. 67 | 2. Quando a **página Registrar um aplicativo** aparecer, insira as informações de registro do seu aplicativo: 68 | - Na seção **Nome**, insira a nome significativo para o aplicativo que irá ser exibido para os usuários do aplicativo, por exemplo `Aplicativo de console para o Microsoft Graph` 69 | - Na seção **Tipos de contas com suporte**, selecione**Contas em qualquer diretório organizacional ou contas pessoais da Microsoft (por exemplo, Skype, Xbox, Outlook.com)**. 70 | - Selecione **Registrar** para criar o aplicativo. 71 | 3. Na página **Visão geral** do aplicativo, encontre o valor de **ID do aplicativo (cliente)** e guarde-o para usar mais tarde. Será necessário configurar o arquivo de configuração do Visual Studio para este projeto. 72 | 4. Na lista de páginas do aplicativo, selecione **Autenticação** 73 | 74 | - Use *urn:ietf:wg:oauth:2.0:oob* na caixa de texto **Redirecionar URI** e selecione o **Type** como Cliente Público (celular e computador) 75 | ![](https://github.com/nicolesigei/console-csharp-connect-sample/blob/master/readme-images/redirect.png) 76 | - Em *URIs de redirecionamento sugeridas para clientes públicos(celular,computador)*, marque a segunda caixa para que o aplicativo possa trabalhar com a biblioteca do MSAL usada no aplicativo. (A caixa dever conter a opção *urn:ietf:wg:oauth:2.0:oob*). 77 | 5. Na lista de páginas do aplicativo, selecione **API de permissões** 78 | - Clique no botão **Adicionar uma permissão** e, em seguida, 79 | - Verifique se a guia **APIs da Microsoft** está selecionada. 80 | -Na seção *APIs mais usadas da Microsoft*, clique em **Microsoft Graph**. 81 | -Na seção **Permissões delegadas**, certifique-se de que as permissões corretas estejam marcadas: **User.Read**, **Mail.Send** and **Files.ReadWrite**. Use a caixa de pesquisa, se necessário. 82 | - Marque o botão **Adicionar permissões**. 83 | 84 | 85 | ### Etapa 3: Configurar o exemplo para usaro seu locatário do Azure AD 86 | 87 | Nas etapas abaixo, *ID de cliente* é o mesmo que *ID de aplicativo* ou *ID de app*. 88 | 89 | Abra a solução no Visual Studio para configurar os projetos. 90 | 91 | #### Configurar o projeto cliente 92 | 93 | 1. Na pasta *console-csharp-connect-sample*, renomeie o arquivo `appsettings.json.example` para `appsettings.json` 94 | 1. Abra e edite o arquivo `appsettings.json` para fazer a seguinte alteração 95 | 1. Localize a linha em que `ClientId` está definida como `YOUR_CLIENT_ID_HERE` e substitua o valor existente pelo ID de aplicativo (cliente) ` Aplicativo de Console para o Microsoft Graph` copiado do portal do Azure. 96 | 97 | 98 | ### Etapa 4: Criar e executar o exemplo 99 | 100 | 1. Abra a solução de exemplo no Visual Studio. 101 | 2. Pressione F5 para criar e executar o exemplo. Isso restaurará as dependências do pacote NuGet e abrirá o aplicativo de console. 102 | 3. Quando solicitado, autentique com a conta da Microsoft e concorde com as permissões necessárias para o aplicativo. 103 | 4. Siga as instruções para enviar uma mensagem a partir da sua conta para você mesmo ou outra pessoa. 104 | 105 | ## Perguntas e comentários 106 | 107 | 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-connect-sample/issues) deste repositório. 108 | 109 | 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 \[microsoftgraph]. 110 | 111 | ## Colaboração ## 112 | 113 | Se quiser contribuir para esse exemplo, confira [CONTRIBUTING.MD](/CONTRIBUTING.md). 114 | 115 | 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. 116 | 117 | ## Recursos adicionais 118 | 119 | - [Outros exemplos de conexão usando o Microsoft Graph](https://github.com/MicrosoftGraph?utf8=%E2%9C%93&query=-Connect) 120 | - [Microsoft Graph](https://developer.microsoft.com/en-us/graph) 121 | 122 | ## Direitos autorais 123 | Copyright (c) 2019 Microsoft. Todos os direitos reservados. 124 | -------------------------------------------------------------------------------- /README-localized/README-ru-ru.md: -------------------------------------------------------------------------------- 1 | --- 2 | page_type: sample 3 | products: 4 | - office-outlook 5 | - ms-graph 6 | languages: 7 | - csharp 8 | description: "В этом примере показано, как подключить консольное приложение Windows к рабочей или учебной школе Microsoft (Azure Active Directory) или личной (Microsoft) учетной записи с помощью API-интерфейса Microsoft Graph для отправки электронной почты." 9 | extensions: 10 | contentType: samples 11 | technologies: 12 | - Microsoft Graph 13 | - Microsoft identity platform 14 | services: 15 | - Microsoft identity platform 16 | - Outlook 17 | createdDate: 12/11/2017 1:55:47 PM 18 | --- 19 | # Пример подключения C# консоли Microsoft Graph 20 | 21 | ## Содержание 22 | 23 | * [Введение](#introduction) 24 | * [Предварительные требования](#prerequisites) 25 | * [Клонирование или скачивание репозитория](#cloning-or-downloading-repo) 26 | * [Настройка клиента Azure AD](#configuring-Azure-AD-tenant ) 27 | * [Настройка примера для использования клиента Azure AD](#configuring-sample-to-use-Azure-AD-tenant) 28 | * [Сборка и запуск примера](#build-and-run-sample) 29 | * [Вопросы и комментарии](#questions-and-comments) 30 | * [Участие](#contributing) 31 | * [Дополнительные ресурсы](#additional-resources) 32 | 33 | ## Введение 34 | 35 | В этом примере показано, как подключить консольное приложение Windows к рабочей или учебной (Azure Active Directory) либо личной учетной записи Майкрософт с помощью API Microsoft Graph для отправки электронной почты. Он использует Microsoft Graph API для получения изображения профиля пользователя, загрузки изображения в OneDrive, создания ссылки для обмена и отправки электронного письма, содержащего фотографию в виде вложения и ссылку для обмена в ее тексте. Для работы с данными, возвращаемыми Microsoft Graph, используется клиентская библиотека Microsoft Graph .NET. В этом примере используется конечная точка Azure AD v2.0, которая позволяет пользователям входить в систему с использованием своих личных или рабочих или школьных учетных записей Microsoft. 36 | 37 | Для проверки подлинности в этом примере используется библиотека Microsoft Authentication Library (MSAL). 38 | 39 | ## Предварительные требования 40 | 41 | Для этого примера требуются приведенные ниже компоненты. 42 | 43 | - [Visual Studio](https://www.visualstudio.com/en-us/downloads) в C# версии 7 и более поздних. 44 | - Учетная запись [Microsoft](www.outlook.com) или [Office 365 для бизнеса](https://msdn.microsoft.com/en-us/office/office365/howto/setup-development-environment#bk_Office365Account). 45 | - Клиент Azure Active Directory (Azure AD). Дополнительную информацию о том, как получить клиента Azure AD, см. В разделе [Как получить клиента Azure AD](https://azure.microsoft.com/en-us/documentation/articles/active-directory-howto-tenant/). 46 | 47 | ## Как запустить этот образец 48 | 49 | 50 | ### Шаг 1. Клонировать или скачать этот репозиторий 51 | 52 | Из вашей оболочки или командной строки: 53 | 54 | `git clone https://github.com/microsoftgraph/console-csharp-connect-sample` 55 | 56 | 57 | ### Шаг 2. Настройка клиента Azure AD 58 | 59 | 1. Войдите на [портал Azure](https://portal.azure.com) с помощью личной учетной записи Майкрософт либо рабочей или учебной учетной записи. 60 | 2. Если ваша учетная запись предоставляет вам доступ более чем к одному арендатору, выберите свою учетную запись в верхнем правом углу и задайте для сеанса портала нужный клиент Azure AD (с помощью **Switch Directory**). 61 | 3. В левой области навигации выберите службу **Azure Active Directory**, а затем выберите **Регистрация приложений (предварительный просмотр)**. 62 | 63 | #### Зарегистрировать клиентское приложение 64 | ![](https://github.com/nicolesigei/console-csharp-connect-sample/blob/master/readme-images/registrations.png) 65 | 1. На странице **регистрации приложений** выберите **зарегистрировать приложение**. 66 | 1. На странице **регистрацию приложений (Предварительная версия)** выберите **зарегистрировать приложение**. 67 | 2. При появлении страницы **зарегистрировать приложение** введите сведения о регистрации в приложении: в разделе **имя** введите понятное имя приложения, которое будет отображаться для пользователей приложения, например 68 | - консольное приложение для Microsoft Graph`. 69 | - в разделе **Поддерживаемые типы учетных записей** выберите **учетные записи в любом организационном каталоге и личных учетных записях Майкрософт (например, Skype, Xbox Outlook.com)**. 70 | — Чтобы создать приложение, нажмите кнопку ** зарегистрировать**. 71 | 3. На странице **Обзор** приложения найдите значение **Идентификатор приложения (клиент)** и запишите его, чтобы использовать его позже. Для этого проекта вам потребуется настроить файл конфигурации Visual Studio. 72 | 4. В списке страниц приложения выберите **проверку подлинности** 73 | 74 | - Используйте * urn: ietf: wg: oauth: 2.0: oob * в текстовом поле ** Redirect URI ** и выберите ** Type ** в качестве публичного клиента (для мобильных и настольных компьютеров) 75 | ![](https://github.com/nicolesigei/console-csharp-connect-sample/blob/master/readme-images/redirect.png) 76 | - В *предложенных URI перенаправления для общедоступных клиентов (мобильных, настольных)* установите второй флажок, чтобы приложение могло работать с библиотеками MSAL, используемыми в приложении. (Поле должно содержать параметр *urn: ietf: wg: oauth: 2.0: oob*). 77 | 5. В списке страниц приложения выберите **разрешения API** 78 | — щелкните **добавить разрешение**, а затем 79 | — убедитесь, что выбрана вкладка **Microsoft API**. 80 | — В *часто используемые API Microsoft API*, щелкните в **Microsoft Graph**. 81 | — В разделе **делегированные разрешения** убедитесь, что установлены нужные разрешения. **User.Read**, **Mail.Send** и **файлов. ReadWrite**. При необходимости используйте поле "Поиск". 82 | — Нажмите кнопку **добавить разрешения**. 83 | 84 | 85 | ### Этап 3. Настройка примера для использования клиента Azure AD 86 | 87 | В приведенных ниже инструкциях *идентификатор клиента* совпадает с *Идентификатором приложения * или *идентификатор приложения*. 88 | 89 | Откройте решение в Visual Studio для настройки проектов. 90 | 91 | #### Настроить клиентский проект 92 | 93 | 1. В папке *console-csharp-connect-sample* переименуйте файл `appsettings.json.example` в `appsettings.json` 94 | 1. Откройте и отредактируйте файл `appsettings.json`, чтобы внести следующие изменения 95 | 1. Найдите строку, где `ClientId` установлен как `YOUR_CLIENT_ID_HERE`, и замените существующее значение идентификатором приложения (клиента) приложения `Console App for Microsoft Graph`, скопированным с портала Azure. 96 | 97 | 98 | ### Этап 4. Сборка и запуск примера 99 | 100 | 1. Откройте пример решения в Visual Studio. 101 | 2. Нажмите клавишу F5 для сборки и запуска примера. Это восстановит зависимости пакета NuGet и откроет консольное приложение. 102 | 3. При появлении запроса войдите в свою учетную запись Microsoft и согласитесь с разрешениями, которые необходимы приложению. 103 | 4. Следуйте инструкциям, чтобы отправить сообщение из своей учетной записи себе или кому-либо еще. 104 | 105 | ## Вопросы и комментарии 106 | 107 | Мы будем рады получить ваши отзывы об API консольного приложения Microsoft Graph. Вы можете отправлять нам свои вопросы и предложения с помощью вкладки [Проблемы](https://github.com/microsoftgraph/console-csharp-connect-sample/issues) этого репозитория. 108 | 109 | Общие вопросы о разработке решений для Microsoft Graph следует задавать на сайте [Stack Overflow](https://stackoverflow.com/questions/tagged/microsoftgraph). Обязательно помечайте свои вопросы и комментарии тегом \[microsoftgraph]. 110 | 111 | ## Участие ## 112 | 113 | Если вы хотите добавить код в этот пример, просмотрите статью [CONTRIBUTING.MD](/CONTRIBUTING.md). 114 | 115 | Этот проект соответствует [Правилам поведения разработчиков открытого кода Майкрософт](https://opensource.microsoft.com/codeofconduct/). Дополнительные сведения см. в разделе [вопросов и ответов о правилах поведения](https://opensource.microsoft.com/codeofconduct/faq/). Если у вас возникли вопросы или замечания, напишите нам по адресу [opencode@microsoft.com](mailto:opencode@microsoft.com). 116 | 117 | ## Дополнительные ресурсы 118 | 119 | - [Другие примеры приложений, подключающихся с использованием Microsoft Graph](https://github.com/MicrosoftGraph?utf8=%E2%9C%93&query=-Connect) 120 | - [Microsoft Graph](https://developer.microsoft.com/en-us/graph) 121 | 122 | ## Авторские права 123 | (c) Корпорация Майкрософт (Microsoft Corporation), 2019. Все права защищены. 124 | -------------------------------------------------------------------------------- /README-localized/README-zh-cn.md: -------------------------------------------------------------------------------- 1 | --- 2 | page_type: sample 3 | products: 4 | - office-outlook 5 | - ms-graph 6 | languages: 7 | - csharp 8 | description: "此示例演示如何使用 Microsoft Graph API 将 Windows 控制台应用程序连接到 Microsoft 工作或学校帐户 (Azure Active Directory) 或个人帐户 (Microsoft) 以发送电子邮件。" 9 | extensions: 10 | contentType: samples 11 | technologies: 12 | - Microsoft Graph 13 | - Microsoft identity platform 14 | services: 15 | - Microsoft identity platform 16 | - Outlook 17 | createdDate: 12/11/2017 1:55:47 PM 18 | --- 19 | # Microsoft Graph C# 控制台连接示例 20 | 21 | ## 目录 22 | 23 | * [简介](#introduction) 24 | * [先决条件](#prerequisites) 25 | * [克隆或下载此存储库](#cloning-or-downloading-repo) 26 | * [配置 Azure AD 租户](#configuring-Azure-AD-tenant ) 27 | * [将示例配置为使用 Azure AD 租户](#configuring-sample-to-use-Azure-AD-tenant) 28 | * [生成并运行示例](#build-and-run-sample) 29 | * [问题和意见](#questions-and-comments) 30 | * [参与](#contributing) 31 | * [其他资源](#additional-resources) 32 | 33 | ## 简介 34 | 35 | 此示例演示如何使用 Microsoft Graph API 将 Windows 控制台应用程序连接到 Microsoft 工作或学校帐户 (Azure Active Directory) 或个人帐户 (Microsoft)。它使用 Microsoft Graph API 检索用户的个人资料图片,将该图片上传到 OneDrive,创建一个共享链接,然后发送一封以该照片为附件且在正文中包含该共享链接的电子邮件。它使用 Microsoft Graph .NET 客户端库来处理 Microsoft Graph 返回的数据。本示例使用 Azure AD 2.0 版终结点,支持用户通过其个人或工作/学校 Microsoft 帐户进行登录。 36 | 37 | 本示例使用 Microsoft 身份验证库 (MSAL) 进行身份验证。 38 | 39 | ## 先决条件 40 | 41 | 此示例要求如下: 42 | 43 | - [Visual Studio](https://www.visualstudio.com/en-us/downloads)(支持 C# 7 和更高版本)。 44 | - [Microsoft](www.outlook.com) 或 [Office 365 商业版帐户](https://msdn.microsoft.com/en-us/office/office365/howto/setup-development-environment#bk_Office365Account)。 45 | - Azure Active Directory (Azure AD) 租户。有关如何获取 Azure AD 租户的详细信息,请参阅[如何获取 Azure AD 租户](https://azure.microsoft.com/en-us/documentation/articles/active-directory-howto-tenant/)。 46 | 47 | ## 如何运行此示例 48 | 49 | 50 | ### 步骤 1:克隆或下载此存储库 51 | 52 | 在 shell 或命令行中键入: 53 | 54 | `git clone https://github.com/microsoftgraph/console-csharp-connect-sample` 55 | 56 | 57 | ### 步骤 2:配置 Azure AD 租户 58 | 59 | 1. 使用工作或学校帐户或个人 Microsoft 帐户登录到 [Azure 门户](https://portal.azure.com)。 60 | 2. 如果你的帐户有权访问多个租户,请在右上角选择该帐户,并将门户会话设置为所需的 Azure AD 租户(使用“**切换目录**”)。 61 | 3. 在左侧导航窗格中选择“**Azure Active Directory**”服务,然后选择“**应用注册(预览版)**”。 62 | 63 | #### 注册客户端应用 64 | ![](https://github.com/nicolesigei/console-csharp-connect-sample/blob/master/readme-images/registrations.png) 65 | 1.在“**应用注册**”页面中,选择“**注册应用程序**”。 66 | 1.在“**应用注册(预览版)**”页面中,选择“**注册应用程序**”。 67 | 2.屏幕上出现“**注册应用程序**”页面后,输入应用程序的注册信息: 68 | - 在“**名称**”部分中,输入要向应用程序用户显示的有意义的应用程序名称,例如`适用于 Microsoft Graph 的控制台应用` 69 | - 在“**支持的帐户类型**”部分中,选择“**任意组织目录中的帐户和个人 Microsoft 帐户(例如 Skype、Xbox、Outlook.com)**”。 70 | - 选择“**注册**”以创建应用程序。 71 | 3.在应用的“**概述**”页面上,查找“**应用程序(客户端) ID**”值,记录下来以供稍后使用。为此项目配置 Visual Studio 配置文件时将会用到该值。 72 | 4.在应用的页面列表中,选择“**身份验证**” 73 | 74 | - 在**重定向 URI**文本框中使用*urn:ietf:wg:oauth:2.0:oob*,并在**类型**中选择“公共客户端(移动和桌面)” 75 | ![](https://github.com/nicolesigei/console-csharp-connect-sample/blob/master/readme-images/redirect.png) 76 | - 在“*适用于公共客户端(移动、桌面)的建议重定向 URI*”中,选中第二个框,以便应用可以使用应用程序中使用的 MSAL 库。(此框应包含选项“*urn:ietf:wg:oauth:2.0:oob*”)。 77 | 5.在应用的页面列表中,选择“**API 权限**” 78 | - 单击“**添加权限**”按钮 79 | - 然后确保选中“**Microsoft API**”选项卡。 80 | - 在“*常用的 Microsoft API*”部分中,单击“**Microsoft Graph**”。 81 | - 在“**委派的权限**”部分中,确保选中正确的权限:“**User.Read**”、“**Mail.Send**”和“**Files.ReadWrite**”。如有必要,请使用搜索框。 82 | - 选择“**添加权限**”按钮。 83 | 84 | 85 | ### 步骤 3:将示例配置为使用 Azure AD 租户 86 | 87 | 在下面的步骤中,*客户端 ID* 与*应用程序 ID* 或*应用 ID* 相同。 88 | 89 | 在 Visual Studio 中打开解决方案以配置项目。 90 | 91 | #### 配置客户端项目 92 | 93 | 1. 在 *console-csharp-connect-sample* 文件夹中,将 `appsettings.json.example` 文件重命名为 `appsettings.json` 94 | 1. 打开并编辑 `appsettings.json` 文件以进行以下更改 95 | 1. 找到将 `ClientId` 设置为 `YOUR_CLIENT_ID_HERE` 的行,然后将现有值替换为从 Azure 门户复制的`适用于 Microsoft Graph 的控制台应用`这一应用程序的“应用程序(客户端) ID”。 96 | 97 | 98 | ### 步骤 4:生成并运行示例 99 | 100 | 1. 在 Visual Studio 中打开示例解决方案。 101 | 2. 按 F5 生成并运行此示例。这将还原 NuGet 包依赖项,并打开控制台应用程序。 102 | 3. 出现提示时,使用 Microsoft 帐户进行身份验证并同意应用程序所需的权限。 103 | 4. 按照提示从你的帐户向你自己或其他人发送一封邮件。 104 | 105 | ## 问题和意见 106 | 107 | 我们乐意倾听你有关 Microsoft Graph API 控制台应用的反馈。你可以在该存储库中的[问题](https://github.com/microsoftgraph/console-csharp-connect-sample/issues)部分将问题和建议发送给我们。 108 | 109 | 与 Microsoft Graph 开发相关的一般问题应发布到 [Stack Overflow](https://stackoverflow.com/questions/tagged/microsoftgraph)。请确保你的问题或意见标记有 \[microsoftgraph]。 110 | 111 | ## 参与 ## 112 | 113 | 如果想要参与本示例,请参阅 [CONTRIBUTING.MD](/CONTRIBUTING.md)。 114 | 115 | 此项目已采用 [Microsoft 开放源代码行为准则](https://opensource.microsoft.com/codeofconduct/)。有关详细信息,请参阅[行为准则常见问题解答](https://opensource.microsoft.com/codeofconduct/faq/)。如有其他任何问题或意见,也可联系 [opencode@microsoft.com](mailto:opencode@microsoft.com)。 116 | 117 | ## 其他资源 118 | 119 | - [其他 Microsoft Graph 连接示例](https://github.com/MicrosoftGraph?utf8=%E2%9C%93&query=-Connect) 120 | - [Microsoft Graph](https://developer.microsoft.com/en-us/graph) 121 | 122 | ## 版权信息 123 | 版权所有 (c) 2019 Microsoft。保留所有权利。 124 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # [ARCHIVED] Microsoft Graph C# Console Connect Sample 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 | * [Cloning or downloading this repository](#cloning-or-downloading-repo) 14 | * [Configure your Azure AD tenant](#configuring-Azure-AD-tenant ) 15 | * [Configure the sample to use your Azure AD tenant](#configuring-sample-to-use-Azure-AD-tenant) 16 | * [Build and run the sample](#build-and-run-sample) 17 | * [Questions and comments](#questions-and-comments) 18 | * [Contributing](#contributing) 19 | * [Additional resources](#additional-resources) 20 | 21 | ## Introduction 22 | 23 | This sample shows how to connect a Windows console application to a Microsoft work or school (Azure Active Directory) or personal (Microsoft) account using the Microsoft Graph API. It uses the Microsoft Graph API to retrieve a user's profile picture, upload the picture to OneDrive, create a sharing link, and send an email that contains the photo as an attachment and the sharing link in its text. It uses the Microsoft Graph .NET Client Library to work with data returned by Microsoft Graph. The sample uses the Azure AD v2.0 endpoint, which enables users to sign in with either their personal or work or school Microsoft accounts. 24 | 25 | The sample uses the Microsoft Authentication Library (MSAL) for authentication. 26 | 27 | ## Prerequisites 28 | 29 | This sample requires the following: 30 | 31 | - [Visual Studio](https://www.visualstudio.com/en-us/downloads) with C# version 7 and above. 32 | - Either a [Microsoft](www.outlook.com) or [Office 365 for business account](https://msdn.microsoft.com/en-us/office/office365/howto/setup-development-environment#bk_Office365Account). 33 | - An Azure Active Directory (Azure AD) tenant. For more information on how to get an Azure AD tenant, please see [How to get an Azure AD tenant](https://azure.microsoft.com/en-us/documentation/articles/active-directory-howto-tenant/). 34 | 35 | ## How To Run This Sample 36 | 37 | 38 | ### Step 1: Clone or download this repository 39 | 40 | From your shell or command line: 41 | 42 | `git clone https://github.com/microsoftgraph/console-csharp-connect-sample` 43 | 44 | 45 | ### Step 2: Configure your Azure AD tenant 46 | 47 | 1. Sign in to the [Azure portal](https://portal.azure.com) using either a work or school account or a personal Microsoft account. 48 | 2. If your account gives you access to more than one tenant, select your account in the top right corner, and set your portal session to the desired Azure AD tenant 49 | (using **Switch Directory**). 50 | 3. In the left-hand navigation pane, select the **Azure Active Directory** service, and then select **App registrations (Preview)**. 51 | 52 | #### Register the client app 53 | ![](https://github.com/nicolesigei/console-csharp-connect-sample/blob/master/readme-images/registrations.png) 54 | 1. In **App registrations** page, select **Register an Application**. 55 | 1. In **App registrations (Preview)** page, select **Register an Application**. 56 | 2. When the **Register an application page** appears, enter your application's registration information: 57 | - In the **Name** section, enter a meaningful application name that will be displayed to users of the app, for example `Console App for Microsoft Graph` 58 | - In the **Supported account types** section, select **Accounts in any organizational directory and personal Microsoft accounts (e.g. Skype, Xbox, Outlook.com)**. 59 | - Select **Register** to create the application. 60 | 3. On the app **Overview** page, find the **Application (client) ID** value and record it for later. You'll need it to configure the Visual Studio configuration file for this project. 61 | 4. In the list of pages for the app, select **Authentication** 62 | 63 | - Use *urn:ietf:wg:oauth:2.0:oob* in the **Redirect URI** text box and select the **Type** as Public Client (mobile and desktop) 64 | ![](https://github.com/nicolesigei/console-csharp-connect-sample/blob/master/readme-images/redirect.png) 65 | - In the *Suggested Redirect URIs for public clients(mobile,desktop)*, check the second box so that the app can work with the MSAL libs used in the application. (The box should contain the option *urn:ietf:wg:oauth:2.0:oob*). 66 | 5. In the list of pages for the app, select **API permissions** 67 | - Click the **Add a permission** button and then, 68 | - Ensure that the **Microsoft APIs** tab is selected. 69 | - In the *Commonly used Microsoft APIs* section, click on **Microsoft Graph**. 70 | - In the **Delegated permissions** section, ensure that the right permissions are checked: **User.Read**, **Mail.Send** and **Files.ReadWrite**. Use the search box if necessary. 71 | - Select the **Add permissions** button. 72 | 73 | 74 | ### Step 3: Configure the sample to use your Azure AD tenant 75 | 76 | In the steps below, *Client ID* is the same as *Application ID* or *App ID*. 77 | 78 | Open the solution in Visual Studio to configure the projects. 79 | 80 | #### Configure the client project 81 | 82 | 1. In the *console-csharp-connect-sample* folder, rename the `appsettings.json.example` file to `appsettings.json` 83 | 1. Open and edit the `appsettings.json` file to make the following change 84 | 1. Find the line where `ClientId` is set as `YOUR_CLIENT_ID_HERE` and replace the existing value with the application (client) ID of the `Console App for Microsoft Graph` application copied from the Azure portal. 85 | 86 | 87 | ### Step 4: Build and run the sample 88 | 89 | 1. Open the sample solution in Visual Studio. 90 | 2. Press F5 to build and run the sample. This will restore the NuGet package dependencies and open the console application. 91 | 3. When prompted, authenticate with your Microsoft account and consent to the permissions that the application needs. 92 | 4. Follow the prompts to send a message from your account to yourself or someone else. 93 | 94 | ## Questions and comments 95 | 96 | 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-connect-sample/issues) section of this repository. 97 | 98 | 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]. 99 | 100 | ## Contributing ## 101 | 102 | If you'd like to contribute to this sample, see [CONTRIBUTING.MD](/CONTRIBUTING.md). 103 | 104 | 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. 105 | 106 | ## Additional resources 107 | 108 | - [Other Microsoft Graph Connect samples](https://github.com/MicrosoftGraph?utf8=%E2%9C%93&query=-Connect) 109 | - [Microsoft Graph](https://developer.microsoft.com/en-us/graph) 110 | 111 | ## Copyright 112 | Copyright (c) 2019 Microsoft. All rights reserved. 113 | -------------------------------------------------------------------------------- /console-csharp-connect-sample.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.27004.2009 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "console-csharp-connect-sample", "console-csharp-connect-sample\console-csharp-connect-sample.csproj", "{DF76DFE5-5ECB-41CB-8E85-D7763225E15C}" 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 | {DF76DFE5-5ECB-41CB-8E85-D7763225E15C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {DF76DFE5-5ECB-41CB-8E85-D7763225E15C}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {DF76DFE5-5ECB-41CB-8E85-D7763225E15C}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {DF76DFE5-5ECB-41CB-8E85-D7763225E15C}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {415C80F0-526A-426A-9B24-1008507A121B} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /console-csharp-connect-sample/App.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /console-csharp-connect-sample/AuthenticationConfig.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019 Microsoft Corporation. All rights reserved. Licensed under the MIT license. 3 | See LICENSE in the project root for license information. 4 | */ 5 | 6 | using Microsoft.Extensions.Configuration; 7 | using System; 8 | using System.Collections.Generic; 9 | using System.Globalization; 10 | using System.IO; 11 | using System.Linq; 12 | 13 | namespace console_csharp_connect_sample 14 | { 15 | /// 16 | /// Description of the configuration of an AzureAD public client application (desktop/mobile application). This should 17 | /// match the application registration done in the Azure portal 18 | /// 19 | public class AuthenticationConfig 20 | { 21 | /// 22 | /// instance of Azure AD, for example public Azure or a Sovereign cloud (Azure China, Germany, US government, etc ...) 23 | /// 24 | public string Instance { get; set; } = "https://login.microsoftonline.com/{0}"; 25 | 26 | /// 27 | /// The Tenant is: 28 | /// - either the tenant ID of the Azure AD tenant in which this application is registered (a guid) 29 | /// or a domain name associated with the tenant 30 | /// - or 'organizations' (for a multi-tenant application) 31 | /// 32 | public string TenantId { get; set; } 33 | 34 | /// 35 | /// Guid used by the application to uniquely identify itself to Azure AD 36 | /// 37 | public string ClientId { get; set; } 38 | 39 | /// 40 | /// Delegated resource access permissions as configured in the application registration in your Azure account portal 41 | /// 42 | public IEnumerable Scopes { get; set; } 43 | 44 | /// 45 | /// URL of the authority 46 | /// 47 | public string Authority 48 | { 49 | get 50 | { 51 | return string.Format(CultureInfo.InvariantCulture, Instance, TenantId); 52 | } 53 | } 54 | 55 | /// 56 | /// Checks whether the configuration parameters have values. 57 | /// 58 | /// 59 | /// Returns an ArgumentNullException if the parameter is empty or has white space 60 | /// 61 | public void CheckParameters() 62 | { 63 | string message = "Parameter missing value in the config file"; 64 | if (string.IsNullOrWhiteSpace(ClientId)) 65 | throw new ArgumentNullException(nameof(ClientId), message); 66 | if (string.IsNullOrWhiteSpace(TenantId)) 67 | throw new ArgumentNullException(nameof(TenantId), message); 68 | if (string.IsNullOrWhiteSpace(Instance)) 69 | throw new ArgumentNullException(nameof(Instance), message); 70 | if (!Scopes.Any()) 71 | throw new ArgumentNullException(nameof(Scopes), message); 72 | } 73 | 74 | /// 75 | /// Reads the configuration from a json file 76 | /// 77 | /// Path to the configuration json file 78 | /// AuthenticationConfig read from the json file 79 | public static AuthenticationConfig ReadFromJsonFile(string path) 80 | { 81 | if (string.IsNullOrEmpty(path)) 82 | { 83 | throw new ArgumentException("Configuration file directory path not defined."); 84 | } 85 | try 86 | { 87 | IConfigurationRoot configuration; 88 | 89 | var builder = new ConfigurationBuilder() 90 | .SetBasePath(Directory.GetCurrentDirectory()) 91 | .AddJsonFile(path,false); 92 | 93 | configuration = builder.Build(); 94 | return configuration.Get(); 95 | } 96 | catch (FileNotFoundException) 97 | { 98 | throw; 99 | } 100 | } 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /console-csharp-connect-sample/Constants.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019 Microsoft Corporation. All rights reserved. Licensed under the MIT license. 3 | See LICENSE in the project root for license information. 4 | */ 5 | 6 | namespace console_csharp_connect_sample 7 | { 8 | internal class Constants 9 | { 10 | public const string EmailContent = 11 | " " + 12 | "

Congratulations!

This is a message from the Microsoft Graph Connect Sample. You are well on your way to incorporating Microsoft Graph endpoints in your apps." + 13 | "

Click here to view the profile photo you just uploaded to OneDrive!

What’s next?

" + 14 | "
  • Check out developer.microsoft.com/graph " + 15 | "to start building Microsoft Graph apps today with all the latest tools, templates, and guidance to get started quickly.
  • " + 16 | "
  • Use the Graph Explorer to explore the rest of the APIs and start your testing.
  • " + 17 | "
  • Browse other samples on GitHub to see more of the APIs in action.
" + 18 | "

Give us feedback

If you have any trouble running this sample, please log an issue." + 19 | "

For general questions about the Microsoft Graph API, post to Stack Overflow. " + 20 | "Make sure that your questions or comments are tagged with [microsoftgraph].

Thanks and happy coding!
Your Microsoft Graph samples development team

" + 21 | " "; 24 | } 25 | } -------------------------------------------------------------------------------- /console-csharp-connect-sample/GraphClientFactory.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019 Microsoft Corporation. All rights reserved. Licensed under the MIT license. 3 | See LICENSE in the project root for license information. 4 | */ 5 | 6 | using Microsoft.Graph; 7 | using Microsoft.Identity.Client; 8 | using System.Linq; 9 | using console_csharp_connect_sample.Helpers; 10 | using System.Collections.Generic; 11 | 12 | namespace console_csharp_connect_sample 13 | { 14 | /// 15 | /// This static class returns a fully constructed 16 | /// instance of the GraphServiceClient with the client 17 | /// data to be used when authenticating requests to the Graph API 18 | /// 19 | public static class GraphClientFactory 20 | { 21 | public static GraphServiceClient GetGraphServiceClient(string clientId, string authority, IEnumerable scopes) 22 | { 23 | var authenticationProvider = CreateAuthorizationProvider(clientId, authority, scopes); 24 | return new GraphServiceClient(authenticationProvider); 25 | } 26 | 27 | private static IAuthenticationProvider CreateAuthorizationProvider(string clientId, string authority, IEnumerable scopes) 28 | { 29 | var clientApplication = new PublicClientApplication(clientId, authority); 30 | return new MsalAuthenticationProvider(clientApplication, scopes.ToArray()); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /console-csharp-connect-sample/Helpers/AuthHandler.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019 Microsoft Corporation. All rights reserved. Licensed under the MIT license. 3 | See LICENSE in the project root for license information. 4 | */ 5 | 6 | using Microsoft.Graph; 7 | using System.Net.Http; 8 | using System.Threading; 9 | using System.Threading.Tasks; 10 | 11 | namespace console_csharp_connect_sample.Helpers 12 | { 13 | /// 14 | /// This class allows an implementation of IAuthenticationProvider to be inserted into the DelegatingHandler 15 | /// pipeline of an HttpClient instance. In future versions of GraphSDK, many cross-cutting concerns will 16 | /// be implemented as DelegatingHandlers. This AuthHandler will come in the box. 17 | /// 18 | public class AuthHandler : DelegatingHandler 19 | { 20 | private IAuthenticationProvider _authenticationProvider; 21 | 22 | public AuthHandler(IAuthenticationProvider authenticationProvider, HttpMessageHandler innerHandler) 23 | { 24 | InnerHandler = innerHandler; 25 | _authenticationProvider = authenticationProvider; 26 | } 27 | 28 | protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken = default) 29 | { 30 | await _authenticationProvider.AuthenticateRequestAsync(request); 31 | return await base.SendAsync(request, cancellationToken); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /console-csharp-connect-sample/Helpers/MsalAuthenticationProvider.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019 Microsoft Corporation. All rights reserved. Licensed under the MIT license. 3 | See LICENSE in the project root for license information. 4 | */ 5 | 6 | using System.Net.Http; 7 | using System.Net.Http.Headers; 8 | using System.Threading.Tasks; 9 | using Microsoft.Identity.Client; 10 | using Microsoft.Graph; 11 | using System.Linq; 12 | 13 | namespace console_csharp_connect_sample.Helpers 14 | { 15 | /// 16 | /// This class encapsulates the details of getting a token from MSAL and exposes it via the 17 | /// IAuthenticationProvider interface so that GraphServiceClient or AuthHandler can use it. 18 | /// 19 | /// A significantly enhanced version of this class will in the future be available from 20 | /// the GraphSDK team. It will support all the types of Client Application as defined by MSAL. 21 | public class MsalAuthenticationProvider : IAuthenticationProvider 22 | { 23 | private PublicClientApplication _clientApplication; 24 | private string[] _scopes; 25 | 26 | public MsalAuthenticationProvider(PublicClientApplication clientApplication, string[] scopes) 27 | { 28 | _clientApplication = clientApplication; 29 | _scopes = scopes; 30 | } 31 | 32 | /// 33 | /// Update HttpRequestMessage with credentials 34 | /// 35 | public async Task AuthenticateRequestAsync(HttpRequestMessage request) 36 | { 37 | var authentication = await GetAuthenticationAsync(); 38 | request.Headers.Authorization = AuthenticationHeaderValue.Parse(authentication.CreateAuthorizationHeader()); 39 | } 40 | 41 | /// 42 | /// Acquire Token for user 43 | /// 44 | public async Task GetAuthenticationAsync() 45 | { 46 | AuthenticationResult authResult = null; 47 | var accounts = await _clientApplication.GetAccountsAsync(); 48 | 49 | try 50 | { 51 | authResult = await _clientApplication.AcquireTokenSilentAsync(_scopes, accounts.FirstOrDefault()); 52 | } 53 | catch (MsalUiRequiredException) 54 | { 55 | try 56 | { 57 | authResult = await _clientApplication.AcquireTokenAsync(_scopes); 58 | } 59 | catch (MsalException) 60 | { 61 | throw; 62 | } 63 | } 64 | 65 | return authResult; 66 | } 67 | 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /console-csharp-connect-sample/MailHelper.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019 Microsoft Corporation. All rights reserved. Licensed under the MIT license. 3 | See LICENSE in the project root for license information. 4 | */ 5 | 6 | using System; 7 | using System.Collections.Generic; 8 | using System.IO; 9 | using System.Threading.Tasks; 10 | using Microsoft.Graph; 11 | 12 | namespace console_csharp_connect_sample 13 | { 14 | class MailHelper 15 | { 16 | private static GraphServiceClient _graphServiceClient = null; 17 | 18 | public MailHelper(GraphServiceClient graphServiceClient) 19 | { 20 | _graphServiceClient = graphServiceClient; 21 | } 22 | 23 | /// 24 | /// Compose and send a new email. 25 | /// 26 | /// The subject line of the email. 27 | /// The body of the email. 28 | /// A semicolon-separated list of email addresses. 29 | /// 30 | public static async Task ComposeAndSendMailAsync(string subject, 31 | string bodyContent, 32 | string recipients) 33 | { 34 | // Get current user photo 35 | Stream photoStream = await GetCurrentUserPhotoStreamAsync(); 36 | 37 | 38 | // If the user doesn't have a photo, or if the user account is MSA, we use a default photo 39 | 40 | if (photoStream == null) 41 | { 42 | photoStream = new FileStream("test.jpg", FileMode.Open); 43 | } 44 | 45 | MemoryStream photoStreamMS = new MemoryStream(); 46 | // Copy stream to MemoryStream object so that it can be converted to byte array. 47 | await photoStream.CopyToAsync(photoStreamMS); 48 | photoStream.Close(); 49 | 50 | DriveItem photoFile = await UploadFileToOneDriveAsync(photoStreamMS.ToArray()); 51 | 52 | MessageAttachmentsCollectionPage attachments = new MessageAttachmentsCollectionPage(); 53 | attachments.Add(new FileAttachment 54 | { 55 | ODataType = "#microsoft.graph.fileAttachment", 56 | ContentBytes = photoStreamMS.ToArray(), 57 | ContentType = "image/png", 58 | Name = "me.png" 59 | }); 60 | 61 | // Get the sharing link and insert it into the message body. 62 | Permission sharingLink = await GetSharingLinkAsync(photoFile.Id); ; 63 | 64 | string bodyContentWithSharingLink = String.Format(bodyContent, sharingLink.Link.WebUrl); 65 | 66 | // Prepare the recipient list 67 | string[] splitter = { ";" }; 68 | var splitRecipientsString = recipients.Split(splitter, StringSplitOptions.RemoveEmptyEntries); 69 | List recipientList = new List(); 70 | 71 | foreach (string recipient in splitRecipientsString) 72 | { 73 | recipientList.Add(new Recipient { EmailAddress = new EmailAddress { Address = recipient.Trim() } }); 74 | } 75 | 76 | try 77 | { 78 | var email = new Message 79 | { 80 | Body = new ItemBody 81 | { 82 | Content = bodyContentWithSharingLink, 83 | ContentType = BodyType.Html, 84 | }, 85 | Subject = subject, 86 | ToRecipients = recipientList, 87 | Attachments = attachments 88 | }; 89 | 90 | try 91 | { 92 | await _graphServiceClient.Me.SendMail(email, true).Request().PostAsync(); 93 | } 94 | catch (ServiceException exception) 95 | { 96 | throw new Exception("We could not send the message: " + exception.Error == null ? "No error message returned." : exception.Error.Message); 97 | } 98 | } 99 | 100 | catch (Exception e) 101 | { 102 | throw new Exception("We could not send the message: " + e.Message); 103 | } 104 | } 105 | 106 | /// 107 | /// Gets the stream content of the signed-in user's photo. 108 | /// This snippet doesn't work with consumer accounts. 109 | /// 110 | /// Photo Stream 111 | public static async Task GetCurrentUserPhotoStreamAsync() 112 | { 113 | Stream currentUserPhotoStream = null; 114 | 115 | try 116 | { 117 | currentUserPhotoStream = await _graphServiceClient.Me.Photo.Content.Request().GetAsync(); 118 | 119 | } 120 | // If the user account is MSA (not work or school), the service will throw an exception. 121 | catch (Exception) 122 | { 123 | return null; 124 | } 125 | 126 | return currentUserPhotoStream; 127 | 128 | } 129 | 130 | /// 131 | /// Uploads the specified file to the user's root OneDrive directory. 132 | /// 133 | /// 134 | /// Path of uploaded OneDrive file 135 | public static async Task UploadFileToOneDriveAsync(byte[] file) 136 | { 137 | DriveItem uploadedFile = null; 138 | 139 | try 140 | { 141 | MemoryStream fileStream = new MemoryStream(file); 142 | uploadedFile = await _graphServiceClient.Me.Drive.Root.ItemWithPath("me.png").Content.Request().PutAsync(fileStream); 143 | } 144 | catch (ServiceException) 145 | { 146 | return null; 147 | } 148 | 149 | return uploadedFile; 150 | } 151 | 152 | public static async Task GetSharingLinkAsync(string Id) 153 | { 154 | Permission permission = null; 155 | 156 | try 157 | { 158 | permission = await _graphServiceClient.Me.Drive.Items[Id].CreateLink("view").Request().PostAsync(); 159 | } 160 | catch (ServiceException) 161 | { 162 | return null; 163 | } 164 | 165 | return permission; 166 | } 167 | } 168 | } 169 | -------------------------------------------------------------------------------- /console-csharp-connect-sample/Program.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019 Microsoft Corporation. All rights reserved. Licensed under the MIT license. 3 | See LICENSE in the project root for license information. 4 | */ 5 | 6 | using System; 7 | using System.IO; 8 | using System.Threading.Tasks; 9 | 10 | namespace console_csharp_connect_sample 11 | { 12 | class Program 13 | { 14 | static async Task Main(string[] args) 15 | { 16 | Console.WriteLine("Welcome to the C# Console Connect Sample!\n"); 17 | 18 | try 19 | { 20 | //********************************************************************* 21 | // setup Microsoft Graph Client for user. 22 | //********************************************************************* 23 | AuthenticationConfig config = AuthenticationConfig.ReadFromJsonFile("appsettings.json"); 24 | 25 | // Check whether config. parameters have values 26 | config.CheckParameters(); 27 | 28 | var graphServiceClient = GraphClientFactory.GetGraphServiceClient(config.ClientId, config.Authority, config.Scopes); 29 | 30 | if (graphServiceClient != null) 31 | { 32 | bool sendMail = true; 33 | while (sendMail) 34 | { 35 | var user = await graphServiceClient.Me.Request().GetAsync(); 36 | string userId = user.Id; 37 | string mailAddress = user.UserPrincipalName; 38 | string displayName = user.DisplayName; 39 | 40 | Console.WriteLine("Hello, " + displayName + ". Would you like to send an email to yourself or someone else?"); 41 | Console.WriteLine("Enter the address to which you'd like to send a message. If you enter nothing, the message will go to your address."); 42 | string userInputAddress = Console.ReadLine(); 43 | string messageAddress = String.IsNullOrEmpty(userInputAddress) ? mailAddress : userInputAddress; 44 | 45 | var mailHelper = new MailHelper(graphServiceClient); 46 | await MailHelper.ComposeAndSendMailAsync("Welcome to Microsoft Graph development with C# and the Microsoft Graph Connect sample", Constants.EmailContent, messageAddress); 47 | 48 | Console.WriteLine("\nEmail sent! \n Want to send another message? Type 'y' for yes and any other key to exit."); 49 | ConsoleKeyInfo userInputSendMail = Console.ReadKey(); 50 | sendMail = (userInputSendMail.KeyChar == 'y') ? true : false; 51 | Console.WriteLine(); 52 | } 53 | } 54 | else 55 | { 56 | Console.ForegroundColor = ConsoleColor.Red; 57 | Console.WriteLine("We weren't able to create a GraphServiceClient for you. Please check the output for errors."); 58 | Console.ResetColor(); 59 | Console.ReadKey(); 60 | return; 61 | } 62 | } 63 | catch(ArgumentNullException ex) 64 | { 65 | Console.ForegroundColor = ConsoleColor.Red; 66 | Console.WriteLine(ex.Message + "\nPlease follow the Readme instructions for configuring this application."); 67 | Console.ResetColor(); 68 | Console.ReadKey(); 69 | return; 70 | } 71 | catch (FileNotFoundException) 72 | { 73 | Console.ForegroundColor = ConsoleColor.Red; 74 | Console.WriteLine("The configuration file 'appsettings.json' was not found. " + 75 | "Rename the file 'appsettings.json.example' in the solutions folder to 'appsettings.json'." + 76 | "\nPlease follow the Readme instructions for configuring this application."); 77 | Console.ResetColor(); 78 | Console.ReadKey(); 79 | return; 80 | } 81 | catch (Exception ex) 82 | { 83 | Console.ForegroundColor = ConsoleColor.Red; 84 | Console.WriteLine("Sending an email failed with the following message: {0}", ex.Message); 85 | if (ex.InnerException != null) 86 | { 87 | Console.WriteLine("Error detail: {0}", ex.InnerException.Message); 88 | } 89 | Console.ResetColor(); 90 | Console.ReadKey(); 91 | return; 92 | } 93 | } 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /console-csharp-connect-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-connect-sample")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("console-csharp-connect-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("df76dfe5-5ecb-41cb-8e85-d7763225e15c")] 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-connect-sample/appsettings.json.example: -------------------------------------------------------------------------------- 1 | { 2 | // Azure Cloud instance among: 3 | // - https://login.microsoftonline.com/{0} for the AzurePublic 4 | // (see https://aka.ms/aaddevv2). This is the default value 5 | // - https://login.microsoftonline.us/{0} for AzureUsGovernment 6 | // (see https://docs.microsoft.com/azure/azure-government/documentation-government-developer-guide) 7 | // - https://login.partner.microsoftonline.cn/{0} for AzureChina 8 | // (see https://docs.microsoft.com/azure/china/china-get-started-developer-guide) 9 | // - https://login.microsoftonline.de/{0} for AzureGermany 10 | "Instance": "https://login.microsoftonline.com/{0}", 11 | 12 | 13 | // ClientId (ApplicationId) as copied from the application registration (which depends on the cloud instance) 14 | // See docs referenced in the AzureCloudInstance section above 15 | "ClientId": "YOUR_APP_ID_HERE", 16 | 17 | 18 | // Delegated resource access permissions 19 | // To use the default permissions configured in the application registration in your Azure account portal, 20 | // replace below with "https://graph.microsoft.com/.default" 21 | "Scopes": [ 22 | "User.Read", 23 | "Mail.Send", 24 | "Files.ReadWrite" 25 | ], 26 | 27 | 28 | // Azure AD Audience among: 29 | // - tenant ID or domain (only in your organization) 30 | // - "organizations" (multi-tenant): Any work and school accounts 31 | // - "common" (any work and school account or Microsoft personal account) 32 | // - "consumers" (Microsoft personal account only) 33 | "TenantId": "common" 34 | } -------------------------------------------------------------------------------- /console-csharp-connect-sample/console-csharp-connect-sample.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {DF76DFE5-5ECB-41CB-8E85-D7763225E15C} 8 | Exe 9 | console_csharp_connect_sample 10 | console-csharp-connect-sample 11 | v4.6.1 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 | 7.3 25 | 26 | 27 | AnyCPU 28 | pdbonly 29 | true 30 | bin\Release\ 31 | TRACE 32 | prompt 33 | 4 34 | 35 | 36 | 37 | ..\packages\Microsoft.Extensions.Configuration.2.2.0\lib\netstandard2.0\Microsoft.Extensions.Configuration.dll 38 | 39 | 40 | ..\packages\Microsoft.Extensions.Configuration.Abstractions.2.2.0\lib\netstandard2.0\Microsoft.Extensions.Configuration.Abstractions.dll 41 | 42 | 43 | ..\packages\Microsoft.Extensions.Configuration.Binder.2.2.0\lib\netstandard2.0\Microsoft.Extensions.Configuration.Binder.dll 44 | 45 | 46 | ..\packages\Microsoft.Extensions.Configuration.FileExtensions.2.2.0\lib\netstandard2.0\Microsoft.Extensions.Configuration.FileExtensions.dll 47 | 48 | 49 | ..\packages\Microsoft.Extensions.Configuration.Json.2.2.0\lib\netstandard2.0\Microsoft.Extensions.Configuration.Json.dll 50 | 51 | 52 | ..\packages\Microsoft.Extensions.FileProviders.Abstractions.2.2.0\lib\netstandard2.0\Microsoft.Extensions.FileProviders.Abstractions.dll 53 | 54 | 55 | ..\packages\Microsoft.Extensions.FileProviders.Physical.2.2.0\lib\netstandard2.0\Microsoft.Extensions.FileProviders.Physical.dll 56 | 57 | 58 | ..\packages\Microsoft.Extensions.FileSystemGlobbing.2.2.0\lib\netstandard2.0\Microsoft.Extensions.FileSystemGlobbing.dll 59 | 60 | 61 | ..\packages\Microsoft.Extensions.Primitives.2.2.0\lib\netstandard2.0\Microsoft.Extensions.Primitives.dll 62 | 63 | 64 | ..\packages\Microsoft.Graph.1.12.0\lib\net45\Microsoft.Graph.dll 65 | 66 | 67 | ..\packages\Microsoft.Graph.Core.1.12.0\lib\net45\Microsoft.Graph.Core.dll 68 | 69 | 70 | ..\packages\Microsoft.Identity.Client.2.7.0\lib\net45\Microsoft.Identity.Client.dll 71 | 72 | 73 | ..\packages\Newtonsoft.Json.11.0.2\lib\net45\Newtonsoft.Json.dll 74 | 75 | 76 | 77 | ..\packages\System.Buffers.4.4.0\lib\netstandard2.0\System.Buffers.dll 78 | 79 | 80 | 81 | 82 | 83 | ..\packages\System.Memory.4.5.1\lib\netstandard2.0\System.Memory.dll 84 | 85 | 86 | ..\packages\System.Net.Http.4.3.1\lib\net46\System.Net.Http.dll 87 | 88 | 89 | 90 | ..\packages\System.Numerics.Vectors.4.4.0\lib\net46\System.Numerics.Vectors.dll 91 | 92 | 93 | ..\packages\System.Runtime.CompilerServices.Unsafe.4.5.1\lib\netstandard2.0\System.Runtime.CompilerServices.Unsafe.dll 94 | 95 | 96 | ..\packages\System.Security.Cryptography.Algorithms.4.3.0\lib\net461\System.Security.Cryptography.Algorithms.dll 97 | 98 | 99 | ..\packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll 100 | 101 | 102 | ..\packages\System.Security.Cryptography.Primitives.4.3.0\lib\net46\System.Security.Cryptography.Primitives.dll 103 | 104 | 105 | ..\packages\System.Security.Cryptography.X509Certificates.4.3.0\lib\net461\System.Security.Cryptography.X509Certificates.dll 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | Always 128 | 129 | 130 | Designer 131 | 132 | 133 | 134 | 135 | Always 136 | 137 | 138 | 139 | -------------------------------------------------------------------------------- /console-csharp-connect-sample/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /console-csharp-connect-sample/test.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoftgraph/console-csharp-connect-sample/a443ced44f5e3cb27ea5dbb10f20b4d1d0c87702/console-csharp-connect-sample/test.jpg -------------------------------------------------------------------------------- /readme-images/ID.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoftgraph/console-csharp-connect-sample/a443ced44f5e3cb27ea5dbb10f20b4d1d0c87702/readme-images/ID.png -------------------------------------------------------------------------------- /readme-images/client.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoftgraph/console-csharp-connect-sample/a443ced44f5e3cb27ea5dbb10f20b4d1d0c87702/readme-images/client.png -------------------------------------------------------------------------------- /readme-images/client.xcf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoftgraph/console-csharp-connect-sample/a443ced44f5e3cb27ea5dbb10f20b4d1d0c87702/readme-images/client.xcf -------------------------------------------------------------------------------- /readme-images/redirect.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoftgraph/console-csharp-connect-sample/a443ced44f5e3cb27ea5dbb10f20b4d1d0c87702/readme-images/redirect.png -------------------------------------------------------------------------------- /readme-images/registrations.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoftgraph/console-csharp-connect-sample/a443ced44f5e3cb27ea5dbb10f20b4d1d0c87702/readme-images/registrations.png -------------------------------------------------------------------------------- /readme-images/registrations.xcf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoftgraph/console-csharp-connect-sample/a443ced44f5e3cb27ea5dbb10f20b4d1d0c87702/readme-images/registrations.xcf --------------------------------------------------------------------------------