What is the design pattern name that used to create an object by passing an engine object - database

I have a class called DatabaseModel.
And an interface called DatabaseEngineInterface that have a methods such as:
insert
update
delete
select
So I can on running time determine which engine to use mysql or oracle which are a classes that implements the DatabaseEngineInterface
EngineDatabase engine = new MySQLEngine();
DatabaseModel db = new DatabaseModel(engine);
What is this design pattern called?

Specifically, this is the Constructor Injection pattern (described in my book), which is a special case of the Strategy pattern.

Isn't it an implementation of the strategy pattern? Wikipedia states that the strategy pattern is:
>a software design pattern that enables an algorithm's behavior to be selected at runtime
It also says that the strategy pattern:
defines a family of algorithms,
encapsulates each algorithm, and
makes the algorithms interchangeable within that family.
You are allowing the database which will be used (and so the behaviour) to be selected at run time. You have defined a family of algorithms (your interface), encapsulated each algorithm (by creating a class per provider) and they can be used interchangeably as the DatabaseModel depends only on the interface.

DaoFactory design pattern fits well for your implementation.
Interface
public interface DatabaseEngineInterface {
public void insert(User user);
public void update(User user);
public void delete(int userId);
}
Class which implements the above methods:
public class DatabaseModel implements DatabaseEngineInterface {
#Override
public void delete(int userId) {
// delete user from user table
}
#Override
public User[] findAll() {
// get a list of all users from user table
return null;
}
#Override
public User findByKey(int userId) {
// get a user information if we supply unique userid
return null;
}
#Override
public void insert(User user) {
// insert user into user table
}
#Override
public void update(User user) {
// update user information in user table
}
}
Factory
public class DatabaseModelDAOFactory {
public static UserDAO getUserDAO(String type) {
if (type.equalsIgnoreCase("mysql")) {
return new UserDAOMySQLImpl();
} else {
return new UserDAOORACLEImpl();
}
}
}
Client side code:
Then, in the client side instead of a hardcoded line like:
DatabaseModel userDAO=DatabaseModelDAOFactory.getUserDAODatabaseEngineInterface("jdbc");
You could have a properties file to be able to switch between DAOs dynamically, having retrieved that string from the properties file you can simply do:
DatabaseModel userDAO=DatabaseModelDAOFactory.getUserDaoDatabaseEngineInterface(myStringFromPropertiesFile);
myStringFromPropertiesFile would contain "mysql" or "oracle" according to the definition in your properties file.

Related

Flow: Use new type for variable?

I have a simple new class X which holds some results of a callout to an external system.
In a flow I need a variable of type X. Is there any way to declare a variable of that new type in a flow?
My new class is:
public class FooCalloutResult {
public Boolean success;
public Map<Id, Boolean> results;
public List<String> messages;
public FooCalloutResult() {
success = false;
results = new Map<Id, Boolean>();
messages = new List<String>();
}
}
If you want to get some data in a flow from an apex class you need to have an Process Invocable method - this is done by adding the #InvocableMethod annotation.
Example:
global class lookUpAccountAnnotation {
#InvocableMethod
public static List<String> getAccountIds(List<String> names) {
List<Id> accountIds = new List<Id>();
List<Account> accounts = [SELECT Id FROM Account WHERE Name in :names];
for (Account account : accounts) {
accountIds.add(account.Id);
}
return accountIds;
}
}
With this annotation the class will appear in your list of available elements in the Flow and you need to put the Input and Output that will go into it.
Depending on what kind of operation you want to do you might need to use the Process.plugin interface instead. Please check this article to see which option supports what kind of data to decide on what you need - https://help.salesforce.com/articleView?id=vpm_designer_elements_apex.htm&type=5

Limit c# model class parameter call to MS SQL server for non-existing table field

Working with database-first approach creating ASPNETCORE MVC web app with user authentication, I would like to override the way the parameters from IdentityUser class are queried to the database. The reason is the current implementation of IdentityUser has two new parameters NormalizedEmail and NormalizedUserName (which in my opinion retracts from Normalization).
Is there a way I can write the code below in the Model class so that those two parameters are not included in the query to the database or is that something that needs to be done in the controller class?
public class IdentityUser : Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUser
{
public override string NormalizedUserName
{ get { return null; } set { value = null; } }
public override string NormalizedEmail
{ get { return null; } set { value = null; } }
}
Not far as I can tell, both parameters are part of the data model and as explained in this Issue #351
About Identity 3.0:
...Instead we compute a normalized representation of the user name and we
store it in a separate column so that lookups by normalized user name
should now be sargable.
So in other words, if you "override the way the parameters from IdentityUser class are queried to the database" in essence you'll be doing exactly the opposite the class intends to do.

