Use Application Insight with ASP API Core - asp.net-web-api

Community
I'm having troubles connecting Application Insights to my ASP WEB API Core.
Following standard manuals I still cannot find any record in my AppInsights account.
I used a lot of manuals, but the are pretty identical and describe how to configure App Insights for ASP Core (not API Core).
So I'm wondering is some special configuration (or nuget package or whatever) is required to make AppInsights track requests to my API service?
Once I cannot make AppInsights work out of box, I still can create instance of TelemetryClient and publish data manually, but this is not desirable in my case.
Important note: I'm using VS 2017 RC, Web APi Core project (csproj)
UPD
csproj file content:
<Project ToolsVersion="15.0" Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp1.0</TargetFramework>
<PreserveCompilationContext>true</PreserveCompilationContext>
</PropertyGroup>
<ItemGroup>
<ItemGroup>
<DotNetCliToolReference Include="Microsoft.DotNet.Watcher.Tools" Version="1.0.0-msbuild1-update1" />
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="1.0.0-msbuild1-final" />
<DotNetCliToolReference Include="Microsoft.Extensions.SecretManager.Tools" Version="1.0.0-msbuild2-update1" />
<DotNetCliToolReference Include="Microsoft.DotNet.Watcher.Tools" Version="1.0.0-msbuild1-update1" />
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="1.0.0-msbuild1-final" />
<DotNetCliToolReference Include="Microsoft.Extensions.SecretManager.Tools" Version="1.0.0-msbuild2-update1" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="1.0.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="1.0.1" />
<PackageReference Include="Microsoft.ApplicationInsights" Version="2.2.0" />
<PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="1.0.1" />
<PackageReference Include="Microsoft.AspNetCore.Cors" Version="1.0.1" />
<PackageReference Include="Microsoft.AspNetCore.ResponseCompression" Version="1.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="1.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="1.0.0-msbuild1-final" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning" Version="1.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="1.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="1.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer.Design" Version="1.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="1.0.0-msbuild2-final" />
<PackageReference Include="Microsoft.NETCore.App" Version="1.0.1" />
<PackageReference Include="Microsoft.AspNetCore.Diagnostics" Version="1.0.1" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.0.1" />
<PackageReference Include="Microsoft.AspNetCore.Routing" Version="1.0.1" />
<PackageReference Include="Microsoft.AspNetCore.Server.IISIntegration" Version="1.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Server.Kestrel" Version="1.0.1" />
<PackageReference Include="Microsoft.AspNetCore.Server.Kestrel.Https" Version="1.0.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="1.0.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="1.0.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="1.0.1" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="1.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="1.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.0.0" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="1.0.1" />
<PackageReference Include="Newtonsoft.Json" Version="9.0.1" />
<PackageReference Include="Swashbuckle.SwaggerGen" Version="6.0.0-beta901" />
<PackageReference Include="Swashbuckle.SwaggerUi" Version="6.0.0-beta901" />
</ItemGroup>
</Project>
Configuration in Startup.cs:
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
if (env.IsDevelopment())
{
// This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
builder.AddApplicationInsightsSettings(true);
}
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddApplicationInsightsTelemetry(Configuration);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug(LogLevel.Trace);
loggerFactory.AddConsole(LogLevel.Error);
app.UseApplicationInsightsExceptionTelemetry();
app.UseMvc();
}

