Call API from Python

import requests
import urllib3

# suppress the HTTPS warnings in terminal
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

# BEGIN
session = requests.Session()
session.verify = False

url = "https://some.url.com?param1=something&param2=something"
headers = {'content-type': 'application/json', 'Accept-Charset': 'UTF-8'}

# call the HTTP endpoint
httpResult = session.get(url, headers=headers)
print(httpResult.text)

# some extra details
elapsedSeconds = httpResult.elapsed.total_seconds()
statusCode = httpResult.status_code

Get user credentials securely in PowerShell

#Get user credentials securely
Try {
	$credentials = Get-Credential "$env:username"
}
Catch {
	$log += "`n- " + $_.Exception.Message
	Output-Result
}

#Get current domain to use for authentication. ADSI = Active Directory
$currentDomain = "LDAP://" + ([ADSI]"").distinguishedName

#Authenticate
$activeDirectoryEntry = New-Object System.DirectoryServices.DirectoryEntry($currentDomain,$credentials.GetNetworkCredential().UserName,$credentials.GetNetworkCredential().Password)
if ($activeDirectoryEntry.name -eq $null)
{
    $log += "`n- Failed to authenticate that username and password."
    Output-Result	
} else {
    $log += "`n- Authentication was successful."
}

#Display Results
$log = "Results:"
function Output-Result {
    [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") > null
    $oReturn=[System.Windows.Forms.Messagebox]::Show($log)
    Break
}

Startup.cs example for .NET Core API w/ Swagger

using Swashbuckle.AspNetCore.Swagger;

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvcCore().AddApiExplorer();
    services.AddSwaggerGen();
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
    });

    services.AddTransient<ISomeInterface, SomeDependency>();
}



// -----------------

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseSwagger();
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API");
        });
    }
    app.UseMvc();
}

How to mock IConfiguration

var configuration = new Mock<IConfiguration>();
 
var configurationSection = new Mock<IConfigurationSection>();
configurationSection.Setup(a => a.Value).Returns("testvalue");
 
configuration.Setup(a => a.GetSection("TestValueKey")).Returns(configurationSection.Object);   

Source

.NET C# Factory Pattern Using Reflection

// class implements IModelFactory -> IFactoryModel CreateInstance(string modelName)

private Dictionary<string, Type> _availableTypes;

public ModelFactory() {
    LoadTypes();
}

public IFactoryModel CreateInstance(string modelName)
{
    Type t = GetTypeToCreate(modelName);
    //NOTE: handle null here
    return Activator.CreateInstance(t) as IFactoryModel;
}

private void LoadTypes() 
{
    _availableTypes = new Dictionary<string, Type>();
    Type[] assemblyTypes = Assembly.GetExecutingAssembly().GetTypes();

    assemblyTypes.Where(x => x.GetInterface(typeof(IFactoryModel).ToString()) != null).ToList()
        .ForEach(y => _availableTypes.add(y.Name.ToLower(), y));
}

private IFactoryModel GetTypeToCreate(string name)
{
    _availableTypes.TryGetValue(name, out Type t);
    return t ?? null;
}

source:
https://app.pluralsight.com/library/courses/patterns-library/table-of-contents

Dependency Injection With Multiple Implementations Of The Same Interface

public void ConfigureServices(IServiceCollection services)
{
  services.AddTransient<AddOperationRepository>();
  services.AddTransient<SubtractOperationRepository>();
  services.AddTransient<MultiplyOperationRepository>();
  services.AddTransient<DivideOperationRepository>();
  services.AddTransient<Func<MathOperationType, IMathOperationRepository>>(serviceProvider => key =>
  {
    switch (key)
    {
      case MathOperationType.Add:
        return serviceProvider.GetService<AddOperationRepository>();
      case MathOperationType.Subtract:
        return serviceProvider.GetService<SubtractOperationRepository>();
      case MathOperationType.Multiply:
        return serviceProvider.GetService<MultiplyOperationRepository>();
      case MathOperationType.Divide:
        return serviceProvider.GetService<DivideOperationRepository>();
      default:
        throw new KeyNotFoundException();
    }
  });
  . . .
}

...
public class ValuesController : ControllerBase  
{  
  private Func<MathOperationType, IMathOperationRepository> _mathRepositoryDelegate;  
  public ValuesController(Func<MathOperationType, IMathOperationRepository> mathRepositoryDelegate)  
  {  
    _mathRepositoryDelegate = mathRepositoryDelegate;  
  }  
  [HttpPost]  
  public ActionResult<OperationResult> Post([FromBody] OperationRequest opRequest)  
  {  
    IMathOperationRepository mathRepository = _mathRepositoryDelegate(opRequest.OperationType);  
    OperationResult opResult = mathRepository.PerformOperation(opRequest);  
    return new ObjectResult(opResult);  
  }  
} 

Source:
https://www.c-sharpcorner.com/article/dependency-injection-with-multiple-implementations-of-the-same-interface/