#StackBounty: #angular #azure #asp.net-core #.net-core #angular7 How To Deploy Angular 7 with Net Core API Separately on Azure

Bounty: 50

Right now I have a .Net Core Application with Angular 7 as the Client

I have both the API and Client deployed on Azure however I am stuck on how to get the client working on azure where it reaches the .Net Core endpoints. On my login post request I am getting a 404 however it works on my local build… I’m not sure exaclty what I’m doing wrong?

    Request Method: POST
Status Code: 404 Not Found
Referrer Policy: no-referrer-when-downgrade


Get this bounty!!!

#StackBounty: #c# #.net-core #xml-serialization Why does XmlSerializer fail to serialize enum value in .Net Core but works fine in .NET…

Bounty: 100

Summary

.NET Core apps fail to XML serialize an object which contains an enum value, while .NET Framework (4.7.2) succeeds. Is this a known breaking change, and if so, how can I work around it?

Code Example

The following console application does not throw an exception in .NET Framework 4.7.2 project:

    public enum MyEnum
    {
        One,
    }

    public class ValueContainer
    {
        public object Value;
    }
    class Program
    {
        static void Main(string[] args)
        {
            XmlSerializer newSerializer = XmlSerializer.FromTypes(
                new[] { typeof(ValueContainer)})[0];

            var instance = new ValueContainer();
            instance.Value = MyEnum.One;

            using (var memoryStream = new MemoryStream())
            {
                newSerializer.Serialize(memoryStream, instance);
            }
        }
    }

The exact same code in a .NET Core 3.0 Console Application throws the following exception when calling Serialize:

System.InvalidOperationException
  HResult=0x80131509
  Message=There was an error generating the XML document.
  Source=System.Private.Xml
  StackTrace:
   at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id)
   at System.Xml.Serialization.XmlSerializer.Serialize(Stream stream, Object o, XmlSerializerNamespaces namespaces)
   at System.Xml.Serialization.XmlSerializer.Serialize(Stream stream, Object o)
   at CoreXml.Program.Main(String[] args) in C:UsersvchelsourcereposCoreXmlCoreXmlProgram.cs:line 28

Inner Exception 1:
InvalidOperationException: The type CoreXml.MyEnum may not be used in this context.

Am I doing something wrong in my code? Is this a breaking change between .NET Framework and .NET Core?

Is there a workaround?

Update

I should have pointed out that when serializing in .NET 4.7.2, I get the following (desired) output for Value:

 <Value xsi:type="xsd:int">0</Value>

I would like whatever solution is proposed for .NET Core to also output the same XML, as I need to maintain compatibility with existing files and older versions of the app which aren’t using .NET Standard.


Get this bounty!!!

#StackBounty: #c# #.net-core #mediatr How to add MediatR PublishStrategy to existing project

Bounty: 50

Now I use MediatR notifications like this:

private readonly IMediator _requestsRouter; // from constructor injection 

 OrderCreatedEvent orderCreatedEvent = new OrderCreatedEvent(x,y,z);
 await _requestRouter.Publish(orderCreatedEvent); 

I would like to change default PublishStrategy to ParallelNoWait = 3,

Question: How to extend MediatR functionality from nuget with MediatR PublishStrategies from sample ?

I understand that I can download MediatR source code, add to it code from MediatR.Examples.PublishStrategies and build my own library but maybe there is another “fast” way?


Get this bounty!!!

#StackBounty: #.net-core #nuget #nuget-package #.net-core-3.0 Should a library explicitly target .NET Core 3?

Bounty: 50

With the release of .NET Standard 2.0, it’s advised to target .NET Standard 2.0, even if you target 1.x already.

https://docs.microsoft.com/en-us/dotnet/standard/net-standard:

However, targeting lower .NET Standard versions introduces a number of support dependencies. If your project targets .NET Standard 1.x, we recommend that you also target .NET Standard 2.0. This simplifies the dependency graph for users of your library that run on .NET Standard 2.0 compatible frameworks, and it reduces the number of packages they need to download.

Now another big change is near! .NET Core 3 and I see that Microsoft also is targeting .NET Core 3 for Microsoft packages.

For example, Microsoft.Extensions.Logging is targeting .NET Standard 2.0 and also .NET Core 3 (.NETCoreApp 3.0):

enter image description here

I compared the XML files and both APIs look the same (maybe not the best way to compared them)

Now the question 😉

As a library maintainer that dependents on Microsoft.Extensions.Logging, who trying to support .NET Core 3:
Should I also target .NET Core 3 – or is just .NET Standard 2.0 good enough if I don’t need specific stuff of .NET Core 3?


Get this bounty!!!

#StackBounty: #c# #visual-studio #.net-core #azure-devops #azure-pipelines Visual Studio Build Fails for Net Core 3.0 SDK Preview 9 on …

Bounty: 50

I’ve been struggling with this one all weekend.

I cannot obtain a successful build for Net Core 3 SDK Preview 9 (released 4 September 2019).

I have set up a pipeline solely to:

  1. Use the new SDK
  2. Implement a global.json file using the new SDK
  3. Use Nuget 5.x and Nuget restore to correctly obtain preview packages
  4. Visual Studio Build the solution

I’m getting the following errors with the build stage (4):

Error : Unable to locate the .NET Core SDK. Check that it is installed
and that the version specified in global.json (if any) matches the
installed version.

Error MSB4236: The SDK ‘Microsoft.NET.Sdk.Web’ specified could not be
found.

I was initially getting the same error during the Nuget restore stage (3) before implementing the global.json in step 2, so I know the global.json is being correctly referenced.

Pipeline YAML:

pool:
  name: Azure Pipelines
  demands:
  - msbuild
  - visualstudio

