Inline initialize objects of different types in array of an interface type - interface

Is it possible to inline initialize an array of the interface type IFooFace with different specific implementations? Or is it not possible and I have to initialize my objects before the array and then just pass them in?
This is how I can do it in C#:
public interface IFooFace
{
int Id { get; }
}
public class Bar : IFooFace
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Zar : IFooFace
{
public int Id { get; set; }
public string MegaName { get; set; }
}
internal class Program
{
public static IFooFace[] Data =
{
new Bar
{
Id = 0,
Name = "first"
},
new Zar
{
Id = 1,
MegaName = "meeeega"
}
};
}
And this is what I tried in TypeScript:
export interface IFooFace {
id: number;
}
export class Bar implements IFooFace {
public id: number;
public name: string;
// a lot of more properties
}
export class Zar implements IFooFace {
public id: number;
public megaName: string;
// a lot of more properties
}
var Data : IFooFace[] = [
// how to initialize my objects here? like in C#?
// this won't work:
// new Bar(){
// id: 0,
// name: "first"
// },
// new Zar() {
// id: 1,
// megaName: "meeeeega"
// }
// this also doesn't work:
// {
// id: 0,
// name: "first"
// },
// {
// id: 1,
// megaName: "meeeeega"
// }
];

No, TypeScript does not have object initializers. #RyanCavanaugh shows possible solution in TS:
class MyClass {
constructor(initializers: ...) { ... }
}
var x = new MyClass({field1: 'asd', 'field2: 'fgh' });

Related

Test whether event is published from handler

Can I get sample of how to test whether event is published from given handler or not.
var cmd = new Catalogue()
{
CatalogueCode = "",
CatalogueType = "",
CustomerSegmentCode = "",
DisplayName = "",
EffectiveDate = null,
Products = null
};
Test.Handler(bus => new CatalogueAddedCommandHandler(bus))
.ExpectPublish<ICatalogue>(e => e.CatalogueCode == cmd.CatalogueCode).OnMessage(cmd);
When I debug the test case it shows exception Interface not found at Test.Handler.
I think you need to call Test.Initialize();
You can find the documentation on the Particular docs website
UPDATE:
using NServiceBus;
using NServiceBus.Testing;
using NUnit.Framework;
[TestFixture]
public class Tests
{
[Test]
public void Run()
{
Test.Initialize(c => c.Conventions().DefiningEventsAs(t => t == typeof (ICatalogue)));
var cmd = new Catalogue()
{
CatalogueCode = "TEST"
};
Test.Handler<CatalogueAddedCommandHandler>()
.ExpectPublish<ICatalogue>(e => e.CatalogueCode == cmd.CatalogueCode)
.OnMessage(cmd);
}
}
public interface ICatalogue
{
string CatalogueCode { get; set; }
}
public class Catalogue
{
public string CatalogueCode { get; set; }
}
public class CatalogueEvent : ICatalogue
{
public string CatalogueCode { get; set; }
}
public class CatalogueAddedCommandHandler : IHandleMessages<Catalogue>
{
public IBus Bus { get; set; }
public void Handle(Catalogue message)
{
Bus.Publish<ICatalogue>(e => e.CatalogueCode = message.CatalogueCode);
}
}
Does this help?

EF6 - Get entity for DbUpdateCommandTree in DbCommandTreeInterceptor

I am trying to get the value of a "NotMapped" property for a Entity/class when intercepting a DbUpdateCommandTree.
I have looked through the various metadata, but I cannot find the "link" to the Entity from the CommandTree, so unfortunately I am stuck.
Is it even possible ?
public class SomeEntity
{
public int ID { get; set; }
[NotMapped]
public int SomeUnmappedProperty { get; set; }
}
public class CommandTreeInterceptor : IDbCommandTreeInterceptor
{
public void TreeCreated(DbCommandTreeInterceptionContext ctx)
{
if (ctx.OriginalResult.DataSpace == DataSpace.SSpace)
{
var updateCommand = ctx.OriginalResult as DbUpdateCommandTree;
if (updateCommand != null)
{
// I would like to get a value of a specific property here.
// Pseudo code
var val = updateCommand.Entity.GetPropertyValue("SomeUnmappedProperty") as int;
}
}
}
}

Entity Framework: Entity with composite key as PK/FK throws exception

On escalado, throws the exception. It throws with or wihtout Include.
static void Main(string[] args)
{
try
{
using (var context = new CKContext())
{
var servReprosWithIncludes = context.ServicioRepro
.Include(p => p.Categoria)
.ToList();
var escalado = context.EscaladoPrecio
//.Include(p => p.Servicio)
.ToList();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
InvalidOperationException: The value of a property that is part of an object's key does not match the corresponding property value stored in the ObjectContext. This can occur if properties that are part of the key return inconsistent or incorrect values or if DetectChanges is not called after changes are made to a property that is part of the key.
The mapping of EscaladoPrecio:
public class EscaladoPrecioMapping : EntityTypeConfiguration<EscaladoPrecio>
{
public EscaladoPrecioMapping()
{
base.HasKey(p => new { p.Desde, p.Hasta, p.ServicioReproId });
base.HasRequired(p => p.Servicio)
.WithMany()
.HasForeignKey(p => p.ServicioReproId);
base.ToTable("PreciosServicioReprografia");
}
}
The entity ServicioRepro is a part from TPT hierarchy. Looks like:
public class ServicioRepro : Producto
{
public bool IncluirPrecioClick { get; set; }
public bool IncluirPrecioPapel { get; set; }
public bool HayPapel { get; set; }
public bool HayImpresion { get; set; }
public bool PrecioPorVolumen { get; set; }
//public virtual ICollection<EscaladoPrecio> EscaladoPrecio { get; set; }
public virtual CategoriaServicioRepro Categoria { get; set; }
public virtual ServicioReproFacturacionType ServicioReproFacturacionType { get; set; }
}
On this entity you can't see the key, because the base entity Producto have it.
The entity EscaladoPrecio have 3 PK: desde, hasta and Servicio. Servicio is PK and FK.
The entity looks like (methods, overrides and members have been removed to reduce the code):
public class EscaladoPrecio : IComparable<EscaladoPrecio>, IComparable<int>, IComparable, IEntity
{
#region Declarations
private int _desde;
private int _hasta;
private double _precio;
private int _cada;
#endregion Declarations
#region Constructor
public EscaladoPrecio()
: this(1, 1, 0, 0)
{ }
public EscaladoPrecio(int desde, int hasta, double precio)
: this(desde, hasta, precio, 0)
{ }
public EscaladoPrecio(int desde, int hasta, double precio, int cada)
{
_desde = desde;
_hasta = hasta;
_precio = precio;
_cada = cada;
}
#endregion Constructor
#region Properties
public int Desde
{
get
{
return _desde;
}
set
{
_desde = value;
}
}
public int Hasta
{
get
{
return _hasta;
}
set
{
_hasta = value;
}
}
public double Precio
{
get
{
return _precio;
}
set
{
_precio = value;
}
}
public int Cada
{
get
{
return _cada;
}
set
{
_cada = value;
}
}
#endregion Properties
private int _ServicioReproId;
public int ServicioReproId
{
get
{
if (Servicio != null)
{
_ServicioReproId = Servicio.Id;
return Servicio.Id;
}
else
return 0;
}
set
{
_ServicioReproId = value;
}
}
public virtual ServicioRepro Servicio { get; set; }
}
Why throws the exception?
Why are you doing this:
public int ServicioReproId
{
get
{
if (Servicio != null)
{
_ServicioReproId = Servicio.Id;
return Servicio.Id;
}
else
return 0;
}
set
{
_ServicioReproId = value;
}
}
Your part of the key property ServicioReproId is returning 0 here potentially although it has been loaded (and stored in the context) with a value != 0 (probably). I think this part of the exception is refering to this problem: "This can occur if properties that are part of the key return inconsistent or incorrect values."
Better leave it an automatic property:
public int ServicioReproId { get; set; }
try to initialice his virtual property in the constructor of the class EscaladoPrecio()

Json.net deserialize interface, concrete class uses a JsonConverter

My problem is that my JsonConverter doesn't seem to get invoked by the json.net de-serialization process when the converter is applied to an implementation of an interface, and the propertytype is the interface.
I use TypeNameHandling = TypeNameHandling.Objects to add $type to the json. I do so both on serialization and on de-serialization.
And when I have a property that is of an implementation of the interface the class' converter is invoked properly.
But when I have a property of interface type, the concrete class' converter is not invoked.
When I deserialize this class my JsonDataBagCreationConverter will be invoked by the RealTelephone but not by the Telephone because this is an interface.
Even though they are both serialized with the correct $type.
This results in RealTelephone having its .Data filled whereas Telephones .Data is null.
[JsonConverter(typeof(JsonDataBagCreationConverter<ContainerForITelephone>))]
public class ContainerForITelephone : IDataBag
{
private object _data;
private DataBagTypeEnum _dataBagTypeEnum;
public ITelephone Telephone { get; set; }
public Telephone RealTelephone { get; set; }
public object Data
{
get { return _data; }
set { _data = value; }
}
public DataBagTypeEnum DataBagType_Enum
{
get { return _dataBagTypeEnum; }
}
}
This jsonconverter is not invoked for the Telephone property. But it is for RealTelephone.
public class JsonDataBagCreationConverter<T> : JsonConverter where T : IDataBag, new()
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType != JsonToken.Null)
{
var jsonObject = JObject.Load(reader);
var target = Create(objectType, jsonObject);
serializer.Populate(jsonObject.CreateReader(), target);
((IDataBag)target).Data = jsonObject.ToString();
return target;
}
return null;
}
}
[JsonConverter(typeof(JsonDataBagCreationConverter<Telephone>))]
public class Telephone : ITelephone
{
public string Name { get; set; }
public string AreaCode { get; set; }
public string Number { get; set; }
public SubPhone SubPhone { get; set; }
public object Data { get; set; }
public DataBagTypeEnum DataBagType_Enum { get; set; }
}
I look forward to hearing from you, thanks
Jan
SOLVED:
public class JsonDataBagCreationConverter<T> : JsonConverter where T:IDataBag
{
//, new() prevented us from using interfaces. Activator.CreateInstance did the trick in Create
//Used when the object decorated with [JsonConverter(typeof(JsonDataBagCreationConverter<xxxx>))] is de-serialized
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var jsonObject = JObject.Load(reader);
if (objectType.IsInterface)
{
// Interfaces cannot be instantiated but must be converted to their "real" implemented type
// Because we serialize with settings.TypeNameHandling = TypeNameHandling.Objects;
// A $type property is added to the json by the deserializer.
string type = jsonObject["$type"].ToString();
var typesAsArray = type.Split(',');
var wrappedTarget = Activator.CreateInstance(typesAsArray[1], typesAsArray[0]);
var realTarget = wrappedTarget.Unwrap() as IDataBag;
serializer.Populate(jsonObject.CreateReader(), realTarget); // Will call this function recursively for any objects that have JsonDataBagCreationConverter as attribute
((IDataBag)realTarget).Data = jsonObject.ToString(); // This is where custom data is stored in databag
return realTarget;
}
// Non interface
var target = Create(objectType, jsonObject);
serializer.Populate(jsonObject.CreateReader(), target); // Will call this function recursively for any objects that have JsonDataBagCreationConverter as attribute
((IDataBag)target).Data = jsonObject.ToString(); // This is where custom data is stored in databag
return target;
}
public override bool CanRead
{
get
{
return true;
}
}
public override bool CanWrite
{
get
{
return false;
}
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new Exception("WriteJson not implemented");
}
protected IDataBag Create(Type objectType, JObject jsonObject)
{
var aa = Activator.CreateInstance(objectType);
return aa as IDataBag;
// return new T(); // this demands ,new() on the class and then it will not work with interfaces
}
public override bool CanConvert(Type objectType)
{
return typeof(T).IsAssignableFrom(objectType);
}
}

How to find which Table is mapped by fluent API?

I need to find which table is mapped to an EntityTypeConfiguration class.
For example:
public class PersonMap : EntityTypeConfiguration<Person>
{
public PersonMap()
{
...
this.ToTable("Persons");
....
}
}
I need something like reverse mapping:
var map=new PersonMap();
string table =map.GetMappedTableName();
How can I achieve this?
Add the field to PersonMap:
public class PersonMap : EntityTypeConfiguration<Person>
{
public string TableName { get { return "Persons"; } }
public PersonMap()
{
...
this.ToTable(TableName);
...
}
}
Access it like so:
var map = new PersonMap();
string table = map.TableName;
If you may not know the type of map, use an interface:
public interface IMap
{
string TableName { get; }
}
public class PersonMap : EntityTypeConfiguration<Person>, IMap
{
public string TableName { get { return "Persons"; } }
public PersonMap()
{
...
this.ToTable(TableName);
...
}
}
Access like so:
IMap map = new PersonMap();
string table = map.TableName;