Skip to content

Commit

Permalink
Merge pull request #474 from brjohnstmsft/polyfixrb
Browse files Browse the repository at this point in the history
Adding custom polymorphic discriminator support
  • Loading branch information
stankovski committed Nov 10, 2015
2 parents 4143b3a + 42ec4c4 commit 4eb52d0
Show file tree
Hide file tree
Showing 34 changed files with 492 additions and 237 deletions.
15 changes: 13 additions & 2 deletions AutoRest/Generators/CSharp/CSharp.Tests/AcceptanceTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1030,10 +1030,13 @@ public void ComplexTests()
var polymorphismResult = client.Polymorphism.GetValid() as Salmon;
Assert.NotNull(polymorphismResult);
Assert.Equal("alaska", polymorphismResult.Location);
Assert.True(polymorphismResult.Siblings[0] is Shark);
Assert.True(polymorphismResult.Siblings[1] is Sawshark);
Assert.Equal(3, polymorphismResult.Siblings.Count);
Assert.IsType(typeof(Shark), polymorphismResult.Siblings[0]);
Assert.IsType(typeof(Sawshark), polymorphismResult.Siblings[1]);
Assert.IsType(typeof(Goblinshark), polymorphismResult.Siblings[2]);
Assert.Equal(6, ((Shark) polymorphismResult.Siblings[0]).Age);
Assert.Equal(105, ((Sawshark) polymorphismResult.Siblings[1]).Age);
Assert.Equal(1, ((Goblinshark)polymorphismResult.Siblings[2]).Age);
// PUT polymorphism/valid
var polymorphismRequest = new Salmon
{
Expand All @@ -1057,6 +1060,14 @@ public void ComplexTests()
Species = "dangerous",
Birthday = new DateTime(1900, 1, 5, 1, 0, 0, DateTimeKind.Utc),
Picture = new byte[] {255, 255, 255, 255, 254}
},
new Goblinshark()
{
Age = 1,
Length = 30,
Species = "scary",
Birthday = new DateTime(2015, 8, 8, 0, 0, 0, DateTimeKind.Utc),
Jawsize = 5
}
}
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,7 @@
<Compile Include="Utilities\MirrorTestHelpers.cs" />
<Compile Include="Utilities\MirroringHandler.cs" />
<Compile Include="Utilities\RecordedDelegatingHandler.cs" />
<Compile Include="SerializationTests.cs" />
<Compile Include="MirrorTests.cs" />
<Compile Include="Utilities\ServiceController.cs" />
<Compile Include="AcceptanceTestOrderer.cs" />
<Compile Include="Utilities\TestExtensions.cs" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,14 @@ public partial interface IPolymorphism
/// 'picture': new Buffer([255, 255, 255, 255,
/// 254]).toString('base64'),
/// 'species':'dangerous',
/// },
/// {
/// 'fishtype': 'goblin',
/// 'age': 1,
/// 'birthday': '2015-08-08T00:00:00Z',
/// 'length': 30.0,
/// 'species': 'scary',
/// 'jawsize': 5
/// }
/// ]
/// };
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.13.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.

