How to exclude a .NET 6 Minimal API from code coverage? - c#

I maintain a class library which contains several reference implementations to demonstrate how the library should be used. I have reference implementations for .Net Framework, core, .NET 5 and now I have added a reference implementation for .NET 6 using minimal APIs.
For all of my other reference implementations I have added the ExcludeFromCodeCoverage attribute using System.Diagnostics.CodeAnalysis to all of their containing classes. How would I do something similar for a .NET 6 minimal API?
My program.cs looks like this:
using Microsoft.AspNetCore.Mvc;
using SharedDataLayer.Repositories;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<PaymentRepository>();
var app = builder.Build();
app.MapGet("/Payments", ([FromServices] PaymentRepository repo) =>
{
return repo.GetPayments();
});
app.Run();

Your Program.cs shoud look like this:
using Microsoft.AspNetCore.Mvc;
using SharedDataLayer.Repositories;
using System.Diagnostics.CodeAnalysis;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<PaymentRepository>();
var app = builder.Build();
app.MapGet("/Payments", ([FromServices] PaymentRepository repo) =>
{
return repo.GetPayments();
});
app.Run();`
[ExcludeFromCodeCoverage]
public partial class Program { }

I've tested out the suggestions from #PanagiotisKanavos and #Tolvic in the comments on the initial question and can confirm that adding the following to the top of your program.cs does work and the file is excluded from code coverage.
using System.Diagnostics.CodeAnalysis;
[assembly: ExcludeFromCodeCoverage]

using System.Diagnostics.CodeAnalysis;
[assembly: ExcludeFromCodeCoverage]
worked for me

Related

How to add Startup.cs in existing project .net5

I have an .net5 project and in .csproj file I have this:
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
I added Microsoft.EntityFrameworkCore package to my prject.furturemore I created Dbcontext file like below:
using Domian;
using Microsoft.EntityFrameworkCore;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
namespace Mc2.CrudTest.Presentation.Front.Infrastructure
{
public class DataContext : DbContext
{
protected readonly IConfiguration Configuration;
public DataContext(IConfiguration configuration)
{
Configuration = configuration;
}
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
// connect to sql server with connection string from app settings
options.UseSqlServer(Configuration.GetConnectionString("SqlServerConnection"));
}
public DbSet<Customer> Customers { get; set; }
}
}
since there wasn't any startup.cs file in my project ,I created one this way:
the namespaces of IApplicationBuilder and IWebHostEnvironment coudn't find.
I dont know whether I can use startup.cs file like.net core.3.1 or I shouldn't use startup.cs file in .net5 anymore.
And my program.cs file was formed this way:
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Microsoft.Extensions.DependencyInjection;
namespace Mc2.CrudTest.Presentation.Front
{
public class Program
{
public static async Task Main(string[] args)
{
WebAssemblyHostBuilder builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.Services.AddScoped(_ => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
await builder.Build().RunAsync();
builder.Services.AddDbContext(options => options
}
}
}
In addtion my project is BlazorWebAssembly
First of all, don't use .NET 5. It reached End-of-Life on May 2022. That's almost a year ago. EOL means no support at all, for anything, from either Microsoft or NuGet authors. Not even security patches.
It was known from the start this would be a single-year or "Standard-Term" Support version (STS), supported only for 18 months. The Long-Term-Support version is .NET 6, supported until November 2024. LTS versions are supported for 3 years since release.
Second, you don't need Startup.cs in .NET 6 (or .NET 5). The methods found in Startup.cs were merged into Program.cs. You can write :
builder.Services.AddDbContext(options=>options
.UseSqlServer(builder.Configuration.GetConnectionString("SqlServerConnection")));
This is shown in all ASP.NET Core and EF Core tutorials, eg this Web API tutorial. In this tutorial, Program.cs contains :
using Microsoft.EntityFrameworkCore;
using TodoApi.Models;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddDbContext<TodoContext>(opt =>
opt.UseInMemoryDatabase("TodoList"));
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
Notice that even Program.Main is missing. That's the entire file. This is possible through a few new C# features: top-level statements and implied usings.
If you don't like this style you can use --use-program-main to generate a Program.cs and Main method
First off, of course you should update to .NET6 or .NET7 if you can[1]. But if that's not practical for whatever reason, then of course you can use startup.cs. In fact I prefer to as well, out of habit (you can use it in .NET6 too; not sure about 7 but I assume so).
You can define startup.cs more or less the way you do, but you do need the right using's:
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Hosting;
Less obviously, in your program.cs you need
using Microsoft.AspNetCore;
...
public static async Task Main(string[] args)
{
...
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
...
}
Edit - After discussing with Amir in comments below it seems the scope of this problem is pretty different from what was originally asked. I suggest you spend some time in an example Blazor solution with a separate hosting project from the webassembly SPA project. Things will make a lot more sense after that.
[1] Microsoft IMO has done the world a disservice with its post-Framework policy of introducing breaking changes into each ASP.NET version so liberally. It's not always just a matter of retargeting. And that's especially true of Blazor which is still so immature. Certainly if security is a concern for this application you should be doing everything you can to upgrade, but in the real world isn't always that simple.
you should add blazerServerApp project which consist of program.cs and startup.cs which you looking for as shown below.

How to get your Azure Table Connection String (json) in the latest version of ASP.NET MVC

I noticed that Microsoft has made some code library changes to MVC\Azure Storage that seem to have broken my MVC code. I'm using a repository pattern. I can't seem to get the new documentation figured out.
Here is a basic example of what I am trying to do. Oh, and if you're feeling extra helpful a basic example of it with a set of generics <T> would be even more appreciated. There's just too many wrong answers on the Internet to sort through. I'm using Ninject for Dependency injection into my service layer. I tried to make my example as simple as possible so that everyone can see my using statements and basic code...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Table;
using Microsoft.Framework.Configuration;
//Intellisense paints json red
//using Microsoft.Framework.ConfigurationModel.Json;
//this one paints my IConfiguration interface red
using Microsoft.Framework.ConfigurationModel;
namespace Farmantix.Amity.Website.Repositories
{
public class TableStorageRepository
{
CloudStorageAccount storageAccount;
IConfiguration config;
CloudTableClient tableClient;
CloudTable table;
public TableStorageRepository()
{
var configurationBuilder = new ConfigurationBuilder().AddJsonFile("config.json");
var configuration = configurationBuilder.Build();
storageAccount = CloudStorageAccount.Parse(
config.Get("MicrosoftAzureStorage:[Name of Connection String]"));
}
}
}

UseSqlServer method missing MVC 6

I am trying to implement Entity Framework 7 in MVC 6, and on this page here it says to do
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<MusicStoreContext>(options =>
options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));
But for me, the UseSqlServer method isn't visible? Anyone know how to make it visible? Or is this an old way of configuring entity framework?
My startup.cs file looks like this
using FluentValidation;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.Framework.ConfigurationModel;
using Microsoft.Framework.DependencyInjection;
namespace me.namespace.project
{
public class Startup
{
public static IConfiguration Configuration { get; set; }
public Startup(IHostingEnvironment env)
{
// Setup configuration sources.
Configuration = new Configuration()
.AddJsonFile("config.json")
.AddEnvironmentVariables();
}
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
// entity framework
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<DataContext>();
}
}
}
Install Microsoft.EntityFrameworkCore.SqlServer 1.0.1 package works for me
Version of Microsoft.EntityFrameworkCore is 1.1.0
UseSqlServer is an extension method in the namespace Microsoft.Data.Entity so you need to import that in your code, like this:
using Microsoft.EntityFrameworkCore;
Since this has been posted, assemblies have been renamed. As part of EntityFrameworkCore you now need to add a using statement the following
using Microsoft.EntityFrameworkCore;
And the .UseSqlServer extension method to configure your context will become available
It's a NuGet Packages Problem
Install the following Packages and with its Proper Versions
1. Microsoft.EntityFrameworkCore(Latest Version)
2. Microsoft.EntityFrameworkCore.SqlServer(1.0.4 Version)

LightInject SignalR missing .RegisterHubs method

I just started using LightInject for my MVC project and it's working just fine.
But i wanted to use it for my SignalR hubs too. So i followed the instructions at http://www.lightinject.net/#signalr. However i cannot see the method ServiceContainer.RegisterHubs anywhere. I have installed the LightInject, LightInject.Mvc and LightInject.SignalR dll's.
using log4net.Config;
using LightInject;
using Microsoft.Owin;
using Owin;
using MvcProject;
using MvcProject.ApplicationServices.Interfaces.EventSignups;
[assembly: XmlConfigurator(ConfigFile = "Web.config", Watch = true)]
[assembly: OwinStartup(typeof (Startup))]
namespace MvcProject
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
//ConfigureAuth(app);
var container = new ServiceContainer();
container.Register<IEventSignupService>();
container.Register<IViewModelRetrieverEventCommentService>();
container.Register<IViewModelRetrieverEventService>();
container.RegisterHubs(); //cannot see method
app.MapSignalR(container.EnableSignalR());
}
}
}
Anyone knows what i'm doing wrong?
Unfortunately this is just bad documentation. The method does not exist and never existed. You have to register each and every hub manually within your LightInject Container.
Also, be aware of issues I've encountered by changing the DependencyResolver within SignalR for LightInject.
PS: I know my answer is late but still tought it could be useful for people searching for the same issue.

Wiring up fluentvalidation with Nancy and Ninject

I am using Nancy with Ninject as IoC. All is fine. I now need to add FluentValidation.
How do I go about wiring Nancy to use FluentValidation via Ninject?
I see there's a NuGet package Ninject.Fluent.Validation but I can't find any documentation or example on how to use it.
The demo project on NancyFx website uses the TinyIoC so it's not useful to me.
UPDATE: this is what I have tried to do:
var createRequest = this.BindAndValidate<CreateRequest>();
if (!ModelValidationResult.IsValid)
{
return Response.AsJson(ModelValidationResult, HttpStatusCode.BadRequest);
}
The model is always valid (even if there should be errors reported by the CreateConsumerRequestValidator).
This is what I have added in my Ninject bootstrapper:
Bind<IModelValidatorFactory>().To<FluentValidationValidatorFactory>().InSingletonScope();
AssemblyScanner.FindValidatorsInAssemblyContaining<CreateRequestValidator>()
.ForEach(match => Bind(match.InterfaceType).To(match.ValidatorType));
The IModelValidatorFactory is wired up automatically by Nancy from v0.12 (see here Configure NancyFx with Fluent Validation) - you just need to wire up your validators.
This works with Nancy 0.23
using FluentValidation;
using Ninject.Extensions.Conventions;
using Ninject.Modules;
public class ValidatorModule : NinjectModule
{
public override void Load()
{
this.Kernel.Bind(
x =>
x.FromAssembliesMatching("YourNameSpace.*")
.SelectAllClasses()
.InheritedFrom<IValidator>()
.BindAllInterfaces());
}
}

Categories

Resources