Adding an Owin Startup Class in my project gives a SQL Server not found error - owin

I have added the following startup code for Owin in my Startup.cs file -
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;
[assembly: OwinStartupAttribute(typeof(Biosimilia.Startup))]
namespace Biosimilia
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
}
}
I have added a key in the Web.config file as -
<add key="owin:appStartup" value="Biosimilia.Startup" />
When I run the application with the startup file in place, I get the error -
Unable to connect to SQL Server Database.
If I remove the key and the startup file from the project, I get the following error -
The following errors occurred while attempting to load the app.
- No assembly found containing an OwinStartupAttribute.
- No assembly found containing a Startup or [AssemblyName].Startup class.
To disable OWIN startup discovery, add the appSetting owin:AutomaticAppStartup with a value of "false" in your web.config.
To specify the OWIN startup Assembly, Class, or Method, add the appSetting owin:AppStartup with the fully qualified startup class or configuration method name in your web.config.
If I add a key to my web.config to disable to startup discovery as following -
<add key="owin:AutomaticAppStartup" value="false"/>
I get the following error -
`No owin.Environment item was found in the context.`
I have looked at a lot of posts on the topic here already with no luck. Please help.

I had the following line in my web.config >
This was resulting in a SQL Server connection timed out error. Removed this line from the web.config. The OWIN startup.cs class now runs correctly and the issue is resolved.
It appears that when using Identity, we do not need to have the roleManager explicitly enabled in the web.config.

Related

How to instruct IIS to use environment variable from web.config, to run the .net core application?

Recently, I'm facing a strange issue while hosting .net core 2.2 application on IIS.
After hosting, I get "An error occurred while starting the application". In order to identify the root cause I enabled the log file and found that its because of environment variable issue.
I configured the environment variable in my web.config file as like below,
<aspNetCore processPath="dotnet" arguments=".\PctrClient.Api.dll" stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout" hostingModel="InProcess">
<environmentVariables>
<environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Development" />
</environmentVariables>
</aspNetCore>
Program.cs
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseIISIntegration();
}
But web app interprets it as Development;Development. How is it possible?
Info from log file
info Hosting environment: Development;Development
i have got problems about IIS and i changed applicationHost.config with tags. now i can use same IIS with different env. for each web app.
In order to resolve this issue, we have to set the environment variable either in system level or in web.config file. (if we set the environment variable in both places, it will get appended by .net core 2.2 framework)
From my perspective, it looks like a strange behavior, so I have raised this issue in GitHub/AspNetCore to know other community users thoughts, hope this issue will get addressed soon.

.NET Standard 2.0 logging NLOG gives System.TypeInitializationException

