Could not find named connection string Server nhibernate MySql - c#

New to programming and getting this error.
I have no idea Please Help.
this is my save button click and my configuration file.
private void save_Click(object sender, EventArgs e)
{
Details d =new Details();
d.Firstname = firstname.Text;
Configuration cfg=new Configuration();
cfg.Configure("NHibernate.xml");
ISessionFactory sessionfactory = cfg.BuildSessionFactory();
ISession session = sessionfactory.OpenSession();
ITransaction tx = session.BeginTransaction();
session.Save(d);
tx.Commit();
}
My Configuration File Nhibernate.xml
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="hibernate-configuration"
type="NHibernate.Cfg.ConfigurationSectionHandler,NHibernate"/>
</configSections>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<property name="connection.provider">
NHibernate.Connection.DriverConnectionProvider
</property>
<property name="dialect">
NHibernate.Dialect.MySQLDialect,Nhibernate
</property>
<property name="connection.connection_string_name">
Server=localhost;Database=mohit;User ID=root;Password=root
</property>
<mapping assembly="TestNhibernate"/>
</session-factory>
</hibernate-configuration>
</configuration>
please help

You can use either this name="connection.connection_string":
<session-factory>
...
<property name="connection.connection_string">
Server=localhost;Database=mohit;User ID=root;Password=root
</property>
Or the name="connection.connection_string_name" with the <connectionStrings> configuration:
// another web.config section "<connectionStrings>"
<connectionStrings>
<add name="MyName"
connectionString="Server=localhost;Database=mohit;User ID=root;Password=root" />
</connectionStrings>
// here we reference the name defined in the other section
<session-factory>
...
<property name="connection.connection_string_name">MyName</property>

Related

Logging with NLog and runtime parameters to Database

