Change the object's namespace dynamically - c#

I use PayPal's service on Service References. As is known to have a PayPal SandBox environment.
I know a site is running on local or not.
My problem is that I want to dynamically change the namespace of the class by the environment (because the two classes have the same function). Eventually I want I do not have to change any code, but once automatically when the site is run by local the sandbox will and when he runs on the server is the real product will.
I want to switch between this:
using DynoPayPal.PayPal;
And this:
using DynoPayPal.SandBoxPayPal;
So that the object: PaymentDetailsItemType for example, will "be" DynoPayPal.PayPal in the first case, and DynoPayPal.SandBoxPayPal in the second case.

You cannot change the namespace of a class. That is not what they are there for, and it makes no sense whatsoever to do so. But, as the comments to your question point out, what you are looking for is dependency injection. Consider this:
public interface IPayPal
{
void aMethod();
}
public class PayPal : IPayPal { /* ... */ }
public class SandboxPayPal : IPayPal { /* ... */ }
Then we can perhaps envisage a class that will give us the right one based on the environment:
public sealed class PayPalFactory
{
public IPayPal Create()
{
if(EnvironmentIsLive) // replace this with a proper check!
return new PayPal();
else
return new SandboxPayPal();
}
}

Related

How can I always send a specific value for a given type in an ASP.NET Core app?

I'm loading some endpoints defined in external assemblies, into my web app on startup with:
// Add channel endpoints.
var endpointsFolder = Configuration.GetSection("EndpointsFolder").Get<string>();
foreach (var file in Directory.GetFiles(endpointsFolder))
services.AddMvc().AddApplicationPart(Assembly.LoadFrom(file));
All of the loaded endpoints derive from a custom class called SecureEndpoint which requires an interface ISecurityContext:
[ApiEndpoint]
public class SecureEndpoint : ControllerBase {
public SecureEndpoint(ISecurityContext securityContext) { ... }
}
So, for example:
[Route("test")]
public sealed class TestEndpoint : SecureEndpoint {
public TestEndpoint(ISecurityContext securityContext) : base(securityContext) { ... }
[HttpGet]
public string Get() {
return "This is a test.";
}
}
The problem I'm having is that when I invoke the endpoint, I get an error saying:
System.InvalidOperationException: Unable to resolve service for type Namespacing.ISecurityContext while attempting to activate Namespacing.TestEndpoint.
A few searches on the matter give a pretty simple solution:
services.AddScoped<ISecurityContext, SecurityContext>();
However, I have one problem; ISecurityContext is given to me in the form of the interface only. The value that is given to me, is the value I should use everywhere it's required. As a result, I need a way to say "if ISecurityContext is needed, use this value".
Is there a way to always send a specific value for a given type?
Edit: services.AddSingleton(...) did the trick, but I don't have time to type an answer up for it currently. I'll circle back later this afternoon.
If there are any compilation issues, they are only the result of typing this question.

xUnit class constructor should get arguments passed from theory test methods

On the xUnit website it says the following about constructor:
xUnit.net creates a new instance of the test class for every test that
is run, so any code which is placed into the constructor of the test
class will be run for every single test. This makes the constructor a
convenient place to put reusable context setup code where you want to
share the code without sharing object instances (meaning, you get a
clean copy of the context object(s) for every test that is run).
I have the following code:
public class ProfilePageTest
{
public ProfilePageTest(Role role)
{
AuthRepository.Login(role)
}
[Theory]
[Roles(Role.Editor, Role.Viewer)]
public void OpenProfilePageTest(Role role)
{
var profile = GetPage<ProfilePage>();
profile.GoTo();
profile.IsAt();
}
}
Is it possible to pass the role from the theory attribute to the constructor, so I don't have to do AuthRepository.Login(role) in every test method that I have.
No, that's not possible. The constructor will be run before anything else, as with any constructor you're used to. I don't see the harm in calling AuthRepository.Login(role) in every test though, because it's a single line of code.
This is quite an excellent blog post about the different ways you can pass data into xUnit tests, but all of them are passing in data to individual methods (tests) rather than in the constructor.
If you are looking to set something up for multiple tests you should have a look int IClassFixture
Quick run down, you setup a class with the shared data:
public class DatabaseFixture : IDisposable
{
public DatabaseFixture()
{
Db = new SqlConnection("MyConnectionString");
// ... initialize data in the test database ...
}
public void Dispose()
{
// ... clean up test data from the database ...
}
public SqlConnection Db { get; private set; }
}
And then in your tests you can "inject" the class (along with the data) into the test class:
public class MyDatabaseTests : IClassFixture<DatabaseFixture>
{
DatabaseFixture fixture;
public MyDatabaseTests(DatabaseFixture fixture)
{
this.fixture = fixture;
}
// ... write tests, using fixture.Db to get access to the SQL Server ...
}