namespace Fixtures.AcceptanceTestsBodyComplex.Models
{
using System;
using System.Linq;
using System.Collections.Generic;
using Newtonsoft.Json;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;

/// <summary>
/// </summary>
[JsonObject("goblin")]
public partial class Goblinshark : Shark
{
/// <summary>
/// Initializes a new instance of the Goblinshark class.
/// </summary>
public Goblinshark() { }

/// <summary>
/// Initializes a new instance of the Goblinshark class.
/// </summary>
public Goblinshark(int? jawsize = default(int?))
{
Jawsize = jawsize;
}

/// <summary>
/// </summary>
[JsonProperty(PropertyName = "jawsize")]
public int? Jawsize { get; set; }

/// <summary>
/// Validate the object. Throws ArgumentException or ArgumentNullException if validation fails.
/// </summary>
public override void Validate()
{
base.Validate();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,14 @@ public Polymorphism(AutoRestComplexTestService client)
/// 'picture': new Buffer([255, 255, 255, 255,
/// 254]).toString('base64'),
/// 'species':'dangerous',
/// },
/// {
/// 'fishtype': 'goblin',
/// 'age': 1,
/// 'birthday': '2015-08-08T00:00:00Z',
/// 'length': 30.0,
/// 'species': 'scary',
/// 'jawsize': 5
/// }
/// ]
/// };
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,14 @@ public static Fish GetValid(this IPolymorphism operations)
/// 'picture': new Buffer([255, 255, 255, 255,
/// 254]).toString('base64'),
/// 'species':'dangerous',
/// },
/// {
/// 'fishtype': 'goblin',
/// 'age': 1,
/// 'birthday': '2015-08-08T00:00:00Z',
/// 'length': 30.0,
/// 'species': 'scary',
/// 'jawsize': 5
/// }
/// ]
/// };
Expand Down Expand Up @@ -113,6 +121,14 @@ public static void PutValid(this IPolymorphism operations, Fish complexBody)
/// 'picture': new Buffer([255, 255, 255, 255,
/// 254]).toString('base64'),
/// 'species':'dangerous',
/// },
/// {
/// 'fishtype': 'goblin',
/// 'age': 1,
/// 'birthday': '2015-08-08T00:00:00Z',
/// 'length': 30.0,
/// 'species': 'scary',
/// 'jawsize': 5
/// }
/// ]
/// };
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,26 +4,21 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Fixtures.MirrorRecursiveTypes;
using System.Net.Http;
using Fixtures.MirrorPolymorphic;
using Fixtures.MirrorPolymorphic.Models;
using Fixtures.MirrorPrimitives;
using Fixtures.MirrorRecursiveTypes;
using Fixtures.MirrorSequences;
using Fixtures.MirrorSequences.Models;
using Microsoft.Rest.Modeler.Swagger.Tests;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Xunit;
using System.Net.Http;

namespace Microsoft.Rest.Generator.CSharp.Tests
{
[Collection("AutoRest Tests")]
public class MirrorTests
{

private static string ExpectedPath(string file)
{
return Path.Combine("Expected", file);
Expand Down Expand Up @@ -109,7 +104,10 @@ public void CanRoundTripSequences()
[Fact]
public void CanRoundtripPolymorphicTypes()
{
//SwaggerSpecHelper.RunTests<CSharpCodeGenerator>(SwaggerPath("Mirror\swagger-mirror-polymorphic.json",ExpectedPath("Mirror.Polymorphic.cs");
SwaggerSpecHelper.RunTests<CSharpCodeGenerator>(
SwaggerPath("swagger-mirror-polymorphic.json"),
ExpectedPath("Mirror.Polymorphic"));

var pets = new[]
{
new Animal {Description = "Pet Only", Id = "1"},
Expand Down Expand Up @@ -191,12 +189,12 @@ public void CanRoundtripFilledOutNestedTypesWithoutRecursion2()

public static void SendAndComparePolymorphicObjects(Animal expected)
{
if (expected == null)
if (expected == null)
{
throw new ArgumentNullException("expected");
}

using (var client = new PolymorphicAnimalStore(new Uri("http://localhost:3000"), new MirroringHandler()))
using (var client = new PolymorphicAnimalStore(new Uri("http://localhost:3000"), new MirroringHandler()))
{
var createdPet = client.CreateOrUpdatePolymorphicAnimals(expected);
Assert.NotNull(expected);
Expand All @@ -210,109 +208,4 @@ public static void SendAndComparePolymorphicObjects(Animal expected)
}
}
}

public class PolymorphicJsonSerializer<T> : JsonConverter
{
private readonly string _discriminatorField = "$type";

public PolymorphicJsonSerializer(string discriminatorField)
{
_discriminatorField = discriminatorField;
}

public override bool CanConvert(Type objectType)
{
return typeof (T).IsAssignableFrom(objectType);
}

public override object ReadJson(JsonReader reader,
Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotSupportedException();
}

public override void WriteJson(JsonWriter writer,
object value, JsonSerializer serializer)
{
if (value == null)
{
throw new ArgumentNullException("value");
}

if (writer == null)
{
throw new ArgumentNullException("writer");
}

if (serializer == null)
{
throw new ArgumentNullException("serializer");
}

string typeName = value.GetType().Name;
if (value.GetType().GetCustomAttributes<JsonObjectAttribute>().Any())
{
typeName = value.GetType().GetCustomAttribute<JsonObjectAttribute>().Id;
}

writer.WriteStartObject();
writer.WritePropertyName(_discriminatorField);
writer.WriteValue(typeName);

PropertyInfo[] properties = value.GetType().GetProperties();
foreach (var property in properties.Where(p => p.SetMethod != null))
{
string propertyName = property.Name;
if (property.GetCustomAttributes<JsonPropertyAttribute>().Any())
{
propertyName = property.GetCustomAttribute<JsonPropertyAttribute>().PropertyName;
}
writer.WritePropertyName(propertyName);
serializer.Serialize(writer, property.GetValue(value, null));
}
writer.WriteEndObject();
}
}

public class PolymorphicJsonDeserializer<T> : JsonConverter
{
private readonly string _discriminatorField = "$type";

public PolymorphicJsonDeserializer(string discriminatorField)
{
_discriminatorField = discriminatorField;
}

public override bool CanConvert(Type objectType)
{
return typeof (T) == objectType;
}

public override object ReadJson(JsonReader reader,
Type objectType, object existingValue, JsonSerializer serializer)
{
JObject item = JObject.Load(reader);
string typeDiscriminator = (string) item[_discriminatorField];
foreach (Type type in typeof (T).Assembly.GetTypes()
.Where(t => t.Namespace == typeof (T).Namespace && t != typeof (T)))
{
string typeName = type.Name;
if (type.GetCustomAttributes<JsonObjectAttribute>().Any())
{
typeName = type.GetCustomAttribute<JsonObjectAttribute>().Id;
}
if (typeName.Equals(typeDiscriminator, StringComparison.OrdinalIgnoreCase))
{
return item.ToObject(type, serializer);
}
}
return item.ToObject(objectType);
}

public override void WriteJson(JsonWriter writer,
object value, JsonSerializer serializer)
{
throw new NotSupportedException();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,14 @@ interface PolymorphismService {
'length':10.0,
'picture': new Buffer([255, 255, 255, 255, 254]).toString('base64'),
'species':'dangerous',
},
{
'fishtype': 'goblin',
'age': 1,
'birthday': '2015-08-08T00:00:00Z',
'length': 30.0,
'species': 'scary',
'jawsize': 5
}
]
};
Expand Down Expand Up @@ -114,6 +122,14 @@ interface PolymorphismService {
'length':10.0,
'picture': new Buffer([255, 255, 255, 255, 254]).toString('base64'),
'species':'dangerous',
},
{
'fishtype': 'goblin',
'age': 1,
'birthday': '2015-08-08T00:00:00Z',
'length': 30.0,
'species': 'scary',
'jawsize': 5
}
]
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,14 @@ private ServiceResponse<Fish> getValidDelegate(Response<ResponseBody> response,
'length':10.0,
'picture': new Buffer([255, 255, 255, 255, 254]).toString('base64'),
'species':'dangerous',
},
{
'fishtype': 'goblin',
'age': 1,
'birthday': '2015-08-08T00:00:00Z',
'length': 30.0,
'species': 'scary',
'jawsize': 5
}
]
};
Expand Down Expand Up @@ -148,6 +156,14 @@ public ServiceResponse<Void> putValid(Fish complexBody) throws ServiceException
'length':10.0,
'picture': new Buffer([255, 255, 255, 255, 254]).toString('base64'),
'species':'dangerous',
},
{
'fishtype': 'goblin',
'age': 1,
'birthday': '2015-08-08T00:00:00Z',
'length': 30.0,
'species': 'scary',
'jawsize': 5
}
]
};
Expand Down
Loading

0 comments on commit 4eb52d0

Please sign in to comment.