for object serialization I created a DataTransferObject-Pendant for each of my objects. Each original object gets a ToDTO()-method that returns the appropriate DTO-Object with the properties to be saved . Most of my original objects are inherited from an other, so I would want each inheritance-level to care for their own properties. A simple example:
class base
{
private string _name;
public DTO_base ToDTO()
{
DTO_base result = new DTO_base();
result.Name = _name;
return result;
}
}
The inherited class should override the ToDTO() method, calling the parents method and adding its own properties to be saved, like:
class inherited : base
{
private string _description;
public new DTO_inherited ToDTO()
{
DTO_inherited result = base.ToDTO();
result.Description = _description;
return result;
}
}
Obviously, this wont work, because base.ToDTO() returns a DTO_base object. Can anyone suggest, how this feature would be implemented best?
Thanks in advance,
Frank
If you really want to have the DTO creation logic in your business objects, I would go for a generic approach.
class Base<TDTO> where TDTO : BaseDTO, new()
{
private string _name;
public TDTO ToDTO()
{
TDTO dto = new TDTO();
SetupDTO(dto);
return dto;
}
protected virtual void SetupDTO(TDTO dto)
{
dto.Name = _name;
}
}
class Inherited : Base<InheritedDTO>
{
private string _description;
protected override void SetupDTO(TDTO dto)
{
base.SetupDTO(dto);
dto.Description = _description;
}
}
I would use a Template Method:
class baseCls
{
private string _name;
public DTO_base ToDTO()
{
DTO_base result = createDTO();
result.Name = _name;
setAdditionalData(result);
return result;
}
protected abstract DTO_base createDTO();
protected abstract void setAdditionalData(DTO_base dto);
}
class inherited : baseCls
{
private string _description;
protected override DTO_base createDTO() {
return new DTO_inerited();
}
protected override void setAdditionalData(DTO_base dto) {
inherited i = (DTO_inherited)dto;
i.Description = _Description;
}
}
Related
There are few methods which have Application.Current.Properties and Application.Current.SavePropertiesAsync methods.
So how do I test methods having these two in them? I'm stuck after trying to use Unity container for them but its only working for Properties not SavePropertiesAsync.
How can I implement it?
I have implemented it as:
public interface IAppProperties { IDictionary<string, object> Properties { get; set; } }
public class AppProperty:IAppProperties
{
public const string AppPropertiesName = "AppProperties";
public IDictionary<string, object> Properties { get; set; }
public AppProperty(IDictionary<string, object> appProperties)
{
Properties = appProperties;
}
}
In App XAML.cs
UnityContainer container = new UnityContainer();
if (!IsUnitTestCase)
{
container.RegisterInstance<IDictionary<string, object>>(AppProperty.AppPropertiesName, Application.Current.Properties);
}
else
{
container.RegisterInstance<IDictionary<string, object>>(AppProperty.AppPropertiesName, new Dictionary<string,object>());
}
container.RegisterType<IAppProperties,AppProperty>();
Application.Current.Resources.Add("Unity", container);
If a class depends directly on Application.Current then you can't test it. But it looks like you're already on track with depending on an abstraction.
Suppose there are three things you need to be able to do:
Retrieve a property
Set a property
Save all properties
You can define an abstraction that represents those behaviors:
public interface IApplicationProperties
{
object GetProperty(string key);
void SetProperty(string key, object value);
Task SavePropertiesAsync();
}
Your default implementation could look like this (although there's plenty of room for improvement.)
public class ApplicationProperties : IApplicationProperties
{
private readonly Application _application;
public ApplicationProperties(Application application)
{
_application = application;
}
public object GetProperty(string key)
{
// or whatever behavior you want when the key is missing
return _application.Properties.TryGetValue(key, out object result) ? result : null;
}
public void SetProperty(string key, object value)
{
_application.Properties[key] = value;
}
public async Task SavePropertiesAsync()
{
await _application.SavePropertiesAsync();
}
}
This class could either depend on Application.Current or you could inject the Application into it.
This could benefit from better type checking and perhaps limiting/defining what settings can be read and set. But it allows you to both access the behaviors of Application through an abstraction while mocking the abstraction for unit tests. You could use Moq or just write a simple test double to use in tests.
Here's a tweak to the approach that includes a test double:
// base class
public abstract class ApplicationPropertiesBase : IApplicationProperties
{
protected abstract IDictionary<string, object> Properties { get; }
public object GetProperty(string key)
{
return Properties.TryGetValue(key, out object result) ? result : null;
}
public void SetProperty(string key, object value)
{
Properties[key] = value;
}
public abstract Task SavePropertiesAsync();
}
// inject this
public class ApplicationProperties : ApplicationPropertiesBase
{
private readonly Application _application;
public ApplicationProperties(Application application)
{
_application = application;
}
protected override IDictionary<string, object> Properties => _application.Properties;
public override async Task SavePropertiesAsync()
{
await _application.SavePropertiesAsync();
}
}
// use for tests
public class ApplicationPropertiesTestDouble : ApplicationPropertiesBase
{
private readonly IDictionary<string, object> properties =
new Dictionary<string, object>();
protected override IDictionary<string, object> Properties => properties;
public override async Task SavePropertiesAsync()
{ }
}
See below codes :
new ConditionCreator()
.Add()
.Or()
.Add()
.And()
.Add()
I want to create a Fluent Interface for that
But I need,
after Add() method developer see Only Or() or And()
and
after one of these, see Only Add() method.
so no one can write a code like :
new ConditionCreator()
.Add()
.Add()
.Add()
.Or()
.And()
.Add()
.And()
.And()
I want to have a limitation for some methods can accept special methods and etc.
I can write all methods in one class and return this for each one but that is not suitable !!!
Please guide me How write Advanced Fluent Interface class.
To restrict things, you need to create and return one (of possibly several) "builder" objects that can do special operations, keeping a ref to the main class.
public class ConditionCreator
{
public ConditionCreator() { ... }
public SubConditionCreator Add() { ...; return new SubConditionCreator(this); }
internal ConditionCreator OnAdd() { ...; return this; };
internal ConditionCreator OnOr() { ...; return this; };
}
public class SubConditionCreator
{
private ConditionCreator _creator;
internal SubConditionCreator(ConditionCreator c) { _creator = c; }
public ConditionCreator And() { return _creator.OnAdd(); }
public ConditionCreator Or() { return _creator.OnOr(); }
}
Use internal access to restrict usage.
To avoid creating garbage, store a SubConditionCreator ref in main class
There is no real easy-way I know of to solve this. Perhaps T4 templating may help, but thus far I've always had to build-up the decision-tree, with an explicit interface at each node. For example; lets assume your decision tree is an infinite loop, then (implemented accordingly):
interface IStart<T>
{
IAndOr Add();
T End();
}
interface IAndOr<T>
{
IStart<T> And();
IStart<T> Or();
}
It gets difficult if you want a finite loop; say zero to two Adds:
interface IStart<T> : IFinish<T>
{
IAndOrFirst<T> Add();
}
interface IAndOrFirst<T>
{
ISecond<T> And();
ISecond<T> Or();
}
interface ISecond<T> : IFinish<T>
{
IAndOrSecond<T> Add();
}
interface IAndOrSecond <T>
{
IFinish<T> And();
IFinish<T> Or();
}
interface IFinish<T>
{
T End();
}
You can (explicitly) implement these in a single class that acts as the state machine:
class ConditionCreator <T> : IStart<T>, IFinish<T>, IAndOrFirst<T>, IAndOrSecond<T> {...}
where you'd return this for Add() And() Or() and maintain those state changes and order.
I'm hoping some answers this question with a better way that manually writing out each node.
Consider returning an interface that contains only And() and Or(). For example:
public class ConditionCreator : IFluentAndOr
{
public IFluentAndOr And() { ... }
public IFluentAndOr Or() { ... }
}
public interface IFluentAndOr
{
IFluentAndOr And();
IFluentAndOr Or();
}
public class DoEqual
{
}
public interface ICanAddWhereValue
{
ICanAddWhereOrRun IsEqualTo(object value);
ICanAddWhereOrRun IsNotEqualTo(object value);
IBothEqual BothEqual ( object value );
}
public interface IBothEqual
{
DoEqual Excute();
}
public interface ICanAddWhereOrRun
{
ICanAddWhereValue Where(string columnName);
bool RunNow();
DoEqual Excute();
}
public interface ICanAddCondition
{
ICanAddWhereValue Where(string columnName);
bool AllRows();
}
namespace BuildAFluentInterface
{
public class WhereCondition
{
public enum ComparisonMethod
{
EqualTo,
NotEqualTo
}
public string ColumnName { get; private set; }
public ComparisonMethod Comparator { get; private set; }
public object Value { get; private set; }
public WhereCondition(string columnName, ComparisonMethod comparator, object value)
{
ColumnName = columnName;
Comparator = comparator;
Value = value;
}
}
}
using System.Collections.Generic;
namespace BuildAFluentInterface
{
public class DeleteQueryWithoutGrammar
{
private readonly string _tableName;
private readonly List<WhereCondition> _whereConditions = new List<WhereCondition>();
private string _currentWhereConditionColumn;
// Private constructor, to force object instantiation from the fluent method(s)
private DeleteQueryWithoutGrammar(string tableName)
{
_tableName = tableName;
}
#region Initiating Method(s)
public static DeleteQueryWithoutGrammar DeleteRowsFrom(string tableName)
{
return new DeleteQueryWithoutGrammar(tableName);
}
#endregion
#region Chaining Method(s)
public DeleteQueryWithoutGrammar Where(string columnName)
{
_currentWhereConditionColumn = columnName;
return this;
}
public DeleteQueryWithoutGrammar IsEqualTo(object value)
{
_whereConditions.Add(new WhereCondition(_currentWhereConditionColumn, WhereCondition.ComparisonMethod.EqualTo, value));
return this;
}
public DeleteQueryWithoutGrammar IsNotEqualTo(object value)
{
_whereConditions.Add(new WhereCondition(_currentWhereConditionColumn, WhereCondition.ComparisonMethod.NotEqualTo, value));
return this;
}
#endregion
#region Executing Method(s)
public void AllRows()
{
ExecuteThisQuery();
}
public void RunNow()
{
ExecuteThisQuery();
}
#endregion
private void ExecuteThisQuery()
{
// Code to build and execute the delete query
}
}
}
<br>
In Main Test with
public class myclass
{
private static void Main(string[] args)
{
DoEqual x3 =
DeleteQueryWithGrammar.DeleteRowsFrom("Account")
.Where("Admin")
.IsNotEqualTo("Admin")
.Where("Admin")
.BothEqual("X")
.Excute();
}
}
This seems to work.
public class ConditionCreator
{
private Decision decision;
public ConditionCreator() { decision = new Decision(this); }
public Decision Add() { return decision; }
public class Decision
{
private ConditionCreator creator;
public Decision(ConditionCreator creator) { this.creator = creator; }
public ConditionCreator And() { return creator; }
public ConditionCreator Or() { return creator; }
public Condition Create() { return new Condition(); }
}
}
And you're now restricted to patterns like this when you make the calls:
var condition = new ConditionCreator()
.Add()
.Or()
.Add()
.And()
.Add()
.Create();
i wasn't able to find a similar issue but feel free to redirect me if i just missed it.
I am trying to get familiar with the Repository pattern.
I'll give you an example of the code i'm trying to get to work unsuccessfully.
These are the classes and interfaces that represent the entity i'm using.
public class AbsObj
{
public string Code { get; set; }
}
public interface IAbsObj
{
bool Save();
}
public class User : AbsObj
{
public string Language{get; set;}
}
public class DbUser : User, IAbsObj
{
public bool Save()
{
return true;
}
}
Then to the repository Interface
public interface IRepository<T>
{
void Add(T value);
void Update(T value);
void Delete(T value);
}
The generic Repository
public class Repository<T> : IRepository<T> where T : AbsObj, IAbsObj
{
protected List<T> _lst;
public Repository()
{
_lst = new List<T>();
}
public void Add(T value)
{
}
public void Update(T value)
{
}
public void Delete(T value)
{
}
public bool Save()
{
for (int i = 0; i < _lst.Count; i++)
{
_lst[i].Save();
}
return true;
}
}
Then a more specific repository, which should handle the loading of the users from the db:
public class UserRepository<T> : Repository<T> where T : AbsObj, IAbsObj
{
public void Load()
{
DbUser us = new DbUser();
us.Code = "Cod";
us.Language = "IT";
_lst.Add(us);
}
}
I created the DBUser class just to have the freedom to create an XMLUser in the future which would handle a different type of saving.
It inherits from User which in turn inherits from AbsObj.
It implements IAbsObj.
Nonetheless i got a compile time error when i try to add to the list the DbUser object created, stating that it's impossible to convert from DBUser to T.
Given the constraints i tought it was possible: what am i missing here?
Thanks in advance for any help!
Your UserRepository definition could be:
public class UserRepository : Repository<DbUser>
{
....
}
But since you want to make it generic for XMLUser as well:
public class UserRepository<T> : Repository<T> where T: User, new()
{
public void Load()
{
User us = new T() as User;
us.Code = "Cod";
us.Language = "IT";
_lst.Add(us);
}
}
To use:
new UserRepostitory<DbUser>();
new UserRepostitory<XmlUser>();
I have the following:
List<IReport> myList = new List<IReport>();
Report myReport = TheirApi.GetReport();
myReport meets all the qualifications of IReport, but cannot implement IReport because I do not have access to the source of TheirApi. Casting to type IReport obviously results in null, and I read that I cannot cast an anonymous type to an interface.
Do I have any options here?
A wrapper class was just what the doctor ordered:
ReportServices.GetAllCustomReports().ToList().ForEach(customReport => _customReports.Add(new ReportWrapper(customReport)));
public class ReportWrapper : IReport
{
private Report inner;
public int ID
{
get { return inner.ID; }
set { inner.ID = value; }
}
public string Name
{
get { return inner.Name; }
set { inner.Name = value; }
}
public ReportWrapper(Report obj)
{
inner = obj;
}
}
You will need to wrap this object inside another one that implements the interface, and then you will need to implement it calling the inner object's properties and methods.
For example:
public class ReportWrapper : IReport
{
MyObjectIsLikeReport inner;
public ReportWrapper(MyObjectIsLikeReport obj) {
this.inner = obj;
}
public void ReportMethod(int value) {
this.inner.ReportMethod(value);
}
public int SomeProperty {
get { return this.inner.SomeProperty; }
set { this.inner.SomeProperty = value; }
}
}
To use it, you can do this:
List<IReport> myList = new List<IReport>();
MyObjectIsLikeReport myReport = TheirApi.GetReport();
myList.Add(new ReportWrapper(myReport));
Consider Adapter Design Pattern.
Definition: Convert the interface of a class into another interface
clients expect. Adapter lets classes work together that couldn't
otherwise because of incompatible interfaces.
good reference: http://www.dofactory.com/Patterns/PatternAdapter.aspx
interface IReport
{
void DoSomething();
}
class ReportApdapter : IReport
{
private readonly Report _report;
public ReportApdapter(Report report)
{
_report = report;
}
public void DoSomething()
{
_report.DoSomething();
}
}
class Report
{
public void DoSomething()
{
}
}
//You can use like this.
IReport report = new ReportApdapter(TheirApi.GetReport());
Is it possible to do something like the following:
public class ChildClass : BaseClass
{
public ChildClass(BaseClass o)
{
base = o;
}
}
Basically, I want a transparent way to wrap a base class inside of other functionality. One example I've thought of is a custom Settings Provider which transparently audits the settings passed through it.
public class SettingsAuditor : SettingsProvider
{
public SettingsAuditor(SettingsProvider o)
{
base = o;
}
public override void SetPropertyValues(SettingsContext context, SettingsPropertyValueCollection propvals)
{
// Log the property change to a file
base.SetPropertyValues(context, propvals);
}
}
Then I could do the following:
mySettingsProvider = new SettingsAuditor(mySettingsProvider);
And all changes would go through the overridden SetPropertyValues before passing to the original object.
I could use a private SettingsProvider member, but then I either cannot inherit from SettingsProvider, or have an entire SettingsProvider (base) not being used at all.
I'm using C# 4.0 and .Net 4.0.
You cannot do base = o;
What you're looking for is the Decorator Pattern), which is a way to compositionally add functionality at runtime (vs. inheritance).
Instead of trying to set the base, you just contain the inner member. As long as the wrapper implements the same interface or base class as the inner object, you can pass back the new wrapper. You can wrap as many decorators as you want.
Consider:
public interface ICar
{
void Drive();
}
public class Car : ICar
{
public void Drive()
{
Console.WriteLine("vroom");
}
}
public class BuckleUp : ICar
{
ICar car;
public BuckleUp(ICar car) { this.car = car; }
public void Drive()
{
Console.WriteLine("click!");
car.Drive();
}
}
public class CheckMirrors : ICar
{
ICar car;
public CheckMirrors(ICar car) { this.car = car; }
public void Drive()
{
Console.WriteLine("mirrors adjusted");
car.Drive();
}
}
Now consider you have a method that accepts an ICar and tells it to drive. You could give it a Car, and it would work, but you could also wrap that car in a BuckleUp and a CheckMirrors and you wouldn't have to change that method at all. You've modified functionality through composition using the Decorator Pattern.
No. This looks like it should be a Composition vs Inheritance issue. You need to evaluate whether you are a "is a" or a "has a."
A little help for your journey
This is not a complete implmentation and it could probably be done much cleaner with expression trees... but this was a quick swing at faking AOP using DynamicObject with .Net 4.0.
public class MyDynamicWrapper<T> : DynamicObject
{
public T Wrapped { get; private set; }
public Action<T> Pre { get; private set; }
public Action<T> Post { get; private set; }
public MyDynamicWrapper(T wrapped, Action<T> pre, Action<T> post)
{
this.Wrapped = wrapped;
this.Pre = pre;
this.Post = post;
}
public override bool TryGetMember(
GetMemberBinder binder,
out object result)
{
var type = typeof(T);
var method = type.GetMethod(binder.Name);
if (method != null)
{
Func<object> func = () =>
{
if (Pre != null)
Pre(Wrapped);
// support for input parameters could be added here
var ret = method.Invoke(Wrapped, null);
if (Post != null)
Post(Wrapped);
return ret;
};
result = func;
return true;
}
return base.TryGetMember(binder, out result);
}
}
public class MyDynamicWrapper
{
public static MyDynamicWrapper<T> Create<T>(
T toWrap,
Action<T> pre = null,
Action<T> post = null)
{
return new MyDynamicWrapper<T>(toWrap, pre, post);
}
}
public class MyObject
{
public void MyMethod()
{
Console.WriteLine("Do Something");
}
}
class Program
{
static void Main()
{
var myobject = new MyObject();
dynamic mydyn = MyDynamicWrapper.Create(
myobject,
p => Console.WriteLine("before"),
p => Console.WriteLine("after"));
// Note that you have no intellisence...
// but you could use the old implmentation before you
// changed to this wrapped version.
mydyn.MyMethod();
/* output below
before
Do Something
after
*/
}
}
No, but you could fake it:
public class SettingsAuditor
{
SettingsProvider #base;
public SettingsAuditor(SettingsProvider o)
{
#base = o;
}
public void SetPropertyValues(SettingsContext context, SettingsPropertyValueCollection propvals)
{
// Log the property change to a file
#base.SetPropertyValues(context, propvals);
}
}
Note here, #base isn't the actual base, just a varaible named base