public void AllTheThings() { var stopwatch = Stopwatch.StartNew(); var type = typeof(ComplexType); var assemblyName = new AssemblyName("Gu.State.Emit"); var asmBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); var moduleBuilder = asmBuilder.DefineDynamicModule("FieldAccessors"); var typeBuilder = moduleBuilder.DefineType($"{assemblyName.Name}.{type.Name}", TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.Abstract | TypeAttributes.Sealed); var field = type.GetField(nameof(ComplexType.value), BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); var setMethod = typeBuilder.DefineMethod($"set_{field.Name}", MethodAttributes.Public | MethodAttributes.Static, null, new[] { field.DeclaringType, field.FieldType }); var ilGenerator = setMethod.GetILGenerator(); ilGenerator.Emit(OpCodes.Ldarg_0); ilGenerator.Emit(OpCodes.Ldarg_1); ilGenerator.Emit(OpCodes.Stfld, field); ilGenerator.Emit(OpCodes.Ret); var getterMethod = typeBuilder.DefineMethod($"get_{field.Name}", MethodAttributes.Public | MethodAttributes.Static, field.FieldType, new[] { field.DeclaringType }); ilGenerator = getterMethod.GetILGenerator(); ilGenerator.Emit(OpCodes.Ldarg_0); ilGenerator.Emit(OpCodes.Ldfld, field); ilGenerator.Emit(OpCodes.Ret); var accessor = typeBuilder.CreateType(); var setter = (Action<ComplexType, int>)accessor.GetMethod($"set_{field.Name}").CreateDelegate(typeof(Action<ComplexType, int>)); var getter = (Func<ComplexType, int>)accessor.GetMethod($"get_{field.Name}").CreateDelegate(typeof(Func<ComplexType, int>)); var complexType = new ComplexType(); setter(complexType, 1); Assert.AreEqual(1, complexType.value); Console.WriteLine($"AllTheThings {stopwatch.Elapsed}"); }
public void AddComplexTypeSaveAndLoad() { // Setup var file = GetXmlFile(nameof(AddComplexTypeSaveAndLoad)); File.Delete(file); var set = new XmlSet<ComplexType>(file); // Execute var complex = new ComplexType { Description = "This is a test", Size = 42, Child = new SimpleType { Name = "Test", Value = 12.35, Price = 4.50m, Date = DateTime.Parse("9/1/2015") } }; set.Add(complex); set.Save(); var set2 = new XmlSet<ComplexType>(file); var result = set2.First(); // Assert Assert.AreEqual(complex.Description, result.Description); Assert.AreEqual(complex.Size, result.Size); Assert.IsNotNull(complex.Child); Assert.AreEqual(complex.Child.Name, result.Child.Name); Assert.AreEqual(complex.Child.Value, result.Child.Value); Assert.AreEqual(complex.Child.Price, result.Child.Price); Assert.AreEqual(complex.Child.Date, result.Child.Date); }
public void should_create_complex_type_with_dependency() { var dependency = new ComplexType(); var result = ObjectFactory.CreateInstance(typeof(ComplexTypeWithDependency).ToCachedType(), null, dependency); result.ShouldNotBeNull(); result.ShouldBeType<ComplexTypeWithDependency>(); ((ComplexTypeWithDependency)result).Dependency.ShouldEqual(dependency); }
public void CreateFromPropertyInfo() { var propertyInfo = typeof(ComplexType).GetProperty(nameof(ComplexType.Value)); var getterAndSetter = (GetterAndSetter<ComplexType, int>)GetterAndSetter.GetOrCreate(propertyInfo); var complexType = new ComplexType(); getterAndSetter.SetValue(complexType, 1); Assert.AreEqual(1, complexType.Value); Assert.AreEqual(1, getterAndSetter.GetValue(complexType)); }
public void CtorFieldInfo() { var fieldInfo = typeof(ComplexType).GetField(nameof(ComplexType.value)); var getterAndSetter = new GetterAndSetter<ComplexType, int>(fieldInfo); var complexType = new ComplexType(); getterAndSetter.SetValue(complexType, 1); Assert.AreEqual(1, complexType.Value); Assert.AreEqual(1, getterAndSetter.GetValue(complexType)); }
public void WhenPropertySubValueAssignedIsNotTheSameAsTheCurrentComplexValue_ItShouldNotNotify() { var value = new ComplexType(); ComplexViewModel.Complex = value; // initialize LastPropertyToChange.Should().Be("Complex"); LastPropertyToChange = null; var newValue = new ComplexType {Simple = new SimpleType {Id = 5}}; ComplexViewModel.Complex = newValue; // test LastPropertyToChange.Should().Be("Complex"); }
public ComplexFieldGenerator(FieldInfo fld) : base(fld) { _impl = _type = fld.DeclaringType.ParentConfig.ResolveName<ComplexType>( fld.DeclaringType, ((ComplexTypeRef)fld).TypeName ); if (_type is InterfaceType) _impl = ((InterfaceType) _type).Implementation; }
public void CreateAndDisposeComplexType() { var source = new ComplexType(); WeakReference weakReference = new WeakReference(source); var tracker = Track.Changes(source, ReferenceHandling.Structural); tracker.Dispose(); source = null; GC.Collect(); Assert.IsFalse(weakReference.IsAlive); Assert.NotNull(tracker); // touching it here so it is not optimized away. }
public void SetUsingExpressionSandbox() { var fieldInfo = typeof(ComplexType).GetField(nameof(ComplexType.value)); var source = Expression.Parameter(typeof(ComplexType)); var fieldExp = Expression.Field(source, fieldInfo); var value = Expression.Parameter(typeof(int)); var assign = Expression.Assign(fieldExp, value); var setter = Expression.Lambda<Action<ComplexType, int>>(assign, source, value).Compile(); var complexType = new ComplexType(); setter(complexType, 1); Assert.AreEqual(1, complexType.Value); }
/// <summary> /// Determines whether the complex type is or derives from the specified complex type. /// </summary> /// <param name="complexType">Complex Type to check against.</param> /// <returns> /// A value of <c>true</c> if this complex type is or derives from the specified complex type; otherwise, <c>false</c>. /// </returns> public bool IsKindOf(ComplexType complexType) { for (ComplexType thisType = this; thisType != null; thisType = thisType.BaseType) { if (thisType == complexType) { return true; } } return false; }
public void ConvertComplexTypeToObjectShouldWork() { var complexType = new ComplexType { String = "String", List = new List<string>(), IntDictionary = new Dictionary<int, string>() }; var result = ConvertToObjectHelper.ConvertStrongTypeToObject(complexType); Assert.Equal(typeof(Dictionary<string, object>), result.GetType()); Assert.Equal(typeof(object[]), ((Dictionary<string, object>)result)["List"].GetType()); Assert.Equal(typeof(Dictionary<string, object>), ((Dictionary<string, object>)result)["IntDictionary"].GetType()); }
public void Intersection_of_complex_types_comparing_instances_results_in_empty_set() { ComplexType[] left = new ComplexType[] { new ComplexType(1), new ComplexType(2), new ComplexType(3) }; ComplexType[] right = new ComplexType[] { new ComplexType(4), new ComplexType(5), new ComplexType(1) }; ComplexType[] intersection = ArrayUtil.Intersect(left, right, delegate(ComplexType a, ComplexType b) { return ReferenceEquals(a, b) ? 0 : 1; }); Assert.AreEqual(0, intersection.Length); }
public void Intersection_of_complex_types_based_on_comparison_delegate() { ComplexType[] left = new ComplexType[] { new ComplexType(1), new ComplexType(2), new ComplexType(3) }; ComplexType[] right = new ComplexType[] { new ComplexType(4), new ComplexType(5), new ComplexType(1) }; ComplexType[] intersection = ArrayUtil.Intersect(left, right, delegate(ComplexType a, ComplexType b) { return a.Value.CompareTo(b.Value); }); Assert.AreEqual(1, intersection.Length); Assert.AreEqual(1, intersection[0].Value); }
public void ComplexTypeIsSerializedAndDeserializedCorrectly() { var serializer = this.GetSerializer(); var value = new ComplexType { A = 5, B = 10, C = "hello" }; Assert.DoesNotThrow(() => serializer.Serialize(value)); var serializedValue = serializer.Serialize(value); var deserializedValue = serializer.Deserialize(serializedValue); Assert.IsType<ComplexType>(deserializedValue); var typeCastedValue = (ComplexType)deserializedValue; Assert.Equal(value.A, typeCastedValue.A); Assert.Equal(value.B, typeCastedValue.B); Assert.Equal(value.C, typeCastedValue.C); }
public void TestProperties() { var proprietor = new Proprietor(); proprietor.Value = 20; Assert.That(proprietor.Value, Is.EqualTo(20)); proprietor.Prop = 50; Assert.That(proprietor.Prop, Is.EqualTo(50)); var p = new P(null); p.Value = 20; Assert.That(p.Value, Is.EqualTo(30)); p.Prop = 50; Assert.That(p.Prop, Is.EqualTo(150)); ComplexType complexType = new ComplexType(); p.ComplexType = complexType; Assert.That(p.ComplexType.Check(), Is.EqualTo(5)); Assert.That(p.Test, Is.True); Assert.That(p.IsBool, Is.False); }
public void ComplexType() { var x = new ComplexType("a", 1); var y = new ComplexType("a", 1); var changes = new List<string>(); using (var tracker = Track.IsDirty(x, y)) { tracker.PropertyChanged += (_, e) => changes.Add(e.PropertyName); Assert.AreEqual(false, tracker.IsDirty); } x.Value++; CollectionAssert.IsEmpty(changes); var wrx = new System.WeakReference(x); var wry = new System.WeakReference(y); x = null; y = null; System.GC.Collect(); Assert.AreEqual(false, wrx.IsAlive); Assert.AreEqual(false, wry.IsAlive); }
public void Can_store_complex_type_as_unicode() { using(var con = ConnectionString.OpenDbConnection()) { const string unicodeString = "日本語 äÄöÖüÜß ıIiİüÜğĞşŞöÖçÇ åÅäÄöÖ"; OrmLiteConfig.DialectProvider.UseUnicode = true; ComplexType complexType = new ComplexType { StringList = new List<string>() { unicodeString }, Dictionary = new Dictionary<Guid, string> { { Guid.Empty, unicodeString } }, Id = 1, SubTypes = new List<ComplexType.ComplexSubType>() { new ComplexType.ComplexSubType() { Field1 = 1, Field2 = unicodeString, Field3 = Guid.Empty, Field4 = new DateTime(2000, 01, 01, 0, 0, 0) } } }; con.CreateTable<ComplexType>(true); con.Save(complexType); var result = con.GetById<ComplexType>(1); con.DropTable<ComplexType>(); Assert.That(result.StringList[0] == complexType.StringList[0]); Assert.That(result.Dictionary[Guid.Empty] == complexType.Dictionary[Guid.Empty]); Assert.That(result.SubTypes[0].Field1 == complexType.SubTypes[0].Field1); Assert.That(result.SubTypes[0].Field2 == complexType.SubTypes[0].Field2); Assert.That(result.SubTypes[0].Field3 == complexType.SubTypes[0].Field3); Assert.That(result.SubTypes[0].Field4 == complexType.SubTypes[0].Field4); } }
public void GetByReferenceTypeWithNullablePrimitiveType([FromUri] ComplexType complexType) { }
public void ComplexInputNoOutput(ComplexType input) { ComplexInputNoOutputCalled = true; ComplexInputNoOutputResult = input; }
public static CSDLContainer ReadXElement(XElement edmxRuntime) { XElement schemaElement = edmxRuntime.Element(XName.Get("ConceptualModels", edmxNamespace.NamespaceName)).Element(XName.Get("Schema", csdlNamespace.NamespaceName)); if (schemaElement == null || schemaElement.IsEmpty) { return(null); } XElement entityContainerElement = schemaElement.Element(XName.Get("EntityContainer", csdlNamespace.NamespaceName)); CSDLContainer csdlContainer = new CSDLContainer { Namespace = schemaElement.Attribute("Namespace").Value, Alias = schemaElement.Attribute("Alias").Value, Name = entityContainerElement.Attribute("Name").Value }; #region EntityTypes while (true) { var typesEnumerator = (from ete in schemaElement.Elements(XName.Get("EntityType", csdlNamespace.NamespaceName)) let eteName = ete.Attribute("Name").Value where !csdlContainer.EntityTypes.Any(et => et.Name == eteName) let baseTypeAttribute = ete.Attribute("BaseType") let baseType = baseTypeAttribute == null ? null : csdlContainer.EntityTypes.GetByName(GetName(baseTypeAttribute.Value)) where baseTypeAttribute == null || baseType != null select new { EntityTypeElement = ete, Name = eteName, BaseType = baseType }).GetEnumerator(); if (!typesEnumerator.MoveNext()) { break; } do { var current = typesEnumerator.Current; csdlContainer.EntityTypes.Add(ReadCSDLEntityType(schemaElement, entityContainerElement, current.EntityTypeElement, csdlContainer, current.Name, current.BaseType)); } while (typesEnumerator.MoveNext()); } #endregion EntityTypes #region Associations foreach (var association in csdlContainer.AssociationsCreated) { association.AssociationSetName = entityContainerElement.Elements(XName.Get("AssociationSet", csdlNamespace.NamespaceName)).First(ae => GetName(ae.Attribute("Association").Value) == association.Name).Attribute("Name").Value; if (association.PropertyEnd2.EntityType == null) { var entityTypeName = schemaElement.Elements(XName.Get("Association", csdlNamespace.NamespaceName)).First(ae => ae.Attribute("Name").Value == association.Name).Elements(XName.Get("End", csdlNamespace.NamespaceName)).First(er => er.Attribute("Role").Value == association.PropertyEnd2Role).Attribute("Type").Value; int dotIndex = entityTypeName.IndexOf("."); if (dotIndex != -1) { entityTypeName = entityTypeName.Substring(dotIndex + 1); } var entityType = csdlContainer.EntityTypes.First(et => et.Name == entityTypeName);; entityType.NavigationProperties.Add(association.PropertyEnd2); } } #endregion Associations #region ComplexTypes foreach (var complexTypeElement in schemaElement.Elements(XName.Get("ComplexType", csdlNamespace.NamespaceName))) { var complexType = new ComplexType { Name = complexTypeElement.Attribute("Name").Value }; ReadCSDLType(schemaElement, complexTypeElement, csdlContainer, complexType); csdlContainer.ComplexTypes.Add(complexType); } #endregion ComplexTypes #region Functions foreach (var functionElement in entityContainerElement.Elements(XName.Get("FunctionImport", csdlNamespace.NamespaceName))) { var function = new Function { Name = functionElement.Attribute("Name").Value }; var returnTypeAttribute = functionElement.Attribute("ReturnType"); if (returnTypeAttribute != null) { var returnTypeValue = returnTypeAttribute.Value; returnTypeValue = returnTypeValue.Remove(returnTypeValue.IndexOf(")")).Substring(returnTypeValue.IndexOf("(") + 1); function.ScalarReturnType = GetScalarPropertyTypeFromAttribute(returnTypeValue); if (function.ScalarReturnType == null) { function.EntityType = csdlContainer.EntityTypes.GetByName(GetName(returnTypeValue)); } } SetVisibilityValueFromAttribute(functionElement, "methodAccess", visibility => function.Visibility = visibility); #region Function parameters foreach (var parameterElement in functionElement.Elements(XName.Get("Parameter", csdlNamespace.NamespaceName))) { var parameter = new FunctionParameter { Name = parameterElement.Attribute("Name").Value, Type = GetScalarPropertyTypeFromAttribute(parameterElement).Value }; SetEnumValueFromAttribute <ParameterMode>(parameterElement, "Mode", mode => parameter.Mode = mode); SetIntValueFromAttribute(parameterElement, "Precision", precision => parameter.Precision = precision); SetIntValueFromAttribute(parameterElement, "Scale", scale => parameter.Scale = scale); SetIntValueFromAttribute(parameterElement, "MaxLength", maxLength => parameter.MaxLength = maxLength); function.Parameters.Add(parameter); } #endregion Function parameters csdlContainer.Functions.Add(function); } #endregion Functions return(csdlContainer); }
public static void Verify(Workspace w, ExpNode q, IEnumerable results, ResourceType resType, ComplexType cType, bool bCount) { long count = 0; if (bCount) { object[] args = new object[] { results }; Type qorType = typeof(QueryOperationResponseWrapper<>).MakeGenericType(resType.ClientClrType); object qor = Activator.CreateInstance(qorType, args); PropertyInfo pi = qor.GetType().GetProperty("GetTotalCount"); object i = pi.GetValue(qor, new object[] { }); count = (long)i; LinqQueryBuilder lb = new LinqQueryBuilder(w); lb.CountingMode = true; lb.Build(q); object baselineElementsCount = CommonPayload.CreateList(lb.QueryResult).Count; AstoriaTestLog.IsTrue(count == Convert.ToInt64(baselineElementsCount), "Count is different.Count is " + count.ToString() + ". Baseline count is " + baselineElementsCount.ToString()); } LinqQueryBuilder linqBuilder = new LinqQueryBuilder(w); linqBuilder.Build(q); IQueryable baselines = linqBuilder.QueryResult; IEnumerator b = null; IEnumerator r = null; try { b = TrustedMethods.IQueryableGetEnumerator(baselines); r = results.GetEnumerator(); } catch (InvalidOperationException invalidOperation) { if (!AstoriaTestProperties.IsRemoteClient) throw invalidOperation; } PropertyInfo propertyInfo = null; Object expectedResult1 = null; Object expectedResult2 = null; try { while (b.MoveNext() && r.MoveNext()) { if (b.Current == null) { return; } if (r.Current == null) { throw new TestFailedException("Less results than expected"); } //skip verification for Binary data type for Linq to Sql if (AstoriaTestProperties.DataLayerProviderKinds[0] == DataLayerProviderKind.LinqToSql && b.Current is System.Byte[]) return; if (b.Current is System.Byte[]) { byte[] newBase = (byte[])b.Current; byte[] newAct = (byte[])r.Current; if (newBase.Length != newAct.Length) throw new TestFailedException("Failed to compare the results!"); } #if !ClientSKUFramework else if (b.Current is System.Data.Linq.Binary) { System.Data.Linq.Binary newBase = (System.Data.Linq.Binary)b.Current; System.Data.Linq.Binary newAct = new System.Data.Linq.Binary((byte[])r.Current); if (newBase.Length != newAct.Length) throw new TestFailedException("Failed to compare the results!"); } #endif else if (b.Current is System.Xml.Linq.XElement) { if (b.Current.ToString() != r.Current.ToString()) throw new TestFailedException("Failed to compare the results!"); } else { if (!b.Current.Equals(r.Current)) { if (cType != null) { foreach (ResourceProperty property in cType.Properties) { if (!property.IsNavigation && !property.IsComplexType && !(property.Type is CollectionType)) { propertyInfo = b.Current.GetType().GetProperty(property.Name); expectedResult1 = propertyInfo.GetValue(b.Current, null); PropertyInfo propertyInfo2 = r.Current.GetType().GetProperty(property.Name); expectedResult2 = propertyInfo2.GetValue(r.Current, null); if (expectedResult1 != expectedResult2) { if (expectedResult1 is System.Xml.Linq.XElement) { expectedResult1 = ((System.Xml.Linq.XElement)expectedResult1).ToString(System.Xml.Linq.SaveOptions.None); } if (expectedResult2 is System.Xml.Linq.XElement) { expectedResult2 = ((System.Xml.Linq.XElement)expectedResult2).ToString(System.Xml.Linq.SaveOptions.None); } #if !ClientSKUFramework if (expectedResult1 is byte[]) { expectedResult1 = new System.Data.Linq.Binary((byte[])expectedResult1); } if (expectedResult2 is byte[]) { expectedResult2 = new System.Data.Linq.Binary((byte[])expectedResult2); } #endif AstoriaTestLog.AreEqual(expectedResult1, expectedResult2, String.Format("Resource value for {0} does not match", property.Name), false); } } } } else { foreach (ResourceProperty property in resType.Properties) { if (!property.IsNavigation && !property.IsComplexType && !(property.Type is CollectionType)) { //skip verification for Binary data type for Linq to Sql if (AstoriaTestProperties.DataLayerProviderKinds[0] == DataLayerProviderKind.LinqToSql && property.Type.Name == "LinqToSqlBinary") return; propertyInfo = b.Current.GetType().GetProperty(property.Name); expectedResult1 = propertyInfo.GetValue(b.Current, null); PropertyInfo propertyinfo2 = r.Current.GetType().GetProperty(property.Name); expectedResult2 = propertyinfo2.GetValue(r.Current, null); if (expectedResult1 != expectedResult2) { if (expectedResult1 is System.Xml.Linq.XElement) { expectedResult1 = ((System.Xml.Linq.XElement)expectedResult1).ToString(System.Xml.Linq.SaveOptions.None); } if (expectedResult2 is System.Xml.Linq.XElement) { expectedResult2 = ((System.Xml.Linq.XElement)expectedResult2).ToString(System.Xml.Linq.SaveOptions.None); } #if !ClientSKUFramework if (expectedResult1 is byte[]) { expectedResult1 = new System.Data.Linq.Binary((byte[])expectedResult1); } if (expectedResult2 is byte[]) { expectedResult2 = new System.Data.Linq.Binary((byte[])expectedResult2); } #endif AstoriaTestLog.AreEqual(expectedResult1, expectedResult2, String.Format("Resource value for {0} does not match", property.Name), false); } } } } } } } } catch (Exception e) { AstoriaTestLog.WriteLine(e.ToString()); throw; } }
public String ComplexTypeArgument(ComplexType type) { return String.Format("{0} - {1}", type.Name, type.Age); }
private void Action_Complex_Type(ComplexType complex) { }
public int AnnotatedWithSwaggerResponses(ComplexType param) { throw new NotImplementedException(); }
public void Union_of_complex_types_comparing_instances_results_in_all_values() { ComplexType[] left = new ComplexType[] { new ComplexType(1), new ComplexType(2), new ComplexType(3) }; ComplexType[] right = new ComplexType[] { new ComplexType(4), new ComplexType(5), new ComplexType(1) }; ComplexType[] union = ArrayUtil.Union(left, right, delegate(ComplexType a, ComplexType b) { return ReferenceEquals(a, b) ? 0 : 1; }); Assert.AreEqual(6, union.Length); }
internal ReflectionCache(Type type) { Type = type; TypeName = type.FullName; AssemblyName = type.AssemblyQualifiedName; CircularReferencable = type.IsValueType == false || type != typeof(string); IsAbstract = type.IsUndetermined(); IsAnonymous = type.IsAnonymous(); JsonDataType = Reflection.GetJsonDataType(type); SerializeMethod = JsonSerializer.GetWriteJsonMethod(type); DeserializeMethod = JsonDeserializer.GetReadJsonMethod(type); if (JsonDataType == JsonDataType.Enum) { IsFlaggedEnum = AttributeHelper.HasAttribute <FlagsAttribute> (type, false); return; } if (type.IsPointer) { throw new JsonSerializationException("Can not serialize pointer type: " + type.AssemblyQualifiedName); } if (type.IsArray) { ArgumentTypes = new Type[] { type.GetElementType() }; CommonType = type.GetArrayRank() == 1 ? ComplexType.Array : ComplexType.MultiDimensionalArray; } else { var t = type; if (t.IsGenericType == false) { while ((t = t.BaseType) != null) { if (t.IsGenericType) { break; } } } if (t != null) { ArgumentTypes = t.GetGenericArguments(); var gt = t.GetGenericTypeDefinition(); if (gt.Equals(typeof(Dictionary <,>))) { CommonType = ComplexType.Dictionary; } else if (gt.Equals(typeof(List <>))) { CommonType = ComplexType.List; } else if (gt.Equals(typeof(Nullable <>))) { CommonType = ComplexType.Nullable; SerializeMethod = JsonSerializer.GetWriteJsonMethod(ArgumentTypes[0]); } } } if (typeof(IEnumerable).IsAssignableFrom(type)) { if (typeof(Array).IsAssignableFrom(type) == false) { AppendItem = Reflection.CreateWrapperMethod <AddCollectionItem> (Reflection.FindMethod(type, "Add", new Type[] { null })); } if (ArgumentTypes != null && ArgumentTypes.Length == 1) { ItemSerializer = JsonSerializer.GetWriteJsonMethod(ArgumentTypes[0]); ItemDeserializer = JsonDeserializer.GetReadJsonMethod(ArgumentTypes[0]); } } if (ArgumentTypes != null) { ArgumentReflections = new ReflectionCache[ArgumentTypes.Length]; } if (CommonType != ComplexType.Array && CommonType != ComplexType.MultiDimensionalArray && CommonType != ComplexType.Nullable) { if (type.IsPubliclyAccessible() == false) { ConstructorInfo |= ConstructorTypes.NonPublic; } if (type.IsClass || type.IsValueType) { try { Constructor = Reflection.CreateConstructorMethod(type, type.IsVisible == false || typeof(DatasetSchema).Equals(type)); } catch (Exception ex) { throw new JsonSerializationException("Error occurred when creating constructor method for type " + type.AssemblyQualifiedName, ex); } if (Constructor != null && Constructor.Method.IsPublic == false) { ConstructorInfo |= ConstructorTypes.NonPublic; } if (Constructor == null) { var c = type.GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); if (c != null && c.Length > 0) { ConstructorInfo |= ConstructorTypes.Parametric; } } Members = Reflection.GetMembers(type); } } //if (typeof (IEnumerable).IsAssignableFrom (type)) { // return; //} //if (JsonDataType != JsonDataType.Undefined) { // return; //} }
public void CollectionUpdate() { var innerType = new InnerType() { String = "test" }; var source = new GenericCollections <ComplexType>(false); //initialize source for (int i = 0; i < 50; i++) { source.List.Add(new ComplexType() { A = i, InnerType = innerType }); source.HashSet.Add(new ComplexType() { A = i }); source.SortedSet.Add(new ComplexType() { A = i }); source.Stack.Push(new ComplexType() { A = i }); source.Queue.Enqueue(new ComplexType() { A = i }); source.LinkedList.AddLast(new ComplexType() { A = i }); source.ObservableCollection.Add(new ComplexType() { A = i }); } var tempItemA = new ComplexType() { A = 1 }; var tempItemB = new ComplexType() { A = 49 }; var target = new GenericCollections <ComplexType>(false) { List = new List <ComplexType>() { tempItemA, tempItemB, new ComplexType() { A = 50 } } }; var ultraMapper = new Mapper(cfg => { cfg.MapTypes(source, target) .MapMember(a => a.List, b => b.List, (itemA, itemB) => itemA.A == itemB.A); }); ultraMapper.Map(source, target); Assert.IsTrue(object.ReferenceEquals(target.List.First(item => item.A == 1), tempItemA)); Assert.IsTrue(object.ReferenceEquals(target.List.First(item => item.A == 49), tempItemB)); }
public PropertyTypeReferences(TypeReference typeReference, ComplexType complexType, ClientApiGenerator generator) : this(typeReference, complexType, CollectionKind.None, generator) { }
public void Method(int value1, string value2, ComplexType value3) { }
public void Method(ComplexType value) { }
internal void WriteObjectDefinition(ObjectProvider provider) { try { // Check to see if the company specific directory has been created yet or not, if not create it and copy all of the base configs into it // if it has, then we assume that the base configs are there since the copy always occurs after the directory creation if (!Directory.Exists(this.GetConfigPath(true))) { this.SetupCompanyConfig(ConfigurationOption.Install); } var providerObjectDefinition = this.LoadObjectDefinitionsFromConfigs().FirstOrDefault(str => str.RootDefinition.TypeName.ToUpperInvariant() == provider.Name.ToUpperInvariant()); string configFileName = providerObjectDefinition == null ? CultureInfo.CurrentCulture.TextInfo.ToTitleCase(provider.DisplayName.ConvertToValidFileName().Replace(" ", string.Empty)) + "ObjectProvider.config" : providerObjectDefinition.RootDefinition.DisplayName.ConvertToValidFileName().Replace(" ", string.Empty) + "ObjectProvider.config"; var filePath = Path.Combine(this.GetConfigPath(false), configFileName); Common.ObjectDefinition objDef = new Common.ObjectDefinition(); this.PublishPreConfigurationMessage(string.Format(CultureInfo.CurrentCulture, Resources.StartGeneratingProviderConfiguration, provider.Name)); // Check to see if the object def is stored at the root, which means it is a base or version 1 definition if (File.Exists(filePath)) { provider.Name = Path.GetFileNameWithoutExtension(configFileName); objDef = provider.ObjectDefinition; this.FillObjectDef(objDef); } else { // This is a new configuration file and we need to add the id attribute to it so the framework knows what this object provider's id is XmlDocument doc = new XmlDocument(); XmlAttribute idAttrib = doc.CreateAttribute(CRM2011AdapterUtilities.EntityMetadataId); idAttrib.Value = provider.Id.ToString(); TypeDefinition typeDef = new ComplexType() { ClrType = typeof(System.Collections.Generic.Dictionary<string, object>), Name = provider.Name }; FieldDefinition rootDef = new FieldDefinition() { DisplayName = provider.DisplayName, Name = provider.Name, TypeDefinition = typeDef, TypeName = provider.Name, AdditionalAttributes = new XmlAttribute[] { idAttrib } }; objDef.Types.Add(typeDef); objDef.RootDefinition = rootDef; this.FillObjectDef(objDef); } using (var fs = File.Create(Path.Combine(this.GetConfigPath(true), configFileName))) { using (var xr = XmlWriter.Create(fs, new XmlWriterSettings() { Indent = true })) { var serializer = new XmlSerializer(typeof(ObjectDefinition)); serializer.Serialize(xr, objDef); } } this.PublishPostConfigurationMessage(string.Format(CultureInfo.CurrentCulture, Resources.FinishedGeneratingProviderConfiguration, provider.Name)); } catch (IOException e) { // Log any exceptions the occur and publish them to any listeners TraceLog.Error(string.Format(CultureInfo.InvariantCulture, Resources.ExceptionDump), e); this.PublishExceptionConfigurationMessage(string.Format(CultureInfo.CurrentCulture, Resources.ProviderConfigurationExceptionMessage, provider.Name)); } }
public void AcceptsComplexTypeFromQuery([FromQuery] ComplexType param) { }
private static void GenerateEntityManytoManyObjectDefinitionEntries(ObjectDefinition objDef, string entityDisplayName) { /////GUID Type defination///// TypeDefinition typeDefGUID = new SimpleType() { ClrType = typeof(System.Guid), Name = "System.Guid" }; /////GUID Type defination///// /////String Type defination///// Type tempTypeString = CRM2011AdapterUtilities.SimpleTypeConvert(AttributeTypeCode.String); TypeDefinition typeDefString = new SimpleType() { ClrType = tempTypeString, Name = tempTypeString.FullName }; /////String Type defination///// /////EntityReference Type defination///// ComplexType complexTypeER = new ComplexType() { ClrType = typeof(System.Collections.Generic.Dictionary<string, object>), Name = "EntityReference" }; Type fieldType1 = CRM2011AdapterUtilities.SimpleTypeConvert(AttributeTypeCode.String); ComplexType fieldTypeER = new ComplexType() { ClrType = fieldType1, Name = fieldType1.FullName }; FieldDefinition tempDefER1 = new FieldDefinition() { Name = "name", DisplayName = "name", TypeDefinition = fieldTypeER, TypeName = fieldTypeER.Name }; complexTypeER.Fields.Add(tempDefER1); FieldDefinition tempDefER2 = new FieldDefinition() { Name = "type", DisplayName = "type", TypeDefinition = fieldTypeER, TypeName = fieldTypeER.Name }; complexTypeER.Fields.Add(tempDefER2); FieldDefinition tempDefER3 = new FieldDefinition() { Name = "value", DisplayName = "value", TypeDefinition = fieldTypeER, TypeName = fieldTypeER.Name }; complexTypeER.Fields.Add(tempDefER3); /////EntityReference Type defination///// /////ManyToManyRelationship Type defination///// ComplexType complexTypeR = new ComplexType() { ClrType = typeof(System.Collections.Generic.Dictionary<string, object>), Name = "ManyToManyRelationship" }; ComplexType fieldTypeR = new ComplexType() { ClrType = fieldType1, Name = fieldType1.FullName }; FieldDefinition tempDef1 = new FieldDefinition() { Name = "Target", DisplayName = "Target", TypeDefinition = complexTypeER, TypeName = complexTypeER.Name }; complexTypeR.Fields.Add(tempDef1); FieldDefinition tempDef2 = new FieldDefinition() { Name = "RelatedEntity", DisplayName = "RelatedEntity", TypeDefinition = complexTypeER, TypeName = complexTypeER.Name }; complexTypeR.Fields.Add(tempDef2); FieldDefinition tempDef3 = new FieldDefinition() { Name = "Relationship", DisplayName = "Relationship", TypeDefinition = fieldTypeR, TypeName = fieldTypeR.Name }; complexTypeR.Fields.Add(tempDef3); /////ManyToManyRelationship Type defination///// FieldDefinition entityDef = new FieldDefinition() { Name = entityDisplayName.ToString().Replace(" ", string.Empty), DisplayName = entityDisplayName, TypeDefinition = complexTypeR, TypeName = complexTypeR.Name, IsRequired = false }; objDef.Types.First().Children.Add(entityDef); /////Adding GUID Type defination///// objDef.Types.Add(typeDefGUID); /////GUID Type defination///// /////Adding String Type defination///// objDef.Types.Add(typeDefString); /////String Type defination///// /////Adding EntityReference Type defination///// objDef.Types.Add(complexTypeER); /////EntityReference Type defination///// /////Adding ManyToManyRelationship Type defination///// objDef.Types.Add(complexTypeR); /////ManyToManyRelationship Type defination///// }
public void AcceptsStringFromBody([FromBody] ComplexType param) { }
public void QueryDescendants_MatchingPropertyValue_ReturnsStronglyTypedObject() { // input from pass1.json in test suite at http://www.json.org/JSON_checker/ const string input = @"[ ""JSON Test Pattern pass1"", {""object with 1 member"":[""array with 1 element""]}, {}, [], -42, true, false, null, { ""integer"": 1234567890, ""real"": -9876.543210, ""e"": 0.123456789e-12, ""E"": 1.234567890E+34, """": 23456789012E66, ""zero"": 0, ""one"": 1, ""space"": "" "", ""quote"": ""\"""", ""backslash"": ""\\"", ""controls"": ""\b\f\n\r\t"", ""slash"": ""/ & \/"", ""alpha"": ""abcdefghijklmnopqrstuvwyz"", ""ALPHA"": ""ABCDEFGHIJKLMNOPQRSTUVWYZ"", ""digit"": ""0123456789"", ""0123456789"": ""digit"", ""special"": ""`1~!@#$%^&*()_+-={':[,]}|;.</>?"", ""hex"": ""\u0123\u4567\u89AB\uCDEF\uabcd\uef4A"", ""true"": true, ""false"": false, ""null"": null, ""array"":[ ], ""object"":{ }, ""address"": ""50 St. James Street"", ""url"": ""http://www.JSON.org/"", ""comment"": ""// /* <!-- --"", ""# -- --> */"": "" "", "" s p a c e d "" :[1,2 , 3 , 4 , 5 , 6 ,7 ],""compact"":[1,2,3,4,5,6,7], ""jsontext"": ""{\""object with 1 member\"":[\""array with 1 element\""]}"", ""quotes"": """ \u0022 %22 0x22 034 """, ""\/\\\""\uCAFE\uBABE\uAB98\uFCDE\ubcda\uef4A\b\f\n\r\t`1~!@#$%^&*()_+-=[]{}|;:',./<>?"" : ""A key can be any string"" }, 0.5 ,98.6 , 99.44 , 1066, 1e1, 0.1e1, 1e-1, 1e00,2e+00,2e-00 ,""rosebud""]"; var expected = new ComplexType { integer = 1234567890, real = -9876.543210, e = 0.123456789e-12, E = 1.234567890E+34, _ = 23456789012E66, zero = 0, one = 1, space = " ", quote = "\"", backslash = "\\", controls = "\b\f\n\r\t", slash = "/ & /", alpha = "abcdefghijklmnopqrstuvwyz", ALPHA = "ABCDEFGHIJKLMNOPQRSTUVWYZ", digit = "0123456789", _0123456789 = "digit", special = "`1~!@#$%^&*()_+-={':[,]}|;.</>?", hex = "\u0123\u4567\u89AB\uCDEF\uabcd\uef4A", @true = true, @false = false, @null = null, array = new object[0], @object = new Dictionary<string, object>(), address = "50 St. James Street", url = new Uri("http://www.JSON.org/"), comment = "// /* <!-- --", Comments = " ", spaced = new [] { 1,2,3,4,5,6,7 }, compact = new [] { 1,2,3,4,5,6,7 }, jsontext = "{\"object with 1 member\":[\"array with 1 element\"]}", quotes = "" \u0022 %22 0x22 034 "", A_key_can_be_any_string = "A key can be any string" }; var reader = new JsonReader(new DataReaderSettings(new JsonResolverStrategy())); var source = reader.Query<ComplexType>(input); var query = from foo in source.Descendants() where foo.url == new Uri("http://www.JSON.org/") select foo; var actual = query.FirstOrDefault(); Assert.Equal(expected, actual, false); }
public void AcceptsComplexTypeFromBody([FromBody] ComplexType param) { }
public string EchoWithPostComplexType(ComplexType value) { return("EchoWithPostComplexType" + value.ComplexTypeStringValue); }
public Destination(ComplexType myComplexMember) { MyComplexMember = myComplexMember; }
/// <summary> /// Registers the data generator for the specified complex type. /// </summary> /// <param name="dataGenerator">The data generator.</param> /// <param name="complexType">Type of the complex.</param> public void RegisterDataGenerator(IDataGenerator dataGenerator, ComplexType complexType) { this.Register <IDataGenerator>(complexType, dataGenerator, this.complexTypeDataGenerators); }
private void ImportFrom(object item, string currentPath, ComplexType complexType) { if (null == item) { this.SetValue(currentPath, item); } else { foreach (PropertyInfo propertyInfo in item.GetType().GetProperties()) { MemberProperty mp = complexType.Properties.Where(p => p.Name == propertyInfo.Name).SingleOrDefault(); if (mp == null) { throw new TaupoInvalidOperationException( string.Format(CultureInfo.InvariantCulture, "Complex type '{0}' does not contain property '{1}'.", complexType.FullName, propertyInfo.Name)); } this.SetDataFromPropertyInfo(item, propertyInfo, mp, currentPath + "."); } } }
protected override void VisitComplexType(ComplexType item) { this.Dispatch <ComplexType>(item); base.VisitComplexType(item); }
private void Action_CustomModelBinder_On_Parameter_WithProvider([ModelBinder(typeof(CustomModelBinderProvider))] ComplexType complex) { }
public static ComplexType GetRootAsComplexType(ByteBuffer _bb, ComplexType obj) { return(obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); }
/// <summary> /// Creates a complex property in the passed in ComplexType. /// </summary> /// <param name="name">The name of the new property</param> /// <param name="parentComplexType">The ComplexType to create the property in</param> /// <param name="complexType">The complex type of the property</param> /// <param name="nullable">Flag whether the property is nullable or not</param> internal CreateComplexTypePropertyCommand(string name, ComplexType parentComplexType, ComplexType complexType, bool?nullable) : base(PrereqId) { ValidateString(name); CommandValidation.ValidateComplexType(parentComplexType); CommandValidation.ValidateComplexType(complexType); Name = name; ParentComplexType = parentComplexType; ComplexType = complexType; Nullable = nullable; }
private static IEnumerable <string> TopHalf(Random rand, List <double> normalTimes) { Console.WriteLine("Starting run with " + MethodCache.Count() + " starting points"); var toSerialize = new List <ComplexType>(); for (var i = 0; i < 500; i++) { toSerialize.Add(ComplexType.Random(rand)); } toSerialize = toSerialize.Select(_ => new { _ = _, Order = rand.Next() }).OrderBy(o => o.Order).Select(o => o._).Where((o, ix) => ix % 2 == 0).ToList(); System.GC.Collect(2, GCCollectionMode.Forced, blocking: true); var scores = new Dictionary <string, Dictionary <int, int> >(); var minTimes = new Dictionary <string, double>(); var maxTimes = new Dictionary <string, double>(); Console.WriteLine("\tStarting runs"); for (var i = 1; i <= 10; i++) { Console.WriteLine("\t\tRun #" + i); var inOrder = MethodCache .Select(_ => new { _, Order = rand.Next() }) .OrderBy(_ => _.Order) .Select(_ => _._) .Select( kv => { var mtd = kv.Value; double t; CompareTime(toSerialize, mtd, out t); if (kv.Key == NormalKey) { normalTimes.Add(t); } return(Tuple.Create(kv.Key, t)); } ) .OrderBy(t => t.Item2) .ToList(); double runMin = double.MaxValue; double runMax = double.MinValue; double runNormal = -1; for (var j = 0; j < inOrder.Count; j++) { var t = inOrder[j]; var key = t.Item1; if (t.Item2 < runMin) { runMin = t.Item2; } if (t.Item2 > runMax) { runMax = t.Item2; } if (key == NormalKey) { runNormal = t.Item2; } Dictionary <int, int> inRank; if (!scores.TryGetValue(key, out inRank)) { scores[key] = inRank = new Dictionary <int, int>(); } if (!inRank.ContainsKey(j)) { inRank[j] = 0; } inRank[j]++; double min, max; if (!minTimes.TryGetValue(key, out min)) { minTimes[key] = min = int.MaxValue; } if (!maxTimes.TryGetValue(key, out max)) { maxTimes[key] = max = 0; } if (t.Item2 < min) { minTimes[key] = t.Item2; } if (t.Item2 > max) { maxTimes[key] = t.Item2; } } Console.WriteLine("\t\t\tMin: " + runMin); Console.WriteLine("\t\t\tMax: " + runMax); Console.WriteLine("\t\t\tNormal Time: " + runNormal); } var minest = minTimes.Values.Min(); var maxest = maxTimes.Values.Max(); Console.WriteLine("\tMin: " + minest); Console.WriteLine("\tMax: " + maxest); Console.WriteLine("\tNormal Min: " + minTimes[NormalKey]); Console.WriteLine("\tNormal Max: " + maxTimes[NormalKey]); var take = scores.Count / 2; if (take == 0) { take = 1; } var topHalf = scores .Where(kv => kv.Key != NormalKey) .OrderBy( kv => kv.Value, new FindFastOrderComparer() ) .Take(take) .Select(kv => kv.Key) .ToList(); return(topHalf); }
public ExplorerComplexType(EditingContext context, ComplexType complexType, ExplorerEFElement parent) : base(context, complexType, parent) { // do nothing }
public void Replace(ReferenceHandling referenceHandling) { var source = new ObservableCollection<ComplexType> { new ComplexType("a", 1), new ComplexType("b", 2) }; var target = new ObservableCollection<ComplexType> { new ComplexType("a", 1), new ComplexType("b", 2) }; using (Synchronize.PropertyValues(source, target, referenceHandling)) { source[0] = new ComplexType("c", 3); var expected = new[] { new ComplexType("c", 3), new ComplexType("b", 2) }; CollectionAssert.AreEqual(expected, source, ComplexType.Comparer); CollectionAssert.AreEqual(expected, target, ComplexType.Comparer); source[1] = new ComplexType("d", 4); expected = new[] { new ComplexType("c", 3), new ComplexType("d", 4) }; CollectionAssert.AreEqual(expected, source, ComplexType.Comparer); CollectionAssert.AreEqual(expected, target, ComplexType.Comparer); } }
private void CheckForEnumPropertiesWithStoreGeneratedPattern(ComplexType complexType) { CheckForEnumPropertiesWithStoreGeneratedPattern( complexType.Properties().OfType <ConceptualProperty>().Where(p => p.IsEnumType)); }
/// <summary> /// Write out a object definition for the picklist provider /// </summary> internal void WritePicklistObjectDefinition() { var provider = new PicklistObjectProvider(); try { if (!Directory.Exists(this.GetConfigPath(true))) { this.SetupCompanyConfig(ConfigurationOption.Install); } var providerObjectDefinition = this.LoadObjectDefinitionsFromConfigs().FirstOrDefault(str => str.RootDefinition.TypeName.ToUpperInvariant() == provider.Name.ToUpperInvariant()); string configFileName = providerObjectDefinition == null ? CultureInfo.CurrentCulture.TextInfo.ToTitleCase(provider.DisplayName.ConvertToValidFileName().Replace(" ", string.Empty)) + "ObjectProvider.config" : providerObjectDefinition.RootDefinition.DisplayName.ConvertToValidFileName().Replace(" ", string.Empty) + "ObjectProvider.config"; Common.ObjectDefinition objDef = new Common.ObjectDefinition(); this.PublishPreConfigurationMessage(string.Format(CultureInfo.CurrentCulture, Resources.StartGeneratingProviderConfiguration, provider.Name)); // This is a new configuration file and we need to add the id attribute to it so the framework knows what this object provider's id is XmlDocument doc = new XmlDocument(); XmlAttribute idAttrib = doc.CreateAttribute(CRM2011AdapterUtilities.EntityMetadataId); idAttrib.Value = provider.Id.ToString(); TypeDefinition typeDef = new ComplexType() { ClrType = typeof(System.Collections.Generic.Dictionary<string, object>), Name = "Microsoft.Dynamics.Integration.Adapters.Crm2011.OptionList" }; FieldDefinition rootDef = new FieldDefinition() { DisplayName = "Option list", Name = "OptionList", TypeDefinition = typeDef, TypeName = "Microsoft.Dynamics.Integration.Adapters.Crm2011.OptionList" }; objDef.Types.Add(typeDef); objDef.RootDefinition = rootDef; this.FillPicklistObjectDef(objDef); using (var fs = File.Create(Path.Combine(this.GetConfigPath(true), configFileName))) { using (var xr = XmlWriter.Create(fs, new XmlWriterSettings() { Indent = true })) { var serializer = new XmlSerializer(typeof(ObjectDefinition)); serializer.Serialize(xr, objDef); } } this.PublishPostConfigurationMessage(string.Format(CultureInfo.CurrentCulture, Resources.FinishedGeneratingProviderConfiguration, provider.Name)); } catch (IOException e) { // Log any exceptions the occur and publish them to any listeners TraceLog.Error(string.Format(CultureInfo.InvariantCulture, Resources.ExceptionDump), e); this.PublishExceptionConfigurationMessage(string.Format(CultureInfo.CurrentCulture, Resources.ProviderConfigurationExceptionMessage, provider.Name)); } }
private void Action_Complex_Type_UriAndBody([FromUri] ComplexType complexUri, ComplexType complexBody) { }
private static void GeneratePicklistObjectDefinitionEntries(ObjectDefinition objDef, RetrieveAllEntitiesResponse response) { var orderedEntityMetadata = ((EntityMetadata[])response.Results.First().Value).Where(x => x.DisplayName.LocalizedLabels.Count > 0).OrderBy(x => x.DisplayName.LocalizedLabels[0].Label); // For each entity, add a Type foreach (var entityMetadata in orderedEntityMetadata) { var picklistAttributesMetaData = entityMetadata.Attributes.Where(x => x.AttributeType == AttributeTypeCode.Picklist && x.IsCustomizable.Value == true).OrderBy(x => x.LogicalName); var picklistAttributes = picklistAttributesMetaData.Where(x => ((PicklistAttributeMetadata)x).OptionSet.IsGlobal.Value == false); var entityDisplayName = entityMetadata.DisplayName.LocalizedLabels[0].Label; // All picklists for an entity are here. if (picklistAttributes.Count() > 0) { FieldDefinition entityDef = new FieldDefinition() { Name = entityDisplayName.ToString().Replace(" ", string.Empty), DisplayName = entityDisplayName, TypeName = entityMetadata.LogicalName, IsRequired = false }; objDef.Types.First().Children.Add(entityDef); ComplexType complexType = new ComplexType() { ClrType = typeof(System.Collections.Generic.Dictionary<string, object>), Name = entityMetadata.LogicalName }; objDef.Types.Add(complexType); foreach (var picklist in picklistAttributes) { string displayName = picklist.DisplayName.LocalizedLabels[0].Label; ComplexType fieldType = CRM2011AdapterUtilities.ComplexTypeConvert(picklist.AttributeType.Value, objDef); if (complexType != null) { FieldDefinition tempDef = new FieldDefinition() { Name = picklist.LogicalName, DisplayName = displayName, TypeDefinition = fieldType, TypeName = fieldType.Name }; complexType.Fields.Add(tempDef); } } } } var optionSetValueType = new CollectionType() { ClrType = typeof(string[]), Name = "OptionSetValue" }; optionSetValueType.Item = new FieldDefinition() { Name = "Item", TypeName = "System.String", DisplayName = "Options", IsRequired = false }; objDef.Types.Add(optionSetValueType); }
private void Action_Two_Complex_Types(ComplexType complexBody1, ComplexType complexBody2) { }
public void Can_create_non_composable_function_with_multiple_results() { DbProviderManifest providerManifest; var containerMapping = GetContainerMapping(out providerManifest); var cTypeUsageInt = TypeUsage.Create( PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.Int32), new[] { Facet.Create(MetadataItem.NullableFacetDescription, false) }); var sTypeUsageInt = TypeUsage.Create( providerManifest.GetStoreType(cTypeUsageInt).EdmType, new[] { Facet.Create(MetadataItem.NullableFacetDescription, false) }); var cTypeUsageString = TypeUsage.CreateDefaultTypeUsage( PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String)); var sTypeUsageString = providerManifest.GetStoreType(cTypeUsageString); var complexType = ComplexType.Create( "RT1", "N", DataSpace.CSpace, new[] { EdmProperty.Create("P1", cTypeUsageInt), EdmProperty.Create("P2", cTypeUsageString) }, null); var entityType = EntityType.Create( "RT2", "N", DataSpace.CSpace, new[] { "P3" }, new[] { EdmProperty.Create("P3", cTypeUsageInt), EdmProperty.Create("P4", cTypeUsageString), }, null); var rowType1 = RowType.Create( new[] { EdmProperty.Create("C1", sTypeUsageInt), EdmProperty.Create("C2", sTypeUsageString) }, null); var rowType2 = RowType.Create( new[] { EdmProperty.Create("C3", sTypeUsageInt), EdmProperty.Create("C4", sTypeUsageString) }, null); var functionImport = EdmFunction.Create( "F", "N", DataSpace.CSpace, new EdmFunctionPayload { IsComposable = false, ReturnParameters = new[] { FunctionParameter.Create("R1", complexType.GetCollectionType(), ParameterMode.ReturnValue), FunctionParameter.Create("R2", entityType.GetCollectionType(), ParameterMode.ReturnValue) }, EntitySets = new[] { new EntitySet(), new EntitySet() } }, null); var targetFunction = EdmFunction.Create( "SF", "N", DataSpace.SSpace, new EdmFunctionPayload { IsComposable = false, ReturnParameters = new[] { FunctionParameter.Create("R1", rowType1.GetCollectionType(), ParameterMode.ReturnValue), FunctionParameter.Create("R2", rowType2.GetCollectionType(), ParameterMode.ReturnValue) }, EntitySets = new [] { new EntitySet(), new EntitySet() } }, null); var resultMappings = new List <FunctionImportResultMapping> { new FunctionImportResultMapping(), new FunctionImportResultMapping() }; resultMappings[0].AddTypeMapping(new FunctionImportComplexTypeMapping( complexType, new Collection <FunctionImportReturnTypePropertyMapping>() { new FunctionImportReturnTypeScalarPropertyMapping("P1", "C1"), new FunctionImportReturnTypeScalarPropertyMapping("P2", "C2"), })); resultMappings[1].AddTypeMapping(new FunctionImportEntityTypeMapping( Enumerable.Empty <EntityType>(), new [] { entityType }, new Collection <FunctionImportReturnTypePropertyMapping>() { new FunctionImportReturnTypeScalarPropertyMapping("P3", "C3"), new FunctionImportReturnTypeScalarPropertyMapping("P4", "C4") }, Enumerable.Empty <FunctionImportEntityTypeMappingCondition>())); var functionImportMapping = new FunctionImportMappingNonComposable( functionImport, targetFunction, resultMappings, containerMapping); Assert.Equal(resultMappings.Count, functionImportMapping.ResultMappings.Count); functionImportMapping.ResultMappings.Each(m => Assert.False(m.IsReadOnly)); functionImportMapping.SetReadOnly(); functionImportMapping.ResultMappings.Each(m => Assert.True(m.IsReadOnly)); }
private void Action_Complex_Type_Uri([FromUri] ComplexType complex) { }
private void Action_Default_Custom_Model_Binder([ModelBinder] ComplexType complex) { }
protected virtual ComplexTypeValidator BuildComplexTypeValidator( Type clrType, ComplexType complexType) { return(this.BuildTypeValidator <ComplexTypeValidator>(clrType, (IEnumerable <EdmProperty>)complexType.Properties, Enumerable.Empty <NavigationProperty>(), (Func <IEnumerable <PropertyValidator>, IEnumerable <IValidator>, ComplexTypeValidator>)((propertyValidators, typeLevelValidators) => new ComplexTypeValidator(propertyValidators, typeLevelValidators)))); }
public void TestUncompilableCode() { #pragma warning disable 0168 // warning CS0168: The variable `foo' is declared but never used #pragma warning disable 0219 // warning CS0219: The variable `foo' is assigned but its value is never used ALLCAPS_UNDERSCORES a; using (var testRenaming = new TestRenaming()) { testRenaming.name(); testRenaming.Name(); testRenaming.Property.GetHashCode(); } new ForceCreationOfInterface().Dispose(); new InheritsProtectedVirtualFromSecondaryBase().Dispose(); new InheritanceBuffer().Dispose(); new HasProtectedVirtual().Dispose(); new Proprietor(5).Dispose(); using (var testOverrideFromSecondaryBase = new TestOverrideFromSecondaryBase()) { testOverrideFromSecondaryBase.function(); var ok = false; testOverrideFromSecondaryBase.function(ref ok); var property = testOverrideFromSecondaryBase.property; testOverrideFromSecondaryBase.VirtualMember(); } using (var foo = new Foo()) { var isNoParams = foo.IsNoParams; foo.SetNoParams(); foo.Width = 5; using (var hasSecondaryBaseWithAbstractWithDefaultArg = new HasSecondaryBaseWithAbstractWithDefaultArg()) { hasSecondaryBaseWithAbstractWithDefaultArg.Abstract(); hasSecondaryBaseWithAbstractWithDefaultArg.AbstractWithNoDefaultArg(foo); } } using (var hasOverride = new HasOverrideOfHasPropertyWithDerivedType()) hasOverride.CauseRenamingError(); using (var qux = new Qux()) { new Bar(qux).Dispose(); } using (ComplexType complexType = TestFlag.Flag1) { } using (var typeMappedWithOperator = new TypeMappedWithOperator()) { int i = typeMappedWithOperator | 5; } using (Base <int> @base = new DerivedFromSpecializationOfUnsupportedTemplate()) { } CSharp.CSharp.FunctionInsideInlineNamespace(); using (CSharpTemplates.SpecialiseReturnOnly()) { } #pragma warning restore 0168 #pragma warning restore 0219 }
public void TestProperties() { var proprietor = new Proprietor(); Assert.That(proprietor.Parent, Is.EqualTo(0)); proprietor.Value = 20; Assert.That(proprietor.Value, Is.EqualTo(20)); proprietor.Prop = 50; Assert.That(proprietor.Prop, Is.EqualTo(50)); using (var qux = new Qux()) { using (var p = new P((IQux) qux) { Value = 20 }) { Assert.That(p.Value, Is.EqualTo(30)); p.Prop = 50; Assert.That(p.Prop, Is.EqualTo(150)); using (var complexType = new ComplexType()) { p.ComplexType = complexType; Assert.That(p.ComplexType.Check(), Is.EqualTo(5)); } Assert.That(p.Test, Is.True); Assert.That(p.IsBool, Is.False); } } }
/// <summary> /// Creates complex property with a default,unique name and passed complex type /// </summary> /// <param name="cpc"></param> /// <param name="parentComplexType">parent for new property</param> /// <param name="type">type for new property</param> /// <returns></returns> internal static Property CreateDefaultProperty(CommandProcessorContext cpc, ComplexType parentComplexType, ComplexType type) { var name = ModelHelper.GetUniqueName( typeof(ConceptualProperty), parentComplexType, ComplexConceptualProperty.DefaultComplexPropertyName); var cmd = new CreateComplexTypePropertyCommand(name, parentComplexType, type, false); var cp = new CommandProcessor(cpc, cmd); cp.Invoke(); return(cmd.Property); }