In a C# method, how do I determine (externally) which methods use a field/property

I want to be able to determine the impact of making a change to a Service. In other words, given the following C# example class, I need to be able to determine if I change MyServiceWithConfig that I:
will impact the route /feature/my-route-with-config
will not impact the route /feature/my-route
[RoutePrefix("feature")]
public sealed class MyWebApiController : ApiController
{
public MyWebApiController()
: this(
new MyService(),
new MyServiceWithConfig(StaticClass.Configuration))
{
// noop
}
private MyWebApiController(
MyService myService,
MyServiceWithConfig myServiceWithConfig)
{
this.MyServiceInstance = myService;
this.MyServiceWithConfigInstance = myServiceWithConfig;
}
private MyService MyServiceInstance { get; }
private MyServiceWithConfig MyServiceWithConfigInstance { get; }
[HttpGet,
Route("my-route")]
public async Task<object> Get()
{
return await this.MyServiceInstance.DoWork();
}
[HttpGet,
Route("my-route-with-config")]
public async Task<object> GetWithConfig()
{
return await this.MyServiceWithConfigInstance.DoWork();
}
}
What I have done so far (using reflection in PowerShell 5)
Find all Types that have a base class of ApiController
Of those types I know
If they have a private field or property of type MyServiceWithConfig
Which methods are routes and what those actual routes are
What I am not able to determine how to do:
- Determine that only one of these routes actually references this.MyServiceWithConfigInstance
From what I've read in other posts - it does not look like I can determine usage of a field using reflection. Is this something that I can use another tool to do? It has to be something I can automate because I need it to scan thousands of classes and it isn't practical to process one class at a time.
Is this something that I can leverage Roslyn for?
Thanks!
Note: I can post the PowerShell, but that doesn't seem to be helpful as it is over 100 lines so far.

Hierarchical "OneTimeSetUp" methods

