Unity constructor parameters - c#

class Entity:IEntityName
{
#region IEntityName Members
public string FirstName { get; set; }
public string LastName { get; set; }
#endregion
}
public class Person:IPerson
{
public IEntityName EntityName;
public Person()
{
}
public Person(IEntityName EntityName)
{
this.EntityName = EntityName;
}
public string ReverseName()
{
return string.Format("Your reverse name is {0} {1}",EntityName.LastName, EntityName.FirstName);
}
public override string ToString()
{
return string.Format("Name is {0} {1}", EntityName.FirstName, EntityName.LastName);
}
}
// Main Method
private static string DisplayReverseName(string fName,string lName)
{
IUnityContainer container = new UnityContainer();
container.RegisterType<IPerson, Person>().RegisterType<IEntityName,Entity>();
IEntityName entityName = container.Resolve<IEntityName>();
entityName.FirstName = fName;
entityName.LastName = lName;
var p = container.Resolve<IPerson>();
return p.ReverseName(); // firstName and lastName are still null
}
How can I inject the firstName and lastName into Person constructor ?

You can use a ParameterOverride like:
var p = container.Resolve<IPerson>(new ParameterOverride("EntityName", entityName));
This tells unity to supply the entityName instance to the constructor with the parameter named "EntityName".
You can find some additional info here: http://msdn.microsoft.com/en-us/library/ff660920(v=pandp.20).aspx

Related

C# Accessing custom attribute of owner object

How can I access the custom attribute of the parent or owner object.
Look at the FieldInfo property of the SQLFieldInfo struct
Here's a more detailed program that will compile and run that shows what I need.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Employee myclass = new Employee();
// Load from sql server...
myclass.Name = "Alain";
myclass.Age = 51;
//----
MessageBox.Show(myclass.Name.ToString()); // Should return Alain
MessageBox.Show(myclass.Age.FieldInfo.Type.ToString()); // Should output "int"
}
}
// This next class is generated by a helper exe that reads SQL table design and create the class from it
[SQLTableAttribute(DatabaseName = "Employees", Schema = "dbo", TableName = "Employees")]
public class Employee
{
[SQLFieldAttribute(FieldName = "ID", Type = SqlDbType.Int)]
public SQLFieldInfo<int> ID { get; set; }
[SQLFieldAttribute(FieldName = "Name", Type = SqlDbType.NVarChar, Size = 200)]
public SQLFieldInfo<String> Name { get; set; }
[SQLFieldAttribute(FieldName = "Age", Type = SqlDbType.Int)]
public SQLFieldInfo<int> Age { get; set; }
}
public struct SQLFieldInfo<T>
{
private readonly T value;
public SQLFieldInfo(T Value)
{
this.value = Value;
}
public static implicit operator SQLFieldInfo<T>(T Value)
{
return new SQLFieldInfo<T>(Value);
}
public T Value
{
get
{
return this.value;
}
}
public override string ToString()
{
return this.value.ToString();
}
public SQLFieldAttribute FieldInfo
{
get
{
// Need to retreive the attribute class of the parent or declaring member
return null;
}
}
}
// Holds the sql field information
public class SQLFieldAttribute : Attribute
{
public string FieldName { get; set; }
public SqlDbType Type { get; set; }
public bool AllowNull { get; set; }
public int Size { get; set; }
}
// Holds the sql table information
public class SQLTableAttribute : Attribute
{
public string DatabaseName { get; set; }
public string Schema { get; set; } = "dbo";
public string TableName { get; set; }
}
Thank you!
Alain
My data class is as follows (should be fairly translatable to A above):
public class Foo
{
[Argument(Help = "Name", AssignmentDelimiter = "=")]
public string Name
{
get;
set;
}
}
A helper class is responsible of reading attribute values of objects:
static public string GetCommandLineDelimiter<T>(Expression<Func<T>> property)
{
if(property != null)
{
var memberExpression = (MemberExpression)property.Body;
string propertyName = memberExpression.Member.Name;
PropertyInfo prop = typeof(Arguments).GetProperty(propertyName);
if(prop != null)
{
object[] dbFieldAtts = prop.GetCustomAttributes(typeof(ArgumentAttribute), true);
if(dbFieldAtts.Length > 0)
{
return ((ArgumentAttribute)dbFieldAtts[0]).AssignmentDelimiter;
}
}
}
return null;
}
To use it, simply:
string delimiter = GetCommandLineDelimiter(() => myObject.Name);
That will get the attribute value of AssignmentDelimiter on property Name, i.e. "=".
First, MSDN is your friend.
Then, if you want to get the attributes for ancestors just specify true in the inherit flag of the method:
var attribute = typeof(A).GetProperty("myprop").GetCustomAttributes(true)
.OfType<MycustomAttrib>().FirstOrDefault();
This works. I am doing a lazy initialization of a reference to the custom attribute by using reflection to look at all the properties of all the types.
public class MycustomAttribAttribute : Attribute
{
public MycustomAttribAttribute(string name)
{
this.Name=name;
}
public string Name { get; private set; }
}
class A
{
public A() { MyProp=new B(); }
[MycustomAttrib(name: "OK")]
public B MyProp { get; set; }
}
class B
{
private static Lazy<MycustomAttribAttribute> att = new Lazy<MycustomAttribAttribute>(() =>
{
var types = System.Reflection.Assembly.GetExecutingAssembly().DefinedTypes;
foreach(var item in types)
{
foreach(var prop in item.DeclaredProperties)
{
var attr = prop.GetCustomAttributes(typeof(MycustomAttribAttribute), false);
if(attr.Length>0)
{
return attr[0] as MycustomAttribAttribute;
}
}
}
return null;
});
public string MyProp2
{
get
{
return att.Value.Name;
}
}
}
class Program
{
static void Main(string[] args)
{
// Finds the attribute reference and returns "OK"
string name = (new A()).MyProp.MyProp2;
// Uses the stored attribute reference to return "OK"
string name2 = (new A()).MyProp.MyProp2;
}
}

