Design concept (pattern?) for method call in c#? - c#

I would like to create a structure where I call a method and this method parameter should be only available only from an instanced class.
What I exactly mean..., I have a class which contains functions like:
public class Functions
{
public Request GetId(int item)
{
//return instanced request
}
public Request SetId(int item)
{
//return instanced request
}
}
I have an invoker class, which has a method, called Invoke(Request request).
I would like to use Functions class as the parameter of this method, but accepted parameters can only be come from this class.
Actually I do this to create an instance from the functions class inside the class of the Invoke method and looks like this:
Functions Requests = new Functions();
...so when I would like to call the Invoke method, it looks like this:
Invoke(Requests.GetId(1));
But is there any way to solve, that I can only Invoke Requests from the instanced class, like:
Invoke(GetId(1));
Maybe I think on a wrong way but hopefully, it's clear what I would like to reach. (Seperate Functions from the Invoker class but keep the relation between them).
Thank you!

Why not to make class and methods static
public static class Functions
{
public static Request GetId(int item)
{
//return instanced request
}
public static Request SetId(int item)
{
//return instanced request
}
}
and then
using static Functions;
you will be able to use this syntex then:
Invoke(GetId(1));
But this is not good practice.

Related

Delegate a method call, to another method

I am not sure if what I am looking for is even possible, but I wonder if there is a way to delegate a method, when it is called, to another method. Let's say I have a declared object Receiver with a public method OnReceived(string param), inside a class ReceiverMiddleMan. When this method is called on Receiver, I would like to pass the parameters of this method to a method OnReceivedInMiddleMan somehow, not necessarily in the way as is shown in the code. Why? Because I would like to know if the data in Receiver.OnReceived can be got directly, without for instance inheriting from Receiver to access the method. The Receiver class, used here as an example, is in real life a Third party library which I cannot modify with events and such. The only access I have is the public method.
class Receiver
{
public void OnReceived(string param)
{
//do something
}
}
class ReceiverMiddleMan
{
Receiver receiver = new Receiver();
Listen(receiver.OnReceived);
public void Listen(Method method)
{
OnReceivedInMiddleMan(method.param);
}
public void OnReceivedInMiddleMan(string param)
{
//do something
}
}

Dynamically instantiate objects when they're first invoked in autofac c#

Im trying to figure out how to dynamically instantiate class when it's first used. Something like autofac's Lazy does but without refactoring all my classes.
Is there any possiblity to do something like this:
public class MyService : IMyService {
public MyService() {
// I want it to be invoked only if SomeMethod was invoked before.
// 1. Attempt to invoke SomeMethod
// 2. call MyService.constructor
// 3. invoke MyService.SomeMethod()
}
public void SomeMethod() {
///literally any code.
}
}
It has to be done without changing existing codebase (except services registration/ autofac setup or other areas that could be changed without much effort), and all services look's like that:
public class Service : IService {
public Service(AnotherService service){
///...
}
}
My initial idea was to create Proxy class and then while registering services wrap it with that proxy.
It could look something like this:
public class Proxy<T>
{
private T _target;
private bool instantiated = false;
private void Instantiate()
{
Console.WriteLine("Creating instance");
_target = Activator.CreateInstance<T>();
}
public void xxx() - this method should be called every time any wrapped type method get's called.
{
if (instantiated == false)
{
Instantiate();
instantiated = true;
}
/// proceed with invocation. (im not sure how to do this via reflection).
}
}
The main issue with this idea is that above proxy class should be created at runtime via reflection and it has to mimic wrapping class behaviour.
I'd appreciate any advice on how to approach this problem.
All i want to lazy create dependencies in autofac container (currently if dependency A is requiring dependency B then B is instantiated, i want change this to instantiate B only if any method from A calls B.method).
Thanks!
What you're looking for is the Proxy pattern. You can create a lazy proxy as follows:
public class LazyMyServiceProxy : IMyService
{
private readonly Lazy<MyService> lazy;
public LazyMyServiceProxy(Lazy<MyService> lazy) => this.lazy = lazy;
public void SomeMethod() => this.lazy.SomeMethod();
}
You can use this proxy using the following Autofac registrations.
builder.RegisterType<MyService>();
builder.RegisterType<LazyMyServiceProxy>().As<IMyService>();

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"));
}
}
}

How do I create a proxy object that forwards method calls in c#?

I'm trying to use selenium to run tests; seems like there isn't a good way to run the same set of unit tests on multiple browsers.
I read this post about running tests in parallel:
http://slmoloch.blogspot.com/2009/12/design-of-selenium-tests-for-aspnet_19.html
However, I'm using the visual studio unit testing framework.
I can create a proxy class like this:
public class SeleniumProxy {
private List<DefaultSelenium> targets;
public SeleniumProxy() {
targets = new List<DefaultSelenium>();
targets.Add(new DefaultSelenium(... "firefox"...));
targets.Add(new DefaultSelenium(... "iexplore"...));
}
public void Open(String url) {
foreach (var i in targets) {
i.Open(url);
}
}
...
}
My question is this? How can I do it without having to rewrite the entire class as a proxy?
I thought maybe passing a lamda in to map arguments, or passing by a function that takes the name of the method to invoke, but these all seem like pretty lame ideas.
What I really want is to add a member like:
public class SeleniumProxy {
public dynamic proxy;
....
}
And invoke this like:
var selenium = getProxy();
selenium.proxy.Open("...");
Does c# allow this kind of syntax for dynamic objects?
Or some kind of meta-handler for classes that lets them catch no-such-method exceptions and handle them manually?
Basically:
How can I create a proxy object that dynamically invokes methods on an internal member of the class?
(Edit: perhaps... using reflection on the DefaultSelenium object and creating function stubs on the dynamic proxy object for each entry..?)
If I understand what you're attempting, I think you can extend DynamicObject to achieve this.
class Proxy : System.Dynamic.DynamicObject
{
public Proxy(object someWrappedObject) { ... }
public override bool TryInvokeMember(System.Dynamic.InvokeMemberBinder binder, object[] args, out object result)
{
// Do whatever, binder.Name will be the called method name
}
}
//Do whatever... would become some code that pokes at some other object's internal members (via reflection, presumably) using binder.Name as part of the lookup process.
There are TryGetMember and TryGetIndex methods to override if you need to wrap up anything fancier that simple method invokes.
You will have to cast instances of Proxy to dynamic after construction to make arbitrary calls, just like when dealing with ExpandoObject.
You could leverage inheritance and have your tests defined in an abstract base class with a factory method to create your selenium instance, then inherit this for each type of browser you want to model. The tests will then be run for each inherited class with the appropriate browser. Using NUnit as an example:
public abstract class AbstractTests
{
protected abstract DefaultSelenium CreateSelenium();
[Test]
public void TestSomethingA()
{
DefaulSelenium selenium = CreateSelenium();
//Do some testing with selenium.
}
}
[TestFixture]
public class IETests : AbstractTests
{
protected override DefaultSelenium CreateSelenium()
{
return new DefaultSelenium("iexplore");
}
}
[TestFixture]
public class FirefoxTests : AbstractTests
{
protected override DefaultSelenium CreateSelenium()
{
return new DefaultSelenium("firefox");
}
}

Categories