nhibernate 3.2 how to turn off show_sql - nhibernate

I am using nhibernate 3.2, I dont know by default show_sql is turned on or off, but decided to turn it off in my configuration anyway.
I dont know how to turn show_sql off, but I have following 2 lines in my configuration file. are they the same?
db.LogFormattedSql = false;
db.LogSqlInConsole = false;
public static Configuration Initialize()
{
var configuration = new Configuration();
configuration
.Proxy(p => p.ProxyFactoryFactory<DefaultProxyFactoryFactory>())
.DataBaseIntegration(db =>
{
db.ConnectionStringName = "test";
db.Dialect<MySQLDialect>();
db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
db.LogFormattedSql = false;
db.LogSqlInConsole = false;
})
.AddAssembly(typeof(User).Assembly)
.CurrentSessionContext<LazySessionContext>();
var mapper = new ConventionModelMapper();
mapper.WithConventions(configuration);
return configuration;
}

LogSqlInConsole enables or disables SQL console logging.
LogFormattedSql enables or disables formatting of that SQL.

Related

ASP.NET Core - Redis Sentinel, Getting Error because of ServiceName, HOW TO GET SERVICE NAME?

I have a project with ASP.NET Core integrated with Redis Sentinel.
Caching works very well with Sentinel but it doesn't work while getting all keys with GetServer(), and it wants me to give it a parameter ServiceName, I don't know how to find it??
There is a Master and 4 Slaves
--> appsettings.json
RedisConfiguration:ConnectionString --- > "127.0.0.1:6379,127.0.0.1:6380,127.0.0.1:6381,127.0.0.1:6382,127.0.0.1:6383"
--> RedisCacheManager.cs
Constructor :
public RedisCacheManager()
{
_connectionString = configuration.GetSection("RedisConfiguration:ConnectionString")?.Value;
var connectionStrings = _connectionString.Split(",");
_configurationOptions = new ConfigurationOptions()
{
EndPoints = { aa.ToString() },
AbortOnConnectFail = false,
AsyncTimeout = 10000,
ConnectTimeout = 10000,
KeepAlive = 180,
//ServiceName = ServiceName
};
foreach (var item in connectionStrings)
{
_configurationOptions.EndPoints.Add(item);
}
_client = ConnectionMultiplexer.Connect(_configurationOptions);
}
--> RemoveByPattern method in RedisCacheManager.cs
public void RemoveByPattern()
{
//THIS IS WHERE I USE SENTINEL CONNECT AND CONFIG OPTIONS....
//var aa = ConnectionMultiplexer.SentinelConnect(_configurationOptions);
//THIS IS ALSO WHERE I NEED SERVICE NAME... (FOUND THIS WHILE RESEARCHING)
//var settings = ConfigurationOptions.Parse("localhost,serviceName=mymaster");
// HERE I HAVE TO USE ONLY ONE ENDPOINT....
var server = ConnectionMultiplexer.Connect(settings).GetServer(_client.GetEndPoints().First());
var keys = server.Keys();
var values = keys.Where(x => x.ToString().Contains(pattern)).Select(c => (string)c);
List<string> listKeys = new();
listKeys.AddRange(values);
foreach (var key in listKeys)
{
await _client.GetDatabase().KeyDeleteAsync(key);
}
}

Programmatic configuration of NLog in ASP.NET Core application to filter unwanted chatter?