Moq: Mock SetUp method only returns null during test

I just added dependency inject into my application, and would like to run mock test on my methods to ensure they are working properly.
I have a domain class Person with the following properties:
public class Person : DomainBase
{
public string FirstName { get; set; }
public string LastName { get; set; }
public char Gender { get; set; }
public DateTime DOB {get; set; }
}
I have a partial manager class that is shared with other domain type mangers:
public partial class Manager : IManager1
{
private IHiveTiesContext _ctx;
public Manager(IHiveTiesContext context)
{
_ctx = context;
}
}
The interface IManager1 was extracted from my PersonManager class and contains all need methods.
My PersonManager CreatePerson() method is being called and tested:
public partial class Manager : IManager1
{
public Person CreatePerson(string fn, string ln, DateTime dob, char gender, Guid RId)
{
var _person =_ctx.People.Add(new Person
{
FirstName = fn,
LastName = ln,
DOB = dob,
Gender = gender,
RowId = RId});
_ctx.SaveChanges();
return _person;
}
}
}
My context follows and once again I extracted an interface IHiveTiesContext from it.
public class HiveTiesContext : DbContext, IHiveTiesContext
{
public HiveTiesContext() : base("hiveties")
{
Database.SetInitializer<HiveTiesContext>(null);
}
public virtual IDbSet<Person> People { get; set; }
}
Finally I am trying to test CreatePerson like this:
public class PersonManagerMockTest
{
private static Guid personGuid;
[ClassInitialize]
public static void Init(TestContext test)
{
personGuid = Guid.NewGuid();
}
[TestMethod]
public void AddNewPerson()
{
//Arrange
var mockDbSet = new Mock<DbSet<Person>>();
var mockContext = new Mock<IHiveTiesContext>();
mockContext.Setup(x => x.People)
.Returns(mockDbSet.Object);
var manager = new Manager(mockContext.Object);
//Assert
var _person = manager.CreatePerson("Winston", "Gabriel", DateTime.Now, 'M', personGuid);
if(_person == null)
{
throw new Exception("NOT WORKING MAN!!!!");
}
var personid = mockContext.Object.People.Single(x => x.RowId == personGuid).Id;
//Act
mockDbSet.Verify(x => x.Add(It.IsAny<Person>()));
mockContext.Verify(x => x.SaveChanges());
}
}
My problem is that my Person object is never created, that is, it always returns a null value and the exception is always thrown. I believe I am telling it to return a Person entity, but I am not sure where I am going wrong. This is my first time using Moq and running Mock Unit Tests.
I appreciate any suggestions. Thank you.
You didn't set any behavior on the Add method of mockDbSet.
Add:(This line initialize the method to return the given person)
mockDbSet.Setup(x => x.Add(It.IsAny<Person>()))
.Returns <Person>(p => p);
Between the mocks:
var mockDbSet = new Mock<DbSet<Person>>();
mockDbSet.Setup(x => x.Add(It.IsAny<Person>()))
.Returns<Person>(p => p);
var mockContext = new Mock<IHiveTiesContext>();
mockContext.Setup(x => x.People)
.Returns(mockDbSet.Object);
...
I created a new signature/function in IHiveTiesContext to save Person object. (It's up to you now how you implement the interface).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SampleManager
{
public class Manager : IManager
{
private IHiveTiesContext _ctx;
public Manager(IHiveTiesContext context)
{
_ctx = context;
}
public Person CreatePerson(string fn, string ln, DateTime dob, char gender, Guid RId)
{
var person = _ctx.Save(fn, ln);
return person;
}
}
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public char Gender { get; set; }
public DateTime DOB { get; set; }
public Guid RowId { get; set; }
}
public interface IManager
{
Person CreatePerson(string fn, string ln, DateTime dob, char gender, Guid RId);
}
public interface IHiveTiesContext
{
Person Save(string fn, string ln);
}
}
/// <summary>
///A test for CreatePerson
///</summary>
[TestMethod()]
public void CreatePersonTest1()
{
var mock = new Mock<IHiveTiesContext>();
//fill up your expected object
mock.Setup(m => m.Save(It.IsAny<string>(), It.IsAny<string>())).Returns(new Person { FirstName = "William" });
Manager t = new Manager(mock.Object);
var results = t.CreatePerson(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<DateTime>(), It.IsAny<Char>(), It.IsAny<Guid>());
Assert.AreEqual("William", results.FirstName);
}

