Organizing methods for better accessing them - c#

I'm trying to create a general library which would have all methods for managing data on our database.
This library will have a lot of methods so I would like to make it more organized. I would like it to be used with the following syntax.
db.setData().insertNewAccount(username, password);
db.modifyData().deleteAccount(username, password);
db.getData().getAccount();
How would I make it work like that if I type setData for example methods related to setData would show up.

It sounds like you're approaching this the wrong way - typically you'd have something like an AccountRepository class with all the members relating to accounts; then you'd have (say) an ArticleRepository class with all the members relating to articles.
In other words, organize by the kind of data you're dealing with rather than whether you're trying to fetch, update, insert etc.
Then you can use dependency injection so that each business class will be given just the repositories it uses.

If you really want to do it that way, then you could do something like this (pseudo code):
class DataRepository
{
public SetDataHelper setData()
{ return new SetDataHelper(); }
public ModifyDataHelper modifyData()
{ return new ModifyDataHelper(); }
public GetDataHelper getData()
{ return new GetDataHelper(); }
}
class SetDataHelper
{
public void insertNewAccount(username, password) { ... }
}
class ModifyDataHelper
{
public void deleteAccount(username, password) { ... }
}
class GetDataHelper
{
public Account getAccount() { ... }
}
And then you could do it your way, more fluently:
var db = new DataRepository();
db.setData().insertNewAccount(username, password);
db.modifyData().deleteAccount(username, password);
db.getData().getAccount();

You can create different interfaces, with different functionality, and your class can implement all of them. And then, your setData() can return the class itself, cast to the correcponding interface. E.g:
interface SetData {
int insertNewAccount(A, B);
}
interface ModifyData {
int deleteAccount(A, B);
}
interface GetData {
int getAccount(A, B);
}
class DBHandler : SetData, ModifyData , GetData {
//
// Implement the interfaces...
//
// Returns the interfaces
SetData setData(){ return (SetData)this; }
ModifyData modifyData (){ return (ModifyData )this; }
GetData getData (){ return (GetData )this; }
}
It does what you want, of course use the access modifiers accordingly your project. And this solution doesn't stop you from reaching the implemented interface functions directly, that would need another class, or something to proxy all call toward the DB class.

Related

How to send Class type to another class and create instance of this class?

I'm working on library that will help implement dedicated servers for all sorts of applications (mainly my goal is games). I'm working with sockets and I want to implement some sort of command system, where users will be able to invoke functions on the server.
I have a problem because I wanna let a user implement interactable command environment in a class created by him that my library will need to know about.
I created this template example of how it's all structured:
Implemented by me, part of library (very simplified):
public class UserInfo //class containing info about user
{
public int id;
public UserInfo(int _id)
{
id = _id;
}
}
public class UserManager
{
List<UserInfo> userInfos;
public UserManager(List<UserInfo> _userInfos) //We get out infos from somewhere...
{
userInfos = _userInfos; //...and keep reference to them
//SetupChildClassAndInfos();
}
//I'd like to have something like that BUT I don't know
//how ChildClass is called so I can't just type it like here
/*
List<ChildClass> childs = new List<ChildClass>();
void SetupChildClassAndInfos()
{
foreach (var userInfo in userInfos)
{
ChildClass child = new ChildClass();
child.someInfo = userInfo;
childs.Add(child);
}
}
*/
//I tried working with generics but failed miserably xd
List<T> childs = new List<T>();
public void GetChildClass<T>()
{
foreach (var userInfo in userInfos)
{
T child = new T();
child.userInfo = userInfo;
childs.Add(child);
}
}
//of course it doesn't work and makes no sense xD but I hope you kinda g
//get what I'm trying to accomplish
}
public class UserClass //Base class for further implementation containing
//userInfo that user needs to know about
{
public UserInfo userInfo;
}
Example implementation by someone else, I don't know how ChildClass will be called:
public class ChildClass : UserClass //there needs to be access to UserClass informations
{
CustomManager customManager;
[Command] //attribute making method be called automaticly when is the right time
public void Message(string _message) //A method made by a user BUT(!) he will never use it directly
{
customManager.ReceiveMessage(userInfo.id, _message);
}
}
public class CustomManager
{
UserManager userManager; //assume we somehow have reference
public CustomManager()
{
userManager.GetChildClass<ChildClass>(); //sending information in beginning to infoManager how I implemented my ChildClass (doesn't work)
}
public void ReceiveMessage(int _id, string _message)
{
Debug.Log("We got message: " + _message + " from user with id: " + _id);
}
}
So my question is how do I send a custom made class to UserManager and create instances of this class?
Maybe what I'm writing just doesn't make any sense and my aproach is stupid, feel free to criticize.
Make CustomManager a generic class
Generic Property in C#
OR
Use dependency injection via implementing the dependency inversion principal using spring.net or Unity framework.
What's wrong with having just a dictionary IReadOnlyDictionary<string, object>? Are you concerned with boxing of value types? A glimpse on your code convinces me that it's too early to proceed on more sophisticated solutions. So it makes sense to abstract out this piece into an interface and implement that one in a simplest possible way: with help of dictionaries (a-ka JavaScript way).

