how to know which framework using - asp.net

When I am executing "dotnet new mvc -n MyWeb" command I am getting below code auto generated.
namespace MyWeb
{
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
}
Above code style is different than blog which I am following. The blog I am following shows below output. This is different than mine after executing same command. After googling, I knew it's due to difference in framework.
How I can know which framework in use?
How I can force Visual Studio to use ASP.Net core 1.0
namespace secondapp
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrol()
.UseContentRool(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UserStartup<Startup>()
.Build();
host.run()
}
}
}

Display .NET Core SDK version.
dotnet --version
Display .NET Core information.
dotnet --info
Create a new ASP.NET Core C# MVC application project in the current
directory with no authentication targeting .NET Core 1.0 (Specifies
the framework to target. Values: netcoreapp1.0 or netcoreapp1.1)
dotnet new mvc -au None -f netcoreapp1.0
Check the link for more details
https://learn.microsoft.com/en-us/dotnet/core/tools/dotnet-new?tabs=netcore2x
Also from Visual Studio in Solution Explorer select your project and right click on it then select Properties, you will see the Target framework as below and you can change it.

Related

Unable to create an object of type 'AppContext'. Using verbose but

I tried to do my first migration and I got this error.
I used:
dotnet ef migrations add initial --project AppProject.Core --verbose
The error:
Finding application service provider in assembly 'AppProject.Core'...
Finding Microsoft.Extensions.Hosting service provider...
-> No static method 'CreateHostBuilder(string[])' was found on class 'Program'.
-> No application service provider was found.
Finding DbContext classes in the project...
Found DbContext 'AppContext'.
Microsoft.EntityFrameworkCore.Design.OperationException: Unable to create an object of type 'AppContext'.
My Program.cs
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.UseStartup<Startup>();
});
}
My Startup
services.AddDbContext<AppContext>(options =>
{
options.UseNpgsql(connection);
});
services.AddIdentity<User, IdentityRole<Guid>>()
.AddEntityFrameworkStores<SysFishingContext>()
.AddDefaultTokenProviders();
I don't get what is the problem. Please someone help me.
Try to specify both options --project and --startup-project
-p|--project <PROJECT>
This is the project that DbContext is sitting in.
-s|--startup-project <PROJECT>
This is the project with Depenedency Injection setup, usually the Web project.
Your migrations add command might look like below:
dotnet ef migrations add initial --startup-project AppProject.Web --project AppProject.Core --verbose

Use existing IContainer in new instance of Autofac container

I have solution with .NET Core 3.1 console application, which using Autofac as IoC container. In this solution is approximately 50 projects as class libraries, which is referenced over Autofac as modules. Now I am creating new module, which will start .NET Core web API which will provide data from database and other running modules.
New web API module is declared as follows:
public class RESTModule : Autofac.Module
{
protected override void Load(ContainerBuilder builder)
{
builder.Register(c =>
{
return Host.CreateDefaultBuilder(new string[] { })
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseConfiguration(c.Resolve<IConfiguration>());
webBuilder.UseStartup<Startup>();
})
.Build();
}).SingleInstance();
}
}
And my question is:
Is it possible to add existing Autofac instance with all modules, configurations and databases to instance of this created WEB API without adding this things manually again on start?
Thank you
Note:
.NET Core console application -> loading modules from configuration
loaded Module 1 (Database 1) as IDatabase1
loaded Module 2 (Database 2) as IDatabase2
loaded another 40 modules
and loaded new module RESTModule where i will use IDatabase1, IDatabase2, and another 10 running modules

What's the correct way to set up NLog for logging in a .NET Core app?