C# Base class constructor arguments

I learning C#. I want to see what is the best way to implement inheritance. I have a Employee base class and a PartTime derived class. Employee class only receives First and Last name and has a method to print full name.
I want to know what is the proper way to pass First and last name so that when I just call PartTime class I should be also able to print full name from the calling program. At the moment it is showing blank as full name:
class Program
{
static void Main(string[] args)
{
Employee emp = new Employee("John", "Doe");
// emp.PrintFullName();
PartTime pt = new PartTime();
float pay=pt.CalcPay(10, 8);
pt.PrintFullName();
Console.WriteLine("Pay {0}", pay);
Console.ReadKey();
}
}
public class Employee
{
string _firstName;
string _last_name;
public Employee(string FName, string LName)
{
_firstName = FName;
_last_name = LName;
}
public Employee() { }
public void PrintFullName()
{
Console.WriteLine("Full Name {0} {1} ", _firstName, _last_name);
}
}
public class PartTime : Employee
{
public float CalcPay(int hours, int rate)
{
return hours * rate;
}
}
You can call the base class constructor from you derived class like this:
public class PartTime : Employee
{
public PartTime(string FName, string Lname)
: base(FName, LName)
{ }
}
and then create it,
PartTime pt = new PartTime("Part", "Time");
Try this:
public class Employee
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Employee(string firstName, string lastName)
{
FirstName = firstName;
LastName = lastName;
}
//method implementations removed for clarity
}
public class PartTime:Employee
{
public PartTime(string firstName, string lastName)
: base(firstName, lastName)
{
}
}
Note that your base constructor will run before any code in your derived constructor, should you need further initialization logic in the PartTime class.
You want to add a constructor to PartTime that will pass along the first and last name to the base constructor
public PartTime(string fName, string lName) : base(fName, lName) {
}
Or you could make first and last name public properties on Employee which would be inherited by PartTime. Then you can initialize them when creating instances of either without having to maintain the PartTime constructor.
class Program
{
static void Main(string[] args)
{
Employee emp = new Employee { FirstName = "John", LastName = "Doe" };
emp.PrintFullName();
PartTime pt = new PartTime { FirstName = "Jane", LastName = "Doe" };
float pay=pt.CalcPay(10, 8);
pt.PrintFullName();
Console.WriteLine("Pay {0}", pay);
Console.ReadKey();
}
}
public class Employee
{
public string FirstName { get; set; }
public string LastName { get; set; }
public void PrintFullName()
{
Console.WriteLine("Full Name {0} {1} ", FirstName, LastName);
}
}
public class PartTime : Employee
{
public float CalcPay(int hours, int rate)
{
return hours * rate;
}
}

