├── .gitattributes ├── .github ├── dependabot.yml └── workflows │ ├── auto-merge-dependabot.yml │ └── dotnet.yml ├── .gitignore ├── .vscode ├── launch.json ├── settings.json └── tasks.json ├── CODE_OF_CONDUCT.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 ├── RegisterApp.ps1 ├── images ├── aad-application-id.png ├── aad-default-client-type.png ├── aad-portal-app-registrations.png └── aad-register-an-app.png └── src ├── DeltaQuery.csproj ├── Program.cs ├── Settings.cs └── appsettings.json /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | 4 | # Custom for Visual Studio 5 | *.cs diff=csharp 6 | *.sln merge=union 7 | *.csproj merge=union 8 | *.vbproj merge=union 9 | *.fsproj merge=union 10 | *.dbproj merge=union 11 | 12 | # Standard to msysgit 13 | *.doc diff=astextplain 14 | *.DOC diff=astextplain 15 | *.docx diff=astextplain 16 | *.DOCX diff=astextplain 17 | *.dot diff=astextplain 18 | *.DOT diff=astextplain 19 | *.pdf diff=astextplain 20 | *.PDF diff=astextplain 21 | *.rtf diff=astextplain 22 | *.RTF diff=astextplain 23 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: nuget # See documentation for possible values 4 | directory: /src/ # Location of package manifests 5 | schedule: 6 | interval: weekly 7 | - package-ecosystem: github-actions 8 | directory: / 9 | schedule: 10 | interval: weekly 11 | -------------------------------------------------------------------------------- /.github/workflows/auto-merge-dependabot.yml: -------------------------------------------------------------------------------- 1 | name: Auto-merge dependabot updates 2 | 3 | on: 4 | pull_request: 5 | branches: [ main ] 6 | 7 | permissions: 8 | pull-requests: write 9 | contents: write 10 | 11 | jobs: 12 | 13 | dependabot-merge: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | if: ${{ github.actor == 'dependabot[bot]' }} 18 | 19 | steps: 20 | - name: Dependabot metadata 21 | id: metadata 22 | uses: dependabot/fetch-metadata@v1.6.0 23 | with: 24 | github-token: "${{ secrets.GITHUB_TOKEN }}" 25 | 26 | - name: Enable auto-merge for Dependabot PRs 27 | if: ${{steps.metadata.outputs.update-type != 'version-update:semver-major'}} 28 | run: gh pr merge --auto --merge "$PR_URL" 29 | env: 30 | PR_URL: ${{github.event.pull_request.html_url}} 31 | GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}} 32 | -------------------------------------------------------------------------------- /.github/workflows/dotnet.yml: -------------------------------------------------------------------------------- 1 | name: dotnet build 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | pull_request: 7 | branches: [ main ] 8 | 9 | jobs: 10 | build: 11 | 12 | runs-on: ubuntu-latest 13 | defaults: 14 | run: 15 | working-directory: src/ 16 | 17 | steps: 18 | - uses: actions/checkout@v3 19 | - name: Setup .NET 20 | uses: actions/setup-dotnet@v4 21 | with: 22 | dotnet-version: 7.0.x 23 | - name: Restore dependencies 24 | run: dotnet restore 25 | - name: Build 26 | run: dotnet build --no-restore 27 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.suo 8 | *.user 9 | *.userosscache 10 | *.sln.docstates 11 | 12 | # User-specific files (MonoDevelop/Xamarin Studio) 13 | *.userprefs 14 | 15 | # Build results 16 | [Dd]ebug/ 17 | [Dd]ebugPublic/ 18 | [Rr]elease/ 19 | [Rr]eleases/ 20 | x64/ 21 | x86/ 22 | bld/ 23 | [Bb]in/ 24 | [Oo]bj/ 25 | [Ll]og/ 26 | 27 | # Visual Studio 2015/2017 cache/options directory 28 | .vs/ 29 | # Uncomment if you have tasks that create the project's static files in wwwroot 30 | #wwwroot/ 31 | 32 | # Visual Studio 2017 auto generated files 33 | Generated\ Files/ 34 | 35 | # MSTest test Results 36 | [Tt]est[Rr]esult*/ 37 | [Bb]uild[Ll]og.* 38 | 39 | # NUNIT 40 | *.VisualState.xml 41 | TestResult.xml 42 | 43 | # Build Results of an ATL Project 44 | [Dd]ebugPS/ 45 | [Rr]eleasePS/ 46 | dlldata.c 47 | 48 | # Benchmark Results 49 | BenchmarkDotNet.Artifacts/ 50 | 51 | # .NET Core 52 | project.lock.json 53 | project.fragment.lock.json 54 | artifacts/ 55 | **/Properties/launchSettings.json 56 | 57 | # StyleCop 58 | StyleCopReport.xml 59 | 60 | # Files built by Visual Studio 61 | *_i.c 62 | *_p.c 63 | *_i.h 64 | *.ilk 65 | *.meta 66 | *.obj 67 | *.iobj 68 | *.pch 69 | *.pdb 70 | *.ipdb 71 | *.pgc 72 | *.pgd 73 | *.rsp 74 | *.sbr 75 | *.tlb 76 | *.tli 77 | *.tlh 78 | *.tmp 79 | *.tmp_proj 80 | *.log 81 | *.vspscc 82 | *.vssscc 83 | .builds 84 | *.pidb 85 | *.svclog 86 | *.scc 87 | 88 | # Chutzpah Test files 89 | _Chutzpah* 90 | 91 | # Visual C++ cache files 92 | ipch/ 93 | *.aps 94 | *.ncb 95 | *.opendb 96 | *.opensdf 97 | *.sdf 98 | *.cachefile 99 | *.VC.db 100 | *.VC.VC.opendb 101 | 102 | # Visual Studio profiler 103 | *.psess 104 | *.vsp 105 | *.vspx 106 | *.sap 107 | 108 | # Visual Studio Trace Files 109 | *.e2e 110 | 111 | # TFS 2012 Local Workspace 112 | $tf/ 113 | 114 | # Guidance Automation Toolkit 115 | *.gpState 116 | 117 | # ReSharper is a .NET coding add-in 118 | _ReSharper*/ 119 | *.[Rr]e[Ss]harper 120 | *.DotSettings.user 121 | 122 | # JustCode is a .NET coding add-in 123 | .JustCode 124 | 125 | # TeamCity is a build add-in 126 | _TeamCity* 127 | 128 | # DotCover is a Code Coverage Tool 129 | *.dotCover 130 | 131 | # AxoCover is a Code Coverage Tool 132 | .axoCover/* 133 | !.axoCover/settings.json 134 | 135 | # Visual Studio code coverage results 136 | *.coverage 137 | *.coveragexml 138 | 139 | # NCrunch 140 | _NCrunch_* 141 | .*crunch*.local.xml 142 | nCrunchTemp_* 143 | 144 | # MightyMoose 145 | *.mm.* 146 | AutoTest.Net/ 147 | 148 | # Web workbench (sass) 149 | .sass-cache/ 150 | 151 | # Installshield output folder 152 | [Ee]xpress/ 153 | 154 | # DocProject is a documentation generator add-in 155 | DocProject/buildhelp/ 156 | DocProject/Help/*.HxT 157 | DocProject/Help/*.HxC 158 | DocProject/Help/*.hhc 159 | DocProject/Help/*.hhk 160 | DocProject/Help/*.hhp 161 | DocProject/Help/Html2 162 | DocProject/Help/html 163 | 164 | # Click-Once directory 165 | publish/ 166 | 167 | # Publish Web Output 168 | *.[Pp]ublish.xml 169 | *.azurePubxml 170 | # Note: Comment the next line if you want to checkin your web deploy settings, 171 | # but database connection strings (with potential passwords) will be unencrypted 172 | *.pubxml 173 | *.publishproj 174 | 175 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 176 | # checkin your Azure Web App publish settings, but sensitive information contained 177 | # in these scripts will be unencrypted 178 | PublishScripts/ 179 | 180 | # NuGet Packages 181 | *.nupkg 182 | # The packages folder can be ignored because of Package Restore 183 | **/[Pp]ackages/* 184 | # except build/, which is used as an MSBuild target. 185 | !**/[Pp]ackages/build/ 186 | # Uncomment if necessary however generally it will be regenerated when needed 187 | #!**/[Pp]ackages/repositories.config 188 | # NuGet v3's project.json files produces more ignorable files 189 | *.nuget.props 190 | *.nuget.targets 191 | 192 | # Microsoft Azure Build Output 193 | csx/ 194 | *.build.csdef 195 | 196 | # Microsoft Azure Emulator 197 | ecf/ 198 | rcf/ 199 | 200 | # Windows Store app package directories and files 201 | AppPackages/ 202 | BundleArtifacts/ 203 | Package.StoreAssociation.xml 204 | _pkginfo.txt 205 | *.appx 206 | 207 | # Visual Studio cache files 208 | # files ending in .cache can be ignored 209 | *.[Cc]ache 210 | # but keep track of directories ending in .cache 211 | !*.[Cc]ache/ 212 | 213 | # Others 214 | ClientBin/ 215 | ~$* 216 | *~ 217 | *.dbmdl 218 | *.dbproj.schemaview 219 | *.jfm 220 | *.pfx 221 | *.publishsettings 222 | orleans.codegen.cs 223 | 224 | # Including strong name files can present a security risk 225 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 226 | #*.snk 227 | 228 | # Since there are multiple workflows, uncomment next line to ignore bower_components 229 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 230 | #bower_components/ 231 | 232 | # RIA/Silverlight projects 233 | Generated_Code/ 234 | 235 | # Backup & report files from converting an old project file 236 | # to a newer Visual Studio version. Backup files are not needed, 237 | # because we have git ;-) 238 | _UpgradeReport_Files/ 239 | Backup*/ 240 | UpgradeLog*.XML 241 | UpgradeLog*.htm 242 | ServiceFabricBackup/ 243 | *.rptproj.bak 244 | 245 | # SQL Server files 246 | *.mdf 247 | *.ldf 248 | *.ndf 249 | 250 | # Business Intelligence projects 251 | *.rdl.data 252 | *.bim.layout 253 | *.bim_*.settings 254 | *.rptproj.rsuser 255 | 256 | # Microsoft Fakes 257 | FakesAssemblies/ 258 | 259 | # GhostDoc plugin setting file 260 | *.GhostDoc.xml 261 | 262 | # Node.js Tools for Visual Studio 263 | .ntvs_analysis.dat 264 | node_modules/ 265 | 266 | # Visual Studio 6 build log 267 | *.plg 268 | 269 | # Visual Studio 6 workspace options file 270 | *.opt 271 | 272 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 273 | *.vbw 274 | 275 | # Visual Studio LightSwitch build output 276 | **/*.HTMLClient/GeneratedArtifacts 277 | **/*.DesktopClient/GeneratedArtifacts 278 | **/*.DesktopClient/ModelManifest.xml 279 | **/*.Server/GeneratedArtifacts 280 | **/*.Server/ModelManifest.xml 281 | _Pvt_Extensions 282 | 283 | # Paket dependency manager 284 | .paket/paket.exe 285 | paket-files/ 286 | 287 | # FAKE - F# Make 288 | .fake/ 289 | 290 | # JetBrains Rider 291 | .idea/ 292 | *.sln.iml 293 | 294 | # CodeRush 295 | .cr/ 296 | 297 | # Python Tools for Visual Studio (PTVS) 298 | __pycache__/ 299 | *.pyc 300 | 301 | # Cake - Uncomment if you are using it 302 | # tools/** 303 | # !tools/packages.config 304 | 305 | # Tabs Studio 306 | *.tss 307 | 308 | # Telerik's JustMock configuration file 309 | *.jmconfig 310 | 311 | # BizTalk build output 312 | *.btp.cs 313 | *.btm.cs 314 | *.odx.cs 315 | *.xsd.cs 316 | 317 | # OpenCover UI analysis results 318 | OpenCover/ 319 | 320 | # Azure Stream Analytics local run output 321 | ASALocalRun/ 322 | 323 | # MSBuild Binary and Structured Log 324 | *.binlog 325 | 326 | # NVidia Nsight GPU debugger configuration file 327 | *.nvuser 328 | 329 | # MFractors (Xamarin productivity tool) working folder 330 | .mfractor/ 331 | 332 | appsettings.Development.json 333 | auth-record.bin 334 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.2.0", 3 | "configurations": [ 4 | { 5 | // Use IntelliSense to find out which attributes exist for C# debugging 6 | // Use hover for the description of the existing attributes 7 | // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md 8 | "name": ".NET Core Launch (console)", 9 | "type": "coreclr", 10 | "request": "launch", 11 | "preLaunchTask": "build", 12 | // If you have changed target frameworks, make sure to update the program path. 13 | "program": "${workspaceFolder}/src/bin/Debug/net7.0/DeltaQuery.dll", 14 | "args": [], 15 | "cwd": "${workspaceFolder}/src", 16 | // For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console 17 | "console": "integratedTerminal", 18 | "stopAtEntry": false 19 | }, 20 | { 21 | "name": ".NET Core Attach", 22 | "type": "coreclr", 23 | "request": "attach" 24 | } 25 | ] 26 | } 27 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "cSpell.words": [ 3 | "Deltalink", 4 | "deltaquery" 5 | ], 6 | "[csharp]": { 7 | "editor.formatOnType": true 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0.0", 3 | "tasks": [ 4 | { 5 | "label": "build", 6 | "command": "dotnet", 7 | "type": "process", 8 | "args": [ 9 | "build", 10 | "${workspaceFolder}/src/DeltaQuery.csproj", 11 | "/property:GenerateFullPaths=true", 12 | "/consoleloggerparameters:NoSummary" 13 | ], 14 | "problemMatcher": "$msCompile" 15 | }, 16 | { 17 | "label": "publish", 18 | "command": "dotnet", 19 | "type": "process", 20 | "args": [ 21 | "publish", 22 | "${workspaceFolder}/src/DeltaQuery.csproj", 23 | "/property:GenerateFullPaths=true", 24 | "/consoleloggerparameters:NoSummary" 25 | ], 26 | "problemMatcher": "$msCompile" 27 | }, 28 | { 29 | "label": "watch", 30 | "command": "dotnet", 31 | "type": "process", 32 | "args": [ 33 | "watch", 34 | "run", 35 | "--project", 36 | "${workspaceFolder}/src/DeltaQuery.csproj" 37 | ], 38 | "problemMatcher": "$msCompile" 39 | } 40 | ] 41 | } 42 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Microsoft Open Source Code of Conduct 2 | 3 | This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). 4 | 5 | Resources: 6 | 7 | - [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/) 8 | - [Microsoft Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) 9 | - Contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with questions or concerns 10 | - Employees can reach out at [aka.ms/opensource/moderation-support](https://aka.ms/opensource/moderation-support) 11 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | # The MIT License (MIT) 2 | 3 | Copyright (c) 2023 Microsoft Corporation 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 | - ms-graph 5 | languages: 6 | - csharp 7 | extensions: 8 | contentType: samples 9 | technologies: 10 | - Microsoft Graph 11 | createdDate: 5/25/2017 5:03:53 PM 12 | --- 13 | # ConsoleApp-MicrosoftGraphAPI-DeltaQuery-DotNet 14 | 15 | Esta aplicación de consola demuestra cómo realizar llamadas de Consulta Delta a la Graph API, permitiendo que las aplicaciones soliciten sólo datos modificados a los inquilinos de Microsoft Graph. 16 | 17 | El ejemplo utiliza demostraciones de cómo se pueden hacer llamadas de Graph con el SDK de Graph y cómo se pueden manejar las respuestas. 18 | 19 | El ejemplo específico usado en este ejemplo implica la supervisión de los cambios (suma y eliminación) de MailFolders en la cuenta de correo electrónico de un usuario. 20 | 21 | ## Como ejecutar este ejemplo 22 | 23 | Para ejecutar este ejemplo necesitará: 24 | - Visual Studio 2017 25 | - Una conexión a Internet 26 | - Un inquilino del Azure Active Directory (Azure AD). Para más información sobre cómo conseguir un inquilino de Azure AD, por favor consulte [cómo conseguir un inquilino de Azure AD](https://azure.microsoft.com/en-us/documentation/articles/active-directory-howto-tenant/) 27 | 28 | ### Paso 1: Clone o descargue este repositorio 29 | 30 | Desde la línea de comandos o shell: 31 | 32 | `clonación de git https://github.com/microsoftgraph/ConsoleApp-DeltaQuery-DotNet` 33 | 34 | ### Paso 2: Registre la solicitud de muestra con su inquilino del Azure Active Directory 35 | 36 | Hay un proyecto en este ejemplo. Para registrarlo, puede: 37 | 38 | - o bien siga los pasos [paso 2: Registre la muestra con su inquilino del Azure Active Directory ](#step-2-register-the-sample-with-your-azure-active-directory-tenant)y[ paso 3: Configurar el ejemplo para usar el inquilino de Azure AD](#choose-the-azure-ad-tenant-where-you-want-to-create-your-applications) 39 | - o use los scripts de PowerShell que: 40 | - **automáticamente** crea las aplicaciones de Azure AD y los objetos relacionados (contraseñas, permisos, dependencias) para ti 41 | - modifica los archivos de configuración de los proyectos de Visual Studio. 42 | 43 | Si desea usar esta automatización: 44 | 45 | 1. En Windows ejecute PowerShell y navegue hasta la raíz del directorio clonado 46 | 1. En PowerShell, ejecute: 47 | 48 | ```PowerShell 49 | Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process -Force 50 | ``` 51 | 52 | 1. Ejecute el script para crear su aplicación Azure AD y configure el código de la aplicación de muestra de acuerdo con ello. 53 | 54 | ```PowerShell 55 | .\AppCreationScripts\Configure.ps1 56 | ``` 57 | 58 | > Otras formas de ejecutar los guiones se describen en [scripts de creación de aplicaciones ](./AppCreationScripts/AppCreationScripts.md) 59 | 60 | 1. Abra la solución de Visual Studio y haga clic en inicio. 61 | 62 | Si no quieres usar esta automatización, sigue los siguientes pasos a continuación 63 | 64 | #### Elija el inquilino de Azure AD donde quiere crear sus aplicaciones 65 | 66 | Como primer paso, tendrá que: 67 | 68 | 1. Iniciar sesión en el[ Azure Portal](https://portal.azure.com)usando una cuenta de trabajo o de escuela, o una cuenta personal de Microsoft. 69 | 1. Si su cuenta le da acceso a más de un inquilino, seleccione su cuenta en la esquina superior derecha y establezca su sesión de portal con el inquilino Azure AD deseado (usando**cambiar directorio**). 70 | 1. En el panel de navegación de la izquierda, seleccione el servicio de**Azure Active Directory**, y luego seleccione **registros de aplicaciones (vista previa)**. 71 | 72 | #### Registrar la aplicación cliente (ConsoleApp-DeltaQuery-DotNet) 73 | 74 | 1. En la página **Registros de aplicaciones (versión preliminar)**, seleccione **Registrar una aplicación**. 75 | 1. Cuando aparezca la **página registrar una aplicación**, escriba la información de registro de su aplicación: 76 | - En la sección **Nombre**, introducir un nombre de aplicación significativo que se mostrará a los usuarios de la aplicación, por ejemplo`ConsoleApp-DeltaQuery-DotNet`. 77 | - En la sección **tipos de cuentas admitidas**, seleccione **cuentas en cualquier directorio organizacional y cuentas personales de Microsoft (por ejemplo, Skype, Xbox, Outlook.com)**. 78 | - Seleccione **registrar** para crear la aplicación. 79 | 1. 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ás para configurar el archivo de configuración de Visual Studio para este proyecto. 80 | 1. En la lista de páginas de la aplicación, seleccione **autenticación**. 81 | - 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*). 82 | 1. En la lista de páginas de la aplicación, seleccione **Permisos de API**. 83 | - Haga clic en el botón **Agregar un permiso**. 84 | - Asegúrese de que la pestaña **API de Microsoft** está seleccionada. 85 | - En la sección *API de Microsoft más usadas*, haga clic en **Microsoft Graph**. 86 | - En la sección **Permisos delegados**, asegúrese de que se comprueben los permisos correctos: **Mail.Read**. Si es necesario, use el cuadro de búsqueda. 87 | - Seleccione el botón **Agregar permisos**. 88 | 89 | ### Paso 3: Configure el ejemplo para usar el inquilino de Azure AD 90 | 91 | En los pasos siguientes, "ClientID" es lo mismo que "Application ID" o "AppId". 92 | 93 | Abra la solución en Visual Studio para configurar los proyectos 94 | 95 | #### Configure el proyecto del cliente 96 | 97 | 1. En la carpeta *ConsoleApplication*, renombre el archivo `appsettings.json.example` a `appsettings.json` 98 | 1. Abra y edite el archivo `appsettings.json` para hacer el siguiente cambio 99 | 1. Encuentre la línea donde se establece`ClientId` como `YOUR_CLIENT_ID_HERE` y reemplace el valor existente con el ID de la aplicación (clientId) de la aplicación `ConsoleApp-DeltaQuery-DotNet` copiada del Azure portal. 100 | 101 | Limpie la solución, reconstruya la solución e inicie en el depurador. 102 | 103 | ## Colaboradores 104 | 105 | Si quiere hacer su aportación a este ejemplo, vea [CONTRIBUTING.MD](/CONTRIBUTING.md). 106 | 107 | 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. 108 | 109 | ## Preguntas y comentarios 110 | 111 | Nos encantaría recibir sus comentarios sobre Webhooks de Microsoft Graph con el SDK de WebJobs. Puede enviarnos sus preguntas y sugerencias a través de la sección [Problemas](https://github.com/microsoftgraph/ConsoleApp-DeltaQuery-DotNet/issues) de este repositorio. 112 | 113 | Las preguntas sobre Microsoft Graph en general deben publicarse en [desbordamiento de pila](https://stackoverflow.com/questions/tagged/MicrosoftGraph). Asegúrese de que sus preguntas o comentarios estén etiquetados con *\[MicrosoftGraph]*. 114 | 115 | Si quiere sugerir alguna función, publique su idea en nuestra página de [User Voice](https://officespdev.uservoice.com/) y vote por sus sugerencias. 116 | 117 | ## Recursos adicionales 118 | 119 | - [Ejemplo AAD DQ](https://github.com/Azure-Samples/active-directory-dotnet-graphapi-diffquery) 120 | - [Trabajando con Delta Query en Microsoft Graph ](https://developer.microsoft.com/en-us/graph/docs/concepts/delta_query_overview) 121 | - [Sitio para desarrolladores de Microsoft Graph](https://developer.microsoft.com/en-us/graph/) 122 | - [Llamar a Microsoft Graph desde una aplicación de ASP.NET MVC](https://developer.microsoft.com/en-us/graph/docs/platform/aspnetmvc) 123 | - [MSAL.NET](https://aka.ms/msal-net) 124 | 125 | Copyright (c) 2019 Microsoft Corporation. Todos los derechos reservados. 126 | -------------------------------------------------------------------------------- /README-localized/README-fr-fr.md: -------------------------------------------------------------------------------- 1 | --- 2 | page_type: sample 3 | products: 4 | - ms-graph 5 | languages: 6 | - csharp 7 | extensions: 8 | contentType: samples 9 | technologies: 10 | - Microsoft Graph 11 | createdDate: 5/25/2017 5:03:53 PM 12 | --- 13 | # ConsoleApp-MicrosoftGraphAPI-DeltaQuery-DotNet 14 | 15 | Cette application de console montre comment effectuer des appels de requête delta à l’API Graph pour permettre aux applications de demander uniquement les données modifiées aux clients Microsoft Graph. 16 | 17 | L’exemple montre comment les appels de graphiques peuvent être effectués avec le kit de développement logiciel (SDK) Graph et comment les réponses peuvent être gérées. 18 | 19 | L’exemple spécifique utilisé dans cet exemple implique la surveillance des modifications (ajout et suppression) de MailFolders dans le compte de messagerie d’une personne. 20 | 21 | ## Exécution de cet exemple 22 | 23 | Pour exécuter cet exemple, vous avez besoin des éléments suivants : 24 | - Visual Studio 2017 25 | - une connexion Internet 26 | - 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/) 27 | 28 | ### Étape 1 : Clonage ou téléchargement de ce référentiel 29 | 30 | À partir de votre shell ou de la ligne de commande : 31 | 32 | `git clone https://github.com/microsoftgraph/ConsoleApp-DeltaQuery-DotNet` 33 | 34 | ### Étape 2 : Inscription de l’exemple d’application avec votre client Azure Active Directory 35 | 36 | Cet exemple contient un seul projet. Pour l’enregistrer, vous pouvez : 37 | 38 | - soit suivre la procédure [Étape 2 : Inscription de l’exemple d’application avec votre client Azure Active Directory](#step-2-register-the-sample-with-your-azure-active-directory-tenant) et [Étape 3 : Configuration de l’échantillon pour utiliser votre client Azure AD](#choose-the-azure-ad-tenant-where-you-want-to-create-your-applications) 39 | - soit utiliser des scripts PowerShell qui : 40 | - créent **automatiquement** les applications Azure AD et les objets associés (mots de passe, autorisations, dépendances) à votre place 41 | - modifient les fichiers de configuration des projets Visual Studio. 42 | 43 | Si vous voulez utiliser cette automatisation : 44 | 45 | 1. Sous Windows, exécutez PowerShell et accédez à la racine du répertoire cloné 46 | 1. À partir de PowerShell, exécutez : 47 | 48 | ```PowerShell 49 | Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process -Force 50 | ``` 51 | 52 | 1. Exécutez le script pour créer votre application Azure AD et configurez le code de l’exemple d’application en conséquence. 53 | 54 | ```PowerShell 55 | .\AppCreationScripts\Configure.ps1 56 | ``` 57 | 58 | > D’autres méthodes d’exécution des scripts sont décrites dans [Scripts de création d’applications](./AppCreationScripts/AppCreationScripts.md) 59 | 60 | 1. Ouvrez le fichier de solution Visual Studio et cliquez sur Démarrer. 61 | 62 | Si vous ne voulez pas utiliser cette automatisation, suivez les étapes ci-dessous. 63 | 64 | #### Choix du client Azure AD où créer vos applications 65 | 66 | Pour commencer, vous devez effectuer les opérations suivantes : 67 | 68 | 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. 69 | 1. Si votre compte vous propose un accès à plusieurs clients, 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**). 70 | 1. Dans le volet de navigation gauche, sélectionnez le service **Azure Active Directory**, puis sélectionnez **Inscriptions d’applications (préversion)**. 71 | 72 | #### Inscription de l’application cliente (ConsoleApp-DeltaQuery-DotNet) 73 | 74 | 1. À la page **Inscriptions des applications (préversion)**, sélectionnez **Inscrire une application**. 75 | 1. Lorsque la **page Inscrire une application** s’affiche, saisissez les informations d’inscription de votre application : 76 | - Dans la section **Nom**, saisissez un nom d’application significatif qui s’affichera pour les utilisateurs de l’application, par exemple `ConsoleApp-DeltaQuery-DotNet`. 77 | - Dans la section **Types de comptes pris en charge**, sélectionnez **Comptes dans un annuaire organisationnel et comptes personnels Microsoft (par ex. Skype, Xbox, Outlook.com)**. 78 | - Sélectionnez **S’inscrire** pour créer l’application. 79 | 1. 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. 80 | 1. Dans la liste des pages de l’application, sélectionnez **Authentification**. 81 | - 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*). 82 | 1. Dans la liste des pages de l’application, sélectionnez **Permissions API**. 83 | - Cliquez sur le bouton **Ajouter une autorisation** puis, 84 | - Vérifiez que l'onglet **API Microsoft** est sélectionné 85 | - Dans la section *API Microsoft couramment utilisées*, cliquez sur **Microsoft Graph** 86 | - Dans la section **Autorisations déléguées**, assurez-vous que les autorisations appropriées sont vérifiées : **Mail.Read**. Utilisez la zone de recherche, le cas échéant. 87 | - Cliquez sur le bouton **Ajouter des autorisations** 88 | 89 | ### Étape 3 : Configuration de l’échantillon pour utiliser votre client Azure AD 90 | 91 | Dans les étapes ci-dessous, « ID client » est identique à « ID de l’application ». 92 | 93 | Ouverture de la solution dans Visual Studio pour configurer les projets 94 | 95 | #### Configurer le projet client 96 | 97 | 1. Dans le dossier *ConsoleApplication*, renommez le fichier `appsettings.json.example` en `appsettings.json`. 98 | 1. Ouvrez et modifiez le fichier `appSettings.json` pour apporter la modification suivante : 99 | 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 `ConsoleApp-DeltaQuery-DotNet` copié à partir du portail Azure. 100 | 101 | Nettoyez la solution, reconstruisez-la, puis démarrez-la dans le débogueur. 102 | 103 | ## Contribution 104 | 105 | Si vous souhaitez contribuer à cet exemple, voir [CONTRIBUTING.MD](/CONTRIBUTING.md). 106 | 107 | 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. 108 | 109 | ## Questions et commentaires 110 | 111 | N’hésitez pas à nous faire part de vos commentaires sur l’exemple de webhooks Microsoft Graph utilisant le kit de développement logiciel webjobs. Vous pouvez nous faire part de vos questions et suggestions dans la rubrique [Problèmes](https://github.com/microsoftgraph/ConsoleApp-DeltaQuery-DotNet/issues) de ce référentiel. 112 | 113 | Les questions générales sur Microsoft Graph doivent être publiées sur le [Dépassement de capacité de la pile](https://stackoverflow.com/questions/tagged/MicrosoftGraph). Veillez à poser vos questions ou à rédiger vos commentaires en utilisant les tags *\[MicrosoftGraph]*. 114 | 115 | Si vous avez des suggestions de fonctionnalité, soumettez votre idée sur notre page [Voix utilisateur](https://officespdev.uservoice.com/) et votez pour votre suggestion. 116 | 117 | ## Ressources supplémentaires 118 | 119 | - [Exemple AAD DQ](https://github.com/Azure-Samples/active-directory-dotnet-graphapi-diffquery) 120 | - [Utilisation de la requête delta dans Microsoft Graph](https://developer.microsoft.com/en-us/graph/docs/concepts/delta_query_overview) 121 | - [Site des développeurs de Microsoft Graph](https://developer.microsoft.com/en-us/graph/) 122 | - [Appel de Microsoft Graph dans une application ASP.NET MVC](https://developer.microsoft.com/en-us/graph/docs/platform/aspnetmvc) 123 | - [MSAL.NET](https://aka.ms/msal-net) 124 | 125 | Copyright (c) 2019 Microsoft Corporation. Tous droits réservés. 126 | -------------------------------------------------------------------------------- /README-localized/README-ja-jp.md: -------------------------------------------------------------------------------- 1 | --- 2 | page_type: sample 3 | products: 4 | - ms-graph 5 | languages: 6 | - csharp 7 | extensions: 8 | contentType: samples 9 | technologies: 10 | - Microsoft Graph 11 | createdDate: 5/25/2017 5:03:53 PM 12 | --- 13 | # ConsoleApp-MicrosoftGraphAPI-DeltaQuery-DotNet 14 | 15 | このコンソール アプリケーションは、アプリケーションが Microsoft Graph テナントからの変更データのみを要求できるように、Graph API に対するデルタ クエリ呼び出しを行う方法を示します。 16 | 17 | 使用するサンプルは、Graph SDK を使用してグラフの呼び出しを行う方法と、応答を処理する方法を示しています。 18 | 19 | このサンプルで使用される特定の例には、個人のメール アカウントの MailFolders の変更 (追加および削除) の監視が含まれます。 20 | 21 | ## このサンプルの実行方法 22 | 23 | このサンプルを実行するには、次のものが必要です。 24 | - Visual Studio 2017 25 | - インターネット接続 26 | - Azure Active Directory (Azure AD) テナント。Azure AD テナントを取得する方法の詳細については、「[Azure AD テナントを取得する方法](https://azure.microsoft.com/en-us/documentation/articles/active-directory-howto-tenant/)」を参照してください 27 | 28 | ### 手順 1: このリポジトリのクローンを作成するか、ダウンロードします 29 | 30 | シェルまたはコマンド ラインから: 31 | 32 | `git clone https://github.com/microsoftgraph/ConsoleApp-DeltaQuery-DotNet` 33 | 34 | ### 手順 2:Azure Active Directory テナントにサンプル アプリケーションを登録する 35 | 36 | このサンプルには 1 つのプロジェクトがあります。登録するには、次の操作を行います。 37 | 38 | - 次の手順に従ってください [手順 2:サンプルを Azure Active Directory テナント](#step-2-register-the-sample-with-your-azure-active-directory-tenant)に登録し、[手順 3:サンプルを構成して Azure AD テナント](#choose-the-azure-ad-tenant-where-you-want-to-create-your-applications)を使用します 39 | - または、[PowerShell スクリプト] を使用して: 40 | - Azure AD アプリケーションと関連オブジェクト (パスワード、アクセス許可、依存関係) を**自動的に**作成します 41 | - Visual Studio プロジェクトの構成ファイルを変更します。 42 | 43 | このオートメーションを使用する場合: 44 | 45 | 1. Windows で PowerShell を実行し、複製ディレクトリのルートに移動します 46 | 1. PowerShell で、以下を実行します。 47 | 48 | ```PowerShell 49 | Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process -Force 50 | ``` 51 | 52 | 1. スクリプトを実行して Azure AD アプリケーションを作成し、サンプル アプリケーションのコードを適切に構成します。 53 | 54 | ```PowerShell 55 | .\AppCreationScripts\Configure.ps1 56 | ``` 57 | 58 | > スクリプトを実行する他の方法は、「[App Creation Scripts (アプリ作成スクリプト)](./AppCreationScripts/AppCreationScripts.md)」で説明されています 59 | 60 | 1. Visual Studio ソリューション ファイルを開き、[開始] をクリックします 61 | 62 | このオートメーションを使用しない場合は、次の手順に従ってください 63 | 64 | #### アプリケーションを作成する Azure AD テナントを選択します 65 | 66 | まず、次のことを行う必要があります。 67 | 68 | 1. 職場または学校のアカウントか、個人の Microsoft アカウントを使用して、[Azure portal](https://portal.azure.com)にサインインします。 69 | 1. ご利用のアカウントで複数のテナントにアクセスできる場合は、右上隅でアカウントを選択し、ポータルのセッションを目的の Azure AD テナントに設定します (**Switch Directory** を使用)。 70 | 1. 左側のナビゲーション ウィンドウで、[**Azure Active Directory**] サービスを選択し、[**アプリの登録 (プレビュー)**] を選択します。 71 | 72 | #### クライアント アプリ (ConsoleApp-DeltaQuery-DotNet) を登録します。 73 | 74 | 1. [**アプリの登録 (プレビュー)**] ページで、[**アプリケーションを登録する**] を選択します。 75 | 1. [**アプリケーションの登録ページ**] が表示されたら、以下のアプリケーションの登録情報を入力します。 76 | - [**名前**] セクションに、アプリのユーザーに表示されるわかりやすいアプリケーション名を入力します (例: `ConsoleApp-DeltaQuery-DotNet`)。 77 | - [**サポートされているアカウントの種類**] セクションで、[**組織ディレクトリ内のアカウントと個人の Microsoft アカウント (例: Skype、Xbox、Outlook.com)**] を選択します。 78 | - [**登録**] を選択して、アプリケーションを作成します。 79 | 1. アプリの [**概要**] ページで、[**Application (client) ID**] (アプリケーション (クライアント) ID) の値を確認し、後で使用するために記録します。この情報は、このプロジェクトで Visual Studio 構成ファイルを設定するのに必要になります。 80 | 1. アプリのページの一覧から [**認証**] を選択します 81 | - [*パブリック クライアント (モバイル、デスクトップ) に推奨されるリダイレクト URI*] で、アプリケーションで使用されている MSAL ライブラリをアプリが利用できるように、2 番目のボックスをオンにします。(ボックスには、オプション *urn:ietf:wg:oauth:2.0:oob* を含める必要があります)。 82 | 1. アプリのページの一覧から [**API のアクセス許可**] を選択します。 83 | - [**アクセス許可の追加]**] ボタンをクリックします 84 | - [**Microsoft API**] タブが選択されていることを確認します 85 | - [*一般的に使用される Microsoft API*] セクションで、[**Microsoft Graph**] をクリックします 86 | - [**委任されたアクセス許可**] セクションで、適切なアクセス許可がチェックされていることを確認します。**Mail.Read**。必要に応じて検索ボックスを使用します。 87 | - [**アクセス許可の追加**] ボタンを選択します 88 | 89 | ### 手順 3:Azure AD テナントを使用するようにサンプルを構成する 90 | 91 | 次の手順では、"ClientID" は "Application ID" または "AppId" と同じです。 92 | 93 | Visual Studio でソリューションを開き、プロジェクトを構成します 94 | 95 | #### クライアント プロジェクトを構成する 96 | 97 | 1. *ConsoleApplication* フォルダーで、`appsettings.json.example` ファイルの名前を `appsettings.json` に変更します 98 | 1. `appsettings.json` ファイルを開いて編集し、次の変更を加えます 99 | 1. `ClientId` が `YOUR_CLIENT_ID_HERE` として設定されている行を見つけ、既存の値を Azure ポータルからコピーされた `ConsoleApp-DeltaQuery-DotNet` アプリケーションのアプリケーション ID (clientId) に置き換えます。 100 | 101 | ソリューションをクリーンアップし、ソリューションを再構築して、デバッガーで開始します。 102 | 103 | ## 投稿 104 | 105 | このサンプルに投稿する場合は、[CONTRIBUTING.MD](/CONTRIBUTING.md) を参照してください。 106 | 107 | このプロジェクトでは、[Microsoft Open Source Code of Conduct (Microsoft オープン ソース倫理規定)](https://opensource.microsoft.com/codeofconduct/) が採用されています。詳細については、「[Code of Conduct の FAQ (倫理規定の FAQ)](https://opensource.microsoft.com/codeofconduct/faq/)」を参照してください。また、その他の質問やコメントがあれば、[opencode@microsoft.com](mailto:opencode@microsoft.com) までお問い合わせください。 108 | 109 | ## 質問とコメント 110 | 111 | WebJobs SDK を使用して、Microsoft Graph Webhook のサンプルに関するフィードバックをぜひお寄せください。質問や提案は、このリポジトリの「[問題](https://github.com/microsoftgraph/ConsoleApp-DeltaQuery-DotNet/issues)」セクションで送信できます。 112 | 113 | Microsoft Graph 全般の質問については、「[Stack Overflow](https://stackoverflow.com/questions/tagged/MicrosoftGraph)」に投稿してください。質問やコメントには、必ず "*MicrosoftGraph*" とタグを付けてください。 114 | 115 | 機能に関して提案がございましたら、「[User Voice](https://officespdev.uservoice.com/)」ページでアイデアを投稿してから、その提案に投票してください。 116 | 117 | ## その他の技術情報 118 | 119 | - [AAD DQ サンプル](https://github.com/Azure-Samples/active-directory-dotnet-graphapi-diffquery) 120 | - [Working with Delta Query in Microsoft Graph (Microsoft Graph でのデルタ クエリの操作)](https://developer.microsoft.com/en-us/graph/docs/concepts/delta_query_overview) 121 | - [Microsoft Graph 開発者向けサイト](https://developer.microsoft.com/en-us/graph/) 122 | - [ASP.NET MVC アプリで Microsoft Graph を呼び出す](https://developer.microsoft.com/en-us/graph/docs/platform/aspnetmvc) 123 | - [MSAL.NET](https://aka.ms/msal-net) 124 | 125 | Copyright (c) 2019 Microsoft Corporation.All rights reserved. 126 | -------------------------------------------------------------------------------- /README-localized/README-pt-br.md: -------------------------------------------------------------------------------- 1 | --- 2 | page_type: sample 3 | products: 4 | - ms-graph 5 | languages: 6 | - csharp 7 | extensions: 8 | contentType: samples 9 | technologies: 10 | - Microsoft Graph 11 | createdDate: 5/25/2017 5:03:53 PM 12 | --- 13 | # ConsoleApp-MicrosoftGraphAPI-DeltaQuery-DotNet 14 | 15 | Este aplicativo de console demonstra como fazer chamadas de consulta Delta à API do Graph, permitindo que aplicativos solicitem somente os dados alterados de locatários do Microsoft Graph. 16 | 17 | O aplicativo de exemplo demonstra como chamadas do Graph podem ser feitas com o SDK do Graph e como as respostas podem ser manejas. 18 | 19 | O exemplo específico usado neste aplicativo de exemplo envolve monitoramento de alterações (adição e remoção) de MailFolders em uma conta de email individual. 20 | 21 | ## Como executar esse aplicativo de exemplo 22 | 23 | Para executar este exemplo, você precisará do seguinte: 24 | -Visual Studio 2017 25 | - Uma conexão com a Internet 26 | – Um locatário do Azure Active Directory (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/). 27 | 28 | ### Etapa 1: Clone ou baixe este repositório 29 | 30 | A partir de seu shell ou linha de comando: 31 | 32 | `git clone https://github.com/microsoftgraph/ConsoleApp-DeltaQuery-DotNet` 33 | 34 | ### Etapa 2: Registre seu aplicativo de exemplo com o locatário do Azure Active Directory 35 | 36 | Há um projeto neste exemplo. Para registrá-lo, você pode: 37 | 38 | - ou seguir as instruções das etapas [Etapa 2: Registre seu aplicativo de exemplo com o locatário do Azure Active Directory](#step-2-register-the-sample-with-your-azure-active-directory-tenant) e[Etapa 3: Configure seu aplicativo de exemplo para usar seu locatário Azure AD ](#choose-the-azure-ad-tenant-where-you-want-to-create-your-applications) 39 | - ou use scripts do PowerShell que: 40 | - **automaticamente ** criam os aplicativos do Azure AD e objetos relacionados (senhas, permissões e dependências) para você 41 | - modifiquem os arquivos de configuração dos projetos do Visual Studio. 42 | 43 | Se você quiser usar essa automação: 44 | 45 | 1. No Windows, execute o PowerShell e navegue até a raiz do diretório clonado 46 | 1. No PowerShell, execute: 47 | 48 | ```PowerShell 49 | Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process -Force 50 | ``` 51 | 52 | 1. Execute o script para criar seu aplicativo Azure AD e configure o código do aplicativo de exemplo adequadamente. 53 | 54 | ```PowerShell 55 | .\AppCreationScripts\Configure.ps1 56 | ``` 57 | 58 | > Outras maneiras de executar os scripts estão descritas na [Scripts de criação de aplicativos](./AppCreationScripts/AppCreationScripts.md) 59 | 60 | 1. Abra a solução do Visual Studio e clique em iniciar 61 | 62 | Se não quiser usar essa automação, siga as etapas abaixo. 63 | 64 | #### Escolha o locatário do Azure AD no local em que você deseja criar seus aplicativos 65 | 66 | Como primeira etapa, você precisará: 67 | 68 | 1. Entre no [portal do Azure](https://portal.azure.com)usando uma conta corporativa, de estudante ou uma conta Microsoft pessoal. 69 | 1. 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**). 70 | 1. No painel de navegação à esquerda, selecione o serviço **Azure Active Directory**e, em seguida, selecione **Registros de aplicativo (Visualização)**. 71 | 72 | #### Registre o aplicativo cliente (ConsoleApp-DeltaQuery-DotNet) 73 | 74 | 1. Na página **Registros de aplicativo (Visualização)**, selecione **Registrar um aplicativo**. 75 | 1. Quando a página **Registrar um aplicativo** for exibida, insira as informações de registro do aplicativo: 76 | - Na seção **Nome**, insira um nome de aplicativo relevante que será exibido aos usuários do aplicativo, por exemplo, `ConsoleApp-DeltaQuery-DotNet`. 77 | - Na seção **Tipos de conta com suporte**, selecione **Contas em qualquer diretório organizacional e contas pessoais do Microsoft (por exemplo: Skype, Xbox, Outlook.com)**. 78 | - Selecione **Registrar** para criar o aplicativo. 79 | 1. Na página **Visão geral** do aplicativo, encontre o valor de **ID do aplicativo (cliente)** e registre-o para usar mais tarde. Será necessário configurar o arquivo de configuração do Visual Studio para este projeto. 80 | 1. Na lista de páginas do aplicativo, selecione **Autenticação** 81 | - 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*). 82 | 1. Na lista de páginas do aplicativo, selecione **Permissões de API**. 83 | - Clique no botão **Adicionar uma permissão** e, em seguida, 84 | - Certifique-se de que a guia **APIs da Microsoft** esteja selecionada 85 | - Na seção *APIs mais usadas da Microsoft*, clique em **Microsoft Graph** 86 | - Na seção **Permissões delegadas**, verifique se as permissões corretas estão marcadas: **Mail.Read**. Use a caixa de pesquisa, se necessário. 87 | - Selecione o botão **Adicionar permissões** 88 | 89 | ### Etapa 3: Configurar o exemplo para usar seu locatário do Azure AD 90 | 91 | Nas etapas abaixo, "ClientID" é o mesmo que " ID do aplicativo" or "ID do app". 92 | 93 | Abra o recurso solução no Visual Studio para configurar os projetos. 94 | 95 | #### Configure o projeto cliente 96 | 97 | 1. Na pasta *ConsoleApplication*, renomeie o arquivo `appsettings.json.example` para `appsettings.json` 98 | 1. Abra e edite o arquivo `appsettings.json` para fazer a seguinte alteração 99 | 1. Localize a linha onde `ClientId` está definida como `YOUR_CLIENT_ID_HERE` e substitua o valor existente pelo ID do aplicativo (clientId) do aplicativo `ConsoleApp-DeltaQuery-DotNet` copiado do portal do Azure. 100 | 101 | Limpe a solução, recrie a solução e inicie-a no depurador. 102 | 103 | ## Colaboração 104 | 105 | Se quiser contribuir para esse exemplo, confira [CONTRIBUTING.MD](/CONTRIBUTING.md). 106 | 107 | 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. 108 | 109 | ## Perguntas e comentários 110 | 111 | Gostaríamos de receber seus comentários sobre o exemplo Microsoft Graph Webhooks usando o WebJobs SDK. Você pode nos enviar perguntas e sugestões na seção [Problemas](https://github.com/microsoftgraph/ConsoleApp-DeltaQuery-DotNet/issues) deste repositório. 112 | 113 | Em geral, as perguntas sobre o Microsoft Graph devem ser postadas no [Stack Overflow](https://stackoverflow.com/questions/tagged/MicrosoftGraph). Verifique se suas perguntas ou comentários estão marcados com *\[MicrosoftGraph]*. 114 | 115 | Se você tiver uma sugestão de recurso, poste sua ideia na nossa página em [Voz do Usuário](https://officespdev.uservoice.com/) e vote em suas sugestões. 116 | 117 | ## Recursos adicionais 118 | 119 | - [Exemplo de Consulta Delta (DQ) no AAD](https://github.com/Azure-Samples/active-directory-dotnet-graphapi-diffquery) 120 | - [Trabalhando com Consulta Delta no Microsoft Graph](https://developer.microsoft.com/en-us/graph/docs/concepts/delta_query_overview) 121 | - [Site do desenvolvedor do Microsoft Graph](https://developer.microsoft.com/en-us/graph/) 122 | - [Chamar o Microsoft Graph em um aplicativo do ASP.NET MVC](https://developer.microsoft.com/en-us/graph/docs/platform/aspnetmvc) 123 | - [MSAL.NET](https://aka.ms/msal-net) 124 | 125 | Direitos autorais (c) 2019 Microsoft Corporation. Todos os direitos reservados. 126 | -------------------------------------------------------------------------------- /README-localized/README-ru-ru.md: -------------------------------------------------------------------------------- 1 | --- 2 | page_type: sample 3 | products: 4 | - ms-graph 5 | languages: 6 | - csharp 7 | extensions: 8 | contentType: samples 9 | technologies: 10 | - Microsoft Graph 11 | createdDate: 5/25/2017 5:03:53 PM 12 | --- 13 | # ConsoleApp-MicrosoftGraphAPI-DeltaQuery-DotNet 14 | 15 | Это консольное приложение демонстрирует, как отправлять разностные запросы к API Graph, позволяя приложениям запрашивать только измененные данные из клиентов Microsoft Graph. 16 | 17 | Используемый пример демонстрирует, как можно выполнять вызовы графа с помощью Graph SDK и как можно обрабатывать ответы. 18 | 19 | Конкретный пример, используемый в этом примере, включает мониторинг изменений (добавление и удаление) MailFolders в учетной записи электронной почты отдельного человека. 20 | 21 | ## Как запустить этот образец 22 | 23 | Для запуска этого примера вам понадобятся: 24 | - Visual Studio 2017 25 | - подключение к Интернету 26 | - клиент Azure Active Directory (Azure AD). Дополнительную информацию о том, как получить клиента Azure AD, см. В разделе [Как получить клиента Azure AD](https://azure.microsoft.com/en-us/documentation/articles/active-directory-howto-tenant/). 27 | 28 | ### Шаг 1. Клонировать или скачать этот репозиторий 29 | 30 | Из вашей оболочки или командной строки: 31 | 32 | `git clone https://github.com/microsoftgraph/ConsoleApp-DeltaQuery-DotNet` 33 | 34 | ### Шаг 2. Зарегистрируйте образец приложения у своего клиента Azure Active Directory. 35 | 36 | В этом примере есть один проект. Чтобы зарегистрировать его, вы можете: 37 | 38 | - или выполните действия, описанные [шаге 2. Зарегистрируйте пример в клиенте Azure Active Directory](#step-2-register-the-sample-with-your-azure-active-directory-tenant) и [шаг 3. Настройка примера для использования клиента Azure AD](#choose-the-azure-ad-tenant-where-you-want-to-create-your-applications) 39 | - или используйте сценарии PowerShell, которые: 40 | - **автоматически** создает приложения Azure AD и связанные с ними объекты (пароли, разрешения, зависимости) 41 | - изменить файлы конфигурации проектов Visual Studio. 42 | 43 | Если вы хотите использовать эту автоматизацию: 44 | 45 | 1. В Windows запустите PowerShell и перейдите в корень клонированного каталога. 46 | 1. В PowerShell запустите: 47 | 48 | ```PowerShell 49 | Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process -Force 50 | ``` 51 | 52 | 1. Запустите сценарий, чтобы создать приложение Azure AD и соответствующим образом настроить код примера приложения. 53 | 54 | ```PowerShell 55 | .\AppCreationScripts\Configure.ps1 56 | ``` 57 | 58 | > Другие способы запуска сценариев описаны в [сценариях создания приложений](./AppCreationScripts/AppCreationScripts.md) 59 | 60 | 1. Откройте решение Visual Studio и нажмите кнопку "Пуск" 61 | 62 | Если вы не хотите использовать эту автоматизацию, выполните следующие действия 63 | 64 | #### Выберите клиента Azure AD, в котором вы хотите создавать свои приложения 65 | 66 | Сначала вам потребуется выполнить следующие действия: 67 | 68 | 1. Войдите на [портал Azure](https://portal.azure.com) с помощью личной учетной записи Майкрософт либо рабочей или учебной учетной записи. 69 | 1. Если ваша учетная запись предоставляет вам доступ более чем к одному арендатору, выберите свою учетную запись в верхнем правом углу и задайте для сеанса портала нужный клиент Azure AD (с помощью **Switch Directory**). 70 | 1. В левой области навигации выберите службу **Azure Active Directory**, а затем выберите **Регистрация приложений (предварительный просмотр)**. 71 | 72 | #### Регистрация клиентского приложения (ConsoleApp-DeltaQuery-DotNet) 73 | 74 | 1. На странице **регистрации приложений (Предварительный просмотр)** выберите **Зарегистрировать приложение**. 75 | 1. Когда появится страница **Зарегистрировать приложение**, введите регистрационную информацию вашего приложения: 76 | - В разделе **имя** введите понятное имя приложения, которое будет отображаться для пользователей приложения, например `ConsoleApp-DeltaQuery-DotNet`. 77 | - В разделе **Поддерживаемые типы учетных записей** выберите **Учетные записи в любом каталоге организации и личные учетные записи Майкрософт (например, Skype, Xbox, Outlook.com)**. 78 | - Выберите **Зарегистрировать**, чтобы создать приложение. 79 | 1. На странице **Обзор** приложения найдите значение **Идентификатор приложения (клиент)** и запишите его для последующего использования. Для этого проекта вам потребуется настроить файл конфигурации Visual Studio. 80 | 1. В списке страниц приложения выберите **проверку подлинности** 81 | - В *предложенных URI перенаправления для общедоступных клиентов (мобильных, настольных)* установите второй флажок, чтобы приложение могло работать с библиотеками MSAL, используемыми в приложении. (Поле должно содержать параметр *urn:ietf:wg:oauth:2.0:oob*). 82 | 1. В списке страниц приложения выберите **Разрешения API** 83 | - Нажмите кнопку **Добавить разрешение** и 84 | - Убедитесь, что выбрана вкладка **Интерфейсы API Microsoft** 85 | - В разделе *Часто используемые интерфейсы API Microsoft* щелкните **Microsoft Graph** 86 | - Убедитесь, что в разделе **Делегированные разрешения** выбраны правильные разрешения. **Mail.Read**. При необходимости используйте поле поиска. 87 | - Нажмите кнопку **Добавить разрешения** 88 | 89 | ### Этап 3. Настройка примера для использования клиента Azure AD 90 | 91 | В приведенных ниже инструкциях ClientID — это то же самое, что и "код приложения" или "AppId". 92 | 93 | Откройте решение в Visual Studio для настройки проектов 94 | 95 | #### Настроить клиентский проект 96 | 97 | 1. В папке *ConsoleApplication* переименуйте `appsettings.json.example` файл, чтобы `appSettings.json` 98 | 1. Откройте и отредактируйте файл `appsettings.json`, чтобы внести следующие изменения 99 | 1. Найдите строку, где `ClientId`установлен как `YOUR_CLIENT_ID_HERE`, и замените существующее значение идентификатором приложения (clientId) приложения `ConsoleApp-DeltaQuery-DotNet`, скопированным с портала Azure. 100 | 101 | Очистите решение, перестройте решение и запустите его в отладчике. 102 | 103 | ## Участие 104 | 105 | Если вы хотите добавить код в этот пример, просмотрите статью [CONTRIBUTING.MD](/CONTRIBUTING.md). 106 | 107 | Этот проект соответствует [Правилам поведения разработчиков открытого кода Майкрософт](https://opensource.microsoft.com/codeofconduct/). Дополнительные сведения см. в разделе [часто задаваемых вопросов о правилах поведения](https://opensource.microsoft.com/codeofconduct/faq/). Если у вас возникли вопросы или замечания, напишите нам по адресу [opencode@microsoft.com](mailto:opencode@microsoft.com). 108 | 109 | ## Вопросы и комментарии 110 | 111 | Мы хотели бы получить ваши отзывы о образце Microsoft Graph Webhooks с помощью WebJobs SDK. Вы можете отправлять нам вопросы и предложения в разделе [Проблемы](https://github.com/microsoftgraph/ConsoleApp-DeltaQuery-DotNet/issues) этого репозитория. 112 | 113 | Общие вопросы о Microsoft Graph следует задавать на сайте [Stack Overflow](https://stackoverflow.com/questions/tagged/MicrosoftGraph). Убедитесь, что ваши вопросы или комментарии содержат метку *\[MicrosoftGraph]*. 114 | 115 | Если у вас есть предложение по функции, пожалуйста, опубликуйте свою идею на нашей странице [Голос пользователя](https://officespdev.uservoice.com/) и проголосуйте за ваши предложения. 116 | 117 | ## Дополнительные ресурсы 118 | 119 | - [AAD DQ пример](https://github.com/Azure-Samples/active-directory-dotnet-graphapi-diffquery) 120 | - [Использование разностного запроса в Microsoft Graph](https://developer.microsoft.com/en-us/graph/docs/concepts/delta_query_overview) 121 | - [Сайт разработчика Microsoft Graph](https://developer.microsoft.com/en-us/graph/) 122 | - [Вызов Microsoft Graph в приложении ASP.NET MVC](https://developer.microsoft.com/en-us/graph/docs/platform/aspnetmvc) 123 | - [MSAL.NET](https://aka.ms/msal-net) 124 | 125 | © Корпорация Майкрософт (Microsoft Corporation), 2019. Все права защищены. 126 | -------------------------------------------------------------------------------- /README-localized/README-zh-cn.md: -------------------------------------------------------------------------------- 1 | --- 2 | page_type: sample 3 | products: 4 | - ms-graph 5 | languages: 6 | - csharp 7 | extensions: 8 | contentType: samples 9 | technologies: 10 | - Microsoft Graph 11 | createdDate: 5/25/2017 5:03:53 PM 12 | --- 13 | # ConsoleApp-MicrosoftGraphAPI-DeltaQuery-DotNet 14 | 15 | 此控制台应用程序演示如何对 Graph API 进行 Delta 查询调用,允许应用程序仅从 Microsoft Graph 租户请求更改的数据。 16 | 17 | 此示例演示如何使用 Graph SDK 调用图像以及如何处理响应。 18 | 19 | 此示例中使用的指定例子涉及监控各电子邮件账户中 MailFolders 的变化(添加和删除)。 20 | 21 | ## 如何运行此示例 22 | 23 | 若要运行此示例,需要: 24 | - Visual Studio 2017 25 | - 网络连接 26 | - Azure Active Directory (Azure AD) 租户。有关如何获取 Azure AD 租户的详细信息,请参阅[如何获取 Azure AD 租户](https://azure.microsoft.com/en-us/documentation/articles/active-directory-howto-tenant/) 27 | 28 | ### 步骤 1:克隆或下载此存储库 29 | 30 | 在 shell 或命令行中键入: 31 | 32 | `git clone https://github.com/microsoftgraph/ConsoleApp-DeltaQuery-DotNet` 33 | 34 | ### 步骤 2:将示例注册到 Azure Active Directory 租户 35 | 36 | 此示例中有一个项目。若要注册,可: 37 | 38 | - 遵照 [步骤 2:将示例注册到 Azure Active Directory 租户](#step-2-register-the-sample-with-your-azure-active-directory-tenant)和[步骤 3:将示例配置为使用 Azure AD 租户](#choose-the-azure-ad-tenant-where-you-want-to-create-your-applications) 39 | - 或使用 PowerShell 脚本: 40 | - **自动**为你创建 Azure AD 应用和相关对象(密码、权限、依赖项) 41 | - 修改 Visual Studio 项目的配置文件。 42 | 43 | 如果希望使用此自动化: 44 | 45 | 1. 在 Windows 上运行 PowerShell 并导航至克隆目录的根 46 | 1. 在 PowerShell 中,运行: 47 | 48 | ```PowerShell 49 | Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process -Force 50 | ``` 51 | 52 | 1. 运行此脚本创建 Azure AD 应用并相应配置示例应用的代码。 53 | 54 | ```PowerShell 55 | .\AppCreationScripts\Configure.ps1 56 | ``` 57 | 58 | > 有关运行脚本的其他方法,请参阅“[应用程序创建脚本](./AppCreationScripts/AppCreationScripts.md)” 59 | 60 | 1. 打开 Visual Studio 解决方案并点击开始 61 | 62 | 如果不希望使用此自动化,请按照下列步骤进行 63 | 64 | #### 选择要在其中创建应用程序的 Azure AD 租户 65 | 66 | 第一步需要执行以下操作: 67 | 68 | 1. 使用工作/学校帐户或 Microsoft 个人帐户登录到 [Azure 门户](https://portal.azure.com)。 69 | 1. 如果你的帐户有权访问多个租户,请在右上角选择该帐户,并将门户会话设置为所需的 Azure AD 租户(使用“**切换目录**”)。 70 | 1. 在左侧导航窗格中选择“**Azure Active Directory**”服务,然后选择“**应用注册(预览版)**”。 71 | 72 | #### 注册客户端应用(ConsoleApp-DeltaQuery-DotNet) 73 | 74 | 1. 在“**应用注册(预览版)**”页面中,选择“**注册应用程序**”。 75 | 1. 出现“**注册应用程序页**”后,输入应用程序的注册信息: 76 | - 在“**名称**”部分输入一个会显示给应用用户的有意义的应用程序名称,例如 `ConsoleApp-DeltaQuery-DotNet`。 77 | - 在“**支持的帐户类型**”部分,选择“**任何组织目录中的帐户和个人 Microsoft 帐户(例如 Skype、Xbox、Outlook.com)**”。 78 | - 选择“**注册**”以创建应用程序。 79 | 1. 在应用的“**概述**”页上,查找“**应用程序(客户端) ID**”值,并稍后记录下来。你将需要它来为此项目配置 Visual Studio 配置文件。 80 | 1. 在应用的页面列表中,选择“**身份验证**” 81 | - 在“*适用于公共客户端(移动、桌面)的建议重定向 URI*”中,选中第二个框,以便应用可以使用应用程序中使用的 MSAL 库。(此框应包含选项“*urn:ietf:wg:oauth:2.0:oob*”)。 82 | 1. 在应用的页面列表中,选择“**API 权限**” 83 | - 单击“**添加权限”**按钮,然后, 84 | - 确保已选中”**Microsoft API**”选项卡 85 | - 在“*常用 Microsoft API*”部分,单击“**Microsoft Graph**” 86 | - 在“**委派权限**”部分,确保已选中适当的权限:**Mail.Read**。必要时请使用搜索框。 87 | - 选择“**添加权限**”按钮 88 | 89 | ### 步骤 3:将示例配置为使用 Azure AD 租户 90 | 91 | 在下面的步骤中,“客户端 ID” 与“应用程序 ID” 或“AppId”相同。 92 | 93 | 在 Visual Studio 中打开解决方案以配置项目 94 | 95 | #### 配置客户端项目 96 | 97 | 1. 在 *ConsoleApplication* 文件夹中,将 `appsettings.json.example` 文件重命名为 `appsettings.json` 98 | 1. 打开并编辑 `appsettings.json` 文件以进行以下更改 99 | 1. 找到将 `ClientId` 设置为 `YOUR_CLIENT_ID_HERE` 的行,然后将现有值替换为从 Azure 门户复制的 `ConsoleApp-DeltaQuery-DotNet`应用程序的“应用程序(客户端) ID”。 100 | 101 | 清除解决方案,重新生成解决方案,并在调试程序中启动。 102 | 103 | ## 参与 104 | 105 | 如果想要参与本示例,请参阅 [CONTRIBUTING.MD](/CONTRIBUTING.md)。 106 | 107 | 此项目已采用 [Microsoft 开放源代码行为准则](https://opensource.microsoft.com/codeofconduct/)。有关详细信息,请参阅[行为准则 FAQ](https://opensource.microsoft.com/codeofconduct/faq/)。如有其他任何问题或意见,也可联系 [opencode@microsoft.com](mailto:opencode@microsoft.com)。 108 | 109 | ## 问题和意见 110 | 111 | 我们乐于收到反馈,了解使用 WebJobs SDK 的 Microsoft Graph Webhook 示例的情况。你可通过该存储库中的[问题](https://github.com/microsoftgraph/ConsoleApp-DeltaQuery-DotNet/issues)部分向我们发送问题和建议。 112 | 113 | 与 Microsoft Graph 相关的一般问题应发布到 [Stack Overflow](https://stackoverflow.com/questions/tagged/MicrosoftGraph)。请确保你的问题或意见标记有 *\[MicrosoftGraph]*。 114 | 115 | 如果有功能建议,请将你的想法发布在我们的 [User Voice](https://officespdev.uservoice.com/) 页上,并为你的建议进行投票。 116 | 117 | ## 其他资源 118 | 119 | - [AAD DQ 示例](https://github.com/Azure-Samples/active-directory-dotnet-graphapi-diffquery) 120 | - [在 Microsoft Graph 中使用 Delta Query](https://developer.microsoft.com/en-us/graph/docs/concepts/delta_query_overview) 121 | - [Microsoft Graph 开发人员网站](https://developer.microsoft.com/en-us/graph/) 122 | - [在 ASP.NET MVC 应用中调用 Microsoft Graph](https://developer.microsoft.com/en-us/graph/docs/platform/aspnetmvc) 123 | - [MSAL.NET](https://aka.ms/msal-net) 124 | 125 | 版权所有 (c) 2019 Microsoft Corporation。保留所有权利。 126 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | --- 2 | page_type: sample 3 | description: This console application demonstrates how to make delta queries to Microsoft Graph, allowing applications to request only changed entities within a target resource. This sample monitors changes to the mail folders in a user's mailbox. 4 | products: 5 | - ms-graph 6 | - microsoft-graph-mail-api 7 | - office-exchange-online 8 | languages: 9 | - csharp 10 | extensions: 11 | contentType: samples 12 | technologies: 13 | - Microsoft Graph 14 | createdDate: 5/25/2017 5:03:53 PM 15 | --- 16 | # Microsoft Graph delta query sample 17 | 18 | [![dotnet build](https://github.com/microsoftgraph/msgraph-sample-deltaquery/actions/workflows/dotnet.yml/badge.svg)](https://github.com/microsoftgraph/msgraph-sample-deltaquery/actions/workflows/dotnet.yml) ![License.](https://img.shields.io/badge/license-MIT-green.svg) 19 | 20 | This console application demonstrates how to make [delta queries](https://learn.microsoft.com/graph/delta-query-overview) to Microsoft Graph, allowing applications to request only changed entities within a target resource. This sample monitors changes to the mail folders in a user's mailbox. 21 | 22 | ## How To Run This Sample 23 | 24 | To run this sample you will need: 25 | 26 | - The [.NET 7.0 SDK](https://dotnet.microsoft.com/download) 27 | - A user in a Microsoft 365 tenant with an Exchange Online mailbox. 28 | 29 | ### Step 1: Register the sample application in Azure Active Directory 30 | 31 | Before running the sample, you will need to create an app registration in Azure Active Directory to obtain a client ID. You can do this with the PowerShell script in this sample, or you can register it manually in the Azure Active Directory portal. 32 | 33 | #### Option 1: Register with PowerShell 34 | 35 | The [RegisterApp.ps1](RegisterApp.ps1) script uses the [Microsoft Graph PowerShell SDK](https://learn.microsoft.com/microsoftgraph/overview) to create the app registration. You will need to [install the Microsoft Graph PowerShell SDK](https://learn.microsoft.com/powershell/microsoftgraph/installation) to use this script. 36 | 37 | > **IMPORTANT**: The PowerShell script requires a work/school account with the **Application administrator**, **Cloud application administrator**, or **Global administrator** role. If your account has the **Application developer** role, you can register in the Azure AD admin center. 38 | 39 | 1. Open [PowerShell 7](https://learn.microsoft.com/powershell/scripting/install/installing-powershell-on-windows) in the root directory of this sample. 40 | 41 | 1. Run the following command to set the execution policy for the current PowerShell window to allow the script to run. 42 | 43 | ```powershell 44 | Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process 45 | ``` 46 | 47 | 1. Run the script with the following command. 48 | 49 | ```powershell 50 | ./RegisterApp.ps1 -AppName "Delta Query Console Sample" 51 | ``` 52 | 53 | 1. Follow the prompt to open `https://microsoft.com/devicelogin` in a browser, enter the provided code, and complete the authentication process. 54 | 55 | 1. The application ID is printed to the console. 56 | 57 | ```powershell 58 | SUCCESS 59 | Client ID: 2fb1652f-a9a0-4db9-b220-b224b8d9d38b 60 | Tenant ID: common 61 | ``` 62 | 63 | #### Option 2: Register with the Azure Active Directory admin center 64 | 65 | 1. Open a browser and navigate to the [Azure Active Directory admin center](https://aad.portal.azure.com) and login using a Microsoft 365 user that has permission to register an application in Azure Active Directory. 66 | 67 | 1. Select **Azure Active Directory** in the left-hand navigation, then select **App registrations** under **Manage**. 68 | 69 | ![A screenshot of the App registrations ](./images/aad-portal-app-registrations.png) 70 | 71 | 1. Select **New registration**. On the **Register an application** page, set the values as follows. 72 | 73 | - Set **Name** to `Delta Query Console Sample`. 74 | - Set **Supported account types** to **Accounts in any organizational directory and personal Microsoft accounts**. 75 | - Leave **Redirect URI** empty. 76 | 77 | ![A screenshot of the Register an application page](./images/aad-register-an-app.png) 78 | 79 | 1. Select **Register**. On the **Delta Query Console Sample** page, copy the value of the **Application (client) ID** and save it, you will need it in the next step. 80 | 81 | ![A screenshot of the application ID of the new app registration](./images/aad-application-id.png) 82 | 83 | 1. Select **Authentication** under **Manage**. Locate the **Advanced settings** section and change the **Allow public client flows** toggle to **Yes**, then choose **Save**. 84 | 85 | ![A screenshot of the Default client type section](./images/aad-default-client-type.png) 86 | 87 | ### Step 2: Configure the sample 88 | 89 | Open [appsettings.json](src/appsettings.json) and replace `YOUR_CLIENT_ID_HERE` with the client ID of your app registration. Update other settings as needed. 90 | 91 | | Setting | Description | 92 | |---------|-------------| 93 | | `clientId` | The client ID of your app registration | 94 | | `tenantId` | If you registered your application as a [single tenant app](https://learn.microsoft.com/azure/active-directory/develop/single-and-multi-tenant-apps), add your Azure tenant ID here. Otherwise, leave as `common`. | 95 | | `graphUserScopes` | The Microsoft Graph permission scopes needed by the app. | 96 | | `pollInterval` | The number of seconds to wait between poll requests | 97 | | `authRecordCachePath` | Path to a file to cache the [authentication record](#authentication-record-cache). Set to empty string to disable authentication caching. | 98 | 99 | ### Step 3: Run the sample 100 | 101 | When the sample runs, it will prompt you to browse to a login URL and enter a device code. Once signed in, the app will check for changes to the mail folders in the user's mailbox every 30 seconds. 102 | 103 | #### Option 1: Using Visual Studio Code 104 | 105 | 1. Open the root folder of this sample using Visual Studio Code. 106 | 107 | 1. On the **Debug** menu, choose **Start Debugging**. 108 | 109 | #### Option 2: From the command line 110 | 111 | 1. Open your command-line interface (CLI) in the directory that contains **DeltaQuery.csproj**. 112 | 113 | 1. Run the following command to build the sample. 114 | 115 | ```Shell 116 | dotnet build 117 | ``` 118 | 119 | 1. Run the following command to run the sample. 120 | 121 | ```Shell 122 | dotnet run 123 | ``` 124 | 125 | ### Authentication record cache 126 | 127 | The first time you run this sample, it will prompt you to authenticate in your browser. Your authentication record will be persisted to disk so that if you run the sample again, the app will silently authenticate. You can make the app reauthenticate by deleting the authentication cache file before running the sample. 128 | 129 | To disable authentication caching, set the `authRecordCachePath` value in appsettings.json to an empty string. 130 | 131 | ## Code of conduct 132 | 133 | 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. 134 | 135 | ## Disclaimer 136 | 137 | **THIS CODE IS PROVIDED _AS IS_ WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.** 138 | -------------------------------------------------------------------------------- /RegisterApp.ps1: -------------------------------------------------------------------------------- 1 | # Copyright (c) Microsoft Corporation. All rights reserved. 2 | # Licensed under the MIT license. 3 | 4 | param( 5 | [Parameter(Mandatory=$true, 6 | HelpMessage="The friendly name of the app registration")] 7 | [String] 8 | $AppName, 9 | 10 | [Parameter(Mandatory=$false, 11 | HelpMessage="The sign in audience for the app")] 12 | [ValidateSet("AzureADMyOrg", "AzureADMultipleOrgs", ` 13 | "AzureADandPersonalMicrosoftAccount", "PersonalMicrosoftAccount")] 14 | [String] 15 | $SignInAudience = "AzureADandPersonalMicrosoftAccount", 16 | 17 | [Parameter(Mandatory=$false)] 18 | [Switch] 19 | $StayConnected = $false 20 | ) 21 | 22 | # Tenant to use in authentication. 23 | # See https://learn.microsoft.com/azure/active-directory/develop/v2-oauth2-device-code#device-authorization-request 24 | $authTenant = switch ($SignInAudience) 25 | { 26 | "AzureADMyOrg" { "tenantId" } 27 | "AzureADMultipleOrgs" { "organizations" } 28 | "AzureADandPersonalMicrosoftAccount" { "common" } 29 | "PersonalMicrosoftAccount" { "consumers" } 30 | default { "invalid" } 31 | } 32 | 33 | if ($authTenant -eq "invalid") 34 | { 35 | Write-Host -ForegroundColor Red "Invalid sign in audience:" $SignInAudience 36 | Exit 37 | } 38 | 39 | # Requires an admin 40 | Connect-MgGraph -Scopes "Application.ReadWrite.All User.Read" -UseDeviceAuthentication -ErrorAction Stop 41 | 42 | # Get context for access to tenant ID 43 | $context = Get-MgContext -ErrorAction Stop 44 | 45 | if ($authTenant -eq "tenantId") 46 | { 47 | $authTenant = $context.TenantId 48 | } 49 | 50 | # Create app registration 51 | $appRegistration = New-MgApplication -DisplayName $AppName -SignInAudience $SignInAudience ` 52 | -IsFallbackPublicClient -ErrorAction Stop 53 | Write-Host -ForegroundColor Cyan "App registration created with app ID" $appRegistration.AppId 54 | 55 | # Create corresponding service principal 56 | if ($SignInAudience -ne "PersonalMicrosoftAccount") 57 | { 58 | New-MgServicePrincipal -AppId $appRegistration.AppId -ErrorAction SilentlyContinue ` 59 | -ErrorVariable SPError | Out-Null 60 | if ($SPError) 61 | { 62 | Write-Host -ForegroundColor Red "A service principal for the app could not be created." 63 | Write-Host -ForegroundColor Red $SPError 64 | Exit 65 | } 66 | 67 | Write-Host -ForegroundColor Cyan "Service principal created" 68 | } 69 | 70 | Write-Host 71 | Write-Host -ForegroundColor Green "SUCCESS" 72 | Write-Host -ForegroundColor Cyan -NoNewline "Client ID: " 73 | Write-Host -ForegroundColor Yellow $appRegistration.AppId 74 | Write-Host -ForegroundColor Cyan -NoNewline "Tenant ID: " 75 | Write-Host -ForegroundColor Yellow $authTenant 76 | 77 | if ($StayConnected -eq $false) 78 | { 79 | Disconnect-MgGraph 80 | Write-Host "Disconnected from Microsoft Graph" 81 | } 82 | else 83 | { 84 | Write-Host 85 | Write-Host -ForegroundColor Yellow ` 86 | "The connection to Microsoft Graph is still active. To disconnect, use Disconnect-MgGraph" 87 | } 88 | -------------------------------------------------------------------------------- /images/aad-application-id.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoftgraph/msgraph-sample-deltaquery/32fdf9bd5588169016051920aa812bbc937b87b3/images/aad-application-id.png -------------------------------------------------------------------------------- /images/aad-default-client-type.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoftgraph/msgraph-sample-deltaquery/32fdf9bd5588169016051920aa812bbc937b87b3/images/aad-default-client-type.png -------------------------------------------------------------------------------- /images/aad-portal-app-registrations.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoftgraph/msgraph-sample-deltaquery/32fdf9bd5588169016051920aa812bbc937b87b3/images/aad-portal-app-registrations.png -------------------------------------------------------------------------------- /images/aad-register-an-app.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoftgraph/msgraph-sample-deltaquery/32fdf9bd5588169016051920aa812bbc937b87b3/images/aad-register-an-app.png -------------------------------------------------------------------------------- /src/DeltaQuery.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net7.0 6 | enable 7 | enable 8 | 9 | 10 | 11 | 12 | Always 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /src/Program.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Azure.Core; 5 | using Azure.Identity; 6 | using Microsoft.Graph; 7 | using Microsoft.Graph.Models; 8 | using Microsoft.Graph.Models.ODataErrors; 9 | using Microsoft.Graph.Me.MailFolders.Delta; 10 | 11 | Console.WriteLine("Delta Query Sample app\n"); 12 | 13 | try 14 | { 15 | // Load settings from appsettings.json 16 | var settings = Settings.LoadSettings(); 17 | 18 | var pollInterval = settings.PollInterval > 0 ? settings.PollInterval : 30; 19 | 20 | var credentialOptions = await GetCredentialOptionsAsync(settings); 21 | var credential = new DeviceCodeCredential(credentialOptions); 22 | if (credentialOptions.AuthenticationRecord == null) 23 | { 24 | // Pre-authenticate to persist an auth record 25 | await PreAuthenticateAsync(credential, settings); 26 | } 27 | 28 | var graphClient = new GraphServiceClient(credential, settings.GraphUserScopes); 29 | 30 | await WatchMailFoldersAsync(graphClient, pollInterval); 31 | } 32 | catch (Exception ex) 33 | { 34 | Console.WriteLine($"ERROR: {ex.Message}"); 35 | if (ex is ODataError oDataError) 36 | { 37 | Console.WriteLine(oDataError.Error?.Message); 38 | } 39 | Console.WriteLine(ex.StackTrace); 40 | } 41 | 42 | /// 43 | /// Syncs user's mail folders and periodically polls for changes via delta query. 44 | /// 45 | /// The GraphServiceClient to use for making API calls 46 | /// The number of seconds to wait between poll requests 47 | /// Completed Task 48 | static async Task WatchMailFoldersAsync(GraphServiceClient graphClient, int pollInterval) 49 | { 50 | // Local list of mail folders 51 | var localMailFolders = new List(); 52 | 53 | // Get the first page of folders 54 | var mailFoldersDelta = await graphClient.Me 55 | .MailFolders 56 | .Delta 57 | .GetAsync(); 58 | 59 | while (mailFoldersDelta != null) 60 | { 61 | if (mailFoldersDelta.Value == null || mailFoldersDelta.Value.Count <= 0) 62 | { 63 | Console.WriteLine("No changes..."); 64 | } 65 | else 66 | { 67 | var morePagesAvailable = false; 68 | 69 | do 70 | { 71 | if (mailFoldersDelta == null || mailFoldersDelta.Value == null) 72 | { 73 | continue; 74 | } 75 | 76 | // Process current page 77 | foreach (var folder in mailFoldersDelta.Value) 78 | { 79 | await ProcessFolderAsync(graphClient, folder, localMailFolders); 80 | } 81 | 82 | morePagesAvailable = !string.IsNullOrEmpty(mailFoldersDelta.OdataNextLink); 83 | 84 | if (morePagesAvailable) 85 | { 86 | // If there is a OdataNextLink, there are more pages 87 | // Get the next page of results 88 | var request = new DeltaRequestBuilder(mailFoldersDelta.OdataNextLink, graphClient.RequestAdapter); 89 | mailFoldersDelta = await request.GetAsync(); 90 | } 91 | } 92 | while (morePagesAvailable); 93 | } 94 | 95 | Console.WriteLine($"Processed current delta. Will check back in {pollInterval} seconds."); 96 | 97 | // Once we've iterated through all of the pages, there should 98 | // be a delta link, which is used to request all changes since our last query 99 | var deltaLink = mailFoldersDelta?.OdataDeltaLink; 100 | if (!string.IsNullOrEmpty(deltaLink)) 101 | { 102 | await Task.Delay(pollInterval * 1000); 103 | var request = new DeltaRequestBuilder(deltaLink, graphClient.RequestAdapter); 104 | mailFoldersDelta = await request.GetAsync(); 105 | } 106 | else 107 | { 108 | Console.WriteLine("No @odata.deltaLink found in response!"); 109 | } 110 | } 111 | } 112 | 113 | /// 114 | /// Checks a mail folder returned from a delta query against the local cache of mail folders. 115 | /// Determines if the folder was added, updated, or deleted. 116 | /// 117 | /// The GraphServiceClient to use for making API calls 118 | /// The mail folder 119 | /// The local cache of mail folders 120 | /// Completed Task 121 | static async Task ProcessFolderAsync(GraphServiceClient graphClient, MailFolder mailFolder, List localFolders) 122 | { 123 | // Check if the local list of folders already contains this one 124 | var localFolder = localFolders.Find(f => f.Id == mailFolder.Id); 125 | 126 | var isDeleted = mailFolder.AdditionalData != null ? 127 | mailFolder.AdditionalData.ContainsKey("@removed") : 128 | false; 129 | 130 | if (localFolder != null) 131 | { 132 | // In this case it's a delete or an update of 133 | // a folder we already know about 134 | if (isDeleted) 135 | { 136 | // Remove the entry from the local list 137 | Console.WriteLine($"Folder {localFolder.DisplayName} deleted"); 138 | localFolders.Remove(localFolder); 139 | } 140 | else 141 | { 142 | Console.WriteLine($"Folder {localFolder.DisplayName} updated:"); 143 | 144 | // Was it renamed? 145 | if (string.Compare(localFolder.DisplayName, mailFolder.DisplayName) != 0) 146 | { 147 | Console.WriteLine($" - Renamed to {mailFolder.DisplayName}"); 148 | } 149 | 150 | // Was it moved? 151 | if (string.Compare(localFolder.ParentFolderId, mailFolder.ParentFolderId) != 0) 152 | { 153 | // Get the parent folder 154 | var parent = await graphClient.Me 155 | .MailFolders[mailFolder.ParentFolderId] 156 | .GetAsync(); 157 | 158 | Console.WriteLine($" - Moved to {parent?.DisplayName} folder"); 159 | } 160 | 161 | // Remove old entry and add new one 162 | localFolders.Remove(localFolder); 163 | localFolders.Add(mailFolder); 164 | } 165 | } 166 | else 167 | { 168 | // No local match 169 | if (isDeleted) 170 | { 171 | // Folder deleted, but we never knew about it anyway 172 | Console.WriteLine($"Unknown folder with ID {mailFolder.Id} deleted"); 173 | } 174 | else 175 | { 176 | // New folder, add to local list 177 | Console.WriteLine($"Folder {mailFolder.DisplayName} added"); 178 | localFolders.Add(mailFolder); 179 | } 180 | } 181 | } 182 | 183 | /// 184 | /// Generates a DeviceCodeCredentialOptions instance based on application settings. 185 | /// 186 | /// The Settings instance containing application settings 187 | /// DeviceCodeCredentialOptions 188 | static async Task GetCredentialOptionsAsync(Settings settings) 189 | { 190 | var credentialOptions = new DeviceCodeCredentialOptions 191 | { 192 | ClientId = settings.ClientId, 193 | TenantId = settings.TenantId, 194 | DeviceCodeCallback = (info, cancel) => 195 | { 196 | Console.WriteLine(info.Message); 197 | return Task.FromResult(0); 198 | }, 199 | // Set TokenCachePersistenceOptions so Azure Identity library 200 | // will create a token cache. This will allow subsequent 201 | // runs of the app to silently authenticate 202 | TokenCachePersistenceOptions = new TokenCachePersistenceOptions 203 | { 204 | Name = "msgraph-sample-deltaquery.cache" 205 | } 206 | }; 207 | 208 | // In order to silently authenticate, we need to provide an 209 | // authentication record that identifies the user. 210 | if (!string.IsNullOrEmpty(settings.AuthRecordCachePath)) 211 | { 212 | try 213 | { 214 | // Attempt to load the cached auth record 215 | using (var readCacheStream = new FileStream(settings.AuthRecordCachePath, FileMode.Open, FileAccess.Read)) 216 | { 217 | var authRecord = await AuthenticationRecord.DeserializeAsync(readCacheStream); 218 | credentialOptions.AuthenticationRecord = authRecord; 219 | } 220 | } 221 | catch (FileNotFoundException) 222 | { 223 | Console.WriteLine("No cached authentication found"); 224 | } 225 | } 226 | 227 | return credentialOptions; 228 | } 229 | 230 | /// 231 | /// Authenticates the user and caches the resulting authentication record. 232 | /// 233 | /// The DeviceCodeCredential instance to use for authentication 234 | /// The Settings instance containing application settings 235 | /// Completed Task 236 | static async Task PreAuthenticateAsync(DeviceCodeCredential credential, Settings settings) 237 | { 238 | // If no path is set in settings, there's no need to 239 | // pre-authenticate 240 | if (!string.IsNullOrEmpty(settings.AuthRecordCachePath)) 241 | { 242 | var tokenContext = new TokenRequestContext(settings.GraphUserScopes ?? 243 | new[] {"https://graph.microsoft.com/.default"}); 244 | var authRecord = await credential.AuthenticateAsync(tokenContext); 245 | 246 | if (authRecord != null) 247 | { 248 | // Cache the auth record to disk so subsequent runs can 249 | // use it to silently authenticate 250 | using (var cacheStream = new FileStream(settings.AuthRecordCachePath, FileMode.Create, FileAccess.Write)) 251 | { 252 | await authRecord.SerializeAsync(cacheStream); 253 | } 254 | } 255 | } 256 | } 257 | -------------------------------------------------------------------------------- /src/Settings.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Microsoft Corporation. 2 | // Licensed under the MIT License. 3 | 4 | using Microsoft.Extensions.Configuration; 5 | 6 | /// 7 | /// Represents the settings for the application. 8 | /// 9 | public class Settings 10 | { 11 | /// 12 | /// The client ID (aka application ID) of your app registration. 13 | /// 14 | public string? ClientId { get; set; } 15 | /// 16 | /// The tenant ID of your Azure tenant. Set to "common" if app is registered as multi-tenant. 17 | /// 18 | public string? TenantId { get; set; } 19 | /// 20 | /// The Microsoft Graph permission scopes required by the app. 21 | /// 22 | public string[]? GraphUserScopes { get; set; } 23 | /// 24 | /// The number of seconds to wait between poll requests. 25 | /// 26 | public int PollInterval { get; set; } 27 | /// 28 | /// The path to a file where the authentication record should be persisted. Leave blank to disable auth caching. 29 | /// 30 | public string? AuthRecordCachePath { get; set; } 31 | 32 | /// 33 | /// Deserializes settings from appsettings.json + appsettings.Development.json. 34 | /// 35 | /// A Settings instance with the values from the JSON files. 36 | /// Thrown if the JSON files cannot be deserialized into a Settings instance. 37 | public static Settings LoadSettings() 38 | { 39 | // Load settings 40 | IConfiguration config = new ConfigurationBuilder() 41 | // appsettings.json is required 42 | .AddJsonFile("appsettings.json", optional: false) 43 | // appsettings.Development.json" is optional, values override appsettings.json 44 | .AddJsonFile("appsettings.Development.json", optional: true) 45 | .Build(); 46 | 47 | return config.GetRequiredSection("Settings").Get() ?? 48 | throw new Exception("Could not load app settings. See README for configuration instructions."); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "settings": { 3 | "clientId": "YOUR_CLIENT_ID_HERE", 4 | "tenantId": "common", 5 | "graphUserScopes": [ 6 | "mail.read" 7 | ], 8 | "pollInterval": 30, 9 | "authRecordCachePath": "./auth-record.bin" 10 | } 11 | } 12 | --------------------------------------------------------------------------------