What is the correct way to set up NLog logging for a .NET Core console application?
I see there is mention in Wiring and injected NLog into a .Net Core console application of using Microsoft.Extensions.Logging.ILogger somehow but no example and I'm having the same issue of getting a null. I tried the other examples in the posting but same thing, null object.
As an update, I got the code below to work by adding using statements for NLog.Config and then using the LogManager.GetCurrentClassLogger. I saw this in another post but I'm not sure why it works or if it's the correct way. So, I am still hoping someone can enlighten me on the correct way to get NLog setup in .NET Core or if this is the correct way, please let me know.
using Microsoft.Extensions.Logging;
using NLog;
using NLog.Config;
using NLog.Extensions.Logging;
static void Main(string[] args)
{
var logger = LogManager.GetCurrentClassLogger();
//service collection are were we register our services
var serviceCollection = new ServiceCollection();
ConfigureServices(serviceCollection);
serviceCollection.AddLogging();
//service provider is where we get our services
serviceProvider = serviceCollection.BuildServiceProvider();
//logging (ILoggerFactory requires Microsoft.Extensions.Logging dependency and adding a using statement)
var loggerFactory = serviceProvider.GetService<ILoggerFactory>();
//NLog.LogManager.LoadConfiguration("NLog.config");
//AddNLog required adding dependency NLog.Extensions.Logging and then adding a using statement
loggerFactory.AddNLog().ConfigureNLog("NLog.config");
logger.Debug("I successfully logged a debug via NLog!");
}
The best and most recent way to add and use NLog with support for ASP.Net Core 5 is described on github
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using NLog.Web;
namespace ASP.NET_Core_5_NLog_Example
{
public class Program
{
public static void Main(string[] args)
{
var logger = NLog.LogManager.Setup().LoadConfigurationFromAppSettings().GetCurrentClassLogger();
try
{
logger.Debug("init main");
CreateHostBuilder(args).Build().Run();
}
catch (Exception exception)
{
//NLog: catch setup errors
logger.Error(exception, "Stopped program because of exception");
throw;
}
finally
{
// Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
NLog.LogManager.Shutdown();
}
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.SetMinimumLevel(LogLevel.Trace);
})
.UseNLog(); // NLog: Setup NLog for Dependency injection
}
}

Using Ninject in .NET Core Console App

I'm trying to migrate my code from a Webjobs project runing on .NET Framework 4.6.1 to a new .NET Core 2.0 Console project. I'm getting errors some errors here:
class Program
{
// Here I'm getting IKernel is obsolete. Use IKernelConfiguration and IReadOnlyKernel message.
// Also a message that reads: StandardKerynel is obsolete. Use StandardKernelConfiguration and StandardReadOnlyKernel
static readonly IKernel Kernel = new StandardKernel();
static JobHostConfiguration config;
static void Main(string[] args)
{
Environment.SetEnvironmentVariable("AzureWebJobsDashboard", "connection");
Environment.SetEnvironmentVariable("AzureWebJobsStorage", "storage connection");
BootStrapIoc();
config = new JobHostConfiguration();
if (config.IsDevelopment)
{
config.UseDevelopmentSettings();
}
var host = new JobHost(config);
host.RunAndBlock();
}
private static void BootStrapIoc()
{
// Also getting an error here that reads: Argument 1: Cannot convert System.Reflection.Assembly to System.Collections.Generic.IEnumerable<Ninject.Modules.NinjectModule>
Kernel.Load(Assembly.GetExecutingAssembly());
config = new JobHostConfiguration
{
JobActivator = new BrmJobActivator(Kernel)
};
}
}
I'm also getting errors in my BrmJobActivator code:
public class BrmJobActivator : IJobActivator
{
private readonly IKernel _container;
public BrmJobActivator(IKernel container)
{
_container = container;
}
public T CreateInstance<T>()
{
return _container.Get<T>();
}
}
UPDATE:
This is the warning message under NuGet packages in my project after installing Ninject package 3.2.2:
Also getting an error here that reads: Argument 1: Cannot convert System.Reflection.Assembly to System.Collections.Generic.IEnumerable
There are some changes in the latest prerelease version of Ninject. Please install the latest stable 3.2.2 version instead.
I tested your code on my side. After updated the Ninject version to 3.2.2, the code worked fine.
Ninject 3.3.0 was released September 26th 2017 and now targets .NET Standard 2.0 and thus also runs on .NET Core 2.0. Updating to 3.3.0 will fix the warning.

VS 2017 RC - Core Projects - ClassLibrary and Console - Frameworks differ