Need to create fakes for a class that manipulates the results of interface in microsoft unit testing tool using c#

I need to implement fakes for unit testing one of my methods. Problem is the method I need to test calls a class method and retrieves some system parameters.Scenario is as below:
Class A(){
public void method xx(){
//This needs to be tested.
//This method makes a call to retrieve some informations. The call is like
below:
String culture=Api.GetEnvironmentData().GetCulture();
//This is the problem area.
boolean implmentApi=Api.GetEnvironmentData().DoImplmentApi();
//This is the problem area.
}
}
This GetEnvironmentData method is something like this:
public static EnvironmentData GetEnvironmentData ()
{
return GetDiContainer().Resolve<EnvironmentData >();
}
EnvironmentData class is something like this:
public class EnvironmentData(){
public EnvironmentData(IEnvironmentDataProvider EnvironmentDataProvider){
//
}
}
I can fake the IEnvironmentDataProvider using moq but am not able to figure out how to fake the EnvironmentData class. I need to fake the EnvironmentData class because it manipulated the results of IEnvironmentDataProvider based of various method calls. For example both GetCulture and DoImplmentApi call the getData method of the interface IEnvironmentDataProvider and then cast them accordingly.
Now when I fake the IEnvironmentDataProvider and return some value I am not able to control what to return when GetCulture and when DoImplmentApi is called.
Can some one suggest how to implement the fakes for the above scenario.
You don't need to mock dependencies of EnvironmentData class. I see one problem here: you are using DI container, like Service Locator, which in this scenario behave like antipattern. All dependencies should be injected, e. g.: by constructor or property.
Change your Api class to something like this:
public class Api
{
private readonly EnvironmentData _environmentData;
public Api(EnvironmentData envData)
{
environmentData = envData;
}
public string GetCulture()
{
return _envData.GetCulture();
}
}
Remember that implementation details of Api class should be hidden. You shouldn't expose EnvironmentData in this scenario. Api class should ask for all dependencies which are needed to implement this class and has own interface.
Based on your comments, I think your best shot is to wrap the static class in a facade. Then you can mock the facade.
Something like this:
Class A
{
IEnvironmentDataFacade _environmentDataFacade;
Class A(IEnvironmentDataFacade environmentDataFacade)
{
_environmentDataFacade = environmentDataFacade;
}
public void method xx()
{
//Now you can fake IEnvironmentDataFacade:
String culture= _environmentDataFacade.GetCulture();
//Do the same as above with the method here:
boolean implmentApi=Api.GetEnvironmentData().DoImplmentApi();
//This is the problem area.
}
}
public class EnvironmentDataFacade : IEnvironmentDataFacade
{
public string GetCulture()
{
return Api.GetEnvironmentData().GetCulture();
}
}
public interface IEnvironmentDataFacade
{
string GetCulture();
}

How to call a method implicitly after every method call?