RIA Services SP2 Function Complex type not visible in Object Context

I am struggling with returning a complex type from my services layer. It doesnt seem to be accessible from my object context.
This is the query in the service layer. All compiling fine.
public IQueryable<USP_GetPostsByThreadID_Result> uspGetPostsByThreadID(int ThreadID)
{
return this.ObjectContext.USP_GetPostsByThreadID(ThreadID).AsQueryable();
}
When I try and call it from my client, the ForumContext is not seeing it. I checked the client generated file and nothing similar is being generated. Help!!!
The name of your method may not meet the expected convention for queries. Try one or both of the following:
Add the [Query] attribute
Rename the method to GetUspPostsByThreadID
Result:
[System.ServiceModel.DomainServices.Server.Query]
public IQueryable<USP_GetPostsByThreadID_Result> GetUspPostsByThreadID(int ThreadID)
{
return this.ObjectContext.USP_GetPostsByThreadID(ThreadID).AsQueryable();
}
Its very common to have a stored procedure returning data from multiple tables. The return type doesn't fit well under any of the Entity Types(Tables). Therefore if we define Complex Type as the return collection of objects from Stored Procedure invocation, it becomes quite a powerful tool for the developer.
Following these steps I have achieved successfully the configuration of complex type on a sample AdventureWorks database.
1. Refer the picture and ensure the Stored procedure and function import is done.
2. Add the Domain Service name it as AdventureDomainService.
3. Now its time to define the tell the RIA services framework to identify my Complex Type as Entity Type. To be able to do this, we need to identify a [Key] DataAnnotation. Entity types provide data structure to the application's data model and by design, each entity type is required to define a unique entity key. We can define key on one property or a set of properties in metadata class file AdventureDomainService.metadata.cs
First define the class then add MetadatatypeAttribute like :
[MetadataTypeAttribute(typeof(CTEmployeeManagers.CTEmployeeManagersMetadata))]
public partial class CTEmployeeManagers
{
internal sealed class CTEmployeeManagersMetadata
{
private CTEmployeeManagersMetadata() { }
[Key]
public int EmployeeID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int ManagerID { get; set; }
public string ManagerFirstName { get; set; }
public string ManagerLastName { get; set; }
}
}
Define the Domain service method to return the collection of objects/entities for populating the Silverlight Grid or any other data consuming controls.
public IQueryable<CTEmployeeManagers> GetEmployeeManagers(int empId)
{
return this.ObjectContext.GetEmployeeManagers(empId).AsQueryable();
}
We define IQueryable if we are to fetch the records from datasources like SQL, whereas we define IEnumerable if we are to fetch the records from in memory collections,dictionaty,arrays.lists, etc.
Compile the server side to generate the client proxy.
In the Silverlight side open the MainPage.xaml or wherever the datagrid is put, then add following namespaces :
using System.ServiceModel.DomainServices.Client;
using SLBusinessApplication.Web;
using SLBusinessApplication.Web.Services;
..
Load the data and display:
public partial class MyPage : Page
{
AdventureDomainContext ctx = new AdventureDomainContext();
public MyPage()
{
InitializeComponent();
LoadOperation loadOp = this.ctx.Load(this.ctx.GetEmployeeManagersQuery(29));
myGrid.ItemsSource = loadOp.Entities;
}
// Executes when the user navigates to this page.
protected override void OnNavigatedTo(NavigationEventArgs e)
{
}
}
That is all that is needed to do.
It has to be part of an entity. Complex types cannot be returned by themselves

Initializing DTOs on the server-side when using RIA services