I did 2 projects to test out NLog on a .NET Framework 4.6.1 standard console app and on .NET Standard 2.0 Library. My intention is to port as much code as I can to .NET Standard 2.0 for future multiplatform compatibility.
Both share the same code but the .NET Standard version produces an exception.
Here's the code
Console.WriteLine("Writing log");
Logger _errorLog = LogManager.GetLogger("ErrorsLogger");
Logger _tradesLog = LogManager.GetLogger("TradesLogger");
_errorLog.Error("This is the log message!!!");
Console.WriteLine("End log");
Console.Read();
Here's the App.Config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
</configSections>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets>
<target name="ErrorsLogger" xsi:type="File" fileName="ErrorsLog.txt" />
<target name="TradesLogger" xsi:type="File" fileName="TradesLog.txt" />
</targets>
<rules>
<logger name="ErrorsLogger" minlevel="Info" writeTo="ErrorsLogger" />
<logger name="TradesLogger" minlevel="Info" writeTo="TradesLogger" />
</rules>
</nlog>
</configuration>
I get the log fine in the .NET 4.6.1 Console app and produces the expected log file with the log message in it.
If I run the .NET Standard 2.0 library through some Microsoft Unit Test project I get this exception when it tries to call _errorLog.GetLogger
UnitTestProject.UnitTest1.TestMethod1 threw exception:
System.TypeInitializationException: The type initializer for
'NLog.LogManager' threw an exception. --->
System.TypeInitializationException: The type initializer for
'NLog.LogFactory' threw an exception. --->
System.MissingMethodException: Method not found:
'System.AppDomainSetup System.AppDomain.get_SetupInformation()'.
EDIT:
Nuget NLOG Version: 4.4.12
Exception thrown in a non static method:
About the non static method to get a better exception:
The exception is thrown at the GetLogger("X") level, which is a non static constructor. The initialization routine crashes even before trying to log something.
In addition, I get a WARNING (yellow exclamation mark) in the error list saying:
Warning The 'configuration' element is not declared.
Adding internal logging doesn't produce any output. This is the configuration i have used, starting from their Internal logging guide:
InternalLogger.LogLevel = LogLevel.Trace;
InternalLogger.LogFile = #"C:\temp\int.txt";
InternalLogger.LogToConsole = true;
InternalLogger.LogToConsoleError = true;
InternalLogger.LogWriter = new StringWriter(new StringBuilder());
InternalLogger.LogToTrace = true;
LogManager.ThrowConfigExceptions = true;
LogManager.ThrowExceptions = true;
Logger logger = LogManager.GetLogger("foo");
I'm administrator and Visual Studio 2017 is started as administrator and I have permission to write in C:\temp ad .NET 4.6.1 console application is able to write in that folder and it's in the same project.
The internal log file is empty and the Unit test project runs the test successfully.
I have no clue of what is happening. No error is thrown now.
Any suggestion to debug the issue is welcome.
An ISSUE on GitHub is already opened.
HERE is a test solution that I made to show you (PASSWORD: logging123). Now that I've updated to Nlog 4.5 you will see that the .NET framework solution throws an error trying to get an old version of Nlog (that I've never referenced) and that .NET Core unit test solution works but doesn't produce any file.
I was experiencing the same issue though I was running .NET 4.7. I updated my NLog package from 4.4.12 to 4.5.0-rc04 and it worked. Knowing its pre-release you may want to be cautions about putting it on live environment though.
Your zipped solution is password protected, so now it is just me guessing, but it looks like you are using app.config to hold nlog.config.
Pretty sure app.config are not being used by NetCoreApps. Try to put your Nlog-config in a separate file called nlog.config and make sure it is Copy Always (In Visual Studio File Properties).

NLog with DNX Core 5.0