Ok, I've got some nunit tests I'm writing to test an API. Any time I need to run these tests, I first need to login to the api to obtain a token. To start with, that's how I've written my OneTimeSetUp.
So, OneTimeSetUp is called, I log in, a shared field stores the token, each test is called a tests a different endpoint on api.
Now the problem. We've decided that we want to have individual tests for individual fields on the response, so that we can see what exactly is (and isn't failing) if something is wrong. So, we split out each endpoint into it's own test.
Now, OneTimeSetUp is called, it logs in, and calls the endpoint, stores the result, and all the tests fire, testing their little bit.
The problem is, logging in takes time, and there is no logical reason why all the separate tests couldn't just use the same login details. Is there any way of further sub-dividing tests/ adding extra levels of test? It would be great if we could get a test result that looks like this
ApiTests <--- shared sign-in at this level
- Endpoint 1 <--- call the endpoint at this level
- Field 1 \
- Field 2 --- individual test results here
- Field 3 /
- Endpoint 2 <--- call the endpoint at this level
- Field a \
- Field b --- individual test results here
- Field c /
You can group your test classes into the same namespaces and then add an additional class that is marked with the SetupFixture attribute. This will run the initialization code only once per namespace. (Not to be confused with the "TestFixtureSetUp" attribute, which is marked obsolete since NUnit v3. Thanks Charlie for your comment, I initially mixed it up.)
https://github.com/nunit/docs/wiki/SetUpFixture-Attribute
Code sample (as always, you are free to put each class into a separate code file):
using System.Diagnostics;
using NUnit.Framework;
namespace Test
{
[SetUpFixture]
public class SharedActions
{
[OneTimeSetUp]
public void SharedSignIn()
{
Debug.WriteLine("Signed in.");
}
[OneTimeTearDown]
public void SharedSignOut()
{
Debug.WriteLine("Signed out.");
}
}
[TestFixture]
public class FirstEndpointTests
{
[Test]
public void FirstEndpointTest()
{
Debug.WriteLine("Test for Endpoint A");
}
}
[TestFixture]
public class SecondEndpointTests
{
[Test]
public void SecondEndpointTest()
{
Debug.WriteLine("Test for Endpoint B");
}
}
}
When you "debug all" tests, the following output will appear in the debug window:
Signed in.
Test for Endpoint A
Test for Endpoint B
Signed out.
Here is one possible way of achieving this.
If you have a common base class (as it sounds from your description), you can create a protected lazy to get your token as per the example below
public class ApiTestsBase
{
protected static Lazy<string> TokenLazy = new Lazy<string>(() =>
{
// Log in and get your API token
Console.WriteLine("Logging into API to get token. You should only see this message on the first test that runs");
return "DEADBEEF";
});
}
[TestFixture]
public class EndpointATests : ApiTestsBase
{
private string GetResultFromEndPoint()
{
// Call endpoint with token from TokenLazy.Value
Console.WriteLine($"Calling EndpointA with token {TokenLazy.Value}");
return "PayloadA";
}
[Test]
public void Test1()
{
var payload = this.GetResultFromEndPoint();
// Assert things about payload
}
}
[TestFixture]
public class EndpointBTests : ApiTestsBase
{
private string GetResultFromEndPoint()
{
// Call endpoint with token from TokenLazy.Value
Console.WriteLine($"Calling EndpointB with token {TokenLazy.Value}");
return "PayloadB";
}
[Test]
public void Test1()
{
var payload = this.GetResultFromEndPoint();
// Assert things about payload
}
}
Now I am using string types, but you can use whatever request, response and token types are relevant to your situation. I suspect that you could also with a bit of creativity move the GetResultFromEndPoint call to the base class and use abstract methods or properties to fill in the endpoint specific detail, but you have not shared enough code for me to try that.
The magic is in the static keyword which means you will only have one instance per app domain. The Lazy simply defers creation until its first reference. It gets a little more complex if your test cases run for a long time because you will need to deal with token renewal, but it can still be achieved in a similar way using a singleton class that periodically re authenticates if token age > x. A singleton object can also be used in place of the static in the above example if you do not have a common base class for your fixtures.

Checking Role-based permissions on all actions in centralized or clean way in .Net applications

I am trying to avoid the conventional:
if(!user.HasPermission(Actions.UpdateRecord))
{
// code to update record
}
on a large number of permissions all over my application.
I am looking for a means of checking for permissions in an effective and (if possible) elegant manner.
In this case there are multiple actions within each permission.
How about putting a decorator on your dataaccess objects. The decorator pattern is very useful for doing things like handling permissions. Your dataAccess layer can do just data access and then your decorate those classes with something that handles permissions and permissions only.
It is very elegant...
http://en.wikipedia.org/wiki/Decorator_pattern
There are a lot of ways to do this. The important thing is that you want to encapsulate the concern of checking permissions. One way to do this is with a strategy pattern. Encapsulate the action in a class, and get the class via a factory method. The factory can do the security check, and return a different strategy for disallowed actions.
For example:
public abstract class SecureAction
{
public void PerformAction();
}
public class UpdateRecords : SecureAction
{
public void PerformAction()
{
//code to do the update
}
}
public class DoesNotHavePermissionAction : SecureAction
{
public void PerformAction()
{
//code to handle missing permissions
}
}
public class SecureActionFactory
{
public void GetUpdateRecordsAction(User user)
{
if(user.HasPermissions(Actions.UpdateRecord)) {return new UpdateRecordsAction();}
return new DoesNotHavePermissionAction();
}
}

Categories