steps:
- task: UseDotNet@2
  displayName: 'Use .Net Core sdk 3.0.100-preview9-014004'
  inputs:
    version: '3.0.100-preview9-014004'
    includePreviewVersions: true

- powershell: |
   $globaljson = '{"sdk": {"version": "3.0.100-preview9-014004"}}';
   $globaljson | out-file './test.app/global.json' -Encoding UTF8
  displayName: 'Global Json'

- task: NuGetToolInstaller@1
  displayName: 'Use NuGet 5.x'
  inputs:
    versionSpec: 5.x
    checkLatest: true

- task: NuGetCommand@2
  displayName: 'NuGet restore'
  inputs:
    restoreSolution: '$(Parameters.solution)'

- task: VSBuild@1
  displayName: 'Build solution ***.sln'
  inputs:
    solution: '$(Parameters.solution)'
    msbuildArgs: '/p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true /p:PackageLocation="$(build.artifactstagingdirectory)\"'
    platform: '$(BuildPlatform)'
    configuration: '$(BuildConfiguration)'

enter image description here


Get this bounty!!!

#StackBounty: #c# #.net-core System.Reflection.Emit: bind together a class and an interface

Bounty: 50

I want to bind together a class A and an interface B and create a type C such that C implements the interface B. Also:

  • type C has a constructor that takes an object of type A as a constructor, we call it i
  • And given a map of all properties from A to B (assuming all properties in the map have the same type), then it uses the property values from i instead.

For example:

class A { public string Name { get; set; } } 

interface B { string Name { get; set; } } 

class C : B {
    private readonly A _i;

    public C(A i) { 
        _i = i;
    }

    public string Name
    {
        get => _i.Name;
        set => _i.Name = value;
    }
} 

This is what I have done (by common I mean B and by source I mean A):

/// <summary>
/// Creates a new type dynamically
/// </summary>
public class CustomTypeGenerator<TSource, TCommon>
{
    private readonly TypeBuilder _tb;

    private readonly FieldBuilder _entityFieldBldr;

    private readonly Type _srcType;

    /// <summary>
    /// Initialize custom type builder
    /// </summary>
    public CustomTypeGenerator(IEnumerable<(string CommonPrpName, Type Type, string SourcePrpName)> members)
    {
        var cmType = typeof(TCommon);
        _srcType = typeof(TSource);

        if (!cmType.IsInterface)
        {
            throw new Exception("Type has to be an interface");
        }

        const string assemblyName = "DynamicAseembly123";
        const string typeSignature = "DynamicType123";

        var assemblyBuilder =
            AssemblyBuilder.DefineDynamicAssembly(new AssemblyName(assemblyName), AssemblyBuilderAccess.Run);
        var moduleBuilder = assemblyBuilder.DefineDynamicModule("Module123");

        _tb = moduleBuilder.DefineType(typeSignature,
            TypeAttributes.Public |
            TypeAttributes.Class |
            TypeAttributes.AutoClass |
            TypeAttributes.AnsiClass |
            TypeAttributes.BeforeFieldInit |
            TypeAttributes.AutoLayout);

        _tb.AddInterfaceImplementation(cmType);

        _entityFieldBldr = EmitSourceField();

        _tb.DefineDefaultConstructor(
            MethodAttributes.Public |
            MethodAttributes.SpecialName |
            MethodAttributes.RTSpecialName);

        var constructorBuilder = _tb.DefineConstructor(MethodAttributes.Public,
            CallingConventions.Standard,
            new[] {_srcType});

        constructorBuilder.DefineParameter(0, ParameterAttributes.None, "entity");

        var constructorIl = constructorBuilder.GetILGenerator();
        constructorIl.Emit(OpCodes.Ldarg_0);
        constructorIl.Emit(OpCodes.Ldarg_1);
        constructorIl.Emit(OpCodes.Stfld, _entityFieldBldr);
        constructorIl.Emit(OpCodes.Ret);

        foreach (var (commonPrpName, type, sourcePrpName) in members)
        {
            EmitProperty(commonPrpName, type, sourcePrpName);
        }

        EmittedType = _tb.CreateType();
    }

    public Type EmittedType { get; }

    private FieldBuilder EmitSourceField()
    {
        var entityBldr = _tb.DefineField("_" + "entity", _srcType, FieldAttributes.Private);

        return entityBldr;
    }

    private void EmitProperty(string cPn, Type cmPt, string sPn)
    {
        var srcProp = _srcType.GetProperty(sPn, BindingFlags.Public | BindingFlags.Instance);
        var propertyBldr = _tb.DefineProperty(cPn, PropertyAttributes.HasDefault, cmPt, null);

        var getterMethodInfo = srcProp.GetMethod ?? throw new Exception("Missing getter!");
        var getPropMthdBldr = _tb.DefineMethod($"get_{cPn}",
            MethodAttributes.Public |
            MethodAttributes.SpecialName |
            MethodAttributes.HideBySig,
            cmPt, Type.EmptyTypes);

        var getIl = getPropMthdBldr.GetILGenerator();
        var getProperty = getIl.DefineLabel();
        var exitGet = getIl.DefineLabel();

        getIl.MarkLabel(getProperty);
        getIl.Emit(OpCodes.Ldarg_0);
        getIl.Emit(OpCodes.Ldfld, _entityFieldBldr);
        getIl.Emit(OpCodes.Call, getterMethodInfo);
        getIl.Emit(OpCodes.Dup);
        getIl.MarkLabel(exitGet);
        getIl.Emit(OpCodes.Ret);

        var setterMethodInfo = srcProp.SetMethod ?? throw new Exception("Missing setter!");
        var setPropMthdBldr = _tb.DefineMethod($"set_{cPn}",
            MethodAttributes.Public |
            MethodAttributes.SpecialName |
            MethodAttributes.HideBySig,
            null, new[] {cmPt});

        var setIl = setPropMthdBldr.GetILGenerator();
        var modifyProperty = setIl.DefineLabel();
        var exitSet = setIl.DefineLabel();

        setIl.MarkLabel(modifyProperty);
        setIl.Emit(OpCodes.Ldarg_0);
        getIl.Emit(OpCodes.Ldfld, _entityFieldBldr);
        setIl.Emit(OpCodes.Ldarg_1);
        getIl.Emit(OpCodes.Call, setterMethodInfo);
        setIl.Emit(OpCodes.Nop);
        setIl.MarkLabel(exitSet);
        setIl.Emit(OpCodes.Ret);

        propertyBldr.SetGetMethod(getPropMthdBldr);
        propertyBldr.SetSetMethod(setPropMthdBldr);
    }
}