I create a new project in VS2017 RC I add a console lib and a class library.
now I can see that t he frameworks are added as dependencies.
but why does the core console not have NetStandard.Library ?
Instead I can see Microsoft.NetCore.app
As a result when I try to start the console app with dotnet -run
I get this error
[![enter image description here][2]][2]
Because you have the SDK/build-tools for 1.1.0 installed, but not the shared framework 1.1.0.
The SDK and the shared framework are not the same thing.
Maybe it's best explained in terms of Linux command line.
If you had it, what you currently have installed is
apt-get install dotnet-dev-1.0.1
but what you're missing is
apt-get install dotnet-sharedframework-microsoft.netcore.app-1.1.0
And the deeper reason is that you have
apt-get install dotnet-dev-1.0.1
instead of
apt-get install dotnet-dev-1.1.0
SDK version 1.1 will install shared framework 1.1.0, but if you're SDK is 1.0.1, then 1.1.0 has never been installed.
As to netstandard vs. netcore, David Fowler has a nice explanation attempt here.
Basically, every version of ".NET Core Framework" and ".NET Framework non-core" extend a version of netstandard, where a netstandard-library can be used in both CORE and NON-Core):
Concretely, your app can only run as either .NET Core or as .NET Framework. There is no netstandard-app (currently), only netstandard-libraries.
Both NetFramework_vX and NetCoreFramework_vX are supersets of NetStandardLibray_vX.
using System;
namespace Analogy
{
// Each interface represents a target framework and methods represents groups of APIs available on that target framework.
// The goal is to show the relationship between .NET Standard API surface and other .NET platforms
// .NET Standard
interface INetStandard10
{
void Primitives();
void Reflection();
void Tasks();
void Collections();
void Linq();
}
interface INetStandard11 : INetStandard10
{
void ConcurrentCollections();
void InteropServices();
}
interface INetStandard12 : INetStandard11
{
void ThreadingTimer();
}
interface INetStandard13 : INetStandard12
{
void FileSystem();
void Console();
void ThreadPool();
void Process();
void Sockets();
void AsyncLocal();
}
interface INetStandard14 : INetStandard13
{
void IsolatedStorage();
}
interface INetStandard15 : INetStandard14
{
void AssemblyLoadContext();
}
// .NET Framework
interface INetFramework45 : INetStandard11
{
void FileSystem();
void Console();
void ThreadPool();
void Crypto();
void WebSockets();
void Process();
void Sockets();
void AppDomain();
void Xml();
void Drawing();
void SystemWeb();
void WPF();
void WindowsForms();
void WCF();
}
interface INetFramework451 : INetFramework45, INetStandard12
{
// TODO: .NET Framework 4.5.1 specific APIs
}
interface INetFramework452 : INetFramework451, INetStandard12
{
// TODO: .NET Framework 4.5.2 specific APIs
}
interface INetFramework46 : INetFramework452, INetStandard13
{
// TODO: .NET Framework 4.6 specific APIs
}
interface INetFramework461 : INetFramework46, INetStandard14
{
// TODO: .NET Framework 4.6.1 specific APIs
}
interface INetFramework462 : INetFramework461, INetStandard15
{
// TODO: .NET Framework 4.6 specific APIs
}
// Mono
interface IMono43 : INetFramework46
{
void MonoSpecificApi();
}
// Windows Universal Platform
interface IWindowsUniversalPlatform : INetStandard14
{
void GPS();
void Xaml();
}
// Xamarin
interface IXamarinIOS : INetStandard15
{
void AppleAPIs();
}
interface IXamarinAndroid : INetStandard15
{
void GoogleAPIs();
}
// .NET Core
interface INetCoreApp10 : INetStandard15
{
}
// Future platform
interface ISomeFuturePlatform : INetStandard13
{
// A future platform chooses to implement a specific .NET Standard version.
// All libraries that target that version are instantly compatible with this new
// platform
}
}
For the difference between netcoreapp and netstandard please check: What's the difference between the new netstandardapp and netcoreapp TFMs?.
When you run dotnet -run on the command line you need to have installed the .NET Core SDK, which is a seperate installation of .NET Core. Installing VS2017 RC doesn't install this SDK. You can download the .NET Core 1.1 SDK here

Resources