I tried to make unit tests for my project, but I ran into the problem of missing testhost.deps.json, although it should have been installed with Microsoft.AspNetCore.Mvc.Testing. As I was told the error may be related to shadow copy, but no matter what I tried to do the error is still displayed just during the creation of the client.
How do I fix this error? Thank you in advance for your answer.
System.InvalidOperationException : Can't find 'C:\Users\flybe\OneDrive\Desktop\HomeworkProject\HomeworkTest\bin\Debug\net7.0\testhost.deps.json'.
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.VisualStudio.TestPlatform.TestHost;
namespace HomeworkTest
{
public class UnitTest1 :IClassFixture<WebApplicationFactory<Program>>
{
private readonly WebApplicationFactory<Program> _factory;
public UnitTest1(WebApplicationFactory<Program> factory)
{
_factory = factory;
}
[Fact]
public void Test1()
{
var client = _factory.CreateClient();
}
}
}
I tried to repeat what was in the training video. I also tried doing a test according to the documentation and the JetBrains article, where this problem was solved with ReSharper, but nothing helped.
Make sure testhost.deps.json file exists in the bin folder. if it's missing make sure you have
<PreserveCompilationContext>true</PreserveCompilationContext>
in your .csproj file.
and if that's not work try to remove the below line from your code.
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
Related
I'm new to C# and by extension, Rider and this is quite strange to me.
I have a controller with several mappings - only showing the first one, but the problem is the same for all of them.
The application works fine, each of the individual endpoints does its job as expected when triggered by Postman, but for some reason the method names are greyed out and Rider keeps suggesting removing them because they are "unused".
{
[ApiController]
[Route("")]
public class HomeController
{
private readonly IToDoService _toDoService;
public HomeController(IToDoService toDoService)
{
_toDoService = toDoService;
}
[HttpGet("")]
[HttpGet("/list")]
public ActionResult<List<ToDo>> ShowTodos()
{
var todos = _toDoService.GetAllToDos();
return todos;
}
Any ideas on how to force Rider to recognize the methods and remove related warnings?
Thanks in advance.
As the other comments already pointed out, this is a limitation of static code analysis.
But since I personally want to have a Solution free of R# warnings, I explicitly decorate classes like this (e. g. controllers) with the [UsedImplicitly] attribute from the JetBrains.Annotations NuGet package.
I have a class Library, I want to log to System.Diagnostics if host assembly is in debug (My class library is always in release since its downloaded from nuget).
Tried this
var debug =
Assembly.GetEntryAssembly()
.GetCustomAttributes()
.OfType<DebuggableAttribute>()
.Any(a => a.IsJITTrackingEnabled);
Problem is GetEntryAssembly return null, and both Executing and Calling assmebly methods return my class library assemly which is always in releae as stated above
Any ideas how to determin from a class library built in release if the hosting assembly is in debug?
edit: When downvoting, please specify why. Anyway,
Enviroment.UserInteractive returns true when you are using IIS Express but not IIS so its almost what I want. But you can use IIS to host your debug enviroment too and then it will not work. Any ideas how to detect if Host is in debug?
edit: This is what I have now, working, but not 100% bullet proof, wont work if you debug from IIS (Only works with debug from IIS express)
public class BusinessContext : IBusinessContext
{
private readonly DbContext _db;
private static readonly bool Debug;
static BusinessContext()
{
Debug = Environment.UserInteractive; //User is probably in debug from VS with IIS express
//Assembly.GetEntryAssembly()
//.GetCustomAttributes()
//.OfType<DebuggableAttribute>()
//.Any(a => a.IsJITTrackingEnabled);
}
public BusinessContext(DbContext db)
{
_db = db;
if (Debug)
_db.Database.Log = sql => Trace.WriteLine(sql);
}
...
}
I have 7 unit tests which fail when I run all tests from Solution level or from the test runner, but, when I run the tests from project level or from the project within the test runner they succeed.
I am trying to test that I can resolve an item from a Castle Windsor container once they have been installed.
[TestFixture]
public class Having_installed_the_request_processors
{
private IWindsorContainer _container;
[SetUp]
public void Setup()
{
_container = new WindsorContainer();
_container.Install(FromAssembly.Containing<RequestProcessorInstaller>());
}
[TearDown]
public void Teardown()
{
((WindsorContainer)this._container).Dispose();
_container = null;
}
[Test]
public void can_resolve_the_job_status_request_processor()
{
Assert.That(_container.Resolve<IJobStatusRequestProcessor>(), Is.Not.Null);
}
}
This is the error returned:
SetUp : Castle.MicroKernel.SubSystems.Conversion.ConverterException : Could not convert string 'Castle.Services.Logging.Log4netIntegration.Log4netFactory,Castle.Services.Logging.Log4netIntegration,Version=3.3.0.0, Culture=neutral,PublicKeyToken=407dd0808d44fbdc' to a type. Assembly was not found. Make sure it was deployed and the name was not mistyped.
As far as I can see the code in my test project is the same as my production code (which appears to function as expected).
Do you see any issues with the above?
Why does the test succeed in the aforementioned way?
I determined that this was due to the way in which the projects in the solution referenced each other, by changing the direction of some references it resolved the issue - thank you for looking
I tried to write a MVC application with ASP.net Identity from scratch.
To do so I followed two tutorials from Ben Foster (Tutorial Part1 and Tutorial Part2)
But I stuck at the second tutorial - Configuring UserManager. The following line doesn't work for me:
// configure the user manager
UserManagerFactory = () =>
{
var usermanager = new UserManager<AppUser>(
new UserStore<AppUser>(new AppDbContext()));
...
}
Visual Studio underlines
new AppDbContext()
and shows me the following message:
Argument type "MyProject.DbContext.AppDbContext" is not assignable to parameter type "System.Data.Entity.DbContext"
I don't understand why it doesn't work in my solution because I followed completely the tutorial. My AppDbContext looks like:
namespace MyProject.DbContext
{
using MyProject.Models;
using Microsoft.AspNet.Identity.EntityFramework;
public class AppDbContext : IdentityDbContext<User>
{
public AppDbContext()
: base("DefaultConnection")
{
}
}
}
My User class:
namespace MyProject.Models
{
using Microsoft.AspNet.Identity.EntityFramework;
public class User : IdentityUser
{
public string Name{ get; set; }
}
}
I also downloaded the source code from Ben and tried to run it and it works without any problems. I think it doesn't make any difference that all of my files aren't located in the same folder?!
I hope you can help me. It's really frustrating if a simple tutorial doesn't work as it should...
Regards, winklerrr
I solved the problem by removing all the references that had something to do with owin and ASP.net Identity and re-added them again.
I think, the problem was caused by a discrepancy between the referenced dlls and the actual used dlls... (Played to much with the package manager console.)
Your UserManager takes AppUser as generic type: UserManager<AppUser>, when you db-context takes User as generic param. AppUser and User are not the same classes.
Your user-defining class should be the same everywhere.
Unable to cast object of type 'MvcMiniProfiler.Data.EFProfiledDbConnection' to type 'System.Data.SqlClient.SqlConnection'.
I am trying to upgrade to MvcMiniProfiler 1.9.0 and I keep getting this when I call MiniProfilerEF.Initialize(). I have removed the system.data config section. I don't know what I am doing wrong. I have followed the steps on the site, but maybe I missed something?
I am using EF code first 4.1 and I am passing in the name of my connectionstring into a constructor to create my datacontext.
Web Activator
using Project.Web.App_Start;
using WebActivator;
[assembly: PreApplicationStartMethod(typeof(MiniProfiler), "Start")]
namespace Project.Web.App_Start {
public class MiniProfiler {
public static void Start()
{
if (Eco.Environment.IsDevelopment) {
MiniProfilerEF.Initialize();
}
}
}
}
StructureMap Registry:
using Project.Domain.Repositories;
using StructureMap.Configuration.DSL;
namespace Project.Web.DependencyResolution.Registries {
public class RepositoriesRegistry : Registry {
public RepositoriesRegistry() {
For<IProjectDataContext>().HybridHttpOrThreadLocalScoped().Use(() => new ProjectDataContext(Eco.Database.Name));
}
}
}
DataContext Constructor:
public ProjectDataContext(string nameOrConnectionString)
: base(nameOrConnectionString) {
Active = new Active(this);
}
I have removed system.data dataproviders fron my config since the documentation says I only need to call MiniProfilerEF.Initialize().
**Update
Previously in 1.7 MvcMiniProfiler I had to set the Database.DefaultConnectionFactory property, but I've removed that. The Database.DefaultConnectionFactory always comes back as SqlConnectionFactory, shouldn't it be ProfiledConnectionFactory or something like that?
I was seeing this same error. It drove me nuts but I finally figured it out. My issue had nothing to do with web.config, assemblies, Initialize_42 or Initialize(false) hacks or anything.
Here's where I went wrong...
I had enabled automatic application of migrations like this:
App_Start:
Database.SetInitializer(
new MigrateDatabaseToLatestVersion<DataContext, Migrations.Configuration>()
);
Migrations/Configuration.cs:
internal sealed class Configuration
: DbMigrationsConfiguration<Path.To.DataContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
}
}
And that was being triggered via WebActivator like this:
[assembly: WebActivator.PreApplicationStartMethod(
typeof(service_tracker_mvc.App_Start.DatabaseInitializer), "Start")]
I accidentally found that disabling this process resulted in the profiler working. The issue, as it happens, is that this init process was happening too soon. It normally happens during Application_Start (if you're not using this fancy WebActivator stuff) so I changed it to PostStart. Now it works:
▼▼▼▼
[assembly: WebActivator.PostApplicationStartMethod(
typeof(service_tracker_mvc.App_Start.DatabaseInitializer), "Start")]
I made the mistake of adding MiniProfiler.EF rather than MiniProfiler.EF6. Removing MiniProfiler.EF and replacing it with the EF6 version fixed my issue.
see https://stackoverflow.com/a/10814033/311289
This is caused by doing DB operations before initializing miniprofiler, put a breakpoint in the contstructor for your db context, and another on the MiniProfilerEF.Initialize(); line, and revise until the initialization is first.
The problem I see here, is that ProjectDataContext encapsulates some data context into property "Active", which could not be found by MvcProfiler proxy.
More than that, EFProfiledDbConnection is actually DbConnection child, but not SqlConnection's child. It is made in terms of abstraction to use different Db providers, like MySql, Postgres, etc. Please, try to review all variables in code, they should be DbConnection, but not SqlConnection (this is a provider of MsSql).
I had this same problem and the way I found to fix it was to move to Glimpse: http://getglimpse.com/. In my opinion, it is a lot better than miniprofiler, easy to use, complete, etc.