The exception I’m getting:

Method ‘get_Name’ in type ‘DynamicType123’ from assembly
‘DynamicAseembly123, Version=0.0.0.0, Culture=neutral,
PublicKeyToken=null’ does not have an implementation.

Thank you for any help or hint.


Update: I used ILSpy to spy on generated IL on my dummy example code:

.class private auto ansi beforefieldinit ConsoleApp1.C
    extends [System.Runtime]System.Object
    implements ConsoleApp1.B
{
    // Fields
    .field private initonly class ConsoleApp1.A _i

    // Methods
    .method public hidebysig specialname rtspecialname 
        instance void .ctor (
            class ConsoleApp1.A i
        ) cil managed 
    {
        // Method begins at RVA 0x206a
        // Code size 16 (0x10)
        .maxstack 8

        // (no C# code)
        IL_0000: ldarg.0
        IL_0001: call instance void [System.Runtime]System.Object::.ctor()
        IL_0006: nop
        IL_0007: nop
        // _i = i;
        IL_0008: ldarg.0
        IL_0009: ldarg.1
        IL_000a: stfld class ConsoleApp1.A ConsoleApp1.C::_i
        // (no C# code)
        IL_000f: ret
    } // end of method C::.ctor

    .method public final hidebysig specialname newslot virtual 
        instance string get_Name () cil managed 
    {
        // Method begins at RVA 0x207b
        // Code size 12 (0xc)
        .maxstack 8

        // return _i.Name;
        IL_0000: ldarg.0
        IL_0001: ldfld class ConsoleApp1.A ConsoleApp1.C::_i
        IL_0006: callvirt instance string ConsoleApp1.A::get_Name()
        // (no C# code)
        IL_000b: ret
    } // end of method C::get_Name

    .method public final hidebysig specialname newslot virtual 
        instance void set_Name (
            string 'value'
        ) cil managed 
    {
        // Method begins at RVA 0x2088
        // Code size 14 (0xe)
        .maxstack 8

        // _i.Name = value;
        IL_0000: ldarg.0
        IL_0001: ldfld class ConsoleApp1.A ConsoleApp1.C::_i
        IL_0006: ldarg.1
        IL_0007: callvirt instance void ConsoleApp1.A::set_Name(string)
        // (no C# code)
        IL_000c: nop
        IL_000d: ret
    } // end of method C::set_Name

    // Properties
    .property instance string Name()
    {
        .get instance string ConsoleApp1.C::get_Name()
        .set instance void ConsoleApp1.C::set_Name(string)
    }

} // end of class ConsoleApp1.C

And I used the hints in ILSpy to get some hints and here is my updated C# code:

/// <summary>
/// Creates a new type dynamically
/// </summary>
public class CustomTypeGenerator<TSource, TCommon>
{
    private readonly TypeBuilder _tb;

    private readonly FieldBuilder _entityFieldBldr;

    private readonly Type _srcType;

    /// <summary>
    /// Initialize custom type builder
    /// </summary>
    public CustomTypeGenerator(Dictionary<string, (Type Type, string SourcePrpName)> members)
    {
        var objType = typeof(object);
        var cmType = typeof(TCommon);
        _srcType = typeof(TSource);

        if (!cmType.IsInterface)
        {
            throw new Exception("Type has to be an interface");
        }

        const string assemblyName = "DynamicAssembly123";
        const string typeSignature = "DynamicType123";

        var assemblyBuilder =
            AssemblyBuilder.DefineDynamicAssembly(new AssemblyName(assemblyName), AssemblyBuilderAccess.Run);

        var moduleBuilder = assemblyBuilder.DefineDynamicModule("Module123");

        _tb = moduleBuilder.DefineType(typeSignature,
            TypeAttributes.Public |
            TypeAttributes.Serializable |
            TypeAttributes.Class |
            TypeAttributes.Sealed |
            TypeAttributes.AutoLayout, objType);

        _tb.AddInterfaceImplementation(cmType);

        _entityFieldBldr = EmitSourceField();

        _tb.DefineDefaultConstructor(
            MethodAttributes.Public |
            MethodAttributes.SpecialName |
            MethodAttributes.RTSpecialName);

        var constructorBuilder = _tb.DefineConstructor(MethodAttributes.Public,
            CallingConventions.Standard,
            new[] {_srcType});

        constructorBuilder.DefineParameter(0, ParameterAttributes.None, "entity");

        var constructorIl = constructorBuilder.GetILGenerator();
        constructorIl.Emit(OpCodes.Ldarg_0);
        constructorIl.Emit(OpCodes.Ldarg_1);
        constructorIl.Emit(OpCodes.Stfld, _entityFieldBldr);
        constructorIl.Emit(OpCodes.Ret);

        foreach (var (commonPrpName, (type, sourcePrpName)) in members)
        {
            EmitProperty(commonPrpName, type, sourcePrpName);
        }

        EmittedType = _tb.CreateType();
    }

