Design class chaining - c#

I have a third party C# library for ldap operations. It does all operations on connection object as below:
LdapConnection connection = new LdapConnetion(Settings settings);
connection.Search(searchOU, filter,...);
which I feel is not readable. I want to write a wrapper around it so that I should be able to write code like below:
As I would like to have different Ldap classes like
public class AD: LdapServer { }
public class OpenLdap: LdapServer { }
and then
AD myldap = new AD(Settings settings);
myldap.Users.Search(searchOU, filter,...)
myldap.Users.Add(searchOU, filter,...)
myldap.Users.Delete(searchOU, filter,...)
I am thinking about Proxy design pattern, but things are not getting into my head about hot to go about it. What classes should I have etc.
Any help?

The solution posted above inherits from the LdapConnection. This is good if you want to maintain the inheritance chain, but I dont think that is necessary in your case. You simply want to customize and simplify the interface.
The proxy design pattern inherits from the underlying object so that the proxy object can be used anywhere that the underlying object is required, this is good if you want to "inject" extra functionality into the class without the clients of that class realising. I dont think this is your intention here?
The big problem with the solution posted above is that (because it inherits directly from LdapConnection) you can call search in two ways like so:
Settings settings = new Settings();
AD myAD = new AD(settings);
object results = myAD.Users.Search();
// OR
object results2 = myAD.Search();
As I'm sure you can see from the code, both of these call the exact same underlying method. But in my opinion, this is even more confusing to developers than just using the vanilla LdapConnection object. I would always be thinking "whats the difference between these seemingly identical methods??" Even worse, if you add some custom code inside the UsersWrapper Search method, you cannot always guarentee that it will be called. The possibility will always exist for a developer to call Search directly without going through the UsersWrapper.
Fowler in his book PoEAA defines a pattern called Gateway. This is a way to simplify and customize the interface to an external system or library.
public class AD
{
private LdapConnection ldapConn;
private UsersWrapper users;
public AD()
{
this.ldapConn = new LdapConnection(new Settings(/* configure settings here*/));
this.users = new UsersWrapper(this.ldapConn);
}
public UsersWrapper Users
{
get
{
return this.users;
}
}
public class UsersWrapper
{
private LdapConnection ldapConn;
public UsersWrapper(LdapConnection ldapConn)
{
this.ldapConn = ldapConn;
}
public object Search()
{
return this.ldapConn.Search();
}
public void Add(object something)
{
this.ldapConn.Add(something);
}
public void Delete(object something)
{
this.ldapConn.Delete(something);
}
}
}
This can then be used like so:
AD myAD = new AD();
object results = myAD.Users.Search();
Here you can see that the LdapConnection object is completly encapsulated inside the class and there is only one way to call each method. Even better, the setting up of the LdapConnection is also completely encapsulated. The code using this class doesn't have to worry about how to set it up. The settings are only defined in one place (in this class, instead of spread throughout your application).
The only disadvantage is that you loose the inheritance chain back to LdapConnection, but I dont think this is necessary in your case.

Ok, if you simply want to split the methods up into they objects that they act on (i.e. in your example add the .Users. before the method call) you can do something similar to this.. You'll need to get the method parameters and return types correct for your library, I've just used object here.
Is this the sort of thing you're looking for?
public class AD : LdapConnection
{
private UsersWrapper users;
public AD(Settings settings) : base(settings)
{
this.users = new UsersWrapper(this);
}
public UsersWrapper Users
{
get
{
return this.users;
}
}
public class UsersWrapper
{
private AD parent;
public UsersWrapper(AD parent)
{
this.parent = parent;
}
public object Search()
{
return this.parent.Search();
}
public void Add(object something)
{
this.parent.Add(something);
}
public void Delete(object something)
{
this.parent.Delete(something);
}
}
}
This can then be be used as follows:
Settings settings = new Settings();
AD myAD = new AD(settings);
object results = myAD.Users.Search();
Remember that this isn't strictly a "wrapper" because it actually inherits from the underlying class.

Related

How can this class be designed better?

