public static Topology.CoordinateSystems.ICoordinateSystem GetCoordinateSystem(ServerConnectionI connection, string mapdef) { MapDefinition mdef = connection.GetMapDefinition(mapdef); Topology.CoordinateSystems.CoordinateSystemFactory cf = new Topology.CoordinateSystems.CoordinateSystemFactory(); return(cf.CreateFromWkt(mdef.CoordinateSystem)); }
public override void Weave( TypeDefinition typeDef, AssemblyDefinition assemblyDefinition, MapDefinition mapDefinition, Dictionary<string, List<MapDefinition>> assemblyMapDefinitions, Dictionary<string, AssemblyDefinition> assemblyDefinitions) { var constructors = typeDef.GetConstructors().ToArray(); foreach (var oneToManyColumnDefinition in mapDefinition.ColumnDefinitions.Where(c => c.Relationship == RelationshipType.OneToMany)) { var propDef = this.GetProperty(typeDef, oneToManyColumnDefinition.Name); if (propDef.SetMethod.CustomAttributes.Any(c => c.AttributeType.FullName == typeof(CompilerGeneratedAttribute).FullName)) { // auto prop - see if the prop set method is called in any of the constructors if (!constructors.Any(c => c.Body.Instructions.Any(i => i.Operand != null && i.Operand.Equals(propDef.SetMethod)))) { this.InstantiateCollection(typeDef, constructors, propDef); } } else { // not an auto prop var backingField = this.GetBackingField(propDef); if ( !constructors.Any( c => c.Body.Instructions.Any(i => i.Operand != null && (i.Operand.Equals(propDef.SetMethod) || i.Operand.Equals(backingField))))) { this.InstantiateCollection(typeDef, constructors, propDef); } } } }
public static List <string> EnumerateLayers(ServerConnectionI connection, string mapdef, bool onlyVisible) { List <string> l = new List <string>(); MapDefinition mdef = connection.GetMapDefinition(mapdef); foreach (MapLayerType lt in mdef.Layers) { if (!onlyVisible || lt.Visible) { l.Add(lt.ResourceId); } } if (mdef.BaseMapDefinition != null && mdef.BaseMapDefinition.BaseMapLayerGroup != null) { foreach (BaseMapLayerGroupCommonType bgt in mdef.BaseMapDefinition.BaseMapLayerGroup) { if (!onlyVisible || bgt.Visible) { if (bgt.BaseMapLayer != null) { foreach (BaseMapLayerType blt in bgt.BaseMapLayer) { l.Add(blt.ResourceId); } } } } } return(l); }
public override void Weave( TypeDefinition typeDef, AssemblyDefinition assemblyDefinition, MapDefinition mapDefinition, Dictionary <string, List <MapDefinition> > assemblyMapDefinitions, Dictionary <string, AssemblyDefinition> assemblyDefinitions) { var constructors = typeDef.GetConstructors().ToArray(); foreach (var oneToManyColumnDefinition in mapDefinition.ColumnDefinitions.Where(c => c.Relationship == RelationshipType.OneToMany)) { var propDef = this.GetProperty(typeDef, oneToManyColumnDefinition.Name); if (propDef.SetMethod.CustomAttributes.Any(c => c.AttributeType.FullName == typeof(CompilerGeneratedAttribute).FullName)) { // auto prop - see if the prop set method is called in any of the constructors if (!constructors.Any(c => c.Body.Instructions.Any(i => i.Operand != null && i.Operand.Equals(propDef.SetMethod)))) { this.InstantiateCollection(typeDef, constructors, propDef); } } else { // not an auto prop var backingField = this.GetBackingField(propDef); if ( !constructors.Any( c => c.Body.Instructions.Any(i => i.Operand != null && (i.Operand.Equals(propDef.SetMethod) || i.Operand.Equals(backingField))))) { this.InstantiateCollection(typeDef, constructors, propDef); } } } }
public void Setup() { def = ScriptableObject.CreateInstance <MapDefinition>(); data = ScriptableObject.CreateInstance <DataLayer>(); def.Initialize(10, 10); data.Definition = def; data.ResetData(); }
internal static void Reload() { NumberOfLoadedMods = 0; Console.WriteLine("Loading mods"); // prepare lists for the different kinds of object we'll encounter in the folder List <MapDefinition> mapDefinitions = new List <MapDefinition>(); // get the path for the mods directory string modsDirectoryPath = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location), "Mods"); // get the paths of the potential mods string[] files = Directory.EnumerateFiles(modsDirectoryPath, "*.dll", SearchOption.AllDirectories).ToArray(); // check each potential mod foreach (string file in files) { Console.WriteLine("Trying to load mods from {0}", file); // load the assembly Assembly DLL = Assembly.LoadFile(file); int containedMods = 0; // go through the public types in the assembly foreach (Type type in DLL.GetExportedTypes()) { if (!typeof(IModBase).IsAssignableFrom(type)) { continue; } containedMods++; try { // if the type can be cast to a map, create a new map instance based on that type if (typeof(MapDefinition).IsAssignableFrom(type)) { MapDefinition mapDefinition = Activator.CreateInstance(type) as MapDefinition; if (mapDefinition != null) { // each map definition counts as a mod loadMod(mapDefinition, file); // if it succeeded, add it to the list of maps mapDefinitions.Add(mapDefinition); } } } catch (Exception) { // nothing bad should happen when a type can not get instantiated or has other problems... } } Console.WriteLine("The file {0} contained {1} mods", Path.GetFileName(file), containedMods); } // save the acquired maps in the local array _mapDefinitions = mapDefinitions.ToArray(); // report the number of loaded mods Console.WriteLine("Total mods loaded: {0}", NumberOfLoadedMods); }
public List <WayPoints> AllWayPointsGetInfo(int MapSelection) { string MapDefinition; MapDefinition = "1"; MapDefinition = MapSelection.ToString(); string mystring = "" + (char)34; MapDefinition = MapDefinition.Replace(mystring, ""); mystring = "" + (char)47; MapDefinition = MapDefinition.Replace(mystring, ""); mystring = "" + (char)92; MapDefinition = MapDefinition.Replace(mystring, ""); //MapDefinition = "1"; List <WayPoints> SelectionItemsinfo = new List <WayPoints>(); DataSet ds = new DataSet(); int iMapDefinition = Convert.ToInt32(MapDefinition); string ConnectionString = ReturnConnectionString(); using (SqlConnection con = new SqlConnection(ConnectionString)) { using (SqlCommand cmd = new SqlCommand()) { string SqlCommandText = "[WebSite].[AllWayPointsGetInfo]"; cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = SqlCommandText; cmd.Parameters.AddWithValue("@MapDefinition", iMapDefinition); cmd.Connection = con; using (SqlDataAdapter da = new SqlDataAdapter(cmd)) { da.Fill(ds, "SelectionItems"); } } } if (ds != null) { if (ds.Tables.Count > 0) { if (ds.Tables["SelectionItems"].Rows.Count > 0) { foreach (DataRow dr in ds.Tables["SelectionItems"].Rows) { SelectionItemsinfo.Add(new WayPoints { WayPointID = Convert.ToInt32(dr["WayPointsID"]), WayPointName = dr["WayPointName"].ToString(), Latitude = Convert.ToDouble(dr["Latitude"]), Longitude = Convert.ToDouble(dr["Longitude"]), FishingText = dr["FishingText"].ToString(), BestWindText = dr["BestWindText"].ToString(), TypeOfFishingText = dr["TypeOfFishingText"].ToString(), }); } } } } return(SelectionItemsinfo); }
/// <inheritdoc/> public IGuildMap CreateGuildMap(ushort id, MapDefinition definition, Svmap config, int guildId) { if (definition.CreateType == CreateType.GRB) { return(new GRBMap(guildId, _guildRankingManager, id, definition, config, _logger, _packetFactory, _databasePreloader, _mobFactory, _npcFactory, _obeliskFactory, _timeService)); } return(new GuildHouseMap(guildId, _guildRankingManager, id, definition, config, _logger, _packetFactory, _databasePreloader, _mobFactory, _npcFactory, _obeliskFactory, _timeService)); }
/// <inheritdoc/> public IMap CreateMap(ushort id, MapDefinition definition, Svmap config, IEnumerable <ObeliskConfiguration> obelisks = null) { if (obelisks is null) { obelisks = new List <ObeliskConfiguration>(); } return(new Map(id, definition, config, obelisks, _logger, _packetFactory, _databasePreloader, _mobFactory, _npcFactory, _obeliskFactory, _timeService)); }
public void TryToMapMethodFails() { // Arrange var mapDefinition = new MapDefinition <SampleModel>(); // Act, Assert Assert.Throws <InvalidOperationException>( () => mapDefinition.Map(model => model.TestMethod("Test"), false)); }
public void Initialize(MapDefinition mapDefiniton) { gameObject.SetActive(true); MapDefinition = mapDefiniton; mapFrame.sprite = mapDefiniton.SlotBackground; slotButton.onClick.AddListener(OnMapSlotClicked); }
public void DefaultValueDoesNotSupportDateTime() { // Arrange var mapDefinition = new MapDefinition <TestModel>(); // Act, Assert Assert.Throws <InvalidOperationException>( () => mapDefinition.Map(model => model.DateTimeProperty, true, DateTime.Today)); }
public void DefaultValueDoesNotSupportGuid() { // Arrange var mapDefinition = new MapDefinition <TestModel>(); // Act, Assert Assert.Throws <InvalidOperationException>( () => mapDefinition.Map(model => model.GuidProperty, true, Guid.NewGuid())); }
public void DefaultValueDoesNotSupportDecimal() { // Arrange var mapDefinition = new MapDefinition <TestModel>(); // Act, Assert Assert.Throws <InvalidOperationException>( () => mapDefinition.Map(model => model.DecimalProperty, true, (decimal)3.14)); }
public void DefaultValueIncompatibleTypesFail() { // Arrange var mapDefinition = new MapDefinition <TestModel>(); // Act, Assert Assert.Throws <ArgumentException>( () => mapDefinition.Map(model => model.StringProperty, true, 5)); }
public void DefaultValueNotSetWithAllowNullsFails() { // Arrange var mapDefinition = new MapDefinition <TestModel>(); // Act, Assert Assert.Throws <InvalidOperationException>( () => mapDefinition.Map(model => model.StringProperty, false, "default")); }
public void TryToMapInvalidFails() { // Arrange var mapDefinition = new MapDefinition <InvalidModel>(); // Act, Assert Assert.Throws <ArgumentOutOfRangeException>( () => mapDefinition.Map(model => model.Data)); }
public PartyMap(IParty party, ushort id, MapDefinition definition, MapConfiguration config, ILogger <Map> logger, IDatabasePreloader databasePreloader, IMobFactory mobFactory, INpcFactory npcFactory, IObeliskFactory obeliskFactory) : base(id, definition, config, logger, databasePreloader, mobFactory, npcFactory, obeliskFactory) { _party = party; if (_party != null) { _party.AllMembersLeft += Party_AllMembersLeft; } }
public PartyMap(IParty party, ushort id, MapDefinition definition, Svmap config, ILogger <Map> logger, IGamePacketFactory packetFactory, IDatabasePreloader databasePreloader, IMobFactory mobFactory, INpcFactory npcFactory, IObeliskFactory obeliskFactory, ITimeService timeService) : base(id, definition, config, new List <ObeliskConfiguration>(), logger, packetFactory, databasePreloader, mobFactory, npcFactory, obeliskFactory, timeService) { _party = party; if (_party != null) { _party.AllMembersLeft += Party_AllMembersLeft; } }
public MapEmit(MapDefinition <T> mapDefinition) { this.mapDefinition = mapDefinition; #if !NETSTANDARD1_6 if (MapEmitAssembly.EmitDebugSymbols) { this.mapEmitDebugInfo = new MapEmitDebugInfo <T>(TypeNamespace, this.GetTypeName(), this.GetClassName()); } #endif }
[InlineData("0 17 * * Sunday", "0 18 * * Sunday", 2021, 3, 28, 17, 59, 00, true)] // Every sunday at 17:00-18:00, now is 28 of March 2021, sunday 17:59 public void MapIsOpen(string openTime, string closeTime, int year, int month, int day, int hour, int minute, int second, bool isOpen) { var def = new MapDefinition() { OpenTime = openTime, CloseTime = closeTime }; var now = new DateTime(year, month, day, hour, minute, second); Assert.Equal(isOpen, def.IsOpen(now)); }
public void MapProperty() { // Arrange var mapDefinition = new MapDefinition<SampleModel>(); // Act mapDefinition.Map(model => model.Test1); // Assert var fields = mapDefinition.FieldMapDefinitions; AssertFieldMap(fields, "Test1", "Test1", true); }
public void MapPropertySetSourceColumnAndAllowNulls() { // Arrange var mapDefinition = new MapDefinition<SampleModel>(); // Act mapDefinition.Map(model => model.Test3, "Source", true); // Assert var fields = mapDefinition.FieldMapDefinitions; AssertFieldMap(fields, "Test3", "Source", true); }
public void MapPropertySetSourceColumn() { // Arrange var mapDefinition = new MapDefinition<SampleModel>(); // Act mapDefinition.Map(model => model.Test2, "Bar"); // Assert var fields = mapDefinition.FieldMapDefinitions; AssertFieldMap(fields, "Test2", "Bar", false); }
public void MapPropertySetAllowNullsWithDefault() { // Arrange var mapDefinition = new MapDefinition<SampleModel>(); // Act mapDefinition.Map(model => model.Test1, true, "default"); // Assert var fields = mapDefinition.FieldMapDefinitions; AssertFieldMap(fields, "Test1", "Test1", true, "default"); }
public void MapPropertySetAllowNulls() { // Arrange var mapDefinition = new MapDefinition<SampleModel>(); // Act mapDefinition.Map(model => model.Test1, false); // Assert var fields = mapDefinition.FieldMapDefinitions; AssertFieldMap(fields, "Test1", "Test1", false); }
public static void SaveMapToStream(Map m, Stream s) { MapDefinition md = new MapDefinition(); md.Extent = new Extent() { Xmin = m.Envelope.MinX, Xmax = m.Envelope.MaxX, Ymin = m.Envelope.MinY, Ymax = m.Envelope.MaxY }; md.BackGroundColor = ColorTranslator.ToHtml(m.BackColor); md.SRID = m.SRID; List <MapLayer> layers = new List <MapLayer>(); foreach (var layer in m.Layers) { MapLayer ml = null; if (layer is SharpMap.Layers.VectorLayer) { } else if (layer is SharpMap.Layers.WmsLayer) { WmsLayer sl = new WmsLayer(); sl.OnlineURL = (layer as SharpMap.Layers.WmsLayer).CapabilitiesUrl; sl.WmsLayers = string.Join(",", (layer as SharpMap.Layers.WmsLayer).LayerList.ToArray()); if ((layer as SharpMap.Layers.WmsLayer).Credentials is NetworkCredential) { sl.WmsUser = ((layer as SharpMap.Layers.WmsLayer).Credentials as NetworkCredential).UserName; sl.WmsPassword = ((layer as SharpMap.Layers.WmsLayer).Credentials as NetworkCredential).Password; } ml = sl; } ml.MinVisible = layer.MinVisible; ml.MaxVisible = layer.MaxVisible; ml.Name = layer.LayerName; if (ml != null) { layers.Add(ml); } } md.Layers = layers.ToArray(); XmlSerializer serializer = new XmlSerializer(typeof(MapDefinition)); serializer.Serialize(s, md); }
public void MapProperty() { // Arrange var mapDefinition = new MapDefinition <SampleModel>(); // Act mapDefinition.Map(model => model.Test1); // Assert var fields = mapDefinition.FieldMapDefinitions; AssertFieldMap(fields, "Test1", "Test1", true); }
public void MapPropertySetAllowNulls() { // Arrange var mapDefinition = new MapDefinition <SampleModel>(); // Act mapDefinition.Map(model => model.Test1, false); // Assert var fields = mapDefinition.FieldMapDefinitions; AssertFieldMap(fields, "Test1", "Test1", false); }
public void MapPropertySetAllowNullsWithDefault() { // Arrange var mapDefinition = new MapDefinition <SampleModel>(); // Act mapDefinition.Map(model => model.Test1, true, "default"); // Assert var fields = mapDefinition.FieldMapDefinitions; AssertFieldMap(fields, "Test1", "Test1", true, "default"); }
public void MapPropertySetSourceColumn() { // Arrange var mapDefinition = new MapDefinition <SampleModel>(); // Act mapDefinition.Map(model => model.Test2, "Bar"); // Assert var fields = mapDefinition.FieldMapDefinitions; AssertFieldMap(fields, "Test2", "Bar", false); }
public void MapPropertySetSourceColumnAndAllowNulls() { // Arrange var mapDefinition = new MapDefinition <SampleModel>(); // Act mapDefinition.Map(model => model.Test3, "Source", true); // Assert var fields = mapDefinition.FieldMapDefinitions; AssertFieldMap(fields, "Test3", "Source", true); }
public bool TryGetValue(string mapName, uint key, out string value) { value = null; MapDefinition mapDef = null; if (this.valueMaps.TryGetValue(mapName, out mapDef)) { return(mapDef.TryGetValue(key, out value)); } return(false); }
public void MapPropertyExplicit() { // Arrange var mapDefinition = new MapDefinition <SampleModel>(); // Act mapDefinition.Map(model => model.Test3, "Explicit", true, int.MaxValue); // Assert var fields = mapDefinition.FieldMapDefinitions; AssertFieldMap(fields, "Test3", "Explicit", true, int.MaxValue); }
public GuildRankingManager(ILogger <IGuildRankingManager> logger, IMapsLoader mapsLoader, ITimeService timeService, IBackgroundTaskQueue backgroundTaskQueue) { _logger = logger; _mapsLoader = mapsLoader; _timeService = timeService; _taskQueue = backgroundTaskQueue; var defitions = _mapsLoader.LoadMapDefinitions(); var grbMap = defitions.Maps.FirstOrDefault(x => x.CreateType == CreateType.GRB); _grbMap = grbMap; Init(); }
public GuildRankingManager(ILogger <IGuildRankingManager> logger, IMapsLoader mapsLoader, ITimeService timeService, IDatabase database, IGuildHouseConfiguration houseConfig) { _logger = logger; _mapsLoader = mapsLoader; _timeService = timeService; _database = database; _houseConfig = houseConfig; var defitions = _mapsLoader.LoadMapDefinitions(); var grbMap = defitions.Maps.FirstOrDefault(x => x.CreateType == CreateType.GRB); _grbMap = grbMap; Init(); }
public void MapGetByte() { // Arrange var mapDefinition = new MapDefinition<TestModel>(); mapDefinition.Map(model => model.ByteProperty); var map = mapDefinition.CreateMap(); var reader = SetupGetByteFromReader("ByteProperty", (byte)8); // Act var item = new TestModel(); map.LoadOrdinals(reader); map.Load(item, reader); // Assert Assert.Equal(8, item.ByteProperty); }
public void MapGetShort() { // Arrange var mapDefinition = new MapDefinition<TestModel>(); mapDefinition.Map(model => model.ShortProperty); var map = mapDefinition.CreateMap(); var reader = SetupGetShortFromReader("ShortProperty", (short)16); // Act var item = new TestModel(); map.LoadOrdinals(reader); map.Load(item, reader); // Assert Assert.Equal(16, item.ShortProperty); }
public void MapGetInt() { // Arrange var mapDefinition = new MapDefinition<TestModel>(); mapDefinition.Map(model => model.IntProperty); var map = mapDefinition.CreateMap(); var reader = SetupGetIntFromReader("IntProperty", 32); // Act var item = new TestModel(); map.LoadOrdinals(reader); map.Load(item, reader); // Assert Assert.Equal(32, item.IntProperty); }
public void AddDateTimeParameter() { // Arrange var mapDefinition = new MapDefinition<TestModel>(false); mapDefinition.Map(model => model.DateTimeProperty); var parameterName = "@DateTimeProperty"; var command = new SqlCommand(); var map = mapDefinition.CreateMap(); // Act var item = new TestModel(); item.DateTimeProperty = DateTime.Today; map.LoadParameters(command, item); // Assert Assert.Equal(DateTime.Today, command.Parameters[parameterName].Value); }
public void SetNullableIntParameter() { // Arrange var mapDefinition = new MapDefinition<TestModel>(); mapDefinition.Map(model => model.NullableIntProperty); var parameterName = "@NullableIntProperty"; var command = CreateCommandWithParameter("MySproc", CommandType.StoredProcedure, parameterName); var map = mapDefinition.CreateMap(); // Act var item = new TestModel(); item.NullableIntProperty = 32; map.LoadParameters(command, item); // Assert Assert.Equal(32, command.Parameters[parameterName].Value); }
public override void Weave( TypeDefinition typeDef, AssemblyDefinition assemblyDefinition, MapDefinition mapDefinition, Dictionary<string, List<MapDefinition>> assemblyMapDefinitions, Dictionary<string, AssemblyDefinition> assemblyDefinitions) { // this gets called with a typeDef set to something that's being mapped // but there's the possibility of each column belonging to a different parent class // so we'll find all of the class hierarchy and weave them individually var classHierarchy = this.GetClassHierarchy(typeDef); var totalInChain = classHierarchy.Count; // if there's only one class and that class is not extended elsewhere we'll use non-virtual methods var notInInheritance = totalInChain == 1 && !assemblyDefinitions.Any( a => a.Value.MainModule.Types.Any(t => t.IsClass && t.BaseType != null && t.BaseType.FullName == typeDef.FullName)); while (classHierarchy.Count > 0) { this.ImplementISetLoggerForTypeDefinition(classHierarchy.Pop(), mapDefinition, notInInheritance); } }
public void MapGetCharWithDefaultToNullableField() { // Arrange var mapDefinition = new MapDefinition<TestModel>(); mapDefinition.Map(model => model.NullableCharProperty, true, 'e'); var map = mapDefinition.CreateMap(); var reader = SetupGetCharFromReader("NullableCharProperty", 'c'); // Act var item = new TestModel(); map.LoadOrdinals(reader); map.Load(item, reader); // Assert Assert.NotNull(item.NullableCharProperty); Assert.Equal('c', item.NullableCharProperty.Value); }
public void MapGetShortWithDefaultToNullableField() { // Arrange var mapDefinition = new MapDefinition<TestModel>(); mapDefinition.Map(model => model.NullableShortProperty, true, short.MinValue); var map = mapDefinition.CreateMap(); var reader = SetupGetShortFromReader("NullableShortProperty", (short)16); // Act var item = new TestModel(); map.LoadOrdinals(reader); map.Load(item, reader); // Assert Assert.NotNull(item.NullableShortProperty); Assert.Equal(16, item.NullableShortProperty.Value); }
public void MapGetLong() { // Arrange var mapDefinition = new MapDefinition<TestModel>(); mapDefinition.Map(model => model.LongProperty); var map = mapDefinition.CreateMap(); var reader = SetupGetLongFromReader("LongProperty", 64); // Act var item = new TestModel(); map.LoadOrdinals(reader); map.Load(item, reader); // Assert Assert.Equal(64, item.LongProperty); }
public void MapGetDoubleWithDefaultNull() { // Arrange var mapDefinition = new MapDefinition<TestModel>(); mapDefinition.Map(model => model.DoubleProperty, true, 6.022140857); var map = mapDefinition.CreateMap(); var reader = GetDataRecordWithNullColumn("DoubleProperty"); // Act var item = new TestModel(); map.LoadOrdinals(reader); map.Load(item, reader); // Assert Assert.Equal(6.022140857, item.DoubleProperty); }
public void MapGetFloatWithDefaultNull() { // Arrange var mapDefinition = new MapDefinition<TestModel>(); mapDefinition.Map(model => model.FloatProperty, true, (float)3.14); var map = mapDefinition.CreateMap(); var reader = GetDataRecordWithNullColumn("FloatProperty"); // Act var item = new TestModel(); map.LoadOrdinals(reader); map.Load(item, reader); // Assert Assert.Equal((float)3.14, item.FloatProperty); }
public override void Weave( TypeDefinition typeDef, AssemblyDefinition assemblyDefinition, MapDefinition mapDefinition, Dictionary<string, List<MapDefinition>> assemblyMapDefinitions, Dictionary<string, AssemblyDefinition> assemblyDefinitions) { var boolTypeDef = typeDef.Module.Import(typeof(bool)); foreach (var columnDef in mapDefinition.ColumnDefinitions.Where( c => c.Relationship == RelationshipType.ManyToOne || c.Relationship == RelationshipType.OneToOne)) { // remember the property may be defined on a parent class var propDef = this.GetProperty(typeDef, columnDef.Name); // add a field with DbType and DbName TypeReference fkTypeReference; var fkPkType = columnDef.DbType.GetCLRType(); if (fkPkType.IsValueType) { fkTypeReference = typeDef.Module.Import(typeof(Nullable<>).MakeGenericType(fkPkType)); } else { fkTypeReference = typeDef.Module.Import(fkPkType); } var fkField = new FieldDefinition(columnDef.DbName, FieldAttributes.Public, fkTypeReference); if (propDef.DeclaringType.Fields.Any(f => f.Name == columnDef.DbName)) { continue; // already done something here! } this.MakeNotDebuggerBrowsable(typeDef.Module, fkField); propDef.DeclaringType.Fields.Add(fkField); // override the set method to set to null propDef.SetMethod.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Initobj, fkTypeReference)); propDef.SetMethod.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Ldflda, fkField)); propDef.SetMethod.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Ldarg_0)); // override the get method to access this field if null and create a new instance // TODO solve for non auto properties if (!propDef.GetMethod.Body.Variables.Any()) { // Release code is different to debug code! propDef.GetMethod.Body.Variables.Add(new VariableDefinition(propDef.PropertyType)); } propDef.GetMethod.Body.Variables.Add(new VariableDefinition(propDef.PropertyType)); propDef.GetMethod.Body.Variables.Add(new VariableDefinition(boolTypeDef)); propDef.GetMethod.Body.InitLocals = true; //propDef.GetMethod.Body.Instructions.Clear(); var backingField = this.GetBackingField(propDef); var il = propDef.GetMethod.Body.Instructions; var lastInstr = il[0]; var index = 0; // first bit does the null/hasValue checks on the backing fields il.Insert(index++, Instruction.Create(OpCodes.Ldarg_0)); il.Insert(index++, Instruction.Create(OpCodes.Ldfld, backingField)); il.Insert(index++, Instruction.Create(OpCodes.Brtrue, lastInstr)); if (fkPkType.IsValueType) { il.Insert(index++, Instruction.Create(OpCodes.Ldarg_0)); il.Insert(index++, Instruction.Create(OpCodes.Ldflda, fkField)); il.Insert( index++, Instruction.Create( OpCodes.Call, MakeGeneric( typeDef.Module.Import(fkTypeReference.Resolve().GetMethods().Single(m => m.Name == "get_HasValue")), typeDef.Module.Import(fkPkType)))); } else { il.Insert(index++, Instruction.Create(OpCodes.Ldarg_0)); il.Insert(index++, Instruction.Create(OpCodes.Ldfld, fkField)); } il.Insert(index++, Instruction.Create(OpCodes.Brfalse, lastInstr)); // if we have a pk but no ref we create a new instance with the primary key set il.Insert(index++, Instruction.Create(OpCodes.Ldarg_0)); il.Insert( index++, Instruction.Create(OpCodes.Newobj, typeDef.Module.Import(propDef.PropertyType.Resolve().GetConstructors().First()))); il.Insert(index++, Instruction.Create(OpCodes.Stloc_0)); il.Insert(index++, Instruction.Create(OpCodes.Ldloc_0)); il.Insert(index++, Instruction.Create(OpCodes.Ldarg_0)); if (fkPkType.IsValueType) { il.Insert(index++, Instruction.Create(OpCodes.Ldflda, fkField)); il.Insert( index++, Instruction.Create( OpCodes.Call, typeDef.Module.Import( MakeGeneric( fkField.FieldType.Resolve().GetMethods().Single(m => m.Name == "get_Value"), typeDef.Module.Import(fkPkType))))); var fkMapDef = assemblyMapDefinitions.SelectMany(am => am.Value).First(m => m.TypeFullName == columnDef.TypeFullName); var assemblyDef = assemblyDefinitions.Single(ad => ad.Value.FullName == fkMapDef.AssemblyFullName).Value; var fkMapTypeRef = GetTypeDefFromFullName(columnDef.TypeFullName, assemblyDef); il.Insert( index++, Instruction.Create( OpCodes.Callvirt, typeDef.Module.Import( this.GetProperty(fkMapTypeRef, fkMapDef.ColumnDefinitions.Single(cd => cd.IsPrimaryKey).Name).SetMethod))); } else { il.Insert(index++, Instruction.Create(OpCodes.Ldfld, fkField)); var fkMapDef = assemblyMapDefinitions.SelectMany(am => am.Value).First(m => m.TypeFullName == columnDef.TypeFullName); var assemblyDef = assemblyDefinitions.Single(ad => ad.Value.FullName == fkMapDef.AssemblyFullName).Value; var fkMapTypeRef = GetTypeDefFromFullName(columnDef.TypeFullName, assemblyDef); il.Insert( index++, Instruction.Create( OpCodes.Callvirt, typeDef.Module.Import( this.GetProperty(fkMapTypeRef, fkMapDef.ColumnDefinitions.Single(cd => cd.IsPrimaryKey).Name).SetMethod))); } il.Insert(index++, Instruction.Create(OpCodes.Ldloc_0)); il.Insert(index, Instruction.Create(OpCodes.Stfld, backingField)); } }
public void MapGetNullableGuidWithNull() { // Arrange var mapDefinition = new MapDefinition<TestModel>(); mapDefinition.Map(model => model.NullableGuidProperty); var map = mapDefinition.CreateMap(); var reader = GetDataRecordWithNullColumn("NullableGuidProperty"); // Act var item = new TestModel(); map.LoadOrdinals(reader); map.Load(item, reader); // Assert Assert.Null(item.NullableGuidProperty); }
public void MapGetNullableGuid() { // Arrange var mapDefinition = new MapDefinition<TestModel>(); mapDefinition.Map(model => model.NullableGuidProperty); var map = mapDefinition.CreateMap(); var guid = Guid.NewGuid(); var reader = SetupGetGuidFromReader("NullableGuidProperty", guid); // Act var item = new TestModel(); map.LoadOrdinals(reader); map.Load(item, reader); // Assert Assert.NotNull(item.NullableGuidProperty); Assert.Equal(guid, item.NullableGuidProperty.Value); }
public void MapGetDateTime() { // Arrange var mapDefinition = new MapDefinition<TestModel>(); mapDefinition.Map(model => model.DateTimeProperty); var map = mapDefinition.CreateMap(); var reader = SetupGetDateTimeFromReader("DateTimeProperty", DateTime.Today); // Act var item = new TestModel(); map.LoadOrdinals(reader); map.Load(item, reader); // Assert Assert.Equal(DateTime.Today, item.DateTimeProperty); }
public void MapGetNullableDouble() { // Arrange var mapDefinition = new MapDefinition<TestModel>(); mapDefinition.Map(model => model.NullableDoubleProperty); var map = mapDefinition.CreateMap(); var reader = SetupGetDoubleFromReader("NullableDoubleProperty", 6.022140857); // Act var item = new TestModel(); map.LoadOrdinals(reader); map.Load(item, reader); // Assert Assert.NotNull(item.NullableDoubleProperty); Assert.Equal(6.022140857, item.NullableDoubleProperty.Value); }
public void MapGetNullableFloat() { // Arrange var mapDefinition = new MapDefinition<TestModel>(); mapDefinition.Map(model => model.NullableFloatProperty); var map = mapDefinition.CreateMap(); var reader = SetupGetFloatFromReader("NullableFloatProperty", (float)3.141); // Act var item = new TestModel(); map.LoadOrdinals(reader); map.Load(item, reader); // Assert Assert.NotNull(item.NullableFloatProperty); Assert.Equal((float)3.141, item.NullableFloatProperty.Value); }
public void MapGetNullableDateTimeOffset() { // Arrange var mapDefinition = new MapDefinition<TestModel>(); mapDefinition.Map(model => model.NullableDateTimeOffsetProperty); var map = (ISqlMap<TestModel>)mapDefinition.CreateMap(); var reader = SetupGetDateTimeOffsetFromReader("NullableDateTimeOffsetProperty", DateTime.Today); // Act var item = new TestModel(); map.LoadOrdinals(reader); map.Load(item, reader); map.LoadSqlDataReader(item, reader); // Assert Assert.NotNull(item.NullableDateTimeOffsetProperty); Assert.Equal(DateTime.Today, item.NullableDateTimeOffsetProperty.Value); }
public abstract void Weave( TypeDefinition typeDef, AssemblyDefinition assemblyDefinition, MapDefinition mapDefinition, Dictionary<string, List<MapDefinition>> assemblyMapDefinitions, Dictionary<string, AssemblyDefinition> assemblyDefinitions);
public void MapGetIntWithDefaultNull() { // Arrange var mapDefinition = new MapDefinition<TestModel>(); mapDefinition.Map(model => model.IntProperty, true, int.MaxValue); var map = mapDefinition.CreateMap(); var reader = GetDataRecordWithNullColumn("IntProperty"); // Act var item = new TestModel(); map.LoadOrdinals(reader); map.Load(item, reader); // Assert Assert.Equal(int.MaxValue, item.IntProperty); }
private void ImplementITrackedEntityForTypeDefinition(TypeDefinition typeDef, MapDefinition mapDefinition, bool notInInheritance, Dictionary<string, AssemblyDefinition> assemblyDefinitions, Dictionary<string, List<MapDefinition>> assemblyMapDefinitions) { if (typeDef.Methods.Any(m => m.Name == "GetDirtyProperties")) { return; // type already woven } if (!this.ImplementsInterface(typeDef, typeof(ITrackedEntity))) { this.AddInterfaceToNonObjectAncestor(typeDef, typeof(ITrackedEntity)); } // some common type definitions var boolTypeDef = typeDef.Module.Import(typeof(bool)); var voidTypeDef = typeDef.Module.Import(typeof(void)); var stringTypeDef = typeDef.Module.Import(typeof(string)); var listStringTypeDef = typeDef.Module.Import(typeof(List<>)).MakeGenericInstanceType(stringTypeDef); var objectTypeDef = typeDef.Module.Import(typeof(object)); // some column names const string isTrackingName = "__isTracking"; // add isTracking field if base class if (this.IsBaseClass(typeDef)) { var _isTrackingField = new FieldDefinition(isTrackingName, FieldAttributes.Family, boolTypeDef); this.MakeNotDebuggerBrowsable(typeDef.Module, _isTrackingField); typeDef.Fields.Add(_isTrackingField); } // fields for tracking state of properties on this class only var nonPkCols = mapDefinition.ColumnDefinitions.Where(c => !c.IsPrimaryKey && c.Relationship != RelationshipType.OneToMany).ToList(); foreach (var columnDefinition in nonPkCols) { if (this.HasPropertyInInheritanceChain(typeDef, columnDefinition.Name)) { var propertyDefinition = this.GetProperty(typeDef, columnDefinition.Name); if (propertyDefinition.DeclaringType.FullName == typeDef.FullName) { var dirtyField = new FieldDefinition( string.Format("__{0}_IsDirty", columnDefinition.Name), FieldAttributes.Family, boolTypeDef); this.MakeNotDebuggerBrowsable(typeDef.Module, dirtyField); typeDef.Fields.Add(dirtyField); // handle other maps, strings, valuetype, valuetype? var oldValuePropType = propertyDefinition.PropertyType; if (columnDefinition.Relationship == RelationshipType.None && propertyDefinition.PropertyType.IsValueType && propertyDefinition.PropertyType.Name != "Nullable`1") { oldValuePropType = typeDef.Module.Import(typeof(Nullable<>)).MakeGenericInstanceType(oldValuePropType); // use nullable value types } var oldValueField = new FieldDefinition( string.Format("__{0}_OldValue", columnDefinition.Name), FieldAttributes.Family, oldValuePropType); this.MakeNotDebuggerBrowsable(typeDef.Module, oldValueField); typeDef.Fields.Add(oldValueField); } } } // insert the instructions in to the setter var isTrackingField = this.GetField(typeDef, isTrackingName); foreach (var columnDefinition in nonPkCols) { if (this.HasPropertyInInheritanceChain(typeDef, columnDefinition.Name)) { var propertyDefinition = this.GetProperty(typeDef, columnDefinition.Name); if (propertyDefinition.DeclaringType.FullName == typeDef.FullName) { var backingField = this.GetBackingField(propertyDefinition); var setter = propertyDefinition.SetMethod; setter.Body.Variables.Add(new VariableDefinition(boolTypeDef)); // we need a local bool setter.Body.InitLocals = true; var setIl = setter.Body.Instructions; var setIntructions = new List<Instruction>(); setIntructions.Add(Instruction.Create(OpCodes.Nop)); setIntructions.Add(Instruction.Create(OpCodes.Ldarg_0)); setIntructions.Add(Instruction.Create(OpCodes.Ldfld, isTrackingField)); setIntructions.Add(Instruction.Create(OpCodes.Ldc_I4_0)); setIntructions.Add(Instruction.Create(OpCodes.Ceq)); setIntructions.Add(Instruction.Create(OpCodes.Stloc_0)); setIntructions.Add(Instruction.Create(OpCodes.Ldloc_0)); var endNopInstr = Instruction.Create(OpCodes.Nop); var endLdArgInstr = setIl.First(); setIntructions.Add(Instruction.Create(OpCodes.Brtrue, endLdArgInstr)); setIntructions.Add(Instruction.Create(OpCodes.Nop)); setIntructions.Add(Instruction.Create(OpCodes.Ldarg_0)); setIntructions.Add( Instruction.Create( OpCodes.Ldfld, typeDef.Fields.Single(f => f.Name == string.Format("__{0}_IsDirty", columnDefinition.Name)))); setIntructions.Add(Instruction.Create(OpCodes.Stloc_0)); setIntructions.Add(Instruction.Create(OpCodes.Ldloc_0)); setIntructions.Add(Instruction.Create(OpCodes.Brtrue, endNopInstr)); setIntructions.Add(Instruction.Create(OpCodes.Nop)); setIntructions.Add(Instruction.Create(OpCodes.Ldarg_0)); if (propertyDefinition.PropertyType.IsValueType) { var isEnum = propertyDefinition.PropertyType.Resolve().IsEnum; if (isEnum) { setIntructions.Add(Instruction.Create(OpCodes.Ldfld, backingField)); setIntructions.Add(Instruction.Create(OpCodes.Box, propertyDefinition.PropertyType)); } else { setIntructions.Add(Instruction.Create(OpCodes.Ldflda, backingField)); } setIntructions.Add(Instruction.Create(OpCodes.Ldarg_1)); if (isEnum) { setIntructions.Add(Instruction.Create(OpCodes.Box, propertyDefinition.PropertyType)); setIntructions.Add( Instruction.Create( OpCodes.Callvirt, typeDef.Module.Import( objectTypeDef.Resolve() .GetMethods() .Single( m => m.Name == "Equals" && m.Parameters.Count == 1 && m.Parameters.First().ParameterType.Name.ToLowerInvariant() == "object")))); } else if (propertyDefinition.PropertyType.Name == "Nullable`1") { setIntructions.Add(Instruction.Create(OpCodes.Box, backingField.FieldType)); setIntructions.Add(Instruction.Create(OpCodes.Constrained, backingField.FieldType)); setIntructions.Add( Instruction.Create( OpCodes.Callvirt, typeDef.Module.Import( objectTypeDef.Resolve() .GetMethods() .Single( m => m.Name == "Equals" && m.Parameters.Count == 1 && m.Parameters.First().ParameterType.Name.ToLowerInvariant() == "object")))); } else { setIntructions.Add( Instruction.Create( OpCodes.Call, typeDef.Module.Import( propertyDefinition.PropertyType.Resolve() .Methods.Single( m => m.Name == "Equals" && m.Parameters.Count == 1 && m.Parameters.First().ParameterType.Name.ToLowerInvariant() != "object")))); } setIntructions.Add(Instruction.Create(OpCodes.Stloc_0)); setIntructions.Add(Instruction.Create(OpCodes.Ldloc_0)); setIntructions.Add(Instruction.Create(OpCodes.Brtrue, endNopInstr)); } else { var fkPkType = columnDefinition.DbType.GetCLRType(); TypeReference fkTypeReference; if (fkPkType.IsValueType) { fkTypeReference = typeDef.Module.Import(typeof(Nullable<>).MakeGenericType(fkPkType)); } else { fkTypeReference = typeDef.Module.Import(fkPkType); } setIntructions.Add(Instruction.Create(OpCodes.Ldfld, backingField)); var hmmInstr = Instruction.Create(OpCodes.Ldc_I4_0); var hmmInstr2 = Instruction.Create(OpCodes.Ldc_I4_1); if (propertyDefinition.PropertyType.Name.ToLowerInvariant() == "string") { var orInstr = Instruction.Create(OpCodes.Ldarg_0); setIntructions.Add(Instruction.Create(OpCodes.Brtrue, orInstr)); setIntructions.Add(Instruction.Create(OpCodes.Ldarg_1)); setIntructions.Add(Instruction.Create(OpCodes.Brtrue, hmmInstr)); setIntructions.Add(orInstr); } else { var orInstr = Instruction.Create(OpCodes.Ldarg_1); var orInstr2 = Instruction.Create(OpCodes.Ldarg_0); setIntructions.Add(Instruction.Create(OpCodes.Brtrue, orInstr)); setIntructions.Add(Instruction.Create(OpCodes.Ldarg_1)); setIntructions.Add(Instruction.Create(OpCodes.Brtrue, hmmInstr)); setIntructions.Add(orInstr); setIntructions.Add(Instruction.Create(OpCodes.Brtrue, orInstr2)); setIntructions.Add(Instruction.Create(OpCodes.Ldarg_0)); if (fkPkType.IsValueType) { // need to call HasValue setIntructions.Add(Instruction.Create(OpCodes.Ldflda, typeDef.Fields.Single(f => f.Name == columnDefinition.DbName))); setIntructions.Add(Instruction.Create( OpCodes.Call, MakeGeneric( typeDef.Module.Import(fkTypeReference.Resolve().GetMethods().Single(m => m.Name == "get_HasValue")), typeDef.Module.Import(fkPkType)))); setIntructions.Add(Instruction.Create(OpCodes.Brtrue, hmmInstr)); } else { // check for null setIntructions.Add(Instruction.Create(OpCodes.Ldfld, typeDef.Fields.Single(f => f.Name == columnDefinition.DbName))); setIntructions.Add(Instruction.Create(OpCodes.Brtrue, hmmInstr)); } setIntructions.Add(orInstr2); } setIntructions.Add(Instruction.Create(OpCodes.Ldfld, backingField)); setIntructions.Add(Instruction.Create(OpCodes.Brfalse, hmmInstr2)); setIntructions.Add(Instruction.Create(OpCodes.Ldarg_0)); setIntructions.Add(Instruction.Create(OpCodes.Ldfld, backingField)); setIntructions.Add(Instruction.Create(OpCodes.Ldarg_1)); if (propertyDefinition.PropertyType.Name.ToLowerInvariant() == "string") { setIntructions.Add( Instruction.Create( OpCodes.Callvirt, typeDef.Module.Import( propertyDefinition.PropertyType.Resolve() .GetMethods() .Single( m => m.Name == "Equals" && m.Parameters.Count == 1 && m.Parameters.First().ParameterType.Name.ToLowerInvariant() == "string")))); } else { setIntructions.Add( Instruction.Create( OpCodes.Callvirt, typeDef.Module.Import( objectTypeDef.Resolve() .GetMethods() .Single( m => m.Name == "Equals" && m.Parameters.Count == 1 && m.Parameters.First().ParameterType.Name.ToLowerInvariant() == "object")))); } var nopInstr = Instruction.Create(OpCodes.Nop); setIntructions.Add(Instruction.Create(OpCodes.Br, nopInstr)); setIntructions.Add(hmmInstr2); setIntructions.Add(nopInstr); var nopInstr2 = Instruction.Create(OpCodes.Nop); setIntructions.Add(Instruction.Create(OpCodes.Br, nopInstr2)); setIntructions.Add(hmmInstr); setIntructions.Add(nopInstr2); setIntructions.Add(Instruction.Create(OpCodes.Stloc_0)); setIntructions.Add(Instruction.Create(OpCodes.Ldloc_0)); setIntructions.Add(Instruction.Create(OpCodes.Brtrue, endNopInstr)); setIntructions.Add(Instruction.Create(OpCodes.Nop)); } // it's now dirty setIntructions.Add(Instruction.Create(OpCodes.Nop)); var topOfSetIsDirtyInstr = Instruction.Create(OpCodes.Ldarg_0); if (columnDefinition.Relationship == RelationshipType.ManyToOne || columnDefinition.Relationship == RelationshipType.OneToOne) { // we need to check whether the foreign key backing field has a value var setToBackingFieldInstr = Instruction.Create(OpCodes.Ldarg_0); setIntructions.Add(Instruction.Create(OpCodes.Ldarg_0)); setIntructions.Add(Instruction.Create(OpCodes.Ldfld, backingField)); setIntructions.Add(Instruction.Create(OpCodes.Brtrue, setToBackingFieldInstr)); var fkPkType = columnDefinition.DbType.GetCLRType(); TypeReference fkTypeReference; if (fkPkType.IsValueType) { fkTypeReference = typeDef.Module.Import(typeof(Nullable<>).MakeGenericType(fkPkType)); } else { fkTypeReference = typeDef.Module.Import(fkPkType); } var fkField = typeDef.Fields.Single(f => f.Name == columnDefinition.DbName); setIntructions.Add(Instruction.Create(OpCodes.Ldarg_0)); if (fkPkType.IsValueType) { // need to call HasValue setIntructions.Add(Instruction.Create(OpCodes.Ldflda, fkField)); setIntructions.Add(Instruction.Create( OpCodes.Call, MakeGeneric( typeDef.Module.Import(fkTypeReference.Resolve().GetMethods().Single(m => m.Name == "get_HasValue")), typeDef.Module.Import(fkPkType)))); setIntructions.Add(Instruction.Create(OpCodes.Brfalse, setToBackingFieldInstr)); } else { // check for null setIntructions.Add(Instruction.Create(OpCodes.Ldfld, fkField)); setIntructions.Add(Instruction.Create(OpCodes.Brfalse, setToBackingFieldInstr)); } // need to add a variable to hold the new obj var fkGeneratedVariableDef = new VariableDefinition(propertyDefinition.PropertyType); propertyDefinition.SetMethod.Body.Variables.Add(fkGeneratedVariableDef); // if we get here then we have an FK value but null in this backing field so we need to create a new instance of the FK and set that as the old value setIntructions.Add(Instruction.Create(OpCodes.Ldarg_0)); setIntructions.Add(Instruction.Create(OpCodes.Newobj, typeDef.Module.Import(propertyDefinition.PropertyType.Resolve().GetConstructors().First()))); setIntructions.Add(Instruction.Create(OpCodes.Stloc, fkGeneratedVariableDef)); setIntructions.Add(Instruction.Create(OpCodes.Ldloc, fkGeneratedVariableDef)); setIntructions.Add(Instruction.Create(OpCodes.Ldarg_0)); if (fkPkType.IsValueType) { setIntructions.Add(Instruction.Create(OpCodes.Ldflda, typeDef.Fields.Single(f => f.Name == columnDefinition.DbName))); setIntructions.Add(Instruction.Create( OpCodes.Call, typeDef.Module.Import( MakeGeneric( fkField.FieldType.Resolve().GetMethods().Single(m => m.Name == "get_Value"), typeDef.Module.Import(fkPkType))))); var fkMapDef = assemblyMapDefinitions.SelectMany(am => am.Value).First(m => m.TypeFullName == columnDefinition.TypeFullName); var assemblyDef = assemblyDefinitions.Single(ad => ad.Value.FullName == fkMapDef.AssemblyFullName).Value; var fkMapTypeRef = GetTypeDefFromFullName(columnDefinition.TypeFullName, assemblyDef); setIntructions.Add( Instruction.Create( OpCodes.Callvirt, typeDef.Module.Import( this.GetProperty(fkMapTypeRef, fkMapDef.ColumnDefinitions.Single(cd => cd.IsPrimaryKey).Name).SetMethod))); } else { setIntructions.Add(Instruction.Create(OpCodes.Ldfld, fkField)); var fkMapDef = assemblyMapDefinitions.SelectMany(am => am.Value).First(m => m.TypeFullName == columnDefinition.TypeFullName); var assemblyDef = assemblyDefinitions.Single(ad => ad.Value.FullName == fkMapDef.AssemblyFullName).Value; var fkMapTypeRef = GetTypeDefFromFullName(columnDefinition.TypeFullName, assemblyDef); setIntructions.Add(Instruction.Create( OpCodes.Callvirt, typeDef.Module.Import( this.GetProperty(fkMapTypeRef, fkMapDef.ColumnDefinitions.Single(cd => cd.IsPrimaryKey).Name).SetMethod))); } setIntructions.Add(Instruction.Create(OpCodes.Ldloc, fkGeneratedVariableDef)); setIntructions.Add(Instruction.Create(OpCodes.Stfld, typeDef.Fields.Single(f => f.Name == string.Format("__{0}_OldValue", columnDefinition.Name)))); setIntructions.Add(Instruction.Create(OpCodes.Br, topOfSetIsDirtyInstr)); // set using backing field setIntructions.Add(setToBackingFieldInstr); setIntructions.Add(Instruction.Create(OpCodes.Ldarg_0)); setIntructions.Add(Instruction.Create(OpCodes.Ldfld, backingField)); setIntructions.Add( Instruction.Create( OpCodes.Stfld, typeDef.Fields.Single(f => f.Name == string.Format("__{0}_OldValue", columnDefinition.Name)))); } else { setIntructions.Add(Instruction.Create(OpCodes.Ldarg_0)); setIntructions.Add(Instruction.Create(OpCodes.Ldarg_0)); setIntructions.Add(Instruction.Create(OpCodes.Ldfld, backingField)); if (columnDefinition.Relationship == RelationshipType.None && propertyDefinition.PropertyType.IsValueType && propertyDefinition.PropertyType.Name != "Nullable`1") { setIntructions.Add( Instruction.Create( OpCodes.Newobj, MakeGeneric( typeDef.Module.Import( typeDef.Fields.Single(f => f.Name == string.Format("__{0}_OldValue", columnDefinition.Name)) .FieldType.Resolve() .GetConstructors() .First()), propertyDefinition.PropertyType))); } setIntructions.Add( Instruction.Create( OpCodes.Stfld, typeDef.Fields.Single(f => f.Name == string.Format("__{0}_OldValue", columnDefinition.Name)))); } setIntructions.Add(topOfSetIsDirtyInstr); setIntructions.Add(Instruction.Create(OpCodes.Ldc_I4_1)); setIntructions.Add( Instruction.Create( OpCodes.Stfld, typeDef.Fields.Single(f => f.Name == string.Format("__{0}_IsDirty", columnDefinition.Name)))); setIntructions.Add(Instruction.Create(OpCodes.Nop)); setIntructions.Add(endNopInstr); setIntructions.Reverse(); foreach (var instruction in setIntructions) { setIl.Insert(0, instruction); } } } } // implement the ITrackedEntity methods // EnableTracking if (this.IsBaseClass(typeDef)) { var enableTracking = new MethodDefinition( "EnableTracking", MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual | MethodAttributes.Final, voidTypeDef); enableTracking.Body.Instructions.Add(Instruction.Create(OpCodes.Nop)); enableTracking.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_0)); enableTracking.Body.Instructions.Add(Instruction.Create(OpCodes.Ldc_I4_1)); enableTracking.Body.Instructions.Add(Instruction.Create(OpCodes.Stfld, typeDef.Fields.Single(f => f.Name == isTrackingName))); enableTracking.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); typeDef.Methods.Add(enableTracking); } // DisableTracking var disableTrackingMethodAttrs = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual; if (notInInheritance) { disableTrackingMethodAttrs = disableTrackingMethodAttrs | MethodAttributes.NewSlot | MethodAttributes.Final; } var disableTracking = new MethodDefinition("DisableTracking", disableTrackingMethodAttrs, voidTypeDef); var disableInstructions = disableTracking.Body.Instructions; disableInstructions.Add(Instruction.Create(OpCodes.Nop)); disableInstructions.Add(Instruction.Create(OpCodes.Ldarg_0)); disableInstructions.Add(Instruction.Create(OpCodes.Ldc_I4_0)); disableInstructions.Add(Instruction.Create(OpCodes.Stfld, isTrackingField)); foreach (var col in nonPkCols) { if (this.HasPropertyInInheritanceChain(typeDef, col.Name)) { var propDef = this.GetProperty(typeDef, col.Name); // reset isdirty disableInstructions.Add(Instruction.Create(OpCodes.Ldarg_0)); disableInstructions.Add(Instruction.Create(OpCodes.Ldc_I4_0)); disableInstructions.Add(Instruction.Create(OpCodes.Stfld, this.GetField(typeDef, string.Format("__{0}_IsDirty", col.Name)))); // reset oldvalue disableInstructions.Add(Instruction.Create(OpCodes.Ldarg_0)); var oldValueField = this.GetField(typeDef, string.Format("__{0}_OldValue", col.Name)); if (propDef.PropertyType.IsValueType) { disableInstructions.Add(Instruction.Create(OpCodes.Ldflda, oldValueField)); disableInstructions.Add(Instruction.Create(OpCodes.Initobj, oldValueField.FieldType)); } else { disableInstructions.Add(Instruction.Create(OpCodes.Ldnull)); disableInstructions.Add(Instruction.Create(OpCodes.Stfld, oldValueField)); } } } disableInstructions.Add(Instruction.Create(OpCodes.Ret)); typeDef.Methods.Add(disableTracking); // IsTrackingEnabled if (this.IsBaseClass(typeDef)) { var isTrackingEnabled = new MethodDefinition( "IsTrackingEnabled", MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual | MethodAttributes.Final, boolTypeDef); isTrackingEnabled.Body.Instructions.Add(Instruction.Create(OpCodes.Nop)); isTrackingEnabled.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_0)); isTrackingEnabled.Body.Instructions.Add(Instruction.Create(OpCodes.Ldfld, typeDef.Fields.Single(f => f.Name == isTrackingName))); isTrackingEnabled.Body.Instructions.Add(Instruction.Create(OpCodes.Stloc_0)); var loadInstr = Instruction.Create(OpCodes.Ldloc_0); isTrackingEnabled.Body.Instructions.Add(Instruction.Create(OpCodes.Br, loadInstr)); isTrackingEnabled.Body.Instructions.Add(loadInstr); isTrackingEnabled.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); isTrackingEnabled.Body.InitLocals = true; isTrackingEnabled.Body.Variables.Add(new VariableDefinition(boolTypeDef)); typeDef.Methods.Add(isTrackingEnabled); } // GetDirtyProperties var getDirtyPropertiesMethodAttrs = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual; if (notInInheritance) { getDirtyPropertiesMethodAttrs = getDirtyPropertiesMethodAttrs | MethodAttributes.NewSlot | MethodAttributes.Final; } var getDirtyProperties = new MethodDefinition( "GetDirtyProperties", getDirtyPropertiesMethodAttrs, typeDef.Module.Import(typeof(IEnumerable<>)).MakeGenericInstanceType(stringTypeDef)); getDirtyProperties.Body.Variables.Add(new VariableDefinition("dirtyProps", listStringTypeDef)); getDirtyProperties.Body.Variables.Add( new VariableDefinition(typeDef.Module.Import(typeof(IEnumerable<>)).MakeGenericInstanceType(stringTypeDef))); getDirtyProperties.Body.Variables.Add(new VariableDefinition(boolTypeDef)); getDirtyProperties.Body.InitLocals = true; var instructions = getDirtyProperties.Body.Instructions; instructions.Add(Instruction.Create(OpCodes.Nop)); var listStringContruictor = MakeGeneric( typeDef.Module.Import(listStringTypeDef.Resolve().GetConstructors().First(c => !c.HasParameters && !c.IsStatic && c.IsPublic)), stringTypeDef); instructions.Add(Instruction.Create(OpCodes.Newobj, listStringContruictor)); instructions.Add(Instruction.Create(OpCodes.Stloc_0)); var breakToInstruction = Instruction.Create(nonPkCols.Count == 1 ? OpCodes.Ldloc_0 : OpCodes.Ldarg_0); var addMethod = typeDef.Module.Import(listStringTypeDef.Resolve().Methods.Single(m => m.Name == "Add")); addMethod = MakeGeneric(addMethod, stringTypeDef); var visibleCols = nonPkCols.Where(c => this.HasPropertyInInheritanceChain(typeDef, c.Name)).ToList(); for (var i = 0; i < visibleCols.Count; i++) { if (i == 0) { instructions.Add(Instruction.Create(OpCodes.Ldarg_0)); } instructions.Add( Instruction.Create(OpCodes.Ldfld, this.GetField(typeDef, string.Format("__{0}_IsDirty", visibleCols.ElementAt(i).Name)))); instructions.Add(Instruction.Create(OpCodes.Ldc_I4_0)); instructions.Add(Instruction.Create(OpCodes.Ceq)); instructions.Add(Instruction.Create(OpCodes.Stloc_2)); instructions.Add(Instruction.Create(OpCodes.Ldloc_2)); instructions.Add(Instruction.Create(OpCodes.Brtrue, breakToInstruction)); instructions.Add(Instruction.Create(OpCodes.Nop)); instructions.Add(Instruction.Create(OpCodes.Ldloc_0)); instructions.Add(Instruction.Create(OpCodes.Ldstr, visibleCols.ElementAt(i).Name)); instructions.Add(Instruction.Create(OpCodes.Callvirt, addMethod)); instructions.Add(Instruction.Create(OpCodes.Nop)); instructions.Add(Instruction.Create(OpCodes.Nop)); instructions.Add(breakToInstruction); breakToInstruction = Instruction.Create(i == visibleCols.Count - 2 ? OpCodes.Ldloc_0 : OpCodes.Ldarg_0); } instructions.Add(Instruction.Create(OpCodes.Stloc_1)); var retInstr = Instruction.Create(OpCodes.Ldloc_1); instructions.Add(Instruction.Create(OpCodes.Br, retInstr)); instructions.Add(retInstr); instructions.Add(Instruction.Create(OpCodes.Ret)); typeDef.Methods.Add(getDirtyProperties); // GetOldValue var getOldValueMethodAttrs = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual; if (notInInheritance) { getOldValueMethodAttrs = getOldValueMethodAttrs | MethodAttributes.NewSlot | MethodAttributes.Final; } var getOldValue = new MethodDefinition("GetOldValue", getOldValueMethodAttrs, objectTypeDef); getOldValue.Parameters.Add(new ParameterDefinition("propertyName", ParameterAttributes.None, stringTypeDef)); getOldValue.Body.Variables.Add(new VariableDefinition(objectTypeDef)); getOldValue.Body.Variables.Add(new VariableDefinition(stringTypeDef)); getOldValue.Body.Variables.Add(new VariableDefinition(boolTypeDef)); getOldValue.Body.InitLocals = true; var getBodyInstructions = getOldValue.Body.Instructions; getBodyInstructions.Add(Instruction.Create(OpCodes.Nop)); getBodyInstructions.Add(Instruction.Create(OpCodes.Ldarg_1)); getBodyInstructions.Add(Instruction.Create(OpCodes.Stloc_1)); getBodyInstructions.Add(Instruction.Create(OpCodes.Ldloc_1)); var throwExceptionTarget = Instruction.Create(OpCodes.Ldstr, "propertyName"); var returnTarget = Instruction.Create(OpCodes.Ldloc_0); getBodyInstructions.Add(Instruction.Create(OpCodes.Brfalse, throwExceptionTarget)); var switchInstructions = new List<Instruction>(); var opEqualityRef = typeDef.Module.Import(typeof(string).GetMethods().Single(m => m.Name == "op_Equality")); for (var i = 0; i < visibleCols.Count; i++) { // generate the switch bit getBodyInstructions.Add(Instruction.Create(OpCodes.Ldloc_1)); getBodyInstructions.Add(Instruction.Create(OpCodes.Ldstr, visibleCols.ElementAt(i).Name)); getBodyInstructions.Add(Instruction.Create(OpCodes.Call, opEqualityRef)); // generate the if bit var targetInstr = Instruction.Create(OpCodes.Ldarg_0); getBodyInstructions.Add(Instruction.Create(OpCodes.Brtrue, targetInstr)); switchInstructions.Add(targetInstr); switchInstructions.Add( Instruction.Create(OpCodes.Ldfld, this.GetField(typeDef, String.Format("__{0}_IsDirty", visibleCols.ElementAt(i).Name)))); switchInstructions.Add(Instruction.Create(OpCodes.Ldc_I4_0)); switchInstructions.Add(Instruction.Create(OpCodes.Ceq)); switchInstructions.Add(Instruction.Create(OpCodes.Stloc_2)); switchInstructions.Add(Instruction.Create(OpCodes.Ldloc_2)); // generate the return bit var breakInstruction = Instruction.Create(OpCodes.Br, throwExceptionTarget); switchInstructions.Add(Instruction.Create(OpCodes.Brtrue, breakInstruction)); switchInstructions.Add(Instruction.Create(OpCodes.Nop)); switchInstructions.Add(Instruction.Create(OpCodes.Ldarg_0)); switchInstructions.Add( Instruction.Create(OpCodes.Ldfld, this.GetField(typeDef, String.Format("__{0}_OldValue", visibleCols.ElementAt(i).Name)))); if (this.GetProperty(typeDef, visibleCols.ElementAt(i).Name).PropertyType.IsValueType) { switchInstructions.Add( Instruction.Create( OpCodes.Box, this.GetField(typeDef, String.Format("__{0}_OldValue", visibleCols.ElementAt(i).Name)).FieldType)); } switchInstructions.Add(Instruction.Create(OpCodes.Stloc_0)); switchInstructions.Add(Instruction.Create(OpCodes.Br, returnTarget)); switchInstructions.Add(breakInstruction); } // add a br getBodyInstructions.Add(Instruction.Create(OpCodes.Br, throwExceptionTarget)); // run them foreach (var instruction in switchInstructions) { getBodyInstructions.Add(instruction); } // handle the exception getBodyInstructions.Add(Instruction.Create(OpCodes.Nop)); getBodyInstructions.Add(throwExceptionTarget); getBodyInstructions.Add( Instruction.Create(OpCodes.Ldstr, "Either the property doesn't exist or it's not dirty. Consult GetDirtyProperties first")); getBodyInstructions.Add( Instruction.Create( OpCodes.Newobj, typeDef.Module.Import( typeof(ArgumentOutOfRangeException).GetConstructors() .First( c => c.GetParameters().All(p => p.ParameterType == typeof(string)) && c.GetParameters().Count() == 2)))); getBodyInstructions.Add(Instruction.Create(OpCodes.Throw)); getBodyInstructions.Add(returnTarget); getBodyInstructions.Add(Instruction.Create(OpCodes.Ret)); typeDef.Methods.Add(getOldValue); }
public void MapGetStringWithDefaultNull() { // Arrange var mapDefinition = new MapDefinition<TestModel>(); mapDefinition.Map(model => model.StringProperty, true, "default"); var map = mapDefinition.CreateMap(); var reader = GetDataRecordWithNullColumn("StringProperty"); // Act var item = new TestModel(); map.LoadOrdinals(reader); map.Load(item, reader); // Assert Assert.Equal("default", item.StringProperty); }
public void MapGetDecimal() { // Arrange var mapDefinition = new MapDefinition<TestModel>(); mapDefinition.Map(model => model.DecimalProperty); var map = mapDefinition.CreateMap(); var reader = SetupGetDecimalFromReader("DecimalProperty", (decimal)3.141529); // Act var item = new TestModel(); map.LoadOrdinals(reader); map.Load(item, reader); // Assert Assert.Equal((decimal)3.141529, item.DecimalProperty); }
public void MapGetNullableString() { // Arrange var mapDefinition = new MapDefinition<TestModel>(); mapDefinition.Map(model => model.StringProperty); var map = mapDefinition.CreateMap(); var reader = SetupGetStringFromReader("StringProperty", "This is a test."); // Act var item = new TestModel(); map.LoadOrdinals(reader); map.Load(item, reader); // Assert Assert.Equal("This is a test.", item.StringProperty); }