I am trying to log some info to database with NLog, but I can retrieve some DB parameters only at runtime. Tried few solutions, but unsuccessfully.
There is my NLog.config:
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true">
<variable name="sqlDate" value="[${date:format=yyyy-MM-dd HH\:mm\:ss\.fff}]"/>
<targets>
<target name="dataBase"
xsi:type="Database"
dbProvider="System.Data.SqlClient"
connectionString="${gdc:item=myConnectionstring}"
dbDatabase="${gdc:item=myDataBase}">
<commandText>
INSERT INTO [TABLE_NAME]([COL1], [COL2] )
VALUES(#val1, #val2)
</commandText>
<parameter name="#val1" layout="${event-context:item=val1}"/>
<parameter name="#val2" layout="${event-context:item=val2}"/>
</target>
</targets>
<rules>
<logger name="_dataBase" levels="Info" writeTo="dataBase" final="true" />
</rules>
</nlog>
And there is my .NET C# code:
public static class Log
{
private static NLog.Logger _logger = NLog.LogManager.GetCurrentClassLogger();
private static Config _config = LoadConfig();
public static void Info(string val1, string val2)
{
DatabaseTarget databaseTarget = (NLog.Targets.DatabaseTarget)NLog.LogManager.Configuration.FindTargetByName("dataBase");
databaseTarget.ConnectionString = _config.ConnectString;
databaseTarget.DBDatabase = _config.DBName;
NLog.LogManager.ReconfigExistingLoggers();
LogEventInfo info = new LogEventInfo(LogLevel.Info, "_dataBase", "Test_message");
info.Properties["val1"] = val1;
info.Properties["val2"] = val2;
_logger.Log(info);
}
}
And it just do nothing: not crashing, not writing any data to DB. Here is my internal NLog log: http://pastebin.com/0tLi9zJ1
How can I fix this?
P.S. Sorry for my last try to ask this question, it looks like I forgot to put to it some necessary information.
So, the working code is:
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true">
<variable name="sqlDate" value="${date:format=yyyy-MM-dd HH\:mm\:ss\.fff}"/>
<targets>
<target name="dataBase"
xsi:type="Database"
dbProvider="System.Data.SqlClient"
connectionString="${gdc:item=myConnectionString}"
dbDatabase="${gdc:item=myDataBase}">
<commandText>
INSERT INTO [TABLE_NAME]([COL1], [COL2] )
VALUES(#val1, #val2)
</commandText>
<parameter name="#val1" layout="${event-context:item=val1}"/>
<parameter name="#val2" layout="${event-context:item=val2}"/>
</target>
</targets>
<rules>
<logger name="_dataBase" levels="Info" writeTo="dataBase" final="true" />
</rules>
</nlog>
public static class Log
{
private static Config _config = LoadConfig();
public static void Info(string val1, string val2)
{
NLog.Logger logger = NLog.LogManager.GetLogger("_dataBase");
GlobalDiagnosticsContext.Set("myConnectionString", _config.ConnectString);
GlobalDiagnosticsContext.Set("myDataBase", _config.DBName);
LogEventInfo info = new LogEventInfo(LogLevel.Info, "_dataBase", "Test_message");
info.Properties["val1"] = val1;
info.Properties["val2"] = val2;
logger.Log(info);
}
}

Write appSettings in external file

I have a config file app.exe.config and appSettings section has something like this:
<configuration>
<appSettings configSource="app.file.config" />
</configuration>
app.file.config file has something like this:
<?xml version="1.0" encoding="utf-8" ?>
<appSettings>
<add key="var1" value="value 1" />
<add key="var2" value="value 2" />
<add key="var3" value="value 3" />
</appSettings>
I need to edit var1, var2 and var3 at runtime and I have code like this:
Configuration config = ConfigurationManager.OpenExeConfiguration("...path\app.exe);
config.AppSettings.SectionInformation.ConfigSource = "app.file.config";
config.AppSettings.Settings["var1"].Value = "value 11";
config.AppSettings.Settings["var2"].Value = "value 22";
config.AppSettings.Settings["var3"].Value = "value 33";
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
When I run config.Save.... the file app.file.config has a appSettings node with an attribute "file". This attribute has the value to app.file.config
<appSettings file="app.file.config">
<add key="var1" value="value 1" />
<add key="var2" value="value 2" />
<add key="var3" value="value 3" />
</appSettings>
Now, if I try to load the config file, I have an exception with message "Unrecognized attribute 'file'. Note that attribute names are case-sensitive." in app.file.config.
If I delete the file attribute manually, the configuration file is loaded properly.
Any ideas?
How can avoid to write file attribute when I save config files.
Thanks
using an external config file is transparent for the application,
this part is o.k
</configuration>
<appSettings configSource="app.file.config" />
</configuration>
and also this:
<?xml version="1.0" encoding="utf-8" ?>
<appSettings>
<add key="var1" value="value 1" />
<add key="var2" value="value 2" />
<add key="var3" value="value 3" />
</appSettings>
change your code to be like this:
Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
config.AppSettings.Settings["var1"].Value = "value 11";
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
referring an external configuration file is transparent to the application,
so you don't have to call it directly. you can use the default appSetting section in the configuration manager.
Good luck
A more complete answer to prevent confusion:
Setup:
Commandline project called 'app'
app.exe.config file, App.config:
<appSettings file="App.Settings.config"></appSettings>
App.Settings.config file with 'Copy to Output Directory'= 'Copy Always'
<?xml version="1.0" encoding="utf-8"?>
<appSettings>
<add key="test" value="OVERRIDDEN"/>
</appSettings>
Program.cs:
static void Main(string[] args)
{
try
{
Console.WriteLine("Local Config sections");
var exepath = (new Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase)).LocalPath;
Configuration config = ConfigurationManager.OpenExeConfiguration(exepath);
config.AppSettings.SectionInformation.ConfigSource = "App.Settings.config";
Console.WriteLine("BEFORE[test]=" + config.AppSettings.Settings["test"].Value);
Console.WriteLine($"BEFORE[testExternalOnly]={config.AppSettings.Settings["testExternalOnly"]?.Value}");
//to avoid: Error CS0266
//Explicitly cast 'System.Configuration.AppSettingsSection'
AppSettingsSection myAppSettings = (AppSettingsSection)config.GetSection("appSettings");
myAppSettings.Settings["test"].Value = "NEW";
if (!myAppSettings.Settings.AllKeys.Contains("testExternalOnly"))
myAppSettings.Settings.Add("testExternalOnly", "NEWEXTERNAL");
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
//Read updated config
Console.WriteLine("AFTER[test]=" + config.AppSettings.Settings["test"].Value);
Console.WriteLine("AFTER[testExternalOnly]=" + config.AppSettings.Settings["testExternalOnly"].Value);
Console.WriteLine("AFTER CONFIG EXTERNAL FILE: " + System.IO.File.ReadAllText("App.Settings.config"));
Console.WriteLine("AFTER CONFIG FILE: " + System.IO.File.ReadAllText(System.AppDomain.CurrentDomain.FriendlyName + ".config"));
//Shut current config
config = null;
//Open config
config = ConfigurationManager.OpenExeConfiguration(exepath);
config.AppSettings.SectionInformation.ConfigSource = "App.Settings.config";
Console.WriteLine("AFTER[test]=" + config.AppSettings.Settings["test"].Value);
Console.WriteLine("AFTER[testExternalOnly]=" + config.AppSettings.Settings["testExternalOnly"].Value);
Console.WriteLine("AFTER CONFIG EXTERNAL FILE: " + System.IO.File.ReadAllText("App.Settings.config"));
Console.WriteLine("AFTER CONFIG FILE: " + System.IO.File.ReadAllText(System.AppDomain.CurrentDomain.FriendlyName + ".config"));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.WriteLine("press the ENTER key to end");
Console.ReadLine();
}
This will result in App.Settings.config file updated to be on the filesystem as:
<?xml version="1.0" encoding="utf-8"?>
<appSettings>
<add key="test" value="NEW" />
<add key="testExternalOnly" value="NEWEXTERNAL" />
</appSettings>
Finally, I have found a solution.
The solution is to declare the config file as this:
<appSettings configSource="app.file.config">
<add key="var1" value="value 1" />
<add key="var2" value="value 2" />
<add key="var3" value="value 3" />
</appSettings>
And from code
Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
AppSettingsSection myAppSettings = config.GetSection("appSettings")
myAppSettings.Settings["var1"].Value = "value 11";
config.Save(ConfigurationSaveMode.Modified);
Note that I use
GetSection("appSettings")
instead of
config.AppSettings.Settings
Thanks to all that help people in StackOverflow.

No persister for class Error

when i run the application i get "No persister for Test.Student" Error
I am new in Nhibernate Mapping ,i can't figure this out
How can i solve ?? plz help
NHibernate Configuration part
App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="hibernate-configuration"
type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate" />
</configSections>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<property name="connection.provider">
NHibernate.Connection.DriverConnectionProvider
</property>
<property name="connection.driver_class">
NHibernate.Driver.SqlClientDriver
</property>
<property name="connection.connection_string">
Server=(local);database=Student;Integrated Security=SSPI;
</property>
<property name="dialect">
NHibernate.Dialect.MsSql2005Dialect
</property>
<!--<property name="proxyfactory.factory_class">
NHibernate.Bytecode.DefaultProxyFactoryFactory, NHibernates
</property>-->
<property name="show_sql">
false
</property>
</session-factory>
Main Program
program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using NHibernate.Cfg;
namespace Test
{
class Program
{
static void Main(string[] args)
{
ISessionFactory factor = new Configuration().Configure().BuildSessionFactory();
if(factor!=null){
Console.WriteLine("Configured");
}
else{
Console.WriteLine("Not Configured");
}
Student std = new Student { Fname = "James", Lname = "Bond", Address = "32 Baker Street", Institution = "MIT" };
using (ISession session = factor.OpenSession())
{
using (ITransaction transaction= session.BeginTransaction())
{
try
{
session.Save(std);
transaction.Commit();
session.Close();
}
catch(Exception e)
{
Console.WriteLine("ERROR :" + e);
}
}
}
}
//protected ISessionFactory factory;
protected void execute_query()
{
}
}
}
Mapping part
Student.hbm.xml
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" auto-import="true">
<class name="Test.Student" table="Info" lazy="true">
<id name="Id" type="int" column="Id">
<generator class="native" />
</id>
<property name="Fname" column ="Fname"/>
<property name="Lname" column="Lname"/>
<property name="Address" column="Address"/>
<property name="Institution" column="Institution"/>
<!-- We don't have to specify a column name if its the same
as the variable name -->
You need to add mapping assembly name in your app.config file as described here.
<property name="show_sql">false</property>
<mapping assembly="Test"/> <!-- Here -->
</session-factory>
Also make sure to mark the XML file as Embedded Resource if haven't.

Custom Config section in App.config C#

I'm a quite beginner with config sections in c#
I want to create a custom section in config file. What I've tried after googling is as the follows
Config file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="MyCustomSections">
<section name="CustomSection" type="CustomSectionTest.CustomSection,CustomSection"/>
</sectionGroup>
</configSections>
<MyCustomSections>
<CustomSection key="Default"/>
</MyCustomSections>
</configuration>
CustomSection.cs
namespace CustomSectionTest
{
public class CustomSection : ConfigurationSection
{
[ConfigurationProperty("key", DefaultValue="Default", IsRequired = true)]
[StringValidator(InvalidCharacters = "~!##$%^&*()[]{}/;'\"|\\", MinLength = 1, MaxLength = 60)]
public String Key
{
get { return this["key"].ToString(); }
set { this["key"] = value; }
}
}
}
When I use this code to retrieve Section I get an error saying configuration error.
var cf = (CustomSection)System.Configuration.ConfigurationManager.GetSection("CustomSection");
What am I missing?
Thanks.
Edit
What I need ultimately is
<CustomConfigSettings>
<Setting id="1">
<add key="Name" value="N"/>
<add key="Type" value="D"/>
</Setting>
<Setting id="2">
<add key="Name" value="O"/>
<add key="Type" value="E"/>
</Setting>
<Setting id="3">
<add key="Name" value="P"/>
<add key="Type" value="F"/>
</Setting>
</CustomConfigSettings>
App.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="customAppSettingsGroup">
<section name="customAppSettings" type="System.Configuration.AppSettingsSection, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</sectionGroup>
</configSections>
<customAppSettingsGroup>
<customAppSettings>
<add key="KeyOne" value="ValueOne"/>
<add key="KeyTwo" value="ValueTwo"/>
</customAppSettings>
</customAppSettingsGroup>
</configuration>
Usage:
NameValueCollection settings =
ConfigurationManager.GetSection("customAppSettingsGroup/customAppSettings")
as System.Collections.Specialized.NameValueCollection;
if (settings != null)
{
foreach (string key in settings.AllKeys)
{
Response.Write(key + ": " + settings[key] + "<br />");
}
}
Try using:
var cf = (CustomSection)System.Configuration.ConfigurationManager.GetSection("MyCustomSections/CustomSection");
You need both the name of the section group and the custom section.
Highlight ConfigurationSection press F1,
You will see that the implementation on the MSDN website overrides a property called "Properties" which returns a "ConfigurationPropertyCollection", as your properties have a matching attribute of that type you should be able to populate this collection with your properties if not wrap them in the same way the MS guys have.

NHibernate.NHibernateException: Unable to locate row for retrieval of generated properties: [MyNamespace.Company#<null>]

It looks like all of my mappings are compiling correctly, I'm able to validly get a session from session factory. However, when I try to ISession.SaveOrUpdate(obj); I get this. Can anyone please help point me in the right direction?
private Configuration configuration;
protected Configuration Configuration {
get
{
configuration = configuration ?? GetNewConfiguration();
return configuration;
}
}
protected ISession GetNewSession() {
var sessionFactory = Configuration.BuildSessionFactory();
var session = sessionFactory.OpenSession();
return session;
}
[TestMethod] public void
TestSessionSave() {
var company = new Company();
company.Name = "Test Company 1";
DateTime savedAt = DateTime.Now;
using (var session = GetNewSession())
{
try
{
session.SaveOrUpdate(company);
}
catch (Exception e)
{
throw e;
}
}
Assert.IsTrue((company.CreationDate != null && company.CreationDate > savedAt), "Company was saved, creation date was set."); }
For those that might be interested, here is my mapping for this class:
<!-- Company -->
<class name="MyNamespace.Company,MyLibrary" table="Companies">
<id name="Id" column="Id">
<generator class="native" />
</id>
<property name="ExternalId" column="GUID" generated="insert" />
<property name="Name" column="Name" type="string" />
<property name="CreationDate" column="CreationDate" generated="insert" />
<property name="UpdatedDate" column="UpdatedDate" generated="always" />
</class>
<!-- End Company -->
Finally, here is my config -- I'm just connecting to a SQL Server CE instance for this for testing purposes.
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory name="">
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="connection.driver_class">NHibernate.Driver.SqlServerCeDriver</property>
<property name="connection.connection_string">Data Source="D:\Build\MyProject\Source\MyProject.UnitTests\MyProject.TestDatabase.sdf"</property>
<property name="dialect">NHibernate.Dialect.MsSqlCeDialect</property>
<property name="proxyfactory.factory_class">NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property>
</session-factory>
</hibernate-configuration>
Thanks!
It might be a problem retrieving the identity value.
Are you sure Id is declared as identity in the DB? That's what you're telling NHibernate when declaring <generator class="native" />.
If this is a new database, it would also be useful to use a client-side generator, like guid.comb or hilo.
One more thing about your code. This:
catch (Exception e)
{
throw e;
}
Is harmful, because all it does is swallow the stack trace, with might provide additional debugging information.

Categories