BLToolkit - is it able to make async database operation? - bltoolkit

I want to avoid blocking the executing thread by slow database read , and I like BLToolkit DataAccessor very much
public abstract class PersonAccessor : DataAccessor
{
[SqlText(#"SELECT * FROM Person WHERE FirstName = #firstName")]
public abstract List<Person> GetPersonListByFirstName(string #firstName);
[SprocName("sp_GetPersonListByLastName")]
public abstract List<Person> GetPersonListByLastName(string #lastName);
}
Is it possible to use async operation for BLToolkit DataAccessor?
Hope it is able to return Task<T> and I can use await from C# 5.0
Br.

You may combine the Async attribute which provides the Begin End pattern and turn it into Task like this (not tested) :
public abstract class PersonAccessor : DataAccessor
{
[SqlText(#"SELECT * FROM Person WHERE FirstName = #firstName")]
public abstract List<Person> GetPersonListByFirstName(string #firstName);
[Async]
public abstract IAsyncResult BeginGetPersonListByFirstName(string #firstName, AsyncCallback callback, object state);
[Async]
public abstract List<Person> EndGetPersonListByFirstName(IAsyncResult asyncResult);
public Task<List<Person>> GetPersonListByFirstNameAsync(string #firstName)
{
return Task.Factory.FromAsync(
BeginGetPersonListByFirstName(),
EndGetPersonListByFirstName,
#firstName,
null);
}
}
public class TestClass
{
public List<Person> AwaitTest(PersonAccessor personAccessor, string #firstName)
{
return await personAccessor.GetPersonListByFirstNameAsync(#firstName);
}
}

Related

A way to always filter query results with Entity Framework Core

I am using an OrgID on all my models in an ASP.NET application using EF as a way to partition the database. I do this so that the database can be shared among multiple users while ensuring that only the data of their organization is available to them.
This forces me to write this OrgID with every insert and to filter every call I make to the database.
So for instance I query the current user's OrgID and insert this in my controllers' Update methods like this:
store.OrgID = await _userManager.GetUserAsync(User).OrgID;
_context.Update(store);
await _context.SaveChangesAsync();
Then when I want to list out objects I again need to filter by OrgID:
var orgID = await _userManager.GetUserAsync(User).OrgID;
var stores = await _context.Stores.Where(s => s.OrgID == orgID).ToListAsync();
I'd love to find a way to override the ApplicationDBContext so that these are handled automatically otherwise it's quite a tedious and error prone task to always handle this in every call to the database.
Any suggestions would be greatly appreciated.
Check Global Query Filters.
Global query filters are LINQ query predicates (a boolean expression
typically passed to the LINQ Where query operator) applied to Entity
Types in the metadata model (usually in OnModelCreating). Such filters
are automatically applied to any LINQ queries involving those Entity
Types, including Entity Types referenced indirectly, such as through
the use of Include or direct navigation property references.
Create an interface that has the OrgID :
public interface IOrgID
{
public int OrgID { get; set; }
}
All your models must implement this interface e.g.:
public class ApplicationUser : IdentityUser, IOrgID
{
public int OrgID { get; set; }
//...
}
public class Stores : IOrgID
{
public int OrgID { get; set; }
//...
}
Use generic repository and create CRUD methods considering the OrgID from the currently logged in user:
public class MyRepo
{
private readonly ApplicationDbContext _context;
private readonly IHttpContextAccessor _accessor;
private readonly int _orgID;
public MyRepo(ApplicationDbContext context, IHttpContextAccessor accessor)
{
_context = context;
_accessor = accessor;
var userId = _accessor.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
_orgID = _context.Users.Find(userId).OrgID;
}
public async Task<T> GetAsync<T>(Expression<Func<T, bool>> whereExp)
where T : class, IOrgId
{
return await _context.Set<T>().Where(x => x.OrgId == _orgID).FirstOrDefaultAsync(whereExp);
}
public async Task<bool> Create<T>(T entitiy)
where T : class, IOrgId
{
_context.Set<T>().Add(entitiy);
return await _context.SaveChangesAsync() > 0;
}
public async Task<bool> UpdateAsync<T>(T entity)
where T : class, IOrgId
{
_context.Entry<T>(entity).State = EntityState.Modified;
return await _context.SaveChangesAsync() > 0;
}
public async Task<IEnumerable<T>> ListAsync<T>(Expression<Func<T, bool>> whereExp)
where T : class, IOrgId
{
return await _context.Set<T>().AsNoTracking().Where(x => x.OrgId == _orgID).Where(whereExp).ToListAsync();
}
public async Task<bool> DeleteAync<T>(T entity)
where T : class, IOrgId
{
_context.Entry<T>(entity).State = EntityState.Deleted;
return await _context.SaveChangesAsync() > 0;
}
}
What people do I this case is create a class wrapping the DbContext and exposing methods that make sense for their business logic. In your case you can make a UserRepository/StoreRepository classes where the search methods require a origID paramamter
public class StoreRepository {
private ApplicationDBContext _context
StoreRepository(ApplicationDBContext context){
_context = context
}
public Task<Ilist<Store>> GetStores(int origID){
return _context.Stores.Where(s => s.OrgID == orgID).ToListAsync();
}
}

How to map object properties in an Orika custom mapper?

I tried to find an answer to this question in the Orika documentation but no luck.
I have the following classes:
public class A {
private String partNumber1;
private String partNumber2;
...
}
public class B {
private Integer shelfNumber;
private A a;
...
}
public class BDTO {
private Integer selfNumber;
private ADTO someA;
...
}
public class ADTO {
private String partNumber;
...
}
.. and the following CustomMapper's to map Objects of B to objects BDO
#Component
public class BMapper extends CustomMapper<B, BDTO> {
#Override
public void mapAtoB(B b, BDTO bdto, MappingContext context) {
super.mapAtoB(b, bdto, context);
//??? what to do here ???
}
}
#Component
public class AMapper extends CustomMapper<A, ADTO> {
#Override
public void mapAtoB(A a, ADTO adto, MappingContext context) {
super.mapAtoB(a, adto, context);
adto.setPartNumber(a.getPartNumber1() + a.getPartNumber2());
}
}
In my client code I have:
B b = new B(5, new A("100392", "100342"));
BDTO bdto = mapper.map(b, BDTO.class);
My question is, in BMapper, what is the correct way to get the AMapper to map "a" to "someA"? To put it differently, what is the correct way to map a to someA in BMapper? I suspect that it can be done through some interface in the MappingContext object.
I found an answer after some experimentation. To map property objects in the main objects mapper, i.e. the scenario explained above, one can use the protected "mapperFacade" member of CustomMapper.
So you can do something like this:
bdto.setSomeA(super.mapperFacade.map(b.getA(), ADTO.class));

abstract class methods overriding the methods of another abstract class

Lets say that I have this line of code:
public abstract class User
{
public string name;
public string email;
public string password;
public abstract void Create();
public abstract void Remove();
public abstract void Modify();
}
And then another abstract class:
public abstract class AbstractCustomer : User
{
public string address;
public Order order;
public abstract override void Create(string n,string e,string pa,int ph,string a);
public abstract override void Modify(string e, string pa, int ph, string a);
public abstract override void Remove(Order o);
public abstract void PlaceOrder(Item i);
public abstract void MakePayment(Order o);
}
and we have the customer which implements the AbstractCustomer:
public class Customer : AbstractCustomer
{
public override void Create(string name, string email, string password, int phoneNum, string address)
{
this.name = name;
this.email = email;
this.password = password;
this.phoneNum = phoneNum;
this.address = address;
this.isActive = true;
ConnectionToDB.SaveCustToDB();
}
public override void Remove(Order order)
{
order.CancelOrder();
}
public override void Modify(string email, string password, int phoneNum, string address)
{
ConnectionToDB.UpdateCustInDB();
}
public override void PlaceOrder(Item item)
{
order = new Order(item);
}
public override void MakePayment(Order order)
{
ConnectionToDB.SavePayToDB(order);
}
}
and this is where the problem starts (this is a helper class whose purpose is to call the methods easily)
public static void Create(AbstractCustomer user, string name, string email, string password, int phoneNum, string address)
{
user.Create(name, email, password, phoneNum, address);
}
public static void Remove(AbstractCustomer user, Order order)
{
user.Remove(order);
}
public static void Modify(AbstractCustomer user, string email, string password, int phoneNum, string address)
{
user.Modify(email, password, phoneNum, address);
}
public static void PlaceOrder(AbstractCustomer user, Item item)
{
user.PlaceOrder(item);
}
public static void MakePayment(AbstractCustomer user, Order order)
{
user.MakePayment(order);
}
These lines of codes produces errors like:
VS will tell you that the Customer class didn't implement the User's abstract methods(well, I think I did because I tried overriding it in the AbstractCustomer). But apparently, we don't need to override it in the Abstract class because the child class(Customer) will automatically inherits it and from there you can just directly override the methods. I found the explanation here overriding abstract methods in an inherited abstract class
But by doing the above solution, it presents another problem. The AbstractCustomer class will lose its purpose and therefore the HelperClass can't call any methods because its static classes depends on the AbstractCustomer that will be passed in the method.
So for the questions: (Problem: Grouping the methods into a static class for me to call it easily)
Is there a way to fix this kind of problem?(I'm thinking of using decorator pattern)
If I use the decorator pattern, what is the purpose of the ConcreteComponent?Is it okay if I remove it?
If I don't use the decorator pattern, is there any pattern available for this kind of problem?
If I don't use any pattern, is there any way to solve this?
Thanks for reading! Sorry coz its a long one! :)
Your solution is not related to Decorator pattern. Decorator - it is something, that should be inherited from existing abstraction (AbstractCustomer in your case) and add extra logic to it (it can be logging, or it can be extra check of each method's parameters for null, or something like that...). See this link.
Btw, I don't like the way how you construct your abstractions. It is better to have well-grained interfaces for each of your methods, e.g. ICanCreate for Create() method, ICanRemove for Remove() method, etc. It allows you to control further types which will implement that functionality. E.g., one customer can implement only ICanCreate interface, another one - ICanCreate + ICanRemove, etc.

DI in Service Contract WCF

Please find below my code. Employee class implements IEmployee interface.
namespace MiddleWare.ServiceContracts
{
[ServiceContract(Namespace = "http://mywebsite.com/MyProject")]
public interface IMiscellaneous
{
[OperationContract]
[ServiceKnownType(typeof(MiddleWare.Classes.Employee))]
IEnumerable<IEmployee> Search_Employee
(string SearchText);
}
namespace MiddleWare.ServiceClasses
{
public class Miscellaneous : IMiscellaneous
{
public IEnumerable<IEmployee> Search_Employee
(string SearchText)
{
List<IEmployee> emp = new List<IEmployee>();
IEmployee TempObject = (IEmployee)Activator.CreateInstance(typeof(IEmployee));
TempObject.EmployeeId = "12345678";
emp.Add(TempObject);
return emp;
}
}
}
As is visible the above code does compile but wont work because interface instance cannot be created.How can I achive DI(Dependency Injection) here...If I write..
IEmployee TempObject = (IEmployee)Activator.CreateInstance(typeof(Employee));
Then this class will be dependent not only on the Interface but also the class...assuming that one fine day Employee class becomes Employee2.There will be code changes at two places..
1)[ServiceKnownType(typeof(MiddleWare.Classes.Employee2))]
2)IEmployee TempObject = (IEmployee)Activator.CreateInstance(typeof(Employee2));
I want to avoid that. Can we do something at implementation of IOperationBehavior or is there a Ninject way of achieving this or am I trying to achieve impossible?
Consider a design change - Use the factory pattern to create an instance of your employee.
public EmployeeFactory : IEmployeeFactory
{
public IEmployee CreateEmployee()
{
return new Employee();
}
}
And introduce a dependency on the Factory from your middleware, so creating a new IEmployee becomes:
public class Miscellaneous : IMiscellaneous
{
private readonly IEmployeeFasctory _employeeFactory;
public class Miscellaneous(IEmployeeFactory employeeFactory)
{
_employeeFactory = employeeFactory;
}
public IEnumerable Search_Employee (string searchText)
{
List employees = new List();
IEmployee employee = _employeeFactory.CreateEmployee();
employee.EmployeeId = "12345678";
employees.Add(TempObject);
return employees;
}
And then you can inject your EmployeeFactory into Miscellaneous. And should Employee one day become deprecated and Employee2 comes along, just change the factory!
As rich.okelly points out in another answer, IEmployeeFactory should be used to create instances of the IEmployee interface, since IEmployee isn't a Service, but an Entity.
The IEmployeeFactory interface, on the other hand, is a Service, so should be injected into the service class using Constructor Injection. Here's a write-up of enabling Constructor Injection in WCF.
Had a discussion within the team.
1) Constructor based implementation is not comfortable..The service would be IIS hosted and consumed as a web-reference.Cannot ask client systems to provide FactoryImplementatedObjects in Miscellaneous class call.
2) Entity based factories is also not absolutely accurate.If I happen to have say 20 specific entities in my project like Employee,Material,Project,Location,Order then I need to have 20 Factories.Also the Miscellaneous class will have several custom constructors to support specific contract calls..
I have prepared a system which is working and DI is achieved to a great level but I feel like I am cheating OOPS..Doesnt feel correct at heart..but cannot be refuted to be wrong..Please check and let me know your comments.
I now have a IEntity Interface which is the base for all other Entities.
namespace BusinessModel.Interfaces
{
public interface IEntity
{
string EntityDescription { get; set; }
}
}
Hence forth all will implement this.
namespace BusinessModel.Interfaces
{
public interface IEmployee : IEntity
{
string EmployeeId { get; set ; }
}
}
namespace BusinessModel.Interfaces
{
public interface IProject : IEntity
{
string ProjectId { get; set; }
}
}
and so on..(Interface implementing interface..absolutely ridiculous,cheating but working)
Next,An Enum type is declared to have a list of all Entities...
namespace MiddleWare.Common
{
internal enum BusinessModel
{
IEmployee,
IProject
}
}
A DI Helper class is created which will henceforth be considered a part of Business Model and any changes to it (Implementation,Naming..) would be taken as a Business Shift.So if DIHelper class has to become DIHelper2 then this is like BIG.(Can this also be avoided??)
namespace MiddleWare.Common
{
internal sealed class DIHelper
{
internal static IEntity GetRequiredIEntityBasedObject(BusinessModel BusinessModelObject)
{
switch (BusinessModelObject)
{
case BusinessModel.IEmployee:
return new Employee();
}
return null;
}
}
}
Function is Self Explanatory...
So now finally,the contract and implementation...
namespace MiddleWare.ServiceContracts
{
[ServiceContract(Namespace = "http://mywebsite.com/MyProject")]
public interface IMiscellaneous
{
[OperationContract]
[ServiceKnownType(typeof(MiddleWare.Classes.Employee))]
IEnumerable<IEmployee> Search_Employee
(string SearchText);
}
}
namespace MiddleWare.ServiceClasses
{
public class Miscellaneous : IMiscellaneous
{
public IEnumerable<IEmployee> Search_Employee
(string SearchText)
{
List<IEmployee> IEmployeeList = new List<IEmployee>();
IEmployee TempObject = (IEmployee)DIHelper.GetRequiredIEntityBasedObject(MiddleWare.Common.BusinessModel.IEmployee);
TempObject.EmployeeId = "12345678";
IEmployeeList.Add(TempObject);
return IEmployeeList;
}
}
}
What do you say??
My Team is happy though :)
From your updated requirements, there is nothing related to DI in this question...
So, to create a type based on the service known types of a service contract you can use:
public class EntityLoader<TServiceContract>
{
private static readonly HashSet<Type> ServiceKnownTypes = new HashSet<Type>();
static EntityLoader()
{
var attributes = typeof(TServiceContract).GetMethods().SelectMany(m => m.GetCustomAttributes(typeof(ServiceKnownTypeAttribute), true)).Cast<ServiceKnownTypeAttribute>();
foreach (var attribute in attributes)
{
ServiceKnownTypes.Add(attribute.Type);
}
}
public TEntity CreateEntity<TEntity>()
{
var runtimeType = ServiceKnownTypes.Single(t => typeof(TEntity).IsAssignableFrom(t));
return (TEntity)Activator.CreateInstance(runtimeType);
}
}
Which is then useable like so:
[ServiceContract(Namespace = "http://mywebsite.com/MyProject")]
public interface IMiscellaneous
{
[OperationContract]
[ServiceKnownType(typeof(Employee))]
IEnumerable<IEmployee> SearchEmployee(string SearchText);
}
public class Miscellaneous : IMiscellaneous
{
private readonly EntityLoader<IMiscellaneous> _entityLoader = new EntityLoader<IMiscellaneous>();
public IEnumerable<IEmployee> SearchEmployee(string SearchText)
{
List<IEmployee> employees = new List<IEmployee>();
IEmployee employee = _entityLoader.CreateEntity<IEmployee>();
employee.EmployeeId = "12345678";
employees.Add(employee);
return employees;
}
}
Obviously, the above code assumes that ALL of your service entities will contain public parameterless constructors and that there will only be one ServiceKnownType that implements each interface.

NHibernate: How to inject dependency on an entity

NHibernate 3.2/Fluent NHibernate 1.3/StructureMap 2.6.3 -
Trying to follow DDD as an architectural strategy, I typically don't have dependencies on domain entities. However, I'm experimenting right now with adding more behavior to my domain entities so that they are not so anemic. Everything was going well until I hooked up NHibernate. I've got two issues:
NH requires a parameterless constructor and I'd rather not have a
ctor that shouldn't be used.
When NH tries to instantiate my entity, it needs to resolve my
dependencies but I haven't given NH anything with which it can do
that.
I've been reading on the web, but most (if not all) of the examples I have found are outdated (or just old). Even though the NH camp probably doesn't approve of what I'm doing, I'm looking for the NH way to do this.
The solution ended up an implementation of NHibernate's IInterceptor. It is actually a very simple implementation when you inherit from EmptyInterceptor and override JUST the Instantiate() and SetSession() methods. Here's my interceptor using StructureMap:
public class DependencyInjectionEntityInterceptor : EmptyInterceptor
{
IContainer _container;
ISession _session;
public DependencyInjectionEntityInterceptor(IContainer container)
{
_container = container;
}
public override void SetSession(ISession session)
{
_session = session;
}
public override object Instantiate(string clazz, EntityMode entityMode, object id)
{
if (entityMode == EntityMode.Poco)
{
var type = Assembly.GetAssembly(typeof (SomeClass)).GetTypes().FirstOrDefault(x => x.FullName == clazz);
var hasParameters = type.GetConstructors().Any(x => x.GetParameters().Any());
if (type != null && hasParameters)
{
var instance = _container.GetInstance(type);
var md = _session.SessionFactory.GetClassMetadata(clazz);
md.SetIdentifier(instance, id, entityMode);
return instance;
}
}
return base.Instantiate(clazz, entityMode, id);
}
}
Then, all you have to do is tell NHibernate to use your interceptor:
public FluentConfiguration GetFluentConfiguration(IContainer container)
{
return Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2008
.ConnectionString(c => c.FromConnectionStringWithKey("Database"))
.ShowSql())
.Mappings(m =>
m.AutoMappings.Add(AutoMap.AssemblyOf<SomeClass>()))
.ExposeConfiguration(x =>
x.SetInterceptor(new DependencyInjectionEntityInterceptor(container)));
}
When I was researching this, some suggested passing in the SessionFactory into the ctor of the interceptor class. Honestly, from a session management perspective, this approach would be better.
If you need additional dependencies in your entities don't use constructor injection. Instead create an additional parameter in the entity method.
Now you will ask yourself how do you get the dependency. For this you can use CommandHandlers and Commands. The command handler takes the dependency within its constructor and calls the method of the entity. In the UI you create a command message and send it to a command processor which is responsible for calling the correct command handler.
I hope my explanation is comprehensible to you.
Domain:
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public void SendNotification(string message, INotifier notifier)
{
notifier.SendMessage(string.Format("Message for customer '{0}' ({1}): {2}", Name, Id, message));
}
}
The INotifier infrastructure component is passed through the method and not the constructor!
Infrastructure:
public interface INotifier
{
void SendMessage(string message);
}
class EmailNotifier : INotifier
{
public void SendMessage(string message)
{
// SmtpClient...
}
}
class SMSNotifier : INotifier
{
public void SendMessage(string message)
{
// SMS ...
}
}
Command and CommandHandler:
public class NotificationCommandHandler : ICommandHandler<NotificationCommand>
{
private readonly INotifier _notifier;
public NotificationCommandHandler(INotifier notifier)
{
_notifier = notifier;
}
public void Execute(NotificationCommand commandMessage)
{
commandMessage.Employee.SendNotification(commandMessage.Message, _notifier);
}
}
public class NotificationCommand
{
public string Message { get; set; }
public Employee Employee { get; set; }
}
The CommandHandler gets the INotifier through constructor injection. So you do not need to use your IoC Container like a ServiceLocator.
Usage i.e. in the UI in a controller:
public class Controller
{
private readonly IMessageProcessor _messageProcessor;
public Controller(IMessageProcessor messageProcessor)
{
_messageProcessor = messageProcessor;
}
public void SendNotification (Employee employee, string message)
{
var sendMailCommand = new NotificationCommand
{
Employee = employee,
Message = message
};
_messageProcessor.Process(sendMailCommand);
}
}
If you have questions about the command processor have a look at the mvccontrib project or ask a separate question.
Sorry my previous answer didn't address the specific question. I did some more research, and it looks like I have much more to learn about when and when not to use an anemic domain model. Regarding your question, I found this article to be very on topic. It is on java, not c#, but the principles are the same. Hope this helps.