If you're using the "new" asp.net core in VS2017, then the old instructions are wrong, as they are for the previous xproj based asp.net core implementations.
If you create a new asp.net core web project in VS2017, ApplicationInsights will be already installed from the start, and should be versions:
<PackageReference Include="Microsoft.ApplicationInsights" Version="2.2.0" />
<PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.0.0" />
(or newer, if the asp.net core team has updated them at all)
Those projects will already have Application Insights wired up as well, not in Startup.cs (that's the old way), but in Program.cs:
new WebHostBuilder()
...
.UseApplicationInsights() // this starts up appinsights in asp.net core now
...
.UseOtherThings();
and possibly in web templates, like:
#inject Microsoft.ApplicationInsights.AspNetCore.JavaScriptSnippet JavaScriptSnippet
at the top, and
#Html.Raw(JavaScriptSnippet.FullScript)
inside the bottom of the <head> tag.
if you're migrating from a previous version of asp.net core and app insights, you'll also have to remove things like:
#Html.ApplicationInsightsJavaScript(TelemetryConfiguration)
from _Layout.cshtml and replace them with the lines above, and you can remove all of the lines like:
app.UseApplicationInsightsExceptionTelemetry();
in Startup.cs (if you're using 2.x versions of the packages, i believe those items will all show deprecation warnings as well, as they're no longer needed)
VS2017's official release notes include this information as a section in the "known issues" for application insights

The issue is solved thanks to this article
There are 2 points I missed in my configuration:
1. In csproj should be referenced package "Microsoft.ApplicationInsights.AspNetCore" Version="2.0.0-beta1"
2. In class Startup, method Configure I missed to add app.UseApplicationInsightsRequestTelemetry();
When I changed what described above AppInsights has started to track all requests

Related

Class not registered exception: BitmapImage

When I try to create a BitmapImage instance (under WinUI 3) I get an exception that a necessary class is not registered. This is taking place within Visual Studio 2022, within an xUnit based test project.
The line throwing the exception is simply:
var retVal = new BitmapImage();
Given how simple the line is I'm wondering if there's something wrong with my xUnit project setup. Here it is:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0-windows10.0.19041.0</TargetFramework>
<RuntimeIdentifiers>win10-x64</RuntimeIdentifiers>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="FluentAssertions" Version="6.6.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.1.0" />
<PackageReference Include="xunit" Version="2.4.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.3">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="coverlet.collector" Version="3.1.2">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\MapLibraryWinApp\MapLibraryWinApp.csproj" />
</ItemGroup>
</Project>
Here's the project file for the library containing the code I'm trying to test:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0-windows10.0.19041.0</TargetFramework>
<TargetPlatformMinVersion>10.0.17763.0</TargetPlatformMinVersion>
<RuntimeIdentifiers>win10-x86;win10-x64;win10-arm64</RuntimeIdentifiers>
<UseWinUI>true</UseWinUI>
<Nullable>enable</Nullable>
<RootNamespace>J4JSoftware.MapLibrary</RootNamespace>
<AssemblyName>J4JSoftware.MapLibraryWinApp</AssemblyName>
<AssemblyTitle>Map Library (Windows Apps)</AssemblyTitle>
<Version>0.5.0</Version>
<Copyright>Copyright © Mark A. Olbert</Copyright>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.WindowsAppSDK" Version="1.0.3" />
<PackageReference Include="Microsoft.Windows.SDK.BuildTools" Version="10.0.22000.197" />
<PackageReference Include="Microsoft.AspNetCore.WebUtilities" Version="2.2.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\J4JLogging\J4JLogging\J4JLogging.csproj" />
<ProjectReference Include="..\MapLibrary\MapLibrary.csproj" />
</ItemGroup>
</Project>
I thought perhaps the test project might need to contain the <UseWinUI> tag, but adding it did not solve the problem.
You need to run an actual packaged WinUI app or deploy the Windows App SDK runtime along with a non-MSIX-packaged app to be able to use the WinUI types.
I am afraid it's not as simple as simply referencing the WinUI code from a standalone testrunner app.
Please refer to this blog post for an example of how to set up an actual app that runs the tests. Or avoid creating UI specific stuff in your unit tests.

Error processing method: 'Android.Gms.Tasks.CancellationToken Google.Places.FetchPhotoRequest::get_CancellationToken()'

I updated my project to use the Xamarin.Google.Android.Places v1.1.0.1 package from the NuGet package Manager.
But the project build fails after upgrading to the new Places package.
I have tried uninstalling and reinstalling the Places package and it's dependencies, deleting the bin and obj folders, but none of it really helped.
This is the following error that I amgetting while building the solution:
The "LinkAssemblies" task failed unexpectedly.
Mono.Linker.MarkException: Error processing method: 'Android.Gms.Tasks.CancellationToken Google.Places.FetchPhotoRequest::get_CancellationToken()' in assembly: 'Xamarin.Google.Places.dll' ---> Mono.Cecil.ResolutionException: Failed to resolve Android.Gms.Tasks.CancellationToken
The issue was that the latest stable GooglePlayServices APIs were not supported by the Xamarin.Google.Android.Places API. I added the following package versions of the required dependencies and the error was gone.
<PackageReference Include="Xamarin.Android.Volley" Version="1.1.1.1" PrivateAssets="all" />
<PackageReference Include="Xamarin.Google.Android.Places">
<Version>1.1.0.1</Version>
</PackageReference>
<PackageReference Include="Xamarin.Android.Glide" Version="4.9.0" PrivateAssets="all" />
<PackageReference Include="Xamarin.Android.Glide.DiskLruCache" Version="4.9.0" PrivateAssets="all" />
<PackageReference Include="Xamarin.Android.Glide.GifDecoder" Version="4.9.0" PrivateAssets="all" />
<PackageReference Include="Xamarin.GooglePlayServices.Base" Version="71.1601.0-preview3" PrivateAssets="all" />
<PackageReference Include="Xamarin.GooglePlayServices.Basement" Version="71.1610.0-preview3" PrivateAssets="all" />
<PackageReference Include="Xamarin.GooglePlayServices.Clearcut" Version="71.1600.0-preview3" PrivateAssets="all" />
<PackageReference Include="Xamarin.GooglePlayServices.Location" Version="71.1600.0-preview3" PrivateAssets="all" />
<PackageReference Include="Xamarin.GooglePlayServices.Maps" Version="71.1600.0-preview3" PrivateAssets="all" />
<PackageReference Include="Xamarin.GooglePlayServices.Phenotype" Version="71.1600.0-preview3" PrivateAssets="all" />
<PackageReference Include="Xamarin.GooglePlayServices.Places.PlaceReport" Version="71.1600.0-preview3" PrivateAssets="all" />
<PackageReference Include="Xamarin.GooglePlayServices.Tasks" Version="71.1601.0-preview3" PrivateAssets="all" />
<PackageReference Include="Xamarin.Google.AutoValue.Annotations" Version="1.6.5" PrivateAssets="All" />
<PackageReference Include="GoogleGson" Version="2.8.5" PrivateAssets="All" />
<PackageReference Include="Xamarin.Build.Download">
<Version>0.4.11</Version>
</PackageReference>

"Application is in Break Mode" with OpenIddict on .net Core 2.0 Win vs. Mac (scary)

I encounter a scary problem with OpenIddict on .NET Core 2.0.
I use a Windows 10 PC with Visual Studio 2017 at work and a Mac when I'm doing homeoffice. On the Mac I use Visual Studio for Mac.
So sometimes I continue work on my Mac, pushing changes to the Git repository and check them out on the Windows PC.
Without doing any changes on the code that deals with OpenIddict I am suddenly encountering problems only on windows when the code comes to return an access token through an AuthController method with this signature:
public async System.Threading.Tasks.Task<IActionResult> GetTokenAsync(OpenIdConnectRequest request)
The return command is
return SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme);
I can debug until the end of GetTokenAsync(). Then the system runs into the following case and falls into the Application Break Mode.
An unhandled exception of type 'System.ExecutionEngineException'
occurred in AspNet.Security.OpenIdConnect.Extensions.dll
The project compiles fine on both my Mac and Windows. When I deploy to Azure from Visual Studio 2017 for Windows, the software crashes on Azure as well. When I deploy to Azure from my Mac, the software works.
Conclusion: It must be a problem with Visual Studio or the NuGet packages?
These are my used package references, they are pretty much up to date:
<PackageReference Include="AspNet.Security.OAuth.Introspection" Version="2.0.0-rc1-final" />
<PackageReference Include="AutoMapper" Version="6.1.1" />
<PackageReference Include="Jwt.Token.Authorization.Server" Version="1.0.3" />
<PackageReference Include="Mailjet.Api" Version="1.0.1" />
<PackageReference Include="Microsoft.AspNetCore" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Formatters.Xml" Version="2.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="2.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="2.0.0" />
<PackageReference Include="MySql.Data" Version="8.0.9-dmr" />
<PackageReference Include="Newtonsoft.Json" Version="10.0.3" />
<PackageReference Include="AspNet.Security.OAuth.Validation" Version="2.0.0-rc1-final" />
<PackageReference Include="OpenIddict" Version="2.0.0-rc1-final" />
<PackageReference Include="OpenIddict.EntityFrameworkCore" Version="2.0.0-rc1-final" />
<PackageReference Include="OpenIddict.Mvc" Version="2.0.0-rc1-final" />
<PackageReference Include="System.Threading.Timer" Version="4.3.0" />
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="2.0.0" />
<PackageReference Include="WindowsAzure.Storage" Version="8.5.0" />
<PackageReference Include="HtmlAgilityPack" Version="1.6.2" />
Does anybody has an idea, how I can get my Windows environment back to work? I even stepped back on my Git history to a point where I didn't do the last checkout from my Mac, but the problem persists. So I am pretty sure that it is a problem of .net core, NuGet or Visual Studio.
Thanks in advance!
I fixed the problem by deleting the contents of C:\Users\Me\.nuget.
#Pinpoint's comment points to the solution as well.