ASP.NET C# list of properties when type '=' on a property

I have this class I use as searcher to pass user values to my manager method that calls a stored procedure to read users data:
public class UserSearcher
{
public UserSearcher()
{
this.username = null;
this.password = null;
this.email = null;
this.SortType = UserGeneric.SortType.ByKey;
this.SortOrder = UserGeneric.SortOrder.ASC;
}
#region Properties
public string username { get; set; }
public string password { get; set; }
public string email { get; set; }
public UserGeneric.SortType SortType { get; set; }
public UserGeneric.SortOrder SortOrder { get; set; }
#endregion
}
}
I have this other class I use to set orderType and SortType to pass to the store:
public class UserGeneric
{
// Fields
private SortOrder _order;
private SortType _type;
// Methods
public UserGenericComparer()
{
this._type = SortType.BySurName;
this._order = SortOrder.ASC;
}
public UserGenericComparer(SortType type, SortOrder order)
{
this._type = type;
this._order = order;
}
// Nested Types
public enum SortOrder
{
ASC = 1,
DESC = -1
}
public enum SortType
{
ByKey,
ByUserName,
BySurName,
ByRegistrationDate
}
}
}
My problem is that when I use the searcher:
UserSearcher mysearcher = new UserSearcher();
and I type "mysearcher.SortOrder = something" or "mysearcher.SortType = something"
I want that when I type "=" (after ysearcher.SortOrder) automatically are displayed the properties I can use without type:
uso.SortType = UserGenericComparer.SortType.(List of my properties)
So I wanna that the intellisense should show the list of the property automatically when I type "=".
How can I do that?
thank you

In C#, how to instantiate a passed generic type inside a method?

