How do I inject a property of a primitive type using Ninject? - ninject

How do I inject the name "Tommy" into the Name property of Bar when instantiating / activating a Foo object?
class Foo
{
public Bar Bar { get; set; }
public Foo(Bar b) { Bar = b; }
}
class Bar
{
[Inject]
public string Name { get; set; }
}

Alternatively, this is more refactor-safe:
kernel.Bind<Bar>().ToSelf().OnActivation(bar => bar.Name = "Tommy");
but beware, you should only use property injection when there's no alternatives. Objects should be built up by the constructor - i.E. after the constructor was run they should have all they need to operate. So maybe you should inject the value into the constructor instead.

kernel.Bind<Bar>().ToSelf().WithPropertyValue("Name", "Tommy");

Related

C# type serialization not as a collection of key value pairs

I have a class that when serialized, I want to return as a single string without key value pairs. A string becomes a string. An int becomes an int. How do I make my class become a string?
Looking at DataContract and Serializable, it doesn't look that this is possible. The SerializationInfo.AddValue(name, value) setup forces your whole object into a key-value approach. I just want to return "A and B".
[DataContract]
public class MyObject
{
public int A { get; set; }
public int B { get; set; }
}
When serialized using the DataContractJsonSerializer, for example, I want it to be:
4 and 2
Not
{
"A": 4,
"B": 2
}
So let's say I have a parent class that uses both of these custom types:
[DataContract]
public class Parent
{
[DataMember]
public MyObject One { get; set; }
[DataMember]
public MyObject Two { get; set; }
}
I want to it serialize like this:
{
"One": "4 and 2",
"Two": "6 and 8"
}
Instead, the only thing I seem to be able to make it do is:
{
"One": {
"A": 4,
"B": 2
},
"Two": {
"A": 6,
"B": 8
}
}
The only solution that would work, is to add the custom serialization on Parent, setting One and Two accordingly, but I don't want to do that, I want my new class to get serialized as a string everywhere.
Can I serialize a type as a single return value? Or do all types besides built-in ones like int and string have to serialize to an object?
You can simply add a get attribute that returns the attributes as a string in any way that you like...
public class MyObject
{
public int A { get; set; }
public int B { get; set; }
public string MyNewStringAttribute {
get{
return A + " and " + B;
}
}
}
Then, when you can serialize from the controller using the new attribute from an array, linq, etc.
My answer: You can't.
The parent class, MyObject has to implement ISerializable to provide the custom serialization of the class itself. This places the responsibility of correctly serializing the class the way it is intended to each class that wishes to use it, which is an undesirable experience, and highlights a severe design flaw in the supported .NET custom serializer strategy.
[Serializable]
public class Parent : ISerializable
{
public MyObject One { get; set; }
public MyObject Two { get; set; }
public (SerializerInfo info, SerializerContext context)
{
string oneString = info.GetString("One");
One = new MyObject(oneString);
string twoString = info.GetString("Two");
Two = new MyObject(twoString);
}
public override void GetObjectData(SerializerInfo info, SerializerContext context)
{
info.AddValue("One", One.ToString());
info.AddValue("Two", Two.ToString());
}
}
Grumble grumble... add this to the long list of things that .NET has gotten wrong. Static / non interfaced classes for everything making the framework untestable by default without creating plug-n-chug wrappers for everything. Compilers with lossful MSIL/symbols. I could go on and on.

How to map object type field in Nhibernate Auto Mapping

When trying to map, I got this error:
Association references unmapped class: System.Object
My class:
public partial class MessageIdentifier
{
public virtual int ID { get; set; }
public virtual object Item { get; set; }
}
And the convention:
public class MyUsertypeConvention : IPropertyConvention
{
public void Apply(IPropertyInstance instance)
{
if (instance.Type.Name == "Object")
instance.CustomType<string>();
}
}
Kindly suggest how to map?
As a simple (quick, naive) solution - I would suggest to create and map real string property. And then let your setter and getter (or some AOP or listener) to do the "to/from string conversion":
public partial class MessageIdentifier
{
public virtual int ID { get; set; }
public virtual object Item
{
get { return ... my conversion from string; }
set { ItemString = ...my conversion to string; }
}
public virtual string ItemString { get; set; }
}
A smart and preferred (but a bit more challenging) is to create CustomType - which will hide that conversion and support REUSE. Check e.g. here
NHibernate Pitfalls: Custom Types and Detecting Changes
Creating and Testing a Custom NHibernate User Type
Not a satisfactory answer. It doesn't work with class that is generated from xsd by using XML. You can try the following:
public partial class MessageIdentifier
{
public virtual int ID { get; set; }
private object itemField;
public object Item
{
get { return this.itemField; }
set { this.itemField = value; }
}
}

