Skip to content

MissingMethodException on getting ResourceInstance from ODataResourceSerializer#2558

Open
komdil wants to merge 495 commits into
OData:masterfrom
komdil:resourceInstanseFix
Open

MissingMethodException on getting ResourceInstance from ODataResourceSerializer#2558
komdil wants to merge 495 commits into
OData:masterfrom
komdil:resourceInstanseFix

Conversation

@komdil

@komdil komdil commented Sep 1, 2021

Copy link
Copy Markdown
Contributor

Issues

This pull request fixes issue #2557.

Description

Adding constructor param on generic SelectExpandWrapper class for setting instance of resource

Checklist (Uncheck if it is not completed)

  • Test cases added
  • Build and test with one-click build and test script passed

Additional work necessary

If documentation update is needed, please add "Docs Needed" label to the issue and provide details about the required document change in the issue.

xuzhg and others added 30 commits July 17, 2018 14:17
 (OData#1560)

* Don't assume port 80 when generating nextLink in ASP.NET Core OData#1559

If the port isn't set on `request.Host`, port 80 was assumed previously.
If the app is running behind a reverse proxy, and the port was not forwarded,
this can result in invalid URLs - for example an https URL using port 80
Instead, we just omit the port completely if it's not explictly set.

* Add unit tests for GetNextPageLink

* Add copyright notice
…#1588)

- Null check on ODataQueryParameterBindingAttribute for Net Core
This is a regression from 5.x to 6.x/7.x. It looks like the original fix was
never merged to the 6.0 development branch.

Issue: OData#736
- Add comma before MyLevel property.
This is addresses the unhelpful error message described in this GitHub issue:

OData#1421
Improving the error message for when an unknown property is deserialized
…a#1628)

* Enable adding members to collection of complex types

* Fix deserialization for primitive types

The ODataPrimitiveDeserializer did not support non-trivial (that cannot be cast directly from the string representation) primitive types like Binary, GUIDS, Spatial etc.

* Support cast uri as well

* Pass the type reference to ODL to parse correctly

* Do not use ConvertPrimitiveValue, add unit test for ODataPrimitiveDeserializer

* Fix unit tests

* Add unit tests for propertyrouting changes

* Undo unnecessary changes

* Add E2E test for PostToCollections

Add E2E test for PostToCollections

* typo

* E2E case for collection of Enums

* Keep original and add another testcase

* Account for the additional property on the test cases

* Add test cases for Binary and Guids

* Make the private helper functions for Enum deserialization tests accessible for other classes

* New E2E cases for posting to collection of complex type with inheritance

* Add more test cases for trivial primitive values

* Add a new date time object to a collection property

* Do not imply unique identifiers

* Change the response from Created to Ok to avoid exception, response is yet to be discussed

* fix spacing errors

* Fix Unit test

* Remove test case for the time being because of difference in behavior locally and on server

* Address self reviewed issues

* Improve the enum test case

* Address Sam's comments on the PR

* remove extra whitespace

* Add testcase to return representation

* Add using to Netcore as well

* Address more PR comments

* Address last of the PR comments
1. Update the Microsoft.Data.OData vulnerability to 5.8.4
2. Update the Microsoft.AspNetCore.All to 2.0.9
3. Update the Microsoft.AspNetCore.Server.Kestrel.* to 2.0.4
* Allow ODataFeature.TotalCount set to null.

* CR update: set this.totalCountSet = value.HasValue.
* Respect preference header for specifying maxpagesize

* Don't set pagesize in the enable query code; instead wait till options to maintain parity

* Fix single get request issue

* Revert "Merge branch 'Respect-preference-header-for-paging' of https://github.com/KanishManuja-MS/WebApi into Respect-preference-header-for-paging"

This reverts commit 14a45de, reversing
changes made to 338d857.

* Update src/Microsoft.AspNet.OData.Shared/RequestPreferenceHelpers.cs

* Fix for classic version

* fix aspnet oddities

* Update src/Microsoft.AspNet.OData.Shared/RequestPreferenceHelpers.cs

* Use String instead of string to avoid performance build error

* Address PR comments

* Update src/Microsoft.AspNet.OData.Shared/RequestPreferenceHelpers.cs

* Fix spacing
…Data#1618)

* Take and Top query use wrong Provider.CreateQuery Method OData#1617

* Bugfix: Cast to IProviderInterface before scanning for the methods

* Based on review feedback, method searching is now cached
* For individual query options, pass in the container so that global config is available.

* CR comments.
* Update src/Microsoft.AspNetCore.OData/Extensions/ODataApplicationBuilderExtensions.cs

* Update public API bsl
@komdil

komdil commented Sep 6, 2021

Copy link
Copy Markdown
Contributor Author

I couldn't solve the tests. I think someone needs to take a look.
I think BuildResourceInstance is working wrong because it is trying to create an instance of the resource.
The instance was already created. It may cause a lot of problems (performance). One of the big problems:
It is creating instances of resources and setting property. What if the property setter will not allow it or have autocorrect. For example,
Return only one instance from controller
Put this logic:

static bool alreadySet;
        string firstName;
        public string FirstName
        {
            get
            {
                return firstName;
            }
            set
            {
                if (alreadySet)
                {
                    throw new InvalidOperationException("Do not set it again!");
                }
                firstName = value;
                alreadySet = true;
            }
        }

Send query https://localhost:5001/oData/Student?$select=Id,FirstName

It will throw exception from DeserializationHelpers.SetProperty(resource, propertyName, value); 261 line ResourceContext.cs

@xuzhg I think these changes were made by you.

Dilshod Komilov added 2 commits September 6, 2021 14:07

@KenitoInc KenitoInc left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems this PR is addressing a specific use case for you.
In the next release of WebApi Aspnetcore v8.x, we will have the ability to inject a custom implementation of the SelectExpandBinder (PR). That should work for you.

@komdil

komdil commented Sep 23, 2021

Copy link
Copy Markdown
Contributor Author

It seems this PR is addressing a specific use case for you.
In the next release of WebApi Aspnetcore v8.x, we will have the ability to inject a custom implementation of the SelectExpandBinder (PR). That should work for you.

Maybe, but I am using v7.x. Is it possible to merge that branch in version 7.x also?

@KenitoInc

Copy link
Copy Markdown
Contributor

It seems this PR is addressing a specific use case for you.
In the next release of WebApi Aspnetcore v8.x, we will have the ability to inject a custom implementation of the SelectExpandBinder (PR). That should work for you.

Maybe, but I am using v7.x. Is it possible to merge that branch in version 7.x also?

@xuzhg @gathogojr What do you think?

@komdil

komdil commented Sep 30, 2021

Copy link
Copy Markdown
Contributor Author

It seems this PR is addressing a specific use case for you.
In the next release of WebApi Aspnetcore v8.x, we will have the ability to inject a custom implementation of the SelectExpandBinder (PR). That should work for you.

Maybe, but I am using v7.x. Is it possible to merge that branch in version 7.x also?

@xuzhg @gathogojr What do you think?

I am seeing Activator.CreateInstanse on BuildResource method on v.8x also. I think the problem exists on v.8x also

Expression.Constant(_modelID);
wrapperTypeMemberAssignments.Add(Expression.Bind(wrapperProperty, wrapperPropertyValueExpression));

bool instanseOfWrapperClassWasSet = false;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

super nit: spelling "instance"


// Assert
IEnumerator enumerator = queryable.GetEnumerator();
IEnumerator _querableEnumerator = _queryable.GetEnumerator();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IEnumerator implements IDisposable. Please wrap this in a using block

corranrogue9
corranrogue9 previously approved these changes Oct 18, 2021
return Expression.MemberInit(Expression.New(wrapperType), wrapperTypeMemberAssignments);

if (instanseOfWrapperClassWasSet)
return Expression.MemberInit(Expression.New(wrapperType), wrapperTypeMemberAssignments);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

as per code guidelines, please enclose body of conditional in braces (even if it's a single line). Improves code readability and reduces introducing logical errors later.

@pull-request-quantifier-deprecated

Copy link
Copy Markdown

This PR has 34 quantified lines of changes. In general, a change size of upto 200 lines is ideal for the best PR experience!


Quantification details

Label      : Extra Small
Size       : +21 -13
Percentile : 13.6%

Total files changed: 4

Change summary by file extension:
.cs : +21 -13

Change counts above are quantified counts, based on the PullRequestQuantifier customizations.

Why proper sizing of changes matters

Optimal pull request sizes drive a better predictable PR flow as they strike a
balance between between PR complexity and PR review overhead. PRs within the
optimal size (typical small, or medium sized PRs) mean:

  • Fast and predictable releases to production:
    • Optimal size changes are more likely to be reviewed faster with fewer
      iterations.
    • Similarity in low PR complexity drives similar review times.
  • Review quality is likely higher as complexity is lower:
    • Bugs are more likely to be detected.
    • Code inconsistencies are more likely to be detetcted.
  • Knowledge sharing is improved within the participants:
    • Small portions can be assimilated better.
  • Better engineering practices are exercised:
    • Solving big problems by dividing them in well contained, smaller problems.
    • Exercising separation of concerns within the code changes.

What can I do to optimize my changes

  • Use the PullRequestQuantifier to quantify your PR accurately
    • Create a context profile for your repo using the context generator
    • Exclude files that are not necessary to be reviewed or do not increase the review complexity. Example: Autogenerated code, docs, project IDE setting files, binaries, etc. Check out the Excluded section from your prquantifier.yaml context profile.
    • Understand your typical change complexity, drive towards the desired complexity by adjusting the label mapping in your prquantifier.yaml context profile.
    • Only use the labels that matter to you, see context specification to customize your prquantifier.yaml context profile.
  • Change your engineering behaviors
    • For PRs that fall outside of the desired spectrum, review the details and check if:
      • Your PR could be split in smaller, self-contained PRs instead
      • Your PR only solves one particular issue. (For example, don't refactor and code new features in the same PR).

How to interpret the change counts in git diff output

  • One line was added: +1 -0
  • One line was deleted: +0 -1
  • One line was modified: +1 -1 (git diff doesn't know about modified, it will
    interpret that line like one addition plus one deletion)
  • Change percentiles: Change characteristics (addition, deletion, modification)
    of this PR in relation to all other PRs within the repository.


Was this comment helpful? 👍  :ok_hand:  :thumbsdown: (Email)
Customize PullRequestQuantifier for this repository.

@Sreejithpin

Copy link
Copy Markdown
Contributor

@komdil Can you please look at the review comments., thanks

@komdil

komdil commented Dec 9, 2021

Copy link
Copy Markdown
Contributor Author

@komdil Can you please look at the review comments., thanks

@Sreejithpin The tests are failing. It looks this solution will not work for solving this problem. I don't have next steps

@corranrogue9

Copy link
Copy Markdown
Contributor

@komdil, I'd like to help out and take a look, but it seems that I can't kick off a new build. Do you mind re-running the checks?

@KenitoInc

Copy link
Copy Markdown
Contributor

@komdil
These is how expressions are generated using a few examples

GET http://localhost:6143/odata/Books?$select=Title

$it => new SelectSome`1() 
    {
        ModelID = value(Microsoft.AspNet.OData.Query.Expressions.LinqParameterContainer+TypedLinqParameterContainer`1[System.String]).TypedProperty,
        Container = new NamedPropertyWithNext0`1() 
        {
            Name = "Title",
            Value = $it.Title,
            Next0 = new AutoSelectedNamedProperty`1() 
            {
                Name = "Id",
                Value = Convert($it.Id, Nullable`1)
            }
        }
    }

GET http://localhost:6143/odata/Books?$select=*

$it => new SelectAll`1() {
    ModelID = value(Microsoft.AspNet.OData.Query.Expressions.LinqParameterContainer+TypedLinqParameterContainer`1[System.String]).TypedProperty,
    Instance = $it,
    UseInstanceForProperties = True
    }
}

GET http://localhost:6143/odata/Books?$expand=Authors

$it => new SelectAllAndExpand`1() 
    {
        ModelID = value(Microsoft.AspNet.OData.Query.Expressions.LinqParameterContainer+TypedLinqParameterContainer`1[System.String]).TypedProperty,
        Instance = $it,
        UseInstanceForProperties = True,
        Container = new NamedProperty`1() 
            {
                Name = "Authors",
                Value = $it.Authors.Select($it => new SelectAll`1() 
                    {
                        ModelID = value(Microsoft.AspNet.OData.Query.Expressions.LinqParameterContainer+TypedLinqParameterContainer`1[System.String]).TypedProperty,
                        Instance = $it,
                        UseInstanceForProperties = True
                    }
                )
            }
    }

We don't set the Instance in all scenarios.
For example in $Select=Title, we don't need the Books instance since we have the Title in the Container.

Your PR introduces an Instance property in all scenarios.

@xuzhg xuzhg force-pushed the master branch 2 times, most recently from 4c43a84 to ddfd3dd Compare May 29, 2026 01:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.