    public Type EmittedType { get; }

    private FieldBuilder EmitSourceField()
    {
        var entityBldr = _tb.DefineField("_" + "entity", _srcType,
            FieldAttributes.Private |
            FieldAttributes.InitOnly);

        return entityBldr;
    }

    private void EmitProperty(string cPn, Type cmPt, string sPn)
    {
        var srcProp = _srcType.GetProperty(sPn, BindingFlags.Public | BindingFlags.Instance);

        var getterMethodInfo = srcProp.GetMethod ?? throw new Exception("Missing getter!");
        var getPropMthdBldr = _tb.DefineMethod($"get_{cPn}",
            MethodAttributes.Public |
            MethodAttributes.Virtual |
            MethodAttributes.SpecialName |
            MethodAttributes.HideBySig,
            cmPt, Type.EmptyTypes);

        var getIl = getPropMthdBldr.GetILGenerator();
        var getPropertyLbl = getIl.DefineLabel();
        var exitGetLbl = getIl.DefineLabel();

        getIl.MarkLabel(getPropertyLbl);
        getIl.Emit(OpCodes.Ldarg_0);
        getIl.Emit(OpCodes.Ldfld, _entityFieldBldr);
        getIl.Emit(OpCodes.Callvirt, getterMethodInfo);
        getIl.MarkLabel(exitGetLbl);
        getIl.Emit(OpCodes.Ret);

        var setterMethodInfo = srcProp.SetMethod ?? throw new Exception("Missing setter!");
        var setPropMthdBldr = _tb.DefineMethod($"set_{cPn}",
            MethodAttributes.Public |
            MethodAttributes.Virtual |
            MethodAttributes.SpecialName |
            MethodAttributes.HideBySig,
            null, new[] {cmPt});

        var setIl = setPropMthdBldr.GetILGenerator();
        var modifyPropertyLbl = setIl.DefineLabel();
        var exitSetLbl = setIl.DefineLabel();

        setIl.MarkLabel(modifyPropertyLbl);
        setIl.Emit(OpCodes.Ldarg_0);
        getIl.Emit(OpCodes.Ldfld, _entityFieldBldr);
        setIl.Emit(OpCodes.Ldarg_1);
        getIl.Emit(OpCodes.Callvirt, setterMethodInfo);
        setIl.Emit(OpCodes.Nop);
        setIl.MarkLabel(exitSetLbl);
        setIl.Emit(OpCodes.Ret);

        var propertyBldr = _tb.DefineProperty(cPn, PropertyAttributes.None, cmPt, null);
        propertyBldr.SetGetMethod(getPropMthdBldr);
        propertyBldr.SetSetMethod(setPropMthdBldr);
    }
}


Get this bounty!!!

#StackBounty: #api #.net-core #swashbuckle How to upload multipart file from request body in swashbuckle?

Bounty: 50

How should I setup swashbuckle in .net core so that I could upload file from request body (multipart, form value model binding disabled)?

What I tried (added FileUploadHelper in swashbuckle startup config, obviously):

public class FileUploadHelper : IOperationFilter
{
    public void Apply(Operation operation, OperationFilterContext context)
    {
        if (operation.OperationId.ToLower() == "apifileuploadpost")
        {
            operation.Parameters.Clear();
            operation.Parameters.Add(new NonBodyParameter()
            {
                Name = "File",
                In = "formData",
                Description = "uploaded file",
                Type = "file",
                Required = true,
            });
            operation.Consumes.Add("multipart/form-data");
        }
    }
}


 [HttpPost, DisableRequestSizeLimit]
 [DisableFormValueModelBinding]      
    public async Task<IActionResult> Upload()
    {
        int id = await Request.StreamFile(fileService);
        return CreatedAtAction(nameof(GetFileInfo), id);
    }

StreamFile is an extension method that saves file content from request body in filecontent entity (byte[]) and also creates a fileinfo entity with file content id and some additional info (name, description etc.) but returns only generated id. I just want to be able to click upload button in swagger, choose file and get the returned id or error response. I do NOT use IFileForm, form value model binding is disabled (according to large file upload using streaming in asp.net core documentation) and the file is straight from request body so I don’t pass any file-related parameter in Upload controller method, only ‘this HttpRequest’. Is that even doable in Swashbuckle?


Get this bounty!!!

#StackBounty: #c# #.net #.net-core #nuget Core 2 Application Root Empty When From Nuget Packet

Bounty: 50

The code in the GetApplicationRoot() method is identical to the code in the WildHare IOExtensions.GetApplicationRoot() method.

If the code is referenced in the same solution using a project reference in a .net Core 2 project, they return the same value. In a net471 project, both lines also return the same application root.

In .net Core 2, if I use the IOExtensions.GetApplicationRoot() method imported from the Nuget WildHare packet, it returns an empty value.

Just to be clear, I am the author of the package and was surprised when this did not work in the context of a .net Core Nuget package and am interested in the why.

Any ideas?

using System;
using System.IO;
using System.Reflection;
using System.Text.RegularExpressions;
using WildHare.Extensions;

namespace FirstCore
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine($"GetApplicationRoot(): { GetApplicationRoot() }");
            // Returns C:CodeSamplesCore2FirstCore

            Console.WriteLine($"IOExtensions.GetApplicationRoot(): { IOExtensions.GetApplicationRoot() }");
            // Returns empty string

            Console.ReadLine();
        }

        public static string GetApplicationRoot()
        {
            var exePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
            var appPathMatcher = new Regex(@"(?<!fil)[A-Za-z]:\+[Ss]*?(?=\+bin)");
            var appRoot = appPathMatcher.Match(exePath).Value;

            return appRoot;
        }
    }
 }