Say you have an domain entity with business logic for initializing its default values. E.g.
class User : IUser, Entity
{
public User()
{
StartDate = DateTime.Now;
EndDate = StartDate.AddDays(3); // This value could be user-configured.
}
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
}
Using RIA services, the DTO that will be generated of course does not include any logic, only public properties. Which means that when a client (e.g. Silverlight application) displays a 'create new user' dialog, it will not be able to populate the fields with any default values (without, of course, duplicating the business logic on the client).
In an attempt to achieve this, I created new DTO (UserDTO) and a query in my UserDomainService:
// Construct a new domain entity and then convert to DTO
public UserDTO CreateNewUser()
{
var user = new User(); // Business logic has now been executed.
return new UserDTO(user);
}
This does allow the client to populate fields with default values, however when it comes time to add the newly created user, RIA has already added the UserDTO to it's internally mainted collection of entities, so you cannot call .Add on your domain context. You can still just call SubmitChanges, which will trigger the [Update] method to be called, however this seems to be going against the grain of how RIA services is supposed to be used (i.e. you shouldn't be doing an INSERT operation in an UPDATE method).
Is this scenario (i.e. server-side creation of DTOs) achievable in RIA services?
I don't know what your business logic looks like, but if you used a common method to save objects (whether new or modified) on the server, than you would be able to differentiate within that method, whether it is a modified object or really a new one.
Example on the server:
[Insert]
public void InsertUser(UserDTO user)
{
this.SaveUser(user);
}
[Update]
public void UpdateUser(UserDTO user)
{
this.SaveUser(user);
}
You could add a property to your User (or the base class, if you have one):
public class UserDTO
{
[...]
// only set this within the constructor,
// unfortunately it cannot be "private set", because of RIA Services
public bool IsNewEntity { get; set; }
}
In your SaveUser method use that flag:
private void SaveUser(UserDTO user)
{
if (user.IsNewEntity)
{
// do something with a new user
}
else
{
// do something with an existing user
}
}
The Constructor for the UserDTO would then be:
public UserDTO()
{
this.IsNewEntity = true;
}
I know, this looks a little trivial, but I do not know of a more "elegant" way.

Winforms: access class properties throughout application

I know this must be an age-old, tired question, but I cant seem to find anything thru my trusty friend (aka Google).
I have a .net 3.5 c# winforms app, that presents a user with a login form on application startup. After a successful login, I want to run off to the DB, pull in some user-specific data and hold them (in properties) in a class called AppCurrentUser.cs, that can thereafer be accessed across all classes in the assembly - the purpose here being that I can fill some properties with a once-off data read, instead of making a call to the DB everytime I need to. In a web app, I would usually use Session variables, and I know that the concept of that does not exist in WinForms.
The class structure resembles the following:
public class AppCurrentUser {
public AppCurrentUser() { }
public Guid UserName { get; set; }
public List<string> Roles { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
}
Now, I have some options that I need some expert advice on:
Being a "dumb" class, I should make the properties non-static, instantiate the class and then set the properties...but then I will only be able to access that instance from within the class that it was created in, right?
Logically, I believe that these properties should be static as I will only be using the class once throughout the application (and not creating new instances of it), and it's property values will be "reset" on application close. (If I create an instance of it, I can dispose of it on application close)
How should I structure my class and how do I access its properties across all classes in my assembly? I really would appreciate your honest and valued advice on this!!
Thanks!
Use the singleton pattern here:
public class AppUser
{
private static _current = null;
public static AppUser Current
{
get { return = _current; }
}
public static void Init()
{
if (_current == null)
{
_current = new AppUser();
// Load everything from the DB.
// Name = Dd.GetName();
}
}
public string Name { get; private set; }
}
// App startup.
AppUser.Init();
// Now any form / class / whatever can simply do:
var name = AppUser.Current.Name;
Now the "static" things are thread-unsafe. I'll leave it as an exercise of the reader to figure out how to properly use the lock() syntax to make it thread-safe. You should also handle the case if the Current property is accessed before the call to Init.
It depends on how you setup your architecture. If you're doing all your business logic code inside the actual form (e.g. coupling it to the UI), then you probably want to pass user information in as a parameter when you make a form, then keep a reference to it from within that form. In other words, you'd be implementing a Singleton pattern.
You could also use Dependency Injection, so that every time you request the user object, the dependency injection framework (like StructureMap) will provide you with the right object. -- you could probably use it like a session variable since you'll be working in a stateful environment.
The correct place to store this type of information is in a custom implementation of IIdentity. Any information that you need to identify a user or his access rights can be stored in that object, which is then associated with the current thread and can be queried from the current thread whenever needed.
This principal is illustrated in Rocky Lhotka's CLSA books, or google winforms custom identity.
I'm not convinced this is the right way but you could do something like this (seems to be what you're asking for anyway):
public class Sessions
{
// Variables
private static string _Username;
// properties
public static string Username
{
get
{
return _Username;
}
set
{
_Username = value;
}
}
}
in case the c# is wrong...i'm a vb.net developer...
then you'd just use Sessions.USername etc etc

Resources