We have a Web API library, that calls into a Business/Service library(where our business logic is located), which in turn calls a Data access library (Repository).
We use this type of data transfer object all over the place. It has a "Payers" property that we may have to filter (meaning, manipulate its value). I have gone about implementing that check as such, but it feels dirty to me, as I'm calling the same function all over the place. I have thought about either:
Using an attribute filter to handle this or
Making the RequestData a property on the class, and do the filtering in the constructor.
Any additional thoughts or design patterns where this could be designed more efficiently:
public class Example
{
private MyRepository _repo = new MyRepository();
private void FilterRequestData(RequestData data)
{
//will call into another class that may or may not alter RequestData.Payers
}
public List<ReturnData> GetMyDataExample1(RequestData data)
{
FilterRequestData(RequestData data);
return _repo.GetMyDataExample1(data);
}
public List<ReturnData> GetMyDataExample2(RequestData data)
{
FilterRequestData(RequestData data);
return _repo.GetMyDataExample2(data);
}
public List<ReturnData> GetMyDataExample3(RequestData data)
{
FilterRequestData(RequestData data);
return _repo.GetMyDataExample3(data);
}
}
public class RequestData
{
List<string> Payers {get;set;}
}
One way of dealing with repeated code like that is to use a strategy pattern with a Func (and potentially some generics depending on your specific case). You could refactor that into separate classes and everything but the basic idea looks like that:
public class MyRepository
{
internal List<ReturnData> GetMyDataExample1(RequestData arg) { return new List<ReturnData>(); }
internal List<ReturnData> GetMyDataExample2(RequestData arg) { return new List<ReturnData>(); }
internal List<ReturnData> GetMyDataExample3(RequestData arg) { return new List<ReturnData>(); }
}
public class ReturnData { }
public class Example
{
private MyRepository _repo = new MyRepository();
private List<ReturnData> FilterRequestDataAndExecute(RequestData data, Func<RequestData, List<ReturnData>> action)
{
// call into another class that may or may not alter RequestData.Payers
// and then execute the actual code, potentially with some standardized exception management around it
// or logging or anything else really that would otherwise be repeated
return action(data);
}
public List<ReturnData> GetMyDataExample1(RequestData data)
{
// call the shared filtering/logging/exception mgmt/whatever code and pass some additional code to execute
return FilterRequestDataAndExecute(data, _repo.GetMyDataExample1);
}
public List<ReturnData> GetMyDataExample2(RequestData data)
{
// call the shared filtering/logging/exception mgmt/whatever code and pass some additional code to execute
return FilterRequestDataAndExecute(data, _repo.GetMyDataExample2);
}
public List<ReturnData> GetMyDataExample3(RequestData data)
{
// call the shared filtering/logging/exception mgmt/whatever code and pass some additional code to execute
return FilterRequestDataAndExecute(data, _repo.GetMyDataExample3);
}
}
public class RequestData
{
List<string> Payers { get; set; }
}
This sort of thinking naturally leads to aspect oriented programming.
It's specifically designed to handle cross-cutting concerns (e.g. here, your filter function cuts across your query logic.)
As #dnickless suggests, you can do this in an ad-hoc way by refactoring your calls to remove the duplicated code.
More general solutions exist, such as PostSharp which give you a slightly cleaner way of structuring code along aspects. It is proprietary, but I believe the free tier gives enough to investigate an example like this. At the very least it's interesting to see how it would look in PostSharp, and whether you think it improves it at all! (It makes strong use of attributes, which extends first suggestion.)
(N.B. I'm not practically suggesting installing another library for a simple case like this, but highlighting how these types of problems might be examined in general.)

Ordering items when conforming to the open-closed principle

I have a scenario where I need to return a list of actions and represent them on a context menu.
The software has a standard list of actions, e.g:
Analyse
Design
Develop
Implement
I am tasked with extending the original software for a different client, who would like to add an extra action, e.g.:
Analyse
Design
Develop
Test
Implement
I would like to develop this conforming to the OCP, so I have written the following factory class:
internal class ActionFactory
{
public IList<Action> Create()
{
var actionProvider =
Composition.Entity.CreateProvider<ActionProvider, Client>()[CurrentlyRunningClient];
return
actionProvider != null
?
StandardActions.Concat(actionProvider.AdditionalActions).ToList()
:
StandardActions;
}
private IList<Action> StandardActions
{
get
{
return
new Action[]
{
new Analyse(),
new Design(),
new Develop(),
new Implement()
}
.ToReadOnlyCollection();
}
}
}
The ActionProvider will seek out anything that implements a certain interface using reflection, returning me this class (if running the client that requires the new action):
internal class ActionProvider
{
public IList<MedicationAction> AdditionalActions
{
get
{
return new Action[]
{
new Test()
}
.ToReadOnlyCollection();
}
}
}
As far as conforming to OCP goes -- so far, so good! If anyone else wants to introduce a new action, then they don't have to modify any existing code. But the factory returns the standard list of actions with any new ones just tagged onto the end.
How would I specify an order for these actions without having to write some sort of class that would know about every possible action? (as I see it, violation of the OCP).

Is it possible to get the calling instance inside a method?

The general reason I want to do this is:
class MovieApiController : ApiController
{
public string CurrentUser {get;set;}
// ...
public string Index()
{
return Resources.GetText("Color");
}
}
class Resources
{
static string GetText(string id)
{
var caller = ??? as MovieApiController;
if (caller && caller.CurrentUser == "Bob")
{
return "Red";
}
else
{
return "Blue";
}
}
}
I don't need this to be 100% dependable. It seems like the callstack should have this information, but StackFrame doesn't seem to expose any information about the specific object on which each frame executes.
It is generally a bad idea for a method to try to "sniff" its surroundings, and produce different results based on who is making the call.
A better approach is to make your Resources class aware of whatever it needs to know in order to make its decision, and configure it in a place where all relevant information is known, for example
class MovieApiController : ApiController {
private string currentUser;
private Resources resources;
public string CurrentUser {
get {
return currentUser;
}
set {
currentUser = value;
resources = new Resources(currentUser);
}
}
// ...
public string Index() {
return resources.GetText("Color");
}
}
class Resources {
private string currentUser;
public Resources(string currentUser) {
this.currentUser = currentUser;
}
public string GetText(string id) {
if (currentUser == "Bob") {
return "Red";
} else {
return "Blue";
}
}
}
CurrentUser should be available at HttpContext.Current.User and you can leave your controller out of the resource class.
It seems like the callstack should have this information,
Why? The call stack indicated what methods are called to get where you are at - it does not have any information about instances.
Rethink your parameters be deciding what information does the method need to do its job. Reaching outside of the class (e.g. by using the callstack or taking advantage of static methods like HttpContext.Current) limit the re-usability of your code.
From what you've shown, all you need is the current user name (you don't even show where you use the id value. If you want to return different things based on what's passed in then maybe you need separate methods?
As a side note, the optimizer has a great deal of latitude in reorganizing code to make it more efficient, so there are no guarantees that the call stack even contains what you think it should from the source code.
Short answer - you can't, short of creating a custom controller factory that stores the current controller as a property of the current HttpContext, and even that could prove unpredictable.
But it's really not good for a class to behave differently by attempting to inspect its caller. When a method depends on another class it needs to get the correct behavior by depending on the right class, calling the right method, and passing the right parameters.
So in this case you could
have a parameter that you pass to GetResources that tells it what it needs to know in order to return the correct string.
Create a more specific version of the Resources class that does what you need
declare
public interface IResources
{
string GetText(string id);
}
And have multiple classes that implement IResources, use dependency injection to provide the correct implementation to this controller. Ideally that's the best scenario. MovieApiController doesn't know anything about the implementation of IResources. It just knows that there's an instance of IResources that will do what it needs. And the Resource class doesn't know anything about what is calling it. It behaves the same no matter what calls it.
That would look like this:
public class MovieApiController : ApiController
{
private readonly IResources _resources;
public MovieApiController(IResources resources)
{
_resources = resources;
}
public string Index()
{
return _resources.GetText("Color");
}
}
Notice how the controller doesn't know anything about the Resources class. It just knows that it has something that implements IResources and it uses it.
If you're using ASP.NET Core then dependency injection is built in. (There's some good reading in there on the general concept.) If you're using anything older then you can still add it in.
http://www.asp.net/mvc/overview/older-versions/hands-on-labs/aspnet-mvc-4-dependency-injection - This has a picture that is worth 1000 words for describing the concept.
http://www.c-sharpcorner.com/UploadFile/dacca2/implement-ioc-using-unity-in-mvc-5/
Some of these recommend understanding "inversion of control" first. You might find it easier to just implement something according to the example without trying to understand it first. The understanding comes when you see what it does.