Visual Studio 2017 csproj .NET Core build - views not being copied correctly

I have a project running in .NET Core and I am using VS2017 as IDE.
When I build my project through Visual Studio 2017 it does not automatically add the Views folder and the wwwroot folder to the output in [projectRoot]/bin/Debug/netcoreapp1.1/win10-x64(BuildDir). This means that if I try to run my website directly from the .exe file created in the bin folder, I get an error with the missing views and wwwroot. If I manually copy these folders to the BuildDir then the views load correctly.
This I can setup in my .csproj file with the following:
<Content Update="Views\**">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
And then the Views work but now my layout file is not being compiled so I get the following:
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>#ViewData["Title"] - FirstAgenda</title>
<environment names="Development">
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
<link rel="stylesheet" href="~/css/site.css"/>
<link rel="stylesheet" href="~/css/overwrite.css" asp-append-version="true" />
</environment>
<environment names="Staging,Production">
<link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.6/css/bootstrap.min.css"
asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute" />
<link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" />
<link rel="stylesheet" href="~/css/overwrite.css" asp-append-version="true" />
</environment>
</head>
This means that my root folder is not being targeted correctly. And also kinda tells me that just copying the files to the output directory is incorrect.
All of the above is working if I do a publish of my application (also without the addition to the .csproj file). I just have a project runner that I would like to be able to point to the Debug version of my websites executable file, because it is very easy to forget to do a publish compared to just building the project with VS2017.
I just don't know where to go from this and any help will be appreciated?
EDIT:
Added the stripped down version of csproj (which does not work):
<Project ToolsVersion="15.0" Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp1.1</TargetFramework>
<PreserveCompilationContext>true</PreserveCompilationContext>
<RuntimeIdentifier>win10-x64</RuntimeIdentifier>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Autofac.Extensions.DependencyInjection" Version="4.0.0" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="1.1.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="1.1.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="1.1.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="1.1.1" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="1.1.1" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="1.1.1" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.1.1" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="1.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.Cookies" Version="1.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Diagnostics" Version="1.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore" Version="1.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="1.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.2" />
<PackageReference Include="Microsoft.AspNetCore.Routing" Version="1.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Server.IISIntegration" Version="1.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Server.Kestrel" Version="1.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.MicrosoftAccount" Version="1.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.Google" Version="1.1.1" />
<PackageReference Include="Microsoft.AspNetCore.WebSockets" Version="1.0.1" />
<PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.1.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="1.1.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="1.1.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer.Design" Version="1.1.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="1.1.0-preview4-final" />
<PackageReference Include="IdentityServer4" Version="1.3.1" />
<PackageReference Include="IdentityServer4.AspNetIdentity" Version="1.0.0" />
<PackageReference Include="IdentityServer4.EntityFramework" Version="1.0.0" />
<PackageReference Include="OctoPack" Version="3.5.2" />
<PackageReference Include="Serilog.Extensions.Logging.File" Version="1.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.ViewCompilation" Version="1.1.0" />
</ItemGroup>
<ItemGroup>
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet">
<Version>1.1.0-preview4-final</Version>
</DotNetCliToolReference>
<DotNetCliToolReference Include="Microsoft.Extensions.SecretManager.Tools">
<Version>1.0.0-msbuild1-final</Version>
</DotNetCliToolReference>
<DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools">
<Version>1.0.0-msbuild1-final</Version>
</DotNetCliToolReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\[OWNPROJECT]" />
<ProjectReference Include="..\[OWNPROJECT1]" />
</ItemGroup>
</Project>
Also tried creating a new project with dotnet new mvc
And it is also not working.
My dotnet core cli version is [1.0.1].
EDIT:
I followed the steps you outlined. I also tried to create a new project with dotnet new mvc and followed your steps. Both gave me the same errors. It was unable to find the appsettings.json. If I then add a propertygroup to the .csproj. That tells msbuild to copy appsettings.json and web.config to the output
<ItemGroup>
<Content Update="appsettings.json;web.config">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
I can then start the program through the exe, but when I access the index, then when I try to access one of the views it gives me:
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[0]
An unhandled exception has occurred while executing the request
System.InvalidOperationException: The view 'Index' was not found. The following locations were searched:
/Views/Home/Index.cshtml
/Views/Shared/Index.cshtml
UPDATE:
Shaun Lutins answer seems to be working for me. Both with build and publish options. Only problem was that I was getting an error:
Duplicate 'Content' items were included. The .NET SDK includes 'Content' items from your project directory by default.
But it was resolved by changing the following:
<ItemGroup>
<Content Include="appsettings.json" CopyToOutputDirectory="Always" />
<Content Include="Views\**\*" CopyToOutputDirectory="Always" />
<Content Include="wwwroot\**\*" CopyToOutputDirectory="Always" />
</ItemGroup>
to
<ItemGroup>
<Content Update="appsettings.json;web.config" CopyToOutputDirectory="PreserveNewest"/>
<Content Update="Views\**\*" CopyToOutputDirectory="PreserveNewest" />
<Content Update="wwwroot\**\*" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
The challenge as I have interpreted it is to run dotnet build and be able to execute the compiled EXE from anywhere. The answer requires two steps:
copy required content to the bin, and
set the ContentRoot and WebRoot relative to the bin.
First, modify the csproj to copy required content to the bin. Out of the box, dotnet build does not copy Views, appsettings.json, or wwwroot to the bin. So, we need to specify CopyToOutputDirectory explicitly; and to do that, we also need to set EnableDefaultContentItems to false, otherwise our explicit settings will duplicate the default content item settings.
Second, modify Program.cs to specify the new ContentRoot and WebRoot. Out of the box, Program.cs sets UseContentRoot(Directory.GetCurrentDirectory()). Problematically for our situation, the current directory is the directory from which we run the executable. So, if we run the EXE from the command line at our desktop, then the current directory will be C:/Users/MyUser/Desktop. The app will not find the Views, appsettings.json, and other content.
Here are some working steps that I have used to meet the challenge as I have interpreted it.
Working Steps
cd C:\temp
dotnet new mvc
Update the temp.csproj with the "Working csproj" XML.
Update the Program.cs with the "Working Program.cs" code.
dotnet restore
dotnet build
cd ..
From anywhere, run C:\temp\bin\Debug\netcoreapp1.0\win10-x64\temp.exe
Working csproj
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp1.0</TargetFramework>
<RuntimeIdentifier>win10-x64</RuntimeIdentifier>
<OutputType>exe</OutputType>
<EnableDefaultContentItems>false</EnableDefaultContentItems>
</PropertyGroup>
<ItemGroup>
<Content Include="appsettings.json" CopyToOutputDirectory="Always" />
<Content Include="Views\**\*" CopyToOutputDirectory="Always" />
<Content Include="wwwroot\**\*" CopyToOutputDirectory="Always" />
</ItemGroup>
<ItemGroup>
<!-- Package references omitted for clarity -->
</ItemGroup>
</Project>
Working Program.cs
public class Program
{
public static void Main(string[] args)
{
// C:\temp\bin\Debug\netcoreapp1.0\win10-x64\temp.dll
var assemblyFilePath =
System.Reflection.Assembly.GetEntryAssembly().Location;
// C:\temp\bin\Debug\netcoreapp1.0\win10-x64\
var binDirectory =
System.IO.Path.GetDirectoryName(assemblyFilePath);
Console.WriteLine(assemblyFilePath);
Console.WriteLine(binDirectory);
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(binDirectory) // <--
.UseWebRoot("wwwroot") // <--
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
}
I've posted this as an issue to the ASP.NET Core repo on GitHub:
https://github.com/aspnet/Home/issues/2897
While the accepted answer works, it feels a bit like a hack.
There are problems with it too. The build process is slow when there are a lot of files to copy, and the build process does not remove files that have been deleted.
The accepted answer is also a misuse of the EnableDefaultContentItems setting.
So while I'm glad there is a short-term solution, a long-term solution to the problem needs to be sought.
Hopefully, the issue I've raised at GitHub will work someway towards a more permenant solution.

No executable found matching command "dotnet-ef" (Csproj)

I started a project on a Mac using VS Code and ASP.NET Core MVC, here is my csproj:
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore" Version="1.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.2" />
<PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.1.1" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.1.1" />
<PackageReference Include="Microsoft.VisualStudio.Web.BrowserLink" Version="1.1.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.Cookies" Version="1.1.0" />
<PackageReference Include="System.Data.SqlClient" Version="4.3.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="1.1.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="1.1.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="1.1.1" PrivateAssets="All" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="1.1.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="1.0.0" />
</ItemGroup>
I always get "No executable found matching command "dotnet-ef""
I tried it on Windows 10 and I get the same result.
What am I missing?
Added this to make it work:
<ItemGroup>
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version = "1.0.0"/>
</ItemGroup>
From inside the folder containing the csproj file, Add the following to the csproj file:
<PropertyGroup>
<TargetFramework>netcoreapp2.0</TargetFramework>
<RuntimeFrameworkVersion>2.0.5</RuntimeFrameworkVersion>
</PropertyGroup>
<ItemGroup>
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />
</ItemGroup>
Now include the needed dependencies by executing the following commands:
dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools.DotNet
Restore the project so that all dependencies are checked upon
dotnet restore
In order to make sure it all went ok, run the following command
dotnet ef
A screen with the basic dotnet ef command usage should appear
Check if the project is still building:
dotnet build
Generate the scaffold from your database with the following command:
dotnet ef dbcontext scaffold "Server=<your_server_address[,port_number]>;Initial Catalog=<your_db>;User Id=<your_user>;Password=<your_password>" Microsoft.EntityFrameworkCore.SqlServer -f -c YourDbContext -o Db --json
The command above can be described as the one responsible for reading out your database and generating your scaffold poco entity classes and the dbcontext file. It requires a basic working connection string, the parameter f forces the overwrite, the c gives the context a name, the o determines the output folder and the namespace for the created classes and the json parameter outputs the command result in json instead of a zero stout.
it is nice to keep this command at hand, it will be used anytime changes from the database must be reflected upon the ORM

Resources