Result

 


Get this bounty!!!

#StackBounty: #.net #amazon-web-services #asp.net-core #amazon-ec2 #.net-core Service segmentation fault in AWS EC2

Bounty: 250

I have my service running in EC2 (under systemd). It is a self-contained app built for .Net Core 2.1.
From time to time (a few times a week) it crashes with SEGV.

Apr 30 21:20:51 ip-10-4-226-55 kernel: traps: App.Name[26176] general protection ip:7f22da3609da sp:7f1fedf11510 error:0 in libc-2.26.so[7f22da2e3000+1ad000]

Apr 30 21:20:51 ip-10-4-226-55 systemd: appname.service: main process exited, code=killed, status=11/SEGV

Apr 30 21:20:51 ip-10-4-226-55 systemd: Unit appname.service entered failed state.

Apr 30 21:20:51 ip-10-4-226-55 systemd: appname.service failed.

For some reason, crash dump is not created (even though I removed the size limit).
How can I investigate the problem further? What can be the source of the issue?


Get this bounty!!!

#StackBounty: #c# #performance #entity-framework-core #.net-core Persist payload containing multiple items using EF Core Performance Im…

Bounty: 50

I have an .NET Core EF application, setup as Database first, that is supposed to take in a payload containing items to be persisted to my database. They payloads can be huge containing multiple “Securities” and each “Security” has multiple “Positions/Transactions” to be persisted to the database. This application can be called multiple times in parallel from a commandline tool. Sometimes these payloads can take up to 20 minutes to deserialize to their components and persist. The ultimate goal here is to reduce the amount of time taken to run through a payload and persist. The SaveChanges() function call is not the issue here (afaik). I think the issue is the nested looping through the securities and all of their positions on the payload and the corresponding LINQ queries. These operations are happening in HandlePostions/HandleTransactions/TryFindSecId functions. Any help pointing out any obvious code smells, any performance improvements, or any help optimizing the queries would be welcomed. Here is my calling function:

    private async Task<AccPackBody> Persist(AccPackBody pack)
    {
        bool hasModifications = false, hasErrors = false;

        using (var dbContext = new newportMasterContext(Configs.MasterDbConnString))
        {
            dbContext.Database.SetCommandTimeout(300);

            foreach(var mappedSecurity in pack.Internal)
            {
                mappedSecurity.FirmId = pack.FirmId;

                SEC_IDENTIFIER existingSecurity = null;
                try
                {
                    existingSecurity = await TryFindSecId(mappedSecurity, pack.FirmId.Value, dbContext);
                }
                catch(Exception ex)
                {
                    await Logger.Send(LogType.Error, "Something failed while trying to clone security");
                }

                if(existingSecurity == null)
                {
                    await Logger.Send(pack, LogType.Error, $"Missing security for: Identifier: {mappedSecurity.IdentifierName} Value: {mappedSecurity.IdentifierValue}, Firm{pack.FirmId}, Currency:{mappedSecurity.Currency}");
                    throw new LoggedException();
                }
                else
                {
                    mappedSecurity.SecurityGuid = existingSecurity.Security_UID;

                    POSITION[] updatedPositions = null;
                    if(mappedSecurity.Postitions != null && mappedSecurity.Postitions.Length > 0)
                    {
                        updatedPositions = HandlePositions(pack,dbContext, pack.State, pack.AccountUID.Value, mappedSecurity, pack.StatementDate.Value);


                        mappedSecurity.Postitions = updatedPositions != null  && updatedPositions.Count() > 0
                            ? updatedPositions
                            : new POSITION[0];

                        if(updatedPositions != null && updatedPositions.Count() > 0)
                            hasModifications = true;
                    }

                    //EditTransaction
                    TRANSACTION[] updatedTransactions = null;
                    if(mappedSecurity.Transactions != null && mappedSecurity.Transactions.Length > 0)
                    {
                        updatedTransactions = HandleTransctions(dbContext, pack, mappedSecurity);
                        mappedSecurity.Transactions = updatedTransactions != null && updatedTransactions.Count() > 0
                            ? updatedTransactions
                            : new TRANSACTION[0];

                        if(updatedTransactions != null && updatedTransactions.Count() > 0)
                            hasModifications = true;
                    } 
                }
            }

            if(!hasErrors && dbContext.ChangeTracker.HasChanges())
            {
                try
                {
                    await dbContext.SaveChangesAsync();
                }
                catch(Exception ex)
                {
                    await Logger.Send(pack,LogType.Warning, "Error persisting changes to db, rolling back: " + ex.ToString());
                    throw new LoggedException();
                }
            }
        }

        return pack;
    } 