How can I instantiate the type T inside my InstantiateType<T> method below?
I'm getting the error: 'T' is a 'type parameter' but is used like a 'variable'.:
(SCROLL DOWN FOR REFACTORED ANSWER)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestGeneric33
{
class Program
{
static void Main(string[] args)
{
Container container = new Container();
Console.WriteLine(container.InstantiateType<Customer>("Jim", "Smith"));
Console.WriteLine(container.InstantiateType<Employee>("Joe", "Thompson"));
Console.ReadLine();
}
}
public class Container
{
public T InstantiateType<T>(string firstName, string lastName) where T : IPerson
{
T obj = T();
obj.FirstName(firstName);
obj.LastName(lastName);
return obj;
}
}
public interface IPerson
{
string FirstName { get; set; }
string LastName { get; set; }
}
public class Customer : IPerson
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Company { get; set; }
}
public class Employee : IPerson
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int EmployeeNumber { get; set; }
}
}
REFACTORED ANSWER:
Thanks for all the comments, they got me on the right track, this is what I wanted to do:
using System;
namespace TestGeneric33
{
class Program
{
static void Main(string[] args)
{
Container container = new Container();
Customer customer1 = container.InstantiateType<Customer>("Jim", "Smith");
Employee employee1 = container.InstantiateType<Employee>("Joe", "Thompson");
Console.WriteLine(PersonDisplayer.SimpleDisplay(customer1));
Console.WriteLine(PersonDisplayer.SimpleDisplay(employee1));
Console.ReadLine();
}
}
public class Container
{
public T InstantiateType<T>(string firstName, string lastName) where T : IPerson, new()
{
T obj = new T();
obj.FirstName = firstName;
obj.LastName = lastName;
return obj;
}
}
public interface IPerson
{
string FirstName { get; set; }
string LastName { get; set; }
}
public class PersonDisplayer
{
private IPerson _person;
public PersonDisplayer(IPerson person)
{
_person = person;
}
public string SimpleDisplay()
{
return String.Format("{1}, {0}", _person.FirstName, _person.LastName);
}
public static string SimpleDisplay(IPerson person)
{
PersonDisplayer personDisplayer = new PersonDisplayer(person);
return personDisplayer.SimpleDisplay();
}
}
public class Customer : IPerson
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Company { get; set; }
}
public class Employee : IPerson
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int EmployeeNumber { get; set; }
}
}
Declare your method like this:
public string InstantiateType<T>(string firstName, string lastName)
where T : IPerson, new()
Notice the additional constraint at the end. Then create a new instance in the method body:
T obj = new T();
Couple of ways.
Without specifying the type must have a constructor:
T obj = default(T); //which will produce null for reference types
With a constructor:
T obj = new T();
But this requires the clause:
where T : new()
To extend on the answers above, adding where T:new() constraint to a generic method will require T to have a public, parameterless constructor.
If you want to avoid that - and in a factory pattern you sometimes force the others to go through your factory method and not directly through the constructor - then the alternative is to use reflection (Activator.CreateInstance...) and keep the default constructor private. But this comes with a performance penalty, of course.
you want new T(), but you'll also need to add , new() to the where spec for the factory method
A bit old but for others looking for a solution, perhaps this could be of interest: http://daniel.wertheim.se/2011/12/29/c-generic-factory-with-support-for-private-constructors/
Two solutions. One using Activator and one using Compiled Lambdas.
//Person has private ctor
var person = Factory<Person>.Create(p => p.Name = "Daniel");
public static class Factory<T> where T : class
{
private static readonly Func<T> FactoryFn;
static Factory()
{
//FactoryFn = CreateUsingActivator();
FactoryFn = CreateUsingLambdas();
}
private static Func<T> CreateUsingActivator()
{
var type = typeof(T);
Func<T> f = () => Activator.CreateInstance(type, true) as T;
return f;
}
private static Func<T> CreateUsingLambdas()
{
var type = typeof(T);
var ctor = type.GetConstructor(
BindingFlags.Instance | BindingFlags.CreateInstance |
BindingFlags.NonPublic,
null, new Type[] { }, null);
var ctorExpression = Expression.New(ctor);
return Expression.Lambda<Func<T>>(ctorExpression).Compile();
}
public static T Create(Action<T> init)
{
var instance = FactoryFn();
init(instance);
return instance;
}
}
You can also use reflection to fetch the object's constructor and instantiate that way:
var c = typeof(T).GetConstructor();
T t = (T)c.Invoke();
Using a factory class to build your object with compiled lamba expression: The fastest way I've found to instantiate generic type.
public static class FactoryContructor<T>
{
private static readonly Func<T> New =
Expression.Lambda<Func<T>>(Expression.New(typeof (T))).Compile();
public static T Create()
{
return New();
}
}
Here is the steps I followed to set up the benchmark.
Create my benchmark test method:
static void Benchmark(Action action, int iterationCount, string text)
{
GC.Collect();
var sw = new Stopwatch();
action(); // Execute once before
sw.Start();
for (var i = 0; i <= iterationCount; i++)
{
action();
}
sw.Stop();
System.Console.WriteLine(text + ", Elapsed: {0}ms", sw.ElapsedMilliseconds);
}
I've also tried using a factory method:
public static T FactoryMethod<T>() where T : new()
{
return new T();
}
For the tests I've created the simplest class :
public class A { }
The script to test:
const int iterations = 1000000;
Benchmark(() => new A(), iterations, "new A()");
Benchmark(() => FactoryMethod<A>(), iterations, "FactoryMethod<A>()");
Benchmark(() => FactoryClass<A>.Create(), iterations, "FactoryClass<A>.Create()");
Benchmark(() => Activator.CreateInstance<A>(), iterations, "Activator.CreateInstance<A>()");
Benchmark(() => Activator.CreateInstance(typeof (A)), iterations, "Activator.CreateInstance(typeof (A))");
Results over 1 000 000 iterations:
new A(): 11ms
FactoryMethod A(): 275ms
FactoryClass A .Create(): 56ms
Activator.CreateInstance A (): 235ms
Activator.CreateInstance(typeof (A)): 157ms
Remarks: I've tested using both .NET Framework 4.5 and 4.6 (equivalent results).
Instead of creating a function to Instantiate the type
public T InstantiateType<T>(string firstName, string lastName) where T : IPerson, new()
{
T obj = new T();
obj.FirstName = firstName;
obj.LastName = lastName;
return obj;
}
you could have done it like this
T obj = new T { FirstName = firstName, LastName = lastname };

Categories