Visual Studio Unit test crashes - c#

I suddenly get errors while running the unit test for C# program in visual studio.
I guess the error appears after I added the System.Numerics.Vectors NuGet package, howewert the test I run does not use it yet.
Before adding it, the test run was fine.
I get following error:
for more details on managing these settings.
[1/13/2018 6:37:32 PM Informational] Test Adapter for Google Test: Test discovery starting...
[1/13/2018 6:37:32 PM Error] ERROR: Exception while discovering tests: System.AggregateException: One or more errors occurred. ---> System.NullReferenceException: Object reference not set to an instance of an object.
at GoogleTestAdapter.DiaResolver.PeParser.<>c__DisplayClass4_0.<ProcessImports>b__0(LoadedImage image)
at GoogleTestAdapter.DiaResolver.PeParser.ParsePeFile(String executable, ILogger logger, Action`1 action)
at GoogleTestAdapter.DiaResolver.PeParser.ProcessImports(String executable, ILogger logger, Func`2 predicate)
at GoogleTestAdapter.DiaResolver.PeParser.FindImport(String executable, String import, StringComparison comparisonType, ILogger logger)
at GoogleTestAdapter.GoogleTestDiscoverer.IsGoogleTestExecutable(String executable, String customRegex, ILogger logger)
at GoogleTestAdapter.GoogleTestDiscoverer.<>c__DisplayClass6_0.<DiscoverTests>b__0()
at GoogleTestAdapter.Settings.SettingsWrapper.ExecuteWithSettingsForExecutable(String executable, Action action, ILogger logger)
at GoogleTestAdapter.GoogleTestDiscoverer.DiscoverTests(String executable, ITestFrameworkReporter reporter, SettingsWrapper settings, ILogger logger, IDiaResolverFactory diaResolverFactory)
at GoogleTestAdapter.GoogleTestDiscoverer.<>c__DisplayClass5_0.<DiscoverTests>b__1()
at System.Threading.Tasks.Task.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
--- End of inner exception stack trace ---
at System.Threading.Tasks.Task.WaitAll(Task[] tasks, Int32 millisecondsTimeout, CancellationToken cancellationToken)
at GoogleTestAdapter.Helpers.Utils.SpawnAndWait(Action[] actions, Int32 timeoutInMs)
at GoogleTestAdapter.GoogleTestDiscoverer.DiscoverTests(IEnumerable`1 executables, ITestFrameworkReporter reporter)
at GoogleTestAdapter.TestAdapter.TestDiscoverer.DiscoverTests(IEnumerable`1 executables, IDiscoveryContext discoveryContext, IMessageLogger logger, ITestCaseDiscoverySink discoverySink)
---> (Inner Exception #0) System.NullReferenceException: Object reference not set to an instance of an object.
at GoogleTestAdapter.DiaResolver.PeParser.<>c__DisplayClass4_0.<ProcessImports>b__0(LoadedImage image)
at GoogleTestAdapter.DiaResolver.PeParser.ParsePeFile(String executable, ILogger logger, Action`1 action)
at GoogleTestAdapter.DiaResolver.PeParser.ProcessImports(String executable, ILogger logger, Func`2 predicate)
at GoogleTestAdapter.DiaResolver.PeParser.FindImport(String executable, String import, StringComparison comparisonType, ILogger logger)
at GoogleTestAdapter.GoogleTestDiscoverer.IsGoogleTestExecutable(String executable, String customRegex, ILogger logger)
at GoogleTestAdapter.GoogleTestDiscoverer.<>c__DisplayClass6_0.<DiscoverTests>b__0()
at GoogleTestAdapter.Settings.SettingsWrapper.ExecuteWithSettingsForExecutable(String executable, Action action, ILogger logger)
at GoogleTestAdapter.GoogleTestDiscoverer.DiscoverTests(String executable, ITestFrameworkReporter reporter, SettingsWrapper settings, ILogger logger, IDiaResolverFactory diaResolverFactory)
at GoogleTestAdapter.GoogleTestDiscoverer.<>c__DisplayClass5_0.<DiscoverTests>b__1()
at System.Threading.Tasks.Task.InnerInvoke()
at System.Threading.Tasks.Task.Execute()<---
can someone give me advice pls?
To see it, it is enough to do :
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
Console.WriteLine("hello");
}
}

