private object InstantiateProxy(CompositeType compositeType, Type proxyType, MockFactory mockFactory, MockStyle mockStyle, string name, object[] constructorArgs) { IInterceptor interceptor = new MockObjectInterceptor(mockFactory, compositeType, name, mockStyle); object[] activationArgs; /* ^ */ var _typeInfo = compositeType.PrimaryType.GetTypeInfo(); /* [email protected] ^ */ if (/* ^ */ _typeInfo.IsClass /* [email protected] ^ */) { activationArgs = new object[constructorArgs.Length + 1]; constructorArgs.CopyTo(activationArgs, 1); activationArgs[0] = new[] { interceptor }; } else { activationArgs = new[] { new[] { interceptor }, new object(), name }; } return Activator.CreateInstance(proxyType, activationArgs); }
public List<CompositeType> DoWork() { comm_sqlDataContext mylinq = new comm_sqlDataContext(); ISingleResult<adrbook> bb = mylinq.getdata(); var peoples = new List<CompositeType> (); foreach (adrbook cast in bb) { CompositeType p = new CompositeType(); p.Lid= cast.id; p.Ltype = cast.type; p.Lsubtype = cast.subtype; p.Llastname = cast.lastname; p.Lfirstname = cast.firstname; p.Lmiddlename = cast.middlename; p.Lpost = cast.post; p.Lemail1 = cast.email1; p.Lemail2 = cast.email2; p.Lroom = cast.room; p.Lphone1 = cast.phone1; p.Lphone2 = cast.phone2; p.Lphone3 = cast.phone3; peoples.Add(p); } return peoples; }
public MethodReference(CompositeType owner, string name, Prototype prototype) : this() { Owner = owner; Name = name; Prototype = prototype; }
protected MockObject(CompositeType mockedType, string name, IExpectationCollector expectationCollector, IInvocationListener invocationListener) { this.name = name; this.invocationListener = invocationListener; this.expectationCollector = expectationCollector; mockedTypes = mockedType; }
public void TestConstructorFailureNullItemNames() { CompositeType type = new CompositeType("TypeName", "TypeDescription", new string[] {"ItemName1", null}, new string[] {"ItemDescr1", "ItemDescr2"}, new OpenType[] { SimpleType.Integer, SimpleType.Double}); }
public override object CreateMock(MockFactory mockFactory, CompositeType typesToMock, string name, MockStyle mockStyle, object[] constructorArgs) { if (typesToMock == null) throw new ArgumentNullException("typesToMock"); Type primaryType = typesToMock.PrimaryType; Type[] additionalInterfaces = BuildAdditionalTypeArrayForProxyType(typesToMock); IInterceptor mockInterceptor = new MockObjectInterceptor(mockFactory, typesToMock, name, mockStyle); object result; /* ^ */ var _typeInfo = primaryType.GetTypeInfo(); /* [email protected] ^ */ if (/* ^ */ _typeInfo.IsInterface /* [email protected] ^ */) { result = generator.CreateInterfaceProxyWithoutTarget(primaryType, additionalInterfaces, new ProxyGenerationOptions {BaseTypeForInterfaceProxy = typeof (InterfaceMockBase)}, mockInterceptor); ((InterfaceMockBase) result).Name = name; } else { result = generator.CreateClassProxy(primaryType, additionalInterfaces, ProxyGenerationOptions.Default, constructorArgs, mockInterceptor); //return generator.CreateClassProxy(primaryType, new []{typeof(IMockObject)}, mockInterceptor); } return result; }
public CompositeType GetDataUsingDataContract(CompositeType composite) { if (composite.BoolValue) { composite.StringValue += "Suffix"; } return composite; }
/// <summary> /// Initializes a new instance of the <see cref="MockObject"/> class. /// </summary> /// <param name="mockFactory">The mockFactory.</param> /// <param name="mockedType">Type of the mocked.</param> /// <param name="name">The name.</param> /// <param name="mockStyle">The mock style.</param> protected MockObject(MockFactory mockFactory, CompositeType mockedType, string name, MockStyle mockStyle) { MockFactory = mockFactory; MockStyle = mockStyle; MockName = name; eventHandlers = new Dictionary<string, List<Delegate>>(); MockedTypes = mockedType; }
public CompositeType GetDataUsingDataContract(CompositeType composite) { Console.WriteLine(String.Format("GetDataUsingDataContract(Composite({0}, {1})", composite.BoolValue, composite.StringValue)); if (composite.BoolValue) { composite.StringValue += "Suffix"; } return composite; }
public CompositeType GetDataUsingDataContract(CompositeType composite) { if (composite == null) { throw new ArgumentNullException("composite"); } if (composite.BoolValue) { composite.StringValue += "Suffix"; } return composite; }
public void DisplayMessage(CompositeType composite) { string username = composite.Username ?? ""; string message = composite.Message ?? ""; // Dispatcher is here to take care of threads ownership over UI components Dispatcher.Invoke(() => { ChatHistory.Text += (username + ": " + message + Environment.NewLine); }); }
public void Ws2007HttpBindingTest() { using (var client = new ServiceClient("Ws2007HttpEndpoint")) { var input = new CompositeType { BoolValue = true, StringValue = "Hello, world!" }; var result = client.GetDataUsingDataContract(input); Assert.AreEqual<string>(input.StringValue + "Suffix", result.StringValue); Assert.AreEqual<bool>(input.BoolValue, result.BoolValue); } }
public void LoadFile(string filename) { XmlDocument document = new XmlDocument(); document.Load(filename); XmlNode compositeNode = document.SelectSingleNode(CompositeXPath); string rootNamespace = GetNodeValue(compositeNode, "@rootNamespace"); RootNamespace = rootNamespace; XmlNodeList types = document.SelectNodes(TypesXPath); foreach (XmlNode typeNode in types) { string typeName = GetNodeValue(typeNode, "@name"); string className = GetNodeValue(typeNode, "@className"); string theNamespace = GetNodeValue(typeNode, "@namespace"); if (!Namespaces.Contains(theNamespace)) { Namespaces.Add(theNamespace); } CompositeType compositeType = new CompositeType(typeName, className, theNamespace); Type foundType = FindType(className, theNamespace); foreach (PropertyInfo pi in foundType.GetProperties()) { if (pi.CanRead && pi.CanWrite) { CompositeProperty property = new CompositeProperty(typeName, pi.Name, pi.PropertyType); compositeType.Properties.Add(property); } } XmlNodeList hiddenNodes = typeNode.SelectNodes(PropertiesXPath); foreach (XmlNode propertyNode in hiddenNodes) { string propertyName = GetNodeValue(propertyNode, "@name"); string alias = GetNodeValue(propertyNode, "@alias"); bool isReadOnly = GetBooleanNodeValue(propertyNode, "@isReadOnly"); bool isHidden = GetBooleanNodeValue(propertyNode, "@isHidden"); CompositeProperty property = compositeType.Properties.FindCompositeProperty(typeName, propertyName); if (property != null) { if (!String.IsNullOrEmpty(alias)) { property.Alias = alias; } property.IsReadOnly = isReadOnly; property.IsHidden = isHidden; } } } }
public void JavaBytes_To_CompositeType() { // arrange var expected = new CassandraObject[] { (BytesType)_compositeType[0].GetValue<string>(), (BytesType)_compositeType[1].GetValue<long>() }; // act var actual = new CompositeType(); actual.SetValueFromBigEndian(_javaByteOrder); // assert Assert.True(expected.SequenceEqual((CassandraObject[])actual)); }
public void JavaBytes_To_CompositeType_WithHints() { // arrange // act var actual = new CompositeType(); actual.ComponentTypeHints = _compositeType.Select(t => t.GetType()).ToList(); actual.SetValueFromBigEndian(_javaByteOrder); // assert Assert.True(_compositeType.SequenceEqual((CassandraObject[])actual)); }
private async void GetCompositeType() { var serviceClient = new CompositeTypeServiceClient(); var arg = new CompositeType { StringValue = StringRequest, }; var res = await serviceClient.CompositeTypeAsync(arg); StringResponce = res.StringValue; }
private string CreateGetDataUsingDataContractRequest(CompositeType composite) { return String.Format(@"<?xml version=""1.0"" encoding=""utf-8""?> <s:Envelope xmlns:s=""http://schemas.xmlsoap.org/soap/envelope/""> <s:Body> <GetDataUsingDataContract xmlns=""http://tempuri.org/""> <composite xmlns:d4p1=""http://schemas.datacontract.org/2004/07/AppWithWCF"" xmlns:i=""http://www.w3.org/2001/XMLSchema-instance""> <d4p1:BoolValue>{0}</d4p1:BoolValue> <d4p1:StringValue>{1}</d4p1:StringValue> </composite> </GetDataUsingDataContract> </s:Body> </s:Envelope>", composite.BoolValue.ToString().ToLower(), composite.StringValue); }
public void Save_CompositeType() { // arrange var family = _db.GetColumnFamily(FamilyName); var expected = new CompositeType<LongType, UTF8Type>(300L, "string1"); // act family.InsertColumn(TestKey, expected, Math.PI); var value = family.Get(TestKey).Execute(); var actual = value.FirstOrDefault().Columns.FirstOrDefault(); // assert Assert.AreEqual((object)expected, (object)actual.ColumnName); }
public override object CreateMock(MockFactory mockFactory, CompositeType typesToMock, string name, MockStyle mockStyle, object[] constructorArgs) { _typesToMock = typesToMock; _typesToMock.Add(typeof(IMockObject)); var reflectiveInterceptor = new ReflectiveInterceptor(mockFactory, typesToMock, name, mockStyle); var proxy = CreateMock(reflectiveInterceptor, constructorArgs); if (_typesToMock.PrimaryType.IsInterface) ((InterfaceMockBase) proxy).Name = name; return proxy; }
public void SaveCompositeType() { CompositeType value = new CompositeType(); value.Foo = "foobar"; value.Bar.A = 5; value.Bar.B = 10; value.Bar.C = "hello \"world\"!"; Dom dom = Dom.Serialise(value); string output = dom.Save(); string expected = "SaveTest+CompositeType {\n Foo: String \"foobar\",\n Bar: SaveTest+NonParsable {\n A: Int32 \"5\",\n B: Single \"10\",\n C: String \"hello \\\"world\\\"!\",\n D: null\n }\n}"; Assert.AreEqual(expected, output); }
public async Task<CompositeType> GetDataUsingDataContract(CompositeType composite) { var soapString = this.CreateGetDataUsingDataContractRequest(composite); using (var client = new HttpClient()) { client.DefaultRequestHeaders.Add("SOAPAction", "http://tempuri.org/IService1/GetDataUsingDataContract"); var content = new StringContent(soapString, Encoding.UTF8, "text/xml"); using (var response = await client.PostAsync(this.uri, content)) { string soapResponse = await response.Content.ReadAsStringAsync(); CompositeType result = this.ParseGetDataUsingDataContractResponse(soapResponse); return result; } } }
public void SaveCompositeTypeDictionary() { CompositeType value = new CompositeType(); value.Foo = "foobar"; value.Bar.A = 5; value.Bar.B = 10; value.Bar.C = "hello \"world\"!"; var dictionary = new Dictionary<CompositeType, CompositeType>() { { value, value } }; Dom dom = Dom.Serialise(dictionary); string output = dom.Save(); string expected = "Dictionary<SaveTest+CompositeType,SaveTest+CompositeType> [\n SaveTest+CompositeType {\n Foo: String \"foobar\",\n Bar: SaveTest+NonParsable {\n A: Int32 \"5\",\n B: Single \"10\",\n C: String \"hello \\\"world\\\"!\",\n D: null\n }\n }: SaveTest+CompositeType {\n Foo: String \"foobar\",\n Bar: SaveTest+NonParsable {\n A: Int32 \"5\",\n B: Single \"10\",\n C: String \"hello \\\"world\\\"!\",\n D: null\n }\n }\n]"; Assert.AreEqual(expected, output); }
public void Service1_GetDataUsingDataContract_CompositTypeBoolValueFalse_DoNotAppendSuffix() { // Arrange Wcf.Service1 service = new Service1(); string testString = "Test"; CompositeType ct = new CompositeType() { BoolValue = false, StringValue = testString }; // Act var result = service.GetDataUsingDataContract(ct); // Assert Assert.AreEqual(testString, result.StringValue); }
public void TestGetDataUsingDataContract() { using (RealWorldProxy client = new RealWorldProxy(realWorldEndpoint)) { client.Instance.ClientCredentials.UserName.UserName = "******"; client.Instance.ClientCredentials.UserName.Password = "******"; CompositeType data = new CompositeType() { BoolValue = true, StringValue = "Good", }; CompositeType result = client.Instance.GetDataUsingDataContract(data); Assert.Equal("GoodSuffix", result.StringValue); } using (RealWorldProxy client = new RealWorldProxy(realWorldEndpoint)) { client.Instance.ClientCredentials.UserName.UserName = "******"; client.Instance.ClientCredentials.UserName.Password = "******"; CompositeType data = new CompositeType() { BoolValue = false, StringValue = "Good", }; CompositeType result = client.Instance.GetDataUsingDataContract(data); Assert.Equal("Good", result.StringValue); } using (RealWorldProxy client = new RealWorldProxy(realWorldEndpoint)) { client.Instance.ClientCredentials.UserName.UserName = "******"; client.Instance.ClientCredentials.UserName.Password = "******"; try { CompositeType result = client.Instance.GetDataUsingDataContract(null); Assert.True(false, "Hey, I expect FaultException."); } catch (System.ServiceModel.FaultException) { Assert.True(true, "Very good, excepted."); } } }
/// <summary> /// Combines the specified types with the <see cref="IMockObject"/> into an array. /// </summary> /// <returns>An array of the specified types and <see cref="IMockObject"/>,</returns> protected static Type[] BuildAdditionalTypeArrayForProxyType(CompositeType compositeType) { List<Type> types = new List<Type>(); //IMockObject always needs to be first types.Add(typeof(IMockObject)); types.AddRange(compositeType.AdditionalInterfaceTypes); return types.ToArray(); /* if (compositeType.PrimaryType.IsInterface) { //The primary type is an interface so there is no need to check for explicit mapping types.AddRange(compositeType.AdditionalInterfaceTypes); } else { foreach (Type t in compositeType.AdditionalInterfaceTypes) { if (t.IsAssignableFrom(compositeType.PrimaryType)) { InterfaceMapping map = compositeType.PrimaryType.GetInterfaceMap(t); //if any members are public, the interface is not using explicit implementation if (map.TargetMethods.Any(info => info.IsPublic)) { //castle dynamic proxy can only have additionalInterfaceTypes that are not explicit implementation //see: http://www.mail-archive.com/[email protected]/msg04685.html types.Add(t); } } else { //add the type so it is generated in the proxy types.Add(t); } } } return types.ToArray(); */ }
public void Service1_GetDataUsingDataContract_CompositTypeBoolValueTrue_AppendSuffix() { // Arrange Wcf.Service1 service = new Service1(); string testString = "Test"; CompositeType ct = new CompositeType() { BoolValue = true, StringValue = testString }; var expected = testString + "Suffix"; // Act var result = service.GetDataUsingDataContract(ct); // Assert Assert.AreEqual(expected, result.StringValue); }
public CassandraObject CreateInstance() { if (_type == null) Init(); CassandraObject obj; if (_type == typeof(CompositeType)) obj = new CompositeType(_compositeTypes); else if (_type == typeof(DynamicCompositeType)) obj = new DynamicCompositeType(_dynamicCompositeType); else obj = Activator.CreateInstance(_type) as CassandraObject; if (obj == null) return null; return obj; }
public static void CustomBinding_DefaultSettings_Echo_RoundTrips_DataContract() { // Verifies a typed proxy can call a service operation echoing a DataContract object synchronously CustomBinding customBinding = null; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; EndpointAddress endpointAddress = null; CompositeType request = null; CompositeType response = null; try { // *** SETUP *** \\ customBinding = new CustomBinding(); customBinding.Elements.Add(new TextMessageEncodingBindingElement()); customBinding.Elements.Add(new HttpTransportBindingElement()); // Note the service interface used. It was manually generated with svcutil. endpointAddress = new EndpointAddress(Endpoints.DefaultCustomHttp_Address); factory = new ChannelFactory<IWcfService>(customBinding, endpointAddress); serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ request = new CompositeType() { StringValue = "myString", BoolValue = true }; response = serviceProxy.GetDataUsingDataContract(request); // *** VALIDATE *** \\ Assert.True(response != null, "GetDataUsingDataContract(request) returned null"); string expectedStringValue = request.StringValue + "Suffix"; Assert.True(String.Equals(response.StringValue, expectedStringValue), String.Format("Expected CompositeType.StringValue \"{0}\", actual was \"{1}\"", expectedStringValue, response.StringValue)); Assert.True(response.BoolValue == request.BoolValue, String.Format("Expected CompositeType.BoolValue \"{0}\", actual was \"{1}\"", request.BoolValue, response.BoolValue)); // *** CLEANUP *** \\ factory.Close(); ((ICommunicationObject)serviceProxy).Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } }
static void Main(string[] args) { using (var wcfProxy = new RestfulServiceClient()) { var data = wcfProxy.GetJsonData(value: "1"); data = wcfProxy.GetXmlData(value: "2"); var compositeInstance = new CompositeType { BoolValue = true, StringValue = "new data from consoleUI" }; CompositeType result = wcfProxy.AddData(composite: compositeInstance); Console.WriteLine("Press any key to exit ..."); Console.ReadKey(); } }
public static void CustomBinding_DefaultSettings_Echo_RoundTrips_DataContract() { // Verifies a typed proxy can call a service operation echoing a DataContract object synchronously StringBuilder errorBuilder = new StringBuilder(); try { CustomBinding customBinding = new CustomBinding(); customBinding.Elements.Add(new TextMessageEncodingBindingElement()); customBinding.Elements.Add(new HttpTransportBindingElement()); // Note the service interface used. It was manually generated with svcutil. ChannelFactory<IWcfService> factory = new ChannelFactory<IWcfService>(customBinding, new EndpointAddress(Endpoints.DefaultCustomHttp_Address)); IWcfService serviceProxy = factory.CreateChannel(); CompositeType request = new CompositeType() { StringValue = "myString", BoolValue = true }; CompositeType response = serviceProxy.GetDataUsingDataContract(request); Assert.True(response != null, "GetDataUsingDataContract(request) returned null"); string expectedStringValue = request.StringValue + "Suffix"; if (!string.Equals(response.StringValue, expectedStringValue)) { errorBuilder.AppendLine(string.Format("Expected CompositeType.StringValue \"{0}\", actual was \"{1}\"", expectedStringValue, response.StringValue)); } if (response.BoolValue != request.BoolValue) { errorBuilder.AppendLine(string.Format("Expected CompositeType.BoolValue \"{0}\", actual was \"{1}\"", request.BoolValue, response.BoolValue)); } factory.Close(); } catch (Exception ex) { errorBuilder.AppendLine(String.Format("Unexpected exception was caught: {0}", ex.ToString())); } Assert.True(errorBuilder.Length == 0, errorBuilder.ToString()); }
/// <exception cref="ArgumentNullException"> /// <paramref name="parent"/> is null. /// </exception> internal CSharpField(CompositeType parent) : this("newField", parent) { }
public CompositeType GetDataUsingDataContract(CompositeType composite) { return(base.Channel.GetDataUsingDataContract(composite)); }
/// <exception cref="BadSyntaxException"> /// The <paramref name="name" /> does not fit to the syntax. /// </exception> /// <exception cref="ArgumentException"> /// The language of <paramref name="parent" /> does not equal. /// </exception> /// <exception cref="ArgumentNullException"> /// <paramref name="parent" /> is null. /// </exception> internal JavaField(string name, CompositeType parent) : base(name, parent) { }
public System.Threading.Tasks.Task <CompositeType> GetDataUsingDataContractAsync(CompositeType composite) { return(base.Channel.GetDataUsingDataContractAsync(composite)); }
private static ICompositeData ExtractCompositeValue(CompositeType openType, CompositeData compositeData) { return(new CompositeDataSupport(openType, compositeData.Properties.Select(x => x.Name), compositeData.Properties.Select(x => ExtractSimpleValue(openType.GetOpenType(x.Name), x.Value)))); }
private static CompositeData FormatCompositeValue(CompositeType compositeType, ICompositeData compositeData) { return(new CompositeData(compositeType.KeySet.Select(x => new CompositeDataProperty(x, FormatSimpleValue(compositeType.GetOpenType(x), compositeData[x]))))); }
/// <exception cref="ArgumentException"> /// The language of <paramref name="parent" /> does not equal. /// </exception> /// <exception cref="ArgumentNullException"> /// <paramref name="parent" /> is null. /// </exception> internal CSharpConstructor(CompositeType parent) : base(parent) { }
public AzureCompositeTypeModel(CompositeType compositeType, string package) : this(package) { this.LoadFrom(compositeType); }
public void ResourceIsFlattenedForComplexResource() { var serviceClient = new ServiceClient(); serviceClient.BaseUrl = "https://petstore.swagger.wordnik.com"; serviceClient.ApiVersion = "1.0.0"; serviceClient.Documentation = "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification"; serviceClient.Name = "Swagger Petstore"; var getPet = new Method(); var resource = new CompositeType(); var resourceProperties = new CompositeType(); var dogProperties = new CompositeType(); var dog = new CompositeType(); serviceClient.Methods.Add(getPet); resource.Name = "resource"; resource.SerializedName = "resource"; resource.Properties.Add(new Property { Name = "id", SerializedName = "id", Type = new PrimaryType(KnownPrimaryType.String), IsRequired = true }); resource.Properties.Add(new Property { Name = "location", SerializedName = "location", Type = new PrimaryType(KnownPrimaryType.String), IsRequired = true }); resource.Properties.Add(new Property { Name = "name", SerializedName = "name", Type = new PrimaryType(KnownPrimaryType.String), IsRequired = true }); resource.Properties.Add(new Property { Name = "tags", SerializedName = "tags", Type = new SequenceType { ElementType = new PrimaryType(KnownPrimaryType.String) }, IsRequired = true }); resource.Properties.Add(new Property { Name = "type", SerializedName = "type", Type = new PrimaryType(KnownPrimaryType.String), IsRequired = true }); resourceProperties.Name = "resourceProperties"; resourceProperties.SerializedName = "resourceProperties"; resourceProperties.Properties.Add(new Property { Name = "parent", SerializedName = "parent", Type = new PrimaryType(KnownPrimaryType.Long), IsRequired = true }); dogProperties.Name = "dogProperties"; dogProperties.SerializedName = "dogProperties"; dogProperties.BaseModelType = resourceProperties; dogProperties.Properties.Add(new Property { Name = "id", SerializedName = "id", Type = new PrimaryType(KnownPrimaryType.Long), IsRequired = true }); dogProperties.Properties.Add(new Property { Name = "name", SerializedName = "name", Type = new PrimaryType(KnownPrimaryType.String), IsRequired = true }); dog.Name = "dog"; dog.SerializedName = "dog"; dog.BaseModelType = resource; var dogPropertiesProperty = new Property { Name = "properties", SerializedName = "properties", Type = dogProperties, IsRequired = true }; dogPropertiesProperty.Extensions[Generator.Extensions.FlattenExtension] = true; dog.Properties.Add(dogPropertiesProperty); dog.Properties.Add(new Property { Name = "pedigree", SerializedName = "pedigree", Type = new PrimaryType(KnownPrimaryType.Boolean), IsRequired = true }); getPet.ReturnType = new Response(dog, null); serviceClient.ModelTypes.Add(resource); serviceClient.ModelTypes.Add(dogProperties); serviceClient.ModelTypes.Add(resourceProperties); serviceClient.ModelTypes.Add(dog); var codeGen = new SampleAzureCodeGenerator(new Settings()); codeGen.NormalizeClientModel(serviceClient); Assert.Equal(3, serviceClient.ModelTypes.Count); Assert.Equal("dog", serviceClient.ModelTypes.First(m => m.Name == "dog").Name); Assert.Equal(4, serviceClient.ModelTypes.First(m => m.Name == "dog").Properties.Count); Assert.Equal("dog_id", serviceClient.ModelTypes.First(m => m.Name == "dog").Properties[1].Name); Assert.Equal("dog_name", serviceClient.ModelTypes.First(m => m.Name == "dog").Properties[2].Name); Assert.Equal("pedigree", serviceClient.ModelTypes.First(m => m.Name == "dog").Properties[0].Name); Assert.Equal("parent", serviceClient.ModelTypes.First(m => m.Name == "dog").Properties[3].Name); }
public static string ConstructMapper(this IModelType type, string serializedName, IVariable parameter, bool isPageable, bool expandComposite) { var builder = new IndentedStringBuilder(" "); string defaultValue = null; bool isRequired = false; bool isConstant = false; bool isReadOnly = false; Dictionary <Constraint, string> constraints = null; var property = parameter as Property; if (parameter != null) { defaultValue = parameter.DefaultValue; isRequired = parameter.IsRequired; isConstant = parameter.IsConstant; constraints = parameter.Constraints; } if (property != null) { isReadOnly = property.IsReadOnly; } CompositeType composite = type as CompositeType; if (composite != null && composite.ContainsConstantProperties && (parameter != null && parameter.IsRequired)) { defaultValue = "{}"; } SequenceType sequence = type as SequenceType; DictionaryType dictionary = type as DictionaryType; PrimaryType primary = type as PrimaryType; EnumType enumType = type as EnumType; builder.AppendLine("").Indent(); if (isRequired) { builder.AppendLine("required: true,"); } else { builder.AppendLine("required: false,"); } if (isReadOnly) { builder.AppendLine("readOnly: true,"); } if (isConstant) { builder.AppendLine("isConstant: true,"); } if (serializedName != null) { builder.AppendLine("serializedName: '{0}',", serializedName); } if (defaultValue != null) { builder.AppendLine("defaultValue: {0},", defaultValue); } if (constraints != null && constraints.Count > 0) { builder.AppendLine("constraints: {").Indent(); var keys = constraints.Keys.ToList <Constraint>(); for (int j = 0; j < keys.Count; j++) { var constraintValue = constraints[keys[j]]; if (keys[j] == Constraint.Pattern) { constraintValue = $"'{constraintValue}'"; } if (j != keys.Count - 1) { builder.AppendLine("{0}: {1},", keys[j], constraintValue); } else { builder.AppendLine("{0}: {1}", keys[j], constraintValue); } } builder.Outdent().AppendLine("},"); } // Add type information if (primary != null) { switch (primary.KnownPrimaryType) { case KnownPrimaryType.Boolean: builder.AppendLine("type: {").Indent().AppendLine("name: 'Boolean'").Outdent().AppendLine("}"); break; case KnownPrimaryType.Int: case KnownPrimaryType.Long: case KnownPrimaryType.Decimal: case KnownPrimaryType.Double: builder.AppendLine("type: {").Indent().AppendLine("name: 'Number'").Outdent().AppendLine("}"); break; case KnownPrimaryType.String: builder.AppendLine("type: {").Indent().AppendLine("name: 'String'").Outdent().AppendLine("}"); break; case KnownPrimaryType.Uuid: builder.AppendLine("type: {").Indent().AppendLine("name: 'String'").Outdent().AppendLine("}"); break; // case KnownPrimaryType.Uuid: // builder.AppendLine("type: {").Indent().AppendLine("name: 'Uuid'").Outdent().AppendLine("}"); //break; case KnownPrimaryType.ByteArray: builder.AppendLine("type: {").Indent().AppendLine("name: 'ByteArray'").Outdent().AppendLine("}"); break; case KnownPrimaryType.Base64Url: builder.AppendLine("type: {").Indent().AppendLine("name: 'Base64Url'").Outdent().AppendLine("}"); break; case KnownPrimaryType.Date: builder.AppendLine("type: {").Indent().AppendLine("name: 'Date'").Outdent().AppendLine("}"); break; case KnownPrimaryType.DateTime: builder.AppendLine("type: {").Indent().AppendLine("name: 'DateTime'").Outdent().AppendLine("}"); break; case KnownPrimaryType.DateTimeRfc1123: builder.AppendLine("type: {").Indent().AppendLine("name: 'DateTimeRfc1123'").Outdent().AppendLine("}"); break; case KnownPrimaryType.TimeSpan: builder.AppendLine("type: {").Indent().AppendLine("name: 'TimeSpan'").Outdent().AppendLine("}"); break; case KnownPrimaryType.UnixTime: builder.AppendLine("type: {").Indent().AppendLine("name: 'UnixTime'").Outdent().AppendLine("}"); break; case KnownPrimaryType.Object: builder.AppendLine("type: {").Indent().AppendLine("name: 'Object'").Outdent().AppendLine("}"); break; case KnownPrimaryType.Stream: builder.AppendLine("type: {").Indent().AppendLine("name: 'Stream'").Outdent().AppendLine("}"); break; default: throw new NotImplementedException(string.Format(Resources.InvalidType, primary)); } } else if (enumType != null) { if (enumType.ModelAsString) { builder.AppendLine("type: {").Indent().AppendLine("name: 'String'").Outdent().AppendLine("}"); } else { builder.AppendLine("type: {") .Indent() .AppendLine("name: 'Enum',") .AppendLine("allowedValues: {0}", enumType.GetEnumValuesArray()) .Outdent() .AppendLine("}"); } } else if (sequence != null) { builder.AppendLine("type: {") .Indent() .AppendLine("name: 'Sequence',") .AppendLine("element: {") .Indent() .AppendLine("{0}", sequence.ElementType.ConstructMapper(sequence.ElementType.DeclarationName + "ElementType", null, false, false)) .Outdent().AppendLine("}").Outdent().AppendLine("}"); } else if (dictionary != null) { builder.AppendLine("type: {") .Indent() .AppendLine("name: 'Dictionary',") .AppendLine("value: {") .Indent() .AppendLine("{0}", dictionary.ValueType.ConstructMapper(dictionary.ValueType.DeclarationName + "ElementType", null, false, false)) .Outdent().AppendLine("}").Outdent().AppendLine("}"); } else if (composite != null) { builder.AppendLine("type: {") .Indent() .AppendLine("name: 'Composite',"); if (composite.IsPolymorphic) { builder = ConstructPolymorphicDiscriminator(composite, builder); } if (!expandComposite) { builder.AppendLine("className: '{0}'", composite.Name).Outdent().AppendLine("}"); } else { builder.AppendLine("className: '{0}',", composite.Name) .AppendLine("modelProperties: {").Indent(); var composedPropertyList = new List <Property>(composite.ComposedProperties); for (var i = 0; i < composedPropertyList.Count; i++) { var prop = composedPropertyList[i]; var serializedPropertyName = prop.SerializedName; PropertyInfo nextLinkName = null; string nextLinkNameValue = null; if (isPageable) { var itemName = composite.GetType().GetProperty("ItemName"); nextLinkName = composite.GetType().GetProperty("NextLinkName"); nextLinkNameValue = (string)nextLinkName.GetValue(composite); if (itemName != null && ((string)itemName.GetValue(composite) == prop.Name)) { serializedPropertyName = ""; } if (prop.Name.Contains("nextLink") && nextLinkName != null && nextLinkNameValue == null) { continue; } } if (i != composedPropertyList.Count - 1) { if (!isPageable) { builder.AppendLine("{0}: {{{1}}},", prop.Name, prop.ModelType.ConstructMapper(serializedPropertyName, prop, false, false)); } else { // if pageable and nextlink is also present then we need a comma as nextLink would be the next one to be added if (nextLinkNameValue != null) { builder.AppendLine("{0}: {{{1}}},", prop.Name, prop.ModelType.ConstructMapper(serializedPropertyName, prop, false, false)); } else { builder.AppendLine("{0}: {{{1}}}", prop.Name, prop.ModelType.ConstructMapper(serializedPropertyName, prop, false, false)); } } } else { builder.AppendLine("{0}: {{{1}}}", prop.Name, prop.ModelType.ConstructMapper(serializedPropertyName, prop, false, false)); } } // end of modelProperties and type builder.Outdent().AppendLine("}").Outdent().AppendLine("}"); } } else { throw new NotImplementedException(string.Format(Resources.InvalidType, type)); } return(builder.ToString()); }
private string GetPagingSetting(CodeModelPya codeModel, CompositeType body, Dictionary <string, object> extensions, IModelType valueType, IDictionary <int, string> typePageClasses, string methodName) { string valueTypeName = valueType.Name; var ext = extensions[AzureExtensions.PageableExtension] as JContainer; var ignoreNextLink = false; if ((ext["nextLinkName"] != null) && (ext["nextLinkName"].Type == JTokenType.Null)) { ignoreNextLink = true; } var nextLinkName = (string)ext["nextLinkName"] ?? "nextLink"; var itemName = (string)ext["itemName"] ?? "value"; // nextLinkName = nextLinkName.Replace(".", "\\\\."); // itemName = itemName.Replace(".", "\\\\."); var findNextLink = false; var findItem = false; foreach (var property in body.ComposedProperties) { var propName = property.SerializedName; if (propName == nextLinkName) { findNextLink = true; nextLinkName = property.SerializedName = property.SerializedName.Replace(".", "\\\\.")?.Replace("\\\\\\\\", "\\\\"); } else if (propName == itemName) { findItem = true; itemName = property.SerializedName = property.SerializedName.Replace(".", "\\\\.")?.Replace("\\\\\\\\", "\\\\"); } if (propName == nextLinkName.Replace(".", "\\\\.")?.Replace("\\\\\\\\", "\\\\")) { nextLinkName = nextLinkName.Replace(".", "\\\\.")?.Replace("\\\\\\\\", "\\\\"); findNextLink = true; } else if (propName == itemName.Replace(".", "\\\\.")?.Replace("\\\\\\\\", "\\\\")) { itemName = itemName.Replace(".", "\\\\.")?.Replace("\\\\\\\\", "\\\\"); findItem = true; } } if (!findItem) { throw new KeyNotFoundException("Couldn't find the item property specified by extension"); } string className; var hash = (nextLinkName + "#" + itemName).GetHashCode(); if (!typePageClasses.ContainsKey(hash)) { className = (string)ext["className"]; if (string.IsNullOrEmpty(className)) { if (typePageClasses.Count > 0) { className = valueTypeName + string.Format(CultureInfo.InvariantCulture, "Paged{0}", typePageClasses.Count); } else { className = valueTypeName + "Paged"; } } typePageClasses.Add(hash, className); } className = typePageClasses[hash]; ext["className"] = className; var pageModel = new PagePya(className, nextLinkName, itemName, valueType); if (!codeModel.PageModels.Contains(pageModel)) { codeModel.PageModels.Add(pageModel); } return(className); }
/// <summary> /// Parse a ResourceSchemaModel from the provided ServiceClient. /// </summary> /// <param name="serviceClient"></param> /// <returns></returns> public static IDictionary <string, ResourceSchema> Parse(CodeModel serviceClient, string version) { if (serviceClient == null) { throw new ArgumentNullException(nameof(serviceClient)); } Dictionary <string, ResourceSchema> resourceSchemas = new Dictionary <string, ResourceSchema>(); foreach (Method method in serviceClient.Methods.Where(method => method.Parameters.FirstOrDefault(p => p.SerializedName == "api-version")?.DefaultValue.Value == version || version == serviceClient.ApiVersion)) { if (method.HttpMethod != HttpMethod.Put || string.IsNullOrWhiteSpace(method.Url) || !resourceMethodPrefixRx.IsMatch(method.Url) || !method.Url.EndsWith("}", StringComparison.OrdinalIgnoreCase)) { continue; } string afterPrefix = method.Url.Substring(resourceMethodPrefixRx.Match(method.Url).Length); int forwardSlashIndexAfterProvider = afterPrefix.IndexOf('/'); string resourceProvider = afterPrefix.Substring(0, forwardSlashIndexAfterProvider); if (IsPathVariable(resourceProvider)) { // If the resourceProvider is a path variable, such as {someValue}, then this // is not a create resource method. Skip it. continue; } // extract API version string apiVersion = serviceClient.ApiVersion.Else(method.Parameters.FirstOrDefault(p => p.SerializedName == "api-version")?.DefaultValue); if (string.IsNullOrWhiteSpace(apiVersion)) { throw new ArgumentException("No API version is provided in the swagger document or the method."); } ResourceSchema resourceSchema; if (!resourceSchemas.ContainsKey(resourceProvider)) { resourceSchema = new ResourceSchema(); resourceSchema.Id = string.Format(CultureInfo.InvariantCulture, "https://schema.management.azure.com/schemas/{0}/{1}.json#", apiVersion, resourceProvider); resourceSchema.Title = resourceProvider; resourceSchema.Description = resourceProvider.Replace('.', ' ') + " Resource Types"; resourceSchema.Schema = "http://json-schema.org/draft-04/schema#"; resourceSchemas.Add(resourceProvider, resourceSchema); } else { resourceSchema = resourceSchemas[resourceProvider]; } string methodUrlPathAfterProvider = afterPrefix.Substring(forwardSlashIndexAfterProvider + 1); string[] resourceTypes = ParseResourceTypes(resourceProvider, methodUrlPathAfterProvider, method); foreach (string resourceType in resourceTypes) { JsonSchema resourceDefinition = new JsonSchema(); resourceDefinition.JsonType = "object"; resourceDefinition.ResourceType = resourceType; // get the resource name parameter, e.g. {fooName} var resNameParam = methodUrlPathAfterProvider.Substring(methodUrlPathAfterProvider.LastIndexOf('/') + 1); if (IsPathVariable(resNameParam)) { // strip the enclosing braces resNameParam = resNameParam.Trim(new[] { '{', '}' }); // look up the type var param = method.Parameters.Where(p => p.SerializedName == resNameParam).FirstOrDefault(); if (param != null) { // create a schema for it var nameParamSchema = ParseType(param.ClientProperty, param.ModelType, resourceSchema.Definitions, serviceClient.ModelTypes); nameParamSchema.ResourceType = resNameParam; // add it as the name property resourceDefinition.AddProperty("name", nameParamSchema, true); } } resourceDefinition.AddProperty("type", JsonSchema.CreateStringEnum(resourceType), true); resourceDefinition.AddProperty("apiVersion", JsonSchema.CreateStringEnum(apiVersion), true); if (method.Body != null) { CompositeType body = method.Body.ModelType as CompositeType; // Debug.Assert(body != null, "The create resource method's body must be a CompositeType and cannot be null."); if (body != null) { foreach (Property property in body.ComposedProperties) { if (property.SerializedName != null && !resourceDefinition.Properties.Keys.Contains(property.SerializedName)) { JsonSchema propertyDefinition = ParseType(property, property.ModelType, resourceSchema.Definitions, serviceClient.ModelTypes); if (propertyDefinition != null) { resourceDefinition.AddProperty(property.SerializedName, propertyDefinition, property.IsRequired || property.SerializedName == "properties"); } } } } } resourceDefinition.Description = resourceType; string resourcePropertyName = resourceType.Substring(resourceProvider.Length + 1).Replace('/', '_'); if (string.IsNullOrEmpty(resourcePropertyName)) { // System.Console.Error.WriteLine($"Skipping '{method.Url}' -- no resource type."); continue; } if (resourceSchema.ResourceDefinitions.ContainsKey(resourcePropertyName)) { // System.Console.Error.WriteLine($"Uh oh. '{resourcePropertyName}' -- duplicated?"); continue; } Debug.Assert(!resourceSchema.ResourceDefinitions.ContainsKey(resourcePropertyName)); resourceSchema.AddResourceDefinition(resourcePropertyName, resourceDefinition); } } // This loop adds child resource schemas to their parent resource schemas. We can't do // this until we're done adding all resources as top level resources, though, because // it's possible that we will parse a child resource before we parse the parent // resource. foreach (ResourceSchema resourceSchema in resourceSchemas.Values) { // By iterating over the reverse order of the defined resource definitions, I'm // counting on the resource definitions being in sorted order. That way I'm // guaranteed to visit child resource definitions before I visit their parent // resource definitions. By doing this, I've guaranteed that grandchildren resource // definitions will be added to their grandparent (and beyond) ancestor // resource definitions. foreach (string resourcePropertyName in resourceSchema.ResourceDefinitions.Keys.Reverse()) { JsonSchema resourceDefinition = resourceSchema.ResourceDefinitions[resourcePropertyName]; string resourceType = resourceDefinition.ResourceType; int lastSlashIndex = resourceType.LastIndexOf('/'); string parentResourceType = resourceType.Substring(0, lastSlashIndex); JsonSchema parentResourceDefinition = resourceSchema.GetResourceDefinitionByResourceType(parentResourceType); if (parentResourceDefinition != null) { string childResourceType = resourceType.Substring(lastSlashIndex + 1); JsonSchema childResourceDefinition = resourceDefinition.Clone(); childResourceDefinition.ResourceType = childResourceType; string childResourceDefinitionPropertyName = string.Join("_", resourcePropertyName, "childResource"); resourceSchema.AddDefinition(childResourceDefinitionPropertyName, childResourceDefinition); JsonSchema childResources; if (parentResourceDefinition.Properties.ContainsKey("resources")) { childResources = parentResourceDefinition.Properties["resources"]; } else { childResources = new JsonSchema() { JsonType = "array", Items = new JsonSchema() }; parentResourceDefinition.AddProperty("resources", childResources); } childResources.Items.AddOneOf(new JsonSchema() { Ref = "#/definitions/" + childResourceDefinitionPropertyName, }); } } } return(resourceSchemas); }
internal void InsertNewMember(MemberType type) { int fieldCount = CompositeType.FieldCount; switch (type) { case MemberType.Field: if (CompositeType.SupportsFields) { int index = Math.Min(ActiveMemberIndex + 1, fieldCount); bool changing = (index == fieldCount && ActiveMember.MemberType != MemberType.Field); CompositeType.InsertMember(MemberType.Field, index); ActiveMemberIndex = index; } break; case MemberType.Method: if (CompositeType.SupportsMethods) { int index = Math.Max(ActiveMemberIndex + 1, fieldCount); CompositeType.InsertMember(MemberType.Method, index); ActiveMemberIndex = index; } break; case MemberType.Constructor: if (CompositeType.SupportsConstuctors) { int index = Math.Max(ActiveMemberIndex + 1, fieldCount); CompositeType.InsertMember(MemberType.Constructor, index); ActiveMemberIndex = index; } break; case MemberType.Destructor: if (CompositeType.SupportsDestructors) { int index = Math.Max(ActiveMemberIndex + 1, fieldCount); CompositeType.InsertMember(MemberType.Destructor, index); ActiveMemberIndex = index; } break; case MemberType.Property: if (CompositeType.SupportsProperties) { int index = Math.Max(ActiveMemberIndex + 1, fieldCount); CompositeType.InsertMember(MemberType.Property, index); ActiveMemberIndex = index; } break; case MemberType.Event: if (CompositeType.SupportsEvents) { int index = Math.Max(ActiveMemberIndex + 1, fieldCount); CompositeType.InsertMember(MemberType.Event, index); ActiveMemberIndex = index; } break; } }
public static void ConstructMapper(TSObject mapper, IModelType type, string serializedName, IVariable parameter, bool isPageable, bool expandComposite, bool isXML, bool isCaseSensitive = true, string xmlName = null) { string defaultValue = null; bool isRequired = false; bool isConstant = false; bool isReadOnly = false; Dictionary <Constraint, string> constraints = null; var property = parameter as Property; if (parameter != null) { defaultValue = parameter.DefaultValue; isRequired = parameter.IsRequired; isConstant = parameter.IsConstant; constraints = parameter.Constraints; } string xmlPrefix = !isXML ? null : property?.XmlPrefix ?? type?.XmlPrefix; bool addXmlNameFromParameterValue = isXML && !string.IsNullOrEmpty(xmlName) && xmlName != serializedName; if (addXmlNameFromParameterValue) { if (!string.IsNullOrEmpty(xmlPrefix)) { xmlName = $"{xmlPrefix}:{xmlName}"; } mapper.QuotedStringProperty("xmlName", xmlName); } if (isXML && !string.IsNullOrEmpty(serializedName) && !string.IsNullOrEmpty(xmlPrefix)) { serializedName = $"{xmlPrefix}:{serializedName}"; } if (property != null) { isReadOnly = property.IsReadOnly; if (isXML) { if (property.XmlIsAttribute) { mapper.BooleanProperty("xmlIsAttribute", true); } if (property.XmlIsWrapped) { mapper.BooleanProperty("xmlIsWrapped", true); } string propertyXmlName = property.ModelType.XmlProperties?.Name ?? property.XmlName; if (!addXmlNameFromParameterValue && !string.IsNullOrEmpty(propertyXmlName)) { if (!string.IsNullOrEmpty(xmlPrefix)) { propertyXmlName = $"{xmlPrefix}:{propertyXmlName}"; } // For some reason we can't omit xmlName in this scenario if it is equal to // serializedName. It might have to do with whether or not xmlElementName // is present, but I'm not sure at this time. mapper.QuotedStringProperty("xmlName", propertyXmlName); } } } CompositeTypeTS composite = type as CompositeTypeTS; if (composite != null && composite.ContainsConstantProperties && (parameter != null && parameter.IsRequired)) { defaultValue = "{}"; } SequenceType sequence = type as SequenceType; if (sequence != null && isXML) { if (sequence.ElementXmlIsWrapped) { mapper.BooleanProperty("xmlElementIsWrapped", true); } string xmlElementName = sequence.ElementType.XmlProperties?.Name ?? sequence.ElementXmlName; if (!string.IsNullOrEmpty(xmlElementName)) { mapper.QuotedStringProperty("xmlElementName", xmlElementName); } } if (isRequired) { mapper.BooleanProperty("required", true); } if (parameter?.IsXNullable != null) { if (parameter.IsXNullable.Value) { mapper.BooleanProperty("nullable", true); } else { mapper.BooleanProperty("nullable", false); } } if (isReadOnly) { mapper.BooleanProperty("readOnly", true); } if (isConstant) { mapper.BooleanProperty("isConstant", true); } if (serializedName != null) { if (!isCaseSensitive) { serializedName = serializedName.ToLower(); } mapper.QuotedStringProperty("serializedName", serializedName); } if (!string.IsNullOrEmpty(defaultValue)) { mapper.TextProperty("defaultValue", defaultValue); } DictionaryType dictionary = type as DictionaryType; PrimaryType primary = type as PrimaryType; EnumType enumType = type as EnumType; void applyConstraints(TSObject obj) { bool useClientSideValidation = (bool)(Settings.Instance?.CustomSettings[CodeModelTS.ClientSideValidationSettingName] ?? false); if (useClientSideValidation && constraints != null && constraints.Any()) { obj.ObjectProperty("constraints", constraintsObject => { foreach (KeyValuePair <Constraint, string> constraintEntry in constraints) { Constraint constraint = constraintEntry.Key; string constraintValue = constraintEntry.Value; if (constraint == Constraint.Pattern) { constraintValue = CreateRegexPatternConstraintValue(constraintValue); } constraintsObject.TextProperty(constraint.ToString(), constraintValue); } }); } } // Apply header collection constraints only to dictionary values, not the dictionary itself string prefix = parameter?.Extensions?.GetValue <string>(SwaggerExtensions.HeaderCollectionPrefix); bool skipConstraints = !string.IsNullOrEmpty(prefix) && dictionary != null; if (!skipConstraints) { applyConstraints(mapper); } if (primary != null) { switch (primary.KnownPrimaryType) { case KnownPrimaryType.Base64Url: case KnownPrimaryType.Boolean: case KnownPrimaryType.ByteArray: case KnownPrimaryType.Date: case KnownPrimaryType.DateTime: case KnownPrimaryType.DateTimeRfc1123: case KnownPrimaryType.Object: case KnownPrimaryType.Stream: case KnownPrimaryType.String: case KnownPrimaryType.TimeSpan: case KnownPrimaryType.UnixTime: case KnownPrimaryType.Uuid: AddTypeProperty(mapper, primary.KnownPrimaryType.ToString()); break; case KnownPrimaryType.Int: case KnownPrimaryType.Long: case KnownPrimaryType.Decimal: case KnownPrimaryType.Double: AddTypeProperty(mapper, "Number"); break; default: throw new NotImplementedException($"{primary} is not a supported Type."); } } else if (enumType != null) { if (enumType.ModelAsString) { AddTypeProperty(mapper, "String"); } else { AddTypeProperty(mapper, "Enum", typeObject => { typeObject.ArrayProperty("allowedValues", allowedValues => { foreach (EnumValue enumValue in enumType.Values) { allowedValues.QuotedString(enumValue.SerializedName); } }); }); } } else if (sequence != null) { AddTypeProperty(mapper, "Sequence", typeObject => { typeObject.Property("element", element => { ConstructMapper(element, sequence.ElementType, null, null, false, false, isXML, isCaseSensitive); }); }); } else if (dictionary != null) { AddTypeProperty(mapper, "Dictionary", typeObject => { typeObject.ObjectProperty("value", dictionaryValue => { ConstructMapper(dictionaryValue, dictionary.ValueType, null, null, false, false, isXML, isCaseSensitive); applyConstraints(dictionaryValue); }); }); if (!string.IsNullOrEmpty(prefix)) { mapper.QuotedStringProperty("headerCollectionPrefix", prefix); } } else if (composite != null) { AddTypeProperty(mapper, "Composite", typeObject => { if (expandComposite) { if (composite.IsPolymorphic) { // Note: If the polymorphicDiscriminator has a dot in it's name then do not escape that dot for // it's serializedName, the way it is done for other properties. This makes it easy to find the // discriminator property from the responseBody during deserialization. Please, do not get confused // between the definition of the discriminator and the definition of the property that is // marked as the discriminator. typeObject.ObjectProperty("polymorphicDiscriminator", polymorphicDiscriminator => { polymorphicDiscriminator.QuotedStringProperty("serializedName", composite.PolymorphicDiscriminator); polymorphicDiscriminator.QuotedStringProperty("clientName", Singleton <CodeNamerTS> .Instance.GetPropertyName(composite.PolymorphicDiscriminator)); }); typeObject.QuotedStringProperty("uberParent", composite.Name); } else { CompositeType baseType = composite; while (baseType.BaseModelType != null) { baseType = baseType.BaseModelType; } if (baseType.IsPolymorphic) { typeObject.TextProperty("polymorphicDiscriminator", baseType.Name + ".type.polymorphicDiscriminator"); typeObject.QuotedStringProperty("uberParent", baseType.Name); } } } typeObject.QuotedStringProperty("className", composite.Name); if (expandComposite) { typeObject.ObjectProperty("modelProperties", modelProperties => { if (composite.BaseModelType != null && composite.BaseModelType.ComposedProperties.Any()) { modelProperties.Spread(composite.BaseModelType.Name + ".type.modelProperties"); } foreach (Property prop in composite.Properties) { var serializedPropertyName = prop.SerializedName; if (isPageable) { PropertyInfo itemName = composite.GetType().GetProperty("ItemName"); PropertyInfo nextLinkName = composite.GetType().GetProperty("NextLinkName"); string nextLinkNameValue = (string)nextLinkName.GetValue(composite); if (itemName != null && ((string)itemName.GetValue(composite) == prop.Name)) { serializedPropertyName = ""; } if (prop.Name.Contains("nextLink") && nextLinkName != null && nextLinkNameValue == null) { continue; } } if (modelProperties.ContainsProperty(prop.Name)) { // throw new InvalidOperationException($"Mapper \"{serializedName}\" contains multiple modelProperties with the name \"{prop.Name}\"."); } else { modelProperties.Property(prop.Name, propertyValue => ConstructMapper(propertyValue, prop.ModelType, serializedPropertyName, prop, false, false, isXML, isCaseSensitive)); } } }); } if (composite.AdditionalProperties != null) { typeObject.ObjectProperty("additionalProperties", additionalProperties => { ConstructMapper(additionalProperties, composite.AdditionalProperties, serializedName: null, parameter: null, isPageable: false, expandComposite: false, isXML: isXML); }); } else { CompositeTypeTS baseType = composite; while (true) { baseType = (CompositeTypeTS)baseType.BaseModelType; if (baseType == null) { break; } else if (baseType.AdditionalProperties != null) { typeObject.TextProperty("additionalProperties", $"{baseType.Name}.type.additionalProperties"); break; } } } }); } else { throw new NotImplementedException($"{type} is not a supported Type."); } }
private static JsonSchema ParseCompositeType(Property property, CompositeType compositeType, bool includeBaseModelTypeProperties, IDictionary <string, JsonSchema> definitions, IEnumerable <CompositeType> modelTypes) { string definitionName = compositeType.Name; if (!definitions.ContainsKey(definitionName)) { JsonSchema definition = new JsonSchema() { JsonType = "object", Description = compositeType.Documentation, }; // This definition must be added to the definition map before we start parsing // its properties because its properties may recursively reference back to this // definition. definitions.Add(definitionName, definition); IEnumerable <Property> compositeTypeProperties = includeBaseModelTypeProperties ? compositeType.ComposedProperties : compositeType.Properties; foreach (Property subProperty in compositeTypeProperties) { JsonSchema subPropertyDefinition = ParseType(subProperty, subProperty.ModelType, definitions, modelTypes); if (subPropertyDefinition != null) { definition.AddProperty(subProperty.SerializedName.Else(subProperty.Name.RawValue), subPropertyDefinition, subProperty.IsRequired); } } string discriminatorPropertyName = compositeType.BasePolymorphicDiscriminator; if (!string.IsNullOrWhiteSpace(discriminatorPropertyName)) { definition.AddProperty(discriminatorPropertyName, new JsonSchema() { JsonType = "string" }, true); Func <CompositeType, bool> isSubTypeOrSelf = type => type == compositeType || type.BaseModelType == compositeType; CompositeType[] subTypes = modelTypes.Where(isSubTypeOrSelf).ToArray(); foreach (CompositeType subType in subTypes) { JsonSchema derivedTypeDefinitionRef = new JsonSchema(); JsonSchema discriminatorDefinition = new JsonSchema() { JsonType = "string" }; discriminatorDefinition.AddEnum(subType.SerializedName); derivedTypeDefinitionRef.AddProperty(discriminatorPropertyName, discriminatorDefinition); if (subType != compositeType) { // Sub-types are never referenced directly in the Swagger // discriminator scenario, so they wouldn't be added to the // produced resource schema. By calling ParseCompositeType() on the // sub-type we add the sub-type to the resource schema. ParseCompositeType(null, subType, false, definitions, modelTypes); derivedTypeDefinitionRef.AddAllOf(new JsonSchema() { Ref = "#/definitions/" + subType.Name, }); } definition.AddOneOf(derivedTypeDefinitionRef); } } } JsonSchema result = new JsonSchema() { Ref = "#/definitions/" + definitionName }; if (property != null) { result.Description = RemovePossibleValuesFromDescription(property.Documentation); } return(result); }
private void AssertComposite(CompositeType compositeType) { Assert.IsNotNull(compositeType); Assert.IsTrue(compositeType.BoolValue); Assert.AreEqual("TestSuffix", compositeType.StringValue); }
/// <exception cref="ArgumentNullException"> /// <paramref name="compositeType"/> is null. /// </exception> protected CompositeTypeShape(CompositeType compositeType) : base(compositeType) { }
public abstract AbstractType Create(CompositeType parent, Enum product, string name);
/// <summary> /// Checks whether model should be excluded from producing. /// </summary> /// <param name="model">The model.</param> /// <returns>True if should be excluded, false otherwise.</returns> protected virtual bool ExcludeModel(CompositeType model) { return(false); }
/// <exception cref="ArgumentNullException"> /// <paramref name="parent" /> is null. /// </exception> internal JavaField(CompositeType parent) : this("newField", parent) { }
/// <summary> /// Adds the parameter groups to operation parameters. /// </summary> /// <param name="serviceClient"></param> public static void AddParameterGroups(ServiceClient serviceClient) { if (serviceClient == null) { throw new ArgumentNullException("serviceClient"); } foreach (Method method in serviceClient.Methods) { //This group name is normalized by each languages code generator later, so it need not happen here. Dictionary <string, Dictionary <Property, Parameter> > parameterGroups = new Dictionary <string, Dictionary <Property, Parameter> >(); foreach (Parameter parameter in method.Parameters) { if (parameter.Extensions.ContainsKey(ParameterGroupExtension)) { Newtonsoft.Json.Linq.JContainer extensionObject = parameter.Extensions[ParameterGroupExtension] as Newtonsoft.Json.Linq.JContainer; if (extensionObject != null) { string parameterGroupName = method.Group + "-" + method.Name + "-" + "Parameters"; parameterGroupName = extensionObject.Value <string>("name") ?? parameterGroupName; if (!parameterGroups.ContainsKey(parameterGroupName)) { parameterGroups.Add(parameterGroupName, new Dictionary <Property, Parameter>()); } Property groupProperty = new Property() { IsReadOnly = false, //Since these properties are used as parameters they are never read only Name = parameter.Name, IsRequired = parameter.IsRequired, DefaultValue = parameter.DefaultValue, //Constraints = parameter.Constraints, Omit these since we don't want to perform parameter validation Documentation = parameter.Documentation, Type = parameter.Type, SerializedName = null //Parameter is never serialized directly }; parameterGroups[parameterGroupName].Add(groupProperty, parameter); } } } foreach (string parameterGroupName in parameterGroups.Keys) { //Define the new parameter group type (it's always a composite type) CompositeType parameterGroupType = new CompositeType() { Name = parameterGroupName, Documentation = "Additional parameters for the " + method.Name + " operation." }; //Populate the parameter group type with properties. foreach (Property property in parameterGroups[parameterGroupName].Keys) { parameterGroupType.Properties.Add(property); } //Add to the service client serviceClient.ModelTypes.Add(parameterGroupType); bool isGroupParameterRequired = parameterGroupType.Properties.Any(p => p.IsRequired); //Create the new parameter object based on the parameter group type Parameter parameterGroup = new Parameter() { Name = parameterGroupName, IsRequired = isGroupParameterRequired, Location = ParameterLocation.None, SerializedName = string.Empty, Type = parameterGroupType, Documentation = "Additional parameters for the operation" }; method.Parameters.Add(parameterGroup); //Link the grouped parameters to their parent, and remove them from the method parameters foreach (Property property in parameterGroups[parameterGroupName].Keys) { Parameter p = parameterGroups[parameterGroupName][property]; method.InputParameterMappings.Add(new ParameterMapping { InputParameter = parameterGroup, OutputParameter = p, InputParameterProperty = property.Name }); method.Parameters.Remove(p); } } } }
internal CSharpMethod(CompositeType parent) : this("NewMethod", parent) { }
/// <exception cref="BadSyntaxException"> /// The <paramref name="name"/> does not fit to the syntax. /// </exception> /// <exception cref="ArgumentException"> /// The language of <paramref name="parent"/> does not equal. /// </exception> internal CSharpMethod(string name, CompositeType parent) : base(name, parent) { }
public void ExternalResourceTypeIsNullSafe() { var serviceClient = new ServiceClient(); serviceClient.BaseUrl = "https://petstore.swagger.wordnik.com"; serviceClient.ApiVersion = "1.0.0"; serviceClient.Documentation = "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification"; serviceClient.Name = "Swagger Petstore"; var resource = new CompositeType(); var resourceProperties = new CompositeType(); serviceClient.ModelTypes.Add(resource); serviceClient.ModelTypes.Add(resourceProperties); resource.Name = "resource"; resource.Properties.Add(new Property { Name = "id", Type = new PrimaryType(KnownPrimaryType.String), IsRequired = true }); resource.Properties.Add(new Property { Name = "location", Type = new PrimaryType(KnownPrimaryType.String), IsRequired = true }); resource.Properties.Add(new Property { Name = "name", Type = new PrimaryType(KnownPrimaryType.String), IsRequired = true }); resource.Properties.Add(new Property { Name = "tags", Type = new SequenceType { ElementType = new PrimaryType(KnownPrimaryType.String) }, IsRequired = true }); resource.Properties.Add(new Property { Name = "type", Type = new PrimaryType(KnownPrimaryType.String), IsRequired = true }); resource.Extensions[AzureExtensions.AzureResourceExtension] = null; resourceProperties.Name = "resourceProperties"; resourceProperties.Properties.Add(new Property { Name = "parent", Type = new PrimaryType(KnownPrimaryType.Long), IsRequired = true }); var codeGen = new SampleAzureCodeGenerator(new Settings()); codeGen.NormalizeClientModel(serviceClient); Assert.Equal(2, serviceClient.ModelTypes.Count); }
/// <summary> /// Updates a composite type. /// Documentation https://developers.google.com/deploymentmanageralpha/alpha/reference/compositeTypes/update /// Generation Note: This does not always build corectly. Google needs to standardise things I need to figuer out which ones are wrong. /// </summary> /// <param name="service">Authenticated Deploymentmanageralpha service.</param> /// <param name="project">The project ID for this request.</param> /// <param name="compositeType">The name of the composite type for this request.</param> /// <param name="body">A valid Deploymentmanageralpha alpha body.</param> /// <returns>OperationResponse</returns> public static Operation Update(DeploymentmanageralphaService service, string project, string compositeType, CompositeType body) { try { // Initial validation. if (service == null) { throw new ArgumentNullException("service"); } if (body == null) { throw new ArgumentNullException("body"); } if (project == null) { throw new ArgumentNullException(project); } if (compositeType == null) { throw new ArgumentNullException(compositeType); } // Make the request. return(service.CompositeTypes.Update(body, project, compositeType).Execute()); } catch (Exception ex) { throw new Exception("Request CompositeTypes.Update failed.", ex); } }