├── .editorconfig
├── .github
├── CODEOWNERS
├── ISSUE_TEMPLATE
│ ├── 01-sdk-bug.yml
│ ├── 02-sdk-feature-request.yml
│ ├── 03-blank-issue.md
│ └── config.yml
├── PULL_REQUEST_TEMPLATE.md
├── dependabot.yml
├── policies
│ ├── msgraph-sdk-dotnet-core-branch-protection.yml
│ └── resourceManagement.yml
├── release-please.yml
└── workflows
│ ├── auto-merge-dependabot.yml
│ ├── project-auto-add.yml
│ ├── sonarcloud.yml
│ └── validatePullRequest.yml
├── .gitignore
├── .release-please-manifest.json
├── CHANGELOG.md
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── Directory.Build.props
├── LICENSE.txt
├── Microsoft.Graph.Core.sln
├── README.md
├── THIRD PARTY NOTICES
├── build
└── 35MSSharedLib1024.snk
├── docs
├── FAQ.md
├── collections.md
├── contributions.md
├── errors.md
├── headers.md
├── logging-requests.md
├── overview.md
└── readme.md
├── global.json
├── pipelines
└── productionBuild.yml
├── release-please-config.json
├── scripts
├── EnableSigning.ps1
├── GetLatestCommitSHA.ps1
├── GetNugetPackageVersion.ps1
└── ValidateUpdatedNugetVersion.ps1
├── src
└── Microsoft.Graph.Core
│ ├── 35MSSharedLib1024.snk
│ ├── Authentication
│ ├── AzureIdentityAccessTokenProvider.cs
│ └── AzureIdentityAuthenticationProvider.cs
│ ├── CoreConstants.cs
│ ├── Exceptions
│ ├── ClientException.cs
│ ├── ErrorConstants.cs
│ └── ServiceException.cs
│ ├── Extensions
│ ├── HttpClientExtensions.cs
│ ├── HttpRequestMessageExtensions.cs
│ ├── IDecryptableContentExtensions.cs
│ ├── IEncryptableSubscriptionExtensions.cs
│ ├── IParseNodeExtensions.cs
│ └── ITokenValidableExtension.cs
│ ├── Helpers
│ ├── ExtractSelectHelper.cs
│ ├── ReadOnlySubStream.cs
│ ├── StringHelper.cs
│ └── UrlHelper.cs
│ ├── HttpMethods.cs
│ ├── LICENSE.txt
│ ├── Microsoft.Graph.Core.csproj
│ ├── Models
│ ├── AsyncOperationStatus.cs
│ ├── BatchRequestStep.cs
│ ├── IDecryptableContent.cs
│ ├── IEncryptableSubscription.cs
│ ├── IEncryptedContentBearer.cs
│ ├── ITokenValidable.cs
│ ├── IUploadSession.cs
│ ├── ReferenceRequestBody.cs
│ ├── UploadResult.cs
│ └── UploadSession.cs
│ ├── Properties
│ └── AssemblyInfo.cs
│ ├── Requests
│ ├── AsyncMonitor.cs
│ ├── BaseGraphRequestAdapter.cs
│ ├── BatchRequestBuilder.cs
│ ├── Content
│ │ ├── BatchRequestContent.cs
│ │ ├── BatchRequestContentCollection.cs
│ │ ├── BatchRequestContentSteps.cs
│ │ ├── BatchResponseContent.cs
│ │ ├── BatchResponseContentCollection.cs
│ │ └── KeyedBatchResponseContent.cs
│ ├── DeltaResponseHandler.cs
│ ├── FeatureFlag.cs
│ ├── GraphClientFactory.cs
│ ├── GraphClientOptions.cs
│ ├── GraphRequestContext.cs
│ ├── GraphResponse.cs
│ ├── GraphResponse{T}.cs
│ ├── IAsyncMonitor.cs
│ ├── IBaseClient.cs
│ ├── Middleware
│ │ └── GraphTelemetryHandler.cs
│ ├── ResponseHandler.cs
│ └── Upload
│ │ ├── UploadResponseHandler.cs
│ │ ├── UploadSessionRequestBuilder.cs
│ │ └── UploadSliceRequestBuilder.cs
│ ├── Tasks
│ ├── LargeFileUploadTask.cs
│ └── PageIterator.cs
│ └── global.json
└── tests
├── Microsoft.Graph.DotnetCore.Core.Test
├── Exceptions
│ └── ServiceExceptionTests.cs
├── Extensions
│ ├── HttpClientExtensionsTests.cs
│ └── IDecryptableContentExtensionsTests.cs
├── Helpers
│ ├── ExtractSelectHelperTest.cs
│ ├── ReadOnlySubStreamTests.cs
│ ├── StringHelperTests.cs
│ └── UrlHelperTests.cs
├── Microsoft.Graph.DotnetCore.Core.Test.csproj
├── Mocks
│ ├── BaseClient.cs
│ ├── ExceptionHttpMessageHandler.cs
│ ├── MockAccessTokenProvider.cs
│ ├── MockAuthenticationProvider.cs
│ ├── MockProgress.cs
│ ├── MockRedirectHandler.cs
│ ├── MockTokenCredential.cs
│ ├── MockUploadSessionWithoutInterface.cs
│ └── TestHttpMessageHandler.cs
├── Properties
│ └── AssemblyInfo.cs
├── Requests
│ ├── AsyncMonitorTests.cs
│ ├── BaseClientTests.cs
│ ├── BatchRequestBuilderTests.cs
│ ├── Content
│ │ ├── BatchRequestContentStepsTests.cs
│ │ ├── BatchRequestContentTests.cs
│ │ └── BatchResponseContentTests.cs
│ ├── GraphClientFactoryTests.cs
│ ├── GraphResponseTests.cs
│ ├── Middleware
│ │ └── TelemetryHandlerTests.cs
│ ├── RequestTestBase.cs
│ ├── ResponseHandlerTests.cs
│ └── Upload
│ │ ├── UploadResponseHandlerTests.cs
│ │ └── UploadSliceRequestTests.cs
├── Serialization
│ └── SerializerTests.cs
├── Tasks
│ ├── LargeFileUploadTaskTests.cs
│ └── PageIteratorTests.cs
├── TestModels
│ ├── AbstractEntityType.cs
│ ├── DateTestClass.cs
│ ├── DerivedTypeClass.cs
│ ├── EnumType.cs
│ ├── EnumTypeWithFlags.cs
│ └── ServiceModels
│ │ ├── TestAttendee.cs
│ │ ├── TestBodyType.cs
│ │ ├── TestChangeNotificationEncryptedContent.cs
│ │ ├── TestChatMessage.cs
│ │ ├── TestDateTimeTimeZone.cs
│ │ ├── TestDrive.cs
│ │ ├── TestDriveItem.cs
│ │ ├── TestEmailAddress.cs
│ │ ├── TestEvent.cs
│ │ ├── TestEventDeltaCollectionResponse.cs
│ │ ├── TestEventItem.cs
│ │ ├── TestEventsDeltaResponse.cs
│ │ ├── TestEventsResponse.cs
│ │ ├── TestItemBody.cs
│ │ ├── TestNotebook.cs
│ │ ├── TestRecipient.cs
│ │ ├── TestResourceData.cs
│ │ ├── TestSubscription.cs
│ │ └── TestUser.cs
├── ms-logo.png
└── xunit.runner.json
└── Microsoft.Graph.DotnetCore.Core.Trimming
├── Microsoft.Graph.DotnetCore.Core.Trimming.csproj
├── Program.cs
└── global.json
/.github/CODEOWNERS:
--------------------------------------------------------------------------------
1 | * @microsoftgraph/msgraph-devx-dotnet-write
2 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/01-sdk-bug.yml:
--------------------------------------------------------------------------------
1 | name: SDK Bug Report
2 | description: File SDK bug report
3 | labels: ["type:bug", "status:waiting-for-triage"]
4 | body:
5 | - type: markdown
6 | attributes:
7 | value: |
8 | **Thank you for taking the time to fill out this bug report!**
9 | 💥Before submitting a new request, please search existing issues to see if an issue already exists.
10 | - type: textarea
11 | id: description
12 | attributes:
13 | label: Describe the bug
14 | description: |
15 | Provide a description of the actual behavior observed. If applicable please include any error messages, exception stacktraces or a screenshot.
16 | placeholder: I am trying to do [...] but [...]
17 | validations:
18 | required: true
19 | - type: textarea
20 | id: expected-behavior
21 | attributes:
22 | label: Expected behavior
23 | description: |
24 | A clear and concise description of what you expected to happen.
25 | placeholder: Expected behavior
26 | validations:
27 | required: true
28 | - type: textarea
29 | id: repro-steps
30 | attributes:
31 | label: How to reproduce
32 | description: |
33 | Please include minimal steps to reproduce the problem if possible. E.g.: the smallest possible code snippet; or steps to run project in link above. If possible include text as text rather than screenshots (so it shows up in searches).
34 | If there's a link to a public repo where the sample code exists, include it too.
35 | placeholder: Minimal Reproduction steps
36 | validations:
37 | required: true
38 | - type: input
39 | attributes:
40 | label: SDK Version
41 | placeholder: e.g. 5.32.1
42 | description: Version of the SDK with the bug described above.
43 | validations:
44 | required: false
45 | - type: input
46 | id: regression
47 | attributes:
48 | label: Latest version known to work for scenario above?
49 | description: |
50 | Did this work in a previous build or release of the SDK or API client? If you can try a previous release or build to find out, that can help us narrow down the problem. If you don't know, that's OK.
51 | placeholder: version-number
52 | validations:
53 | required: false
54 | - type: textarea
55 | id: known-workarounds
56 | attributes:
57 | label: Known Workarounds
58 | description: |
59 | Please provide a description of any known workarounds.
60 | placeholder: Known Workarounds
61 | validations:
62 | required: false
63 | - type: textarea
64 | id: logs
65 | attributes:
66 | label: Debug output
67 | description: Please copy and paste the debug output below.
68 | value: |
69 | Click to expand log
70 | ```
71 |
72 |
73 |
74 | ```
75 |
76 | validations:
77 | required: false
78 | - type: textarea
79 | id: configuration
80 | attributes:
81 | label: Configuration
82 | description: |
83 | Please provide more information on your SDK configuration:
84 | * What OS and version, and what distro if applicable (Windows 10, Windows 11, MacOS Catalina, Ubuntu 22.04)?
85 | * What is the architecture (x64, x86, ARM, ARM64)?
86 | * Do you know whether it is specific to that configuration?
87 | placeholder: |
88 | - OS:
89 | - architecture:
90 | validations:
91 | required: false
92 | - type: textarea
93 | id: other-info
94 | attributes:
95 | label: Other information
96 | description: |
97 | If you have an idea where the problem might lie, let us know that here. Please include any pointers to code, relevant changes, or related issues you know of.
98 | placeholder: Other information
99 | validations:
100 | required: false
101 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/02-sdk-feature-request.yml:
--------------------------------------------------------------------------------
1 | name: SDK Feature request
2 | description: Request a new feature on the SDK
3 | labels: ["type:feature", "status:waiting-for-triage"]
4 | body:
5 | - type: markdown
6 | attributes:
7 | value: |
8 | **Thank you for taking the time to fill out this feature request form!**
9 | 💥Please search to see if an issue already exists for the feature you are requesting.
10 | - type: textarea
11 | attributes:
12 | label: Is your feature request related to a problem? Please describe the problem.
13 | description: A clear and concise description of what the problem is.
14 | placeholder: I am trying to do [...] but [...]
15 | validations:
16 | required: false
17 | - type: textarea
18 | attributes:
19 | label: Describe the solution you'd like.
20 | description: |
21 | A clear and concise description of what you want to happen. Include any alternative solutions you've considered.
22 | validations:
23 | required: true
24 | - type: textarea
25 | attributes:
26 | label: Additional context?
27 | description: |
28 | Add any other context or screenshots about the feature request here.
29 | validations:
30 | required: false
31 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/03-blank-issue.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Blank issue
3 | about: Something that doesn't fit the other categories
4 | title: ''
5 | labels: ["status:waiting-for-triage"]
6 | assignees: ''
7 |
8 | ---
9 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/config.yml:
--------------------------------------------------------------------------------
1 | blank_issues_enabled: true
2 | contact_links:
3 | - name: Question on use of graph sdk
4 | url: https://github.com/microsoftgraph/msgraph-sdk-dotnet/discussions
5 | about: Please add your question in the discussions section of the repo
6 | - name: Question on use of kiota
7 | url: https://github.com/microsoft/kiota/discussions
8 | about: Please add your question in the discussions section of the repo
9 | - name: Question or Feature Request for the MS Graph API?
10 | url: https://aka.ms/msgraphsupport
11 | about: Report an issue or limitation with the MS Graph service APIs
12 |
--------------------------------------------------------------------------------
/.github/PULL_REQUEST_TEMPLATE.md:
--------------------------------------------------------------------------------
1 |
9 |
10 |
11 | Fixes #
12 |
13 |
14 | ### Changes proposed in this pull request
15 | -
16 | -
17 | -
18 |
19 |
20 | ### Other links
21 | -
22 | -
23 | -
--------------------------------------------------------------------------------
/.github/dependabot.yml:
--------------------------------------------------------------------------------
1 | version: 2
2 | updates:
3 | - package-ecosystem: nuget
4 | directories:
5 | - "**/*"
6 | schedule:
7 | interval: daily
8 | open-pull-requests-limit: 10
9 | groups:
10 | kiota-dependencies:
11 | patterns:
12 | - "*kiota*"
13 | xunit:
14 | patterns:
15 | - xunit*
16 | coverlet:
17 | patterns:
18 | - coverlet*
19 | mstest:
20 | patterns:
21 | - Microsoft.NET.Test.Sdk
22 | - Microsoft.TestPlatform.ObjectModel
23 | - package-ecosystem: github-actions
24 | directory: "/"
25 | schedule:
26 | interval: daily
27 | open-pull-requests-limit: 10
28 |
--------------------------------------------------------------------------------
/.github/policies/msgraph-sdk-dotnet-core-branch-protection.yml:
--------------------------------------------------------------------------------
1 | # Copyright (c) Microsoft Corporation.
2 | # Licensed under the MIT License.
3 |
4 | # File initially created using https://github.com/MIchaelMainer/policyservicetoolkit/blob/main/branch_protection_export.ps1.
5 |
6 | name: msgraph-sdk-dotnet-core-branch-protection
7 | description: Branch protection policy for the msgraph-sdk-dotnet-core repository
8 | resource: repository
9 | configuration:
10 | branchProtectionRules:
11 |
12 | - branchNamePattern: main
13 | # This branch pattern applies to the following branches:
14 | # main
15 |
16 | # Specifies whether this branch can be deleted. boolean
17 | allowsDeletions: false
18 | # Specifies whether forced pushes are allowed on this branch. boolean
19 | allowsForcePushes: false
20 | # Specifies whether new commits pushed to the matching branches dismiss pull request review approvals. boolean
21 | dismissStaleReviews: true
22 | # Specifies whether admins can overwrite branch protection. boolean
23 | isAdminEnforced: false
24 | # Indicates whether "Require a pull request before merging" is enabled. boolean
25 | requiresPullRequestBeforeMerging: true
26 | # Specifies the number of pull request reviews before merging. int (0-6). Should be null/empty if PRs are not required
27 | requiredApprovingReviewsCount: 1
28 | # Require review from Code Owners. Requires requiredApprovingReviewsCount. boolean
29 | requireCodeOwnersReview: true
30 | # Are commits required to be signed. boolean. TODO: all contributors must have commit signing on local machines.
31 | requiresCommitSignatures: false
32 | # Are conversations required to be resolved before merging? boolean
33 | requiresConversationResolution: true
34 | # Are merge commits prohibited from being pushed to this branch. boolean
35 | requiresLinearHistory: false
36 | # Required status checks to pass before merging. Values can be any string, but if the value does not correspond to any existing status check, the status check will be stuck on pending for status since nothing exists to push an actual status
37 | requiredStatusChecks:
38 | - Build and Test # Contains CodeQL
39 | - Validate Project for Trimming
40 | - license/cla
41 | # Require branches to be up to date before merging. boolean
42 | requiresStrictStatusChecks: true
43 | # Indicates whether there are restrictions on who can push. boolean. Should be set with whoCanPush.
44 | restrictsPushes: false
45 | # Restrict who can dismiss pull request reviews. boolean
46 | restrictsReviewDismissals: false
47 |
--------------------------------------------------------------------------------
/.github/policies/resourceManagement.yml:
--------------------------------------------------------------------------------
1 | id:
2 | name: GitOps.PullRequestIssueManagement
3 | description: GitOps.PullRequestIssueManagement primitive
4 | owner:
5 | resource: repository
6 | disabled: false
7 | where:
8 | configuration:
9 | resourceManagementConfiguration:
10 | scheduledSearches:
11 | - description:
12 | frequencies:
13 | - hourly:
14 | hour: 1
15 | filters:
16 | - isIssue
17 | - isOpen
18 | - hasLabel:
19 | label: 'status:waiting-for-author-feedback'
20 | - hasLabel:
21 | label: no-recent-activity
22 | - noActivitySince:
23 | days: 3
24 | - isNotLabeledWith:
25 | label: service bug
26 | actions:
27 | - closeIssue
28 | - description:
29 | frequencies:
30 | - hourly:
31 | hour: 1
32 | filters:
33 | - isIssue
34 | - isOpen
35 | - hasLabel:
36 | label: 'status:waiting-for-author-feedback'
37 | - noActivitySince:
38 | days: 4
39 | - isNotLabeledWith:
40 | label: no-recent-activity
41 | actions:
42 | - addLabel:
43 | label: no-recent-activity
44 | - addReply:
45 | reply: This issue has been automatically marked as stale because it has been marked as requiring author feedback but has not had any activity for **4 days**. It will be closed if no further activity occurs **within 3 days of this comment**.
46 | - description:
47 | frequencies:
48 | - hourly:
49 | hour: 1
50 | filters:
51 | - isIssue
52 | - isOpen
53 | - hasLabel:
54 | label: duplicate
55 | - noActivitySince:
56 | days: 1
57 | actions:
58 | - addReply:
59 | reply: This issue has been marked as duplicate and has not had any activity for **1 day**. It will be closed for housekeeping purposes.
60 | - closeIssue
61 | eventResponderTasks:
62 | - if:
63 | - payloadType: Issues
64 | - isAction:
65 | action: Closed
66 | - hasLabel:
67 | label: 'status:waiting-for-author-feedback'
68 | then:
69 | - removeLabel:
70 | label: 'status:waiting-for-author-feedback'
71 | description:
72 | - if:
73 | - payloadType: Issue_Comment
74 | - isAction:
75 | action: Created
76 | - isActivitySender:
77 | issueAuthor: True
78 | - hasLabel:
79 | label: 'status:waiting-for-author-feedback'
80 | then:
81 | - addLabel:
82 | label: 'Needs: Attention :wave:'
83 | - removeLabel:
84 | label: 'status:waiting-for-author-feedback'
85 | description:
86 | - if:
87 | - payloadType: Issues
88 | - not:
89 | isAction:
90 | action: Closed
91 | - hasLabel:
92 | label: no-recent-activity
93 | then:
94 | - removeLabel:
95 | label: no-recent-activity
96 | description:
97 | - if:
98 | - payloadType: Issues
99 | - labelAdded:
100 | label: service bug
101 | then: []
102 | description:
103 | - if:
104 | - payloadType: Issue_Comment
105 | - activitySenderHasAssociation:
106 | association: Contributor
107 | - bodyContains:
108 | pattern: '?'
109 | isRegex: False
110 | - bodyContains:
111 | pattern: '@'
112 | isRegex: False
113 | then:
114 | - addLabel:
115 | label: 'status:waiting-for-author-feedback'
116 | description:
117 | - if:
118 | - payloadType: Pull_Request
119 | - isAction:
120 | action: Opened
121 | then:
122 | - addCodeFlowLink
123 | description:
124 | onFailure:
125 | onSuccess:
126 |
--------------------------------------------------------------------------------
/.github/release-please.yml:
--------------------------------------------------------------------------------
1 | manifest: true
2 | primaryBranch: main
3 | handleGHRelease: true
--------------------------------------------------------------------------------
/.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@v2.4.0
23 | with:
24 | github-token: "${{ secrets.GITHUB_TOKEN }}"
25 |
26 | - name: Enable auto-merge for Dependabot PRs
27 | # Only if version bump is not a major version change
28 | if: ${{steps.metadata.outputs.update-type != 'version-update:semver-major'}}
29 | run: gh pr merge --auto --merge "$PR_URL"
30 | env:
31 | PR_URL: ${{github.event.pull_request.html_url}}
32 | GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}}
33 |
--------------------------------------------------------------------------------
/.github/workflows/project-auto-add.yml:
--------------------------------------------------------------------------------
1 | # This workflow is used to add new issues to GitHub GraphSDKs Project
2 |
3 | name: Add Issue or PR to project
4 | on:
5 | issues:
6 | types:
7 | - opened
8 | pull_request:
9 | types:
10 | - opened
11 | branches:
12 | - "main"
13 |
14 | jobs:
15 | track_issue:
16 | if: github.actor != 'dependabot[bot]' && github.event.pull_request.head.repo.fork == false
17 | runs-on: ubuntu-latest
18 | steps:
19 | - name: Generate token
20 | id: generate_token
21 | uses: actions/create-github-app-token@v2
22 | with:
23 | app-id: ${{ secrets.GRAPHBOT_APP_ID }}
24 | private-key: ${{ secrets.GRAPHBOT_APP_PEM }}
25 |
26 | - name: Get project data
27 | env:
28 | GITHUB_TOKEN: ${{ steps.generate_token.outputs.token }}
29 | ORGANIZATION: microsoftgraph
30 | PROJECT_NUMBER: 55
31 | run: |
32 | gh api graphql -f query='
33 | query($org: String!, $number: Int!) {
34 | organization(login: $org){
35 | projectV2(number: $number) {
36 | id
37 | fields(first:20) {
38 | nodes {
39 | ... on ProjectV2SingleSelectField {
40 | id
41 | name
42 | options {
43 | id
44 | name
45 | }
46 | }
47 | }
48 | }
49 | }
50 | }
51 | }' -f org=$ORGANIZATION -F number=$PROJECT_NUMBER > project_data.json
52 |
53 | echo 'PROJECT_ID='$(jq '.data.organization.projectV2.id' project_data.json) >> $GITHUB_ENV
54 | echo 'LANGUAGE_FIELD_ID='$(jq '.data.organization.projectV2.fields.nodes[] | select(.name== "Language") | .id' project_data.json) >> $GITHUB_ENV
55 | echo 'LANGUAGE_OPTION_ID='$(jq '.data.organization.projectV2.fields.nodes[] | select(.name== "Language") | .options[] | select(.name=="CSharp") |.id' project_data.json) >> $GITHUB_ENV
56 |
57 | - name: Add Issue or PR to project
58 | env:
59 | GITHUB_TOKEN: ${{ steps.generate_token.outputs.token }}
60 | ISSUE_ID: ${{ github.event_name == 'issues' && github.event.issue.node_id || github.event.pull_request.node_id }}
61 | run: |
62 | item_id="$( gh api graphql -f query='
63 | mutation($project:ID!, $issue:ID!) {
64 | addProjectV2ItemById(input: {projectId: $project, contentId: $issue}) {
65 | item {
66 | id
67 | }
68 | }
69 | }' -f project=$PROJECT_ID -f issue=$ISSUE_ID --jq '.data.addProjectV2ItemById.item.id')"
70 |
71 | echo 'ITEM_ID='$item_id >> $GITHUB_ENV
72 |
73 | - name: Set Language
74 | env:
75 | GITHUB_TOKEN: ${{ steps.generate_token.outputs.token }}
76 | run: |
77 | gh api graphql -f query='
78 | mutation (
79 | $project: ID!
80 | $item: ID!
81 | $language_field: ID!
82 | $language_value: String!
83 | ) {
84 | set_status: updateProjectV2ItemFieldValue(input: {
85 | projectId: $project
86 | itemId: $item
87 | fieldId: $language_field
88 | value: {singleSelectOptionId: $language_value}
89 | }) {
90 | projectV2Item {
91 | id
92 | }
93 | }
94 | }' -f project=$PROJECT_ID -f item=$ITEM_ID -f language_field=$LANGUAGE_FIELD_ID -f language_value=${{ env.LANGUAGE_OPTION_ID }} --silent
95 |
--------------------------------------------------------------------------------
/.github/workflows/sonarcloud.yml:
--------------------------------------------------------------------------------
1 | name: Sonarcloud
2 | on:
3 | workflow_dispatch:
4 | push:
5 | branches:
6 | - main
7 | pull_request:
8 | types: [opened, synchronize, reopened]
9 |
10 | permissions:
11 | contents: read
12 | pull-requests: read
13 |
14 | env:
15 | SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
16 |
17 | jobs:
18 | checksecret:
19 | name: check if SONAR_TOKEN is set in github secrets
20 | runs-on: ubuntu-latest
21 | outputs:
22 | is_SONAR_TOKEN_set: ${{ steps.checksecret_job.outputs.is_SONAR_TOKEN_set }}
23 | steps:
24 | - name: Check whether unity activation requests should be done
25 | id: checksecret_job
26 | run: |
27 | echo "is_SONAR_TOKEN_set=${{ env.SONAR_TOKEN != '' }}" >> $GITHUB_OUTPUT
28 | build:
29 | needs: [checksecret]
30 | if: needs.checksecret.outputs.is_SONAR_TOKEN_set == 'true'
31 | name: Build
32 | runs-on: ubuntu-latest
33 | steps:
34 | - name: Set up JDK 21
35 | uses: actions/setup-java@v4
36 | with:
37 | distribution: "adopt"
38 | java-version: 21
39 | - name: Setup .NET
40 | uses: actions/setup-dotnet@v4
41 | with:
42 | dotnet-version: |
43 | 8.x
44 | - uses: actions/checkout@v4
45 | with:
46 | fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis
47 | - name: Cache SonarCloud packages
48 | uses: actions/cache@v4
49 | with:
50 | path: ~/.sonar/cache
51 | key: ${{ runner.os }}-sonar
52 | restore-keys: ${{ runner.os }}-sonar
53 | - name: Cache SonarCloud scanner
54 | id: cache-sonar-scanner
55 | uses: actions/cache@v4
56 | with:
57 | path: ./.sonar/scanner
58 | key: ${{ runner.os }}-sonar-scanner
59 | restore-keys: ${{ runner.os }}-sonar-scanner
60 | - name: Install SonarCloud scanner
61 | if: steps.cache-sonar-scanner.outputs.cache-hit != 'true'
62 | shell: pwsh
63 | run: |
64 | New-Item -Path ./.sonar/scanner -ItemType Directory
65 | dotnet tool update dotnet-sonarscanner --tool-path ./.sonar/scanner
66 | - name: Build and analyze
67 | env:
68 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Needed to get PR information, if any
69 | CollectCoverage: true
70 | CoverletOutputFormat: "opencover" # https://github.com/microsoft/vstest/issues/4014#issuecomment-1307913682
71 | shell: pwsh
72 | run: |
73 | ./.sonar/scanner/dotnet-sonarscanner begin /k:"microsoftgraph_msgraph-sdk-dotnet-core" /o:"microsoftgraph2" /d:sonar.scanner.scanAll=false /d:sonar.token="${{ secrets.SONAR_TOKEN }}" /d:sonar.host.url="https://sonarcloud.io" /d:sonar.cs.opencover.reportsPaths="tests/Microsoft.Graph.DotnetCore.Core.Test/coverage.opencover.xml"
74 | dotnet workload restore
75 | dotnet build
76 | dotnet test Microsoft.Graph.Core.sln --no-build --verbosity normal /p:CollectCoverage=true /p:CoverletOutputFormat=opencover --framework net6.0
77 | ./.sonar/scanner/dotnet-sonarscanner end /d:sonar.token="${{ secrets.SONAR_TOKEN }}"
--------------------------------------------------------------------------------
/.github/workflows/validatePullRequest.yml:
--------------------------------------------------------------------------------
1 | name: Validate Pull Request
2 |
3 | on:
4 | workflow_dispatch:
5 | push:
6 | branches: [ 'feature/*', 'main' ]
7 | pull_request:
8 | branches: [ 'feature/*', 'main' ]
9 |
10 | permissions:
11 | contents: read #those permissions are required to run the codeql analysis
12 | actions: read
13 | security-events: write
14 |
15 | jobs:
16 | build:
17 | name: Build and Test
18 | runs-on: windows-latest
19 | env:
20 | solutionName: Microsoft.Graph.Core.sln
21 | relativePath: ./src/Microsoft.Graph.Core
22 | steps:
23 | - uses: actions/checkout@v4.1.7
24 |
25 | - name: Setup .NET
26 | uses: actions/setup-dotnet@v4
27 | with:
28 | dotnet-version: 6.0.x
29 |
30 | - name: Setup JDK for android targets
31 | uses: actions/setup-java@v4
32 | with:
33 | distribution: 'microsoft'
34 | java-version: '11'
35 |
36 | - name: Initialize CodeQL
37 | uses: github/codeql-action/init@v3
38 | with:
39 | languages: csharp
40 |
41 | - name: Install needed dotnet workloads
42 | run: dotnet workload install android macos ios maccatalyst
43 |
44 | - name: Restore nuget dependencies
45 | run: dotnet restore ${{ env.solutionName }}
46 |
47 | - name: Lint the code
48 | run: dotnet format --verify-no-changes
49 |
50 | - name: Build
51 | run: dotnet build ${{ env.solutionName }} -c Debug /p:UseSharedCompilation=false,IncludeMauiTargets=true
52 |
53 | - name: Test
54 | run: dotnet test ${{ env.solutionName }} --no-build --verbosity normal -c Debug /p:CollectCoverage=true /p:CoverletOutput=TestResults/ /p:CoverletOutputFormat=opencover
55 |
56 | - name: Perform CodeQL Analysis
57 | uses: github/codeql-action/analyze@v3
58 |
59 | validate-trimming:
60 | name: Validate Project for Trimming
61 | runs-on: windows-latest
62 | steps:
63 | - uses: actions/checkout@v4.1.7
64 |
65 | - name: Setup .NET
66 | uses: actions/setup-dotnet@v4
67 | with:
68 | dotnet-version: 9.x
69 |
70 | - name: Validate Trimming warnings
71 | run: dotnet publish -c Release -r win-x64 /p:TreatWarningsAsErrors=true /warnaserror -f net9.0
72 | working-directory: ./tests/Microsoft.Graph.DotnetCore.Core.Trimming
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.sln.docstates
2 | *.suo
3 | *.user
4 | *.userosscache
5 | *.sln.ide
6 | #*.snk
7 | TestResults/*
8 | .vs/*
9 |
10 | # UWP project files
11 | project.lock.json
12 | *StoreKey.pfx
13 | Package.StoreAssociation.xml
14 |
15 | # Build results
16 | **/[Dd]ebug/
17 | **/[Dd]ebugPublic/
18 | **/[Rr]elease/
19 | **/[Rr]eleases/
20 | **/x64/
21 | **/x86/
22 | **/build/
23 | **/bld/
24 | **/[Bb]in/
25 | **/[Oo]bj/
26 |
27 | # NuGet
28 | *.nupkg
29 | **/packages/*
30 | !**/packages/build/
31 |
32 | # VS project upgrade files
33 | _UpgradeReport_Files/
34 | Backup*/
35 | UpgradeLog*.XML
36 | UpgradeLog*.htm
37 | .idea/
38 |
39 | .mono/
40 |
--------------------------------------------------------------------------------
/.release-please-manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | ".": "3.2.4"
3 | }
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing to the Microsoft Graph .Net Client Library
2 | Thanks for considering making a contribution! Read over our guidelines and we will do our best to see your PRs merged successfully.
3 |
4 | **NOTE**: A signed a contribution license agreement is required for all contributions and is checked automatically on new pull requests. You will be asked to read and sign the agreement https://cla.microsoft.com/ after submitting a request to this repository.
5 |
6 | There are a few different recommended paths to get contributions into the released version of this library.
7 |
8 | ## File issues
9 | The best way to get started with a contribution is to start a dialog with us. Sometimes features will be under development or out of scope for this library and it's best to check before starting work on contribution, especially for large work items.
10 |
11 | ## Pull requests
12 | All pull requests should be submitted against the **main** branch or a specific feature branch. The **main** branch is intended to represent the code released in the most-recent Nuget package.
13 |
14 | Some things to note about this project:
15 |
16 | ## Commit message format
17 | To support our automated release process, pull requests are required to follow the [Conventional Commit](https://www.conventionalcommits.org/en/v1.0.0/)
18 | format.
19 |
20 | Each commit message consists of a **header**, an optional **body** and an optional **footer**. The header is the first line of the commit and
21 | MUST have a **type** (see below for a list of types) and a **description**. An optional **scope** can be added to the header to give extra context.
22 |
23 | ```
24 | [optional scope]:
25 |
26 |
27 |
28 |
29 | ```
30 |
31 | The recommended commit types used are:
32 |
33 | - **feat** for feature updates (increments the _minor_ version)
34 | - **fix** for bug fixes (increments the _patch_ version)
35 | - **perf** for performance related changes e.g. optimizing an algorithm
36 | - **refactor** for code refactoring changes
37 | - **test** for test suite updates e.g. adding a test or fixing a test
38 | - **style** for changes that don't affect the meaning of code. e.g. formatting changes
39 | - **docs** for documentation updates e.g. ReadMe update or code documentation updates
40 | - **build** for build system changes (gradle updates, external dependency updates)
41 | - **ci** for CI configuration file changes e.g. updating a pipeline
42 | - **chore** for miscallaneous non-sdk changesin the repo e.g. removing an unused file
43 |
44 | Adding a footer with the prefix **BREAKING CHANGE:** will cause an increment of the _major_ version.
45 |
--------------------------------------------------------------------------------
/Directory.Build.props:
--------------------------------------------------------------------------------
1 |
2 |
3 | net6.0
4 |
5 |
6 | $(MauiTargets);net6.0-android;net6.0-ios;net6.0-maccatalyst;net6.0-macos;net6.0-windows
7 |
8 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 | Microsoft Graph SDK for .NET
2 |
3 | Copyright 2019 Microsoft Graph
4 |
5 | All right reserved.
6 |
7 | MIT License
8 |
9 | Permission is hereby granted, free of charge, to any person obtaining a copy
10 | of this software and associated documentation files (the "Software"), to deal
11 | in the Software without restriction, including without limitation the rights
12 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 | copies of the Software, and to permit persons to whom the Software is
14 | furnished to do so, subject to the following conditions:
15 |
16 | The above copyright notice and this permission notice shall be included in
17 | all copies or substantial portions of the Software.
18 |
19 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 | THE SOFTWARE.
26 |
--------------------------------------------------------------------------------
/Microsoft.Graph.Core.sln:
--------------------------------------------------------------------------------
1 | Microsoft Visual Studio Solution File, Format Version 12.00
2 | # Visual Studio Version 17
3 | VisualStudioVersion = 17.3.32804.467
4 | MinimumVisualStudioVersion = 10.0.40219.1
5 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{5E0B65FC-67B7-41F8-87BF-96D6A342C438}"
6 | EndProject
7 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{6496B661-8321-4D07-ACC2-B6602649293C}"
8 | EndProject
9 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Graph.Core", "src\Microsoft.Graph.Core\Microsoft.Graph.Core.csproj", "{9F04608C-D845-4445-83B1-E6D4EEE38CBC}"
10 | EndProject
11 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Graph.DotnetCore.Core.Test", "tests\Microsoft.Graph.DotnetCore.Core.Test\Microsoft.Graph.DotnetCore.Core.Test.csproj", "{A337BD4B-5C76-4BC5-8EC2-2EE7B834D030}"
12 | EndProject
13 | Global
14 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
15 | Debug|Any CPU = Debug|Any CPU
16 | Debug|ARM = Debug|ARM
17 | Debug|x64 = Debug|x64
18 | Debug|x86 = Debug|x86
19 | Release|Any CPU = Release|Any CPU
20 | Release|ARM = Release|ARM
21 | Release|x64 = Release|x64
22 | Release|x86 = Release|x86
23 | EndGlobalSection
24 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
25 | {9F04608C-D845-4445-83B1-E6D4EEE38CBC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
26 | {9F04608C-D845-4445-83B1-E6D4EEE38CBC}.Debug|Any CPU.Build.0 = Debug|Any CPU
27 | {9F04608C-D845-4445-83B1-E6D4EEE38CBC}.Debug|ARM.ActiveCfg = Debug|Any CPU
28 | {9F04608C-D845-4445-83B1-E6D4EEE38CBC}.Debug|ARM.Build.0 = Debug|Any CPU
29 | {9F04608C-D845-4445-83B1-E6D4EEE38CBC}.Debug|x64.ActiveCfg = Debug|Any CPU
30 | {9F04608C-D845-4445-83B1-E6D4EEE38CBC}.Debug|x64.Build.0 = Debug|Any CPU
31 | {9F04608C-D845-4445-83B1-E6D4EEE38CBC}.Debug|x86.ActiveCfg = Debug|Any CPU
32 | {9F04608C-D845-4445-83B1-E6D4EEE38CBC}.Debug|x86.Build.0 = Debug|Any CPU
33 | {9F04608C-D845-4445-83B1-E6D4EEE38CBC}.Release|Any CPU.ActiveCfg = Release|Any CPU
34 | {9F04608C-D845-4445-83B1-E6D4EEE38CBC}.Release|Any CPU.Build.0 = Release|Any CPU
35 | {9F04608C-D845-4445-83B1-E6D4EEE38CBC}.Release|ARM.ActiveCfg = Release|Any CPU
36 | {9F04608C-D845-4445-83B1-E6D4EEE38CBC}.Release|ARM.Build.0 = Release|Any CPU
37 | {9F04608C-D845-4445-83B1-E6D4EEE38CBC}.Release|x64.ActiveCfg = Release|Any CPU
38 | {9F04608C-D845-4445-83B1-E6D4EEE38CBC}.Release|x64.Build.0 = Release|Any CPU
39 | {9F04608C-D845-4445-83B1-E6D4EEE38CBC}.Release|x86.ActiveCfg = Release|Any CPU
40 | {9F04608C-D845-4445-83B1-E6D4EEE38CBC}.Release|x86.Build.0 = Release|Any CPU
41 | {A337BD4B-5C76-4BC5-8EC2-2EE7B834D030}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
42 | {A337BD4B-5C76-4BC5-8EC2-2EE7B834D030}.Debug|Any CPU.Build.0 = Debug|Any CPU
43 | {A337BD4B-5C76-4BC5-8EC2-2EE7B834D030}.Debug|ARM.ActiveCfg = Debug|Any CPU
44 | {A337BD4B-5C76-4BC5-8EC2-2EE7B834D030}.Debug|ARM.Build.0 = Debug|Any CPU
45 | {A337BD4B-5C76-4BC5-8EC2-2EE7B834D030}.Debug|x64.ActiveCfg = Debug|Any CPU
46 | {A337BD4B-5C76-4BC5-8EC2-2EE7B834D030}.Debug|x64.Build.0 = Debug|Any CPU
47 | {A337BD4B-5C76-4BC5-8EC2-2EE7B834D030}.Debug|x86.ActiveCfg = Debug|Any CPU
48 | {A337BD4B-5C76-4BC5-8EC2-2EE7B834D030}.Debug|x86.Build.0 = Debug|Any CPU
49 | {A337BD4B-5C76-4BC5-8EC2-2EE7B834D030}.Release|Any CPU.ActiveCfg = Release|Any CPU
50 | {A337BD4B-5C76-4BC5-8EC2-2EE7B834D030}.Release|Any CPU.Build.0 = Release|Any CPU
51 | {A337BD4B-5C76-4BC5-8EC2-2EE7B834D030}.Release|ARM.ActiveCfg = Release|Any CPU
52 | {A337BD4B-5C76-4BC5-8EC2-2EE7B834D030}.Release|ARM.Build.0 = Release|Any CPU
53 | {A337BD4B-5C76-4BC5-8EC2-2EE7B834D030}.Release|x64.ActiveCfg = Release|Any CPU
54 | {A337BD4B-5C76-4BC5-8EC2-2EE7B834D030}.Release|x64.Build.0 = Release|Any CPU
55 | {A337BD4B-5C76-4BC5-8EC2-2EE7B834D030}.Release|x86.ActiveCfg = Release|Any CPU
56 | {A337BD4B-5C76-4BC5-8EC2-2EE7B834D030}.Release|x86.Build.0 = Release|Any CPU
57 | EndGlobalSection
58 | GlobalSection(SolutionProperties) = preSolution
59 | HideSolutionNode = FALSE
60 | EndGlobalSection
61 | GlobalSection(NestedProjects) = preSolution
62 | {9F04608C-D845-4445-83B1-E6D4EEE38CBC} = {5E0B65FC-67B7-41F8-87BF-96D6A342C438}
63 | {A337BD4B-5C76-4BC5-8EC2-2EE7B834D030} = {6496B661-8321-4D07-ACC2-B6602649293C}
64 | EndGlobalSection
65 | GlobalSection(ExtensibilityGlobals) = postSolution
66 | SolutionGuid = {0DB06E6E-58F0-497F-9ECC-00DD03BA9357}
67 | EndGlobalSection
68 | EndGlobal
69 |
--------------------------------------------------------------------------------
/THIRD PARTY NOTICES:
--------------------------------------------------------------------------------
1 | This file is based on or incorporates material from the projects listed below (Third Party OSS). The original copyright notice and the license under which Microsoft received such Third Party OSS, are set forth below. Such licenses and notices are provided for informational purposes only. Microsoft licenses the Third Party OSS to you under the licensing terms for the Microsoft product or service. Microsoft
2 | reserves all other rights not expressly granted under this agreement, whether by implication, estoppel or otherwise.
3 |
4 | Newtonsoft.Json - 6.0.1 <= 9.0.1
5 | Copyright (c) 2008 James Newton-King
6 |
7 | Provided for Informational Purposes Only
8 |
9 | MIT License
10 |
11 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the Software), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
12 |
13 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
17 |
--------------------------------------------------------------------------------
/build/35MSSharedLib1024.snk:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoftgraph/msgraph-sdk-dotnet-core/aee58489ff89d89ea20ed3825224a6339858d980/build/35MSSharedLib1024.snk
--------------------------------------------------------------------------------
/docs/FAQ.md:
--------------------------------------------------------------------------------
1 | # Frequently Asked Questions
2 |
3 | ## How do I get past the System.IO.FileLoadException
4 |
5 | We built the .Net Microsoft Graph client library against a specific version of the JSON.Net library. That version is specified in the .Net client library assembly manifest. We specify a range of potential JSON.Net versions that can be used by our client library in our Nuget package specification.
6 |
7 | Your project may already have a reference to JSON.Net. When you add the Microsoft Graph library via Nuget, Nuget won't install the JSON.Net dependency that was used to build the Microsoft Graph library when you already have a reference to JSON.Net in your project. This may lead to a FileLoadException as the CLR will try to load the version used to build the Microsoft Graph library and won't find it in the case that your project reference to JSON.Net is different than the version of JSON.Net used to build the Microsoft Graph library.
8 |
9 | You have three options to get around this scenario:
10 |
11 | 1. Add a [binding redirect to your application](https://docs.microsoft.com/en-us/dotnet/framework/configure-apps/redirect-assembly-versions#redirecting-assembly-versions-at-the-app-level) to unify the version of JSON.Net used by your application.
12 | 2. [Assembly resolution at runtime](https://docs.microsoft.com/en-us/dotnet/framework/app-domains/resolve-assembly-loads) if the binding redirect option is not available. Here's an [AssemblyResolutionDemo](https://github.com/danmalcolm/AssemblyResolutionDemo) that shows how this works.
13 | 3. Change the version of the JSON.Net dependency in your project to match the version used by Microsoft Graph .Net client library. This will be your only option for UWP applications at the time of this writing.
--------------------------------------------------------------------------------
/docs/collections.md:
--------------------------------------------------------------------------------
1 | Collections in the Microsoft Graph .NET Client Library
2 | =====
3 |
4 | Whenever a request returns a collection of objects that allow paging or navigation into the collection, the library generates a complex collection page object.
5 |
6 | ## Getting a collection
7 |
8 | To retrieve a collection, like the list of groups in the service, you call `GetAsync` on the collection request:
9 |
10 | ```csharp
11 | await graphServiceClient
12 | .Groups
13 | .GetAsync();
14 | ```
15 |
16 | `GetAsync` returns an `IParsable` implementation on success and throws a `ServiceException` on error.
17 |
18 | The `IParsable` instance returned will typically contain two properties:
19 |
20 | |Name |Description |
21 | |--------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------|
22 | |**Value** |An `List- `. |
23 | |**NextLink** |A `string` representing the url used to get to the next page of items, if another page exists. This value will be null if there is not a next page.|
24 | |**AdditionalData** |An `IDictionary` to any additional values returned by the service. In this case, none. |
25 |
26 | ## Adding to a collection
27 |
28 | Some collections, like the groups collection, can be changed. To create a group you can call:
29 |
30 | ```csharp
31 | var groupToCreate = new Group
32 | {
33 | GroupTypes = new List { "Unified" },
34 | DisplayName = "Unified group",
35 | Description = "Best group ever"
36 | };
37 |
38 | var newGroup = await graphServiceClient
39 | .Groups
40 | .PostAsync(groupToCreate);
41 | ```
42 |
43 | `AddAsync` returns the created group on success and throws a `ApiException` on error.
44 |
45 | ## Expanding a collection
46 |
47 | To expand a collection, you call `Expand` on the collection request object with the string value of the expand:
48 |
49 | ```csharp
50 | var children = await graphServiceClient
51 | .Drive
52 | .Items["itemId"]
53 | .Children
54 | .GetAsync((requestConfiguration) => requestConfiguration.QueryParameters.Expand = new[] { "thumbnails" });
55 | ```
56 |
--------------------------------------------------------------------------------
/docs/contributions.md:
--------------------------------------------------------------------------------
1 | Contributing to the Microsoft Graph .NET Client Library
2 | =====
3 |
4 | The Microsoft Graph .NET Client Library is avaliable for all manner of contribution. There are a few different recommended paths to get contributions into the released version of this library.
5 |
6 | **NOTE** A signed a contribution license agreement is required for all contributions and is checked automatically on new pull requests. Please read and sign the agreement https://cla.microsoft.com/ before starting any work for this repository.
7 |
8 | ## File issues
9 |
10 | The best way to get started with a contribution is to start a dialog with the owners of the repository. Sometimes features will be under development or out of scope for this library and it's best to check before starting work on contribution.
11 |
12 | ## Pull requests
13 |
14 | If you are making documentation changes, feel free to submit a pull request against the **main** branch. Other pull requests could be submitted against a specific **feature** branch.
15 |
16 | The package will be generated from **main**.
17 |
18 | ## Submit pull requests for trivial changes
19 |
20 | If you are making a change that does not affect the interface components and does not affect other downstream callers, feel free to make a pull request against the **main** branch.
21 |
22 | Revisions of this nature will result in a 0.0.X change of the version number.
23 |
24 | ## Submit pull requests for features
25 |
26 | If major functionality is being added it should be submitted against the **main** branch. If the functionality will require multiple changes or iterations before it is ready for **main**, feel free to submit pull requests into a dedicated **feature** branch until the whole change is ready.
27 |
28 | Revisions of this nature will result in a 0.X.X change of the version number.
--------------------------------------------------------------------------------
/docs/errors.md:
--------------------------------------------------------------------------------
1 | Handling errors in the Microsoft Graph .NET Client Library
2 | =====
3 |
4 | Errors in the Microsoft Graph .NET Client Library behave like errors returned from the Microsoft Graph service. You can read more about them [here](https://graph.microsoft.io/en-us/docs/overview/errors).
5 |
6 | Anytime you make a request against the service there is the potential for an error. In the case of an error, the request will throw a `ServiceException` object with an inner `Error` object that contains the service error details.
7 |
8 | ## Checking the error
9 |
10 | There are a few different types of errors that can occur during a network call. These error codes are defined in [GraphErrorCode.cs](../src/Microsoft.Graph/Enums/GraphErrorCode.cs).
11 |
12 | ### Checking the error code
13 | You can easily check if an error has a specific code by calling `IsMatch` on the error code value. `IsMatch` is not case sensitive:
14 |
15 | ```csharp
16 | if (exception.IsMatch(GraphErrorCode.AccessDenied.ToString())
17 | {
18 | // Handle access denied error
19 | }
20 | ```
21 |
22 | Each error object has a `Message` property as well as code. This message is for debugging purposes and is not be meant to be displayed to the user. Common error codes are defined in [GraphErrorCode.cs](../src/Microsoft.Graph/Enums/GraphErrorCode.cs).
--------------------------------------------------------------------------------
/docs/headers.md:
--------------------------------------------------------------------------------
1 | # Headers in the Microsoft Graph .NET Client Library
2 |
3 | The .NET Client Library allows you to add your own custom request headers and inspect the response headers that come back from the Graph service.
4 |
5 | ## Adding request headers
6 |
7 | Custom headers can be added by using the requestConfiguration object and adding it to the headers collection:
8 |
9 | ```csharp
10 | var message = await graphServiceClient
11 | .Me
12 | .Messages["message-id"]
13 | .GetAsync((requestConfiguration) =>
14 | {
15 | requestConfiguration.Headers.Add("Etag", "etag");
16 | requestConfiguration.Headers.Add("If-Match", "ifmatch");
17 | });
18 | ```
19 |
--------------------------------------------------------------------------------
/docs/overview.md:
--------------------------------------------------------------------------------
1 | Microsoft Graph .NET Client Library Overview
2 | =====
3 |
4 | The Microsoft Graph .NET Client Library is made up of 6 major components:
5 |
6 | * A client object
7 | * An authentication provider
8 | * An HTTP provider + serializer
9 | * Request builder objects
10 | * Request objects
11 | * Property bag object model classes for serialization and deserialization
12 |
13 | The library is designed to be highly extensible. This overview covers basic scenarios but many of the individual components can be replaced with custom implementations.
14 |
15 | ## GraphServiceClient
16 |
17 | To begin making requests with the library, you will need to initialize a **GraphServiceClient** instance for building and sending requests.
18 |
19 | ### GraphServiceClientConstructor
20 |
21 | | Parameter | Required? | Default Value |
22 | |:-----------------------------------------------|:---------------|:-------------------------------------------------|
23 | |`IAuthenticationProvider` authenticationProvider| Yes | n/a |
24 |
25 | ## IAuthenticationProvider
26 |
27 | The authentication provider is responsible for authenticating requests before sending them to the service. The Microsoft Graph .NET Client Library doesn't implement any authentication by default. Instead, you will need to retrieve access tokens for the service via the authentication library of your choice or by coding against one of the authentication endpoints directly. Please [read here](https://developer.microsoft.com/en-us/graph/docs/concepts/auth_overview) for more details about authenticating the Microsoft Graph service.
28 |
29 | You can also read about authentication with Kiota generated clients [here](https://github.com/microsoft/kiota/blob/main/docs/extending/authentication.md#authentication-with-kiota-clients)
30 |
31 | ## Resource model
32 |
33 | Microsoft Graph service resource are represented by property bag model classes of the same name in the client library. For example, the [user resource](https://graph.microsoft.io/en-us/docs/api-reference/v1.0/resources/user) is represented by the [user class](../src/Microsoft.Graph/Models/Generated/User.cs) in the client library. Each of these model classes contain properties that represent the properties of the resources they represent.
34 |
35 | These classes are used for serializing and deserializing the resources in requests to the service. They do not contain any logic to issue requests.
36 |
37 | The resource model classes are generated based on the $metadata description of the service.
38 |
39 | ## Requests
40 |
41 | To make requests against the service, you'll need to build a request using the request builders of the client. The request builder patterns are intended to mirror the REST API pattern.
42 |
43 | ### 1. Request builders
44 |
45 | You get the first request builder from the `GraphServiceClient` object. For example, to get a request builder for the /me navigation you call:
46 |
47 | |Task | SDK | URL |
48 | |:----------|:----------------------:|:-------------------------------|
49 | |Get me | graphServiceClient.Me | GET graph.microsoft.com/v1.0/me|
50 |
51 | The call will return a `UserRequestBuilder` object. From Me you can continue to chain the request builders.
52 |
53 | The [Microsoft Graph service documentation](https://graph.microsoft.io/en-us/docs) has more details about the full functionality of the API.
54 |
55 |
56 | ### 2. Request calls
57 |
58 | To get /me/calendar you call:
59 |
60 | ``` csharp
61 | var calendar = await graphServiceClient
62 | .Me
63 | .Calendar
64 | .GetAsync();
65 | ```
66 |
67 | Any errors while building or sending a request will bubble up as an `ApiException`. See [errors](/docs/errors.md) for more information on errors.
68 |
69 | ## Query options
70 |
71 | If you only want to retrieve certain properties of a resource you can select them. Here's how to get only the ID of the me object:
72 |
73 | ``` csharp
74 | var user = await graphServiceClient
75 | .Me
76 | .GetAsync( requestConfiguration => requestConfiguration.QueryParameters.Select = new string[] { "id"});
77 | ```
78 |
79 | All properties other than `Id` will be null on the returned user object.
80 |
81 | Expand, Skip, Top, OrderBy, and Filter are also supported via the client library when supported by the Microsoft Graph service for the request type.
82 |
83 | ## Collections
84 |
85 | Please see [collections](/docs/collections.md) for details on collections and paging.
86 |
--------------------------------------------------------------------------------
/global.json:
--------------------------------------------------------------------------------
1 | {
2 | "sdk": {
3 | "version": "6.0.417", /* https://github.com/dotnet/maui/wiki/.NET-7-and-.NET-MAUI */
4 | "rollForward": "major"
5 | }
6 | }
--------------------------------------------------------------------------------
/release-please-config.json:
--------------------------------------------------------------------------------
1 | {
2 | "bootstrap-sha": "ee54a79fcbc6d412ed8b9cef875371558de3627e",
3 | "exclude-paths": [
4 | ".git",
5 | ".idea",
6 | ".github",
7 | ".vscode"
8 | ],
9 | "release-type": "simple",
10 | "include-component-in-tag": false,
11 | "include-v-in-tag": false,
12 | "packages": {
13 | ".": {
14 | "package-name": "Microsoft.Graph.Core",
15 | "changelog-path": "CHANGELOG.md",
16 | "extra-files": [
17 | "src/Microsoft.Graph.Core/Microsoft.Graph.Core.csproj"
18 | ]
19 | }
20 | },
21 | "$schema": "https://raw.githubusercontent.com/googleapis/release-please/main/schemas/config.json"
22 | }
--------------------------------------------------------------------------------
/scripts/EnableSigning.ps1:
--------------------------------------------------------------------------------
1 | # Copyright (c) Microsoft Corporation. All rights reserved.
2 | # Licensed under the MIT License.
3 |
4 | <#
5 | .Synopsis
6 | Sets the project ready for signing.
7 |
8 | .Description
9 | This allows us to not have to checkin .csproj files with DelaySign and SignAssembly set to to true.
10 | If the flag is set, then project is not debuggable with SignAssembly set to true.
11 | Assumption: working directory is /src/
12 |
13 | .Parameter projectPath
14 | Specifies the path to the project file.
15 | #>
16 |
17 | Param(
18 | [parameter(Mandatory = $true)]
19 | [string]$projectPath
20 | )
21 |
22 | $doc = New-Object System.Xml.XmlDocument
23 | $doc.Load($projectPath)
24 |
25 | # Set the DelaySign element to 'true' so that delay signing is set.
26 | $delaySign = $doc.SelectSingleNode("//DelaySign");
27 | $delaySign.'#text' = "true"
28 |
29 | # Set the SignAssembly element to 'true' so that we can sign the assemblies.
30 | $signAssembly = $doc.SelectSingleNode("//SignAssembly");
31 | $signAssembly.'#text' = "true"
32 |
33 | $doc.Save($projectPath);
34 |
35 | Write-Host "Updated the .csproj file so that we can sign the built assemblies." -ForegroundColor Green
--------------------------------------------------------------------------------
/scripts/GetLatestCommitSHA.ps1:
--------------------------------------------------------------------------------
1 | # Copyright (c) Microsoft Corporation. All rights reserved.
2 | # Licensed under the MIT License.
3 |
4 | <#
5 | .Synopsis
6 | Gets the latest commit SHA for the repository.
7 | .Description
8 | Uses the GitHub API and the owner name, the repository name, and the branch name
9 | to get the latest commit SHA and set its value to an environment variable named
10 | LATEST_COMMIT_SHA in an Azure DevOps release environment.
11 | .Parameter owner
12 | Specifies the owner of the repo.
13 | .Parameter repo
14 | Specifies the name of the repository.
15 | .Parameter branchName
16 | Specifies the target branch name. The default value is 'main'.
17 | #>
18 |
19 | Param(
20 | [string]$owner,
21 | [string]$repo,
22 | [string]$branchName = "main"
23 | )
24 |
25 | if ([string]::IsNullOrEmpty($owner)) {
26 | Write-Error "owner cannot be empty."
27 | EXIT 1
28 | }
29 |
30 | if ([string]::IsNullOrEmpty($repo)) {
31 | Write-Error "repo cannot be empty."
32 | EXIT 1
33 | }
34 |
35 | Write-Host "Getting the latest commit SHA for $($branchName):" -ForegroundColor Magenta
36 |
37 | $latestCommitUrl = "https://api.github.com/repos/$($owner)/$($repo)/commits/$($branchName)"
38 |
39 | Write-Host "Getting latest commit with '$($latestCommitUrl)'" -ForegroundColor Blue
40 | $latestCommitData = Invoke-RestMethod -Uri $latestCommitUrl -Method Get
41 |
42 | if ($latestCommitData.Count -eq 0) {
43 | Write-Host "Unable to get latest commit with '$($latestCommitUrl)'" -ForegroundColor Red
44 | EXIT 1;
45 | }
46 |
47 | if ([string]::IsNullOrEmpty($latestCommitData.sha)) {
48 | Write-Host "SHA is not present in the latest commit that is fetched" -ForegroundColor Red
49 | Write-Host "Latest Commit Data:" -ForegroundColor Cyan
50 | Write-Host -Object $latestCommitData -ForegroundColor Cyan
51 | EXIT 1;
52 | }
53 |
54 | Write-Host "Latest Commit SHA is '$($latestCommitData.sha)'" -ForegroundColor Green
55 |
56 | Write-Host "##vso[task.setvariable variable=LATEST_COMMIT_SHA]$($latestCommitData.sha)"
57 |
58 | Write-Host "Updated the LATEST_COMMIT_SHA environment variable with the latest commit SHA." -ForegroundColor Green
--------------------------------------------------------------------------------
/scripts/GetNugetPackageVersion.ps1:
--------------------------------------------------------------------------------
1 | # Copyright (c) Microsoft Corporation. All rights reserved.
2 | # Licensed under the MIT License.
3 |
4 | <#
5 | .Synopsis
6 | Get the NuGet package version.
7 | .Description
8 | Get the NuGet package version and write the package version to an environment
9 | variable named VERSION_STRING in the Azure DevOps release environment.
10 | VERSION_STRING is used to name a tag for setting a GitHub release. This
11 | script assumes that the NuGet package has been named with correct version number.
12 |
13 | Assumption:
14 | Targets Microsoft.Graph.
15 |
16 | .Parameter packageDirPath
17 | Specifies the fully qualified path to the NuGet package directory.
18 | #>
19 |
20 | Param(
21 | [string]$packageDirPath
22 | )
23 |
24 | Write-Host "Get the NuGet package version and set it in the global variable: VERSION_STRING" -ForegroundColor Magenta
25 |
26 | $nugetPackageName = (Get-ChildItem (Join-Path $packageDirPath *.nupkg) -Exclude *.symbols.nupkg).Name
27 |
28 | Write-Host "Found NuGet package: $nugetPackageName" -ForegroundColor Magenta
29 |
30 | ## Extracts the package version from nupkg file name.
31 | $packageVersion = $nugetPackageName.Replace("Microsoft.Graph.Core.", "").Replace(".nupkg", "")
32 |
33 | Write-Host "##vso[task.setvariable variable=VERSION_STRING]$($packageVersion)";
34 | Write-Host "Updated the VERSION_STRING environment variable with the package version value '$packageVersion'." -ForegroundColor Green
35 |
36 | $isPrerelease = $packageVersion.Contains("preview")
37 | Write-Host "##vso[task.setvariable variable=IS_PRE_RELEASE]$($isPrerelease)";
38 | Write-Host "Updated the IS_PRE_RELEASE environment variable with the pre-release value '$isPrerelease'." -ForegroundColor Green
--------------------------------------------------------------------------------
/scripts/ValidateUpdatedNugetVersion.ps1:
--------------------------------------------------------------------------------
1 | # Copyright (c) Microsoft Corporation. All rights reserved.
2 | # Licensed under the MIT License.
3 |
4 | <#
5 | .Synopsis
6 | Gets the latest production release version of the specified NuGet package.
7 |
8 | .Description
9 | Gets the NuGet package version of latest production release and compares the
10 | version to the version set in the specified project file. If they match, this
11 | script will fail and indicate that the version needs to be updated.
12 |
13 | .Parameter packageName
14 | Specifies the package name of the package. For example, 'microsoft.kiota.abstractions'
15 | is a valid package name.
16 |
17 | .Parameter projectPath
18 | Specifies the path to the project file.
19 | #>
20 |
21 | Param(
22 | [parameter(Mandatory = $true)]
23 | [string]$packageName,
24 |
25 | [parameter(Mandatory = $true)]
26 | [string]$projectPath
27 | )
28 |
29 | [xml]$xmlDoc = Get-Content $projectPath
30 |
31 | # Assumption: VersionPrefix is set in the first property group.
32 | $versionPrefixString = $xmlDoc.Project.PropertyGroup[0].VersionPrefix
33 | if($xmlDoc.Project.PropertyGroup[0].VersionSuffix){
34 | $versionPrefixString = $versionPrefixString + "-" + $xmlDoc.Project.PropertyGroup[0].VersionSuffix
35 | }
36 |
37 |
38 | # System.Version, get the version prefix.
39 | $currentProjectVersion = [System.Management.Automation.SemanticVersion]"$versionPrefixString"
40 |
41 | # API is case-sensitive
42 | $packageName = $packageName.ToLower()
43 | $url = "https://api.nuget.org/v3/registration5-gz-semver2/$packageName/index.json"
44 |
45 | # Call the NuGet API for the package and get the current published version.
46 | Try {
47 | $nugetIndex = Invoke-RestMethod -Uri $url -Method Get
48 | }
49 | Catch {
50 | if ($_.ErrorDetails.Message && $_.ErrorDetails.Message.Contains("The specified blob does not exist.")) {
51 | Write-Host "No package exists. You will probably be publishing $packageName for the first time."
52 | Exit # exit gracefully
53 | }
54 |
55 | Write-Host $_
56 | Exit 1
57 | }
58 |
59 | $currentPublishedVersion = [System.Management.Automation.SemanticVersion]$nugetIndex.items[$nugetIndex.items.Count-1].upper
60 |
61 | # Validate that the version number has been updated.
62 | if ($currentProjectVersion -le $currentPublishedVersion) {
63 |
64 | Write-Error "The current published version number, $currentPublishedVersion, and the version number `
65 | in the csproj file, $currentProjectVersion, match. You must increment the version"
66 | }
67 | else {
68 | Write-Host "Validated that the version has been updated from $currentPublishedVersion to $currentProjectVersion" -ForegroundColor Green
69 | }
--------------------------------------------------------------------------------
/src/Microsoft.Graph.Core/35MSSharedLib1024.snk:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoftgraph/msgraph-sdk-dotnet-core/aee58489ff89d89ea20ed3825224a6339858d980/src/Microsoft.Graph.Core/35MSSharedLib1024.snk
--------------------------------------------------------------------------------
/src/Microsoft.Graph.Core/Authentication/AzureIdentityAccessTokenProvider.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | using System;
6 | using System.Linq;
7 | using Azure.Core;
8 | using Microsoft.Kiota.Abstractions.Authentication;
9 |
10 | namespace Microsoft.Graph.Authentication;
11 |
12 | ///
13 | /// An overload of the Access Token Provider that has the defaults for Microsoft Graph.
14 | ///
15 | public class AzureIdentityAccessTokenProvider : Microsoft.Kiota.Authentication.Azure.AzureIdentityAccessTokenProvider
16 | {
17 | ///
18 | public AzureIdentityAccessTokenProvider(TokenCredential credential, string[] allowedHosts = null, Microsoft.Kiota.Authentication.Azure.ObservabilityOptions observabilityOptions = null, bool isCaeEnabled = true, params string[] scopes)
19 | : base(credential, allowedHosts, observabilityOptions, isCaeEnabled, scopes)
20 | {
21 | if (!allowedHosts?.Any() ?? true)
22 | AllowedHostsValidator = new AllowedHostsValidator(new string[] { "graph.microsoft.com", "graph.microsoft.us", "dod-graph.microsoft.us", "graph.microsoft.de", "microsoftgraph.chinacloudapi.cn", "canary.graph.microsoft.com", "graph.microsoft-ppe.com" });
23 | }
24 |
25 | ///
26 | [Obsolete("This constructor is obsolete and will be removed in a future version. Use the constructor that takes an isCaeEnabled parameter instead.")]
27 | public AzureIdentityAccessTokenProvider(TokenCredential credential, string[] allowedHosts = null, Microsoft.Kiota.Authentication.Azure.ObservabilityOptions observabilityOptions = null, params string[] scopes)
28 | : this(credential, allowedHosts, observabilityOptions, true, scopes)
29 | {
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/Microsoft.Graph.Core/Authentication/AzureIdentityAuthenticationProvider.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | using System;
6 | using Azure.Core;
7 | using Microsoft.Kiota.Abstractions.Authentication;
8 |
9 | namespace Microsoft.Graph.Authentication;
10 | ///
11 | /// An overload of the Azure Identity Authentication Provider that has the defaults for Microsoft Graph.
12 | ///
13 | public class AzureIdentityAuthenticationProvider : BaseBearerTokenAuthenticationProvider
14 | {
15 | ///
16 | /// The constructor
17 | ///
18 | /// The credential implementation to use to obtain the access token.
19 | /// The list of allowed hosts for which to request access tokens.
20 | /// The scopes to request the access token for.
21 | /// The observability options to use for the authentication provider.
22 | /// Determines if the Continuous Access Evaluation (CAE) is enabled.
23 | public AzureIdentityAuthenticationProvider(TokenCredential credential, string[] allowedHosts = null, Microsoft.Kiota.Authentication.Azure.ObservabilityOptions observabilityOptions = null, bool isCaeEnabled = true, params string[] scopes) : base(new AzureIdentityAccessTokenProvider(credential, allowedHosts, observabilityOptions, isCaeEnabled, scopes))
24 | {
25 | }
26 | ///
27 | /// The constructor
28 | ///
29 | /// The credential implementation to use to obtain the access token.
30 | /// The list of allowed hosts for which to request access tokens.
31 | /// The scopes to request the access token for.
32 | /// The observability options to use for the authentication provider.
33 | [Obsolete("Use the constructor that takes an isCaeEnabled parameter instead.")]
34 | public AzureIdentityAuthenticationProvider(TokenCredential credential, string[] allowedHosts = null, Microsoft.Kiota.Authentication.Azure.ObservabilityOptions observabilityOptions = null, params string[] scopes) : this(credential, allowedHosts, observabilityOptions, true, scopes)
35 | {
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/Microsoft.Graph.Core/Exceptions/ClientException.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | namespace Microsoft.Graph
6 | {
7 | using System;
8 | using Microsoft.Kiota.Abstractions;
9 |
10 | ///
11 | /// Graph client exception.
12 | ///
13 | public class ClientException : ApiException
14 | {
15 | ///
16 | /// Creates a new client exception.
17 | ///
18 | /// The exception message.
19 | /// The possible innerException.
20 | public ClientException(string message, Exception innerException = null) : base(message, innerException)
21 | {
22 | }
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/Microsoft.Graph.Core/Exceptions/ErrorConstants.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | namespace Microsoft.Graph
6 | {
7 | internal static class ErrorConstants
8 | {
9 | internal static class Codes
10 | {
11 | internal const string GeneralException = "generalException";
12 | }
13 |
14 | internal static class Messages
15 | {
16 | internal const string MaximumValueExceeded = "{0} exceeds the maximum value of {1}.";
17 |
18 | internal const string NullParameter = "{0} parameter cannot be null.";
19 |
20 | internal const string UnableToDeserializeContent = "Unable to deserialize content.";
21 |
22 | internal const string InvalidDependsOnRequestId = "Corresponding batch request id not found for the specified dependsOn relation.";
23 |
24 | internal const string ExpiredUploadSession = "Upload session expired. Upload cannot resume";
25 |
26 | internal const string NoResponseForUpload = "No Response Received for upload.";
27 |
28 | internal const string MissingRetryAfterHeader = "Missing retry after header.";
29 |
30 | internal const string PageIteratorRequestError = "Error occured when making a request with the page iterator. See inner exception for more details.";
31 |
32 | internal const string BatchRequestError = "Error occured when making the batch request. See inner exception for more details.";
33 |
34 | internal const string InvalidProxyArgument = "Proxy cannot be set more once. Proxy can only be set on the proxy or defaultHttpHandler argument and not both.";
35 | }
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/Microsoft.Graph.Core/Extensions/HttpClientExtensions.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | namespace Microsoft.Graph
6 | {
7 | using System;
8 | using System.Linq;
9 | using System.Net.Http;
10 |
11 | internal static class HttpClientExtensions
12 | {
13 | ///
14 | /// Adds featureflag to existing header values.
15 | ///
16 | /// The http client to set FeatureUsage header.
17 | /// The Feature usage flag to set.
18 | internal static void SetFeatureFlag(this HttpClient httpClient, FeatureFlag featureFlag)
19 | {
20 | // If feature flag header exists, add incoming flag to existing bitfield values and replace existing header with the computed bitfield total.
21 | if (httpClient.DefaultRequestHeaders.TryGetValues(CoreConstants.Headers.FeatureFlag, out var flags))
22 | {
23 | // Add incoming flag to existing feature flag values.
24 | foreach (string flag in flags)
25 | if (Enum.TryParse(Convert.ToInt32(flag, 16).ToString(), out FeatureFlag targetFeatureFlag))
26 | featureFlag |= targetFeatureFlag;
27 |
28 | // Remove current header value.
29 | httpClient.DefaultRequestHeaders.Remove(CoreConstants.Headers.FeatureFlag);
30 | }
31 |
32 | // Add/Replace new computed bitfield.
33 | httpClient.DefaultRequestHeaders.Add(CoreConstants.Headers.FeatureFlag, Enum.Format(typeof(FeatureFlag), featureFlag, "x"));
34 | }
35 |
36 | ///
37 | /// Checks if a featureflag existing in the default header values.
38 | ///
39 | /// The http client to set FeatureUsage header.
40 | /// The Feature usage flag to check for.
41 | internal static bool ContainsFeatureFlag(this HttpClient httpClient, FeatureFlag featureFlag)
42 | {
43 | if (httpClient.DefaultRequestHeaders.TryGetValues(CoreConstants.Headers.FeatureFlag, out var flags))
44 | {
45 | string flag = flags.FirstOrDefault();
46 | if (Enum.TryParse(Convert.ToInt32(flag, 16).ToString(), out FeatureFlag targetFeatureFlag))
47 | return targetFeatureFlag.HasFlag(featureFlag);
48 | }
49 | return false;
50 | }
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/src/Microsoft.Graph.Core/Extensions/HttpRequestMessageExtensions.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | namespace Microsoft.Graph
6 | {
7 | using System;
8 | using System.Collections.Generic;
9 | using System.Linq;
10 | using System.Net.Http;
11 |
12 | ///
13 | /// Contains extension methods for
14 | ///
15 | public static class HttpRequestMessageExtensions
16 | {
17 | ///
18 | /// Get's feature request header value from the incoming
19 | ///
20 | /// The object
21 | ///
22 | internal static FeatureFlag GetFeatureFlags(this HttpRequestMessage httpRequestMessage)
23 | {
24 | httpRequestMessage.Headers.TryGetValues(CoreConstants.Headers.FeatureFlag, out IEnumerable flags);
25 |
26 | if (!Enum.TryParse(flags?.FirstOrDefault(), out FeatureFlag featureFlag))
27 | {
28 | featureFlag = FeatureFlag.None;
29 | }
30 |
31 | return featureFlag;
32 | }
33 |
34 | ///
35 | /// Gets a from
36 | ///
37 | /// The representation of the request.
38 | ///
39 | public static GraphRequestContext GetRequestContext(this HttpRequestMessage httpRequestMessage)
40 | {
41 | GraphRequestContext requestContext = new GraphRequestContext();
42 | #pragma warning disable CS0618
43 | if (httpRequestMessage.Properties.TryGetValue(nameof(GraphRequestContext), out var requestContextObject))
44 | #pragma warning restore CS0618
45 | {
46 | requestContext = (GraphRequestContext)requestContextObject;
47 | }
48 | return requestContext;
49 | }
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/src/Microsoft.Graph.Core/Extensions/IEncryptableSubscriptionExtensions.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | namespace Microsoft.Graph
6 | {
7 | using System;
8 | using System.Security.Cryptography.X509Certificates;
9 |
10 | ///
11 | /// Contains extension methods for
12 | ///
13 | public static class IEncryptableSubscriptionExtensions
14 | {
15 | ///
16 | /// Adds the public encryption certificate information for change notifications with resource data to the subscription creation information.
17 | ///
18 | /// The subscription instance of type
19 | /// Certificate to use for encryption
20 | /// Thrown when is null
21 | public static void AddPublicEncryptionCertificate(this IEncryptableSubscription subscription, X509Certificate2 certificate)
22 | {
23 | if (certificate == null)
24 | throw new ArgumentNullException(nameof(certificate));
25 |
26 | subscription.EncryptionCertificate = Convert.ToBase64String(certificate.Export(X509ContentType.Cert));
27 | }
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/Microsoft.Graph.Core/Extensions/IParseNodeExtensions.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.Kiota.Abstractions.Serialization;
2 |
3 | namespace Microsoft.Graph;
4 |
5 | ///
6 | /// Extension helpers for the
7 | ///
8 | public static class ParseNodeExtensions
9 | {
10 | internal static string GetErrorMessage(this IParseNode responseParseNode)
11 | {
12 | var errorParseNode = responseParseNode.GetChildNode("error");
13 | // concatenate the error code and message
14 | return $"{errorParseNode?.GetChildNode("code")?.GetStringValue()} : {errorParseNode?.GetChildNode("message")?.GetStringValue()}";
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/Microsoft.Graph.Core/Helpers/StringHelper.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | namespace Microsoft.Graph
6 | {
7 | using System.Linq;
8 |
9 | ///
10 | /// Helper class for string casing.
11 | ///
12 | public static class StringHelper
13 | {
14 | ///
15 | /// Converts the type string to title case.
16 | ///
17 | /// The type string.
18 | /// The converted string.
19 | public static string ConvertTypeToTitleCase(string typeString)
20 | {
21 | if (!string.IsNullOrEmpty(typeString))
22 | {
23 | var stringSegments = typeString.Split('.').Select(
24 | segment => string.Concat(segment.Substring(0, 1).ToUpperInvariant(), segment.Substring(1)));
25 | return string.Join(".", stringSegments);
26 | }
27 |
28 | return typeString;
29 | }
30 |
31 | ///
32 | /// Converts the type string to lower camel case.
33 | ///
34 | /// The type string.
35 | /// The converted string.
36 | public static string ConvertTypeToLowerCamelCase(string typeString)
37 | {
38 | if (!string.IsNullOrEmpty(typeString))
39 | {
40 | var stringSegments = typeString.Split('.').Select(
41 | segment => string.Concat(segment.Substring(0, 1).ToLowerInvariant(), segment.Substring(1)));
42 | return string.Join(".", stringSegments);
43 | }
44 |
45 | return typeString;
46 | }
47 |
48 | ///
49 | /// Converts the identifier string to lower camel case.
50 | ///
51 | /// The identifier string.
52 | /// The converted string.
53 | public static string ConvertIdentifierToLowerCamelCase(string identifierString)
54 | {
55 | if (!string.IsNullOrEmpty(identifierString))
56 | {
57 | return string.Concat(identifierString.Substring(0, 1).ToLowerInvariant(), identifierString.Substring(1));
58 | }
59 | return identifierString;
60 | }
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/src/Microsoft.Graph.Core/Helpers/UrlHelper.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | namespace Microsoft.Graph
6 | {
7 | using System;
8 | using System.Collections.Generic;
9 | using System.Net;
10 |
11 | ///
12 | /// Helper class for working with URLs.
13 | ///
14 | public static class UrlHelper
15 | {
16 | ///
17 | /// Parse query options from the URL.
18 | ///
19 | ///
20 | ///
21 | public static IDictionary GetQueryOptions(Uri resultUri)
22 | {
23 | string[] queryParams = null;
24 | var queryValues = new Dictionary();
25 |
26 | int fragmentIndex = resultUri.AbsoluteUri.IndexOf("#", StringComparison.Ordinal);
27 | if (fragmentIndex > 0 && fragmentIndex < resultUri.AbsoluteUri.Length + 1)
28 | {
29 | queryParams = resultUri.AbsoluteUri.Substring(fragmentIndex + 1).Split('&');
30 | }
31 | else if (fragmentIndex < 0)
32 | {
33 | if (!string.IsNullOrEmpty(resultUri.Query))
34 | {
35 | queryParams = resultUri.Query.TrimStart('?').Split('&');
36 | }
37 | }
38 |
39 | if (queryParams != null)
40 | {
41 | foreach (var param in queryParams)
42 | {
43 | if (!string.IsNullOrEmpty(param))
44 | {
45 | string[] kvp = param.Split('=');
46 | queryValues.Add(kvp[0], WebUtility.UrlDecode(kvp[1]));
47 | }
48 | }
49 | }
50 |
51 | return queryValues;
52 | }
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/src/Microsoft.Graph.Core/HttpMethods.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | namespace Microsoft.Graph
6 | {
7 | ///
8 | /// Enum used specify Http methods
9 | ///
10 | public enum HttpMethods
11 | {
12 | ///
13 | /// The GET method.
14 | ///
15 | GET,
16 |
17 | ///
18 | /// The POST method.
19 | ///
20 | POST,
21 |
22 | ///
23 | /// The PATCH method.
24 | ///
25 | PATCH,
26 |
27 | ///
28 | /// The PUT method.
29 | ///
30 | PUT,
31 |
32 | ///
33 | /// The DELETE method.
34 | ///
35 | DELETE,
36 |
37 | ///
38 | /// The HEAD method.
39 | ///
40 | HEAD,
41 |
42 | ///
43 | /// The CONNECT method.
44 | ///
45 | CONNECT,
46 |
47 | ///
48 | /// The OPTIONS method.
49 | ///
50 | OPTIONS,
51 |
52 | ///
53 | /// The TRACE method.
54 | ///
55 | TRACE
56 |
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/src/Microsoft.Graph.Core/LICENSE.txt:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2019 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 |
--------------------------------------------------------------------------------
/src/Microsoft.Graph.Core/Models/AsyncOperationStatus.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | namespace Microsoft.Graph
6 | {
7 | using System;
8 | using System.Collections.Generic;
9 | using Microsoft.Kiota.Abstractions.Serialization;
10 |
11 | ///
12 | /// The type AsyncOperationStatus.
13 | ///
14 | public partial class AsyncOperationStatus : IParsable, IAdditionalDataHolder
15 | {
16 | ///
17 | /// Gets or sets operation.
18 | ///
19 | public string Operation
20 | {
21 | get; set;
22 | }
23 |
24 | ///
25 | /// Gets or sets percentageComplete.
26 | ///
27 | public double? PercentageComplete
28 | {
29 | get; set;
30 | }
31 |
32 | ///
33 | /// Gets or sets status.
34 | ///
35 | public string Status
36 | {
37 | get; set;
38 | }
39 |
40 | ///
41 | /// Gets or sets additional data.
42 | ///
43 | public IDictionary AdditionalData { get; set; } = new Dictionary();
44 |
45 | ///
46 | /// Gets the field deserializers for the instance
47 | ///
48 | ///
49 | public IDictionary> GetFieldDeserializers()
50 | {
51 | return new Dictionary>
52 | {
53 | {"operation", (n) => { Operation = n.GetStringValue(); } },
54 | {"percentageComplete", (n) => { PercentageComplete = n.GetDoubleValue(); } },
55 | {"status", (n) => { Status = n.GetStringValue(); } },
56 | };
57 | }
58 |
59 | ///
60 | /// Serialize the instance
61 | ///
62 | /// The to serialize the instance
63 | /// Thrown when the writer is null
64 | public void Serialize(ISerializationWriter writer)
65 | {
66 | _ = writer ?? throw new ArgumentNullException(nameof(writer));
67 | writer.WriteStringValue("operation", Operation);
68 | writer.WriteDoubleValue("percentageComplete", PercentageComplete);
69 | writer.WriteStringValue("status", Status);
70 | writer.WriteAdditionalData(AdditionalData);
71 | }
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/src/Microsoft.Graph.Core/Models/BatchRequestStep.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | namespace Microsoft.Graph
6 | {
7 | using System;
8 | using System.Collections.Generic;
9 | using System.Net.Http;
10 |
11 | ///
12 | /// A single batch request step.
13 | ///
14 | public class BatchRequestStep
15 | {
16 | ///
17 | /// A unique batch request id property.
18 | ///
19 | public string RequestId
20 | {
21 | get; private set;
22 | }
23 |
24 | ///
25 | /// A http request message for an individual batch request operation.
26 | ///
27 | public HttpRequestMessage Request
28 | {
29 | get; private set;
30 | }
31 |
32 | ///
33 | /// An OPTIONAL array of batch request ids specifying the order of execution for individual batch requests.
34 | ///
35 | public List DependsOn
36 | {
37 | get; set;
38 | }
39 |
40 | ///
41 | /// Constructs a new .
42 | ///
43 | /// A unique batch request id.
44 | /// A http request message for an individual batch request operation.
45 | /// An OPTIONAL array of batch request ids specifying the order of execution for individual batch requests.
46 | public BatchRequestStep(string requestId, HttpRequestMessage httpRequestMessage, List dependsOn = null)
47 | {
48 | RequestId = (!string.IsNullOrEmpty(requestId)) ? requestId : throw new ArgumentNullException(nameof(requestId));
49 |
50 | Request = httpRequestMessage ?? throw new ArgumentNullException(nameof(httpRequestMessage));
51 |
52 | DependsOn = dependsOn;
53 | }
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/src/Microsoft.Graph.Core/Models/IDecryptableContent.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | namespace Microsoft.Graph
6 | {
7 | ///
8 | /// The IDecryptableContent interface
9 | ///
10 | public interface IDecryptableContent
11 | {
12 | ///
13 | /// The Data string
14 | ///
15 | string Data
16 | {
17 | get; set;
18 | }
19 |
20 | ///
21 | /// The DataKey string
22 | ///
23 | string DataKey
24 | {
25 | get; set;
26 | }
27 |
28 | ///
29 | /// The DataSignature string
30 | ///
31 | string DataSignature
32 | {
33 | get; set;
34 | }
35 |
36 | ///
37 | /// The EncryptionCertificateId string
38 | ///
39 | string EncryptionCertificateId
40 | {
41 | get; set;
42 | }
43 |
44 | ///
45 | /// The EncryptionCertificateThumbprint string
46 | ///
47 | string EncryptionCertificateThumbprint
48 | {
49 | get; set;
50 | }
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/src/Microsoft.Graph.Core/Models/IEncryptableSubscription.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | namespace Microsoft.Graph
6 | {
7 | ///
8 | /// The IEncryptableSubscription interface
9 | ///
10 | public interface IEncryptableSubscription
11 | {
12 | ///
13 | /// The encryption certificate
14 | ///
15 | string EncryptionCertificate
16 | {
17 | get; set;
18 | }
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/Microsoft.Graph.Core/Models/IEncryptedContentBearer.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | namespace Microsoft.Graph
6 | {
7 | ///
8 | /// The IEncryptedContentBearer interface
9 | ///
10 | public interface IEncryptedContentBearer where T : IDecryptableContent
11 | {
12 | ///
13 | /// The encrypted content
14 | ///
15 | T EncryptedContent
16 | {
17 | get; set;
18 | }
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/Microsoft.Graph.Core/Models/ITokenValidable.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | namespace Microsoft.Graph
6 | {
7 | using System.Collections.Generic;
8 |
9 | ///
10 | /// The ITokenValidable interface
11 | ///
12 | public interface ITokenValidable where T1 : IEncryptedContentBearer where T2 : IDecryptableContent
13 | {
14 | ///
15 | /// The collection of validation tokens
16 | ///
17 | List ValidationTokens
18 | {
19 | get; set;
20 | }
21 |
22 | ///
23 | /// The collection of encrypted token bearers
24 | ///
25 | List Value
26 | {
27 | get; set;
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/Microsoft.Graph.Core/Models/IUploadSession.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | namespace Microsoft.Graph
6 | {
7 | using System;
8 | using System.Collections.Generic;
9 | using Microsoft.Kiota.Abstractions.Serialization;
10 |
11 | ///
12 | /// The IUploadSession interface
13 | ///
14 | public interface IUploadSession : IParsable, IAdditionalDataHolder
15 | {
16 | ///
17 | /// Expiration date of the upload session
18 | ///
19 | DateTimeOffset? ExpirationDateTime
20 | {
21 | get; set;
22 | }
23 |
24 | ///
25 | /// The ranges yet to be uploaded to the server
26 | ///
27 | List NextExpectedRanges
28 | {
29 | get; set;
30 | }
31 |
32 | ///
33 | /// The URL for upload
34 | ///
35 | string UploadUrl
36 | {
37 | get; set;
38 | }
39 |
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/src/Microsoft.Graph.Core/Models/ReferenceRequestBody.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 |
6 | namespace Microsoft.Graph
7 | {
8 | using System.Text.Json.Serialization;
9 |
10 | ///
11 | /// The reference request body.
12 | ///
13 | public class ReferenceRequestBody
14 | {
15 | ///
16 | /// The OData.id value.
17 | ///
18 | [JsonPropertyName("@odata.id")]
19 | public string ODataId
20 | {
21 | get; set;
22 | }
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/Microsoft.Graph.Core/Models/UploadResult.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | namespace Microsoft.Graph
6 | {
7 | using System;
8 |
9 | ///
10 | /// Result that we get from uploading a slice
11 | ///
12 | ///
13 | public class UploadResult
14 | {
15 | ///
16 | /// The UploadSession containing information about the created upload session.
17 | ///
18 | public IUploadSession UploadSession;
19 |
20 | ///
21 | /// The uploaded item, once upload has completed.
22 | ///
23 | public T ItemResponse;
24 |
25 | ///
26 | /// The uploaded item location, once upload has completed.
27 | ///
28 | public Uri Location;
29 |
30 | ///
31 | /// Status of the request.
32 | ///
33 | public bool UploadSucceeded => (this.ItemResponse != null) || (this.Location != null);
34 |
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/Microsoft.Graph.Core/Models/UploadSession.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | namespace Microsoft.Graph.Core.Models
6 | {
7 | using System;
8 | using System.Collections.Generic;
9 | using System.Linq;
10 | using Microsoft.Kiota.Abstractions.Serialization;
11 |
12 | ///
13 | /// Concrete implementation of the IUploadSession interface
14 | ///
15 | internal class UploadSession : IUploadSession
16 | {
17 | ///
18 | /// Expiration date of the upload session
19 | ///
20 | public DateTimeOffset? ExpirationDateTime
21 | {
22 | get; set;
23 | }
24 |
25 | ///
26 | /// The ranges yet to be uploaded to the server
27 | ///
28 | public List NextExpectedRanges
29 | {
30 | get; set;
31 | }
32 |
33 | ///
34 | /// The URL for upload
35 | ///
36 | public string UploadUrl
37 | {
38 | get; set;
39 | }
40 |
41 | ///
42 | /// Stores additional data not described in the OpenAPI description found when deserializing. Can be used for serialization as well.
43 | ///
44 | public IDictionary AdditionalData { get; set; } = new Dictionary();
45 |
46 | ///
47 | /// The deserialization information for the current model
48 | ///
49 | public IDictionary> GetFieldDeserializers()
50 | {
51 | return new Dictionary>(StringComparer.OrdinalIgnoreCase)
52 | {
53 | {"expirationDateTime", (n) => { ExpirationDateTime = n.GetDateTimeOffsetValue(); } },
54 | {"nextExpectedRanges", (n) => { NextExpectedRanges = n.GetCollectionOfPrimitiveValues().ToList(); } },
55 | {"uploadUrl", (n) => { UploadUrl = n.GetStringValue(); } },
56 | };
57 | }
58 |
59 | ///
60 | /// Serializes information the current object
61 | /// Serialization writer to use to serialize this model
62 | ///
63 | public void Serialize(ISerializationWriter writer)
64 | {
65 | _ = writer ?? throw new ArgumentNullException(nameof(writer));
66 | writer.WriteDateTimeOffsetValue("expirationDateTime", ExpirationDateTime);
67 | writer.WriteCollectionOfPrimitiveValues("nextExpectedRanges", NextExpectedRanges);
68 | writer.WriteStringValue("uploadUrl", UploadUrl);
69 | writer.WriteAdditionalData(AdditionalData);
70 | }
71 |
72 | ///
73 | /// Creates a new instance of the appropriate class based on discriminator value
74 | /// The parse node to use to read the discriminator value and create the object
75 | ///
76 | public static UploadSession CreateFromDiscriminatorValue(IParseNode parseNode)
77 | {
78 | _ = parseNode ?? throw new ArgumentNullException(nameof(parseNode));
79 | return new UploadSession();
80 | }
81 | }
82 | }
83 |
--------------------------------------------------------------------------------
/src/Microsoft.Graph.Core/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Runtime.CompilerServices;
2 | #if DEBUG
3 | [assembly: InternalsVisibleTo("Microsoft.Graph.DotnetCore.Core.Test")]
4 | #endif
5 |
--------------------------------------------------------------------------------
/src/Microsoft.Graph.Core/Requests/BaseGraphRequestAdapter.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | namespace Microsoft.Graph
6 | {
7 | using System.Net.Http;
8 | using Microsoft.Kiota.Abstractions;
9 | using Microsoft.Kiota.Abstractions.Authentication;
10 | using Microsoft.Kiota.Abstractions.Serialization;
11 | using Microsoft.Kiota.Http.HttpClientLibrary;
12 |
13 | ///
14 | /// The instance for use with microsoft graph
15 | ///
16 | public class BaseGraphRequestAdapter : HttpClientRequestAdapter
17 | {
18 | ///
19 | /// The public constructor for
20 | ///
21 | /// The authentication provider.
22 | /// The options for the graph client
23 | /// The parse node factory.
24 | /// The serialization writer factory.
25 | /// The native HTTP client.
26 | public BaseGraphRequestAdapter(IAuthenticationProvider authenticationProvider, GraphClientOptions graphClientOptions = null, IParseNodeFactory parseNodeFactory = null, ISerializationWriterFactory serializationWriterFactory = null, HttpClient httpClient = null)
27 | : base(authenticationProvider, parseNodeFactory ?? ParseNodeFactoryRegistry.DefaultInstance, serializationWriterFactory ?? SerializationWriterFactoryRegistry.DefaultInstance, httpClient ?? GraphClientFactory.Create(graphClientOptions))
28 | {
29 | }
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/Microsoft.Graph.Core/Requests/Content/KeyedBatchResponseContent.cs:
--------------------------------------------------------------------------------
1 | namespace Microsoft.Graph
2 | {
3 | using System.Collections.Generic;
4 |
5 | internal class KeyedBatchResponseContent
6 | {
7 | internal readonly HashSet Keys;
8 | internal readonly BatchResponseContent Response;
9 |
10 | public KeyedBatchResponseContent(HashSet keys, BatchResponseContent response)
11 | {
12 | Keys = keys;
13 | Response = response;
14 | }
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/Microsoft.Graph.Core/Requests/FeatureFlag.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | namespace Microsoft.Graph
6 | {
7 | using System;
8 | ///
9 | /// Feature Flags
10 | ///
11 | [Flags]
12 | public enum FeatureFlag
13 | {
14 | /// None set
15 | None = 0x00000000,
16 | /// Redirect Handler
17 | RedirectHandler = 0x00000001,
18 | /// Retry Handler
19 | RetryHandler = 0x00000002,
20 | /// Auth Handler
21 | AuthHandler = 0x00000004,
22 | /// Default Handler
23 | DefaultHttpProvider = 0x00000008,
24 | /// Logging Handler
25 | LoggingHandler = 0x00000010,
26 | /// Service Discovery Handler
27 | ServiceDiscoveryHandler = 0x00000020,
28 | /// Compression Handler
29 | CompressionHandler = 0x00000040,
30 | /// Connection Pool Manager
31 | ConnectionPoolManager = 0x00000080,
32 | /// Long Running Operation Handler
33 | LongRunningOperationHandler = 0x00000100,
34 | /// Batch Request Content Used
35 | BatchRequestContext = 0x00000200,
36 | /// Page Iterator task Used
37 | PageIteratorTask = 0x00000400,
38 | /// File Upload task Used
39 | FileUploadTask = 0x00000800
40 |
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/src/Microsoft.Graph.Core/Requests/GraphClientOptions.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | namespace Microsoft.Graph
6 | {
7 | ///
8 | /// The options for setting up a given graph client
9 | ///
10 | public class GraphClientOptions
11 | {
12 | ///
13 | /// The target version of the api endpoint we are targeting (v1 or beta)
14 | ///
15 | public string GraphServiceTargetVersion
16 | {
17 | get; set;
18 | }
19 |
20 | ///
21 | /// The version of the service library in use. Should be in the format `x.x.x` (Semantic version)
22 | ///
23 | public string GraphServiceLibraryClientVersion
24 | {
25 | get; set;
26 | }
27 |
28 | ///
29 | /// The version of the core library in use. Should be in the format `x.x.x` (Semantic version).
30 | ///
31 | public string GraphCoreClientVersion
32 | {
33 | get; set;
34 | }
35 |
36 | ///
37 | /// The product prefix to use in setting the telemetry headers.
38 | /// Will default to `graph-dotnet` if not set.
39 | ///
40 | public string GraphProductPrefix
41 | {
42 | get; set;
43 | }
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/src/Microsoft.Graph.Core/Requests/GraphRequestContext.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | namespace Microsoft.Graph
6 | {
7 | using System.Threading;
8 |
9 | ///
10 | /// The graph request context class
11 | ///
12 | public class GraphRequestContext
13 | {
14 | ///
15 | /// A ClientRequestId property
16 | ///
17 | public string ClientRequestId
18 | {
19 | get; set;
20 | }
21 |
22 | ///
23 | /// A CancellationToken property
24 | ///
25 | public CancellationToken CancellationToken
26 | {
27 | get; set;
28 | }
29 |
30 | ///
31 | /// A FeatureUsage property
32 | ///
33 | public FeatureFlag FeatureUsage
34 | {
35 | get; set;
36 | }
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/Microsoft.Graph.Core/Requests/GraphResponse.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | namespace Microsoft.Graph
6 | {
7 | using System;
8 | using System.Net;
9 | using System.Net.Http;
10 | using System.Net.Http.Headers;
11 | using Microsoft.Kiota.Abstractions;
12 | ///
13 | /// The GraphResponse Object
14 | ///
15 | public class GraphResponse : IDisposable
16 | {
17 | ///
18 | /// The GraphResponse Constructor
19 | ///
20 | /// The Request made for the response
21 | /// The response
22 | public GraphResponse(RequestInformation requestInformation, HttpResponseMessage httpResponseMessage)
23 | {
24 | this.httpResponseMessage = httpResponseMessage ??
25 | throw new ArgumentException(string.Format(ErrorConstants.Messages.NullParameter, nameof(httpResponseMessage)));
26 | this.RequestInformation = requestInformation ??
27 | throw new ArgumentException(string.Format(ErrorConstants.Messages.NullParameter, nameof(requestInformation)));
28 | }
29 |
30 | private readonly HttpResponseMessage httpResponseMessage;
31 |
32 | ///
33 | /// The Response Status code
34 | ///
35 | public HttpStatusCode StatusCode => httpResponseMessage.StatusCode;
36 |
37 | ///
38 | /// The Response Content
39 | ///
40 | public HttpContent Content => httpResponseMessage.Content;
41 |
42 | ///
43 | /// The Response Headers
44 | ///
45 | public HttpResponseHeaders HttpHeaders => httpResponseMessage.Headers;
46 |
47 | ///
48 | /// The reference to the original request
49 | ///
50 | public RequestInformation RequestInformation;
51 |
52 | ///
53 | /// Get the native Response Message
54 | ///
55 | ///
56 | public HttpResponseMessage ToHttpResponseMessage()
57 | {
58 | return httpResponseMessage;
59 | }
60 |
61 | ///
62 | /// Cleanup
63 | ///
64 | public void Dispose()
65 | {
66 | httpResponseMessage?.Dispose();
67 | }
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/src/Microsoft.Graph.Core/Requests/GraphResponse{T}.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | namespace Microsoft.Graph
6 | {
7 | using System.Collections.Generic;
8 | using System.Net.Http;
9 | using System.Threading.Tasks;
10 | using Microsoft.Kiota.Abstractions;
11 | using Microsoft.Kiota.Abstractions.Serialization;
12 |
13 | ///
14 | /// The GraphResponse Object
15 | ///
16 | public class GraphResponse : GraphResponse
17 | {
18 | ///
19 | /// The GraphResponse Constructor
20 | ///
21 | /// The Request made for the response
22 | /// The response
23 | public GraphResponse(RequestInformation requestInformation, HttpResponseMessage httpResponseMessage)
24 | : base(requestInformation, httpResponseMessage)
25 | {
26 | }
27 |
28 | ///
29 | /// Gets the deserialized object
30 | ///
31 | /// The response handler to use for the reponse
32 | /// The errorMappings to use in the event of a non sucess request
33 | public async Task GetResponseObjectAsync(IResponseHandler responseHandler, Dictionary> errorMappings = null)
34 | {
35 | return await responseHandler.HandleResponseAsync(this.ToHttpResponseMessage(), errorMappings).ConfigureAwait(false);
36 | }
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/Microsoft.Graph.Core/Requests/IAsyncMonitor.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | namespace Microsoft.Graph
6 | {
7 | using System;
8 | using System.Threading;
9 | using System.Threading.Tasks;
10 |
11 | ///
12 | /// Monitor for async operations to the Graph service on the client.
13 | ///
14 | /// The object type to return.
15 | public interface IAsyncMonitor
16 | {
17 | ///
18 | /// Poll to check for completion of an async call to the Graph service.
19 | ///
20 | /// The progress status.
21 | /// The cancellation token.
22 | /// The operation task.
23 | Task PollForOperationCompletionAsync(IProgress progress, CancellationToken cancellationToken);
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/Microsoft.Graph.Core/Requests/IBaseClient.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | namespace Microsoft.Graph
6 | {
7 | using Microsoft.Graph.Core.Requests;
8 | using Microsoft.Kiota.Abstractions;
9 |
10 | ///
11 | /// A default client interface.
12 | ///
13 | public interface IBaseClient
14 | {
15 | ///
16 | /// Gets the for sending requests.
17 | ///
18 | IRequestAdapter RequestAdapter
19 | {
20 | get; set;
21 | }
22 |
23 | ///
24 | /// Gets the for building batch Requests
25 | ///
26 | public BatchRequestBuilder Batch
27 | {
28 | get;
29 | }
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/Microsoft.Graph.Core/Requests/Upload/UploadSessionRequestBuilder.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | namespace Microsoft.Graph
6 | {
7 | using System.Net.Http;
8 | using System.Threading;
9 | using System.Threading.Tasks;
10 | using Microsoft.Graph.Core.Models;
11 | using Microsoft.Kiota.Abstractions;
12 |
13 | internal class UploadSessionRequestBuilder
14 | {
15 | private readonly UploadResponseHandler responseHandler;
16 | private readonly IRequestAdapter requestAdapter;
17 | private readonly string urlTemplate;
18 |
19 | ///
20 | /// Create a new UploadSessionRequest
21 | ///
22 | /// The IUploadSession to use in the request.
23 | /// The for handling requests.
24 | public UploadSessionRequestBuilder(IUploadSession uploadSession, IRequestAdapter requestAdapter)
25 | {
26 | this.responseHandler = new UploadResponseHandler();
27 | this.requestAdapter = requestAdapter;
28 | this.urlTemplate = uploadSession.UploadUrl;
29 | }
30 |
31 | ///
32 | /// Deletes the specified Session
33 | ///
34 | /// to use for cancelling requests
35 | /// The task to await.
36 | public async Task DeleteAsync(CancellationToken cancellationToken = default)
37 | {
38 | var requestInformation = this.ToDeleteRequestInformation();
39 | await this.requestAdapter.SendNoContentAsync(requestInformation, cancellationToken: cancellationToken);
40 | }
41 |
42 | ///
43 | /// Creates instance for a DELETE request
44 | ///
45 | /// The instance.
46 | public RequestInformation ToDeleteRequestInformation()
47 | {
48 | var requestInfo = new RequestInformation
49 | {
50 | HttpMethod = Method.DELETE,
51 | UrlTemplate = urlTemplate,
52 | };
53 | return requestInfo;
54 | }
55 |
56 | ///
57 | /// Gets the specified UploadSession.
58 | ///
59 | /// to use for cancelling requests
60 | /// The Item.
61 | public async Task GetAsync(CancellationToken cancellationToken = default)
62 | {
63 | var requestInformation = this.ToGetRequestInformation();
64 | var nativeResponseHandler = new NativeResponseHandler();
65 | requestInformation.SetResponseHandler(nativeResponseHandler);
66 | await this.requestAdapter.SendNoContentAsync(requestInformation, cancellationToken: cancellationToken).ConfigureAwait(false);
67 | var uploadResult = await this.responseHandler.HandleResponseAsync(nativeResponseHandler.Value as HttpResponseMessage).ConfigureAwait(false);
68 | return uploadResult.UploadSession;
69 | }
70 |
71 | ///
72 | /// Creates instance for a GET request
73 | ///
74 | /// The instance.
75 | public RequestInformation ToGetRequestInformation()
76 | {
77 | var requestInfo = new RequestInformation
78 | {
79 | HttpMethod = Method.GET,
80 | UrlTemplate = urlTemplate,
81 | };
82 | return requestInfo;
83 | }
84 | }
85 | }
86 |
--------------------------------------------------------------------------------
/src/Microsoft.Graph.Core/global.json:
--------------------------------------------------------------------------------
1 | {
2 | "sdk": {
3 | "version": "6.0.417", /* https://github.com/dotnet/maui/wiki/.NET-7-and-.NET-MAUI */
4 | "rollForward": "major"
5 | }
6 | }
--------------------------------------------------------------------------------
/tests/Microsoft.Graph.DotnetCore.Core.Test/Exceptions/ServiceExceptionTests.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | namespace Microsoft.Graph.DotnetCore.Core.Test.Exceptions
6 | {
7 | using System;
8 | using System.Text.Json;
9 | using Xunit;
10 | public class ServiceExceptionTests
11 | {
12 | [Fact]
13 | public void IsMatch_ErrorCodeRequired()
14 | {
15 | var serviceException = new ServiceException("errorCode");
16 |
17 | Assert.Throws(() => serviceException.IsMatch(null));
18 | }
19 |
20 | [Fact]
21 | public void IsMatch_NestedErrors()
22 | {
23 | var responsebody = JsonSerializer.Serialize(new
24 | {
25 | Code = "errorCode",
26 | InnerError = new
27 | {
28 | Code = "differentErrorCode",
29 | InnerError = new
30 | {
31 | Code = "errorCodeMatch",
32 | }
33 | }
34 | });
35 | var serviceException = new ServiceException("errorCode", null, 0, responsebody);
36 |
37 | Assert.True(serviceException.IsMatch("errorcodematch"));
38 | }
39 |
40 | [Fact]
41 | public void IsMatch_NoMatch()
42 | {
43 | var responsebody = JsonSerializer.Serialize(new
44 | {
45 | Code = "errorCode",
46 | InnerError = new
47 | {
48 | Code = "differentErrorCode",
49 | InnerError = new
50 | {
51 | Code = "errorCodeMatch",
52 | }
53 | }
54 | });
55 | var serviceException = new ServiceException("errorCode", null, 0, responsebody);
56 |
57 | Assert.False(serviceException.IsMatch("noMatch"));
58 | }
59 |
60 | [Fact(Skip = "Changed the signature of ServiceException.ToString() in ccecc486cce5769313c0cb59ab56142d1b43ce5a")]
61 | public void ToString_ErrorNull()
62 | {
63 | var serviceException = new ServiceException(null);
64 |
65 | Assert.Null(serviceException.ToString());
66 | }
67 |
68 | [Fact]
69 | public void IsMatch_ThrowsNoException()
70 | {
71 | var serviceException = new ServiceException(null);
72 |
73 | bool result = serviceException.IsMatch("Any Error");
74 |
75 | Assert.False(result);
76 | }
77 | }
78 | }
79 |
--------------------------------------------------------------------------------
/tests/Microsoft.Graph.DotnetCore.Core.Test/Extensions/HttpClientExtensionsTests.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | namespace Microsoft.Graph.DotnetCore.Core.Test.Extensions
6 | {
7 | using System;
8 | using System.Linq;
9 | using System.Net.Http;
10 | using Xunit;
11 | public class HttpClientExtensionsTests
12 | {
13 | [Fact]
14 | public void SetFeatureFlag_should_add_new_flag_to_featureflag_header()
15 | {
16 | HttpClient client = new HttpClient();
17 | client.SetFeatureFlag(FeatureFlag.LongRunningOperationHandler);
18 |
19 | string expectedHeaderValue = Enum.Format(typeof(FeatureFlag), FeatureFlag.LongRunningOperationHandler, "x");
20 |
21 | Assert.True(client.DefaultRequestHeaders.Contains(CoreConstants.Headers.FeatureFlag));
22 | Assert.True(client.DefaultRequestHeaders.GetValues(CoreConstants.Headers.FeatureFlag).Count().Equals(1));
23 | Assert.Equal(client.DefaultRequestHeaders.GetValues(CoreConstants.Headers.FeatureFlag).First(), expectedHeaderValue);
24 | }
25 |
26 | [Fact]
27 | public void SetFeatureFlag_should_add_flag_to_existing_featureflag_header_values()
28 | {
29 | FeatureFlag flags = FeatureFlag.AuthHandler | FeatureFlag.CompressionHandler | FeatureFlag.RetryHandler | FeatureFlag.RedirectHandler;
30 |
31 | HttpClient client = new HttpClient();
32 | client.DefaultRequestHeaders.Add(CoreConstants.Headers.FeatureFlag, Enum.Format(typeof(FeatureFlag), FeatureFlag.DefaultHttpProvider, "x"));
33 | client.SetFeatureFlag(flags);
34 |
35 | // 0000004F
36 | string expectedHeaderValue = Enum.Format(typeof(FeatureFlag), flags |= FeatureFlag.DefaultHttpProvider, "x");
37 |
38 | Assert.True(client.DefaultRequestHeaders.Contains(CoreConstants.Headers.FeatureFlag));
39 | Assert.True(client.DefaultRequestHeaders.GetValues(CoreConstants.Headers.FeatureFlag).Count().Equals(1));
40 | Assert.Equal(client.DefaultRequestHeaders.GetValues(CoreConstants.Headers.FeatureFlag).First(), expectedHeaderValue);
41 | }
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/tests/Microsoft.Graph.DotnetCore.Core.Test/Helpers/ReadOnlySubStreamTests.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | using System.Collections.Generic;
6 | using System.IO;
7 | using Xunit;
8 |
9 | namespace Microsoft.Graph.DotnetCore.Core.Test.Helpers
10 | {
11 | public class ReadOnlySubStreamTests
12 | {
13 | private readonly Stream _baseStream;
14 | private readonly List _segments = new List()
15 | {
16 | "1234567890","0987654321","1357924680","2468013579"
17 | };
18 |
19 | public ReadOnlySubStreamTests()
20 | {
21 | _baseStream = new MemoryStream();
22 | var writer = new StreamWriter(_baseStream);
23 | foreach (var segment in _segments)
24 | {
25 | writer.Write(segment);
26 | }
27 | writer.Flush();
28 | _baseStream.Position = 0;
29 | }
30 |
31 | [Fact]
32 | public void SubstreamsAreReadableOnce()
33 | {
34 | long startIndex = 0;
35 | foreach (var segment in _segments)
36 | {
37 | using var substream = new ReadOnlySubStream(_baseStream, startIndex, 10);
38 | startIndex += substream.Length;
39 | using var streamReader = new StreamReader(substream);
40 | var readBytes = streamReader.ReadToEnd();
41 | Assert.Equal(segment, readBytes);
42 | }
43 | }
44 |
45 | [Fact]
46 | public void SubstreamsAreReadableMultipleTimes()
47 | {
48 | long startIndex = 0;
49 | foreach (var segment in _segments)
50 | {
51 | using var substream = new ReadOnlySubStream(_baseStream, startIndex, 10);
52 | startIndex += substream.Length;
53 | using var streamReader = new StreamReader(substream);
54 |
55 | var readBytes = streamReader.ReadToEnd();
56 | Assert.Equal(segment, readBytes);
57 |
58 | // reset stream and read again
59 | substream.Position = 0;
60 | readBytes = streamReader.ReadToEnd();
61 | Assert.Equal(segment, readBytes);
62 | }
63 | }
64 |
65 | [Fact]
66 | public void SubstreamsAreReadableFromDifferentPositionsTimes()
67 | {
68 | long startIndex = 0;
69 | foreach (var segment in _segments)
70 | {
71 | using var substream = new ReadOnlySubStream(_baseStream, startIndex, 10);
72 | startIndex += substream.Length;
73 | using var streamReader = new StreamReader(substream);
74 |
75 | var readBytes = streamReader.ReadToEnd();
76 | Assert.Equal(segment, readBytes);
77 |
78 | // reset stream to middle and read again
79 | substream.Seek(5, SeekOrigin.Begin);
80 | readBytes = streamReader.ReadToEnd();
81 | Assert.Equal(segment[5..], readBytes);
82 |
83 | // reset stream and read again
84 | substream.Position = 0;
85 | readBytes = streamReader.ReadToEnd();
86 | Assert.Equal(segment, readBytes);
87 | }
88 | }
89 | }
90 | }
91 |
--------------------------------------------------------------------------------
/tests/Microsoft.Graph.DotnetCore.Core.Test/Helpers/StringHelperTests.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | namespace Microsoft.Graph.DotnetCore.Core.Test.Helpers
6 | {
7 | using Xunit;
8 | public class StringHelperTests
9 | {
10 | [Fact]
11 | public void ConvertTypeToLowerCamelCase()
12 | {
13 | var expectedTypeString = "microsoft.graph.type";
14 |
15 | var returnedTypeString = StringHelper.ConvertTypeToLowerCamelCase("Microsoft.Graph.Type");
16 |
17 | Assert.Equal(expectedTypeString, returnedTypeString);
18 | }
19 |
20 | [Fact]
21 | public void ConvertTypeToLowerCamelCase_NoNamespace()
22 | {
23 | var expectedTypeString = "newType";
24 |
25 | var returnedTypeString = StringHelper.ConvertTypeToLowerCamelCase("NewType");
26 |
27 | Assert.Equal(expectedTypeString, returnedTypeString);
28 | }
29 |
30 | [Fact]
31 | public void ConvertTypeToLowerCamelCase_NullTypeString()
32 | {
33 | var returnedTypeString = StringHelper.ConvertTypeToLowerCamelCase(null);
34 |
35 | Assert.Null(returnedTypeString);
36 | }
37 |
38 | [Fact]
39 | public void ConvertTypeToTitleCase()
40 | {
41 | var expectedTypeString = "Microsoft.Graph.Type";
42 |
43 | var returnedTypeString = StringHelper.ConvertTypeToTitleCase("microsoft.graph.type");
44 |
45 | Assert.Equal(expectedTypeString, returnedTypeString);
46 | }
47 |
48 | [Fact]
49 | public void ConvertTypeToTitleCase_NoNamespace()
50 | {
51 | var expectedTypeString = "NewType";
52 |
53 | var returnedTypeString = StringHelper.ConvertTypeToTitleCase("newType");
54 |
55 | Assert.Equal(expectedTypeString, returnedTypeString);
56 | }
57 |
58 | [Fact]
59 | public void ConvertTypeToTitleCase_NullTypeString()
60 | {
61 | var returnedTypeString = StringHelper.ConvertTypeToTitleCase(null);
62 |
63 | Assert.Null(returnedTypeString);
64 | }
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/tests/Microsoft.Graph.DotnetCore.Core.Test/Helpers/UrlHelperTests.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | namespace Microsoft.Graph.DotnetCore.Core.Test.Helpers
6 | {
7 | using System;
8 | using Xunit;
9 | public class UrlHelperTests
10 | {
11 | [Fact]
12 | public void GetQueryOptions_EmptyFragment()
13 | {
14 | var uri = new Uri("https://localhost#");
15 |
16 | var queryValues = UrlHelper.GetQueryOptions(uri);
17 |
18 | Assert.Empty(queryValues);
19 | }
20 |
21 | [Fact]
22 | public void GetQueryOptions_EmptyQueryString()
23 | {
24 | var uri = new Uri("https://localhost?");
25 |
26 | var queryValues = UrlHelper.GetQueryOptions(uri);
27 |
28 | Assert.Empty(queryValues);
29 | }
30 |
31 | [Fact]
32 | public void GetQueryOptions_NoQueryString()
33 | {
34 | var uri = new Uri("https://localhost");
35 |
36 | var queryValues = UrlHelper.GetQueryOptions(uri);
37 |
38 | Assert.Empty(queryValues);
39 | }
40 |
41 | [Fact]
42 | public void GetQueryOptions_MultipleFragments()
43 | {
44 | var uri = new Uri("https://localhost#key=value&key2=value%202");
45 |
46 | var queryValues = UrlHelper.GetQueryOptions(uri);
47 |
48 | Assert.Equal(2, queryValues.Count);
49 | Assert.Equal("value", queryValues["key"]);
50 | Assert.Equal("value 2", queryValues["key2"]);
51 | }
52 |
53 | [Fact]
54 | public void GetQueryOptions_SingleFragment()
55 | {
56 | var uri = new Uri("https://localhost#key=value");
57 |
58 | var queryValues = UrlHelper.GetQueryOptions(uri);
59 |
60 | Assert.Single(queryValues);
61 | Assert.Equal("value", queryValues["key"]);
62 | }
63 |
64 | [Fact]
65 | public void GetQueryOptions_MultipleQueryOptions()
66 | {
67 | var uri = new Uri("https://localhost?key=value&key2=value%202");
68 |
69 | var queryValues = UrlHelper.GetQueryOptions(uri);
70 |
71 | Assert.Equal(2, queryValues.Count);
72 | Assert.Equal("value 2", queryValues["key2"]);
73 | }
74 |
75 | [Fact]
76 | public void GetQueryOptions_SingleQueryOption()
77 | {
78 | var uri = new Uri("https://localhost?key=value");
79 |
80 | var queryValues = UrlHelper.GetQueryOptions(uri);
81 |
82 | Assert.Single(queryValues);
83 | Assert.Equal("value", queryValues["key"]);
84 | }
85 |
86 | [Fact]
87 | public void GetQueryOptions_TrailingAmpersand()
88 | {
89 | var uri = new Uri("https://localhost?key=value&");
90 |
91 | var queryValues = UrlHelper.GetQueryOptions(uri);
92 |
93 | Assert.Single(queryValues);
94 | Assert.Equal("value", queryValues["key"]);
95 | }
96 | }
97 | }
98 |
--------------------------------------------------------------------------------
/tests/Microsoft.Graph.DotnetCore.Core.Test/Microsoft.Graph.DotnetCore.Core.Test.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | net6.0
4 | false
5 | false
6 | false
7 | latest
8 |
9 |
10 |
11 | PreserveNewest
12 |
13 |
14 | PreserveNewest
15 |
16 |
17 |
18 |
19 | all
20 |
21 |
22 | all
23 | runtime; build; native; contentfiles; analyzers; buildtransitive
24 |
25 |
26 |
27 |
28 |
29 | runtime; build; native; contentfiles; analyzers; buildtransitive
30 | all
31 |
32 |
33 | runtime; build; native; contentfiles; analyzers; buildtransitive
34 | all
35 |
36 |
37 |
38 | runtime; build; native; contentfiles; analyzers; buildtransitive
39 | all
40 |
41 |
42 |
43 |
44 |
45 |
46 |
--------------------------------------------------------------------------------
/tests/Microsoft.Graph.DotnetCore.Core.Test/Mocks/BaseClient.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | namespace Microsoft.Graph.DotnetCore.Core.Test.Mocks
6 | {
7 | using Microsoft.Graph.Core.Requests;
8 | using Microsoft.Kiota.Abstractions;
9 | using Microsoft.Kiota.Abstractions.Authentication;
10 |
11 | ///
12 | /// A default client implementation.
13 | ///
14 | internal class BaseClient : IBaseClient
15 | {
16 | ///
17 | /// Constructs a new .
18 | ///
19 | /// The custom to be used for making requests
20 | internal BaseClient(IRequestAdapter requestAdapter)
21 | {
22 | this.RequestAdapter = requestAdapter;
23 | }
24 |
25 | ///
26 | /// Constructs a new .
27 | ///
28 | /// The base service URL. For example, "https://graph.microsoft.com/v1.0."
29 | /// The for authenticating request messages.
30 | internal BaseClient(
31 | string baseUrl,
32 | IAuthenticationProvider authenticationProvider
33 | ) : this(new BaseGraphRequestAdapter(authenticationProvider) { BaseUrl = baseUrl })
34 | {
35 | }
36 |
37 | ///
38 | /// Gets the for sending requests.
39 | ///
40 | public IRequestAdapter RequestAdapter
41 | {
42 | get; set;
43 | }
44 |
45 | ///
46 | /// Gets the for building batch Requests
47 | ///
48 | public BatchRequestBuilder Batch
49 | {
50 | get
51 | {
52 | return new BatchRequestBuilder(this.RequestAdapter);
53 | }
54 | }
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/tests/Microsoft.Graph.DotnetCore.Core.Test/Mocks/ExceptionHttpMessageHandler.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | namespace Microsoft.Graph.DotnetCore.Core.Test.Mocks
6 | {
7 | using System;
8 | using System.Net.Http;
9 | using System.Threading;
10 | using System.Threading.Tasks;
11 | public class ExceptionHttpMessageHandler : HttpMessageHandler
12 | {
13 | private Exception exceptionToThrow;
14 |
15 | public ExceptionHttpMessageHandler(Exception exceptionToThrow)
16 | {
17 | this.exceptionToThrow = exceptionToThrow;
18 | }
19 |
20 | protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
21 | {
22 | throw exceptionToThrow;
23 | }
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/tests/Microsoft.Graph.DotnetCore.Core.Test/Mocks/MockAccessTokenProvider.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | using System;
6 | using System.Collections.Generic;
7 | using System.Threading;
8 | using System.Threading.Tasks;
9 | using Microsoft.Kiota.Abstractions.Authentication;
10 | using Moq;
11 |
12 | namespace Microsoft.Graph.DotnetCore.Core.Test.Mocks
13 | {
14 | public class MockAccessTokenProvider : Mock
15 | {
16 | public MockAccessTokenProvider(string accessToken = null) : base(MockBehavior.Strict)
17 | {
18 | this.Setup(x => x.GetAuthorizationTokenAsync(
19 | It.IsAny(),
20 | It.IsAny>(),
21 | It.IsAny()
22 | )).Returns(Task.FromResult(accessToken));
23 |
24 | this.Setup(x => x.AllowedHostsValidator).Returns(
25 | new AllowedHostsValidator(new List { "graph.microsoft.com" })
26 | );
27 | }
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/tests/Microsoft.Graph.DotnetCore.Core.Test/Mocks/MockAuthenticationProvider.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | namespace Microsoft.Graph.DotnetCore.Core.Test.Mocks
6 | {
7 | using System.Collections.Generic;
8 | using System.Threading;
9 | using System.Threading.Tasks;
10 | using Microsoft.Kiota.Abstractions;
11 | using Microsoft.Kiota.Abstractions.Authentication;
12 | using Moq;
13 |
14 | public class MockAuthenticationProvider : Mock
15 | {
16 | public MockAuthenticationProvider(string accessToken = null)
17 | : base(MockBehavior.Strict)
18 | {
19 | this.Setup(
20 | provider => provider.AuthenticateRequestAsync(It.IsAny(), It.IsAny>(), It.IsAny()))
21 | .Callback, CancellationToken>((r, d, c) => r.Headers.Add(CoreConstants.Headers.Bearer, accessToken ?? "Default-Token"))
22 | .Returns(Task.FromResult(0));
23 | }
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/tests/Microsoft.Graph.DotnetCore.Core.Test/Mocks/MockProgress.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | namespace Microsoft.Graph.DotnetCore.Core.Test.Mocks
6 | {
7 | using System;
8 | using Moq;
9 | public class MockProgress : Mock>
10 | {
11 | public MockProgress()
12 | : base(MockBehavior.Strict)
13 | {
14 | this.Setup(mockProgress => mockProgress.Report(It.IsAny()));
15 | }
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/tests/Microsoft.Graph.DotnetCore.Core.Test/Mocks/MockRedirectHandler.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | namespace Microsoft.Graph.DotnetCore.Core.Test.Mocks
6 | {
7 | using System.Net.Http;
8 | using System.Threading;
9 | using System.Threading.Tasks;
10 | public class MockRedirectHandler : HttpMessageHandler
11 | {
12 | private HttpResponseMessage _response1
13 | {
14 | get; set;
15 | }
16 | private HttpResponseMessage _response2
17 | {
18 | get; set;
19 | }
20 |
21 | private bool _response1Sent = false;
22 |
23 | protected async override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
24 | {
25 | if (!_response1Sent)
26 | {
27 | _response1Sent = true;
28 | _response1.RequestMessage = request;
29 | return await Task.FromResult(_response1);
30 | }
31 | else
32 | {
33 | _response1Sent = false;
34 | _response2.RequestMessage = request;
35 | return await Task.FromResult(_response2);
36 | }
37 | }
38 |
39 | public void SetHttpResponse(HttpResponseMessage response1, HttpResponseMessage response2 = null)
40 | {
41 | this._response1Sent = false;
42 | this._response1 = response1;
43 | this._response2 = response2;
44 | }
45 |
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/tests/Microsoft.Graph.DotnetCore.Core.Test/Mocks/MockTokenCredential.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 |
6 |
7 | namespace Microsoft.Graph.DotnetCore.Core.Test.Mocks
8 | {
9 | using System;
10 | using System.Threading;
11 | using System.Threading.Tasks;
12 | using Azure.Core;
13 | using Moq;
14 |
15 | public class MockTokenCredential : Mock
16 | {
17 | public MockTokenCredential()
18 | : base(MockBehavior.Strict)
19 | {
20 | this.Setup(tokenCredential => tokenCredential.GetTokenAsync(It.IsAny(), CancellationToken.None))
21 | .Returns(new ValueTask(new AccessToken("mockToken", DateTimeOffset.UtcNow.AddMinutes(10))));
22 | }
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/tests/Microsoft.Graph.DotnetCore.Core.Test/Mocks/MockUploadSessionWithoutInterface.cs:
--------------------------------------------------------------------------------
1 | namespace Microsoft.Graph.DotnetCore.Core.Test.Mocks
2 | {
3 | using System;
4 | using System.Collections.Generic;
5 | using System.Linq;
6 | using Microsoft.Kiota.Abstractions.Serialization;
7 |
8 | ///
9 | /// Concrete implementation of the IUploadSession interface
10 | ///
11 | internal class MockUploadSessionWithoutUploadSessionInterface : IParsable, IAdditionalDataHolder
12 | {
13 | ///
14 | /// Expiration date of the upload session
15 | ///
16 | public DateTimeOffset? ExpirationDateTime
17 | {
18 | get; set;
19 | }
20 |
21 | ///
22 | /// The ranges yet to be uploaded to the server
23 | ///
24 | public List NextExpectedRanges
25 | {
26 | get; set;
27 | }
28 |
29 | ///
30 | /// The URL for upload
31 | ///
32 | public string UploadUrl
33 | {
34 | get; set;
35 | }
36 |
37 | ///
38 | /// Stores additional data not described in the OpenAPI description found when deserializing. Can be used for serialization as well.
39 | ///
40 | public IDictionary AdditionalData { get; set; } = new Dictionary();
41 |
42 | ///
43 | /// The deserialization information for the current model
44 | ///
45 | public IDictionary> GetFieldDeserializers()
46 | {
47 | return new Dictionary>(StringComparer.OrdinalIgnoreCase)
48 | {
49 | {"expirationDateTime", (n) => { ExpirationDateTime = n.GetDateTimeOffsetValue(); } },
50 | {"nextExpectedRanges", (n) => { NextExpectedRanges = n.GetCollectionOfPrimitiveValues().ToList(); } },
51 | {"uploadUrl", (n) => { UploadUrl = n.GetStringValue(); } },
52 | };
53 | }
54 |
55 | ///
56 | /// Serializes information the current object
57 | /// Serialization writer to use to serialize this model
58 | ///
59 | public void Serialize(ISerializationWriter writer)
60 | {
61 | _ = writer ?? throw new ArgumentNullException(nameof(writer));
62 | writer.WriteDateTimeOffsetValue("expirationDateTime", ExpirationDateTime);
63 | writer.WriteCollectionOfPrimitiveValues("nextExpectedRanges", NextExpectedRanges);
64 | writer.WriteStringValue("uploadUrl", UploadUrl);
65 | writer.WriteAdditionalData(AdditionalData);
66 | }
67 |
68 | ///
69 | /// Creates a new instance of the appropriate class based on discriminator value
70 | /// The parse node to use to read the discriminator value and create the object
71 | ///
72 | public static MockUploadSessionWithoutUploadSessionInterface CreateFromDiscriminatorValue(IParseNode parseNode)
73 | {
74 | _ = parseNode ?? throw new ArgumentNullException(nameof(parseNode));
75 | return new MockUploadSessionWithoutUploadSessionInterface();
76 | }
77 | }
78 | }
79 |
--------------------------------------------------------------------------------
/tests/Microsoft.Graph.DotnetCore.Core.Test/Mocks/TestHttpMessageHandler.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | namespace Microsoft.Graph.DotnetCore.Core.Test.Mocks
6 | {
7 | using System;
8 | using System.Collections.Generic;
9 | using System.Net.Http;
10 | using System.Threading;
11 | using System.Threading.Tasks;
12 | public class TestHttpMessageHandler : HttpMessageHandler
13 | {
14 | private Action requestMessageDelegate;
15 | private Dictionary responseMessages;
16 |
17 | public TestHttpMessageHandler(Action requestMessage = null)
18 | {
19 | this.requestMessageDelegate = requestMessage ?? DefaultRequestHandler;
20 | this.responseMessages = new Dictionary();
21 | }
22 |
23 | public void AddResponseMapping(string requestUrl, HttpResponseMessage responseMessage)
24 | {
25 | this.responseMessages.Add(requestUrl, responseMessage);
26 | }
27 |
28 | protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
29 | {
30 | HttpResponseMessage responseMessage;
31 |
32 | requestMessageDelegate(request);
33 |
34 | if (this.responseMessages.TryGetValue(request.RequestUri.ToString(), out responseMessage))
35 | {
36 | responseMessage.RequestMessage = request;
37 | return Task.FromResult(responseMessage);
38 | }
39 |
40 | return Task.FromResult(new HttpResponseMessage());
41 | }
42 |
43 | private void DefaultRequestHandler(HttpRequestMessage httpRequest)
44 | {
45 |
46 | }
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/tests/Microsoft.Graph.DotnetCore.Core.Test/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.InteropServices;
3 |
4 | // General Information about an assembly is controlled through the following
5 | // set of attributes. Change these attribute values to modify the information
6 | // associated with an assembly.
7 | [assembly: AssemblyConfiguration("")]
8 | [assembly: AssemblyCompany("")]
9 | [assembly: AssemblyProduct("Microsoft.Graph.DotnetCore.Core.Test")]
10 | [assembly: AssemblyTrademark("")]
11 |
12 | // Setting ComVisible to false makes the types in this assembly not visible
13 | // to COM components. If you need to access a type in this assembly from
14 | // COM, set the ComVisible attribute to true on that type.
15 | [assembly: ComVisible(false)]
16 |
17 | // The following GUID is for the ID of the typelib if this project is exposed to COM
18 | [assembly: Guid("a337bd4b-5c76-4bc5-8ec2-2ee7b834d030")]
19 |
--------------------------------------------------------------------------------
/tests/Microsoft.Graph.DotnetCore.Core.Test/Requests/BaseClientTests.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | namespace Microsoft.Graph.DotnetCore.Core.Test.Requests
6 | {
7 | using Microsoft.Graph.DotnetCore.Core.Test.Mocks;
8 | using Xunit;
9 | public class BaseClientTests
10 | {
11 | private MockAuthenticationProvider authenticationProvider;
12 | private MockTokenCredential tokenCredential;
13 |
14 | public BaseClientTests()
15 | {
16 | this.authenticationProvider = new MockAuthenticationProvider();
17 | this.tokenCredential = new MockTokenCredential();
18 | }
19 |
20 | [Fact]
21 | public void BaseClient_InitializeBaseUrlWithoutTrailingSlash()
22 | {
23 | var expectedBaseUrl = "https://localhost";
24 |
25 | var baseClient = new BaseClient(expectedBaseUrl, this.authenticationProvider.Object);
26 |
27 | Assert.Equal(expectedBaseUrl, baseClient.RequestAdapter.BaseUrl);
28 | }
29 |
30 | [Fact]
31 | public void BaseClient_InitializeBaseUrlTrailingSlash()
32 | {
33 | var expectedBaseUrl = "https://localhost";
34 |
35 | var baseClient = new BaseClient("https://localhost/", this.authenticationProvider.Object);
36 |
37 | Assert.Equal(expectedBaseUrl, baseClient.RequestAdapter.BaseUrl);
38 | }
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/tests/Microsoft.Graph.DotnetCore.Core.Test/Requests/GraphResponseTests.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 |
6 | namespace Microsoft.Graph.DotnetCore.Core.Test.Requests
7 | {
8 | using System.Linq;
9 | using System.Net;
10 | using System.Net.Http;
11 | using System.Text;
12 | using System.Threading.Tasks;
13 | using Microsoft.Graph.DotnetCore.Core.Test.TestModels.ServiceModels;
14 | using Microsoft.Kiota.Abstractions;
15 | using Microsoft.Kiota.Serialization.Json;
16 | using Xunit;
17 |
18 | public class GraphResponseTests : RequestTestBase
19 | {
20 | [Fact]
21 | public void GraphResponse_Initialize()
22 | {
23 | // Arrange
24 | HttpResponseMessage responseMessage = new HttpResponseMessage(HttpStatusCode.OK);
25 | RequestInformation requestInformation = new RequestInformation() { UrlTemplate = "http://localhost" };
26 |
27 | // Act
28 | GraphResponse response = new GraphResponse(requestInformation, responseMessage);
29 |
30 | // Assert
31 | Assert.Equal(responseMessage, response.ToHttpResponseMessage());
32 | Assert.Equal(responseMessage.StatusCode, response.StatusCode);
33 | Assert.Equal(requestInformation, response.RequestInformation);
34 |
35 | }
36 |
37 | [Fact]
38 | public void GraphResponse_ValidateHeaders()
39 | {
40 | // Arrange
41 | HttpResponseMessage responseMessage = new HttpResponseMessage(HttpStatusCode.OK);
42 | responseMessage.Headers.Add("Authorization", "bearer token");// add a test header
43 | RequestInformation requestInformation = new RequestInformation() { UrlTemplate = "http://localhost" };
44 |
45 | // Act
46 | GraphResponse response = new GraphResponse(requestInformation, responseMessage);
47 |
48 | // Assert
49 | Assert.Equal(responseMessage, response.ToHttpResponseMessage());
50 | Assert.Equal(responseMessage.Headers.Count(), response.HttpHeaders.Count());
51 | Assert.Equal("Authorization", responseMessage.Headers.First().Key);
52 | Assert.Equal("bearer token", responseMessage.Headers.First().Value.First());
53 |
54 | }
55 |
56 | [Fact]
57 | public async Task ValidateResponseHandlerAsync()
58 | {
59 | // Arrange
60 | HttpResponseMessage responseMessage = new HttpResponseMessage()
61 | {
62 | Content = new StringContent(@"{
63 | ""id"": ""123"",
64 | ""givenName"": ""Joe"",
65 | ""surname"": ""Brown"",
66 | ""@odata.type"":""test""
67 | }", Encoding.UTF8, CoreConstants.MimeTypeNames.Application.Json)
68 | };
69 |
70 | // create a custom responseHandler
71 | IResponseHandler responseHandler = new ResponseHandler(new JsonParseNodeFactory());
72 | RequestInformation requestInformation = new RequestInformation() { UrlTemplate = "http://localhost" };
73 |
74 |
75 | // Act
76 | GraphResponse response = new GraphResponse(requestInformation, responseMessage);
77 | TestUser user = await response.GetResponseObjectAsync(responseHandler);
78 |
79 | // Assert
80 | Assert.Equal("123", user.Id);
81 | Assert.Equal("Joe", user.GivenName);
82 | Assert.Equal("Brown", user.Surname);
83 |
84 | }
85 | }
86 | }
87 |
--------------------------------------------------------------------------------
/tests/Microsoft.Graph.DotnetCore.Core.Test/Requests/RequestTestBase.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | namespace Microsoft.Graph.DotnetCore.Core.Test.Requests
6 | {
7 | using System;
8 | using System.Net.Http;
9 | using Microsoft.Graph.DotnetCore.Core.Test.Mocks;
10 | public class RequestTestBase : IDisposable
11 | {
12 | protected string baseUrl = "https://localhost/v1.0";
13 |
14 | protected MockAuthenticationProvider authenticationProvider;
15 | protected HttpResponseMessage httpResponseMessage;
16 | protected IBaseClient baseClient;
17 |
18 | public RequestTestBase()
19 | {
20 | this.authenticationProvider = new MockAuthenticationProvider();
21 | this.httpResponseMessage = new HttpResponseMessage();
22 |
23 | this.baseClient = new BaseClient(
24 | this.baseUrl,
25 | this.authenticationProvider.Object);
26 | }
27 |
28 | public void Dispose()
29 | {
30 | this.httpResponseMessage.Dispose();
31 | }
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/tests/Microsoft.Graph.DotnetCore.Core.Test/Requests/Upload/UploadSliceRequestTests.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | namespace Microsoft.Graph.DotnetCore.Core.Test.Requests
6 | {
7 | using System;
8 | using System.IO;
9 | using System.Linq;
10 | using System.Net;
11 | using System.Net.Http;
12 | using System.Text;
13 | using System.Threading.Tasks;
14 | using Microsoft.Graph.DotnetCore.Core.Test.Mocks;
15 | using Microsoft.Graph.DotnetCore.Core.Test.TestModels.ServiceModels;
16 | using Microsoft.Kiota.Abstractions.Authentication;
17 | using Microsoft.Kiota.Abstractions.Serialization;
18 | using Microsoft.Kiota.Serialization.Json;
19 | using Xunit;
20 |
21 | public class UploadSliceRequests : RequestTestBase
22 | {
23 | public UploadSliceRequests()
24 | {
25 | // register the default serialization instance as the generator would.
26 | ParseNodeFactoryRegistry.DefaultInstance.ContentTypeAssociatedFactories.TryAdd(CoreConstants.MimeTypeNames.Application.Json, new JsonParseNodeFactory());
27 | }
28 |
29 | [Fact]
30 | public async Task PutAsyncReturnsExpectedUploadSessionAsync()
31 | {
32 | using (HttpResponseMessage responseMessage = new HttpResponseMessage(HttpStatusCode.OK))
33 | using (TestHttpMessageHandler testHttpMessageHandler = new TestHttpMessageHandler())
34 | {
35 | /* Arrange */
36 | // 1. create a mock response
37 | string requestUrl = "https://localhost/";
38 | string responseJSON = @"{
39 | ""expirationDateTime"": ""2015 - 01 - 29T09: 21:55.523Z"",
40 | ""nextExpectedRanges"": [
41 | ""12345-55232"",
42 | ""77829-99375""
43 | ]
44 | }";
45 | HttpContent content = new StringContent(responseJSON, Encoding.UTF8, CoreConstants.MimeTypeNames.Application.Json);
46 | responseMessage.Content = content;
47 |
48 | // 2. Map the response
49 | testHttpMessageHandler.AddResponseMapping(requestUrl, responseMessage);
50 |
51 | // 3. Create a batch request object to be tested
52 | IBaseClient client = new BaseClient(requestUrl, authenticationProvider.Object);
53 | IBaseClient baseClient = new BaseClient(new BaseGraphRequestAdapter(new AnonymousAuthenticationProvider(), httpClient: GraphClientFactory.Create(finalHandler: testHttpMessageHandler)));
54 | UploadSliceRequestBuilder uploadSliceRequestBuilder = new UploadSliceRequestBuilder(requestUrl, baseClient.RequestAdapter, 0, 200, 1000);
55 | Stream stream = new MemoryStream(new byte[300]);
56 |
57 | /* Act */
58 | var uploadResult = await uploadSliceRequestBuilder.PutAsync(stream);
59 | var uploadSession = uploadResult.UploadSession;
60 |
61 | /* Assert */
62 | Assert.False(uploadResult.UploadSucceeded);
63 | Assert.NotNull(uploadSession);
64 | Assert.Null(uploadSession.UploadUrl);
65 | Assert.Equal(DateTimeOffset.Parse("2015 - 01 - 29T09: 21:55.523Z"), uploadSession.ExpirationDateTime);
66 | Assert.Equal("12345-55232", uploadSession.NextExpectedRanges.First());
67 | Assert.Equal("77829-99375", uploadSession.NextExpectedRanges.Last());
68 | Assert.Equal(2, uploadSession.NextExpectedRanges.Count());
69 | }
70 | }
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/tests/Microsoft.Graph.DotnetCore.Core.Test/TestModels/AbstractEntityType.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | namespace Microsoft.Graph.DotnetCore.Core.Test.TestModels
6 | {
7 | using System;
8 | using System.Collections.Generic;
9 | using Microsoft.Kiota.Abstractions.Serialization;
10 |
11 | ///
12 | /// A class to test abstract entity serialization and deserialization.
13 | ///
14 | public class AbstractEntityType : IParsable, IAdditionalDataHolder
15 | {
16 | ///
17 | /// Gets or sets id.
18 | ///
19 | public string Id
20 | {
21 | get; set;
22 | }
23 |
24 | ///
25 | /// Gets or sets additional data.
26 | ///
27 | public IDictionary AdditionalData
28 | {
29 | get; set;
30 | }
31 |
32 | ///
33 | /// Gets the field deserializers for the class
34 | ///
35 | ///
36 | public IDictionary> GetFieldDeserializers()
37 | {
38 | return new Dictionary>
39 | {
40 | {"id", (n) => { Id = n.GetStringValue(); } }
41 | };
42 | }
43 |
44 | ///
45 | /// Serializes this instance
46 | ///
47 | /// The to use.
48 | ///
49 | public void Serialize(ISerializationWriter writer)
50 | {
51 | _ = writer ?? throw new ArgumentNullException(nameof(writer));
52 | writer.WriteStringValue("id", Id);
53 | writer.WriteAdditionalData(AdditionalData);
54 | }
55 |
56 | ///
57 | /// Creates a new instance of the appropriate class based on discriminator value
58 | /// The parse node to use to read the discriminator value and create the object
59 | ///
60 | public static AbstractEntityType CreateFromDiscriminatorValue(IParseNode parseNode)
61 | {
62 | _ = parseNode ?? throw new ArgumentNullException(nameof(parseNode));
63 | var mappingValueNode = parseNode.GetChildNode("@odata.type");
64 | var mappingValue = mappingValueNode?.GetStringValue();
65 | return mappingValue switch
66 | {
67 | "#microsoft.graph.dotnetCore.core.test.testModels.derivedTypeClass" => new DerivedTypeClass(),
68 | _ => new AbstractEntityType()
69 | };
70 | }
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/tests/Microsoft.Graph.DotnetCore.Core.Test/TestModels/DateTestClass.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | namespace Microsoft.Graph.DotnetCore.Core.Test.TestModels
6 | {
7 | using System;
8 | using System.Collections.Generic;
9 | using Microsoft.Kiota.Abstractions;
10 | using Microsoft.Kiota.Abstractions.Serialization;
11 |
12 | ///
13 | /// Test class for testing serialization of Date.
14 | ///
15 | public class DateTestClass : IParsable
16 | {
17 | ///
18 | /// Gets or sets nullableDate.
19 | ///
20 | public Date? NullableDate
21 | {
22 | get; set;
23 | }
24 |
25 | ///
26 | /// Gets or sets dateCollection.
27 | ///
28 | public IEnumerable DateCollection
29 | {
30 | get; set;
31 | }
32 |
33 | ///
34 | /// Gets or sets InvalidType.
35 | ///
36 | public int? InvalidType
37 | {
38 | get; set;
39 | }
40 |
41 | ///
42 | /// Gets or sets IgnoredNumber
43 | ///
44 | public int IgnoredNumber
45 | {
46 | get; set;
47 | }
48 |
49 | ///
50 | /// Gets or sets AdditionalData
51 | ///
52 | public IDictionary AdditionalData { get; set; } = new Dictionary();
53 |
54 | ///
55 | /// Gets the field deserializers for the class
56 | ///
57 | ///
58 | public IDictionary> GetFieldDeserializers()
59 | {
60 | return new Dictionary>
61 | {
62 | {"nullableDate", (n) => { NullableDate = n.GetDateValue(); } },
63 | {"dateCollection", (n) => { DateCollection = n.GetCollectionOfPrimitiveValues(); } },
64 | {"invalidType", (n) => { InvalidType = n.GetIntValue(); } },
65 | };
66 | }
67 |
68 | ///
69 | /// Serializes this instance
70 | ///
71 | /// The to use.
72 | ///
73 | public void Serialize(ISerializationWriter writer)
74 | {
75 | _ = writer ?? throw new ArgumentNullException(nameof(writer));
76 | writer.WriteDateValue("nullableDate", NullableDate);
77 | writer.WriteCollectionOfPrimitiveValues("dateCollection", DateCollection);
78 | writer.WriteIntValue("invalidType", InvalidType);
79 | writer.WriteAdditionalData(AdditionalData);
80 | }
81 |
82 | ///
83 | /// Creates a new instance of the appropriate class based on discriminator value
84 | /// The parse node to use to read the discriminator value and create the object
85 | ///
86 | public static DateTestClass CreateFromDiscriminatorValue(IParseNode parseNode)
87 | {
88 | _ = parseNode ?? throw new ArgumentNullException(nameof(parseNode));
89 | return new DateTestClass();
90 | }
91 | }
92 | }
93 |
--------------------------------------------------------------------------------
/tests/Microsoft.Graph.DotnetCore.Core.Test/TestModels/DerivedTypeClass.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | namespace Microsoft.Graph.DotnetCore.Core.Test.TestModels
6 | {
7 | using System;
8 | using System.Collections.Generic;
9 | using Microsoft.Kiota.Abstractions.Serialization;
10 |
11 | ///
12 | /// A property bag class for testing derived type deserialization.
13 | ///
14 | public class DerivedTypeClass : AbstractEntityType, IParsable, IAdditionalDataHolder
15 | {
16 | ///
17 | /// Gets or sets enumType.
18 | ///
19 | public EnumType? EnumType
20 | {
21 | get; set;
22 | }
23 |
24 | ///
25 | /// Gets or sets id.
26 | ///
27 | public string Name
28 | {
29 | get; set;
30 | }
31 |
32 | ///
33 | /// Gets or sets id.
34 | ///
35 | public IEnumerable MemorableDates
36 | {
37 | get; set;
38 | }
39 |
40 | ///
41 | /// Gets or sets link.
42 | ///
43 | public string WebUrl
44 | {
45 | get; set;
46 | }
47 |
48 | ///
49 | /// Gets the field deserializers for the class
50 | ///
51 | ///
52 | public new IDictionary> GetFieldDeserializers()
53 | {
54 | return new Dictionary>(base.GetFieldDeserializers())
55 | {
56 | {"enumType", (n) => { EnumType = n.GetEnumValue(); } },
57 | {"name", (n) => { Name = n.GetStringValue(); } },
58 | {"memorableDates", (n) => { MemorableDates = n.GetCollectionOfObjectValues(DateTestClass.CreateFromDiscriminatorValue); } },
59 | {"link", (n) => { WebUrl = n.GetStringValue(); } },
60 | };
61 | }
62 |
63 | ///
64 | /// Serializes this instance
65 | ///
66 | /// The to use.
67 | ///
68 | public new void Serialize(ISerializationWriter writer)
69 | {
70 | _ = writer ?? throw new ArgumentNullException(nameof(writer));
71 | base.Serialize(writer);
72 | writer.WriteEnumValue("enumType", EnumType);
73 | writer.WriteStringValue("name", Name);
74 | writer.WriteCollectionOfObjectValues("memorableDates", MemorableDates);
75 | writer.WriteStringValue("link", WebUrl);
76 | writer.WriteAdditionalData(AdditionalData);
77 | }
78 |
79 | ///
80 | /// Creates a new instance of the appropriate class based on discriminator value
81 | /// The parse node to use to read the discriminator value and create the object
82 | ///
83 | public static new DerivedTypeClass CreateFromDiscriminatorValue(IParseNode parseNode)
84 | {
85 | _ = parseNode ?? throw new ArgumentNullException(nameof(parseNode));
86 | return new DerivedTypeClass();
87 | }
88 | }
89 | }
90 |
--------------------------------------------------------------------------------
/tests/Microsoft.Graph.DotnetCore.Core.Test/TestModels/EnumType.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 |
6 | using System.Runtime.Serialization;
7 |
8 | namespace Microsoft.Graph.DotnetCore.Core.Test.TestModels
9 | {
10 | ///
11 | /// Enum for testing enum serialization and deserialization.
12 | ///
13 | public enum EnumType
14 | {
15 | [EnumMember(Value = "value")]
16 | Value,
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/tests/Microsoft.Graph.DotnetCore.Core.Test/TestModels/EnumTypeWithFlags.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 |
6 | using System.Runtime.Serialization;
7 |
8 | namespace Microsoft.Graph.DotnetCore.Core.Test.TestModels
9 | {
10 | ///
11 | /// Enum for testing enum serialization and deserialization.
12 | ///
13 | [System.Flags]
14 | public enum EnumTypeWithFlags
15 | {
16 | [EnumMember(Value = "firstValue")]
17 | FirstValue = 1,
18 | [EnumMember(Value = "secondValue")]
19 | SecondValue = 2
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/tests/Microsoft.Graph.DotnetCore.Core.Test/TestModels/ServiceModels/TestAttendee.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | namespace Microsoft.Graph.DotnetCore.Core.Test.TestModels.ServiceModels
6 | {
7 | using System;
8 | using System.Collections.Generic;
9 | using Microsoft.Kiota.Abstractions.Serialization;
10 |
11 | public class TestAttendee : TestRecipient, IParsable, IAdditionalDataHolder
12 | {
13 | ///
14 | /// Initializes a new instance of the class.
15 | ///
16 | public TestAttendee()
17 | {
18 | this.ODataType = "microsoft.graph.attendee";
19 | }
20 |
21 | ///
22 | /// Gets the field deserializers for the instance
23 | ///
24 | ///
25 | public new IDictionary> GetFieldDeserializers()
26 | {
27 | return new Dictionary>(base.GetFieldDeserializers())
28 | {
29 | };
30 | }
31 |
32 | ///
33 | /// Serialize the instance
34 | ///
35 | /// The to serialize the instance
36 | /// Thrown when the writer is null
37 | public new void Serialize(ISerializationWriter writer)
38 | {
39 | _ = writer ?? throw new ArgumentNullException(nameof(writer));
40 | base.Serialize(writer);
41 | writer.WriteAdditionalData(AdditionalData);
42 | }
43 |
44 | ///
45 | /// Creates a new instance of the appropriate class based on discriminator value
46 | /// The parse node to use to read the discriminator value and create the object
47 | ///
48 | public static new TestAttendee CreateFromDiscriminatorValue(IParseNode parseNode)
49 | {
50 | _ = parseNode ?? throw new ArgumentNullException(nameof(parseNode));
51 | return new TestAttendee();
52 | }
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/tests/Microsoft.Graph.DotnetCore.Core.Test/TestModels/ServiceModels/TestBodyType.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | using System.Runtime.Serialization;
6 |
7 | namespace Microsoft.Graph.DotnetCore.Core.Test.TestModels.ServiceModels
8 | {
9 | ///
10 | /// The enum BodyType.
11 | ///
12 | public enum TestBodyType
13 | {
14 |
15 | ///
16 | /// Text
17 | ///
18 | [EnumMember(Value = "text")]
19 | Text = 0,
20 |
21 | ///
22 | /// Html
23 | ///
24 | [EnumMember(Value = "html")]
25 | Html = 1,
26 |
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/tests/Microsoft.Graph.DotnetCore.Core.Test/TestModels/ServiceModels/TestDateTimeTimeZone.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | namespace Microsoft.Graph.DotnetCore.Core.Test.TestModels.ServiceModels
6 | {
7 | using System;
8 | using System.Collections.Generic;
9 | using Microsoft.Kiota.Abstractions.Serialization;
10 |
11 | ///
12 | /// The type DateTimeTimeZone.
13 | ///
14 | public partial class TestDateTimeTimeZone : IParsable, IAdditionalDataHolder
15 | {
16 | ///
17 | /// Initializes a new instance of the class.
18 | ///
19 | public TestDateTimeTimeZone()
20 | {
21 | this.ODataType = "microsoft.graph.dateTimeTimeZone";
22 | }
23 |
24 | ///
25 | /// Gets or sets dateTime.
26 | /// A single point of time in a combined date and time representation ({date}T{time}; for example, 2017-08-29T04:00:00.0000000).
27 | ///
28 | public string DateTime
29 | {
30 | get; set;
31 | }
32 |
33 | ///
34 | /// Gets or sets timeZone.
35 | /// Represents a time zone, for example, 'Pacific Standard Time'. See below for more possible values.
36 | ///
37 | public string TimeZone
38 | {
39 | get; set;
40 | }
41 |
42 | ///
43 | /// Gets or sets additional data.
44 | ///
45 | public IDictionary AdditionalData { get; set; } = new Dictionary();
46 |
47 | ///
48 | /// Gets or sets @odata.type.
49 | ///
50 | public string ODataType
51 | {
52 | get; set;
53 | }
54 |
55 | ///
56 | /// Gets the field deserializers for the instance
57 | ///
58 | ///
59 | public IDictionary> GetFieldDeserializers()
60 | {
61 | return new Dictionary>
62 | {
63 | {"dateTime", (n) => { DateTime = n.GetStringValue(); } },
64 | {"timeZone", (n) => { TimeZone = n.GetStringValue(); } },
65 | {"@odata.type", (n) => { ODataType = n.GetStringValue(); } },
66 | };
67 | }
68 |
69 | ///
70 | /// Serialize the instance
71 | ///
72 | /// The to serialize the instance
73 | /// Thrown when the writer is null
74 | public void Serialize(ISerializationWriter writer)
75 | {
76 | _ = writer ?? throw new ArgumentNullException(nameof(writer));
77 | writer.WriteStringValue("dateTime", DateTime);
78 | writer.WriteStringValue("timeZone", TimeZone);
79 | writer.WriteStringValue("@odata.type", ODataType);
80 | writer.WriteAdditionalData(AdditionalData);
81 | }
82 |
83 | ///
84 | /// Creates a new instance of the appropriate class based on discriminator value
85 | /// The parse node to use to read the discriminator value and create the object
86 | ///
87 | public static TestDateTimeTimeZone CreateFromDiscriminatorValue(IParseNode parseNode)
88 | {
89 | _ = parseNode ?? throw new ArgumentNullException(nameof(parseNode));
90 | return new TestDateTimeTimeZone();
91 | }
92 | }
93 | }
94 |
--------------------------------------------------------------------------------
/tests/Microsoft.Graph.DotnetCore.Core.Test/TestModels/ServiceModels/TestDrive.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | namespace Microsoft.Graph.DotnetCore.Core.Test.TestModels.ServiceModels
6 | {
7 | using System;
8 | using System.Collections.Generic;
9 | using Microsoft.Kiota.Abstractions.Serialization;
10 |
11 | public partial class TestDrive : IParsable, IAdditionalDataHolder
12 | {
13 | ///
14 | /// The Drive constructor
15 | ///
16 | public TestDrive()
17 | {
18 | this.ODataType = "microsoft.graph.drive";
19 | }
20 |
21 | ///
22 | /// Gets or sets id.
23 | /// Read-only.
24 | ///
25 | public string Id
26 | {
27 | get; set;
28 | }
29 |
30 | ///
31 | /// Gets or sets @odata.type.
32 | ///
33 | public string ODataType
34 | {
35 | get; set;
36 | }
37 |
38 | ///
39 | /// Gets or sets name.
40 | /// The name of the item. Read-write.
41 | ///
42 | public string Name
43 | {
44 | get; set;
45 | }
46 |
47 | ///
48 | /// Gets or sets additional data.
49 | ///
50 | public IDictionary AdditionalData
51 | {
52 | get; set;
53 | }
54 |
55 | ///
56 | /// Gets the field deserializers for the instance
57 | ///
58 | ///
59 | public IDictionary> GetFieldDeserializers()
60 | {
61 | return new Dictionary>
62 | {
63 | {"@odata.type", (n) => { ODataType = n.GetStringValue(); } },
64 | {"id", (n) => { Id = n.GetStringValue(); } },
65 | {"name", (n) => { Name = n.GetStringValue(); } },
66 | };
67 | }
68 |
69 | ///
70 | /// Serialize the instance
71 | ///
72 | /// The to serialize the instance
73 | /// Thrown when the writer is null
74 | public void Serialize(ISerializationWriter writer)
75 | {
76 | _ = writer ?? throw new ArgumentNullException(nameof(writer));
77 | writer.WriteStringValue("@odata.type", ODataType);
78 | writer.WriteStringValue("id", Id);
79 | writer.WriteStringValue("name", Name);
80 | writer.WriteAdditionalData(AdditionalData);
81 | }
82 | }
83 | }
84 |
--------------------------------------------------------------------------------
/tests/Microsoft.Graph.DotnetCore.Core.Test/TestModels/ServiceModels/TestDriveItem.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | namespace Microsoft.Graph.DotnetCore.Core.Test.TestModels.ServiceModels
6 | {
7 | using System;
8 | using System.Collections.Generic;
9 | using System.Text.Json.Serialization;
10 | using Microsoft.Kiota.Abstractions.Serialization;
11 |
12 | public partial class TestDriveItem : IParsable, IAdditionalDataHolder
13 | {
14 | ///
15 | /// The Drive constructor
16 | ///
17 | public TestDriveItem()
18 | {
19 | this.ODataType = "microsoft.graph.drive";
20 | }
21 |
22 | ///
23 | /// Gets or sets id.
24 | /// Read-only.
25 | ///
26 | public string Id
27 | {
28 | get; set;
29 | }
30 |
31 | ///
32 | /// Gets or sets @odata.type.
33 | ///
34 | [JsonPropertyName("@odata.type")]
35 | public string ODataType
36 | {
37 | get; set;
38 | }
39 |
40 | ///
41 | /// Gets or sets name.
42 | /// The name of the item. Read-write.
43 | ///
44 | [JsonPropertyName("name")]
45 | public string Name
46 | {
47 | get; set;
48 | }
49 |
50 | ///
51 | /// Gets or sets additional data.
52 | ///
53 | [JsonExtensionData]
54 | public IDictionary AdditionalData
55 | {
56 | get; set;
57 | }
58 |
59 | ///
60 | /// Gets or sets size.
61 | /// Size of the item in bytes. Read-only.
62 | ///
63 | [JsonPropertyName("size")]
64 | public Int64? Size
65 | {
66 | get; set;
67 | }
68 |
69 | ///
70 | /// Gets the field deserializers for the instance
71 | ///
72 | ///
73 | public IDictionary> GetFieldDeserializers()
74 | {
75 | return new Dictionary>
76 | {
77 | {"id", (n) => { Id = n.GetStringValue(); } },
78 | {"@odata.type", (n) => { ODataType = n.GetStringValue(); } },
79 | {"name", (n) => { Name = n.GetStringValue(); } },
80 | {"size", (n) => { Size = n.GetLongValue(); } }
81 | };
82 | }
83 |
84 | ///
85 | /// Serialize the instance
86 | ///
87 | /// The to serialize the instance
88 | /// Thrown when the writer is null
89 | public void Serialize(ISerializationWriter writer)
90 | {
91 | _ = writer ?? throw new ArgumentNullException(nameof(writer));
92 | writer.WriteStringValue("id", Id);
93 | writer.WriteStringValue("@odata.type", ODataType);
94 | writer.WriteStringValue("name", Name);
95 | writer.WriteLongValue("size", Size);
96 | }
97 | }
98 | }
99 |
--------------------------------------------------------------------------------
/tests/Microsoft.Graph.DotnetCore.Core.Test/TestModels/ServiceModels/TestEmailAddress.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | namespace Microsoft.Graph.DotnetCore.Core.Test.TestModels.ServiceModels
6 | {
7 | using System;
8 | using System.Collections.Generic;
9 | using Microsoft.Kiota.Abstractions.Serialization;
10 |
11 | ///
12 | /// The type TestEmailAddress.
13 | ///
14 | public partial class TestEmailAddress : IParsable, IAdditionalDataHolder
15 | {
16 | ///
17 | /// Initializes a new instance of the class.
18 | ///
19 | public TestEmailAddress()
20 | {
21 | this.ODataType = "microsoft.graph.emailAddress";
22 | }
23 |
24 | ///
25 | /// Gets or sets name.
26 | /// The display name of the person or entity.
27 | ///
28 | public string Name
29 | {
30 | get; set;
31 | }
32 |
33 | ///
34 | /// Gets or sets address.
35 | /// The email address of the person or entity.
36 | ///
37 | public string Address
38 | {
39 | get; set;
40 | }
41 |
42 | ///
43 | /// Gets or sets additional data.
44 | ///
45 | public IDictionary AdditionalData { get; set; } = new Dictionary();
46 |
47 | ///
48 | /// Gets or sets @odata.type.
49 | ///
50 | public string ODataType
51 | {
52 | get; set;
53 | }
54 |
55 | ///
56 | /// Gets the field deserializers for the instance
57 | ///
58 | ///
59 | public IDictionary> GetFieldDeserializers()
60 | {
61 | return new Dictionary>
62 | {
63 | {"@odata.type", (n) => { ODataType = n.GetStringValue(); } },
64 | {"address", (n) => { Address = n.GetStringValue(); } },
65 | {"name", (n) => { Name = n.GetStringValue(); } },
66 | };
67 | }
68 |
69 | ///
70 | /// Serialize the instance
71 | ///
72 | /// The to serialize the instance
73 | /// Thrown when the writer is null
74 | public void Serialize(ISerializationWriter writer)
75 | {
76 | _ = writer ?? throw new ArgumentNullException(nameof(writer));
77 | writer.WriteStringValue("name", Name);
78 | writer.WriteStringValue("address", Address);
79 | writer.WriteStringValue("@odata.type", ODataType);
80 | writer.WriteAdditionalData(AdditionalData);
81 | }
82 |
83 | ///
84 | /// Creates a new instance of the appropriate class based on discriminator value
85 | /// The parse node to use to read the discriminator value and create the object
86 | ///
87 | public static TestEmailAddress CreateFromDiscriminatorValue(IParseNode parseNode)
88 | {
89 | _ = parseNode ?? throw new ArgumentNullException(nameof(parseNode));
90 | return new TestEmailAddress();
91 | }
92 | }
93 | }
94 |
--------------------------------------------------------------------------------
/tests/Microsoft.Graph.DotnetCore.Core.Test/TestModels/ServiceModels/TestEventDeltaCollectionResponse.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | using System;
6 | using System.Collections.Generic;
7 | using System.Linq;
8 | using Microsoft.Kiota.Abstractions.Serialization;
9 |
10 | namespace Microsoft.Graph.DotnetCore.Core.Test.TestModels.ServiceModels
11 | {
12 | ///
13 | /// The type UserEventsCollectionResponse.
14 | ///
15 |
16 | public class TestEventDeltaCollectionResponse : IParsable, IAdditionalDataHolder
17 | {
18 | ///
19 | /// Gets or sets the event collection value.
20 | ///
21 | public List Value
22 | {
23 | get; set;
24 | }
25 |
26 | ///
27 | /// Gets or sets the OdataNextLink string value.
28 | ///
29 | public string OdataNextLink
30 | {
31 | get; set;
32 | }
33 | ///
34 | /// Gets or sets additional data.
35 | ///
36 | public IDictionary AdditionalData
37 | {
38 | get; set;
39 | }
40 |
41 | ///
42 | /// Gets the field deserializers for the instance
43 | ///
44 | ///
45 | public IDictionary> GetFieldDeserializers()
46 | {
47 | return new Dictionary>
48 | {
49 | {"@odata.nextLink", (n) => { OdataNextLink = n.GetStringValue(); } },
50 | {"value", (n) => { Value = n.GetCollectionOfObjectValues(TestEvent.CreateFromDiscriminatorValue).ToList(); } },
51 | };
52 | }
53 |
54 | ///
55 | /// Serialize the instance
56 | ///
57 | /// The to serialize the instance
58 | /// Thrown when the writer is null
59 | public void Serialize(ISerializationWriter writer)
60 | {
61 | _ = writer ?? throw new ArgumentNullException(nameof(writer));
62 | writer.WriteStringValue("@odata.nextLink", OdataNextLink);
63 | writer.WriteCollectionOfObjectValues("value", Value);
64 | writer.WriteAdditionalData(AdditionalData);
65 | }
66 |
67 | ///
68 | /// Creates a new instance of the appropriate class based on discriminator value
69 | /// The parse node to use to read the discriminator value and create the object
70 | ///
71 | public static TestEventDeltaCollectionResponse CreateFromDiscriminatorValue(IParseNode parseNode)
72 | {
73 | _ = parseNode ?? throw new ArgumentNullException(nameof(parseNode));
74 | return new TestEventDeltaCollectionResponse();
75 | }
76 | }
77 | }
78 |
--------------------------------------------------------------------------------
/tests/Microsoft.Graph.DotnetCore.Core.Test/TestModels/ServiceModels/TestEventsDeltaResponse.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | using System;
6 | using System.Collections.Generic;
7 | using System.Linq;
8 | using Microsoft.Kiota.Abstractions.Serialization;
9 | namespace Microsoft.Graph.DotnetCore.Core.Test.TestModels.ServiceModels
10 | {
11 | public class TestEventsDeltaResponse : IParsable, IAdditionalDataHolder
12 | {
13 | /// Stores additional data not described in the OpenAPI description found when deserializing. Can be used for serialization as well.
14 | public IDictionary AdditionalData
15 | {
16 | get; set;
17 | }
18 |
19 | public string OdataDeltaLink
20 | {
21 | get; set;
22 | }
23 |
24 | public string OdataNextLink
25 | {
26 | get; set;
27 | }
28 |
29 | public List Value
30 | {
31 | get; set;
32 | }
33 | ///
34 | /// Instantiates a new eventsResponse and sets the default values.
35 | ///
36 | public TestEventsDeltaResponse()
37 | {
38 | AdditionalData = new Dictionary();
39 | }
40 | ///
41 | /// The deserialization information for the current model
42 | ///
43 | public IDictionary> GetFieldDeserializers()
44 | {
45 | return new Dictionary> {
46 | {"@odata.deltaLink", n => { OdataDeltaLink = n.GetStringValue(); } },
47 | {"@odata.nextLink", n => { OdataNextLink = n.GetStringValue(); } },
48 | {"value", (n) => { Value = n.GetCollectionOfObjectValues(TestEventItem.CreateFromDiscriminatorValue).ToList(); } },
49 | };
50 | }
51 | ///
52 | /// Serializes information the current object
53 | /// Serialization writer to use to serialize this model
54 | ///
55 | public void Serialize(ISerializationWriter writer)
56 | {
57 | _ = writer ?? throw new ArgumentNullException(nameof(writer));
58 | writer.WriteStringValue("@odata.deltaLink", OdataDeltaLink);
59 | writer.WriteStringValue("@odata.nextLink", OdataNextLink);
60 | writer.WriteCollectionOfObjectValues("value", Value);
61 | writer.WriteAdditionalData(AdditionalData);
62 | }
63 |
64 | ///
65 | /// Creates a new instance of the appropriate class based on discriminator value
66 | /// The parse node to use to read the discriminator value and create the object
67 | ///
68 | public static TestEventsDeltaResponse CreateFromDiscriminatorValue(IParseNode parseNode)
69 | {
70 | _ = parseNode ?? throw new ArgumentNullException(nameof(parseNode));
71 | return new TestEventsDeltaResponse();
72 | }
73 | }
74 | }
75 |
--------------------------------------------------------------------------------
/tests/Microsoft.Graph.DotnetCore.Core.Test/TestModels/ServiceModels/TestEventsResponse.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | using System;
6 | using System.Collections.Generic;
7 | using System.Linq;
8 | using Microsoft.Kiota.Abstractions.Serialization;
9 | namespace Microsoft.Graph.DotnetCore.Core.Test.TestModels.ServiceModels
10 | {
11 | public class TestEventsResponse : IParsable, IAdditionalDataHolder
12 | {
13 | /// Stores additional data not described in the OpenAPI description found when deserializing. Can be used for serialization as well.
14 | public IDictionary AdditionalData
15 | {
16 | get; set;
17 | }
18 | public string OdataNextLink
19 | {
20 | get; set;
21 | }
22 | public List Value
23 | {
24 | get; set;
25 | }
26 | ///
27 | /// Instantiates a new eventsResponse and sets the default values.
28 | ///
29 | public TestEventsResponse()
30 | {
31 | AdditionalData = new Dictionary();
32 | }
33 | ///
34 | /// The deserialization information for the current model
35 | ///
36 | public IDictionary> GetFieldDeserializers()
37 | {
38 | return new Dictionary> {
39 | {"@odata.nextLink", (n) => { OdataNextLink = n.GetStringValue(); } },
40 | {"value", (n) => { Value = n.GetCollectionOfObjectValues(TestEventItem.CreateFromDiscriminatorValue).ToList(); } },
41 | };
42 | }
43 | ///
44 | /// Serializes information the current object
45 | /// Serialization writer to use to serialize this model
46 | ///
47 | public void Serialize(ISerializationWriter writer)
48 | {
49 | _ = writer ?? throw new ArgumentNullException(nameof(writer));
50 | writer.WriteStringValue("@odata.nextLink", OdataNextLink);
51 | writer.WriteCollectionOfObjectValues("value", Value);
52 | writer.WriteAdditionalData(AdditionalData);
53 | }
54 |
55 | ///
56 | /// Creates a new instance of the appropriate class based on discriminator value
57 | /// The parse node to use to read the discriminator value and create the object
58 | ///
59 | public static TestEventsResponse CreateFromDiscriminatorValue(IParseNode parseNode)
60 | {
61 | _ = parseNode ?? throw new ArgumentNullException(nameof(parseNode));
62 | return new TestEventsResponse();
63 | }
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/tests/Microsoft.Graph.DotnetCore.Core.Test/TestModels/ServiceModels/TestItemBody.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | namespace Microsoft.Graph.DotnetCore.Core.Test.TestModels.ServiceModels
6 | {
7 | using System;
8 | using System.Collections.Generic;
9 | using Microsoft.Kiota.Abstractions.Serialization;
10 |
11 | ///
12 | /// The type ItemBody.
13 | ///
14 | public partial class TestItemBody : IParsable, IAdditionalDataHolder
15 | {
16 | ///
17 | /// Initializes a new instance of the class.
18 | ///
19 | public TestItemBody()
20 | {
21 | this.ODataType = "microsoft.graph.itemBody";
22 | }
23 |
24 | ///
25 | /// Gets or sets contentType.
26 | /// The type of the content. Possible values are text and html.
27 | ///
28 | public TestBodyType? ContentType
29 | {
30 | get; set;
31 | }
32 |
33 | ///
34 | /// Gets or sets content.
35 | /// The content of the item.
36 | ///
37 | public string Content
38 | {
39 | get; set;
40 | }
41 |
42 | ///
43 | /// Gets or sets additional data.
44 | ///
45 | public IDictionary AdditionalData { get; set; } = new Dictionary();
46 |
47 | ///
48 | /// Gets or sets @odata.type.
49 | ///
50 | public string ODataType
51 | {
52 | get; set;
53 | }
54 |
55 | ///
56 | /// Gets the field deserializers for the instance
57 | ///
58 | ///
59 | public IDictionary> GetFieldDeserializers()
60 | {
61 | return new Dictionary>
62 | {
63 | {"@odata.type", (n) => { ODataType = n.GetStringValue(); } },
64 | {"contentType", (n) => { ContentType = n.GetEnumValue(); } },
65 | {"content", (n) => { Content = n.GetStringValue(); } },
66 | };
67 | }
68 |
69 | ///
70 | /// Serialize the instance
71 | ///
72 | /// The to serialize the instance
73 | /// Thrown when the writer is null
74 | public void Serialize(ISerializationWriter writer)
75 | {
76 | _ = writer ?? throw new ArgumentNullException(nameof(writer));
77 | writer.WriteStringValue("@odata.type", ODataType);
78 | writer.WriteEnumValue("contentType", ContentType);
79 | writer.WriteStringValue("content", Content);
80 | writer.WriteAdditionalData(AdditionalData);
81 | }
82 |
83 | ///
84 | /// Creates a new instance of the appropriate class based on discriminator value
85 | /// The parse node to use to read the discriminator value and create the object
86 | ///
87 | public static TestItemBody CreateFromDiscriminatorValue(IParseNode parseNode)
88 | {
89 | _ = parseNode ?? throw new ArgumentNullException(nameof(parseNode));
90 | return new TestItemBody();
91 | }
92 | }
93 | }
94 |
--------------------------------------------------------------------------------
/tests/Microsoft.Graph.DotnetCore.Core.Test/TestModels/ServiceModels/TestNotebook.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | namespace Microsoft.Graph.DotnetCore.Core.Test.TestModels.ServiceModels
6 | {
7 | using System;
8 | using System.Collections.Generic;
9 | using Microsoft.Kiota.Abstractions.Serialization;
10 |
11 | public partial class TestNoteBook : IParsable, IAdditionalDataHolder
12 | {
13 | ///
14 | /// The Drive constructor
15 | ///
16 | public TestNoteBook()
17 | {
18 | this.ODataType = "microsoft.graph.notebook";
19 | }
20 |
21 | ///
22 | /// Gets or sets id.
23 | /// Read-only.
24 | ///
25 | public string Id
26 | {
27 | get; set;
28 | }
29 |
30 | ///
31 | /// Gets or sets @odata.type.
32 | ///
33 | public string ODataType
34 | {
35 | get; set;
36 | }
37 |
38 | ///
39 | /// Gets or sets name.
40 | /// The name of the item. Read-write.
41 | ///
42 | public string DisplayName
43 | {
44 | get; set;
45 | }
46 |
47 | ///
48 | /// Gets or sets additional data.
49 | ///
50 | public IDictionary AdditionalData
51 | {
52 | get; set;
53 | }
54 |
55 | ///
56 | /// Gets the field deserializers for the instance
57 | ///
58 | ///
59 | public IDictionary> GetFieldDeserializers()
60 | {
61 | return new Dictionary>
62 | {
63 | {"@odata.type", (n) => { ODataType = n.GetStringValue(); } },
64 | {"id", (n) => { Id = n.GetStringValue(); } },
65 | {"displayName", (n) => { DisplayName = n.GetStringValue(); } },
66 | };
67 | }
68 |
69 | ///
70 | /// Serialize the instance
71 | ///
72 | /// The to serialize the instance
73 | /// Thrown when the writer is null
74 | public void Serialize(ISerializationWriter writer)
75 | {
76 | _ = writer ?? throw new ArgumentNullException(nameof(writer));
77 | writer.WriteStringValue("@odata.type", ODataType);
78 | writer.WriteStringValue("id", Id);
79 | writer.WriteStringValue("displayName", DisplayName);
80 | writer.WriteAdditionalData(AdditionalData);
81 | }
82 |
83 | ///
84 | /// Creates a new instance of the appropriate class based on discriminator value
85 | /// The parse node to use to read the discriminator value and create the object
86 | ///
87 | public static TestNoteBook CreateFromDiscriminatorValue(IParseNode parseNode)
88 | {
89 | _ = parseNode ?? throw new ArgumentNullException(nameof(parseNode));
90 | return new TestNoteBook();
91 | }
92 | }
93 | }
94 |
--------------------------------------------------------------------------------
/tests/Microsoft.Graph.DotnetCore.Core.Test/TestModels/ServiceModels/TestRecipient.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | namespace Microsoft.Graph.DotnetCore.Core.Test.TestModels.ServiceModels
6 | {
7 | using System;
8 | using System.Collections.Generic;
9 | using Microsoft.Kiota.Abstractions.Serialization;
10 |
11 | public class TestRecipient : IParsable, IAdditionalDataHolder
12 | {
13 | ///
14 | /// Initializes a new instance of the class.
15 | ///
16 | public TestRecipient()
17 | {
18 | this.ODataType = "microsoft.graph.recipient";
19 | }
20 |
21 | ///
22 | /// Gets or sets emailAddress.
23 | /// The recipient's email address.
24 | ///
25 | public TestEmailAddress EmailAddress
26 | {
27 | get; set;
28 | }
29 |
30 | ///
31 | /// Gets or sets additional data.
32 | ///
33 | public IDictionary AdditionalData
34 | {
35 | get; set;
36 | }
37 |
38 | ///
39 | /// Gets or sets @odata.type.
40 | ///
41 | public string ODataType
42 | {
43 | get; set;
44 | }
45 |
46 | ///
47 | /// Gets the field deserializers for the instance
48 | ///
49 | ///
50 | public IDictionary> GetFieldDeserializers()
51 | {
52 | return new Dictionary>
53 | {
54 | {"@odata.type", (n) => { ODataType = n.GetStringValue(); } },
55 | {"emailAddress", (n) => { EmailAddress = n.GetObjectValue(TestEmailAddress.CreateFromDiscriminatorValue); } },
56 | };
57 | }
58 |
59 | ///
60 | /// Serialize the instance
61 | ///
62 | /// The to serialize the instance
63 | /// Thrown when the writer is null
64 | public void Serialize(ISerializationWriter writer)
65 | {
66 | _ = writer ?? throw new ArgumentNullException(nameof(writer));
67 | writer.WriteStringValue("@odata.type", ODataType);
68 | writer.WriteObjectValue("emailAddress", EmailAddress);
69 | writer.WriteAdditionalData(AdditionalData);
70 | }
71 |
72 | ///
73 | /// Creates a new instance of the appropriate class based on discriminator value
74 | /// The parse node to use to read the discriminator value and create the object
75 | ///
76 | public static TestRecipient CreateFromDiscriminatorValue(IParseNode parseNode)
77 | {
78 | var mappingValueNode = parseNode.GetChildNode("@odata.type");
79 | var mappingValue = mappingValueNode?.GetStringValue();
80 | return mappingValue switch
81 | {
82 | "microsoft.graph.attendee" => new TestAttendee(),
83 | _ => new TestRecipient()
84 | };
85 | }
86 | }
87 | }
88 |
--------------------------------------------------------------------------------
/tests/Microsoft.Graph.DotnetCore.Core.Test/TestModels/ServiceModels/TestResourceData.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | namespace Microsoft.Graph
6 | {
7 | using System;
8 | using System.Collections.Generic;
9 | using Microsoft.Kiota.Abstractions.Serialization;
10 |
11 | ///
12 | /// The type ResourceData.
13 | ///
14 | public partial class TestResourceData : IParsable, IAdditionalDataHolder
15 | {
16 |
17 | ///
18 | /// Gets or sets additional data.
19 | ///
20 | public IDictionary AdditionalData
21 | {
22 | get; set;
23 | }
24 |
25 | ///
26 | /// Gets or sets @odata.type.
27 | ///
28 | public string ODataType
29 | {
30 | get; set;
31 | }
32 |
33 | ///
34 | /// Gets the field deserializers for the instance
35 | ///
36 | ///
37 | public IDictionary> GetFieldDeserializers()
38 | {
39 | return new Dictionary>
40 | {
41 | {"@odata.type", (n) => { ODataType = n.GetStringValue(); } },
42 | };
43 | }
44 |
45 | ///
46 | /// Serialize the instance
47 | ///
48 | /// The to serialize the instance
49 | /// Thrown when the writer is null
50 | public void Serialize(ISerializationWriter writer)
51 | {
52 | _ = writer ?? throw new ArgumentNullException(nameof(writer));
53 | writer.WriteStringValue("@odata.type", ODataType);
54 | writer.WriteAdditionalData(AdditionalData);
55 | }
56 |
57 |
58 | ///
59 | /// Creates a new instance of the appropriate class based on discriminator value
60 | /// The parse node to use to read the discriminator value and create the object
61 | ///
62 | public static TestResourceData CreateFromDiscriminatorValue(IParseNode parseNode)
63 | {
64 | _ = parseNode ?? throw new ArgumentNullException(nameof(parseNode));
65 | return new TestResourceData();
66 | }
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/tests/Microsoft.Graph.DotnetCore.Core.Test/TestModels/ServiceModels/TestSubscription.cs:
--------------------------------------------------------------------------------
1 | // ------------------------------------------------------------------------------
2 | // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3 | // ------------------------------------------------------------------------------
4 |
5 | namespace Microsoft.Graph.DotnetCore.Core.Test.TestModels.ServiceModels
6 | {
7 | using System;
8 | using System.Collections.Generic;
9 | using Microsoft.Kiota.Abstractions.Serialization;
10 |
11 | public class TestSubscription : IEncryptableSubscription, IParsable, IAdditionalDataHolder
12 | {
13 | ///
14 | /// Gets or sets encryption certificate.
15 | /// A base64-encoded representation of a certificate with a public key used to encrypt resource data in change notifications. Optional. Required when includeResourceData is true.
16 | ///
17 | public string EncryptionCertificate
18 | {
19 | get; set;
20 | }
21 |
22 | ///
23 | /// Gets or set the additional data bag.
24 | ///
25 | public IDictionary AdditionalData { get; set; } = new Dictionary();
26 |
27 | ///
28 | /// Gets the field deserializers for the instance
29 | ///
30 | ///
31 | public IDictionary> GetFieldDeserializers()
32 | {
33 | return new Dictionary>
34 | {
35 | {"encryptionCertificate", (n) => { EncryptionCertificate = n.GetStringValue(); } },
36 | };
37 | }
38 |
39 | ///
40 | /// Serialize the instance
41 | ///
42 | /// The to serialize the instance
43 | /// Thrown when the writer is null
44 | public void Serialize(ISerializationWriter writer)
45 | {
46 | _ = writer ?? throw new ArgumentNullException(nameof(writer));
47 | writer.WriteStringValue("encryptionCertificate", EncryptionCertificate);
48 | writer.WriteAdditionalData(AdditionalData);
49 | }
50 |
51 | ///
52 | /// Creates a new instance of the appropriate class based on discriminator value
53 | /// The parse node to use to read the discriminator value and create the object
54 | ///
55 | public static TestSubscription CreateFromDiscriminatorValue(IParseNode parseNode)
56 | {
57 | _ = parseNode ?? throw new ArgumentNullException(nameof(parseNode));
58 | return new TestSubscription();
59 | }
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/tests/Microsoft.Graph.DotnetCore.Core.Test/ms-logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoftgraph/msgraph-sdk-dotnet-core/aee58489ff89d89ea20ed3825224a6339858d980/tests/Microsoft.Graph.DotnetCore.Core.Test/ms-logo.png
--------------------------------------------------------------------------------
/tests/Microsoft.Graph.DotnetCore.Core.Test/xunit.runner.json:
--------------------------------------------------------------------------------
1 | {
2 | "parallelizeAssembly": false,
3 | "parallelizeTestCollections": false
4 | }
--------------------------------------------------------------------------------
/tests/Microsoft.Graph.DotnetCore.Core.Trimming/Microsoft.Graph.DotnetCore.Core.Trimming.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | Exe
4 | net9.0
5 | enable
6 | enable
7 | true
8 | true
9 | false
10 | true
11 | true
12 | IL3000
13 |
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/tests/Microsoft.Graph.DotnetCore.Core.Trimming/Program.cs:
--------------------------------------------------------------------------------
1 | namespace Microsoft.Graph.DotnetCore.Core.Trimming;
2 |
3 | class Program
4 | {
5 | static void Main(string[] args)
6 | {
7 | Console.WriteLine("Hello, World!");
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/tests/Microsoft.Graph.DotnetCore.Core.Trimming/global.json:
--------------------------------------------------------------------------------
1 | {
2 | "sdk": {
3 | "version": "9.0.102", /* https://github.com/dotnet/maui/wiki/.NET-7-and-.NET-MAUI */
4 | "rollForward": "major"
5 | }
6 | }
7 |
--------------------------------------------------------------------------------