public void ConstructionWithTail() { var ctor = new ObjectConstructor(typeof(Point)); var context = JsonConvert.CreateImportContext(); const string json = "{ y: 456, z: 789, x: 123 }"; var result = ctor.CreateObject(context, JsonText.CreateReader(json)); var point = (Point)result.Object; Assert.AreEqual(123, point.X); Assert.AreEqual(456, point.Y); var tail = JsonBuffer.From(result.TailReader).GetMembersArray(); Assert.AreEqual(1, tail.Length); var z = tail[0]; Assert.AreEqual("z", z.Name); Assert.AreEqual(789, z.Buffer.GetNumber().ToInt32()); }
public void RemoveColumnThatReferenceThisOne_RemoveColumn() { //Construction phase Table table1 = new Table("t1"); Column column1 = ObjectConstructor.CreateColumn(new List <string>(), TypesKeyConstants.StringTypeKey, "c1"); table1.AddColumn(column1); Table table2 = new Table("t2"); Column column2 = ObjectConstructor.CreateColumn(new List <string>(), TypesKeyConstants.StringTypeKey, "c2"); table2.AddColumn(column2); column1.AddColumnThatReferenceThisOne(column2.columnName, column2); int numberOfColumnsThatReferenceColumn1After = column1.GetNumberOfColumnThatReferenceThisOne(); //TestPhase column1.RemoveColumnThatReferenceThisOne(column2.columnName); Assert.AreEqual(numberOfColumnsThatReferenceColumn1After - 1, column1.GetNumberOfColumnThatReferenceThisOne()); }
public void Insert_BadArguments_ConcretelyTableDoesntExist_NoticeInValidate() { IDatabaseContainer databaseContainer = ObjectConstructor.CreateDatabaseContainer(); Database database = new Database("TestInsert1"); databaseContainer.AddDatabase(database); string doenstExistTableNames = VariousFunctions.GenerateRandomString(6); while (database.ExistTable(doenstExistTableNames)) { doenstExistTableNames = VariousFunctions.GenerateRandomString(6); } Assert.IsFalse(database.ExistTable(doenstExistTableNames)); Insert insert = CreateInsert(databaseContainer, database.databaseName, doenstExistTableNames); Assert.IsFalse(insert.ValidateParameters()); insert.Execute(); }
public void RevoqueDatabasePrivilege_AllParamsExist_RowExist_DeleteRow() { IDatabaseContainer databaseContainer = ObjectConstructor.CreateDatabaseContainer(); ITable table = databaseContainer.GetDatabase(SystemeConstants.SystemDatabaseName).GetTable(SystemeConstants.PrivilegesOfProfilesOnDatabasesTableName); Row row = table.CreateRowDefinition(); row.GetCell(SystemeConstants.PrivilegesOfProfilesOnDatabasesProfileColumnName).data = SystemeConstants.DefaultProfile; row.GetCell(SystemeConstants.PrivilegesOfProfilesOnDatabasesDatabaseNameColumnName).data = SystemeConstants.DefaultDatabaseName; row.GetCell(SystemeConstants.PrivilegesOfProfilesOnDatabasesPrivilegeColumnName).data = SystemeConstants.CreatePrivilegeName; table.AddRow(row); int rowNumber = table.GetRowCount(); RevokeDatabasePrivilege revoqueDatabasePrivilege = CreateRevoqueDatabasePrivilege(databaseContainer, SystemeConstants.SystemDatabaseName, SystemeConstants.PrivilegesOfProfilesOnDatabasesTableName); revoqueDatabasePrivilege.SetData(SystemeConstants.DefaultProfile, SystemeConstants.DefaultDatabaseName, SystemeConstants.CreatePrivilegeName); Assert.IsTrue(revoqueDatabasePrivilege.ValidateParameters()); revoqueDatabasePrivilege.Execute(); Assert.AreEqual(rowNumber - 1, table.GetRowCount()); }
/// <summary> /// Initializes a new instance of the <see cref="JsonDictionaryContract"/> class. /// </summary> /// <param name="underlyingType">The underlying type for the contract.</param> public JsonDictionaryContract(Type underlyingType) : base(underlyingType) { ContractType = JsonContractType.Dictionary; Type keyType; Type valueType; if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(IDictionary <,>), out _genericCollectionDefinitionType)) { keyType = _genericCollectionDefinitionType.GetGenericArguments()[0]; valueType = _genericCollectionDefinitionType.GetGenericArguments()[1]; if (ReflectionUtils.IsGenericDefinition(UnderlyingType, typeof(IDictionary <,>))) { CreatedType = typeof(Dictionary <,>).MakeGenericType(keyType, valueType); } } else { ReflectionUtils.GetDictionaryKeyValueTypes(UnderlyingType, out keyType, out valueType); if (UnderlyingType == typeof(IDictionary)) { CreatedType = typeof(Dictionary <object, object>); } } if (keyType != null && valueType != null) { _parametrizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(CreatedType, typeof(KeyValuePair <,>).MakeGenericType(keyType, valueType)); if (!HasParametrizedCreator && underlyingType.Name == FSharpUtils.FSharpMapTypeName) { FSharpUtils.EnsureInitialized(underlyingType.Assembly()); _parametrizedCreator = FSharpUtils.CreateMap(keyType, valueType); } } ShouldCreateWrapper = !typeof(IDictionary).IsAssignableFrom(CreatedType); DictionaryKeyType = keyType; DictionaryValueType = valueType; }
void SpawnModule(PhotonPlayer owner, GameObject prefab, string prefabPath) { Vector2 pos = spawnPoints[0]; spawnPoints.RemoveAt(0); float rot = 0; Debug.Log("Spawning " + prefab.name + " for " + owner.ToString()); GameObject module = ObjectConstructor.ConstructModule(prefab, owner, pos, rot); inGameModules.Add(module, prefabPath); int controllerID = module.GetComponent <ModuleController>().info.view.viewID; foreach (PhotonPlayer player in playersInGame) { view.RPC("SpawnModule", player, prefabPath, owner, controllerID, pos, rot); } }
public void CreateSecurityProfile_ProfileExits_NoticeInValidate() { IDatabaseContainer databaseContainer = ObjectConstructor.CreateDatabaseContainer(); CreateSecurityProfile query = CreateCreateSecurityProfile(databaseContainer); ITable table = databaseContainer.GetDatabase(SystemeConstants.SystemDatabaseName).GetTable(SystemeConstants.ProfilesTableName); Column column = table.GetColumn(SystemeConstants.ProfileNameColumn); string profileName = VariousFunctions.GenerateRandomString(8); while (column.ExistCells(profileName)) { profileName = VariousFunctions.GenerateRandomString(8); } query.SetProfileName(profileName); query.Execute(); query = CreateCreateSecurityProfile(databaseContainer); query.SetProfileName(profileName); Assert.IsFalse(query.ValidateParameters()); }
void ExportCollectionToJS(List <IJSONExportable> col, ArrayInstance arrjs) { arrjs.Length = (uint)col.Count; for (int i = 0; i < col.Count; ++i) { var obj = col[i]; var json = arrjs[i] as ObjectInstance; if (json == null) { json = (arrjs[i] = ObjectConstructor.Create(engine, engine.Object.InstancePrototype)) as ObjectInstance; } Dictionary <string, double> values = obj.GetExportableValues(); foreach (string key in values.Keys) { json.SetPropertyValue(key, values[key], true); } } }
public RDMPCommandExecutionFactory(IActivateItems activator) { _activator = activator; foreach (Type proposerType in _activator.RepositoryLocator.CatalogueRepository.MEF.GetTypes <ICommandExecutionProposal>()) { try { ObjectConstructor constructor = new ObjectConstructor(); _proposers.Add((ICommandExecutionProposal)constructor.Construct(proposerType, activator)); } catch (Exception ex) { activator.GlobalErrorCheckNotifier.OnCheckPerformed( new CheckEventArgs("Could not instantiate ICommandExecutionProposal '" + proposerType + "'", CheckResult.Fail, ex)); } } }
public void DeleteTable_TableExist_DeleteThen() { AbstractParser xmlParser = CreateXMLParser(); Database testDatabase = ObjectConstructor.CreateDatabaseFull("test5"); xmlParser.SaveDatabase(testDatabase); IEnumerator <ITable> enumerator = testDatabase.GetTableEnumerator(); if (enumerator.MoveNext()) { Assert.IsTrue(xmlParser.ExistTable(testDatabase.databaseName, enumerator.Current.tableName)); xmlParser.DeleteTable(testDatabase.databaseName, enumerator.Current.tableName); Assert.IsFalse(xmlParser.ExistTable(testDatabase.databaseName, enumerator.Current.tableName)); } else { Assert.Fail("there are no tables idiot!"); } }
public void DeleteRow_TheRowIsReferedForAnotherRows_DontDeleteTheRowRefered() { //Construction phase IDatabaseContainer container = ObjectConstructor.CreateDatabaseContainer(); Database db = new Database("database1"); ITable table1 = new Table("table1"); Column column1t1 = new Column("c1t1", DataTypesFactory.GetDataTypesFactory().GetDataType(TypesKeyConstants.IntTypeKey)); table1.AddColumn(column1t1); table1.primaryKey.AddKey(column1t1); db.AddTable(table1); ITable table2 = new Table("table2"); Column column1t2 = new Column("c1t2", DataTypesFactory.GetDataTypesFactory().GetDataType(TypesKeyConstants.IntTypeKey)); table2.AddColumn(column1t2); table2.primaryKey.AddKey(column1t2); db.AddTable(table2); container.AddDatabase(db); table2.foreignKey.AddForeignKey(column1t2, column1t1); //Insert some data Row rowT1; int limit = 10; for (int i = 0; i <= limit; i++) { rowT1 = table1.CreateRowDefinition(); rowT1.GetCell(column1t1.columnName).data = "" + i; table1.AddRow(rowT1); } Row rowT2 = table2.CreateRowDefinition(); rowT2.GetCell(column1t2.columnName).data = "" + limit; table2.AddRow(rowT2); //Test int numberOfRows = table1.GetRowCount(); Delete delete = CreateDelete(container, db.databaseName, table1.tableName); delete.whereClause.AddCritery(column1t1.columnName, "" + 11, Operator.less); Assert.IsTrue(delete.ValidateParameters()); delete.Execute(); Assert.AreEqual(table2.GetRowCount(), numberOfRows - delete.GetAfectedRowCount()); Assert.IsTrue(table1.GetColumn(column1t1.columnName).ExistCells(rowT2.GetCell(column1t2.columnName).data)); }
public void Select_BadArguments_TableDoesntExist_NoticedInValidateParameters() { IDatabaseContainer databaseContainer = ObjectConstructor.CreateDatabaseContainer(); Database database = ObjectConstructor.CreateDatabaseFull("test1"); databaseContainer.AddDatabase(database); string noInDatabaseTableName = VariousFunctions.GenerateRandomString(10); //Do while instead of while is okkkkk while (database.ExistTable(noInDatabaseTableName)) { noInDatabaseTableName = VariousFunctions.GenerateRandomString(10); } Select select = CreateSelect(databaseContainer, database.databaseName, noInDatabaseTableName, true); Assert.IsFalse(select.ValidateParameters()); select.Execute(); Assert.AreEqual(0, select.GetAfectedRowCount()); Console.WriteLine(select.GetResult()); //It is only to see the message not to trace execution }
public void Select_GoodArguments_TableEmpty_ShouldntFindResults() { IDatabaseContainer databaseContainer = ObjectConstructor.CreateDatabaseContainer(); Database database = new Database("aa"); databaseContainer.AddDatabase(database); //Notice the references. (this database object references, no the 'referencias') ITable table = new Table("table1"); Column column = new Column("c1", DataTypesFactory.GetDataTypesFactory().GetDataType(TypesKeyConstants.StringTypeKey)); table.AddColumn(column); database.AddTable(table); Select select = CreateSelect(databaseContainer, database.databaseName, table.tableName, true); select.whereClause.AddCritery(column.columnName, table.GetColumn(column.columnName).dataType.GetDataTypeDefaultValue(), Operator.equal); Assert.IsTrue(select.ValidateParameters()); Assert.IsTrue(table.GetRowCount() == 0); //Maybe assert.equal select.Execute(); Assert.IsTrue(select.GetAfectedRowCount() == 0); }
public static Table CreateTableModel2(string tableName) { List <Column> columnList = new List <Column>(); columnList.Add(ObjectConstructor.CreateColumn(new List <string>(), TypesKeyConstants.StringTypeKey, "col1")); columnList.Add(ObjectConstructor.CreateColumn(new List <string>(), TypesKeyConstants.StringTypeKey, "col2")); columnList.Add(ObjectConstructor.CreateColumn(new List <string>(), TypesKeyConstants.StringTypeKey, "col8")); List <List <string> > cellDatas = new List <List <string> >(); cellDatas.Add(new List <string>()); cellDatas.Add(new List <string>()); cellDatas[0].Add("aaa"); cellDatas[0].Add("aaafsdf"); cellDatas[0].Add("a323f"); cellDatas[1].Add("cccccc"); cellDatas[1].Add("hhhhhh"); cellDatas[1].Add("ffffff"); return(ObjectConstructor.CreateFullTable(tableName, columnList, cellDatas)); }
public void ConstructValidTests() { var constructor = new ObjectConstructor(); var testarg = new TestArg() { Text = "amagad" }; var testarg2 = new TestArg2() { Text = "amagad" }; //anyone can construct on object! constructor.Construct(typeof(TestClass1), testarg); constructor.Construct(typeof(TestClass1), testarg2); //basic case - identical Type parameter var instance = (TestClass2)constructor.Construct(typeof(TestClass2), testarg); Assert.AreEqual(instance.A.Text, "amagad"); //also allowed because testarg2 is a testarg derrived class constructor.Construct(typeof(TestClass2), testarg2); //not allowed because class 3 explicitly requires a TestArg2 Assert.Throws <ObjectLacksCompatibleConstructorException>(() => constructor.Construct(typeof(TestClass3), testarg)); //allowed constructor.Construct(typeof(TestClass3), testarg2); //valid because even though both constructors are valid there is one that matches EXACTLY on Type constructor.Construct(typeof(TestClass4), testarg2); var testarg3 = new TestArg3(); //not valid because there are 2 constructors that are both base classes of TestArg3 so ObjectConstructor doesn't know which to invoke var ex = Assert.Throws <ObjectLacksCompatibleConstructorException>(() => constructor.Construct(typeof(TestClass4), testarg3)); Assert.IsTrue(ex.Message.Contains("Could not pick the correct constructor between")); //exactly the same as the above case but one constructor has been decorated with ImportingConstructor constructor.Construct(typeof(TestClass5), testarg3); }
public JsValue Parse(JsValue thisObject, JsValue[] arguments) { var parser = new JsonParser(_engine); var res = parser.Parse(TypeConverter.ToString(arguments[0])); if (arguments.Length > 1) { this._reviver = arguments[1]; ObjectInstance revRes = ObjectConstructor.CreateObjectConstructor(_engine).Construct(Arguments.Empty); revRes.DefineOwnProperty( "", new PropertyDescriptor( value: res, flags: PropertyFlag.ConfigurableEnumerableWritable ), false ); return(AbstractWalkOperation(revRes, "")); } return(res); }
public void RevokePrivilege_AllParamsExistsButTheCombinationIsNotValid_NoticeInValidate() { //Prefase IDatabaseContainer databaseContainer = ObjectConstructor.CreateDatabaseContainer(); CreateSecurityProfile createSecurityProfile = TestCreateSecurityProfile.CreateCreateSecurityProfile(databaseContainer); Column profileNamesColumn = databaseContainer.GetDatabase(SystemeConstants.SystemDatabaseName).GetTable(SystemeConstants.ProfilesTableName).GetColumn(SystemeConstants.ProfileNameColumn); string profileName = VariousFunctions.GenerateRandomString(8); while (profileNamesColumn.ExistCells(profileName)) { profileName = VariousFunctions.GenerateRandomString(8); } createSecurityProfile.SetProfileName(profileName); createSecurityProfile.ValidateParameters(); createSecurityProfile.Execute(); //TEST RevoquePrivilege revoquePrivilege = CreateRevokePrivilege(databaseContainer, SystemeConstants.SystemDatabaseName, SystemeConstants.PrivilegesOfProfilesOnTablesTableName); revoquePrivilege.SetData(profileName, SystemeConstants.SystemDatabaseName, SystemeConstants.ProfilesTableName, SystemeConstants.InsertPrivilegeName); Assert.IsFalse(revoquePrivilege.ValidateParameters()); }
private RDMPContextMenuStrip ConstructMenu(ObjectConstructor objectConstructor, Type type, RDMPContextMenuStripArgs args, object o) { //there is a compatible menu Type known //parameter 1 must be args //parameter 2 must be object compatible Type var menu = (RDMPContextMenuStrip)objectConstructor.ConstructIfPossible(type, args, o); if (menu != null) { menu.AddCommonMenuItems(this); } if (menu != null) { OrderMenuItems(menu.Items); } return(menu); }
/// <summary> /// Create a factory function that can be used to create instances of a JsonConverter described by the /// argument type. The returned function can then be used to either invoke the converter's default ctor, or any /// parameterized constructors by way of an object array. /// </summary> private static Func <object[], JsonConverter> GetJsonConverterCreator(Type converterType) { Func <object> defaultConstructor = (ReflectionUtils.HasDefaultConstructor(converterType, false)) ? ReflectionDelegateFactory.CreateDefaultConstructor <object>(converterType) : null; return((parameters) => { try { if (parameters != null) { ObjectConstructor <object> parameterizedConstructor = null; Type[] paramTypes = parameters.Select(param => param.GetType()).ToArray(); ConstructorInfo parameterizedConstructorInfo = converterType.GetConstructor(paramTypes); if (null != parameterizedConstructorInfo) { parameterizedConstructor = ReflectionDelegateFactory.CreateParametrizedConstructor(parameterizedConstructorInfo); return (JsonConverter)parameterizedConstructor(parameters); } else { throw new JsonException("No matching parameterized constructor found for '{0}'.".FormatWith(CultureInfo.InvariantCulture, converterType)); } } if (defaultConstructor == null) { throw new JsonException("No parameterless constructor defined for '{0}'.".FormatWith(CultureInfo.InvariantCulture, converterType)); } return (JsonConverter)defaultConstructor(); } catch (Exception ex) { throw new JsonException("Error creating '{0}'.".FormatWith(CultureInfo.InvariantCulture, converterType), ex); } }); }
public void DeleteUser_TheUserExist_DeleteUser() { IDatabaseContainer databaseContainer = ObjectConstructor.CreateDatabaseContainer(); ITable table = databaseContainer.GetDatabase(SystemeConstants.SystemDatabaseName).GetTable(SystemeConstants.UsersTableName); Column column = table.GetColumn(SystemeConstants.UsersNameColumnName); string username = VariousFunctions.GenerateRandomString(8); while (column.ExistCells(username)) { username = VariousFunctions.GenerateRandomString(8); } Row row = table.CreateRowDefinition(); row.GetCell(SystemeConstants.UsersNameColumnName).data = username; table.AddRow(row); DeleteUser deleteUser = CreateDeleteUser(databaseContainer); deleteUser.SetTargetUserName(username); Assert.IsTrue(deleteUser.ValidateParameters()); deleteUser.Execute(); Assert.IsFalse(column.ExistCells(username)); }
public void InsertBadArguments_ConcretelyNotEnougthParameters_NoticeInValidate() { IDatabaseContainer databaseContainer = ObjectConstructor.CreateDatabaseContainer(); Database database = new Database("TestInsert2"); ITable table = new Table("table1"); Column column1 = new Column("c1", DataTypesFactory.GetDataTypesFactory().GetDataType(TypesKeyConstants.StringTypeKey)); Column column2 = new Column("c2", DataTypesFactory.GetDataTypesFactory().GetDataType(TypesKeyConstants.IntTypeKey)); table.AddColumn(column1); table.AddColumn(column2); database.AddTable(table); databaseContainer.AddDatabase(database); int rowCount = table.GetRowCount(); Insert insert = CreateInsert(databaseContainer, database.databaseName, table.tableName); string[] rowData = { "aaa" }; insert.AddValue(rowData[0]); Assert.IsTrue(table.GetColumnCount() > rowData.Length); Assert.IsFalse(insert.ValidateParameters()); insert.Execute(); Assert.AreEqual(rowCount, table.GetRowCount()); }
private bool HandleIfICustomUIDrivenClass(string value, Type concreteType, out object answer) { answer = null; //if it is data driven if (typeof(ICustomUIDrivenClass).IsAssignableFrom(concreteType)) { ICustomUIDrivenClass result; try { Type t = CatalogueRepository.MEF.GetType(concreteType.FullName); ObjectConstructor constructor = new ObjectConstructor(); result = (ICustomUIDrivenClass)constructor.Construct(t, (ICatalogueRepository)Repository); } catch (Exception e) { throw new Exception("Failed to create an ICustomUIDrivenClass of type " + concreteType.FullName + " make sure that you mark your class as public, commit it to the catalogue and mark it with the export ''", e); } try { result.RestoreStateFrom(value);//, (CatalogueRepository)Repository); } catch (Exception e) { throw new Exception("RestoreState failed on your ICustomUIDrivenClass called " + concreteType.FullName + " the restore value was the string value '" + value + "'", e); } answer = result; return(true); } //it is not a custom ui driven type return(false); }
public void WrongArguments_TableDoesntExist_True() { bool parametros, tablaBorrada = false; Database db = ObjectConstructor.CreateDatabaseFull("db1"); List <Column> columnas = new List <Column>(); List <List <string> > celdas = new List <List <string> >(); ITable t = ObjectConstructor.CreateFullTable("table1", columnas, celdas); IDatabaseContainer container = ObjectConstructor.CreateDatabaseContainer(); Drop drop = CreateDrop(container, db.databaseName, t.tableName); parametros = drop.ValidateParameters(); if (parametros) { drop.Execute(); if (db.ExistTable(t.tableName) == false) { tablaBorrada = true; } } Assert.AreEqual(parametros, false); Assert.AreEqual(tablaBorrada, false); }
public void BuildClassWithMultipleParameterConstructor() { var complexDetails = GetComplexClassDetails(); var simpleDetails = GetSimpleClassDetails(); var rootDetails = new BuildDetails { ConstructorToUse = UtilityExtensions.GetConstructors(typeof(MultipleConstructorParamsClass)).First(), TypeToCreate = typeof(MultipleConstructorParamsClass), Dependencies = new List <BuildDetails> { simpleDetails, complexDetails } }; ObjectConstructor ctor = new ObjectConstructor(); var builtObject = ctor.Build(rootDetails) as MultipleConstructorParamsClass; Assert.NotNull(builtObject); Assert.NotNull(builtObject.Simple); Assert.NotNull(builtObject.Complex); }
public void Equals_TwoNoEqualRowSameColumnDiferentData_ReturnFalse() { IEqualityComparer <Row> rowComparer = CreateRowComparer(); List <string> rowData1 = new List <string>(); List <string> rowData2 = new List <string>(); rowData1.Add("aa"); rowData1.Add("cc"); rowData2.Add("bb"); rowData2.Add("dd"); List <Column> columnList1 = new List <Column>(); List <Column> columnList2 = new List <Column>(); columnList1.Add(ObjectConstructor.CreateColumn(new List <string>(), TypesKeyConstants.StringTypeKey, "col1")); columnList1.Add(ObjectConstructor.CreateColumn(new List <string>(), TypesKeyConstants.StringTypeKey, "col2")); columnList2.Add(ObjectConstructor.CreateColumn(new List <string>(), TypesKeyConstants.StringTypeKey, "col1")); columnList2.Add(ObjectConstructor.CreateColumn(new List <string>(), TypesKeyConstants.StringTypeKey, "col2")); Row row1 = ObjectConstructor.CreateRow(rowData1, columnList1); Row row2 = ObjectConstructor.CreateRow(rowData2, columnList2); Assert.IsFalse(rowComparer.Equals(row1, row2)); }
public IDynamic FromPropertyDescriptor(IPropertyDescriptor desc) { // 8.10.4 FromPropertyDescriptor ( Desc ) if (desc == null) // Property descriptors use null rather than undefined to simplify interaction. { return(Undefined); } var obj = ObjectConstructor.Op_Construct(EmptyArgs); if (desc.IsDataDescriptor) { var value = CreateDataDescriptor(desc.Value, true, true, true); var writable = CreateDataDescriptor(CreateBoolean(desc.Writable.Value), true, true, true); obj.DefineOwnProperty("value", value, false); obj.DefineOwnProperty("writable", writable, false); } else { Debug.Assert(desc.IsAccessorDescriptor); var get = CreateDataDescriptor(desc.Get, true, true, true); var set = CreateDataDescriptor(desc.Set, true, true, true); obj.DefineOwnProperty("get", get, false); obj.DefineOwnProperty("set", set, false); } var enumerable = CreateDataDescriptor(CreateBoolean(desc.Enumerable.Value), true, true, true); var configurable = CreateDataDescriptor(CreateBoolean(desc.Configurable.Value), true, true, true); obj.DefineOwnProperty("enumerable", enumerable, false); obj.DefineOwnProperty("configurable", configurable, false); return(obj); }
public void CreateTable_GoodArguments_TableDoenstExist_CreateNewTable() { IDatabaseContainer container = ObjectConstructor.CreateDatabaseContainer(); Database database = new Database("testDatabase"); container.AddDatabase(database); string tableName = "testTable"; Assert.IsFalse(database.ExistTable(tableName)); Create create = CreateCreate(container, database.databaseName, tableName); List <Tuple <string, string> > columnsAndTypes = new List <Tuple <string, string> >() { new Tuple <string, string>("c1", TypesKeyConstants.StringTypeKey), new Tuple <string, string>("c2", TypesKeyConstants.IntTypeKey), new Tuple <string, string>("c3", TypesKeyConstants.DoubleTypeKey) }; foreach (Tuple <string, string> tuple in columnsAndTypes) { create.AddColumn(tuple.Item1, tuple.Item2); } Assert.IsTrue(create.ValidateParameters()); create.Execute(); Assert.IsTrue(database.ExistTable(tableName)); ITable table = database.GetTable(tableName); bool allColumnExist = true; bool correctDataType = true; for (int i = 0; i < columnsAndTypes.Count && allColumnExist; i++) { allColumnExist = table.ExistColumn(columnsAndTypes[i].Item1); if (allColumnExist) { correctDataType = table.GetColumn(columnsAndTypes[i].Item1).dataType.GetSimpleTextValue().Equals(columnsAndTypes[i].Item2); } } Assert.IsTrue(allColumnExist); Assert.IsTrue(correctDataType); Console.WriteLine(create.GetResult()); }
public void Insert_BadArguments_PKViolated_NoticeInValidate() { //Construct IDatabaseContainer databaseContainer = ObjectConstructor.CreateDatabaseContainer(); Database database = new Database("database"); ITable table = new Table("table"); Column column = new Column("c1", DataTypesFactory.GetDataTypesFactory().GetDataType(TypesKeyConstants.StringTypeKey)); table.AddColumn(column); table.primaryKey.AddKey(column); database.AddTable(table); databaseContainer.AddDatabase(database); Row row = table.CreateRowDefinition(); row.GetCell(column.columnName).data = "aaaa"; table.AddRow(row); Insert insert = CreateInsert(databaseContainer, database.databaseName, table.tableName); insert.AddValue(row.GetCell(column.columnName).data); //Test Assert.IsFalse(insert.ValidateParameters()); insert.Execute(); }
internal IWrappedCollection CreateWrapper(object list) { if (this._genericWrapperCreator == null) { Type type; Type[] typeArguments = new Type[] { this.CollectionItemType }; this._genericWrapperType = typeof(CollectionWrapper <>).MakeGenericType(typeArguments); if (ReflectionUtils.InheritsGenericDefinition(this._genericCollectionDefinitionType, typeof(List <>)) || (this._genericCollectionDefinitionType.GetGenericTypeDefinition() == typeof(IEnumerable <>))) { Type[] typeArray2 = new Type[] { this.CollectionItemType }; type = typeof(ICollection <>).MakeGenericType(typeArray2); } else { type = this._genericCollectionDefinitionType; } Type[] types = new Type[] { type }; ConstructorInfo constructor = this._genericWrapperType.GetConstructor(types); this._genericWrapperCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(constructor); } object[] args = new object[] { list }; return((IWrappedCollection)this._genericWrapperCreator(args)); }
public ObjectConstructor <object> BuildMapCreator <TKey, TValue>() { Type genericMapType = _mapType.MakeGenericType(typeof(TKey), typeof(TValue)); ConstructorInfo ctor = genericMapType.GetConstructor( new[] { typeof(IEnumerable <Tuple <TKey, TValue> >) } ); ObjectConstructor <object> ctorDelegate = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(ctor); ObjectConstructor <object> creator = args => { // convert dictionary KeyValuePairs to Tuples IEnumerable <KeyValuePair <TKey, TValue> > values = (IEnumerable <KeyValuePair <TKey, TValue> >)args[0] !; IEnumerable <Tuple <TKey, TValue> > tupleValues = values.Select( kv => new Tuple <TKey, TValue>(kv.Key, kv.Value) ); return(ctorDelegate(tupleValues)); }; return(creator); }
// Token: 0x06000A94 RID: 2708 // RVA: 0x0004156C File Offset: 0x0003F76C internal IWrappedCollection CreateWrapper(object list) { if (this._genericWrapperCreator == null) { this._genericWrapperType = typeof(CollectionWrapper<>).MakeGenericType(new Type[] { this.CollectionItemType }); Type type; if (!ReflectionUtils.InheritsGenericDefinition(this._genericCollectionDefinitionType, typeof(List<>))) { if (this._genericCollectionDefinitionType.GetGenericTypeDefinition() != typeof(IEnumerable<>)) { type = this._genericCollectionDefinitionType; goto IL_8B; } } type = typeof(ICollection<>).MakeGenericType(new Type[] { this.CollectionItemType }); IL_8B: ConstructorInfo constructor = this._genericWrapperType.GetConstructor(new Type[] { type }); this._genericWrapperCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParametrizedConstructor(constructor); } return (IWrappedCollection)this._genericWrapperCreator(new object[] { list }); }
private object CreateObjectUsingCreatorWithParameters(JsonReader reader, JsonObjectContract contract, JsonProperty containerProperty, ObjectConstructor<object> creator, string id) { ValidationUtils.ArgumentNotNull(creator, "creator"); // only need to keep a track of properies presence if they are required or a value should be defaulted if missing Dictionary<JsonProperty, PropertyPresence> propertiesPresence = (contract.HasRequiredOrDefaultValueProperties || HasFlag(Serializer._defaultValueHandling, DefaultValueHandling.Populate)) ? contract.Properties.ToDictionary(m => m, m => PropertyPresence.None) : null; Type objectType = contract.UnderlyingType; if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) { string parameters = string.Join(", ", contract.CreatorParameters.Select(p => p.PropertyName).ToArray()); TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, "Deserializing {0} using creator with parameters: {1}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType, parameters)), null); } IDictionary<string, object> extensionData; IDictionary<JsonProperty, object> propertyValues = ResolvePropertyAndCreatorValues(contract, containerProperty, reader, objectType, out extensionData); object[] creatorParameterValues = new object[contract.CreatorParameters.Count]; IDictionary<JsonProperty, object> remainingPropertyValues = new Dictionary<JsonProperty, object>(); foreach (KeyValuePair<JsonProperty, object> propertyValue in propertyValues) { JsonProperty property = propertyValue.Key; JsonProperty matchingCreatorParameter; if (contract.CreatorParameters.Contains(property)) { matchingCreatorParameter = property; } else { // check to see if a parameter with the same name as the underlying property name exists and match to that matchingCreatorParameter = contract.CreatorParameters.ForgivingCaseSensitiveFind(p => p.PropertyName, property.UnderlyingName); } if (matchingCreatorParameter != null) { int i = contract.CreatorParameters.IndexOf(matchingCreatorParameter); creatorParameterValues[i] = propertyValue.Value; } else { remainingPropertyValues.Add(propertyValue); } if (propertiesPresence != null) { // map from creator property to normal property JsonProperty presenceProperty = propertiesPresence.Keys.FirstOrDefault(p => p.PropertyName == property.PropertyName); if (presenceProperty != null) propertiesPresence[presenceProperty] = (propertyValue.Value == null) ? PropertyPresence.Null : PropertyPresence.Value; } } object createdObject = creator(creatorParameterValues); if (id != null) AddReference(reader, id, createdObject); OnDeserializing(reader, contract, createdObject); // go through unused values and set the newly created object's properties foreach (KeyValuePair<JsonProperty, object> remainingPropertyValue in remainingPropertyValues) { JsonProperty property = remainingPropertyValue.Key; object value = remainingPropertyValue.Value; if (ShouldSetPropertyValue(property, value)) { property.ValueProvider.SetValue(createdObject, value); } else if (!property.Writable && value != null) { // handle readonly collection/dictionary properties JsonContract propertyContract = Serializer._contractResolver.ResolveContract(property.PropertyType); if (propertyContract.ContractType == JsonContractType.Array) { JsonArrayContract propertyArrayContract = (JsonArrayContract)propertyContract; object createdObjectCollection = property.ValueProvider.GetValue(createdObject); if (createdObjectCollection != null) { IWrappedCollection createdObjectCollectionWrapper = propertyArrayContract.CreateWrapper(createdObjectCollection); IWrappedCollection newValues = propertyArrayContract.CreateWrapper(value); foreach (object newValue in newValues) { createdObjectCollectionWrapper.Add(newValue); } } } else if (propertyContract.ContractType == JsonContractType.Dictionary) { JsonDictionaryContract dictionaryContract = (JsonDictionaryContract)propertyContract; object createdObjectDictionary = property.ValueProvider.GetValue(createdObject); if (createdObjectDictionary != null) { IDictionary targetDictionary = (dictionaryContract.ShouldCreateWrapper) ? dictionaryContract.CreateWrapper(createdObjectDictionary) : (IDictionary)createdObjectDictionary; IDictionary newValues = (dictionaryContract.ShouldCreateWrapper) ? dictionaryContract.CreateWrapper(value) : (IDictionary)value; foreach (DictionaryEntry newValue in newValues) { targetDictionary.Add(newValue.Key, newValue.Value); } } } } } if (extensionData != null) { foreach (KeyValuePair<string, object> e in extensionData) { contract.ExtensionDataSetter(createdObject, e.Key, e.Value); } } EndObject(createdObject, reader, contract, reader.Depth, propertiesPresence); OnDeserialized(reader, contract, createdObject); return createdObject; }
internal IWrappedCollection CreateWrapper(object list) { if (_genericWrapperCreator == null) { _genericWrapperType = typeof(CollectionWrapper<>).MakeGenericType(CollectionItemType); Type constructorArgument; if (ReflectionUtils.InheritsGenericDefinition(_genericCollectionDefinitionType, typeof(List<>)) || _genericCollectionDefinitionType.GetGenericTypeDefinition() == typeof(IEnumerable<>)) { constructorArgument = typeof(ICollection<>).MakeGenericType(CollectionItemType); } else { constructorArgument = _genericCollectionDefinitionType; } ConstructorInfo genericWrapperConstructor = _genericWrapperType.GetConstructor(new[] { constructorArgument }); _genericWrapperCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(genericWrapperConstructor); } return (IWrappedCollection)_genericWrapperCreator(list); }
/// <summary> /// Initializes a new instance of the <see cref="JsonArrayContract"/> class. /// </summary> /// <param name="underlyingType">The underlying type for the contract.</param> public JsonArrayContract(Type underlyingType) : base(underlyingType) { ContractType = JsonContractType.Array; IsArray = CreatedType.IsArray; bool canDeserialize; Type tempCollectionType; if (IsArray) { CollectionItemType = ReflectionUtils.GetCollectionItemType(UnderlyingType); IsReadOnlyOrFixedSize = true; _genericCollectionDefinitionType = typeof(List<>).MakeGenericType(CollectionItemType); canDeserialize = true; IsMultidimensionalArray = (IsArray && UnderlyingType.GetArrayRank() > 1); } else if (typeof(IList).IsAssignableFrom(underlyingType)) { if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(ICollection<>), out _genericCollectionDefinitionType)) { CollectionItemType = _genericCollectionDefinitionType.GetGenericArguments()[0]; } else { CollectionItemType = ReflectionUtils.GetCollectionItemType(underlyingType); } if (underlyingType == typeof(IList)) { CreatedType = typeof(List<object>); } if (CollectionItemType != null) { _parameterizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(underlyingType, CollectionItemType); } IsReadOnlyOrFixedSize = ReflectionUtils.InheritsGenericDefinition(underlyingType, typeof(ReadOnlyCollection<>)); canDeserialize = true; } else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(ICollection<>), out _genericCollectionDefinitionType)) { CollectionItemType = _genericCollectionDefinitionType.GetGenericArguments()[0]; if (ReflectionUtils.IsGenericDefinition(underlyingType, typeof(ICollection<>)) || ReflectionUtils.IsGenericDefinition(underlyingType, typeof(IList<>))) { CreatedType = typeof(List<>).MakeGenericType(CollectionItemType); } #if !(NET20 || NET35) if (ReflectionUtils.IsGenericDefinition(underlyingType, typeof(ISet<>))) { CreatedType = typeof(HashSet<>).MakeGenericType(CollectionItemType); } #endif _parameterizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(underlyingType, CollectionItemType); canDeserialize = true; ShouldCreateWrapper = true; } #if !(NET40 || NET35 || NET20 || PORTABLE40) else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(IReadOnlyCollection<>), out tempCollectionType)) { CollectionItemType = tempCollectionType.GetGenericArguments()[0]; if (ReflectionUtils.IsGenericDefinition(underlyingType, typeof(IReadOnlyCollection<>)) || ReflectionUtils.IsGenericDefinition(underlyingType, typeof(IReadOnlyList<>))) { CreatedType = typeof(ReadOnlyCollection<>).MakeGenericType(CollectionItemType); } _genericCollectionDefinitionType = typeof(List<>).MakeGenericType(CollectionItemType); _parameterizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(CreatedType, CollectionItemType); IsReadOnlyOrFixedSize = true; canDeserialize = HasParameterizedCreatorInternal; } #endif else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(IEnumerable<>), out tempCollectionType)) { CollectionItemType = tempCollectionType.GetGenericArguments()[0]; if (ReflectionUtils.IsGenericDefinition(UnderlyingType, typeof(IEnumerable<>))) { CreatedType = typeof(List<>).MakeGenericType(CollectionItemType); } _parameterizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(underlyingType, CollectionItemType); #if !(NET35 || NET20) if (!HasParameterizedCreatorInternal && underlyingType.Name == FSharpUtils.FSharpListTypeName) { FSharpUtils.EnsureInitialized(underlyingType.Assembly()); _parameterizedCreator = FSharpUtils.CreateSeq(CollectionItemType); } #endif if (underlyingType.IsGenericType() && underlyingType.GetGenericTypeDefinition() == typeof(IEnumerable<>)) { _genericCollectionDefinitionType = tempCollectionType; IsReadOnlyOrFixedSize = false; ShouldCreateWrapper = false; canDeserialize = true; } else { _genericCollectionDefinitionType = typeof(List<>).MakeGenericType(CollectionItemType); IsReadOnlyOrFixedSize = true; ShouldCreateWrapper = true; canDeserialize = HasParameterizedCreatorInternal; } } else { // types that implement IEnumerable and nothing else canDeserialize = false; ShouldCreateWrapper = true; } CanDeserialize = canDeserialize; #if (NET20 || NET35) if (CollectionItemType != null && ReflectionUtils.IsNullableType(CollectionItemType)) { // bug in .NET 2.0 & 3.5 that List<Nullable<T>> throws an error when adding null via IList.Add(object) // wrapper will handle calling Add(T) instead if (ReflectionUtils.InheritsGenericDefinition(CreatedType, typeof(List<>), out tempCollectionType) || (IsArray && !IsMultidimensionalArray)) { ShouldCreateWrapper = true; } } #endif #if !(NET20 || NET35 || NET40) Type immutableCreatedType; ObjectConstructor<object> immutableParameterizedCreator; if (ImmutableCollectionsUtils.TryBuildImmutableForArrayContract(underlyingType, CollectionItemType, out immutableCreatedType, out immutableParameterizedCreator)) { CreatedType = immutableCreatedType; _parameterizedCreator = immutableParameterizedCreator; IsReadOnlyOrFixedSize = true; CanDeserialize = true; } #endif }
internal IWrappedDictionary CreateWrapper(object dictionary) { if (_genericWrapperCreator == null) { _genericWrapperType = typeof(DictionaryWrapper<,>).MakeGenericType(DictionaryKeyType, DictionaryValueType); ConstructorInfo genericWrapperConstructor = _genericWrapperType.GetConstructor(new[] { _genericCollectionDefinitionType }); _genericWrapperCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(genericWrapperConstructor); } return (IWrappedDictionary)_genericWrapperCreator(dictionary); }
/// <summary> /// Initializes a new instance of the <see cref="JsonDictionaryContract"/> class. /// </summary> /// <param name="underlyingType">The underlying type for the contract.</param> public JsonDictionaryContract(Type underlyingType) : base(underlyingType) { ContractType = JsonContractType.Dictionary; Type keyType; Type valueType; if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(IDictionary<,>), out _genericCollectionDefinitionType)) { keyType = _genericCollectionDefinitionType.GetGenericArguments()[0]; valueType = _genericCollectionDefinitionType.GetGenericArguments()[1]; if (ReflectionUtils.IsGenericDefinition(UnderlyingType, typeof(IDictionary<,>))) CreatedType = typeof(Dictionary<,>).MakeGenericType(keyType, valueType); #if !(NET40 || NET35 || NET20 || PORTABLE40) IsReadOnlyOrFixedSize = ReflectionUtils.InheritsGenericDefinition(underlyingType, typeof(ReadOnlyDictionary<,>)); #endif } #if !(NET40 || NET35 || NET20 || PORTABLE40) else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(IReadOnlyDictionary<,>), out _genericCollectionDefinitionType)) { keyType = _genericCollectionDefinitionType.GetGenericArguments()[0]; valueType = _genericCollectionDefinitionType.GetGenericArguments()[1]; if (ReflectionUtils.IsGenericDefinition(UnderlyingType, typeof(IReadOnlyDictionary<,>))) CreatedType = typeof(ReadOnlyDictionary<,>).MakeGenericType(keyType, valueType); IsReadOnlyOrFixedSize = true; } #endif else { ReflectionUtils.GetDictionaryKeyValueTypes(UnderlyingType, out keyType, out valueType); if (UnderlyingType == typeof(IDictionary)) CreatedType = typeof(Dictionary<object, object>); } if (keyType != null && valueType != null) { _parameterizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(CreatedType, typeof(KeyValuePair<,>).MakeGenericType(keyType, valueType)); #if !(NET35 || NET20) if (!HasParameterizedCreatorInternal && underlyingType.Name == FSharpUtils.FSharpMapTypeName) { FSharpUtils.EnsureInitialized(underlyingType.Assembly()); _parameterizedCreator = FSharpUtils.CreateMap(keyType, valueType); } #endif } ShouldCreateWrapper = !typeof(IDictionary).IsAssignableFrom(CreatedType); DictionaryKeyType = keyType; DictionaryValueType = valueType; #if (NET20 || NET35) if (DictionaryValueType != null && ReflectionUtils.IsNullableType(DictionaryValueType)) { Type tempDictioanryType; // bug in .NET 2.0 & 3.5 that Dictionary<TKey, Nullable<TValue>> throws an error when adding null via IDictionary[key] = object // wrapper will handle calling Add(T) instead if (ReflectionUtils.InheritsGenericDefinition(CreatedType, typeof(Dictionary<,>), out tempDictioanryType)) { ShouldCreateWrapper = true; } } #endif #if !(NET20 || NET35 || NET40) Type immutableCreatedType; ObjectConstructor<object> immutableParameterizedCreator; if (ImmutableCollectionsUtils.TryBuildImmutableForDictionaryContract(underlyingType, DictionaryKeyType, DictionaryValueType, out immutableCreatedType, out immutableParameterizedCreator)) { CreatedType = immutableCreatedType; _parameterizedCreator = immutableParameterizedCreator; IsReadOnlyOrFixedSize = true; } #endif }
internal static bool TryBuildImmutableForDictionaryContract(Type underlyingType, Type keyItemType, Type valueItemType, out Type createdType, out ObjectConstructor<object> parameterizedCreator) { if (underlyingType.IsGenericType()) { Type underlyingTypeDefinition = underlyingType.GetGenericTypeDefinition(); string name = underlyingTypeDefinition.FullName; ImmutableCollectionTypeInfo definition = DictionaryContractImmutableCollectionDefinitions.FirstOrDefault(d => d.ContractTypeName == name); if (definition != null) { Type createdTypeDefinition = underlyingTypeDefinition.Assembly().GetType(definition.CreatedTypeName); Type builderTypeDefinition = underlyingTypeDefinition.Assembly().GetType(definition.BuilderTypeName); if (createdTypeDefinition != null && builderTypeDefinition != null) { MethodInfo mb = builderTypeDefinition.GetMethods().FirstOrDefault(m => { ParameterInfo[] parameters = m.GetParameters(); return m.Name == "CreateRange" && parameters.Length == 1 && parameters[0].ParameterType.IsGenericType() && parameters[0].ParameterType.GetGenericTypeDefinition() == typeof(IEnumerable<>); }); if (mb != null) { createdType = createdTypeDefinition.MakeGenericType(keyItemType, valueItemType); MethodInfo method = mb.MakeGenericMethod(keyItemType, valueItemType); parameterizedCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParametrizedConstructor(method); return true; } } } } createdType = null; parameterizedCreator = null; return false; }
/// <summary> /// Initializes a new instance of the <see cref="JsonArrayContract"/> class. /// </summary> /// <param name="underlyingType">The underlying type for the contract.</param> public JsonArrayContract(Type underlyingType) : base(underlyingType) { ContractType = JsonContractType.Array; IsArray = CreatedType.IsArray; bool canDeserialize; Type tempCollectionType; if (IsArray) { CollectionItemType = ReflectionUtils.GetCollectionItemType(UnderlyingType); IsReadOnlyOrFixedSize = true; _genericCollectionDefinitionType = typeof(List<>).MakeGenericType(CollectionItemType); canDeserialize = true; IsMultidimensionalArray = (IsArray && UnderlyingType.GetArrayRank() > 1); } else if (typeof(IList).IsAssignableFrom(underlyingType)) { if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(ICollection<>), out _genericCollectionDefinitionType)) CollectionItemType = _genericCollectionDefinitionType.GetGenericArguments()[0]; else CollectionItemType = ReflectionUtils.GetCollectionItemType(underlyingType); if (underlyingType == typeof(IList)) CreatedType = typeof(List<object>); if (CollectionItemType != null) _parametrizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(underlyingType, CollectionItemType); IsReadOnlyOrFixedSize = ReflectionUtils.InheritsGenericDefinition(underlyingType, typeof(ReadOnlyCollection<>)); canDeserialize = true; } else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(ICollection<>), out _genericCollectionDefinitionType)) { CollectionItemType = _genericCollectionDefinitionType.GetGenericArguments()[0]; if (ReflectionUtils.IsGenericDefinition(underlyingType, typeof(ICollection<>)) || ReflectionUtils.IsGenericDefinition(underlyingType, typeof(IList<>))) CreatedType = typeof(List<>).MakeGenericType(CollectionItemType); if (ReflectionUtils.IsGenericDefinition(underlyingType, typeof(ISet<>))) CreatedType = typeof(HashSet<>).MakeGenericType(CollectionItemType); _parametrizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(underlyingType, CollectionItemType); canDeserialize = true; ShouldCreateWrapper = true; } else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(IEnumerable<>), out tempCollectionType)) { CollectionItemType = tempCollectionType.GetGenericArguments()[0]; if (ReflectionUtils.IsGenericDefinition(UnderlyingType, typeof(IEnumerable<>))) CreatedType = typeof(List<>).MakeGenericType(CollectionItemType); _parametrizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(underlyingType, CollectionItemType); #if !(NET35 || NET20 || NETFX_CORE) if (!HasParametrizedCreator && underlyingType.Name == FSharpUtils.FSharpListTypeName) { FSharpUtils.EnsureInitialized(underlyingType.Assembly()); _parametrizedCreator = FSharpUtils.CreateSeq(CollectionItemType); } #endif if (underlyingType.IsGenericType() && underlyingType.GetGenericTypeDefinition() == typeof(IEnumerable<>)) { _genericCollectionDefinitionType = tempCollectionType; IsReadOnlyOrFixedSize = false; ShouldCreateWrapper = false; canDeserialize = true; } else { _genericCollectionDefinitionType = typeof(List<>).MakeGenericType(CollectionItemType); IsReadOnlyOrFixedSize = true; ShouldCreateWrapper = true; canDeserialize = HasParametrizedCreator; } } else { // types that implement IEnumerable and nothing else canDeserialize = false; ShouldCreateWrapper = true; } CanDeserialize = canDeserialize; }
// Token: 0x06000BD7 RID: 3031 // RVA: 0x00045760 File Offset: 0x00043960 private object CreateObjectUsingCreatorWithParameters(JsonReader reader, JsonObjectContract contract, JsonProperty containerProperty, ObjectConstructor<object> creator, string id) { ValidationUtils.ArgumentNotNull(creator, "creator"); Dictionary<JsonProperty, JsonSerializerInternalReader.PropertyPresence> arg_70_0; if (!contract.HasRequiredOrDefaultValueProperties && !this.HasFlag(this.Serializer._defaultValueHandling, DefaultValueHandling.Populate)) { arg_70_0 = null; } else { arg_70_0 = Enumerable.ToDictionary<JsonProperty, JsonProperty, JsonSerializerInternalReader.PropertyPresence>(contract.Properties, (JsonProperty m) => m, (JsonProperty m) => JsonSerializerInternalReader.PropertyPresence.None); } Dictionary<JsonProperty, JsonSerializerInternalReader.PropertyPresence> dictionary = arg_70_0; Type underlyingType = contract.UnderlyingType; if (this.TraceWriter != null && this.TraceWriter.LevelFilter >= TraceLevel.Info) { string arg = string.Join(", ", Enumerable.ToArray<string>(Enumerable.Select<JsonProperty, string>(contract.CreatorParameters, (JsonProperty p) => p.PropertyName))); this.TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, StringUtils.FormatWith("Deserializing {0} using creator with parameters: {1}.", CultureInfo.InvariantCulture, contract.UnderlyingType, arg)), null); } IDictionary<string, object> dictionary3; IDictionary<JsonProperty, object> dictionary2 = this.ResolvePropertyAndCreatorValues(contract, containerProperty, reader, underlyingType, out dictionary3); object[] array = new object[contract.CreatorParameters.Count]; IDictionary<JsonProperty, object> dictionary4 = new Dictionary<JsonProperty, object>(); foreach (KeyValuePair<JsonProperty, object> current in dictionary2) { JsonProperty property = current.Key; JsonProperty jsonProperty; if (contract.CreatorParameters.Contains(property)) { jsonProperty = property; } else { jsonProperty = StringUtils.ForgivingCaseSensitiveFind<JsonProperty>(contract.CreatorParameters, (JsonProperty p) => p.PropertyName, property.UnderlyingName); } if (jsonProperty != null) { int num = contract.CreatorParameters.IndexOf(jsonProperty); array[num] = current.Value; } else { dictionary4.Add(current); } if (dictionary != null) { JsonProperty jsonProperty2 = Enumerable.FirstOrDefault<JsonProperty>(dictionary.Keys, (JsonProperty p) => p.PropertyName == property.PropertyName); if (jsonProperty2 != null) { dictionary[jsonProperty2] = ((current.Value == null) ? JsonSerializerInternalReader.PropertyPresence.Null : JsonSerializerInternalReader.PropertyPresence.Value); } } } object obj = creator(array); if (id != null) { this.AddReference(reader, id, obj); } this.OnDeserializing(reader, contract, obj); foreach (KeyValuePair<JsonProperty, object> current2 in dictionary4) { JsonProperty key = current2.Key; object value = current2.Value; if (this.ShouldSetPropertyValue(key, value)) { key.ValueProvider.SetValue(obj, value); } else if (!key.Writable && value != null) { JsonContract jsonContract = this.Serializer._contractResolver.ResolveContract(key.PropertyType); if (jsonContract.ContractType == JsonContractType.Array) { JsonArrayContract jsonArrayContract = (JsonArrayContract)jsonContract; object value2 = key.ValueProvider.GetValue(obj); if (value2 == null) { continue; } IWrappedCollection wrappedCollection = jsonArrayContract.CreateWrapper(value2); IWrappedCollection wrappedCollection2 = jsonArrayContract.CreateWrapper(value); IEnumerator enumerator3 = wrappedCollection2.GetEnumerator(); try { while (enumerator3.MoveNext()) { object current3 = enumerator3.Current; wrappedCollection.Add(current3); } continue; } finally { IDisposable disposable = enumerator3 as IDisposable; if (disposable != null) { disposable.Dispose(); } } } if (jsonContract.ContractType == JsonContractType.Dictionary) { JsonDictionaryContract jsonDictionaryContract = (JsonDictionaryContract)jsonContract; object value3 = key.ValueProvider.GetValue(obj); if (value3 != null) { IDictionary dictionary5 = jsonDictionaryContract.ShouldCreateWrapper ? jsonDictionaryContract.CreateWrapper(value3) : ((IDictionary)value3); IDictionary dictionary6 = jsonDictionaryContract.ShouldCreateWrapper ? jsonDictionaryContract.CreateWrapper(value) : ((IDictionary)value); foreach (DictionaryEntry dictionaryEntry in dictionary6) { dictionary5.Add(dictionaryEntry.Key, dictionaryEntry.Value); } } } } } if (dictionary3 != null) { foreach (KeyValuePair<string, object> current4 in dictionary3) { contract.ExtensionDataSetter(obj, current4.Key, current4.Value); } } this.EndObject(obj, reader, contract, reader.Depth, dictionary); this.OnDeserialized(reader, contract, obj); return obj; }
private object CreateObjectUsingCreatorWithParameters(JsonReader reader, JsonObjectContract contract, JsonProperty containerProperty, ObjectConstructor<object> creator, string id) { ValidationUtils.ArgumentNotNull(creator, nameof(creator)); // only need to keep a track of properies presence if they are required or a value should be defaulted if missing bool trackPresence = (contract.HasRequiredOrDefaultValueProperties || HasFlag(Serializer._defaultValueHandling, DefaultValueHandling.Populate)); Type objectType = contract.UnderlyingType; if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) { string parameters = string.Join(", ", contract.CreatorParameters.Select(p => p.PropertyName).ToArray()); TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(reader as IJsonLineInfo, reader.Path, "Deserializing {0} using creator with parameters: {1}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType, parameters)), null); } List<CreatorPropertyContext> propertyContexts = ResolvePropertyAndCreatorValues(contract, containerProperty, reader, objectType); if (trackPresence) { foreach (JsonProperty property in contract.Properties) { if (propertyContexts.All(p => p.Property != property)) { propertyContexts.Add(new CreatorPropertyContext { Property = property, Name = property.PropertyName, Presence = PropertyPresence.None }); } } } object[] creatorParameterValues = new object[contract.CreatorParameters.Count]; foreach (CreatorPropertyContext context in propertyContexts) { // set presence of read values if (trackPresence) { if (context.Property != null && context.Presence == null) { object v = context.Value; PropertyPresence propertyPresence; if (v == null) { propertyPresence = PropertyPresence.Null; } else if (v is string) { propertyPresence = CoerceEmptyStringToNull(context.Property.PropertyType, context.Property.PropertyContract, (string)v) ? PropertyPresence.Null : PropertyPresence.Value; } else { propertyPresence = PropertyPresence.Value; } context.Presence = propertyPresence; } } JsonProperty constructorProperty = context.ConstructorProperty; if (constructorProperty == null && context.Property != null) { constructorProperty = contract.CreatorParameters.ForgivingCaseSensitiveFind(p => p.PropertyName, context.Property.UnderlyingName); } if (constructorProperty != null && !constructorProperty.Ignored) { // handle giving default values to creator parameters // this needs to happen before the call to creator if (trackPresence) { if (context.Presence == PropertyPresence.None || context.Presence == PropertyPresence.Null) { if (constructorProperty.PropertyContract == null) { constructorProperty.PropertyContract = GetContractSafe(constructorProperty.PropertyType); } if (HasFlag(constructorProperty.DefaultValueHandling.GetValueOrDefault(Serializer._defaultValueHandling), DefaultValueHandling.Populate)) { context.Value = EnsureType( reader, constructorProperty.GetResolvedDefaultValue(), CultureInfo.InvariantCulture, constructorProperty.PropertyContract, constructorProperty.PropertyType); } } } int i = contract.CreatorParameters.IndexOf(constructorProperty); creatorParameterValues[i] = context.Value; context.Used = true; } } object createdObject = creator(creatorParameterValues); if (id != null) { AddReference(reader, id, createdObject); } OnDeserializing(reader, contract, createdObject); // go through unused values and set the newly created object's properties foreach (CreatorPropertyContext context in propertyContexts) { if (context.Used || context.Property == null || context.Property.Ignored || context.Presence == PropertyPresence.None) { continue; } JsonProperty property = context.Property; object value = context.Value; if (ShouldSetPropertyValue(property, value)) { property.ValueProvider.SetValue(createdObject, value); context.Used = true; } else if (!property.Writable && value != null) { // handle readonly collection/dictionary properties JsonContract propertyContract = Serializer._contractResolver.ResolveContract(property.PropertyType); if (propertyContract.ContractType == JsonContractType.Array) { JsonArrayContract propertyArrayContract = (JsonArrayContract)propertyContract; object createdObjectCollection = property.ValueProvider.GetValue(createdObject); if (createdObjectCollection != null) { IWrappedCollection createdObjectCollectionWrapper = propertyArrayContract.CreateWrapper(createdObjectCollection); IWrappedCollection newValues = propertyArrayContract.CreateWrapper(value); foreach (object newValue in newValues) { createdObjectCollectionWrapper.Add(newValue); } } } else if (propertyContract.ContractType == JsonContractType.Dictionary) { JsonDictionaryContract dictionaryContract = (JsonDictionaryContract)propertyContract; object createdObjectDictionary = property.ValueProvider.GetValue(createdObject); if (createdObjectDictionary != null) { IDictionary targetDictionary = (dictionaryContract.ShouldCreateWrapper) ? dictionaryContract.CreateWrapper(createdObjectDictionary) : (IDictionary)createdObjectDictionary; IDictionary newValues = (dictionaryContract.ShouldCreateWrapper) ? dictionaryContract.CreateWrapper(value) : (IDictionary)value; // Manual use of IDictionaryEnumerator instead of foreach to avoid DictionaryEntry box allocations. IDictionaryEnumerator e = newValues.GetEnumerator(); try { while (e.MoveNext()) { DictionaryEntry entry = e.Entry; targetDictionary[entry.Key] = entry.Value; } } finally { (e as IDisposable)?.Dispose(); } } } context.Used = true; } } if (contract.ExtensionDataSetter != null) { foreach (CreatorPropertyContext propertyValue in propertyContexts) { if (!propertyValue.Used) { contract.ExtensionDataSetter(createdObject, propertyValue.Name, propertyValue.Value); } } } if (trackPresence) { foreach (CreatorPropertyContext context in propertyContexts) { if (context.Property == null) { continue; } EndProcessProperty( createdObject, reader, contract, reader.Depth, context.Property, context.Presence.GetValueOrDefault(), !context.Used); } } OnDeserialized(reader, contract, createdObject); return createdObject; }
internal static bool TryBuildImmutableForArrayContract(Type underlyingType, Type collectionItemType, out Type createdType, out ObjectConstructor<object> parameterizedCreator) { if (underlyingType.IsGenericType()) { string name = underlyingType.GetGenericTypeDefinition().FullName; ImmutableCollectionTypeInfo definition = ArrayContractImmutableCollectionDefinitions.FirstOrDefault(d => d.ContractTypeName == name); if (definition != null) { Type createdTypeDefinition = Type.GetType(definition.CreatedTypeName + ", System.Collections.Immutable"); Type builderTypeDefinition = Type.GetType(definition.BuilderTypeName + ", System.Collections.Immutable"); if (createdTypeDefinition != null && builderTypeDefinition != null) { MethodInfo mb = builderTypeDefinition.GetMethods().FirstOrDefault(m => m.Name == "CreateRange" && m.GetParameters().Length == 1); if (mb != null) { createdType = createdTypeDefinition.MakeGenericType(collectionItemType); MethodInfo method = mb.MakeGenericMethod(collectionItemType); parameterizedCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParametrizedConstructor(method); return true; } } } } createdType = null; parameterizedCreator = null; return false; }
/// <summary> /// Initializes a new instance of the <see cref="JsonDictionaryContract"/> class. /// </summary> /// <param name="underlyingType">The underlying type for the contract.</param> public JsonDictionaryContract(Type underlyingType) : base(underlyingType) { ContractType = JsonContractType.Dictionary; Type keyType; Type valueType; if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(IDictionary<,>), out _genericCollectionDefinitionType)) { keyType = _genericCollectionDefinitionType.GetGenericArguments()[0]; valueType = _genericCollectionDefinitionType.GetGenericArguments()[1]; if (ReflectionUtils.IsGenericDefinition(UnderlyingType, typeof(IDictionary<,>))) CreatedType = typeof(Dictionary<,>).MakeGenericType(keyType, valueType); } else { ReflectionUtils.GetDictionaryKeyValueTypes(UnderlyingType, out keyType, out valueType); if (UnderlyingType == typeof(IDictionary)) CreatedType = typeof(Dictionary<object, object>); } if (keyType != null && valueType != null) { _parametrizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(CreatedType, typeof(KeyValuePair<,>).MakeGenericType(keyType, valueType)); if (!HasParametrizedCreator && underlyingType.Name == FSharpUtils.FSharpMapTypeName) { FSharpUtils.EnsureInitialized(underlyingType.Assembly()); _parametrizedCreator = FSharpUtils.CreateMap(keyType, valueType); } } ShouldCreateWrapper = !typeof(IDictionary).IsAssignableFrom(CreatedType); DictionaryKeyType = keyType; DictionaryValueType = valueType; }