Here are my three functions that the above method calls – these are where a lot of the slowdowns are occuring:

    private async Task<SEC_IDENTIFIER> TryFindSecId(AccMappedSecurity mappedSecurity, long firmId, newportMasterContext dbContext, Guid? packUid = null)
    {
        var existingSecurities = dbContext.SEC_IDENTIFIER
            .Where(x => x.IdentifierName == mappedSecurity.IdentifierName 
                && mappedSecurity.IdentifierValue == x.Identifier
                && x.FirmID == firmId 
                && (string.IsNullOrEmpty(mappedSecurity.Currency) || x.SECURITY.Currency == mappedSecurity.Currency) && x.SECURITY.ChangeType != "D");

        var existingSecurity = existingSecurities.FirstOrDefault();

        if(existingSecurity == null)
        {
            var cloneResult = await ClonePostition.Clone(
                new ClonePositionRequest
                {
                    IdentifierName = mappedSecurity.IdentifierName,
                    IdentifierValue = mappedSecurity.IdentifierValue,
                    NewCurrency = mappedSecurity.Currency,
                    FirmId = firmId
                },
                Logger.LocalLog
            );

            if(cloneResult.Code != HttpStatusCode.InternalServerError)
            {
                existingSecurity = dbContext.SEC_IDENTIFIER
                .FirstOrDefault(x => x.IdentifierName == mappedSecurity.IdentifierName 
                    && mappedSecurity.IdentifierValue == x.Identifier
                    && x.FirmID == firmId 
                    && (string.IsNullOrEmpty(mappedSecurity.Currency) || x.SECURITY.Currency == mappedSecurity.Currency));
            }
            else
            {
                await Logger.Send(LogType.Error, "Internal server error on clone function - clone failed" + cloneResult.Code);
            }
        }
        else
        {

        }

        return existingSecurity;
    }





    private POSITION[] HandlePositions(AccPackBody reqPayload, newportMasterContext dbContext, PackState state, Guid accountGuid, AccMappedSecurity mappedSecurity, DateTime statementDate, Guid? packUid = null)
    {
        if(useDiagnosticLogging) LocalLoggingUtilities.WriteDiagnosticLog(_logText, packUid.Value, "Hit handle positions");

        var handledPositions = new List<POSITION>();
        int posCnt = mappedSecurity.Postitions.Length;
        if(useDiagnosticLogging) LocalLoggingUtilities.WriteDiagnosticLog(_logText, packUid.Value, "Deserializing mapped positions");
        List<POSITION> deserializedPositions = mappedSecurity.Postitions
            .Select(x => JsonConvert.DeserializeObject<POSITION>(x.ToString(), Configs.JsonCircularRefFixConfig))
            .OrderBy(x => x.DateStart)
            .ToList();

        var updatedPosDetails = new List<POSITION_DETAIL>();
        POSITION prevailingPosition = null;

        if(useDiagnosticLogging) LocalLoggingUtilities.WriteDiagnosticLog(_logText, packUid.Value, "Checking for prevailing position.");

        prevailingPosition = dbContext.POSITION
            .Include(x => x.POSITION_DETAIL)
            .Include(x => x.POSITION_DETAIL).ThenInclude(x => x.POSITION_BOND)
            .Include(x => x.POSITION_DETAIL).ThenInclude(x => x.POSITION_FX)
            .Include(x => x.POSITION_DETAIL).ThenInclude(x => x.POSITION_OPTION)
            .Include(x => x.POSITION_DETAIL).ThenInclude(x => x.POSITION_PRICE)
            .Where(x => x.Account_UID == accountGuid 
                && x.Security_UID == mappedSecurity.SecurityGuid 
                && x.SecurityFirmID == mappedSecurity.FirmId 
                && (x.DateStart.Date <= statementDate) && (!x.DateEnd.HasValue || x.DateEnd.Value.Date < statementDate) 
                && x.ChangeType != "D" 
                && x.POSITION_DETAIL.Any(pd => pd.Genesis == "FEED" &&
                                            pd.ChangeType != "D"))
            .OrderByDescending(x => x.DateStart)
            .ToList().FirstOrDefault();

        if(useDiagnosticLogging) LocalLoggingUtilities.WriteDiagnosticLog(_logText, packUid.Value, "Looping incoming positions.");
        foreach(var incomingPosition in deserializedPositions)
        {
            if(useDiagnosticLogging) LocalLoggingUtilities.WriteDiagnosticLog(_logText, packUid.Value, string.Format("Hit new incoming position:{0}", incomingPosition.Position_UID.ToString()));
            incomingPosition.Account_UID = accountGuid;
            incomingPosition.Security_UID = mappedSecurity.SecurityGuid.Value;
            incomingPosition.SecurityFirmID = mappedSecurity.FirmId.Value;
            incomingPosition.Position_UID = Guid.NewGuid();
            if (prevailingPosition == null)
            {
                EntityEntry<POSITION> newPosition = null;
                dbContext.POSITION.Add(incomingPosition);
                newPosition = dbContext.Entry(incomingPosition);
                newPosition.CurrentValues.SetValues(new { ChangeType = "I" });
                foreach(var posDetail in incomingPosition.POSITION_DETAIL.Where(x => x.ChangeType.ToUpper() != "D"))
                {
                    EntityEntry<POSITION_DETAIL> newPositionDetail = null;
                    posDetail.Detail_UID = Guid.NewGuid();
                    dbContext.POSITION_DETAIL.Add(posDetail);
                    newPositionDetail = dbContext.Entry(posDetail);
                    newPositionDetail.CurrentValues.SetValues(new { ChangeType = "I"});
                    updatedPosDetails.Add(posDetail);
                }

                handledPositions.Add(incomingPosition);

                if(useDiagnosticLogging) LocalLoggingUtilities.WriteDiagnosticLog(_logText, packUid.Value, "Inserted: " + incomingPosition.Position_UID.ToString());
            }
            else
            {
                if(prevailingPosition.DateStart.Date == incomingPosition.DateStart.Date)
                {
                    foreach(var posDetail in prevailingPosition.POSITION_DETAIL.Where(x => x.ChangeType.ToUpper() != "D"))
                    {
                        EntityEntry<POSITION_DETAIL> positionDetailToRemove = dbContext.Entry(posDetail);
                        positionDetailToRemove.CurrentValues.SetValues(new
                        {
                            ChangeDate = DateTime.Now,
                            ChangeType = "D"
                        });
                    }
                    EntityEntry<POSITION> positionToRemove = dbContext.Entry(prevailingPosition);
                    positionToRemove.CurrentValues.SetValues(new 
                    {
                        ChangeDate = DateTime.Now,
                        ChangeType = "D"
                    });

                    EntityEntry<POSITION> newPosition = null;
                    dbContext.POSITION.Add(incomingPosition);
                    newPosition = dbContext.Entry(incomingPosition);
                    newPosition.CurrentValues.SetValues(new { ChangeType = "I" });
                    handledPositions.Add(incomingPosition);

                    if(useDiagnosticLogging) LocalLoggingUtilities.WriteDiagnosticLog(_logText, packUid.Value, "inserted: " + incomingPosition.Position_UID.ToString());

                    foreach(var posDetail in incomingPosition.POSITION_DETAIL.Where(x => x.ChangeType.ToUpper() != "D"))
                    {
                        EntityEntry<POSITION_DETAIL> newPositionDetail = null;
                        posDetail.Detail_UID = Guid.NewGuid();
                        dbContext.POSITION_DETAIL.Add(posDetail);
                        newPositionDetail = dbContext.Entry(posDetail);
                        newPositionDetail.CurrentValues.SetValues(new { ChangeType = "I"});
                        updatedPosDetails.Add(posDetail);
                    }
                }
                else if(prevailingPosition.DateStart.Date < incomingPosition.DateStart.Date 
                    && PositionHasChange(prevailingPosition, incomingPosition, packUid))
                {
                    EntityEntry<POSITION> newPosition = null;
                    dbContext.POSITION.Add(incomingPosition);
                    newPosition = dbContext.Entry(incomingPosition);
                    newPosition.CurrentValues.SetValues(new { ChangeType = "I" });
                    handledPositions.Add(incomingPosition);

                    if(useDiagnosticLogging) LocalLoggingUtilities.WriteDiagnosticLog(_logText, packUid.Value, "inserted: " + incomingPosition.Position_UID.ToString());

                    foreach(var posDetail in incomingPosition.POSITION_DETAIL.Where(x => x.ChangeType.ToUpper() != "D"))
                    {
                        EntityEntry<POSITION_DETAIL> newPositionDetail = null;
                        posDetail.Detail_UID = Guid.NewGuid();
                        dbContext.POSITION_DETAIL.Add(posDetail);
                        newPositionDetail = dbContext.Entry(posDetail);
                        newPositionDetail.CurrentValues.SetValues(new { ChangeType = "I"});
                        updatedPosDetails.Add(posDetail);
                    }
                }
                else if(prevailingPosition.DateStart.Date < incomingPosition.DateStart.Date 
                    && !PositionHasChange(prevailingPosition, incomingPosition, packUid))
                {
                }
            }
        }

        return handledPositions.ToArray();
    }





 private TRANSACTION[] HandleTransctions(newportMasterContext dbContext, AccPackBody pack, AccMappedSecurity mappedSecurity, Guid? packUid = null)
    {
        object[] transactionsToProcess = new object[0]; 
        var handledTransactions = new List<TRANSACTION>();

        foreach(var trans in mappedSecurity.Transactions)
        {
            TRANSACTION handledTransaction = null, 
                mappedTransaction = null;

            mappedTransaction =  JsonConvert.DeserializeObject<TRANSACTION>(trans.ToString(), Configs.JsonCircularRefFixConfig);
            mappedTransaction.Security_UID = mappedSecurity.SecurityGuid.Value;

            //HACK
            if(string.IsNullOrWhiteSpace(mappedTransaction.BaseCurrency))
            {
                mappedTransaction.BaseCurrency = "USD";
            }

            //missing transId - drop out
            if(mappedTransaction.Reversal && string.IsNullOrWhiteSpace(mappedTransaction.TranID))
            {
                Logger.Send(pack, LogType.Warning, "Reversal Transaction is missing a transacation Id");
                throw new LoggedException();
            }
            else
            {
                //if(mappedTransaction.Reversal && !string.IsNullOrWhiteSpace(mappedTransaction.TranID))
                if(mappedTransaction.Reversal)
                {
                    List<TRANSACTION> transactionsInDb = dbContext.TRANSACTION
                        .Where(x => x.Account_UID == pack.AccountUID
                            && x.Security_UID == mappedSecurity.SecurityGuid
                            && x.SecurityFirmID == mappedSecurity.FirmId
                            && x.TradeDate.Date == mappedTransaction.TradeDate.Date
                            && x.TranID == mappedTransaction.TranID
                            && !x.Reversal
                            && x.ChangeType != "D")
                        .ToList();

                    if(transactionsInDb.Count == 1)
                    {
                        mappedTransaction.Visible = false;
                        TRANSACTION transactionInDb = transactionsInDb.FirstOrDefault();
                        transactionInDb.Visible = false;
                    }
                }

                mappedTransaction.SecurityFirmID = mappedSecurity.FirmId.Value;
                mappedTransaction.Account_UID = pack.AccountUID.Value;

                if(mappedTransaction?.Comment?.Length >= 100)
                {
                    mappedTransaction.Comment = mappedTransaction.Comment.Substring(0,96) + "...";
                }

                mappedTransaction.Tran_UID = Guid.NewGuid();

                var comparer = new TransactionComparer();
                EntityEntry<TRANSACTION> transactionToInsert = null;
                dbContext.TRANSACTION.Add(mappedTransaction);
                transactionToInsert = dbContext.Entry(mappedTransaction);
                transactionToInsert.CurrentValues.SetValues(new { ChangeType = "I" });

                if(useDiagnosticLogging) LocalLoggingUtilities.WriteDiagnosticLog(_logText, packUid.Value, "inserted: " + mappedTransaction.Tran_UID.ToString());

                if(transactionToInsert != null)
                {
                    transactionToInsert.CurrentValues.SetValues(new { ChangeDate = DateTime.Now });
                }

                handledTransaction = transactionToInsert?.Entity;

                if(handledTransaction != null)
                {
                    handledTransactions.Add(handledTransaction);
                }
             //   }
            }



        }

        return handledTransactions.ToArray();
    }