DataContext in static class in desktop application

i am using 3 tier architecture in my winform application so i have static class which handle the operation of equipment
public static class Equipments
{
public static void AddEquipment(string name, decimal dimLength)
{
DBClassesDataContext db = new DBClassesDataContext();
Equipment equipment = new Equipment();
equipment.Name = name;
equipment.DimLength = dimLength;
db.Equipments.InsertOnSubmit(equipment);
db.SubmitChanges();
}
public static void UpdateEquipment(int equipmentID, string name, decimal dimLength)
{
DBClassesDataContext db = new DBClassesDataContext();
Equipment oldEquipment;
oldEquipment = db.Equipments.Where("EquipmentID = #0",equipmentID).SingleOrDefault();
oldEquipment.Name = name;
oldEquipment.DimLength = dimLength;
db.SubmitChanges();}
so my questions are :
Do i need to create instance of DBClassesDataContext in each method ?
because when i done global static DBClassesDataContext it didn't work correctly.
Is there any better way to handle DBClassesDataContext instead to create it each time inside the method (like create new DBClassesDataContext each time i run a method from this class)
Thanks
Do i need to create instance of DBClassesDataContext in each method?
You should do, absolutely - just like you should normally create a new SqlConnection each time you want to access the database in non-LINQ code. In general, avoid global state - it's almost always a bad idea.
There is any better way to handle DBClassesDataContext instead to create it each time inside the method
No - that's exactly the right approach. Why would you try to avoid just creating it each time?
Even though I'll probably get stoned to death for disagreeing with the Jon Skeet, I'll post this anyway.
You definitely don't need to create the instance in every single method, or at least not like this. There's a principle I like to follow called DRY - don't repeat yourself, and repeating the same line over and over, that can be avoided, clearly violates this principle.
You have multiple options here:
1.) define the methods as instance methods, maybe something like this:
internal class MyDbActions
{
private MyDbContext _myDbContext;
private MyDbContext Db
{
get
{
if (_myDbContext == null) _myDbContext = new MyDbContext();
return _myDbContext;
}
}
internal void Add(SomeClass c)
{
Db.Table.AddObject(c);
Db.SubmitChanges();
Db.Dispose();
}
}
Or something like that, you get the idea. This can be modified to whatever you need.
2.) use can use dependency injection for your methods, so consider something like this:
public static class Equipments
{
public static void AddEquipment(DBClassesDataContext db, string name, decimal dimLength)
{
Equipment equipment = new Equipment();
equipment.Name = name;
equipment.DimLength = dimLength;
db.Equipments.InsertOnSubmit(equipment);
db.SubmitChanges();
}
}
You'd manage your datacontext outside this class.
3.) you can utilize the Repository pattern, Unit of work pattern and IoC. I won't post the example code here, because it's quite lengthy, but here's one link to give you an idea:
Repository pattern with Linq to SQL using IoC, Dependency Injection, Unit of Work

