├── .github └── workflows │ └── dotnet.yml ├── .gitignore ├── DataverseODataClient.Tests ├── .config │ └── dotnet-tools.json ├── Auth │ └── DataverseTokenProviderTests.cs ├── DataverseODataClient.Tests.csproj ├── Extensions │ └── ServiceCollectionExtensionsTests.cs ├── Middlewares │ ├── AuthorizationHeaderHandlerTests.cs │ ├── CorrelationIdHandlerTests.cs │ └── DelegatingHandlerTest.cs └── Services │ └── WebApiEndpointProviderTests.cs ├── DataverseODataClient.sln ├── DataverseODataClient ├── Auth │ ├── AzureIdentityTokenProvider.cs │ ├── DataverseTokenProvider.cs │ └── ITokenProvider.cs ├── DataverseODataClient.cs ├── DataverseODataClient.csproj ├── DataverseODataClientOptions.cs ├── Extensions │ └── ServiceCollectionExtensions.cs ├── Middlewares │ ├── AuthorizationHeaderHandler.cs │ └── CorrelationIdHandler.cs └── Services │ ├── ICorrelationIdProvider.cs │ ├── IWebApiEndpointProvider.cs │ └── WebApiEndpointProvider.cs ├── LICENSE └── README.md /.github/workflows/dotnet.yml: -------------------------------------------------------------------------------- 1 | name: Publish NuGet package 2 | 3 | on: 4 | push: 5 | branches: main 6 | 7 | env: 8 | BUILD_CONFIGURATION: Release 9 | 10 | jobs: 11 | build: 12 | runs-on: ubuntu-latest 13 | 14 | steps: 15 | - name: Checkout 16 | uses: actions/checkout@v3.1.0 17 | 18 | - name: Setup .NET Core SDK 19 | uses: actions/setup-dotnet@v2.0.0 20 | with: 21 | dotnet-version: 6.0.x 22 | 23 | - name: Setup NuGet.exe for use with actions 24 | uses: NuGet/setup-nuget@v1.1.1 25 | 26 | - name: Build 27 | run: dotnet build --configuration $BUILD_CONFIGURATION 28 | 29 | - name: Test 30 | run: dotnet test --no-build --configuration $BUILD_CONFIGURATION --collect:"XPlat Code Coverage" 31 | 32 | - name: Code coverage 33 | uses: codecov/codecov-action@v3.1.1 34 | with: 35 | token: ${{ secrets.CODECOV_TOKEN }} 36 | 37 | - name: Pack 38 | run: dotnet pack --no-build --configuration $BUILD_CONFIGURATION --output ./nupkgs 39 | 40 | - name: Push NuGet package 41 | env: 42 | NUGET_API_KEY: ${{ secrets.NUGET_API_KEY }} 43 | run: dotnet nuget push ./nupkgs/*.nupkg --source https://api.nuget.org/v3/index.json --api-key $NUGET_API_KEY --skip-duplicate 44 | 45 | -------------------------------------------------------------------------------- /.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 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Aa][Rr][Mm]/ 27 | [Aa][Rr][Mm]64/ 28 | bld/ 29 | [Bb]in/ 30 | [Oo]bj/ 31 | [Ll]og/ 32 | [Ll]ogs/ 33 | 34 | # Visual Studio 2015/2017 cache/options directory 35 | .vs/ 36 | # Uncomment if you have tasks that create the project's static files in wwwroot 37 | #wwwroot/ 38 | 39 | # Visual Studio 2017 auto generated files 40 | Generated\ Files/ 41 | 42 | # MSTest test Results 43 | [Tt]est[Rr]esult*/ 44 | [Bb]uild[Ll]og.* 45 | 46 | # NUnit 47 | *.VisualState.xml 48 | TestResult.xml 49 | nunit-*.xml 50 | 51 | # Build Results of an ATL Project 52 | [Dd]ebugPS/ 53 | [Rr]eleasePS/ 54 | dlldata.c 55 | 56 | # Benchmark Results 57 | BenchmarkDotNet.Artifacts/ 58 | 59 | # .NET Core 60 | project.lock.json 61 | project.fragment.lock.json 62 | artifacts/ 63 | 64 | # StyleCop 65 | StyleCopReport.xml 66 | 67 | # Files built by Visual Studio 68 | *_i.c 69 | *_p.c 70 | *_h.h 71 | *.ilk 72 | *.meta 73 | *.obj 74 | *.iobj 75 | *.pch 76 | *.pdb 77 | *.ipdb 78 | *.pgc 79 | *.pgd 80 | *.rsp 81 | *.sbr 82 | *.tlb 83 | *.tli 84 | *.tlh 85 | *.tmp 86 | *.tmp_proj 87 | *_wpftmp.csproj 88 | *.log 89 | *.vspscc 90 | *.vssscc 91 | .builds 92 | *.pidb 93 | *.svclog 94 | *.scc 95 | 96 | # Chutzpah Test files 97 | _Chutzpah* 98 | 99 | # Visual C++ cache files 100 | ipch/ 101 | *.aps 102 | *.ncb 103 | *.opendb 104 | *.opensdf 105 | *.sdf 106 | *.cachefile 107 | *.VC.db 108 | *.VC.VC.opendb 109 | 110 | # Visual Studio profiler 111 | *.psess 112 | *.vsp 113 | *.vspx 114 | *.sap 115 | 116 | # Visual Studio Trace Files 117 | *.e2e 118 | 119 | # TFS 2012 Local Workspace 120 | $tf/ 121 | 122 | # Guidance Automation Toolkit 123 | *.gpState 124 | 125 | # ReSharper is a .NET coding add-in 126 | _ReSharper*/ 127 | *.[Rr]e[Ss]harper 128 | *.DotSettings.user 129 | 130 | # TeamCity is a build add-in 131 | _TeamCity* 132 | 133 | # DotCover is a Code Coverage Tool 134 | *.dotCover 135 | 136 | # AxoCover is a Code Coverage Tool 137 | .axoCover/* 138 | !.axoCover/settings.json 139 | 140 | # Visual Studio code coverage results 141 | *.coverage 142 | *.coveragexml 143 | 144 | # NCrunch 145 | _NCrunch_* 146 | .*crunch*.local.xml 147 | nCrunchTemp_* 148 | 149 | # MightyMoose 150 | *.mm.* 151 | AutoTest.Net/ 152 | 153 | # Web workbench (sass) 154 | .sass-cache/ 155 | 156 | # Installshield output folder 157 | [Ee]xpress/ 158 | 159 | # DocProject is a documentation generator add-in 160 | DocProject/buildhelp/ 161 | DocProject/Help/*.HxT 162 | DocProject/Help/*.HxC 163 | DocProject/Help/*.hhc 164 | DocProject/Help/*.hhk 165 | DocProject/Help/*.hhp 166 | DocProject/Help/Html2 167 | DocProject/Help/html 168 | 169 | # Click-Once directory 170 | publish/ 171 | 172 | # Publish Web Output 173 | *.[Pp]ublish.xml 174 | *.azurePubxml 175 | # Note: Comment the next line if you want to checkin your web deploy settings, 176 | # but database connection strings (with potential passwords) will be unencrypted 177 | *.pubxml 178 | *.publishproj 179 | 180 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 181 | # checkin your Azure Web App publish settings, but sensitive information contained 182 | # in these scripts will be unencrypted 183 | PublishScripts/ 184 | 185 | # NuGet Packages 186 | *.nupkg 187 | # NuGet Symbol Packages 188 | *.snupkg 189 | # The packages folder can be ignored because of Package Restore 190 | **/[Pp]ackages/* 191 | # except build/, which is used as an MSBuild target. 192 | !**/[Pp]ackages/build/ 193 | # Uncomment if necessary however generally it will be regenerated when needed 194 | #!**/[Pp]ackages/repositories.config 195 | # NuGet v3's project.json files produces more ignorable files 196 | *.nuget.props 197 | *.nuget.targets 198 | 199 | # Microsoft Azure Build Output 200 | csx/ 201 | *.build.csdef 202 | 203 | # Microsoft Azure Emulator 204 | ecf/ 205 | rcf/ 206 | 207 | # Windows Store app package directories and files 208 | AppPackages/ 209 | BundleArtifacts/ 210 | Package.StoreAssociation.xml 211 | _pkginfo.txt 212 | *.appx 213 | *.appxbundle 214 | *.appxupload 215 | 216 | # Visual Studio cache files 217 | # files ending in .cache can be ignored 218 | *.[Cc]ache 219 | # but keep track of directories ending in .cache 220 | !?*.[Cc]ache/ 221 | 222 | # Others 223 | ClientBin/ 224 | ~$* 225 | *~ 226 | *.dbmdl 227 | *.dbproj.schemaview 228 | *.jfm 229 | *.pfx 230 | *.publishsettings 231 | orleans.codegen.cs 232 | 233 | # Including strong name files can present a security risk 234 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 235 | #*.snk 236 | 237 | # Since there are multiple workflows, uncomment next line to ignore bower_components 238 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 239 | #bower_components/ 240 | 241 | # RIA/Silverlight projects 242 | Generated_Code/ 243 | 244 | # Backup & report files from converting an old project file 245 | # to a newer Visual Studio version. Backup files are not needed, 246 | # because we have git ;-) 247 | _UpgradeReport_Files/ 248 | Backup*/ 249 | UpgradeLog*.XML 250 | UpgradeLog*.htm 251 | ServiceFabricBackup/ 252 | *.rptproj.bak 253 | 254 | # SQL Server files 255 | *.mdf 256 | *.ldf 257 | *.ndf 258 | 259 | # Business Intelligence projects 260 | *.rdl.data 261 | *.bim.layout 262 | *.bim_*.settings 263 | *.rptproj.rsuser 264 | *- [Bb]ackup.rdl 265 | *- [Bb]ackup ([0-9]).rdl 266 | *- [Bb]ackup ([0-9][0-9]).rdl 267 | 268 | # Microsoft Fakes 269 | FakesAssemblies/ 270 | 271 | # GhostDoc plugin setting file 272 | *.GhostDoc.xml 273 | 274 | # Node.js Tools for Visual Studio 275 | .ntvs_analysis.dat 276 | node_modules/ 277 | 278 | # Visual Studio 6 build log 279 | *.plg 280 | 281 | # Visual Studio 6 workspace options file 282 | *.opt 283 | 284 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 285 | *.vbw 286 | 287 | # Visual Studio LightSwitch build output 288 | **/*.HTMLClient/GeneratedArtifacts 289 | **/*.DesktopClient/GeneratedArtifacts 290 | **/*.DesktopClient/ModelManifest.xml 291 | **/*.Server/GeneratedArtifacts 292 | **/*.Server/ModelManifest.xml 293 | _Pvt_Extensions 294 | 295 | # Paket dependency manager 296 | .paket/paket.exe 297 | paket-files/ 298 | 299 | # FAKE - F# Make 300 | .fake/ 301 | 302 | # CodeRush personal settings 303 | .cr/personal 304 | 305 | # Python Tools for Visual Studio (PTVS) 306 | __pycache__/ 307 | *.pyc 308 | 309 | # Cake - Uncomment if you are using it 310 | # tools/** 311 | # !tools/packages.config 312 | 313 | # Tabs Studio 314 | *.tss 315 | 316 | # Telerik's JustMock configuration file 317 | *.jmconfig 318 | 319 | # BizTalk build output 320 | *.btp.cs 321 | *.btm.cs 322 | *.odx.cs 323 | *.xsd.cs 324 | 325 | # OpenCover UI analysis results 326 | OpenCover/ 327 | 328 | # Azure Stream Analytics local run output 329 | ASALocalRun/ 330 | 331 | # MSBuild Binary and Structured Log 332 | *.binlog 333 | 334 | # NVidia Nsight GPU debugger configuration file 335 | *.nvuser 336 | 337 | # MFractors (Xamarin productivity tool) working folder 338 | .mfractor/ 339 | 340 | # Local History for Visual Studio 341 | .localhistory/ 342 | 343 | # BeatPulse healthcheck temp database 344 | healthchecksdb 345 | 346 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 347 | MigrationBackup/ 348 | 349 | # Ionide (cross platform F# VS Code tools) working folder 350 | .ionide/ 351 | .idea 352 | -------------------------------------------------------------------------------- /DataverseODataClient.Tests/.config/dotnet-tools.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": 1, 3 | "isRoot": true, 4 | "tools": { 5 | "dotnet-stryker": { 6 | "version": "0.22.3", 7 | "commands": [ 8 | "dotnet-stryker" 9 | ] 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /DataverseODataClient.Tests/Auth/DataverseTokenProviderTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading; 3 | using System.Threading.Tasks; 4 | using Azure.Core; 5 | using BauerApps.DataverseODataClient.Auth; 6 | using FakeItEasy; 7 | using FluentAssertions; 8 | using Microsoft.Extensions.Caching.Memory; 9 | using Microsoft.Extensions.Options; 10 | using Xunit; 11 | 12 | namespace BauerApps.DataverseODataClient.Tests.Auth 13 | { 14 | public class DataverseTokenProviderTests 15 | { 16 | [Fact] 17 | public async Task ShouldReturnAcessToken() 18 | { 19 | // Arrange 20 | var options = Options.Create(new DataverseODataClientOptions 21 | { 22 | OrganizationUrl = new Uri("https://my-organization.crm4.dynamics.com") 23 | }); 24 | 25 | var accessToken = new AccessToken("123", DateTimeOffset.MaxValue); 26 | var credential = A.Fake(); 27 | A.CallTo(() => credential.GetTokenAsync(A._, A._)) 28 | .Returns(accessToken); 29 | 30 | var sut = new DataverseTokenProvider(options, A.Fake(), credential); 31 | 32 | // Act 33 | var token = await sut.GetTokenAsync(); 34 | 35 | // Assert 36 | token.Should().Be(accessToken); 37 | } 38 | 39 | [Fact] 40 | public async Task ShouldCacheAccessTokenWhenRequestedMultipleTimes() 41 | { 42 | // Arrange 43 | var options = Options.Create(new DataverseODataClientOptions 44 | { 45 | OrganizationUrl = new Uri("https://my-organization.crm4.dynamics.com") 46 | }); 47 | 48 | var cache = new MemoryCache(new MemoryCacheOptions()); 49 | 50 | var accessToken = new AccessToken("123", DateTimeOffset.MaxValue); 51 | var credential = A.Fake(); 52 | A.CallTo(() => credential.GetTokenAsync(A._, A._)) 53 | .Returns(accessToken); 54 | 55 | var sut = new DataverseTokenProvider(options, cache, credential); 56 | 57 | // Act 58 | await sut.GetTokenAsync(); 59 | await sut.GetTokenAsync(); 60 | await sut.GetTokenAsync(); 61 | 62 | // Assert 63 | A.CallTo(() => credential.GetTokenAsync(A._, A._)) 64 | .MustHaveHappenedOnceExactly(); 65 | } 66 | 67 | [Fact] 68 | public async Task ShouldRefreshAccessTokenWhenAccessTokenIsExpired() 69 | { 70 | // Arrange 71 | var options = Options.Create(new DataverseODataClientOptions 72 | { 73 | OrganizationUrl = new Uri("https://my-organization.crm4.dynamics.com") 74 | }); 75 | 76 | var cache = new MemoryCache(new MemoryCacheOptions()); 77 | 78 | var oldToken = new AccessToken("123", DateTimeOffset.UtcNow); 79 | var newToken = new AccessToken("123", DateTimeOffset.MaxValue); 80 | var credential = A.Fake(); 81 | A.CallTo(() => credential.GetTokenAsync(A._, A._)) 82 | .Returns(oldToken) 83 | .Once() 84 | .Then 85 | .Returns(newToken); 86 | 87 | var sut = new DataverseTokenProvider(options, cache, credential); 88 | 89 | // Act 90 | await sut.GetTokenAsync(); 91 | var accessToken = await sut.GetTokenAsync(); 92 | 93 | // Assert 94 | accessToken.Should().Be(newToken); 95 | } 96 | } 97 | } -------------------------------------------------------------------------------- /DataverseODataClient.Tests/DataverseODataClient.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | false 6 | 7 | net6.0 8 | 9 | BauerApps.DataverseODataClient.Tests 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | runtime; build; native; contentfiles; analyzers; buildtransitive 20 | all 21 | 22 | 23 | runtime; build; native; contentfiles; analyzers; buildtransitive 24 | all 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /DataverseODataClient.Tests/Extensions/ServiceCollectionExtensionsTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net.Http; 3 | using BauerApps.DataverseODataClient.Auth; 4 | using BauerApps.DataverseODataClient.Extensions; 5 | using BauerApps.DataverseODataClient.Middlewares; 6 | using BauerApps.DataverseODataClient.Services; 7 | using FluentAssertions; 8 | using Microsoft.Extensions.DependencyInjection; 9 | using Microsoft.Extensions.Options; 10 | using Simple.OData.Client; 11 | using Xunit; 12 | 13 | namespace BauerApps.DataverseODataClient.Tests.Extensions 14 | { 15 | public class ServiceCollectionExtensionsTests 16 | { 17 | [Fact] 18 | public void ShouldRegisterAllRequiredService() 19 | { 20 | // Arrange 21 | var sut = new ServiceCollection(); 22 | 23 | // Act 24 | sut.AddDataverseODataClient(options => { options.OrganizationUrl = new Uri("http://localhost"); }); 25 | 26 | // Assert 27 | sut.Should().Contain(x => 28 | x.ServiceType == typeof(ITokenProvider) && x.ImplementationType == typeof(DataverseTokenProvider)); 29 | sut.Should().Contain(x => 30 | x.ServiceType == typeof(IWebApiEndpointProvider) && 31 | x.ImplementationType == typeof(WebApiEndpointProvider)); 32 | sut.Should().Contain(x => x.ServiceType == typeof(AuthorizationHeaderHandler)); 33 | sut.Should().Contain(x => x.ServiceType == typeof(CorrelationIdHandler)); 34 | sut.Should().Contain(x => x.ServiceType == typeof(IHttpClientFactory)); 35 | } 36 | 37 | [Fact] 38 | public void ShouldConfigureOptions() 39 | { 40 | // Arrange 41 | var organizationUrl = new Uri("https://my-organization.crm4.dynamics.com"); 42 | const string clientId = "myUserAssignedManagedIdentityClientId"; 43 | 44 | var sut = new ServiceCollection(); 45 | 46 | // Act 47 | sut.AddDataverseODataClient(o => 48 | { 49 | o.OrganizationUrl = organizationUrl; 50 | o.ManagedIdentityClientId = clientId; 51 | }); 52 | 53 | // Assert 54 | var provider = sut.BuildServiceProvider(); 55 | 56 | var options = provider.GetRequiredService>(); 57 | options.Value.OrganizationUrl.Should().Be(organizationUrl); 58 | options.Value.ManagedIdentityClientId.Should().Be(clientId); 59 | } 60 | 61 | [Fact] 62 | public void ShouldConfigureHttpClient() 63 | { 64 | // Arrange 65 | var sut = new ServiceCollection(); 66 | 67 | // Act 68 | sut.AddDataverseODataClient(options => 69 | { 70 | options.OrganizationUrl = new Uri("https://my-organization.crm4.dynamics.com/"); 71 | }); 72 | 73 | // Assert 74 | var provider = sut.BuildServiceProvider(); 75 | 76 | var client = provider.GetRequiredService(); 77 | client.Should().BeOfType(); 78 | 79 | var httpClientFactory = provider.GetRequiredService(); 80 | var httpClient = httpClientFactory.CreateClient(nameof(IODataClient)); 81 | 82 | httpClient.BaseAddress.Should().Be("https://my-organization.crm4.dynamics.com/api/data/v9.1/"); 83 | } 84 | } 85 | } -------------------------------------------------------------------------------- /DataverseODataClient.Tests/Middlewares/AuthorizationHeaderHandlerTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net.Http; 3 | using System.Threading; 4 | using System.Threading.Tasks; 5 | using Azure.Core; 6 | using BauerApps.DataverseODataClient.Auth; 7 | using BauerApps.DataverseODataClient.Middlewares; 8 | using FakeItEasy; 9 | using FluentAssertions; 10 | using Xunit; 11 | 12 | namespace BauerApps.DataverseODataClient.Tests.Middlewares 13 | { 14 | public class AuthorizationHeaderHandlerTests : DelegatingHandlerTest 15 | { 16 | [Fact] 17 | public async Task ShouldAddBearerTokenToAuthorizationHeader() 18 | { 19 | // Arrange 20 | var accessToken = new AccessToken("MySecretAccessToken", DateTimeOffset.MaxValue); 21 | 22 | var tokenProvider = A.Fake(); 23 | A.CallTo(() => tokenProvider.GetTokenAsync(A._)) 24 | .Returns(accessToken); 25 | 26 | var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost"); 27 | 28 | var sut = new AuthorizationHeaderHandler(tokenProvider); 29 | 30 | // Act 31 | var result = await InvokeAsync(sut, request); 32 | 33 | // Assert 34 | result.Headers.Authorization.Should().NotBeNull(); 35 | result.Headers.Authorization?.Scheme.Should().Be("Bearer"); 36 | result.Headers.Authorization?.Parameter.Should().Be(accessToken.Token); 37 | } 38 | } 39 | } -------------------------------------------------------------------------------- /DataverseODataClient.Tests/Middlewares/CorrelationIdHandlerTests.cs: -------------------------------------------------------------------------------- 1 | using System.Net.Http; 2 | using System.Threading.Tasks; 3 | using BauerApps.DataverseODataClient.Middlewares; 4 | using BauerApps.DataverseODataClient.Services; 5 | using FakeItEasy; 6 | using FluentAssertions; 7 | using Xunit; 8 | 9 | namespace BauerApps.DataverseODataClient.Tests.Middlewares 10 | { 11 | public class CorrelationIdHandlerTests : DelegatingHandlerTest 12 | { 13 | [Fact] 14 | public async Task ShouldAddCorrelationIdAsQueryParameterWhenProvided() 15 | { 16 | // Arrange 17 | const string correlationId = "myCorrelationId"; 18 | var correlationIdProvider = A.Fake(); 19 | A.CallTo(() => correlationIdProvider.GetCorrelationId()) 20 | .Returns(correlationId); 21 | 22 | var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost"); 23 | 24 | var sut = new CorrelationIdHandler(correlationIdProvider); 25 | 26 | // Act 27 | var result = await InvokeAsync(sut, request); 28 | 29 | // Assert 30 | result.RequestUri?.Query.Should().Contain($"tag={correlationId}"); 31 | } 32 | 33 | [Fact] 34 | public async Task ShouldSkipExecutionWhenCorrelationIdIsNotProvided() 35 | { 36 | // Arrange 37 | var correlationIdProvider = A.Fake(); 38 | A.CallTo(() => correlationIdProvider.GetCorrelationId()) 39 | .Returns(null); 40 | 41 | var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost"); 42 | 43 | var sut = new CorrelationIdHandler(correlationIdProvider); 44 | 45 | // Act 46 | var result = await InvokeAsync(sut, request); 47 | 48 | // Assert 49 | result.RequestUri?.Query.Should().BeNullOrEmpty(); 50 | } 51 | 52 | [Fact] 53 | public async Task ShouldSkipExecutionWhenNoProviderIsRegistered() 54 | { 55 | // Arrange 56 | var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost"); 57 | 58 | var sut = new CorrelationIdHandler(); 59 | 60 | // Act 61 | var result = await InvokeAsync(sut, request); 62 | 63 | // Assert 64 | result.Should().BeEquivalentTo(request); 65 | } 66 | } 67 | } -------------------------------------------------------------------------------- /DataverseODataClient.Tests/Middlewares/DelegatingHandlerTest.cs: -------------------------------------------------------------------------------- 1 | using System.Net; 2 | using System.Net.Http; 3 | using System.Threading; 4 | using System.Threading.Tasks; 5 | 6 | namespace BauerApps.DataverseODataClient.Tests.Middlewares 7 | { 8 | public abstract class DelegatingHandlerTest 9 | { 10 | protected async Task InvokeAsync(DelegatingHandler handler, HttpRequestMessage request) 11 | { 12 | var testHandler = new TestDelegatingHandler(); 13 | handler.InnerHandler = testHandler; 14 | 15 | var invoker = new HttpMessageInvoker(handler); 16 | 17 | await invoker.SendAsync(request, CancellationToken.None); 18 | 19 | return testHandler.Request; 20 | } 21 | 22 | private class TestDelegatingHandler : DelegatingHandler 23 | { 24 | public HttpRequestMessage Request { get; private set; } 25 | 26 | protected override async Task SendAsync(HttpRequestMessage request, 27 | CancellationToken cancellationToken) 28 | { 29 | Request = request; 30 | 31 | return await Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)); 32 | } 33 | } 34 | } 35 | } -------------------------------------------------------------------------------- /DataverseODataClient.Tests/Services/WebApiEndpointProviderTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using BauerApps.DataverseODataClient.Services; 3 | using FluentAssertions; 4 | using Microsoft.Extensions.Options; 5 | using Xunit; 6 | 7 | namespace BauerApps.DataverseODataClient.Tests.Services 8 | { 9 | public class WebApiEndpointProviderTests 10 | { 11 | [Theory] 12 | [InlineData("https://my-organization.crm4.dynamics.com")] 13 | [InlineData("https://my-organization.crm4.dynamics.com/")] 14 | [InlineData("https://my-organization.crm4.dynamics.com/api/data/v9.1")] 15 | [InlineData("https://my-organization.crm4.dynamics.com/api/data/v9.1/")] 16 | public void ShouldReturnWebApiEndpoint(string organizationUrl) 17 | { 18 | // Arrange 19 | var options = Options.Create(new DataverseODataClientOptions 20 | { 21 | OrganizationUrl = new Uri(organizationUrl) 22 | }); 23 | 24 | var sut = new WebApiEndpointProvider(options); 25 | 26 | // Act 27 | var result = sut.GetWebApiEndpoint(); 28 | 29 | // Assert 30 | result.Should().Be("https://my-organization.crm4.dynamics.com/api/data/v9.1/"); 31 | } 32 | } 33 | } -------------------------------------------------------------------------------- /DataverseODataClient.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.26124.0 5 | MinimumVisualStudioVersion = 15.0.26124.0 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DataverseODataClient", "DataverseODataClient\DataverseODataClient.csproj", "{7037C143-F10B-47CD-9016-5A63BF97AFA2}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DataverseODataClient.Tests", "DataverseODataClient.Tests\DataverseODataClient.Tests.csproj", "{A1ECD9D1-9544-40A4-83CB-20BBF3E65DF3}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Debug|x64 = Debug|x64 14 | Debug|x86 = Debug|x86 15 | Release|Any CPU = Release|Any CPU 16 | Release|x64 = Release|x64 17 | Release|x86 = Release|x86 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 23 | {7037C143-F10B-47CD-9016-5A63BF97AFA2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 24 | {7037C143-F10B-47CD-9016-5A63BF97AFA2}.Debug|Any CPU.Build.0 = Debug|Any CPU 25 | {7037C143-F10B-47CD-9016-5A63BF97AFA2}.Debug|x64.ActiveCfg = Debug|Any CPU 26 | {7037C143-F10B-47CD-9016-5A63BF97AFA2}.Debug|x64.Build.0 = Debug|Any CPU 27 | {7037C143-F10B-47CD-9016-5A63BF97AFA2}.Debug|x86.ActiveCfg = Debug|Any CPU 28 | {7037C143-F10B-47CD-9016-5A63BF97AFA2}.Debug|x86.Build.0 = Debug|Any CPU 29 | {7037C143-F10B-47CD-9016-5A63BF97AFA2}.Release|Any CPU.ActiveCfg = Release|Any CPU 30 | {7037C143-F10B-47CD-9016-5A63BF97AFA2}.Release|Any CPU.Build.0 = Release|Any CPU 31 | {7037C143-F10B-47CD-9016-5A63BF97AFA2}.Release|x64.ActiveCfg = Release|Any CPU 32 | {7037C143-F10B-47CD-9016-5A63BF97AFA2}.Release|x64.Build.0 = Release|Any CPU 33 | {7037C143-F10B-47CD-9016-5A63BF97AFA2}.Release|x86.ActiveCfg = Release|Any CPU 34 | {7037C143-F10B-47CD-9016-5A63BF97AFA2}.Release|x86.Build.0 = Release|Any CPU 35 | {A1ECD9D1-9544-40A4-83CB-20BBF3E65DF3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 36 | {A1ECD9D1-9544-40A4-83CB-20BBF3E65DF3}.Debug|Any CPU.Build.0 = Debug|Any CPU 37 | {A1ECD9D1-9544-40A4-83CB-20BBF3E65DF3}.Debug|x64.ActiveCfg = Debug|Any CPU 38 | {A1ECD9D1-9544-40A4-83CB-20BBF3E65DF3}.Debug|x64.Build.0 = Debug|Any CPU 39 | {A1ECD9D1-9544-40A4-83CB-20BBF3E65DF3}.Debug|x86.ActiveCfg = Debug|Any CPU 40 | {A1ECD9D1-9544-40A4-83CB-20BBF3E65DF3}.Debug|x86.Build.0 = Debug|Any CPU 41 | {A1ECD9D1-9544-40A4-83CB-20BBF3E65DF3}.Release|Any CPU.ActiveCfg = Release|Any CPU 42 | {A1ECD9D1-9544-40A4-83CB-20BBF3E65DF3}.Release|Any CPU.Build.0 = Release|Any CPU 43 | {A1ECD9D1-9544-40A4-83CB-20BBF3E65DF3}.Release|x64.ActiveCfg = Release|Any CPU 44 | {A1ECD9D1-9544-40A4-83CB-20BBF3E65DF3}.Release|x64.Build.0 = Release|Any CPU 45 | {A1ECD9D1-9544-40A4-83CB-20BBF3E65DF3}.Release|x86.ActiveCfg = Release|Any CPU 46 | {A1ECD9D1-9544-40A4-83CB-20BBF3E65DF3}.Release|x86.Build.0 = Release|Any CPU 47 | EndGlobalSection 48 | EndGlobal 49 | -------------------------------------------------------------------------------- /DataverseODataClient/Auth/AzureIdentityTokenProvider.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Threading; 4 | using System.Threading.Tasks; 5 | using Azure.Core; 6 | using Microsoft.Extensions.Caching.Memory; 7 | 8 | namespace BauerApps.DataverseODataClient.Auth 9 | { 10 | internal abstract class AzureIdentityTokenProvider : ITokenProvider 11 | { 12 | private static readonly TimeSpan ExpirationThreshold = TimeSpan.FromMinutes(5); 13 | 14 | private readonly TokenCredential _tokenCredential; 15 | private readonly IMemoryCache _cache; 16 | private readonly string[] _scopes; 17 | 18 | protected AzureIdentityTokenProvider(string[] scopes, TokenCredential tokenCredential, IMemoryCache cache) 19 | { 20 | _scopes = scopes; 21 | _tokenCredential = tokenCredential; 22 | _cache = cache; 23 | } 24 | 25 | public async Task GetTokenAsync(CancellationToken cancellationToken = default) 26 | { 27 | var cacheKey = GetCacheKey(_scopes); 28 | 29 | if (!_cache.TryGetValue(cacheKey, out var accessToken)) 30 | { 31 | accessToken = await _tokenCredential.GetTokenAsync(new TokenRequestContext(_scopes), cancellationToken) 32 | .ConfigureAwait(false); 33 | 34 | _cache.Set(cacheKey, accessToken, accessToken.ExpiresOn - ExpirationThreshold); 35 | } 36 | 37 | return accessToken; 38 | } 39 | 40 | private static string GetCacheKey(IEnumerable scopes) 41 | { 42 | return string.Join('|', scopes); 43 | } 44 | } 45 | } -------------------------------------------------------------------------------- /DataverseODataClient/Auth/DataverseTokenProvider.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Azure.Core; 3 | using Azure.Identity; 4 | using Microsoft.Extensions.Caching.Memory; 5 | using Microsoft.Extensions.Options; 6 | 7 | namespace BauerApps.DataverseODataClient.Auth 8 | { 9 | internal class DataverseTokenProvider : AzureIdentityTokenProvider 10 | { 11 | private const string DefaultScope = "/.default"; 12 | 13 | public DataverseTokenProvider(IOptions options, IMemoryCache cache, 14 | TokenCredential tokenCredential = null) 15 | : base(ConfigureScopes(options.Value), tokenCredential ?? ConfigureTokenCredential(options.Value), cache) 16 | { 17 | } 18 | 19 | private static string[] ConfigureScopes(DataverseODataClientOptions options) 20 | { 21 | // required token scope for Dataverse Web API is https://.crm.dynamics.com/.default 22 | var baseUrl = new Uri(options.OrganizationUrl.GetLeftPart(UriPartial.Authority)); 23 | var scope = new Uri(baseUrl, DefaultScope).AbsoluteUri; 24 | 25 | return new[] { scope }; 26 | } 27 | 28 | private static TokenCredential ConfigureTokenCredential(DataverseODataClientOptions options) 29 | { 30 | var userAssignedClientId = options.ManagedIdentityClientId; 31 | // we have to specify client id when using user-assigned managed identities 32 | return string.IsNullOrWhiteSpace(userAssignedClientId) 33 | ? new DefaultAzureCredential() 34 | : new DefaultAzureCredential(new DefaultAzureCredentialOptions 35 | { ManagedIdentityClientId = userAssignedClientId }); 36 | } 37 | } 38 | } -------------------------------------------------------------------------------- /DataverseODataClient/Auth/ITokenProvider.cs: -------------------------------------------------------------------------------- 1 | using System.Threading; 2 | using System.Threading.Tasks; 3 | using Azure.Core; 4 | 5 | namespace BauerApps.DataverseODataClient.Auth 6 | { 7 | public interface ITokenProvider 8 | { 9 | Task GetTokenAsync(CancellationToken cancellationToken = default); 10 | } 11 | } -------------------------------------------------------------------------------- /DataverseODataClient/DataverseODataClient.cs: -------------------------------------------------------------------------------- 1 | using System.Net.Http; 2 | using Simple.OData.Client; 3 | 4 | namespace BauerApps.DataverseODataClient 5 | { 6 | // this class is needed to enable dependency injection of ODataClientSettings 7 | public class DataverseODataClient : ODataClient 8 | { 9 | public DataverseODataClient(HttpClient httpClient) 10 | : base(new ODataClientSettings(httpClient) { IgnoreUnmappedProperties = true }) 11 | { 12 | } 13 | } 14 | } -------------------------------------------------------------------------------- /DataverseODataClient/DataverseODataClient.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | 6 | BauerApps.DataverseODataClient 7 | 1.0.0 8 | Ready-to-use OData client for communication with Microsoft Dataverse Web API. 9 | Lars Bauer 10 | https://github.com/LarsBauer/DataverseODataClient.git 11 | https://github.com/LarsBauer/DataverseODataClient 12 | MIT 13 | 2.0.2 14 | README.md 15 | BauerApps.DataverseODataClient 16 | 17 | 18 | 19 | 20 | <_Parameter1>$(MSBuildProjectName).Tests 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /DataverseODataClient/DataverseODataClientOptions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace BauerApps.DataverseODataClient 4 | { 5 | /// 6 | /// Dataverse OData client configuration options 7 | /// 8 | public class DataverseODataClientOptions 9 | { 10 | /// 11 | /// The base url of your Dataverse environment in the following format: 12 | /// https://{{organizationName}}.crm4.dynamics.com/api/data/v9.1/ 13 | /// 14 | public Uri OrganizationUrl { get; set; } 15 | 16 | /// 17 | /// When using a user-assigned managed identity in Azure you have to specifiy the client id 18 | /// 19 | public string ManagedIdentityClientId { get; set; } 20 | } 21 | } -------------------------------------------------------------------------------- /DataverseODataClient/Extensions/ServiceCollectionExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using BauerApps.DataverseODataClient.Auth; 3 | using BauerApps.DataverseODataClient.Middlewares; 4 | using BauerApps.DataverseODataClient.Services; 5 | using Microsoft.Extensions.DependencyInjection; 6 | using Simple.OData.Client; 7 | 8 | namespace BauerApps.DataverseODataClient.Extensions 9 | { 10 | public static class ServiceCollectionExtensions 11 | { 12 | public static IServiceCollection AddDataverseODataClient(this IServiceCollection services, 13 | Action options) 14 | { 15 | services.Configure(options); 16 | 17 | // token provider 18 | services.AddMemoryCache(); 19 | services.AddScoped(); 20 | 21 | // Web API endpoint provider 22 | services.AddTransient(); 23 | 24 | // outgoing request middlewares 25 | services.AddTransient(); 26 | services.AddTransient(); 27 | 28 | // register OData client with preconfigured HttpClient 29 | services.AddHttpClient((serviceProvider, client) => 30 | { 31 | var endpointProvider = serviceProvider.GetRequiredService(); 32 | 33 | client.BaseAddress = endpointProvider.GetWebApiEndpoint(); 34 | }) 35 | .AddHttpMessageHandler() 36 | .AddHttpMessageHandler(); 37 | 38 | return services; 39 | } 40 | } 41 | } -------------------------------------------------------------------------------- /DataverseODataClient/Middlewares/AuthorizationHeaderHandler.cs: -------------------------------------------------------------------------------- 1 | using System.Net.Http; 2 | using System.Net.Http.Headers; 3 | using System.Threading; 4 | using System.Threading.Tasks; 5 | using BauerApps.DataverseODataClient.Auth; 6 | 7 | namespace BauerApps.DataverseODataClient.Middlewares 8 | { 9 | internal class AuthorizationHeaderHandler : DelegatingHandler 10 | { 11 | private readonly ITokenProvider _tokenProvider; 12 | 13 | public AuthorizationHeaderHandler(ITokenProvider tokenProvider) 14 | { 15 | _tokenProvider = tokenProvider; 16 | } 17 | 18 | protected override async Task SendAsync(HttpRequestMessage request, 19 | CancellationToken cancellationToken) 20 | { 21 | // acquire access token and add authorization header 22 | var accessToken = await _tokenProvider.GetTokenAsync(cancellationToken); 23 | request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken.Token); 24 | 25 | return await base.SendAsync(request, cancellationToken); 26 | } 27 | } 28 | } -------------------------------------------------------------------------------- /DataverseODataClient/Middlewares/CorrelationIdHandler.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net.Http; 3 | using System.Threading; 4 | using System.Threading.Tasks; 5 | using BauerApps.DataverseODataClient.Services; 6 | using Microsoft.AspNetCore.WebUtilities; 7 | 8 | namespace BauerApps.DataverseODataClient.Middlewares 9 | { 10 | internal class CorrelationIdHandler : DelegatingHandler 11 | { 12 | private const string CorrelationIdQueryParameter = "tag"; 13 | 14 | private readonly ICorrelationIdProvider _provider; 15 | 16 | public CorrelationIdHandler(ICorrelationIdProvider provider = null) 17 | { 18 | _provider = provider; 19 | } 20 | 21 | protected override Task SendAsync(HttpRequestMessage request, 22 | CancellationToken cancellationToken) 23 | { 24 | // skip execution when no provider is registered 25 | if (_provider == null) return base.SendAsync(request, cancellationToken); 26 | 27 | // extract correlation id from http headers 28 | var correlationId = _provider.GetCorrelationId(); 29 | if (string.IsNullOrWhiteSpace(correlationId)) return base.SendAsync(request, cancellationToken); 30 | 31 | // add correlation id as query parameter 32 | var requestUrl = request.RequestUri?.AbsoluteUri ?? throw new InvalidOperationException(); 33 | request.RequestUri = 34 | new Uri(QueryHelpers.AddQueryString(requestUrl, CorrelationIdQueryParameter, correlationId)); 35 | 36 | return base.SendAsync(request, cancellationToken); 37 | } 38 | } 39 | } -------------------------------------------------------------------------------- /DataverseODataClient/Services/ICorrelationIdProvider.cs: -------------------------------------------------------------------------------- 1 | namespace BauerApps.DataverseODataClient.Services 2 | { 3 | public interface ICorrelationIdProvider 4 | { 5 | string GetCorrelationId(); 6 | } 7 | } -------------------------------------------------------------------------------- /DataverseODataClient/Services/IWebApiEndpointProvider.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace BauerApps.DataverseODataClient.Services 4 | { 5 | internal interface IWebApiEndpointProvider 6 | { 7 | Uri GetWebApiEndpoint(); 8 | } 9 | } -------------------------------------------------------------------------------- /DataverseODataClient/Services/WebApiEndpointProvider.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.Extensions.Options; 3 | 4 | namespace BauerApps.DataverseODataClient.Services 5 | { 6 | internal class WebApiEndpointProvider : IWebApiEndpointProvider 7 | { 8 | private const string WebApiPath = "/api/data/v9.1/"; 9 | 10 | private readonly DataverseODataClientOptions _options; 11 | 12 | public WebApiEndpointProvider(IOptions options) 13 | { 14 | _options = options.Value; 15 | } 16 | 17 | public Uri GetWebApiEndpoint() 18 | { 19 | var organizationUrl = _options.OrganizationUrl; 20 | 21 | return organizationUrl.LocalPath == WebApiPath 22 | ? organizationUrl 23 | : new Uri(organizationUrl, WebApiPath); 24 | } 25 | } 26 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Lars Bauer 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.md: -------------------------------------------------------------------------------- 1 | # Dataverse OData Client 2 | 3 | [![Build status](https://github.com/LarsBauer/DataverseODataClient/actions/workflows/dotnet.yml/badge.svg)](https://github.com/LarsBauer/DataverseODataClient/actions/workflows/dotnet.yml) 4 | [![codecov](https://codecov.io/gh/LarsBauer/DataverseODataClient/branch/main/graph/badge.svg?token=C0Y1VMP7YA)](https://codecov.io/gh/LarsBauer/DataverseODataClient) 5 | [![NuGet Badge](https://buildstats.info/nuget/BauerApps.DataverseODataClient)](https://www.nuget.org/packages/BauerApps.DataverseODataClient/) 6 | 7 | This NuGet package provides a ready-to-use OData Client 8 | for [Microsoft Dataverse Web API](https://docs.microsoft.com/en-us/powerapps/developer/data-platform/webapi/overview). 9 | 10 | ## Features 11 | 12 | - based on the very popular and 13 | feature-rich [Simple.OData.Client](https://github.com/simple-odata-client/Simple.OData.Client) 14 | - seamless integration in dependency injection and configuration concepts of .NET 15 | - makes use of `IHttpClientFactory` to delegate `HttpClient` lifecycle to framework 16 | - token handling based on [Azure Identity](https://docs.microsoft.com/en-us/dotnet/api/overview/azure/identity-readme), 17 | which offers various ways to authenticate against Dataverse 18 | - supports e2e-traceability of requests via correlation id 19 | - developed and targeted at Azure Functions and Azure Web Apps 20 | 21 | ## Get started 22 | 23 | To get started with this package just install the latest version from NuGet using the dotnet CLI: 24 | 25 | ```bash 26 | dotnet add package BauerApps.DataverseODataClient 27 | ``` 28 | 29 | After installation you can register the client in `Startup.cs`... 30 | 31 | ```csharp 32 | using System; 33 | using DataverseODataClient.Extensions; 34 | using Microsoft.Extensions.DependencyInjection; 35 | 36 | namespace DataverseODataClient.Sample 37 | { 38 | public class Startup 39 | { 40 | public void ConfigureServices(IServiceCollection services) 41 | { 42 | services.AddDataverseODataClient(options => 43 | { 44 | options.OrganizationUrl = new Uri("https://my-organization.crm4.dynamics.com"); 45 | options.ManagedIdentityClientId = "d0f19fa6-76ef-46cb-93ac-fcde5a4a6143"; // optional 46 | }); 47 | } 48 | } 49 | } 50 | ``` 51 | 52 | ... and inject it for example into your `Controller`. As mentioned above this client basically is a preconfigured 53 | version of `Simple.OData.Client`, which means you can use it the same way. If you are new to `Simple.OData.Client` head 54 | over to the [wiki](https://github.com/simple-odata-client/Simple.OData.Client/wiki) for available features. 55 | 56 | ```csharp 57 | using System.Threading.Tasks; 58 | using Microsoft.AspNetCore.Mvc; 59 | using Simple.OData.Client; 60 | 61 | namespace DataverseODataClient.Sample.Controllers 62 | { 63 | [ApiController] 64 | [Route("[controller]")] 65 | public class SampleController : ControllerBase 66 | { 67 | private readonly IODataClient _client; 68 | 69 | public SampleController(IODataClient client) 70 | { 71 | _client = client; 72 | } 73 | 74 | [HttpGet] 75 | public async Task Get(string id) 76 | { 77 | return await _client 78 | .For() 79 | .Key(id) 80 | .FindEntryAsync(); 81 | } 82 | } 83 | } 84 | ``` 85 | 86 | ## Configuration 87 | 88 | You can configure Dataverse OData Client using `DataverseODataClientOptions` 89 | 90 | | Option | Required | Description | 91 | | ----------------------- | :------: | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | 92 | | OrganizationUrl | ✔ | The base url of your Dataverse organization | 93 | | ManagedIdentityClientId | | When using a Azure user-assigned [managed identity](https://docs.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/overview) for authentication you have to specify the client id of the corresponding managed identity. | 94 | 95 | ### Correlation Id 96 | 97 | It is possible to pass a correlation id to Dataverse by registering a implementation of `ICorrelationIdProvider`. The id is then available as `tag` parameter in the shared variables. See Dataverse [docs](https://learn.microsoft.com/en-us/power-apps/developer/data-platform/understand-the-data-context#passing-a-shared-variable-from-the-api) for details. 98 | 99 | ```csharp 100 | // sample correlation id provider 101 | public class HttpHeaderCorrelationIdProvider : ICorrelationIdProvider 102 | { 103 | private readonly IHttpContextAccessor _httpContextAccessor; 104 | 105 | public HttpHeaderCorrelationIdProvider(IHttpContextAccessor httpContextAccessor) 106 | { 107 | _httpContextAccessor = httpContextAccessor; 108 | } 109 | 110 | public string GetCorrelationId() 111 | { 112 | // extract correlation id from http header 113 | return _httpContextAccessor.HttpContext?.Request.Headers["x-correlation-id"]; 114 | } 115 | } 116 | 117 | // register in Program.cs 118 | services.AddDataverseODataClient(options => { ... }); 119 | 120 | services.AddTransient(); 121 | ``` --------------------------------------------------------------------------------