I am attempting to implement NLog logging using ASP.Net 5 and MVC 6. Be default, both DNX 451 and DNX Core 50 are included in the project template.
I am attempting to implement NLog Logging by following the example here.
However, in the sample app, there is the following line -
#if !DNXCORE50
factory.AddNLog(new global::NLog.LogFactory());
#endif
And if I run the app, this line never gets hit because the mvc application has dnx core 50 installed by default.
Is there any loggers that are available for DNX Core 50? If not, what purpose does dnx core serve in the default mvc app - is it actually needed?
Edit: If I remove the #if !DNXCORE50.... line above, I get a the following error -
DNX Core 5.0 error - The type or namespace name 'NLog' could not be found in the global namespace'
DNX Core 5.0 is only necessary if you want the cloud-optimized cross-platform version of the .Net framework; if you still plan on using the MVC app within only a Windows environment, you can remove your dnxcore50 framework reference from your project.json.
NLog for .NET Core (DNX environment) is currently available in version 4.4.0-alpha1.
Steps:
Create NLog.config
<?xml version="1.0" encoding="utf-8" ?>
<targets>
<target xsi:type="ColoredConsole" name="ToConsole" />
</targets>
<rules>
<logger name="*" minlevel="Info" writeTo="ToConsole" />
</rules>
Load and parse configuration
private static ILogger _logger;
public static void LoggerSetup()
{
var reader = XmlReader.Create("NLog.config");
var config = new XmlLoggingConfiguration(reader, null); //filename is not required.
LogManager.Configuration = config;
_logger = LogManager.GetCurrentClassLogger();
}
public static void Main(string[] args)
{
LoggerSetup();
// Log anything you want
}
When dealing with the MVC tooling in MVC6 (dnx stuff), the answer to this is very fluid.
In order to get NLog to work with my web app, I had to do a couple steps:
-> Big thanks to two NLog discussions(here and here)
I just needed to add the configuration setup in my Startup.cs's constructor:
public Startup(IHostingEnvironment env)
{
// Set up configuration sources.
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables();
// Set up logging configuration
// from: https://github.com/NLog/NLog/issues/641
// and: https://github.com/NLog/NLog/issues/1172
var reader = XmlTextReader.Create(File.OpenRead(Path.Combine(builder.GetBasePath(),"NLog.config"))); //stream preferred above byte[] / string.
LogManager.Configuration = new XmlLoggingConfiguration(reader, null); //filename is not required.
log.Info("NLogger starting");
Configuration = builder.Build();
}
I consider this a bit of a stop-gap as Microsoft is introducing a new Logging interface (that I hope will end up being like SLF4J.org is in Java). Unfortunately, documentation on that is a bit thin at the time I'm writing this. NLog is working diligently on getting themselves an implementation of the new dnx ILoggingProvider interface.
Additional information about my project setup
My NLog.config file is located in the project root folder, next to
the project.json and appsettings.json. I had to do a little digging
inside AddJsonFile() to see how they handled pathing.
I used yeoman.io and their aspnet generator to set up the web project.
Version of NLog, thanks to Lukasz Pyrzyk above:
"NLog": "4.4.0-alpha1"

Owin Startup Detection

I developed an application with Owin Startup class. When i am running the OwinHost.exe, it shows No Assembly found containing OwinStartupAttribute.
But I defined the assembly in my startup class as:
[assembly: OwinStartup(typeof(OwinDemo.BrandStartup))]
I also defined appSettings in the Web.Config file as:
<appSettings>
<add key="owin:AppStartup" value="OwinDemo.Startup, OwinDemo"/>
Project-> right click add new item.
Startup.cs
using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(SignalRChat.Startup))]
namespace SignalRChat
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
}

log4net config settings

I am into the development of a core dll where I have a class library.I want to use log4net to enable logging for exceptions. I have an app.config file in the class library where i have given the settings for the log4net.However when I test the class library the log4net does'nt create logs until i add the app.config in the calling project inspite of the fact that i had added [assembly: log4net.Config.XmlConfigurator(Watch = true)] in the class libary's assemblyinfo.cs and I am using log4net.ILog logger = log4net.LogManager.GetLogger(typeof(ErrorHandler)) where ErrorHandler is the name of my class library's class where log4net's calling functions are handled.Any ideas on what is going wrong?
Secondly, what I want to acheive is the users of my dll will just pass the location where they want to create logs and whether they want to create logs in event viewer or log files from their app.config? They will not handle any other setting of log4net.
Any suggestions or code snippets for the first issue and the second problem?
Only the "main" app.config is active for a .Net application. Your library config file is simply ignored. Either you transfer your settings to the main config file or you use an external config file for log4net. You configure it then for instance like this (assuming you call it log4net.config):
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
Please note that the structure of the config file is a bit different:
<?xml version="1.0" encoding="utf-8" ?>
<log4net>
<appender name="YourAppender" type="..." >
....
</appender>
<root>
<level value="ALL" />
<appender-ref ref="YourAppender" />
</root>
</log4net>
As for your second problem: I am not sure how flexible this has to be. Is it just switching from file appender to event log appender? Depending on your answer you may consider two prepare to configuration files (e.g. file.log4net and eventlog.log4net) and read the configuration as needed (in that case you cannot use the attribute: you call the Configure() method directly) or if your requirements are more complex you might even end up configuring log4net programatically.

Resources