Initializing constructor from stored cache in C#

I'm not sure exactly how to describe this question, but here goes. I've got a class hierarchy of objects that are mapped in a SQLite database. I've already got all the non-trivial code written that communicates between the .NET objects and the database.
I've got a base interface as follows:
public interface IBackendObject
{
void Read(int id);
void Refresh();
void Save();
void Delete();
}
This is the basic CRUD operations on any object. I've then implemented a base class that encapsulates much of the functionality.
public abstract class ABackendObject : IBackendObject
{
protected ABackendObject() { } // constructor used to instantiate new objects
protected ABackendObject(int id) { Read(id); } // constructor used to load object
public void Read(int id) { ... } // implemented here is the DB code
}
Now, finally, I have my concrete child objects, each of which have their own tables in the database:
public class ChildObject : ABackendObject
{
public ChildObject() : base() { }
public ChildObject(int id) : base(id) { }
}
This works fine for all my purposes so far. The child has several callback methods that are used by the base class to instantiate the data properly.
I now want to make this slightly efficient. For example, in the following code:
public void SomeFunction1()
{
ChildObject obj = new ChildObject(1);
obj.Property1 = "blah!";
obj.Save();
}
public void SomeFunction2()
{
ChildObject obj = new ChildObject(1);
obj.Property2 = "blah!";
obj.Save();
}
In this case, I'll be constructing two completely new memory instantiations and depending on the order of SomeFunction1 and SomeFunction2 being called, either Property1 or Property2 may not be saved. What I want to achieve is a way for both these instantiations to somehow point to the same memory location--I don't think that will be possible if I'm using the "new" keyword, so I was looking for hints as to how to proceed.
Ideally, I'd want to store a cache of all loaded objects in my ABackendObject class and return memory references to the already loaded objects when requested, or load the object from memory if it doesn't already exist and add it to the cache. I've got a lot of code that is already using this framework, so I'm of course going to have to change a lot of stuff to get this working, but I just wanted some tips as to how to proceed.
Thanks!
If you want to store a "cache" of loaded objects, you could easily just have each type maintain a Dictionary<int, IBackendObject> which holds loaded objects, keyed by their ID.
Instead of using a constructor, build a factory method that checks the cache:
public abstract class ABackendObject<T> where T : class
{
public T LoadFromDB(int id) {
T obj = this.CheckCache(id);
if (obj == null)
{
obj = this.Read(id); // Load the object
this.SaveToCache(id, obj);
}
return obj;
}
}
If you make your base class generic, and Read virtual, you should be able to provide most of this functionality without much code duplication.
What you want is an object factory. Make the ChildObject constructor private, then write a static method ChildObject.Create(int index) which returns a ChildObject, but which internally ensures that different calls with the same index return the same object. For simple cases, a simple static hash of index => object will be sufficient.
If you're using .NET Framework 4, you may want to have a look at the System.Runtime.Caching namespace, which gives you a pretty powerful cache architecture.
http://msdn.microsoft.com/en-us/library/system.runtime.caching.aspx
Sounds perfect for a reference count like this...
#region Begin/End Update
int refcount = 0;
ChildObject record;
protected ChildObject ActiveRecord
{
get
{
return record;
}
set
{
record = value;
}
}
public void BeginUpdate()
{
if (count == 0)
{
ActiveRecord = new ChildObject(1);
}
Interlocked.Increment(ref refcount);
}
public void EndUpdate()
{
int count = Interlocked.Decrement(ref refcount);
if (count == 0)
{
ActiveRecord.Save();
}
}
#endregion
#region operations
public void SomeFunction1()
{
BeginUpdate();
try
{
ActiveRecord.Property1 = "blah!";
}
finally
{
EndUpdate();
}
}
public void SomeFunction2()
{
BeginUpdate();
try
{
ActiveRecord.Property2 = "blah!";
}
finally
{
EndUpdate();
}
}
public void SomeFunction2()
{
BeginUpdate();
try
{
SomeFunction1();
SomeFunction2();
}
finally
{
EndUpdate();
}
}
#endregion
I think your on the right track more or less. You can either create a factory which creates your child objects (and can track "live" instances), or you can keep track of instances which have been saved, so that when you call your Save method it recognizes that your first instance of ChildObject is the same as your second instance of ChildObject and does a deep copy of the data from the second instance over to the first. Both of these are fairly non-trivial from a coding standpoint, and both probably involve overriding the equality methods on your entities. I tend to think that using the first approach would be less likely to cause errors.
One additional option would be to use an existing Obect-Relational mapping package like NHibernate or Entity Framework to do your mapping between objects and your database. I know NHibernate supports Sqlite, and in my experience tends to be the one that requires the least amount of change to your entity structures. Going that route you get the benefit of the ORM layer tracking instances for you (and generating SQL for you), plus you would probably get some more advanced features your current data access code may not have. The downside is that these frameworks tend to have a learning curve associated with them, and depending on which you go with there could be a not insignificant impact on the rest of your code. So it would be worth weighing the benefits against the cost of learning the framework and converting your code to use the API.

Categories

Resources