I'm attempting to filter out all the unnecessary chatter from the Microsoft hosting assemblies, while still allowing Debug-level messages from our own code to pass through to our logging targets.
Here's code that configures NLog and initializes a web app. Unfortunately, the Microsoft.* and System.* namespace filtering does not functional at all. The result is that all messages Debug and higher are logged.
I do not want to use the old nlog.config process. I want to be able to build the LoggingConfiguration in code.
I really must be missing something easy here, but I don't see it!
public static void Main(string[] args)
{
// Read configuration from a variety of sources to compose our final IConfiguration
var config = ReadOurConfigFromLotsOfPlaces();
var nLogConfig = new LoggingConfiguration();
var consoleTarget = new ColoredConsoleTarget("console")
{
AutoFlush = true,
ErrorStream = true,
Layout = #"${date:format=yyyy-MM-dd HH\:mm\:ss.fff} ${level} [${logger}] - ${message}${onexception:${newline}}${exception:format=shortType,message,stackTrace:maxInnerExceptionLevel=5}"
};
nLogConfig.AddTarget(consoleTarget);
nLogConfig.LoggingRules.Add(new LoggingRule("Microsoft.*", LogLevel.Warn, consoleTarget) {Final = true});
nLogConfig.LoggingRules.Add(new LoggingRule("System.*", LogLevel.Warn, consoleTarget) {Final = true});
nLogConfig.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, consoleTarget));
var logger = NLogBuilder.ConfigureNLog(nLogConfig).GetCurrentClassLogger();
logger.Debug("NLog initialization complete");
try
{
logger.Debug("init main");
CreateHostBuilder(config).Build().Run();
}
catch (Exception exception)
{
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)
LogManager.Shutdown();
}
}
public static IWebHostBuilder CreateHostBuilder(IConfiguration config)
{
// we don't call CreateDefaultBuilder() because we already have assembled the configuration we want to use
return new WebHostBuilder()
.UseConfiguration(config)
.UseKestrel(options => options.UseSystemd())
.UseStartup<Startup>()
.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
})
.UseNLog();
}
Any tips would be greatly appreciated.
Ugh. I understand my problem now: The 'LoggingRules' is looking for a positive match between logger name and the min/max level values, so my first two LoggingRule objects did not match messages coming from the Microsoft.* and System.* namespaces, so the rules did nothing with those messages.
In order to accomplish the filtering I want, this is the solution:
var nLogConfig = new LoggingConfiguration();
var consoleTarget = new ColoredConsoleTarget("console")
{
AutoFlush = true,
ErrorStream = true,
Layout = #"${date:format=yyyy-MM-dd HH\:mm\:ss.fff} ${level} [${logger}] - ${message}${onexception:${newline}}${exception:format=shortType,message,stackTrace:maxInnerExceptionLevel=5}"
};
nLogConfig.AddTarget(consoleTarget);
var nullTarget = new NullTarget("null");
nLogConfig.AddTarget(nullTarget);
// matches every Microsoft.* logger with a LogLevel less than LogLevel.Warn
nLogConfig.LoggingRules.Add(new LoggingRule("Microsoft.*", LogLevel.Trace, LogLevel.Info, nullTarget) {Final = true});
// matches every System.* logger with a LogLevel less than LogLevel.Warn
nLogConfig.LoggingRules.Add(new LoggingRule("System.*", LogLevel.Trace, LogLevel.Info, nullTarget) {Final = true});
// and everything else, LogLevel.Debug and higher
nLogConfig.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, consoleTarget));

Serilog Elasticsearch

i have a microservice api where I try to log all the request which come in...so the elasticsaerch service and kibana are on a different server. I'm using the serilog.sinks.elasticsearch package to send data to the elasticsearch.
Both servers are not running with docker, they are just normal windows server.
My code looks like this to setup the logging...
public static Logger Create(IConfiguration configuration)
{
var elasticsearchSection = configuration.GetSection("Elasticsearch");
if (elasticsearchSection != null)
{
return CreateLoggerConfiguration(elasticsearchSection).CreateLogger();
}
return null;
}
private static LoggerConfiguration CreateLoggerConfiguration(IConfigurationSection section)
{
var loggerConfiguration = new LoggerConfiguration();
var url = section.GetValue<string>("Url");
var minimumLogLevel = section.GetValue<string>("MinimumLogLevel");
var minimumLogEventLevel = section.GetValue<string>("MinimumLogEventLevel");
SetLoggerConfigurationMinimumLogLevel(minimumLogLevel, loggerConfiguration);
loggerConfiguration.WriteTo.Elasticsearch(new ElasticsearchSinkOptions(GetLoggingUri(url))
{
MinimumLogEventLevel = ReturnLogEventLevel(minimumLogEventLevel),
AutoRegisterTemplate = true
});
loggerConfiguration.Enrich.FromLogContext();
return loggerConfiguration;
}
And in my startup,cs I'm using
services.AddLogging(loggingBuilder => loggingBuilder.AddSerilog(dispose: true));
in the ConfigureServices Method...
But apparently I cant create an Index inside my Kibana.
Any ideas why this isnt working?

Asp Net Core Identity UserManager change context

