I have an ASP.NET Core application running as Azure App Service. Azure Application Insights is enabled (I followed these instructions). The problem is my instance of Azure Insights on Azure Portal isn't showing any useful data except for Live Metrics (see the screenshot). As you can see there are multiple requests and custom events on the screenshot.
However, when I open Transaction search it shows nothing (see the screenshot).
Events page is empty as well (see the screenshot).
So far I double-checked an InstrumentKey. Also I tried to use ConnectionString instead of InstrumentKey, but it didn't help.
My app is running on .NET Core 3.1. I installed the latest version of Microsoft.ApplicationInsights.AspNetCore package which is 2.19.0.
Here is how logging is configured in Program.cs:
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.ConfigureLogging(builder =>
{
builder.AddFilter<ApplicationInsightsLoggerProvider>("", LogLevel.Information);
});
And below is code from Startup.cs:
services.AddApplicationInsightsTelemetry(new ApplicationInsightsServiceOptions
{
ConnectionString = Environment.GetEnvironmentVariable("APPLICATIONINSIGHTS_CONNECTION_STRING")
});
LogLevel is also configured in appsettings.json:
"Logging": {
"LogLevel": {
"Default": "Warning"
},
"ApplicationInsights": {
"LogLevel": {
"Default": "Information"
}
}
Update:
My Admin who has more permissions can see all data, including events, performance operations etc. So I suppose there's something to do with permissions. Though it's strange that I'm not seeing any warning messages. The Admin assigned me more roles (see the screenshot), but it didn't make any difference.
I would appreciate any help on this issue!
After tearing almost all hair off my head I finally solved the issue!
Turned out the instance of Azure Application Insights was linked to a Log Analytic Workspace that belonged to a Resource Group to which I didn't have access. So logs were stored properly, but I didn't have permission to read them.
My admin solved the issue by creating a new instance of Azure Application Insights which was linked to a Log Analytic Workspace within my Resource Group.
To anyone who isn't familiar with Log Analytic Workspace - it can be specified when you create a new instance of Azure Application Insights (see the screen).
Thanks everyone for trying to help me!
UPDATE: As Jonathan L. mentioned in the comments, instead of creating a new Application Insights instance, one can just change Workspace in Properties.
I have tried the same and can able to see the logs inside portal .
As Peter Bons suggested make sure that you are using ILogger in your controller .
Here are the steps i have followed .
I have download an sample project from GitHub and after extract open project in Visual studio and configure with Application insight telemetry . Updated latest Microsoft.ApplicationInsights.AspNetCore to 2.19.0
And added instrumentation key in my appsettings.json which copied from Azure portal>Application insight(my applnsight)>overview.
{
"Logging": {
"ApplicationInsights": {
"LogLevel": {
"Default": "Debug",
"Microsoft": "Error"
}
},
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"ApplicationInsights": {
"InstrumentationKey": "mykey",
"ConnectionString": "InstrumentationKey=6xxxxxx-xxxxx-xxxx-xxxx-0000000xxxxxxxx.in.applicationinsights.azure.com/"
}
}
Ilogger configuration in my controller.cs
namespace ApplicationInsightsTutorial.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
var iteracion = 4;
_logger.LogDebug($"Debug {iteracion}");
_logger.LogInformation($"Information {iteracion}");
_logger.LogWarning($"Warning {iteracion}");
_logger.LogError($"Error {iteracion}");
_logger.LogCritical($"Critical {iteracion}");
try
{
throw new NotImplementedException();
}
catch (Exception ex)
{
_logger.LogError(ex, ex.Message);
}
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
}
}
In startup.cs added
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddApplicationInsightsTelemetry();//telemetry added
}
After all that above configuration run the application and navigate to Azure portal to check the logs .
Make sure that you have provided the log information which you want to check as example in my controller.cs .
from the logs we can see the exceptions/errors with line of code as well .
Here are some screenshot for reference:
For more information please refer this SO Thread .
I had the following error in package manager console when Add-Migration
Value cannot be null. Parameter name: connectionString
This is my startup:
namespace MyProject
{
public class Startup
{
public IConfiguration Configuration { get; set; }
public Startup(IConfiguration config)
{
Configuration = config;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContextPool<AppDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddTransient<IDevRepo, DevRepo>();
services.AddMvc();
services.AddMemoryCache();
services.AddSession();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseStatusCodePages();
app.UseStaticFiles();
app.UseMvcWithDefaultRoute();
app.Run(async (context) =>
{
await context.Response.WriteAsync(Configuration["Message"]);
});
}
}
}
program class:
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((context, builder) => builder.SetBasePath(context.HostingEnvironment.ContentRootPath)
.AddJsonFile("appsettings.json")
.Build())
.UseStartup<Startup>()
.Build();
}
appsettings.json:
{
"Message": "Hello World",
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=NotMyFault;Trusted_Connection=True;MultipleActiveResultSets=true"
}
}
Interestingly if I run the app, it displays "Hello World", but when add migration it cannot find connectionString. Can someone please shed some lights here? Thanks.
This problem occurred when the connection string can't be found.
Probably you have the following code in Startup class:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<BenchmarkContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("yourConnectionString name from appsettings.json")));
}
These methods solve your problem:
1- Instead of Configuration.GetConnectionString("yourConnectionString name from appsettings.json(in develop mode: 'appsettings.Development.json')") just put your connectionstring.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<BenchmarkContext>(options =>
options.UseSqlServer("Data Source=.;Initial Catalog=Benchmark;Persist Security Info=True;User ID=****;Password=****"));
}
2- If you are going to use the Configuration file add these codes to Startup class:
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration;
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<BenchmarkContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("TestConnection")));
}
Appsettings.json file(in develop mode: 'appsettings.Development.json'):
{
"ConnectionStrings": {
"TestConnection": "Data Source=.;Initial Catalog=Benchmark;Persist Security Info=True;User ID=****;Password=****"
}
}
After that execute 'add-migration name' command in Package Manager Console
I had the same issue, but my solution was a lot simpler. All I did was to change the order of the appsettings.json from:
{
"Message": "Hello World",
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=NotMyFault;Trusted_Connection=True;MultipleActiveResultSets=true"
}
}
to:
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=NotMyFault;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"Message": "Hello World"
}
I have a suspicion that there is a sequence/order of parameters in the appsettings.json file.
I had such issue when load tesing the service (I recommend it to all) and had ~3/1000 requests with errors,
so I changed
services.AddDbContextPool<AppDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
to
string connectionString = Configuration.GetConnectionString("DefaultConnection");
services.AddDbContextPool<AppDbContext>(options =>
options.UseSqlServer(connectionString));
So it reads connections string 1 time and doesn't use Configuration on every request. And now 100% requests are successful.
But it seems to be a bug in .Net Core
I found my own problem.
I have an AppDbContextFactory class which inherits IDesignTimeDbContextFactory. Deleting this class resolves this issue.
I had the same problem, because I was using the default value in Startup.cs.
I just edited Configuration property from:
public IConfiguration Configuration { get; }
to:
public IConfiguration Configuration;
and it worked!
If someone say why would be appreciated.
I had had a similar issue because of the following reasons:
appsettings.json was not included in the project
I was running the project from the path which did not contain appsettings.json
I had the same error and resolved it by moving "ConnectionStrings" to be the first variable in the appsettings.json file.
Probably, the issue is with your DotNetCliToolReference from the csproj file. If you migrate the project from an older version of asp.net core, the DotNetCliToolReference is not automatically updated.
Update the yourproject.csproj file to use the 2.0.0 version of the CLI as shown in the snippet bellow:
<ItemGroup>
...
<DotNetCliToolReference
Include="Microsoft.EntityFrameworkCore.Tools.DotNet"
Version="2.0.0" />
</ItemGroup>
Rerun, from the project folder, the dotnet command with -v switch to see results
dotnet ef database update -v
Also, recheck your Microsoft.EntityFrameworkCore nuget packages to reference the 2.0.0 version. Remove or update older EF packages. The minimum are:
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Design
both 2.0.0 at this moment.
I had the same problem and what it is the I had to make sure that the name of the connection matches:
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddDbContext<MyContext>(options => options.UseSqlServer(Configuration["ConnectionStrings:DefaultConnection"]));
which ****ConnectionStrings:DefaultConnection*** it was where I had the whole problem.
Make sure that is the same in Startup.cs and appsettings.json(appsettings.Development.json in Vs 2019)
After I fixed this, everything was fine.
I had a similar issue. I had a typo in my appsettings.json. Changing ConnectionsStrings to ConnectionStrings did it for me!
I have solved my issue by setting right base path. The problem is the migrations or anything else from different packages uses wrong path to the appsetting.json file. Not sure if it's an official issue.
I have just changed my Startup.cs as follows:
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
After that you just need to copy your appsettings.json to the right place if it's missing there.
This worked flawlessly for me:
public IConfiguration Configuration;
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext.ApplicationDbContext>(options =>
//options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
options.UseSqlServer("Server=serverAddress; Database=dbName; user=username; password=pswd"));
}
The commented part is just as reference where to replace.
Another scenario can be where you set the configuration. set the connection string in appsettings.json instead of appsettings.Development.json
I had a similar problem when I specified the ".UseContentRoot" as the current process path.
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseUrls("http://*:3001")
.UseStartup<Startup>()
.UseContentRoot(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName));
thus when running Add-Migration the process path is different from the project bin path therefore the process can't find the appsettings.json file.
when I removed the ".UseContentRoot" line the migration was successful
I'm stupid and I had typo
{
"Conn'ce'tionStrings": {
"DefaultConnection": "Data source=datingapp.db"
},
changed it to
{
"ConnectionStrings": {
"DefaultConnection": "Data source=datingapp.db"
},
I had a similar problem after trying to use new created project for ASP.NET Core 2.0 Web Api. As far as I found, the cause of the problem was that application settings specified for development environment were not added. I fixed it by updating startup file to the following:
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
this.Configuration = builder.Build();
}
In my case program class looks like the following:
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
My problem was when I was trying to run App.dll within netcoreapp2.1 folder, but the right folder is netcoreapp2.1\publish\
If you have previously renamed your connection string in appsettings file and you have omitted to rename it in DesignTimeDbContextFactory class (if you have it in your project) and that is checked by Entity framework, then you may run in this issue.
If you are using an IDesignTimeDbContextFactory, you will need to add a default constructor to it with no parameters. Try something like this:
public DbContextFactory()
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddEnvironmentVariables()
.AddJsonFile("appsettings.json", false, true)
.Build();
_connectionString = configuration.GetConnectionString("ConnectionStringName");
}
For me it was that I had appSettings.json instead of appsettings.json for some reason (not quite sure if VS did that with a newly created project or I had renamed it to that). Once I changed the name, it worked fine.
I figured I would add what it was for me. I had followed a popular tutorial to add appsettings.json and dependency injection to a console application. I did not realize in the setup that it referenced the current directory and was using that to set the base path of the configuration builder. It worked fine when I was running locally, but as soon as I tried to deploy and have a SQL scheduled job run the command it was taking the directory where the command was being entered, not where the DLL was so it wasn't finding my appsettings.json file. I simply removed the lines that dealt with getting the current directory and setting that as the base path and it works fine. It seems like it defaults to the same folder as the DLL.
I had this problem due to a difference in connectionstring of appsetting.json file, and the GetConnectionString(connectionstrings) parameter in startup.cs. Once I removed extra s in startup.cs, the problem disappeared.
Check if ASPNETCORE_ENVIRONMENT variable is set up on the server correctly. Depending on that environment it may be taking appsettings.json instead of appsettings.Staging.json or appsettings.Production.json.
In my case i was using configuration["DbContext"]
services.AddDbContext<AstroBhaskarDbContext>(option =>
{
option.UseSqlServer(configuration["DbContext"]);
});
then i replaced configuration["DbContext"] to configuration.GetConnectionString("DbContext") as below
services.AddDbContext<AstroBhaskarDbContext>(option =>
{
option.UseSqlServer(configuration.GetConnectionString("DbContext"));
});
we are trying to develop a asp core application (MVC) using ef code first . however it seems that requires the db context to be in an executable and not class library .
so the data context was added in the web UI project but the issue that how can the db context's dbset be made available in the repository project ..
example code is as under:
public class CompanyRepository : GenericRepository<Company>, /*IGenericRepository<Company>*/ ICompanyRepository
{
public CompanyRepository(DbContext dbContext) : base(dbContext)
{
}
public async Task<IEnumerable<Company>> GetAllAsync()
{
return await base.GetAllAsync<Company>();
}
}
MVC Project StartUp .cs
services.AddDbContext<DBContext>();
services.AddScoped<ICompanyRepository, CompanyRepository>();
DBCOntext.cs in MVC Project
public class DBContext : DbContext
{
private IConfigurationRoot _config;
public DBContext(IConfigurationRoot config, DbContextOptions options):base(options)
{
_config = config;
}
}
currently it seems to raise following error:
An unhandled exception occurred while processing the request. InvalidOperationException: Unable to resolve
service for type 'Microsoft.EntityFrameworkCore.DbContext' while
attempting to activate
'On.Store.Repository.Companies.CompanyRepository'.
We have two problems here:
1) When you configure services in a Startup class, you are configuring your custom context (for easier reference, let's name it CustomDbContext):
public class CustomDbContext: DbContext
{
... and in the Startup class:
services.AddDbContext<CustomDbContext>();
... so in your repository, you need to inject a context of declared class, instead of base DbContext class:
// THIS WILL NOT WORK
public class CompanyRepository : GenericRepository<Company>, ICompanyRepository
{
public CompanyRepository(DbContext dbContext) : base(dbContext)
{
}
}
// THIS WILL WORK
public class CompanyRepository : GenericRepository<Company>, ICompanyRepository
{
public CompanyRepository(CustomDbContext dbContext) : base(dbContext)
{
}
}
2) Problem number two is revealed directly from the first problem. So you have CustomDbContext declared in a MVC project, so cannot be used in a referenced repository project. So the solution seems to be easy, you need to move the CustomDbContext out of the MVC project (either to repository project or any other/third project which could be referenced by both MVC and repository). In such way you will easy configure your CustomDbContext in a Startup class, as well as use this context in repositories.
3) As it comes to registering context from external library you can do it easily with MigrationsAssembly method, it will look like this:
services.AddDbContext<CustomDbContext>(options => options.UseSqlServer(
_configuration.GetConnectionString("YourConnectionStringName"),
b => b.MigrationsAssembly("YourExternalAssemblyName")));
This is an very simples project that can help you and other developers.
Generic Repository Pattern in ASP.NET Core
This is addressing your orginal issue of being unable to use migration command line tools and allow you to keep proper separation of layers.
This is a know issue (tracked here) and there are two workarounds as of now, directly taken from the EntityFramework Core documentation:
Workaround 1 - Utilize a separate startup project
Convert the class library project into an “app” project. This can either be a .NET Core app or a desktop .NET app.
Example:
{
"frameworks": {
"netcoreapp1.0": {
"dependencies": {
"Microsoft.NETCore.App": {
"type": "platform",
"version": "1.0.0-*"
}
}
}
}
}
Be sure to register the EntityFramework Tools as a project dependency and in the tools section of your project.json.
Example:
{
"dependencies": {
"Microsoft.EntityFrameworkCore.Tools": {
"version": "1.0.0-preview2-final",
"type": "build"
}
},
"tools": {
"Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final"
}
}
Finally, specify a startup project that is a “runnable app.”
Example:
dotnet ef --startup-project ../MyConsoleApplication/ migrations list
Workaround 2 - Modify your class library to be a startup application
Convert the class library project into an “app” project. This can either be a .NET Core app or a desktop .NET app.
To make the project a .NET Core App, add the “netcoreapp1.0” framework to project.json along with the other settings in the sample below:
{
"buildOptions": {
"emitEntryPoint": true
},
"frameworks": {
"netcoreapp1.0": {
"dependencies": {
"Microsoft.NETCore.App": {
"type": "platform",
"version": "1.0.0-*"
}
}
}
}
}
To make a desktop .NET app, ensure you project targets “net451” or newer (example “net461” also works) and ensure the build option "emitEntryPoint" is set to true.
{
"buildOptions": {
"emitEntryPoint": true
},
"frameworks": {
"net451": { }
}
}
What is the available implementation of the System.Net.IWebProxy (from System.Net.Primitives, DNX Core)? By application requirement, the only framework can be used in dnxcore50, so what is the right NuGet package that contains proxy implementations?
What is the correct way to resolve such questions? Related functionality seems to be split among dozen of packages.
Despite the name, IWebProxy implementation does not actually need to implement any proxying, it just provides information about the proxy. So, you can create your own implementation:
public class MyProxy : IWebProxy
{
public Uri GetProxy(Uri destination)
{
return new Uri("http://localhost:8888");
}
public bool IsBypassed(Uri host)
{
return false;
}
public ICredentials Credentials { get; set; }
}
There is a WebProxy class in the System.Net namespace (source here) that you can use.
Make sure your project.json file has these two lines under "dependencies"
"frameworks": {
"dotnet5.4": {
"dependencies": {
"Microsoft.Net.Http": "2.2.29",
"System.Net.Primitives": "4.0.11-beta-23516"
}
}
}
I've recently just upgraded Visual Studio 2015 with ASP.NET 5 beta8, which causes the strange shift from the old listener over to this new 'Kestrel' .. thing.
I've attempted to follow the instructions and get it to run, but I simply yield a console window that says...
Hosting environment: Development
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.
Okay, so I navigate to http://localhost:5000, and ... nothing is there. My application doesn't run or anything.
I have tried to launch the default ASP.NET MVC sample project using Kestrel too, with the built in settings, and get the same result. I'm really unsure of what to do.
Here is what I've done so far...
I have it in my project.json file;
"dependencies": {
"Microsoft.AspNet.Server.Kestrel": "1.0.0-beta8",
},
"commands": {
"web": "Microsoft.AspNet.Server.Kestrel"
},
My program was working fine on beta7, using the old listener; But now even that doesn't work suddenly since installing beta8. I'm at the hair-pulling stage of frustration over this forced change. I can't get it to run in IIS either.
Per request, this is my Startup.cs file;
public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv) {
// Setup configuration sources.
Configuration = new ConfigurationBuilder()
.SetBasePath(appEnv.ApplicationBasePath)
.AddJsonFile("config.json")
.AddEnvironmentVariables()
.Build();
}
public IConfiguration Configuration { get; set; }
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services) {
// Add MVC services to the services container.
services.AddMvc();
services.UseCookieAuthentication(o => {
//o.ExpireTimeSpan
o.CookieName = "3b7eaa9c-decd-4c5d-83f9-01f1f11a6e22";
});
}
public void Configure(IApplicationBuilder app) {
app.UseIdentity();
app.UseStaticFiles();
app.UseMvc(routes => {
// add the new route here.
routes.MapRoute(name: "areaRoute",
template: "{area:exists}/{controller}/{action}");
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}"
);
});
}
That understand in which place the request pipeline problem arise, enable logging in your application.