Skip to content

CSHARP4040: Fix bug when using field with same element name as discriminator #1684

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 17 additions & 2 deletions src/MongoDB.Bson/Serialization/BsonClassMap.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1317,16 +1317,31 @@ public void UnmapProperty(string propertyName)
/// Gets the discriminator convention for the class.
/// </summary>
/// <returns>The discriminator convention for the class.</returns>
internal IDiscriminatorConvention GetDiscriminatorConvention()
internal IDiscriminatorConvention GetDiscriminatorConvention(bool checkConflicts = false)
Copy link
Contributor Author

Choose a reason for hiding this comment

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

I tried to find a place where to check that there are no conflicts with the other fields element names. I decided to do it here so it's done once and not continuously when serializing objects.
For now checkConflicts is true only when GetDiscriminatorConvention is called in BsonClassMapSerializer.SerializeDiscriminator (that is used only when serializing classes).
I'm not sure this is the optimal place for this, and if it would be worth throwing also when deserializing, for instance.

Copy link
Contributor

Choose a reason for hiding this comment

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

Why would we ever NOT check for conflicts? Why do we even need the checkConflicts parameter?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

We discussed on slack, but I've removed the parameter and moved the conflict checking inside so that it is run once and not all the time the method is called.

{
// return a cached discriminator convention when possible
var discriminatorConvention = _discriminatorConvention;
if (discriminatorConvention == null)
{
// it's possible but harmless for multiple threads to do the discriminator convention lookukp at the same time
// it's possible but harmless for multiple threads to do the discriminator convention lookup at the same time
discriminatorConvention = LookupDiscriminatorConvention();
_discriminatorConvention = discriminatorConvention;
}

if (checkConflicts && discriminatorConvention != null)
{
var conflictingMemberMap = _allMemberMaps.FirstOrDefault(memberMap => memberMap.ElementName == discriminatorConvention.ElementName);

if (conflictingMemberMap != null)
{
var fieldOrProperty = conflictingMemberMap.MemberInfo is FieldInfo ? "field" : "property";

throw new BsonSerializationException(
$"The {fieldOrProperty} {conflictingMemberMap.MemberName} of type '{_classType.FullName}' cannot use element name '{discriminatorConvention.ElementName}' " +
$"because it is already being used by the discriminator convention '{discriminatorConvention.GetType().Name}'.");
}
}

return discriminatorConvention;

IDiscriminatorConvention LookupDiscriminatorConvention()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,14 +39,19 @@ public abstract class StandardDiscriminatorConvention : IDiscriminatorConvention
/// <param name="elementName">The element name.</param>
protected StandardDiscriminatorConvention(string elementName)
{
if (elementName == null)
if (string.IsNullOrEmpty(elementName))
{
throw new ArgumentNullException("elementName");
throw new ArgumentNullException(nameof(elementName));
}
if (elementName.IndexOf('\0') != -1)
{
throw new ArgumentException("Element names cannot contain nulls.", "elementName");
throw new ArgumentException("Element names cannot be null or empty.", nameof(elementName));
Copy link
Contributor

Choose a reason for hiding this comment

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

throw new ArgumentException("Element names cannot contain nulls.", "elementName");

Should not have been changed.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yes, this should have gone for the previous condition.

Copy link
Contributor

Choose a reason for hiding this comment

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

Would you consider slightly more precise wording?

throw new ArgumentException("Discriminator element name cannot be null or empty.", nameof(elementName));

I think element name (singular) is better than plural.

Also, I prefer Discriminator element name to Element name because element names CAN be empty. It is only discriminator element names that cannot be empty (but that's an arbitrary limitation that we are imposing, in theory they could be empty because "" is an element name just as much as "_t" is).

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I also think it's more appropriate, I will change the wording also on the other exception.

}
if (elementName == "_id")
{
throw new ArgumentException("Element names cannot be '_id'.", nameof(elementName));
}

_elementName = elementName;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -637,7 +637,7 @@ private void SerializeExtraElements(BsonSerializationContext context, object obj

private void SerializeDiscriminator(BsonSerializationContext context, Type nominalType, object obj)
{
var discriminatorConvention = _classMap.GetDiscriminatorConvention();
var discriminatorConvention = _classMap.GetDiscriminatorConvention(true);
if (discriminatorConvention != null)
{
var actualType = obj.GetType();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,12 @@ public void TestConstructorThrowsWhenElementNameContainsNulls()
Assert.Throws<ArgumentException>(() => new ScalarDiscriminatorConvention("a\0b"));
}

[Fact]
public void TestConstructorThrowsWhenElementNameIsId()
{
Assert.Throws<ArgumentException>(() => new ScalarDiscriminatorConvention("_id"));
}

[Fact]
public void TestConstructorThrowsWhenElementNameIsNull()
{
Expand Down
50 changes: 50 additions & 0 deletions tests/MongoDB.Driver.Tests/Jira/Csharp4040Tests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/* Copyright 2010-present MongoDB Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

using FluentAssertions;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Bson.Serialization.Conventions;
using Xunit;

namespace MongoDB.Driver.Tests.Jira
{
public class Csharp4040Tests
{
private class BaseDocument
{
[BsonId] public ObjectId Id { get; set; } = ObjectId.GenerateNewId();

[BsonElement("_t")]
public string Field1 { get; set; }
}

private class DerivedDocument : BaseDocument {}

[Fact]
Copy link
Contributor Author

Choose a reason for hiding this comment

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

These tests can eventually be moved to somewhere more appropriate.

public void BsonClassMapSerializer_serialization_when_using_field_with_same_element_name_as_discriminator_should_throw()
{
var obj = new DerivedDocument { Field1 = "field1" };

var recordedException = Record.Exception(() => obj.ToJson(typeof(BaseDocument)));
recordedException.Should().NotBeNull();
recordedException.Should().BeOfType<BsonSerializationException>();
recordedException.Message.Should().Be("The property Field1 of type 'MongoDB.Driver.Tests.Jira.Csharp4040Tests+DerivedDocument' " +
"cannot use element name '_t' because it is already being used by " +
"the discriminator convention 'ScalarDiscriminatorConvention'.");
}
}
}