Thursday, April 30, 2020

How do I get all URL line variables in .NET Core 3+ including those which start with a dollar sign?

List<string[]> queryStringChunks = new List<string[]>(){};
string queryString = Request.QueryString.ToString();
if (queryString != null && queryString.Length > 1)
{
   queryString = queryString.Substring(1, queryString.Length - 1);
   foreach (var chunk in queryString.Split('&'))
   {
      queryStringChunks.Add(chunk.Split('='));
   }
}

Wednesday, April 29, 2020

How may I pass the username and password to a GET with Postman?

At Headers, make two variables for Username and Password and have each just pass on a string. Back at Authorization, set up NTLM Authentication [Beta] and have the Username pass {{Username}} and the Password pass {{Password}} as well.

How do I grab the latest, most immediate user from .NET Core?

This guy has a pretty good cheat sheet. Inside ConfigureServices in Startup.cs put:

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

 
 

The rest of this code is Controller-flavored. Have a private field at a given Controller.

private readonly IHttpContextAccessor _httpContextAccessor;

 
 

At the constructor:

public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options,
      IHttpContextAccessor httpContextAccessor) : base(options)
{
   _httpContextAccessor = httpContextAccessor;

 
 

When you use it, loop in...

using System.Security.Claims;

 
 

...and then have:

var userId =
      _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;

'base.Channel' threw an exception of type 'System.ServiceModel.CommunicationObjectFaultedException'

Something is sick with a .wsdl/SOAP web service, causing this error. MTOM is Message Transmission Optimization Mechanism. It sends binary data. In SOAP/XML, WS-* or WS-star will include WS-Policy, WS-Addressing, WS-Trust, WS-SecureConversation, WS-Transaction, etc. WS for web services, get it? Duplex channels describe the use of two frequency channels. A talks to B while B talks back to A on a seperate channel. The following in ConfigureServices in Startup.cs will allow IIS to always send credentials with web requests.

services.Configure<IISServerOptions>(options =>
{
   options.AutomaticAuthentication = false;
});

 
 

For Kestrel:

services.AddAuthentication(NegotiateDefaults.AuthenticationScheme).AddNegotiate();

HTTP.sys

It is another way to run a Visual Studio project. sys for system?

Tuesday, April 28, 2020

Don't expect Thread.CurrentPrincipal.Identity.Name or even Thread.CurrentPrincipal to work in .NET Core.

See: this

Use System.DirectoryServices.AccountManagement to verify the password of a user in .NET Core.

using (PrincipalContext pc = new PrincipalContext(ContextType.Domain))
{
   bool isValid = pc.ValidateCredentials(username, password);
   if (isValid)
   {

more on MOQ

Mock.Of is a way to prep a dependency to be jammed into a class (to line up with an interface) and Mock.Loose is a way to set the mocking approach to "not strict" so to speak. There is also a Mock.Get too!

Monday, April 27, 2020

System.DirectoryServices.AccountManagement beyond System.DirectoryServices.ActiveDirectory

using(var ServerContext = new PrincipalContext(ContextType.Domain))
{
   GroupPrincipal outerGroupPrincipal = new GroupPrincipal(ServerContext, alt);
   PrincipalSearcher principalSearcher = new PrincipalSearcher(outerGroupPrincipal);
   foreach (var found in principalSearcher.FindAll())
   {
      GroupPrincipal innerGroupPrincipal = found as GroupPrincipal;
      if (innerGroupPrincipal != null)
      {
         foreach (Principal p in innerGroupPrincipal.GetMembers())
         {
            var hello = "goodbye";
         }
      }
   }
}

Check to see if .FindOne just created a null object in Active Directory stuff in C#!

Following up on this...

SearchResult searchResult = directorySearcher.FindOne();
if (searchResult != null)
{

Novell

These guys had the old way to do active directory stuff.

app.UseAuthentication();

See: this This goes in Startup.cs and this is for always and not sometimes. SPN stands for Service Principal Name(s) in this circumstance. It is part of the .NET Core approach.

Where do I get Active Directory Authentication Library (a.k.a. ADAL) for Active Directory authentication?

At: https://github.com/AzureAD/azure-activedirectory-library-for-js

Why can't I debug in Visual Studio via Postman?

You can! If you set a breakpoint in Program.cs or Startup.cs, these breakpoints will only be hit when you first hit the application and not every single time.

Sunday, April 26, 2020

Friday, April 24, 2020

How do I make Program.cs use Kestrel in modern .NET Core 3+ times?

My code:

using System.Diagnostics.CodeAnalysis;
using Autofac.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
namespace Yin
{
   public class Program
   {
      [ExcludeFromCodeCoverage]
      public static void Main(string[] args)
      {
         CreateHostBuilder(args).Build().Run();
      }
      
      [ExcludeFromCodeCoverage]
      public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
            .UseServiceProviderFactory(new AutofacServiceProviderFactory())
            .ConfigureWebHostDefaults(webBuilder =>
            {
               webBuilder.UseStartup<Startup>().UseKestrel();
            });
   }
}

 
 

A coworker's code:

namespace Yin
{
   using System;
   using System.Diagnostics.CodeAnalysis;
   using Yang;
   using Microsoft.AspNetCore;
   using Microsoft.AspNetCore.Hosting;
   using Serilog;
   
   [ExcludeFromCodeCoverage]
   public class Program
   {
      [ExcludeFromCodeCoverage]
      public static int Main(string[] args)
      {
         Logger.CreateLogger();
         
         try
         {
            Log.Information("{message}", "Starting web host: FnDocs.Web.Api");
            CreateWebHostBuilder(args).Build().Run();
            return 0;
         }
         catch (Exception ex)
         {
            Log.Error(ex, "Host terminated unexpectedly{ex}");
            return 1;
         }
      }
      
      [ExcludeFromCodeCoverage]
      public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .UseKestrel()
            .UseSerilog();
   }
}

Request.Properties in .NET Framework becomes Request.RouteValues in .NET Core???

Request.Properties.Add("FileName", document.FileName);

 
 

...becomes...

Request.RouteValues.Add("FileName", document.FileName);

What's wrong with my port to .NET Core? The .dlls of supporting projects?

Could be. I ran into this in the last two days. It was pointed out to me that Framework projects cannot go into Kubernetes and, hence, I started porting all Framework projects to .NET Core. When I referenced the random, in-house projects back into my main application, I accidentally referenced some of the wrong versions, etc. Lame!

Thursday, April 23, 2020

List vs LinkedList

This suggests: "The difference is the internal data structure used to store the objects. An ArrayList will use a system array (like Object[]) and resize it when needed. On the other hand, a LinkedList will use an object that contains the data and a pointer to the next and previous objects in the list." ...and yes, ArrayList is List. Юлия Данилова (Yulia Danilova) suggests stuff like:

LinkedList<string> linked = new LinkedList<string>(){};
linked.AddLast("baz");
linked.AddLast("qux");
linked.AddFirst("foo");
LinkedListNode<string> node = linked.Find("foo");
linked.AddAfter(node, "bar");

Wednesday, April 22, 2020

Mug Life

For iPhone or Android, it will allow you to make an existing photo talk and freak out some. It is not free.

Tuesday, April 21, 2020

Constructor on type 'meh' not found.

This stems from using System.Activator.CreateInstance which can just pick the wrong constructor for a class. Tricky stuff! Remember if you want to call a type with three parameters at the constructor that you must pass four constructors to the CreateInstance and the CreateInstance will use the first as the type to create. Also, if there are many constructors, the constructor with the most variables wins!

Add a .wsdl/SOAP web service in .NET Core 3+ and Visual Studio 2019.

right-click on the project and pick: Add > Connected Service

magical mystery folder in Visual Studio 2019

In the .NET Framework stuff you may jam into the files a nonexistent folder like so by making this change to the .csproj file:

<ItemGroup>
   <Folder Include="Diagnostics\DocSolLogger\" />
</ItemGroup>

 
 

In .NET Core there should be only one ItemGroup and you should just put this inside of it:

<Folder Include="Diagnostics\DocSolLogger\" />

 
 

I get a red X on the folder in .NET Core.

Sunday, April 19, 2020

Friday, April 17, 2020

An extension method for HttpRequestMessage (Request in a Controller) in .NET Framework becomes an extension method for HttpRequest (Request in a Controller) in .NET Core.

internal static string GetComponentIdentifier(this HttpRequestMessage request)
{
   return request.GetHeader(HttpKeys.ComponentIdentifier);
}

 
 

What is above becomes:

internal static string GetComponentIdentifier(this HttpRequest request, StringValues x)
{
   Boolean isLegit = request.Headers.TryGetValue("ComponentIdentifier", out x);
   return x;
}

translating MVC Framework to MVC Core

Alright Request.RequestUri.AbsoluteUri.ToLower() becomes Request.Path.ToString() while Request.RequestUri.Host becomes Request.Host.Host additionally. The first bit fishes out the chunk of the route after the domain name and the second bit gets the domain name or localhost or whatever. The port is not included. Request.Host.Port digs out the port.

 
 

Addendum 4/24/2020: Request.Path.ToString() should really be Request.Path.ToString().ToLower() you know?

A lot of the new .NET Core 3.1.4 routing tricks do not hydrate a route at IRouteBuilder off of IApplicationBuilder.

app.UseEndpoints(endpoints =>
{
   endpoints.MapControllerRoute(

 
 

...won't work! Fish out the route like so:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Routing;
namespace Cms.Web.Services.Models
{
   public class DeRouting
   {
      IApplicationBuilder app;
      public DeRouting(IApplicationBuilder app)
      {
         this.app = app;
      }
      
      public IRouteBuilder GetRoutes()
      {
         IRouteBuilder routes = new RouteBuilder(app);
         routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");
         return routes;
      }
   }
}

Thursday, April 16, 2020

Have more than one route in .NET Core 3.1.4.

You see how the first is the first criteria to fail against, right?

app.UseEndpoints(endpoints =>
{
   endpoints.MapControllerRoute(name: "default", pattern: "api/[controller]");
   endpoints.MapControllerRoute(name: "failover", pattern: "*", defaults: new { controller =
         "FalloverFailsafe", action = "Get" });
});

How do I set the time zone in a .NET Core 3.1.4 application?

In Startup.cs you have to use .UseMvc before .UseEndpoints like you were still in the 2.0 stuff like so in Configure:

app.UseMvc(m => m.SetTimeZoneInfo(TimeZoneInfo.Utc));
app.UseEndpoints(endpoints =>
{

 
 

Set the EnableEndpointRouting to false upstream in ConfigureServices to keep this from tanking the application outright.

services.AddMvc(options =>
{
   options.Filters.Add(new BubbleUpExceptions());
   options.EnableEndpointRouting = false;

PPP in Agile PPP stands for Principles, Patterns, and Practices.

meh

The ECS of Amazon ECS stands for Elastic Container Service.

It is a "fully managed container orchestration service" per this.

Microsoft.AspNetCore.OData installs sickly in .NET Core 3.1.4.

For me the problem was a mishmash between Microsoft.AspNetCore.OData and the earlier Microsoft.AspNet.OData. I uninstalled everything (both things) and then at the NuGet command line gave:

Install-Package Microsoft.AspNetCore.OData -Version 7.3.0

Wednesday, April 15, 2020

ASR is automatic speech recognition.

It is machine learning stuff.

JsonException: A possible object cycle was detected which is not supported. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 32.

Import Microsoft.AspNetCore.Mvc.NewtonsoftJson into Startup.cs and then make a stitch like so:

services.AddMvc(options =>
{
   options.Filters.Add(new ValidateComponentIdentifier());
   options.Filters.Add(new BubbleUpExceptions());
}).AddNewtonsoftJson(options => options.SerializerSettings.ReferenceLoopHandling =
      Newtonsoft.Json.ReferenceLoopHandling.Ignore);

 
 

It is the last line above (well, the last two really) that is most important.

Find out what controller is being found with OnActionExecuting in .NET Core 3.1.4.

This follows up on this and explains why I need a Controller for every possible route. Without a Controller to find, this method does not get called.

using System;
using Microsoft.AspNetCore.Mvc.Filters;
namespace Cms.Web.Services.Filters
{
   public class ValidateComponentIdentifier : IActionFilter
   {
      public void OnActionExecuting(ActionExecutingContext context)
      {
         string name = (string)context.RouteData.Values["Controller"];
         if (name == "FalloverFailsafe")
         {
            throw new Exception("There is no endpoint with the name specified.");
         }
      }
      
      public void OnActionExecuted(ActionExecutedContext context)
      {
      }
   }
}

 
 

Loop this in as you might BubbleUpExceptions.

Make a .NET Core 3.1.4 Controller catch anything!

using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
namespace NotIt.Controllers
{
   [ApiController]
   [Route("/{a?}")]
   [Route("/{b?}/{c?}")]
   [Route("/{d?}/{e?}/{f?}")]
   [Route("/{g?}/{h?}/{i?}/{j?}")]
   [Route("/{k?}/{l?}/{m?}/{n?}/{o?}")]
   [Route("/{p?}/{q?}/{r?}/{s?}/{t?}/{u?}")]
   public class FalloverFailsafeController : ControllerBase
   {
      [HttpGet]
      public IEnumerable<string> Get()
      {
         IEnumerable<string> error = new string[] {"not", "it"};
         return error;
      }
   }
}

 
 

I changed the end of Configure in Startup.cs like so:

app.UseEndpoints(endpoints =>
{
   endpoints.MapControllerRoute(name: "fallover", pattern: "*", defaults: new { controller =
      "FalloverFailsafe", action="Get" });
});

Use (allow) specific http verbs in .NET Core 3.

In Configure in Startup.cs:

app.UseCors(builder => builder.AllowAnyOrigin().WithMethods("GET", "HEAD", "POST",
      "DEBUG", "PUT", "DELETE", "PATCH", "OPTIONS").AllowAnyHeader());

Debug Failsafe

It stops and starts remote debugging sessions. DEBUG is not a standard http verb. It is its own fallover animal that really just shows up in C# stuff.

Tuesday, April 14, 2020

How to switch a .NET Core project over to Windows Authentication after it was made without it.

Open launchSettings.json and set windowsAuthentication to true and anonymousAuthentication to false.

Force not https traffic to fall over to being https traffic in .NET Core.

In the Configure method in Startup.cs start off with:

if (env.IsDevelopment())
{
   app.UseDeveloperExceptionPage();
}
else
{
   app.UseHttpsRedirection();
}

 
 

In appsettings.json have a https_port property with a number in it!

It's an extension method for an exception in C# to drill back to the root of what is wrong.

using System;
namespace MyStuff.MoreStuff
{
   public static class ExceptionExtensions
   {
      public static Exception GetOriginalException(this Exception ex)
      {
         if (ex.InnerException == null)
         {
            return ex;
         }
         return ex.InnerException.GetOriginalException();
      }
   }
}

Don't wrap nested stuff to yank from appsettings.json in a not null safeguard like this.

IConfiguration configuration = new ConfigurationBuilder().AddJsonFile(
      "appsettings.json", optional: true, reloadOnChange: true).Build();
if (configuration["loggingConfiguration"] != null)
{

.UseMvc in .NET Core with specific routes

This has this example and a bit more.

app.UseMvc(routes =>
{
   routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}");
});

 
 

Honestly, this is probably the .NET Core 2.0 way of doing things per this. In modern times (.NET 3.1.4) we have stuff like so instead:

app.UseEndpoints(endpoints =>
{
   endpoints.MapControllers();
});

Hydrate a Transient in .NET Core from something returned from a method.

Following up on this, it's more of the same breakout.

var logger = new SerilogFactory().CreateLogger();
services.AddTransient<ILogger>(x => logger);

Monday, April 13, 2020

Xunit.Gherkin.Quick is less forgiving than some BDD testing frameworks.

Two back to back Givens must be a Given followed by an And and not merely two Givens.

[TestCategory("Multivalue")]

This is old markup from Microsoft.VisualStudio.TestTools.UnitTesting which I hope I may just throw away. What did it do? Associate some tests together at the reporting maybe.

Friday, April 10, 2020

Assert.IsInstanceOfType becomes Assert.IsType in Xunit.

The two assignments are the other way around also, so foo and typeof(Foo) become typeof(Foo) and foo instead.

SuppressMessage attribute at a test class to NOT run a test???

Nay! ...to have it not show up in the metrics!

[SuppressMessage("Maintainability", "Missing XML Comments", Justification = "XML
      comments not needed for test")]

Did you know that you may unit test some internal items in another project in C#?

I am just stumbling upon this today. There are some wire-ups which work just fine in a unit test which revolt completely when I try to tease them out to other files. Yikes!

ctors means constructors

Also, look... you may copy and paste some characters that do stupid stuff. (unrelated)

Xunit fixtures

I am migrating stuff using .NET Framework Gherkin tests with Microsoft.VisualStudio.TestTools.UnitTesting and TechTalk.SpecFlow to .NET Core and Xunit and Xunit.Gherkin.Quick. [BeforeScenario] needed replacement with an Xunit fixture. This is basically a before-each-test trick. It looks like this:

using MyApp.MyStuff;
using System;
using Moq;
namespace MyApp.MyStuff.Tests
{
   public class MyFixture : IDisposable
   {
      public Mock<Foo> _commit { get; private set; }
      
      public MyFixture()
      {
         _commit = new Mock<Foo>();
      }
      
      public void Dispose()
      {
      }
   }
}

 
 

I do not know that IDisposable is required. I saw it online in an example there that did database stuff honestly. Anyhow, to use the fixture in my test, I now need to give my test a constructor that did not exist like so:

private Mock<Foo> _commit;
public MyTest(MyFixture fixture)
{
   _commit = fixture._commit;
}

 
 

Oh, [BeforeFeature] is also a part of the old stuff.

 
 

Addendum 4/13/2020: I could not get this to work today. Per this, perhaps I need to inherit from IClassFixture<MyFixture> instead of Feature

IReadOnlyList

In C# this is like List only restricted. You have to dig stuff out with the index exclusively.

Thursday, April 9, 2020

MultipartMemoryStreamProvider in .NET Core does not exist.

You can/may have System.Net.Http in .NET Core but, per this, MultipartMemoryStreamProvider for managing multipart data (files) must be replaced with IFormFile in modern times. HttpMessageContent is the same as is .ReadAsMultipartAsync() too.

HttpClientHandler in C#

HttpClientHandler handler = new HttpClientHandler();
handler.Credentials = new NetworkCredential();
HttpClient client = new HttpClient(handler);

 
 

Addendum 4/9/2020: handler.UseDefaultCredentials = true; would be a way to jam in default credentials.

Wednesday, April 8, 2020

@Inject(PLATFORM_ID) in Angular 5

Assuming this...

import { PLATFORM_ID } from "@angular/core";
import { isPlatformBrowser } from "@angular/common";

 
 

...then page 464 of "ASP.NET Core 2 and Angular 5" by Valerio De Sanctis suggests you could have:

constructor (@Inject(PLATFORM_ID) private x: any) {
   if (!isPlatformBrowser(x)) {

 
 

isPlatformBrowser just returns true of false.

DES stands for Data Encryption Standard.

Wikipedia says: "...Triple DES (3DES or TDES), officially the Triple Data Encryption Algorithm (TDEA or Triple DEA), is a symmetric-key block cipher..."

Xamarin.Mac

Stolen from online: "Xamarin.Mac exposes the complete macOS SDK for .NET developers to build native Mac applications using C#."

When making an appsettings.json for a .NET Core xunit test project in Visual Studio 2019...

In the properties pane set the "Copy to Output Directory" to "Copy if newer" to allow the file to be seen.

Tuesday, April 7, 2020

Xunit.Gherkin.Quick

Get it here or from NuGet for an xunit test project in .NET Core. Decorate classes with:

[FeatureFile("./Mandate.feature")]

 
 

Methods with...

[When(@"A mandate check of condition ""(.*)"" is performed")]

 
 

...and:

[Then(@"an argument exception shall be thrown")]

 
 

Mandate.feature is a .txt file with a bunch of scenarios in it.

 
 

Addendum 4/8/2020: What is more...

  1. The class that runs the tests should inheirt from Feature!
  2. The .feature files need the "Copy to Output Directory" setting set to "Copy if newer" at the Properties pane.
  3. [Given(@"a configured HEncoder")] is another decorator.
  4. [And(@"I chose (\d+) as second number")] after Given is legit too.
  5. Do NOT have Utf8Json and Gherkin installed. One of these two causes problems.
  6. If the testing class and the .feature are named the same thing and the .feature is in the root of the project, you do not need the FeatureFile attribute.

Utf8Json

It is a JSON serializer. Go get it from NuGet.

BoDi

It is a simple and embeddable IoC container. See: this

more dealing with strangeness pulled from dotPeek

keyedService.get_ServiceKey() becomes keyedService.ServiceKey while .op_Equality and .op_Inequality suggest == and != comparisons

base..ctor();

When you use JetBrains dotPeek to cast CLR to a C# class backwardsly, you may see this inside a constructor like so:

namespace Could.Be.Anything
{
   public sealed class LessAbstract : MoreAbstract
   {
      public LessAbstract()
      {
         base..ctor();
      }
   }
}

 
 

All that means is...

namespace Could.Be.Anything
{
   public sealed class LessAbstract : MoreAbstract
   {
      public LessAbstract() : base()
      {
      }
   }
}

.resx versus .resources

I found a thread at Stack Overflow which suggests the .resx is uncompiled and the .resources is compiled.

Monday, April 6, 2020

printfn

It's F# for: "print this!"

LemonStand was a Canadian e-commerce entity.

It closed down in 2019.

From Cookiecutter...

You may see this when attempting to add something at the Solution Explorer in Visual Studio 2019. It allows you to splash in code from templates.

Kubernetes Ingress

Stolen from a Googling: "In Kubernetes, an Ingress is an object that allows access to your Kubernetes services from outside the Kubernetes cluster. You configure access by creating a collection of rules that define which inbound connections reach which services. This lets you consolidate your routing rules into a single resource."

How to I fill in the ConfigurationModule for namespace Autofac.Extras.Configuration in .NET Core?

Following up on this, how do we port this?

namespace Autofac.Extras.Configuration
{
   public sealed class ConfigurationModule : Module
   {
      protected override void Load(ContainerBuilder builder);
   }
}

 
 

We could have something like so but it is a guess in the dark honestly.

using Autofac;
namespace Anything.You.Like.Here
{
   public sealed class ConfigurationModule : Module
   {
      protected override void Load(ContainerBuilder builder) { }
   }
}

 
 

Addendum 4/7/2020: After some thought and some use of dotPeek, I think we should instead have:

using Autofac.Core;
namespace Autofac.Extras.Configuration
{
   public sealed class ConfigurationModule : Module
   {
      protected void Load(ContainerBuilder builder)
      {
         RegistrationExtensions.RegisterInstance(builder, (IRegistrationSource)new
               ConfigurationRegistrationSource());
      }
   }
}

 
 

That part is pretty easy, but it opens the door to...

using Autofac.Builder;
using Autofac.Core;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.Linq;
using System.Reflection;
using Microsoft.Extensions.Configuration;
using ConfigurationSection = System.Configuration.ConfigurationSection;
namespace Autofac.Extras.Configuration
{
   internal class ConfigurationRegistrationSource : IRegistrationSource
   {
      public bool IsAdapterForIndividualComponents
      {
         get
         {
            return false;
         }
      }
      
      public IEnumerable<IComponentRegistration> RegistrationsFor(Service service,
            Func<Service, IEnumerable<IComponentRegistration>> registrationAccessor)
      {
         if (!(service is IServiceWithType iserviceWithType)) return
               Enumerable.Empty<IComponentRegistration>();
         Type type = (Type)iserviceWithType.ServiceType;
         if (!typeof(ConfigurationSection).IsAssignableFrom(type) &&
               !typeof(ConfigurationSectionGroup).IsAssignableFrom(type)) return
               Enumerable.Empty<IComponentRegistration>();
         KeyedService keyedService = service as KeyedService;
         string name = keyedService == null ? (string)null :
               Convert.ToString(keyedService.ServiceKey,
               (IFormatProvider)CultureInfo.InvariantCulture);
         if (string.IsNullOrEmpty(name)) return
               Enumerable.Empty<IComponentRegistration>();
         IList<string> stack = ConfigurationRegistrationSource.RecurseSectionNames(type,
               name);
         IRegistrationBuilder<object, SimpleActivatorData, SingleRegistrationStyle>
               iregistrationBuilder1 = RegistrationBuilder.ForDelegate((Type)type,
               (Func<IComponentContext, IEnumerable<Parameter>, object>)((c, p) =>
               ConfigurationRegistrationSource.SectionResolver(type, stack)));
         IRegistrationBuilder<object, SimpleActivatorData, SingleRegistrationStyle>
               iregistrationBuilder2;
         if (name != null)
            iregistrationBuilder2 = iregistrationBuilder1.Named(name, (Type)type);
         else
            iregistrationBuilder2 = iregistrationBuilder1.As((Type[])new Type[1] { type });
         return (IEnumerable<IComponentRegistration>)new IComponentRegistration[1] {
               RegistrationBuilder.CreateRegistration<object, SimpleActivatorData,
               SingleRegistrationStyle>(iregistrationBuilder2) };
      }
      
      private static object SectionResolver(Type type, IList<string> stack)
      {
         IConfiguration config = new ConfigurationBuilder().AddJsonFile("appsettings.json",
               optional: true, reloadOnChange: true).Build();
         return (object) config.GetSection(type.ToString());
      }
      
      private static IList<string> RecurseSectionNames(Type type, string name)
      {
         DefaultSectionGroupAttribute customAttribute =
               type.GetCustomAttribute<DefaultSectionGroupAttribute>(false);
         IList<string> stringList = customAttribute == null ? (IList<string>)new List<string>() :
               ConfigurationRegistrationSource.RecurseSectionNames(customAttribute
               .ParentType, customAttribute.ParentName);
         stringList.Add(name ?? ConfigurationRegistrationSource.GetDefaultName(type));
         return stringList;
      }
      
      private static string GetDefaultName(Type type)
      {
         DefaultNameAttribute customAttribute =
               type.GetCustomAttribute<DefaultNameAttribute>(false);
         if (customAttribute == null) throw new
               DependencyResolutionException("ConfigurationSection type " + (object)type +
               " does not have Default Name Attribute");
         return customAttribute.Name;
      }
   }
}

HPA in Rancher stands for Horizontal Pod Autoscaler.

This allows for autoscales up and down of the amount of services (containers???) running.

ECM could be enterprise content management.

Items managed have a little time line (two words for the past) of history.

Sunday, April 5, 2020

C# XML Documentation Comments

/// <summary>
/// This doubles <paramref name="number" /> and returns it.
/// </summary>
/// <param name="number">any integer</param>
/// <returns>double the inbound value</returns>
public int Double(int number)
{

 
 

Addendum 4/6/2020: If decorating a class instead of a method inside a class, you would maybe just have the summary.

 
 

Addendum 4/10/2020: You could have a <remarks> tag after summary at the top of the file. You may just want a summary at a constructor.

Friday, April 3, 2020

Cast a Guid to a string in C# while handing in a conditional magic argument.

Guid guid = Guid.NewGuid();
string go = guid.ToString();
string d = guid.ToString("D");
string n = guid.ToString("N");
string b = guid.ToString("B");
string p = guid.ToString("P");
string x = guid.ToString("X");

 
 

146aa746-e433-4540-b2cb-9dac7e4a34e4 is the assignment for lines two and three. Then 146aa746e4334540b2cb9dac7e4a34e4 and then {146aa746-e433-4540-b2cb-9dac7e4a34e4} followed by (146aa746-e433-4540-b2cb-9dac7e4a34e4) and finally {0x146aa746,0xe433,0x4540,{0xb2,0xcb,0x9d,0xac,0x7e,0x4a,0x34,0xe4}} is last. The second to last chapter of "ASP.NET Core 2 and Angular 5" by Valerio De Sanctis had this nuget of wisdom.

Here are some .NET Core attributes for a Controller.

[AllowAnonymous]
[ApiController]
[Route("api/[controller]")]

 
 

These sit right above the class declaration that inheirts from Controller. The first and the last speak for themselves. The middlemost suggests that all of the actions you will find inside will be tied to HTTP verbs.

A .NET Framework ApiController just becomes a Controller in .NET Core.

Request.GetQueryNameValuePairs() is instead in .NET Core Request.Query.ToDictionary(q => q.Key, q => q.Value) and along similar lines you could also have something like so:

public IList<KeyValuePair<string, string>> GetQueryString(HttpRequestMessage x)
{
   Dictionary<string, string> y = x.Properties.ToDictionary(q => q.Key,
         q => q.Value.ToString());
   return y.ToList();
}

 
 

Also: IHttpActionResult became IActionResult and there is no more HttpConfiguration.

EntityConnection and EntityException are not in .NET Core.

You may want to reimport System.Data.SqlClient to kick SqlConnection awake, but these other older means for interfacing with Entity Framework gunk in the .NET Framework machinery are gone. Both SqlConnection and EntityConnection inheirt from DbConnection while SqlConnection is also an ICloneable (supports cloning, which creates a new instance of a class with the same value as an existing instance).

When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions.

This is the magic behind .GetBaseException() as shown here:

catch (MagicException ex)
{
   throw ex.GetBaseException();
}

Kubernetes containers will not run .NET Framework code.

If you are porting from .NET Framework to .NET Core everything must at least make it to .NET Standard to be acceptable in that environment.

PdbNavigator

It is JetBrains ReSharper gunk for figuring out what is what in libraries. See this for PDB.

DiagnosticListener

Per this: Provides an implementation of the abstract DiagnosticSource class that represents a named place to which a source sends its information (events).

How do I support the DefaultName attribute of Autofac.Extras.Configuration when porting code from .NET Framework to .NET Core?

I don't know yet. When I drill in their, decompiled with JetBrains decompiler, the attribute reads like so:

using System;
namespace Autofac.Extras.Configuration
{
   [AttributeUsage(AttributeTargets.Class)]
   public sealed class DefaultNameAttribute : Attribute
   {
      public DefaultNameAttribute(string name);
      public string Name { get; private set; }
   }
}

 
 

Does that mean I may just recreate it like this?

using System;
namespace Anything.You.Like.Here
{
   [AttributeUsage(AttributeTargets.Class)]
   public sealed class DefaultNameAttribute : Attribute
   {
      public DefaultNameAttribute(string name)
      {
         Name = name;
      }
      public string Name { get; private set; }
   }
}

 
 

Will the .NET Core version of Autofac honor this?

Thursday, April 2, 2020

.NET Portable

These are a set of assemblies to compile .NET Source Code to a PCL (portable class library) or really any other platform.

IMS

stands for IP Multimedia Subsystem or IP Multimedia Core Network Subsystem, a type of modem

To make a git branch at the server in Azure DevOps...

Go to "Branches" under "Repos" and click the "New branch" button up at the upper right. When you clone down master for the branch you should also be able to switch to one of the other branches as well.

Use a better ConfigurationBuilder instantiation for getting at appsettings.json variables in .NET Core 3.

Outside of a Controller or PageModel (WebMatrix), I had this trick, but here is a better way to go in modern times. It uses the Microsoft.Extensions.Configuration using declaration.

IConfiguration config = new ConfigurationBuilder().AddJsonFile("appsettings.json",
      optional: true, reloadOnChange: true).Build();
string thing = config["Repositories"];

 
 

Oh, it turns out that .AddJsonFile is an extension method from Microsoft.Extensions.Configuration.Json so you need that too. Castle.Core.Configuration may have an IConfiguration also. The name is kinda weak.

Wednesday, April 1, 2020

ConfigureServices returning an System.IServiceProvider isn't supported.

Alright, if you are getting this error, you tried to loop in Autofac as described here and it did not work because you are using version 3 of the .NET Framework (or better). The fix is to undo what you did in ConfigureServices and instead, in Program.cs, add the third line you see below to the mix:

public static IHostBuilder CreateHostBuilder(string[] args) =>
      Host.CreateDefaultBuilder(args)
         .UseServiceProviderFactory(new AutofacServiceProviderFactory())
         .ConfigureWebHostDefaults(webBuilder =>
         {
            webBuilder.UseStartup();
         });

 
 

Alright, now back at Startup.cs you need a new method called ConfigureContainer like so:

public void ConfigureContainer(ContainerBuilder builder)
{
   builder.RegisterType<Tom>().As<ITom>();
}

Use Autofac for IoC in .NET Core.

At: Tools > NuGet Package Manager > Manage NuGet Packages for Solution... ...search for "Autofac.Extensions.DependencyInjection" at the "Browse" tab. You will need the Autofac and Autofac.Extensions.DependencyInjection using declarations. Per this, the ConfigureServices method in Startup must change like so:

public IServiceProvider ConfigureServices(IServiceCollection services)
{
   services.AddControllers();
   var builder = new ContainerBuilder();
   builder.RegisterModule(new Foo());
   builder.RegisterModule(new Bar("bar"));
   builder.RegisterModule<Baz>();
   builder.RegisterType<Qux>().As<IQux>().WithParameter(new
         TypedParameter(typeof(IServiceFactory), new ServiceFactory(new[] { new
         FilenetProvider() })));
   builder.RegisterType<Yin>().As<IYin>();
   builder.RegisterType<Yang>().As<IYang>().SingleInstance();
   builder.Populate(services);
   var container = builder.Build();
   return new AutofacServiceProvider(container);
}

.AllowCredentials()

I think that using .AllowCredentials() like .AllowAnyMethod() at Startup in a .NET Core application is equal to setting .SupportsCredentials to true at a CorsPolicy in the .NET Framework stuff.

Use .WithHeaders instead of .AllowAnyHeader in CORS in .NET Core.

.WithHeaders("GET", "POST", "PUT", "DELETE", "OPTIONS")

Allow all subdomains for a domain name in CORS in a .NET Core orchestration.

Follow this example and replace www with an * to make the magic happen.

Open up CORS for very specific domains in .NET Core 3.1.

This had this example:

public void ConfigureServices(IServiceCollection services)
{
   services.AddCors(options =>
   {
      options.AddPolicy(MyAllowSpecificOrigins,
      builder =>
      {
         builder.WithOrigins("http://example.com",
               "http://www.contoso.com")
               .AllowAnyHeader()
               .AllowAnyMethod();
      });
   });
   services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}

 
 

MyAllowSpecificOrigins above is just a string and...

app.UseCors(MyAllowSpecificOrigins);

 
 

...needs to go inside of:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{