Failing to Assign values to Model/class memebers before Passing it to the view

I have a Model class as follows:
namespace newWorld
{
public class oneWorld
{
//There is no direct property defined
public struct Work // struct
{
public int WorkID;
public int PersonID;
public newWorld.Person.Area.person p1;
public List<Favourite> fav;
}
public struct Favourite
{
public string chocolate {get; set;}
public string dress {get; set;}
}
}
}
=========================================
I want to access this class in controller action method so that I can assign values to list "fav" inside struct work, and access the properties and other variables and methods inside this class. HOW do i do that?
because when I do the following, inside action method:
newWorld.oneWorld obj=new newWorld.oneWorld();
obj. // does not expose anything

Is there a way to create a lazy custom property with NHibernate?

I have a custom property (to binding in a Grid) like that :
public class MyClass
{
public virtual IList<clsClass2> MyList{ get; set; } //Lazy loaded
public virtual string CustomProperty //To use on Grid Binding
{
get
{
if (!MyList.IsNullOrEmpty())
return MyList.Select(__comp => __comp.Name).ToList().ToString(", ");
return string.Empty;
}
}
}
Its working fine... But that way everytime I load a MyClass object, its load every MyList element because of the CustomProperty...
Is there a better way to do that?
Thanks
public virtual string CustomProperty //To use on Grid Binding
{
get; private set;
}
// using FLuentMapping
Map(x => x.CustomProperty).Formula("(SELECT ... FROM Class2Table c2 WHERE c2.MyClass_id = Id)");
and exchange ... with your database syntax of aggregating the string see here

Dynamic Proxy : wrapping constructors

I'm taking a stab at creating a Active Record implementation (I know about Castle's initiative, and it's very good) for another type of data provider (ESRIs geodatabases, using ESRIs .NET libraries) and I'm reaching something interesting.
I have a question nevertheless. I have my ActiveRecord classes which is like this:
public interface IActiveRecord<T> : IActiveRecord where T : class
{
T Create();
void Update(T record);
void Delete(T record);
}
public interface IActiveRecord
{
int ObjectId { get; set; }
bool Managed { get; }
bool IsValid { get; }
IObject EsriObject { get; set; }
IGeometry Geometry { get; set; }
void Save();
void Delete();
}
I have static Create methods, which go to DynamicProxy and generate me a proxy. But how I can enforce that the instance generated for a inheriting class is proxied too?
public class ActiveRecord<T> : IActiveRecord where T : IActiveRecord,new()
{
// protected constructors
public static T Create(IObject obj)
{
var record = Create();
record.EsriObject = obj;
return (T)record;
}
}
// inherited class
[Workspace(#"C:\teste.gdb")]
[Table("TB_PARCEL",Geometry=esriGeometryType.esriGeometryPolygon)]
public class Parcel : ActiveRecord<Parcel>,IParcel
{
[Field(4, "NM_PARCEL_ID", esriFieldType.esriFieldTypeString)]
public virtual string ParcelId { get; set; }
[Field(5, "NR_PARCEL_NO", esriFieldType.esriFieldTypeInteger)]
public virtual int StreetNumber { get; set; }
public virtual IOwner ParcelOwner { get; set; }
}
Take a look at the tests. The first three tests get intercepted as usual, but not the fourth test. I need A) prevent the user from instancing it's own classes (bad approach for the API in my opinion) or find a way to return from the inherited classes constructors the proxies.
[TestMethod]
public void ActiveRecordConstructor()
{
Parcel p1 = Parcel.Create();
Assert.IsFalse(p1.Managed);
Assert.AreEqual(null, p1.ParcelId);
Parcel p2 = Parcel.Create(2);
Assert.IsFalse(p2.Managed);
IObject fake = _repository.StrictMock<IObject>();
using (_repository.Record())
{
fake.Stub(x => x.get_Value(4)).Return("teste");
}
using (_repository.Playback())
{
Parcel p3 = Parcel.Create(fake);
Assert.IsTrue(p3.Managed);
Assert.AreEqual("teste", p3.ParcelId);
}
// this wont be intercepted
Parcel p4 = new Parcel();
Assert.IsFalse(p4.Managed);
Assert.IsNull(p4.ParcelId);
}
In short I need that whenever a user creates a new Class(), it returns a proxied object. Is that possible while allowing inheritance?
Thanks!
DynamicProxy cannot intercept calls to constructors. It has to control the creation of the object.