I have refactored the HandlePositions method to multiple functions for readability and code clarity. I am working some of the other code as well right now.

   private POSITION[] HandlePositions(AccPackBody reqPayload, newportMasterContext dbContext, PackState state, Guid accountGuid, AccMappedSecurity mappedSecurity, DateTime statementDate, Guid? packUid = null)
    {
        var handledPositions = new List<POSITION>();

        //deserialize positions sent in through mappedSecurity
        List<POSITION> deserializedPositions = mappedSecurity.Postitions
            .Select(x => JsonConvert.DeserializeObject<POSITION>(x.ToString(), Configs.JsonCircularRefFixConfig))
            .OrderBy(x => x.DateStart)
            .ToList();

        //get the prevailing position if it exists
        POSITION prevailingPosition = GetPrevailingPosition(accountGuid, statementDate, mappedSecurity, dbContext);

        //loop the incoming positions to persist as necessary
        foreach(var incomingPosition in deserializedPositions)
        {
            incomingPosition.Account_UID = accountGuid;
            incomingPosition.Security_UID = mappedSecurity.SecurityGuid.Value;
            incomingPosition.SecurityFirmID = mappedSecurity.FirmId.Value;
            incomingPosition.Position_UID = Guid.NewGuid();
            if (prevailingPosition == null)
            {
                //persist a position
                POSITION persistedPosition = AddPostionToContext(incomingPosition, dbContext);

                if(persistedPosition!=null)
                    handledPositions.Add(incomingPosition);
            }
            else
            {
                if(prevailingPosition.DateStart.Date == incomingPosition.DateStart.Date)
                {
                    //soft delete a position/details
                    POSITION positionToRemove = RemovePostionFromContext(prevailingPosition, dbContext);

                    //persist a position
                    POSITION persistedPosition = AddPostionToContext(incomingPosition, dbContext);
                    if(persistedPosition != null)
                        handledPositions.Add(persistedPosition);
                }
                else if(prevailingPosition.DateStart.Date < incomingPosition.DateStart.Date 
                    && PositionHasChange(prevailingPosition, incomingPosition, packUid))
                {
                    //persist a position
                    POSITION persistedPosition = AddPostionToContext(incomingPosition, dbContext);
                    if(persistedPosition != null)
                        handledPositions.Add(persistedPosition);
                }
            }
        }

        return handledPositions.ToArray();
    }