I have implemented the microsoft identity framework, I'm using the UserManager via dependecy injection, since it is a multi-tenancy project I would need to extend the UserManager class to pass the desired context, I searched on google but I could not find or better adapt anything For my case.
_userManagerRepository = new UserManagerRepository(new PortaleContext(tenantContext.Tenant))
_userMgr = new UserManager<ApplicationUser>(userStore,null,null,null,null,null,null,null,null);
But when I run this method:
var passwordResetToken = await _userMgr.GeneratePasswordResetTokenAsync(user)
I get the following error:
<div class="titleerror">NotSupportedException: No IUserTokenProvider named 'Default' is registered.</div>
<p class="location">Microsoft.AspNetCore.Identity.UserManager+<VerifyUserTokenAsync>d__122.MoveNext()</p>
And this is a part of my startup class:
services.AddIdentity<ApplicationUser, IdentityRole>(config =>
{
config.User.RequireUniqueEmail = true;
config.Password.RequiredLength = 8;
// config.Cookies.ApplicationCookie.LoginPath = "/App/Login";
config.SignIn.RequireConfirmedEmail = false;
config.SignIn.RequireConfirmedPhoneNumber = false;
})
.AddEntityFrameworkStores<AdminContext>()
.AddDefaultTokenProviders();
services.AddIdentity<ApplicationUser, IdentityRole>(config =>
{
config.User.RequireUniqueEmail = true;
config.Password.RequiredLength = 8;
config.Password.RequireNonAlphanumeric = false;
config.Password.RequireUppercase = false;
// config.Cookies.ApplicationCookie.LoginPath = "/App/Login";
config.SignIn.RequireConfirmedEmail = false;
config.SignIn.RequireConfirmedPhoneNumber = false;
})
.AddEntityFrameworkStores<PortaleContext>()
.AddDefaultTokenProviders();
In a nutshell, depending on which address the request arrives, the usermanager must update to its context
This article references an error when calling AddDefaultTokenProviders() Twice. This may be your issue, I am looking for a similar solution but this one didn't work for me, but maybe you haven't seen it yet and it works for you.
https://github.com/aspnet/Identity/issues/972

NHibernate 3.2: SchemaExport not working with SQLite

I'm using an in-memory db for some quick unit tests, using the following code:
public class MemoryDb
{
private static Configuration configuration;
private static ISessionFactory sessionFactory;
static MemoryDb()
{
configuration = new NHibernate.Cfg.Configuration();
configuration.DataBaseIntegration(x =>
{
x.Driver<SQLite20Driver>();
x.Dialect<SQLiteDialect>();
x.ConnectionProvider<DriverConnectionProvider>();
x.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
x.IsolationLevel = IsolationLevel.ReadCommitted;
x.ConnectionString = "Data Source=:memory:;";
x.Timeout = 255;
x.BatchSize = 100;
x.LogFormattedSql = true;
x.LogSqlInConsole = true;
x.AutoCommentSql = false;
});
configuration.AddMapping(DbHelper.GetAutoMappings());
sessionFactory = configuration.BuildSessionFactory();
}
public static ISession GetSession()
{
var session = sessionFactory.OpenSession();
new SchemaExport(configuration).Execute(true, true, false, session.Connection, null);
return session;
}
}
The problem is that the schema export doesn't seem to be working. On of my tests looks like this:
[Fact]
public void ShouldFindDuplicateByEmail()
{
using (var session = MemoryDb.GetSession())
{
var repo = new NHibernateCustomerRepository(session);
var customer = new Customer();
customer.EmailAddress = "test#test.com";
repo.Save(customer);
var duplicates = repo.FindDuplicates(customer);
Assert.Equal(1, duplicates.Length);
}
}
The test fails with the error no such table: Customers. This all worked with Fluent NHibernate and NHibernate 3.1. I know it's not an issue with the mappings themselves, because the actual application works when I run it against an existing SQL Server db. It only fails when running the tests. Any thoughts?
Edit: If I change only the connection string such that it writes to a file (i.e. x.ConnectionString = "data source=" + Path.GetTempFileName();, the whole thing works. I'm guessing either the schema isn't run correctly against the in-memory db, or it's getting a new in-memory db each time I execute a session command, but have no clue how to figure this out.
I found the answer here: https://forum.hibernate.org/viewtopic.php?p=2397541#p2397541
I had to add the following to the db configuration:
x.ConnectionReleaseMode = ConnectionReleaseMode.OnClose;
Otherwise, NHibernate releases the connection after each statement is flushed, thereby getting rid of the in-memory database with the schema.