Sorry for the terrific Title for the post. I am bit curious to know if below problem does have any solutions or not. The situation is I have a function called SaveSecurity(); which I need to call after every function. Like below:
public void AddUser(string ID, string Name, string Password)
{
///some codes
SaveSecurity();
}
public void DeleteUser(User ObjUser)
{
///some codes
SaveSecurity();
}
public void AddPermission(string ID, string Name, AccessType Access)
{
///some codes
SaveSecurity();
}
public void DeletePermission(Permission ObjPermission)
{
///some codes
SaveSecurity();
}
public void AddRole(string ID, string Name)
{
Roles.AddRole(ID, Name);
SaveSecurity();
}
public void SaveSecurity()
{
///Saves the data
}
And many more. So now if we look there is a similarity to all the function is that at last it calls for the SaveSecurity() after the end of the function. My question is:
Is there a way to call this function after every function with out writing the same line again and again?
My Class Diagram looks like this
You need to look into repository pattern,
Seperate your classes and there operations,
Create another layer (call it business layer) or whatever which will be calling different methods of different classes...
ATM you are trying to follow OOP but all you are doing is functional programming..
Implementing the Repository and Unit of Work Patterns in an ASP.NET MVC Application
Edit After adding class diagram
Your collection classes are actually repository class, you will need to move your methods like deletePermissions, deleteRole to there respective repository classes like permissionsRepo (keep it named as collections if you want) and roleRepo..
So you already have an object class and a repository class of object (can be together) but I like to keep them separate, repostory classes will do what they need to do, like..
// Make changes to DB
// Make changes to AD
// Makes changes to web services etc...
Your manager class may dulicate methods of repository classes but they will only calling them,
PermissionManager.DeletePermissions(PermissionObject);
Then in PermissionManager Class you will have method,
DeletePermissions(Permissions pObject)
{
PermissionRepo.Delete(pObject);
}
Above is just adding a layer to make your code look more readable and future proof in very short time, but if you have more time to invest you can look into Observer pattern too...
Implement Observer pattern in C#
Each time your object changes it's state you can call SaveSecurity method (which will be in another class (Name it Changes maybe). If you don't want to call SaveSecurity for each change of object, you can add a property to your object e.g. IsSecurityChanged ? if yes then call SaveSecurity.
More to explain but if you look at Observer pattern above you will get an idea.
One more way but I won't personally recommend is, to use IDisposable interface, then in dispose method call SaveSecurity method for the object. BUT ITS NOT RECOMMENDED BY ME.
With just C# you can't, but there are some solutions that might help.
The best I know is PostSharp. It will give you the ability to define actions before and after a method is being called (for example). Some information on it can be found here and here.
The only thing you have to do then is to decorate the methods you want to call SaveSecurity for with an attribute.
If you don't want to use such tools, just keep it as is. It is okay the way it is.
You can use some kind of Aspect oriented programming (don't know how to do it in C#, but try googling it).
Another way that would not be better than simply calling one function at the end of another, would be create helper function with functional parameter that execute its parameter and then call your security function. But then body of each function would look something like (if I remember C# lambda correctly):
CallAndSaveSecurity(() => /* some code */);
So it would contain something extra as much as your original solution.
Btw, maybe you need more in your call anyway. If you want that function to be called even when exception happen, you need
try{
// some code
} finally {
SaveSecurity();
}
and hiding that into functional helper makes sense.
using System;
namespace Shweta.Question
{
public class User
{ }
public class Permission
{ }
public enum AccessType
{
none,
full,
other
}
public class Roles
{
public static void AddRole(string id, string name)
{
}
}
public class Shweta
{
public void AddUser(string ID, string Name, string Password)
{
///some codes
SaveSecurity();
}
public void DeleteUser(User ObjUser)
{
}
public void AddPermission(string ID, string Name, AccessType Access)
{
}
public void DeletePermission(Permission ObjPermission)
{
}
public void AddRole(string ID, string Name)
{
Roles.AddRole(ID, Name);
}
public void SaveSecurity()
{
///Saves the data
}
public TResult CallMethod<TResult>(Func<TResult> func)
{
try
{
return func();
}
catch (Exception e)
{
// Add Handle Exception
// replace the next line by exception handler
throw e;
}
}
public void CallMethod(Action method)
{
this.CallMethod(() => { method(); return 0; });
this.SaveSecurity();
}
public static void test()
{
var s = new Shweta();
s.CallMethod(() => s.AddRole("theId", "theName"));
s.CallMethod(() => s.DeleteUser(new User()));
s.CallMethod(() => s.AddPermission("theId", "theName", AccessType.full));
s.CallMethod(() => s.DeletePermission(new Permission()));
s.CallMethod(() => s.AddRole("theId", "theName"));
}
}
}

Can I use more generic interfaces to simplify my classes to use a command pattern?

I'm trying to make an app I'm designing more generic and implement the command pattern into it to use manager classes to invoke methods exposed by interfaces.
I have several classes with the GetItem() and GetList() methods in them, some are overloaded. They accept different parameters as I was trying to use dependency injection, and they return different types. Here are a couple of examples:
class DatastoreHelper
{
public Datastore GetItem(string DatastoreName)
{
// return new Datastore(); from somewhere
}
public Datastore GetItem(int DatastoreID)
{
// return new Datastore(); from somewhere
}
public List<Datastore> GetList()
{
// return List<Datastore>(); from somewhere
}
public List<Datastore> GetList(HostSystem myHostSystem)
{
// return List<Datastore>(); from somewhere
}
}
class HostSystemHelper
{
public HostSystem GetItem(int HostSystemID)
{
// return new HostSystem(); from somewhere
}
public List<HostSystem> GetList(string ClusterName)
{
//return new List<HostSystem>(); from somewhere
}
}
I'm trying to figure out if I could use a generic interface for these two methods, and a manager class which would effectively be the controller. Doing this would increase the reuse ability of my manager class.
interface IGetObjects
{
public object GetItem();
public object GetList();
}
class GetObjectsManager
{
private IGetObjects mGetObject;
public GetObjectsManager(IGetObjects GetObject)
{
this.mGetObject = GetObject;
}
public object GetItem()
{
return this.mGetObject.GetItem();
}
public object GetList()
{
return this.GetList();
}
}
I know I'd have to ditch passing in the parameters to the methods themselves and use class properties instead, but I'd lose the dependency injection. I know I'd have to cast the return objects at the calling code into what they're supposed to be. So my helper classes would then look like this:
class DatastoreHelper
{
public string DatastoreName { get; set; }
public string DatastoreID { get; set; }
public object GetItem()
{
// return new Datastore(); from somewhere
}
public List<object> GetList()
{
// return List<Datastore>(); from somewhere
}
}
class HostSystemHelper
{
public int HostSystemID { get; set; }
public string ClusterName {get; set;}
public object GetItem()
{
// return new HostSystem(); from somewhere
}
public List<object> GetList()
{
//return new List<HostSystem>(); from somewhere
}
}
But is the above a good idea or am I trying to fit a pattern in somewhere it doesn't belong?
EDIT: I've added some more overloaded methods to illustrate that my classes are complex and contain many methods, some overloaded many times according to different input params.
If I understand the concept correctly, a design like this is a really bad idea:
class DatastoreHelper
{
public string DatastoreName { get; set; }
public string DatastoreID { get; set; }
public object GetItem()
{
// return new Datastore(); from somewhere
}
public List<object> GetList()
{
// return List<Datastore>(); from somewhere
}
}
The reason is that getting results would now be a two-step process: first setting properties, then calling a method. This presents a whole array of problems:
Unintuitive (everyone is used to providing parameters as part of the method call)
Moves the parameter binding away from the call site (granted, this would probably mean "moves them to the previous LOC", but still)
It's no longer obvious which method uses which property values
Take an instance of this object and just add a few threads for instant fun
Suggestions:
Make both IGetObjects and GetObjectsManager generic so that you don't lose type safety. This loses you the ability to treat different managers polymorphically, but what is the point in that? Each manager will be in the end specialized for a specific type of object, and unless you know what that type is then you cannot really use the return value of the getter methods. So what do you stand to gain by being able to treat managers as "manager of unknown"?
Look into rewriting your GetX methods to accept an Expression<Func<T, bool>> instead of bare values. This way you can use lambda predicates which will make your code massively more flexible without really losing anything. For example:
helper.GetItem(i => i.DataStoreID == 42);
helper.GetList(i => i.DataStoreName.Contains("Foo"));
The first code samples look quite similar to the Repository Pattern. I think this is what are you trying to apply. The last sample is not good and Jon told you why. However, instead of reinventing the wheel, read a bit about the Repository (lots of questions about it on SO) because, if I understood correctly, this is what you really want.
About reuse, not many things and especially persistence interface are reusable. There is the Generic Repository Pattern (I consider it an anti-pattern) which tries to accomplish that but really, do all the application needs the same persistence interface?
As a general guideline, when you design an object, design it to fullfil the specific application needs, if it happens to be reused that's a bonus, but that's not a primary purpose of an object.
It is not a good idea. Based on these examples you would be better off with a generic interface for the varying return type and parameters of GetItem/GetList. Though honestly the prevalence of Managers, the use of something cas vague as GetItem in multiple places and trying to fit your solution into design patterns (rather than defining the solution in terms of the patterns) are huge code smells to me for the wider solution.

C# code to handle different classes with same method names

Let's say you have two different C# classes A and B that while not deriving from the same base class do share some of the same names for methods. For example, both classes have a connect and a disconnect method, as well as several others. I want to be able to write code once that will work with both types.
Here is a simplified example of what I would like to do:
public void make_connection(Object x)
{
x.connect() ;
// Do some more stuff...
x.disconnect() ;
return ;
}
Of course, this does not compile as the Object class does not have a connect or disconnect method.
Is there a way to do this?
UPDATE. I should have made this clear from the start: I only have the DLLs for A and B and not the source.
You can use an interface to accomplish what you want to do.
interface IConnectable
{
void Connect();
void Disconnect();
}
Both A and B should implement IConnectable. Then use IConnectable instead of Object as the parameter type for your method and you should be all set.
public void MakeConnection(IConnectable connectable)
{
connectable.Connect();
// Do some more stuff...
connectable.Disconnect();
}
Edit: Since you don't have the source code, you have a couple of options:
Use Max's solution of using the dynamic keyword, (if you are using .NET 4.0)
Use Steve's solution of using casting and if/else statements
Create wrapper classes for A and B and have them implement the interface (or use common abstract base class for them)
For example:
class AWrapper : IConnectable
{
private A obj;
public AWrapper(A obj)
{
this.obj = obj;
}
public void Connect()
{
this.obj.Connect();
}
public void Disconnect()
{
this.obj.Disconnect();
}
// other methods as necessary
}
(BWrapper would be similar, just using B instead of A)
Then you could create the wrappers and pass them into MakeConnection. It's up to you how you want to do it. Depending on your situation, one method may be easier than the others.
This will work in C# 4:
public void make_connection(dynamic x)
{
x.connect() ;
// Do some more stuff...
x.disconnect() ;
return ;
}
Try using an Interface rather.
Have a look at interface (C# Reference) and Interfaces (C# Programming Guide)
So something like
public interface IConnections
{
void connect();
void disconnect();
}
public class A : IConnections
{
public void connect()
{
//do something
}
public void disconnect()
{
//do something
}
}
public class B : IConnections
{
public void connect()
{
//do something
}
public void disconnect()
{
//do something
}
}
public void make_connection(IConnections x)
{
x.connect();
// Do some more stuff...
x.disconnect();
return;
}
There is a OOAD concept of 'Programe to an interface not to an implementation' which let's you avoid the chain of inheritance hierarchies
1- You can create a interfcae
interface IConnection
{
void Connect();
void Disconnect();
}
2- And let your classes implement this interface as shown below.
class A : IConnection
{
#region IConnection Members
public void Connect()
{
// your connect method implementation goes here.
}
public void Disconnect()
{
// your disconnect method implementation goes here.
}
#endregion
}
class B : IConnection
{
#region IConnection Members
public void Connect()
{
// your connect method implementation goes here.
}
public void Disconnect()
{
// your disconnect method implementation goes here.
}
#endregion
}
3- Once you done with the implementation than you can make your function accepting an argument of IConnection as shown below.
public void makeConnection(IConnection con)
{
con.Connect();
con.Disconnect();
}
4- And from your client code , you can pass the object of classes which implements IConnect Interface.
If the interface solution is not possible (e.g you don't have source code), another less effecient solution is to use reflection.
As others have said, re-factoring to use interfaces or using the dynamic approach are probably the most elegant ways.
If this is not possible you could cast the object to your types. I'd suggest using as and then checking that the cast worked, an unchecked cast would be dangerous if someone called this with a type that failed to cast.
E.g. If types A and B both have a method called DoSomething() then this will work...
public static void CallDoSomething(object o)
{
A aObject = o as A;
if (aObject != null)
{
aObject.DoSomething();
return;
}
B bObject = o as B;
if (bObject != null)
{
bObject.DoSomething();
return;
}
}
BUT this is pretty ugly to be honest... I'd really try and refactor to interfaces.
Either you will have to use an Interface (or Base class) as shown by Zach and astander, or you will have to case the object before using:
public void make_connection(Object x)
{
((A)x).connect() ;
// Do some more stuff...
x.disconnect() ;
return ;
}
You could also use reflection to invoke the methods
What you want is called Duck Typing.
From Wikipedia:
Duck typing is a style of dynamic typing in which an object's current set of methods and properties determines the valid semantics, rather than its inheritance from a particular class or implementation of a specific interface.
C# 4.0 allows this, as other have said, using the dynamic keyword

Categories