Related

How to implement ILogger in python

I am trying to create a concrete implementation of ILogger in python using the build in python logger.
However, when I try to implement the ILogger interface, I'm getting the exception
Method 'Log' in type 'Microsoft.Extensions.Logging.PyLogger' from assembly 'Python.Runtime.Dynamic, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' does not have an implementation.
The code so far is simple and incomplete
class PyLogger(ILogger):
__namespace__ = "Microsoft.Extensions.Logging"
def Log(self, logLevel, eventId, state, exception, formatter):
print(logLevel, eventId, state, exception, formatter)
return
def IsEnabled(self):
return True
I don't understand why it doesn't like my Log definition.
When I inspect ILogger.Log it get the following, which looks complete.
>>> inspect.signature(ILogger.Log)
<Signature (logLevel, eventId, state, exception, formatter)>

PlatformNotSupportedException thrown in MAUI on macOS when connecting Azure IoT Hub

I am exploring MAUI on macOS. I am porting a WPF application to evaluate the functionalities. The application is connecting to an Azure IoT Hub instance.
Here is the section of code that seems problematic:
var iotHubConnectionStringBuilder = IotHubConnectionStringBuilder.Create("HostName=<iotHubConnectionString>");
var registryManager = RegistryManager.CreateFromConnectionString(iotHubConnectionStringBuilder.ToString());
When calling CreateFromConnectionString, the following exception is thrown:
Unhandled Exception:
System.PlatformNotSupportedException: Operation is not supported on this platform.
at System.Net.Http.NSUrlSessionHandler.set_SslProtocols(SslProtocols value)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
--- End of stack trace from previous location ---
at System.Net.Http.HttpClientHandler.InvokeNativeHandlerMethod(String name, Object[] parameters)
at System.Net.Http.HttpClientHandler.SetSslProtocols(SslProtocols value)
at System.Net.Http.HttpClientHandler.set_SslProtocols(SslProtocols value)
at Microsoft.Azure.Devices.Client.Transport.HttpClientHelper..ctor(Uri baseAddress, IAuthorizationProvider authenticationHeaderProvider, IDictionary`2 defaultErrorMapping, TimeSpan timeout, Action`1 preRequestActionForAllRequests, X509Certificate2 clientCert, HttpClientHandler httpClientHandler, ProductInfo productInfo, IWebProxy proxy, Boolean isClientPrimaryTransportHandler)
at Microsoft.Azure.Devices.Client.Transport.HttpTransportHandler..ctor(IPipelineContext context, IotHubConnectionString iotHubConnectionString, Http1TransportSettings transportSettings, HttpClientHandler httpClientHandler, Boolean isClientPrimaryTransportHandler)
at Microsoft.Azure.Devices.Client.InternalClient..ctor(IotHubConnectionString iotHubConnectionString, ITransportSettings[] transportSettings, IDeviceClientPipelineBuilder pipelineBuilder, ClientOptions options)
at Microsoft.Azure.Devices.Client.ClientFactory.CreateFromConnectionString(String connectionString, IAuthenticationMethod authenticationMethod, ITransportSettings[] transportSettings, IDeviceClientPipelineBuilder pipelineBuilder, ClientOptions options)
at Microsoft.Azure.Devices.Client.ClientFactory.CreateFromConnectionString(String connectionString, IAuthenticationMethod authenticationMethod, TransportType transportType, IDeviceClientPipelineBuilder pipelineBuilder, ClientOptions options)
at Microsoft.Azure.Devices.Client.ClientFactory.CreateFromConnectionString(String connectionString, TransportType transportType, ClientOptions options)
at Microsoft.Azure.Devices.Client.ClientFactory.CreateFromConnectionString(String connectionString, ClientOptions options)
at Microsoft.Azure.Devices.Client.DeviceClient.<>c__DisplayClass8_0.<CreateFromConnectionString>b__0()
at Microsoft.Azure.Devices.Client.DeviceClient.Create(Func`1 internalClientCreator)
at Microsoft.Azure.Devices.Client.DeviceClient.CreateFromConnectionString(String connectionString, ClientOptions options)
[..]
I have played with the different HttpClient implementation without any positive outcome. And, surprinsingly enough, it exhibits the same callstack, with NSUrlSessionHandler.set_SslProtocols on top of it:
Question
Why is this error thrown and how can it be fixed?
I was using Visual Studio 2022 for Mac version 17.3 Preview 1. After updating to Visual Studio 2022 for Mac v17.3 Preview 1.1 as well as the .net MAUI workload, it worked.
I let the HttpClient implementation to NSUrlSession.
I am not sure the exact reason why it works now but I assume these issues are bound to happen when using preview products.

Failing Container orchestration on the Microsoft Service Fabric

i tried to containerize a simple Service Fabric Project into a Service Fabric Container Project.
I used the Create your first Service Fabric container application on Windows manual (https://github.com/MicrosoftDocs/azure-docs/blob/master/articles/service-fabric/service-fabric-get-started-containers.md).
So at the first step i defined my docker image from VotingData service. I just made an own solution out of the service and just added the dockerfile and built it.
FROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS build-env
WORKDIR /app
ADD . .
RUN dotnet publish \
-c Release \
-o ./output
FROM mcr.microsoft.com/dotnet/core/aspnet:3.1
WORKDIR /app
COPY --from=build-env /app/output .
EXPOSE 8000
ENTRYPOINT VotingData.exe
Then i pushed it into my azure image registry, and added it into my Service Fabric application as a container service, like the steps in the manual.
After Starting the SF cluster the Application and nodes are starting in the SF explorer after a while. The Problem is, the local VotingData container is just running for a view seconds.
When i debug into the error exited container i get this log:
$ docker logs sf-4-1a5af364-f71e-4d06-b713-76a6150f92db_d9bda8c5-561c-47c1-88f3-15391d3d2ae3
[17:34:34 INF] Start register Service
Unhandled exception. System.TypeInitializationException: The type initializer for 'System.Fabric.Common.AppTrace' threw an exception.
---> System.DllNotFoundException: Unable to load DLL 'FabricCommon.dll' or one of its dependencies: The specified module could not be found. (0x8007007E)
at System.Fabric.Interop.NativeCommon.FabricGetConfigStore(Guid& riid, IFabricConfigStoreUpdateHandler2 updateHandler)
at System.Fabric.Common.NativeConfigStore.CreateHelper(IFabricConfigStoreUpdateHandler2 updateHandler)
at System.Fabric.Common.NativeConfigStore.<>c__DisplayClass3_0.<FabricGetConfigStore>b__0()
at System.Fabric.Interop.Utility.WrapNativeSyncInvoke[TResult](Func`1 func, String functionTag, String functionArgs)
at System.Fabric.Interop.Utility.<>c__DisplayClass27_0`1.<WrapNativeSyncInvokeInMTA>b__0()
at System.Fabric.Interop.Utility.RunInMTA[TResult](Func`1 func)
at System.Fabric.Interop.Utility.WrapNativeSyncInvokeInMTA[TResult](Func`1 func, String functionTag)
at System.Fabric.Common.NativeConfigStore.FabricGetConfigStore(IConfigStoreUpdateHandler2 updateHandler)
at System.Fabric.Common.Tracing.TraceConfig.InitializeFromConfigStore(Boolean forceUpdate)
at System.Fabric.Common.AppTrace..cctor()
--- End of inner exception stack trace ---
at System.Fabric.Common.AppTrace.get_TraceSource()
at System.Fabric.Interop.AsyncCallOutAdapter2`1.Start(CancellationToken cancellationToken)
at System.Fabric.Interop.AsyncCallOutAdapter2`1.WrapNativeAsyncInvoke(String functionTag, Func`2 beginFunc, Func`2 endFunc, InteropExceptionTracePolicy tracePolicy, CancellationToken cancellationToken, Boolean runContinuationsAsynchronously)
at System.Fabric.Interop.Utility.WrapNativeAsyncInvoke[TResult](Func`2 beginFunc, Func`2 endFunc, InteropExceptionTracePolicy tracePolicy, CancellationToken cancellationToken, Boolean runContinuationsAsynchronously, String functionTag)
at System.Fabric.Interop.Utility.WrapNativeAsyncInvoke[TResult](Func`2 beginFunc, Func`2 endFunc, InteropExceptionTracePolicy tracePolicy, CancellationToken cancellationToken, String functionTag)
at System.Fabric.Interop.Utility.<>c__DisplayClass20_0`1.<WrapNativeAsyncInvokeInMTA>b__0()
at System.Fabric.Interop.Utility.RunInMTA[TResult](Func`1 func)
at System.Fabric.Interop.Utility.WrapNativeAsyncInvokeInMTA[TResult](Func`2 beginFunc, Func`2 endFunc, InteropExceptionTracePolicy tracePolicy, CancellationToken cancellationToken, String functionTag)
at System.Fabric.Interop.Utility.WrapNativeAsyncInvokeInMTA[TResult](Func`2 beginFunc, Func`2 endFunc, CancellationToken cancellationToken, String functionTag)
at System.Fabric.FabricRuntime.NativeFabricRuntimeFactory.GetNodeContextAsync(TimeSpan timeout, CancellationToken cancellationToken)
at System.Fabric.FabricRuntime.GetNodeContextAsync(TimeSpan timeout, CancellationToken cancellationToken)
at Microsoft.ServiceFabric.Services.Runtime.RuntimeContext.GetOrCreateAsync(TimeSpan timeout, CancellationToken cancellationToken)
at Microsoft.ServiceFabric.Services.Runtime.ServiceRuntime.RegisterServiceAsync(String serviceTypeName, Func`2 serviceFactory, TimeSpan timeout, CancellationToken cancellationToken)
at VotingData.Program.Main() in C:\app\Program.cs:line 37
So in my eyes the problem is, that the SF cannot register the containerized service in the program.cs in the main method when it calls registerServiceAsync(). But the image is missing the dependency to the SF or something else.
private static void Main()
{
try
{
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.MinimumLevel.Information()
.WriteTo.File(#"c:\temp\VotingDataLog.txt",
rollingInterval: RollingInterval.Day,
rollOnFileSizeLimit: true)
.CreateLogger();
// The ServiceManifest.XML file defines one or more service type names.
// Registering a service maps a service type name to a .NET type.
// When Service Fabric creates an instance of this service type,
// an instance of the class is created in this host process.
Log.ForContext<VotingData>().Information("Start register Service");
ServiceRuntime.RegisterServiceAsync("VotingDataType",
context => new VotingData(context)).GetAwaiter().GetResult();
Log.ForContext<VotingData>().Information("Service registered");
ServiceEventSource.Current.ServiceTypeRegistered(Process.GetCurrentProcess().Id, typeof(VotingData).Name);
// Prevents this host process from terminating so services keep running.
Thread.Sleep(Timeout.Infinite);
}
catch (Exception e)
{
ServiceEventSource.Current.ServiceHostInitializationFailed(e.ToString());
throw;
}
I also tried another option, so i added an image with the SF runntime.
I used the edalx/servicefabric-runtime:dotnetcore-3.1.2 image from https://github.com/edalx/servicefabric-runtime
FROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS build-env
WORKDIR /app
ADD . .
RUN dotnet publish \
-c Release \
-o ./output
FROM edalx/servicefabric-runtime:dotnetcore-3.1.2
WORKDIR /app
COPY --from=build-env /app/output .
EXPOSE 8000
ENTRYPOINT VotingData.exe
Then i got this error
$ docker logs sf-3-ed4968b2-0783-4550-9e26-8fe2c4879851_dcdc6636-359d-40ca-b499-e0e3ad805dca
[16:44:51 INF] Start register Service
Unhandled exception. System.Fabric.FabricException: An error occurred during this operation. Please check the trace logs for more details.
---> System.Runtime.InteropServices.COMException (0x80071CC0): 0x80071CC0
at System.Fabric.Interop.NativeRuntime.FabricEndGetNodeContext(IFabricAsyncOperationContext context)
at System.Fabric.FabricRuntime.NativeFabricRuntimeFactory.GetNodeContextEndWrapper(IFabricAsyncOperationContext context)
at System.Fabric.Interop.AsyncCallOutAdapter2`1.Finish(IFabricAsyncOperationContext context, Boolean expectedCompletedSynchronously)
--- End of inner exception stack trace ---
at Microsoft.ServiceFabric.Services.Runtime.RuntimeContext.GetOrCreateAsync(TimeSpan timeout, CancellationToken cancellationToken)
at Microsoft.ServiceFabric.Services.Runtime.ServiceRuntime.RegisterServiceAsync(String serviceTypeName, Func`2 serviceFactory, TimeSpan timeout, CancellationToken cancellationToken)
at VotingData.Program.Main() in C:\app\Program.cs:line 37
So the dependency was there but the main method errored when it called registerServiceAsync().

ReflectionTypeLoadException exception in Asp.Net Core in-memory TestServer

I create a IWebHostBuilder like so:
public IWebHostBuilder GetWebHostBuilder()
{
return new WebHostBuilder().UseContentRoot(_contentRoot)
.ConfigureServices(InitializeServiceCollection)
.UseEnvironment(_environment)
.UseConfiguration(GetConfiguration())
.UseStartup(typeof(TStartup));
}
Here, the InitializeServiceCollection is implemented like so:
private void InitializeServiceCollection(IServiceCollection services)
{
var manager = new ApplicationPartManager();
manager.ApplicationParts.Add(new AssemblyPart(_assembly));
manager.FeatureProviders.Add(new ControllerFeatureProvider());
manager.FeatureProviders.Add(new ViewComponentFeatureProvider());
services.AddSingleton(manager);
}
Then I create the TestServer like so:
var myTestServer = new TestServer(GetWebHostBuilder());
Here I get the exception (full exception below). It gets thrown at services.AddAutoMapper(); method call in the system under test. However, when I run the system under test on it's own and test it manually with Postman, it's working fine and the object mapping with Automapper is working well too. It just raises the exception in the integration test.
Full exception:
System.AggregateException : One or more errors occurred. (Unable to load one or more of the requested types.
Could not load type 'Microsoft.EntityFrameworkCore.Metadata.Internal.RelationalFullAnnotationNames' from assembly 'Microsoft.EntityFrameworkCore.Relational, Version=2.2.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'.) (The following constructor parameters did not have matching fixture data: TestFixture fixture)
---- System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types.
Could not load type 'Microsoft.EntityFrameworkCore.Metadata.Internal.RelationalFullAnnotationNames' from assembly 'Microsoft.EntityFrameworkCore.Relational, Version=2.2.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'.
---- The following constructor parameters did not have matching fixture data: TestFixture fixture
----- Inner Stack Trace #1 (System.Reflection.ReflectionTypeLoadException) -----
at System.Reflection.RuntimeModule.GetTypes(RuntimeModule module)
at System.Reflection.RuntimeAssembly.get_DefinedTypes()
at System.Linq.Enumerable.SelectManySingleSelectorIterator`2.ToArray()
at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
at AutoMapper.ServiceCollectionExtensions.AddAutoMapperClasses(IServiceCollection services, Action`2 configAction, IEnumerable`1 assembliesToScan) in xxx\automapper-extensions-microsoft-dependencyinjectio\src\AutoMapper.Extensions.Microsoft.DependencyInjection\ServiceCollectionExtensions.cs:line 72
at xxx.Startup.ConfigureServices(IServiceCollection services) in xxx\Startup.cs:line 35
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Hosting.ConventionBasedStartup.ConfigureServices(IServiceCollection services)
at Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureApplicationServices()
at Microsoft.AspNetCore.Hosting.Internal.WebHost.Initialize()
at Microsoft.AspNetCore.Hosting.WebHostBuilder.Build()
at Microsoft.AspNetCore.TestHost.TestServer..ctor(IWebHostBuilder builder, IFeatureCollection featureCollection)
at xxx.Tests.TestFixture.InitializeServer() in xxx.Tests\TestFixture.cs:line 67
at xxx.Tests.TestFixture..ctor() in xxx.Tests\TestFixture.cs:line 31
----- Inner Stack Trace #2 (Xunit.Sdk.TestClassException) -----
So, I managed to resolve the issue by replacing services.AddAutoMapper() with services.AddAutoMapper(Type[] types) overload. Not sure what is wrong with the original method, but in order to avoid that reflective call on the assemblies, I used this overload and it's working now.

add migration failed when DbContext in sperate project

I have a project with different layers: web, services, model, data each one has a different project in the same solution. The application, compiles and runs OK. But when I tried to implement migration I got the following error
dnx . ef migration add MigrationFile
System.InvalidOperationException: No DbContext was found. Ensure that you're using the correct assembly and that the type is neither abstract nor generic.
at Microsoft.Data.Entity.Commands.ContextTool.SelectType(IEnumerable`1 types, String name)
at Microsoft.Data.Entity.Commands.MigrationTool.GetContextType(String name)
at Microsoft.Data.Entity.Commands.MigrationTool.AddMigration(String migrationName, String contextTypeName, String startupAssemblyName, String rootNamespace,String projectDir)
at Microsoft.Data.Entity.Commands.Program.<>c__DisplayClass12_0.<AddMigration>b__0()
at Microsoft.Data.Entity.Commands.Program.Execute(String startupProject, Func`1 invoke)
at Microsoft.Framework.Runtime.Common.CommandLine.CommandLineApplication.Execute(String[] args)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.Framework.Runtime.Common.EntryPointExecutor.Execute(Assembly assembly, String[] args, IServiceProvider serviceProvider)
at Microsoft.Framework.ApplicationHost.Program.ExecuteMain(DefaultHost host,String applicationName, String[] args)
at Microsoft.Framework.ApplicationHost.Program.Main(String[] args)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.Framework.Runtime.Common.EntryPointExecutor.Execute(Assembly assembly, String[] args, IServiceProvider serviceProvider)
at dnx.host.Bootstrapper.RunAsync(List`1 args, IRuntimeEnvironment env, FrameworkName targetFramework)
at dnx.host.RuntimeBootstrapper.ExecuteAsync(String[] args, FrameworkName targetFramework)
at dnx.host.RuntimeBootstrapper.Execute(String[] args, FrameworkName targetFramework)
I'm using this answer as a reference.
Maybe your project has more than one DbContext or you have not turned on the migrations.
If you have more than one Context, you will want to enable and add migrations for each Context separately:
add-migration -ConfigurationTypeName MyProject.MigrationsFolder.Configuration "migrationName"
This code will add a new Migration based on your Context and using the Configuration class associated to it. The following code will update the database associated with the Configuration class.
update-database -ConfigurationTypeName MyProject.MigrationsFolder.Configuration
the commands must be like this
- dnu restore
cd the project which contain the context path
dnx . ef migration add -c ContextName - s StartupProjectName
try it and if this work let me know, thnx ^^

Categories