dotnet / core

.NET news, announcements, release notes, and more!
https://dot.net
MIT License
20.98k stars 4.91k forks source link

dotnet core 3.1 updating issue #4560

Open bilalmalik777 opened 4 years ago

bilalmalik777 commented 4 years ago

I have updated my dotnet core portal from 2.2 to 3.1 and facing the following error on the landing page I even updated the Microsoft.ApplicationInsights.AspNetCore to the latest version. Please help me to solve this issue

InvalidOperationException: No service for type 'Microsoft.ApplicationInsights.AspNetCore.JavaScriptSnippet' has been registered. image

scalablecory commented 4 years ago

@Pilchie @anurse any ideas about this?

Pilchie commented 4 years ago

@davidfowl - do you have any ideas here?

davidfowl commented 4 years ago

@bilalmalik777 what changes did you make to the application?

bilalmalik777 commented 4 years ago

@davidfowl i just update the application by following the online tutorials. make the required changes to upgrade the application like update the program.cs,startup.cs and also upgraded all the nuget packages. that's all. i also did the same for API project which is working perfectly

davidfowl commented 4 years ago

It sounds like something might be missing. Is there a call to AddApplicationInsights in the broken application?

bilalmalik777 commented 4 years ago

No there is no call to AddApplicationInsights

davidfowl commented 4 years ago

That’s likely the bug? What was working before in the old app with application insights and what did you change?

It’s likely there was some small step missing.

bilalmalik777 commented 4 years ago

Alright give some time today i will again try to upgrade the same code in different branch then I will update regarding issue

bilalmalik777 commented 4 years ago

@davidfowl please go through changes, i made to upgrade the program.cs and startup.cs and let me know if need to make more changes or something is missing

public class Program

    {
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseKestrel();
                webBuilder.UseIIS();
                webBuilder.UseStartup<Startup>();
            });
}

`

public class Startup { ///

/// Initializes a new instance of the class. /// /// The configuration. public Startup(IConfiguration configuration) { var environmentName = Environment.GetEnvironmentVariable("CORE_ENVIRONMENT"); this.Configuration = configuration; var elasticUri = $"{this.Configuration["ElasticSearchSettings:ElasticUri"]}"; var elasticUser = $"{this.Configuration["ElasticSearchSettings:ElasticUser"]}"; var elasticPassword = $"{this.Configuration["ElasticSearchSettings:ElasticPassword"]}"; Log.Logger = new Serilog.LoggerConfiguration() .Enrich.WithProperty("Client", environmentName) .Enrich.FromLogContext() .MinimumLevel.Information() .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) .WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri(elasticUri)) { MinimumLogEventLevel = LogEventLevel.Debug, IndexDecider = (@event, offset) => { return "applogs"; }, AutoRegisterTemplate = true, AutoRegisterTemplateVersion = AutoRegisterTemplateVersion.ESv6, CustomFormatter = new ElasticsearchJsonFormatter(inlineFields: true), CustomDurableFormatter = new ElasticsearchJsonFormatter(inlineFields: true), ModifyConnectionSettings = settings => settings .BasicAuthentication(elasticUser, elasticPassword) .DisableAutomaticProxyDetection() }) .CreateLogger(); }

    /// <summary>
    /// Gets or sets the client version.
    /// </summary>
    /// <value>
    /// The client version.
    /// </value>
    public static string ClientVersion { get; set; }

    /// <summary>
    /// Gets or sets the production storage connection string.
    /// </summary>
    /// <value>
    /// The production storage connection string.
    /// </value>
    public static string ProductionStorageConnectionString { get; set; }

    /// <summary>
    /// Gets or sets the name of the API error table.
    /// </summary>
    /// <value>
    /// The name of the API error table.
    /// </value>
    public static string ApiErrorTableName { get; set; }

    /// <summary>
    /// Gets or sets the email settings.
    /// </summary>
    /// <value>
    /// The email settings.
    /// </value>
    public static EmailSettings EmailSettings { get; set; }

    /// <summary>
    /// Gets or sets a value indicating whether [email errors].
    /// </summary>
    /// <value>
    ///   <c>true</c> if [email errors]; otherwise, <c>false</c>.
    /// </value>
    public static bool EmailErrors { get; set; }

    /// <summary>
    /// Gets or sets a value indicating whether this instance is downtime included.
    /// </summary>
    /// <value>
    ///   <c>true</c> if this instance is downtime included; otherwise, <c>false</c>.
    /// </value>
    public static bool ISDowntimeIncluded { get; set; }

    /// <summary>
    /// Gets the configuration.
    /// </summary>
    /// <value>
    /// The configuration.
    /// </value>
    public IConfiguration Configuration { get; }

    /// <summary>
    /// Configures the services.
    /// </summary>
    /// <param name="services">The services.</param>
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMemoryCache();

        services.AddLogging(builder => { builder.AddSerilog(); });

        services.AddAuthentication(sharedOptions =>
        {
            sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
        })
        .AddAzureAd(adOptions =>
        {
            this.Configuration.Bind("AzureAd", adOptions);
            AzureAdOptions.Settings = adOptions;
        })
        .AddCookie(cookieOptions => cookieOptions.SlidingExpiration = true);

        // Add session services.
        services.AddSession(so => so.IdleTimeout = TimeSpan.FromMinutes(90));
        ////services.AddTransient<IAuthorizationHandler, CustomAuthorizeHandler>();
        bool isAnonymousUser = Convert.ToBoolean(this.Configuration.GetSection("anonymousUser").Value);

        services.AddMvc(config =>
        {
            var policy = new AuthorizationPolicyBuilder()
                .RequireAuthenticatedUser()
                .Build();

            if (!isAnonymousUser)
            {
                config.Filters.Add(new AuthorizeFilter(policy));
                config.Filters.Add(new RequireHttpsAttribute());
            }
        });

        // Configurations
        services.AddOptions();

        ClientVersion = this.Configuration.GetSection("ClientVersion").Value;
        if (string.IsNullOrEmpty(ClientVersion))
        {
            // Local dev machine will have a new version everytime.
            ClientVersion = DateTime.Now.ToString("yyyyMMdd.hhmm", CultureInfo.CurrentCulture);
        }

        services.Configure<TokenConfig>(this.Configuration.GetSection("AzureAd"));
        services.Configure<RecognitionSettings>(this.Configuration.GetSection("RecognitionSettings"));
        services.AddSingleton(provider => this.Configuration);
    }

    /// <summary>
    /// Configures the specified application.
    /// </summary>
    /// <param name="app">The application.</param>
    /// <param name="env">The env.</param>
    /// <param name="loggerFactory">The logger factory.</param>
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
    {
        app.UseDeveloperExceptionPage();
        loggerFactory.AddSerilog();
        app.UseStaticFiles();
        app.UseRouting();
        app.UseSession();
        app.UseAuthentication();
        app.UseAuthorization();

        var rewriteOptions = new RewriteOptions().AddRedirectToHttps();
        app.UseRewriter(rewriteOptions);

        app.UseForwardedHeaders(new ForwardedHeadersOptions
        {
            ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto,
            RequireHeaderSymmetry = true
        });

        app.UseCallToApiMiddleware(this.Configuration["ApiUrl"]);

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapRazorPages();
            endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
        });
    }
}

`