New functions to support the above code:

        private static POSITION AddPostionToContext(POSITION position, newportMasterContext context)
        {
            EntityEntry<POSITION> newPosition = null;
            context.POSITION.Add(position);
            newPosition = context.Entry(position);
            newPosition.CurrentValues.SetValues(new { ChangeType = "I" });
            foreach(var posDetail in position.POSITION_DETAIL.Where(x => x.ChangeType.ToUpper() != "D"))
            {
                EntityEntry<POSITION_DETAIL> newPositionDetail = null;
                posDetail.Detail_UID = Guid.NewGuid();
                context.POSITION_DETAIL.Add(posDetail);
                newPositionDetail = context.Entry(posDetail);
                newPositionDetail.CurrentValues.SetValues(new { ChangeType = "I"});
            }
            return position;
        }

        private static POSITION RemovePostionFromContext(POSITION position, newportMasterContext context)
        {
            foreach(var posDetail in position.POSITION_DETAIL.Where(x => x.ChangeType.ToUpper() != "D"))
            {
                EntityEntry<POSITION_DETAIL> positionDetailToRemove = context.Entry(posDetail);
                positionDetailToRemove.CurrentValues.SetValues(new
                {
                    ChangeDate = DateTime.Now,
                    ChangeType = "D"
                });
            }
            EntityEntry<POSITION> positionToRemove = context.Entry(position);
            positionToRemove.CurrentValues.SetValues(new 
            {
                ChangeDate = DateTime.Now,
                ChangeType = "D"
            });
            return position;
        }

        private static POSITION GetPrevailingPosition(Guid accountId, DateTime statementDate, AccMappedSecurity mappedSecurity, newportMasterContext context)
        {
            return (context.POSITION
                .Include(x => x.POSITION_DETAIL)
                .Include(x => x.POSITION_DETAIL).ThenInclude(x => x.POSITION_BOND)
                .Include(x => x.POSITION_DETAIL).ThenInclude(x => x.POSITION_FX)
                .Include(x => x.POSITION_DETAIL).ThenInclude(x => x.POSITION_OPTION)
                .Include(x => x.POSITION_DETAIL).ThenInclude(x => x.POSITION_PRICE)
                .OrderByDescending(x => x.DateStart)
                .FirstOrDefault(x => x.Account_UID == accountId 
                    && x.Security_UID == mappedSecurity.SecurityGuid 
                    && x.SecurityFirmID == mappedSecurity.FirmId 
                    && (x.DateStart.Date <= statementDate) && (!x.DateEnd.HasValue || x.DateEnd.Value.Date < statementDate) 
                    && x.ChangeType != "D" 
                    && x.POSITION_DETAIL.Any(pd => pd.Genesis == "FEED" &&
                                                pd.ChangeType != "D")));
        }


Get this bounty!!!