Nhibernate 2.1 and mysql 5 - InvalidCastException on Setup - c#

I am trying to use NHibernate with Spring.Net und mySQL 5. However, when setting up the connection and creating the SessionFactoryObject, I get this InvalidCastException:
NHibernate seems to cast MySql.Data.MySqlClient.MySqlConnection to System.Data.Common.DbConnection which causes the exception.
System.InvalidCastException wurde nicht behandelt.
Message="Das Objekt des Typs \"MySql.Data.MySqlClient.MySqlConnection\" kann nicht in Typ \"System.Data.Common.DbConnection\" umgewandelt werden."
Source="NHibernate"
StackTrace:
bei NHibernate.Tool.hbm2ddl.SuppliedConnectionProviderConnectionHelper.Prepare() in c:\CSharp\NH\nhibernate\src\NHibernate\Tool\hbm2ddl\SuppliedConnectionProviderConnectionHelper.cs:Zeile 25.
bei NHibernate.Tool.hbm2ddl.SchemaMetadataUpdater.GetReservedWords(Dialect dialect, IConnectionHelper connectionHelper) in c:\CSharp\NH\nhibernate\src\NHibernate\Tool\hbm2ddl\SchemaMetadataUpdater.cs:Zeile 43.
bei NHibernate.Tool.hbm2ddl.SchemaMetadataUpdater.Update(ISessionFactory sessionFactory) in c:\CSharp\NH\nhibernate\src\NHibernate\Tool\hbm2ddl\SchemaMetadataUpdater.cs:Zeile 17.
bei NHibernate.Impl.SessionFactoryImpl..ctor(Configuration cfg, IMapping mapping, Settings settings, EventListeners listeners) in c:\CSharp\NH\nhibernate\src\NHibernate\Impl\SessionFactoryImpl.cs:Zeile 169.
bei NHibernate.Cfg.Configuration.BuildSessionFactory() in c:\CSharp\NH\nhibernate\src\NHibernate\Cfg\Configuration.cs:Zeile 1090.
bei OrmTest.Program.Main(String[] args) in C:\Users\Max\Documents\Visual Studio 2008\Projects\OrmTest\OrmTest\Program.cs:Zeile 24.
bei System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
bei System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
bei Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
bei System.Threading.ThreadHelper.ThreadStart_Context(Object state)
bei System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
bei System.Threading.ThreadHelper.ThreadStart()
InnerException:
I am using the programmatically setup approach in order to get a quick NHibernate Setup. Here is the setup Code:
Configuration config = new Configuration();
Dictionary props = new Dictionary();
props.Add("dialect", "NHibernate.Dialect.MySQL5Dialect");
props.Add("connection.provider", "NHibernate.Connection.DriverConnectionProvider");
props.Add("connection.driver_class", "NHibernate.Driver.MySqlDataDriver");
props.Add("connection.connection_string", "Server=localhost;Database=orm_test;User ID=root;Password=password");
props.Add("proxyfactory.factory_class", "NHibernate.ByteCode.Spring.ProxyFactoryFactory, NHibernate.ByteCode.Spring");
config.AddProperties(props);
config.AddFile("Person.hbm.xml");
ISessionFactory factory = config.BuildSessionFactory();
ISession session = factory.OpenSession();
Is something missing? I downloaded the current mysql Connector from the mysql Website.

Shame on me, I downloaded accidently a wrong mysql connector and not the latest version: http://dev.mysql.com/downloads/connector/net/6.0.html
Sorry!

Related

P/Invoke CryptUnprotectData breaks SqlConnection constructor

I'm attempting to use CryptUnprotectData to read a password protected using CryptProtectData into a SecureString and use that to connect to a database. I can get the correct password out, but trying to create a new SqlConnection after that fails with the following:
System.TypeInitializationException was unhandled
HResult=-2146233036
Message=The type initializer for 'System.Data.SqlClient.SqlConnection' threw an exception.
Source=System.Data
TypeName=System.Data.SqlClient.SqlConnection
StackTrace:
at System.Data.SqlClient.SqlConnection..ctor()
at System.Data.SqlClient.SqlConnection..ctor(String connectionString, SqlCredential credential)
at System.Data.SqlClient.SqlConnection..ctor(String connectionString)
at ProtectedSqlTest.Program.Main() in C:\Git\ProtectedSqlTest\ProtectedSqlTest\Program.cs:line 16
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
HResult=-2146233036
Message=The type initializer for 'System.Data.SqlClient.SqlConnectionFactory' threw an exception.
Source=System.Data
TypeName=System.Data.SqlClient.SqlConnectionFactory
StackTrace:
at System.Data.SqlClient.SqlConnection..cctor()
InnerException:
HResult=-2146233036
Message=The type initializer for 'System.Data.SqlClient.SqlPerformanceCounters' threw an exception.
Source=System.Data
TypeName=System.Data.SqlClient.SqlPerformanceCounters
StackTrace:
at System.Data.SqlClient.SqlConnectionFactory..cctor()
InnerException:
HResult=-2147024809
Message=The parameter is incorrect. (Exception from HRESULT: 0x80070057 (E_INVALIDARG))
Source=mscorlib
StackTrace:
at System.Globalization.TextInfo.InternalChangeCaseString(IntPtr handle, IntPtr handleOrigin, String localeName, String str, Boolean isToUpper)
at System.Globalization.TextInfo.ToLower(String str)
at System.String.ToLower(CultureInfo culture)
at System.Diagnostics.PerformanceCounterLib.GetPerformanceCounterLib(String machineName, CultureInfo culture)
at System.Diagnostics.PerformanceCounterLib.IsCustomCategory(String machine, String category)
at System.Diagnostics.PerformanceCounter.InitializeImpl()
at System.Diagnostics.PerformanceCounter.set_RawValue(Int64 value)
at System.Data.ProviderBase.DbConnectionPoolCounters.Counter..ctor(String categoryName, String instanceName, String counterName, PerformanceCounterType counterType)
at System.Data.ProviderBase.DbConnectionPoolCounters..ctor(String categoryName, String categoryHelp)
at System.Data.SqlClient.SqlPerformanceCounters..ctor()
at System.Data.SqlClient.SqlPerformanceCounters..cctor()
InnerException:
It's enough to simply call CryptUnprotectData for the SqlConnection to fail, the connection itself doesn't need to use the returned SecureString.
I'm using the extension methods from here as described in this post for my minimal repro:
class Program
{
const string ProtectedSecret = /* SNIP - base 64 encoded protected data here */;
static void Main()
{
// calling AppendProtectedData breaks the following SqlConnection
// without the following line the application works fine
new SecureString().AppendProtectedData(Convert.FromBase64String(ProtectedSecret));
using (var conn = new SqlConnection("Server=(localdb)\\MSSqlLocalDb;Trusted_Connection=true"))
using (var cmd = new SqlCommand("select 1", conn))
{
conn.Open();
cmd.ExecuteNonQuery();
}
}
}
If i create a new SqlConnection before I load the password, I can create new SqlConnections fine for the duration of the application as it seems to use the same SqlConnectionFactory, but that means as a workaround I have to do something like this at the start of the application:
new SqlConnection().Dispose();
... which I'd like to avoid.
The following do not help:
Debug vs Release build
Debugging in Visual Studio vs running through the command line
Changing the CryptProtectFlags that is passed to CryptUnprotectData.
Removing RuntimeHelpers.PrepareConstrainedRegions() from the protection method.
Windows 10, VS Enterprise 2015, Console Application (.NET 4.6.1)
UPDATE: Running the data protection code in another threads gives a similar exception with a different root cause:
System.TypeInitializationException was unhandled
HResult=-2146233036
Message=The type initializer for 'System.Data.SqlClient.SqlConnection' threw an exception.
Source=System.Data
TypeName=System.Data.SqlClient.SqlConnection
StackTrace:
at System.Data.SqlClient.SqlConnection..ctor()
at System.Data.SqlClient.SqlConnection..ctor(String connectionString, SqlCredential credential)
at System.Data.SqlClient.SqlConnection..ctor(String connectionString)
at ProtectedSqlTest.Program.Main() in C:\Git\ProtectedSqlTest\ProtectedSqlTest\Program.cs:line 17
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
HResult=-2146233036
Message=The type initializer for 'System.Data.SqlClient.SqlConnectionFactory' threw an exception.
Source=System.Data
TypeName=System.Data.SqlClient.SqlConnectionFactory
StackTrace:
at System.Data.SqlClient.SqlConnection..cctor()
InnerException:
HResult=-2146233036
Message=The type initializer for 'System.Data.SqlClient.SqlPerformanceCounters' threw an exception.
Source=System.Data
TypeName=System.Data.SqlClient.SqlPerformanceCounters
StackTrace:
at System.Data.SqlClient.SqlConnectionFactory..cctor()
InnerException:
BareMessage=Configuration system failed to initialize
HResult=-2146232062
Line=0
Message=Configuration system failed to initialize
Source=System.Configuration
StackTrace:
at System.Configuration.ClientConfigurationSystem.EnsureInit(String configKey)
at System.Configuration.ClientConfigurationSystem.PrepareClientConfigSystem(String sectionName)
at System.Configuration.ClientConfigurationSystem.System.Configuration.Internal.IInternalConfigSystem.GetSection(String sectionName)
at System.Configuration.ConfigurationManager.GetSection(String sectionName)
at System.Configuration.PrivilegedConfigurationManager.GetSection(String sectionName)
at System.Diagnostics.DiagnosticsConfiguration.Initialize()
at System.Diagnostics.DiagnosticsConfiguration.get_SwitchSettings()
at System.Diagnostics.Switch.InitializeConfigSettings()
at System.Diagnostics.Switch.InitializeWithStatus()
at System.Diagnostics.Switch.get_SwitchSetting()
at System.Data.ProviderBase.DbConnectionPoolCounters..ctor(String categoryName, String categoryHelp)
at System.Data.SqlClient.SqlPerformanceCounters..ctor()
at System.Data.SqlClient.SqlPerformanceCounters..cctor()
InnerException:
HResult=-2147024809
Message=Item has already been added. Key in dictionary: 'MACHINE' Key being added: 'MACHINE'
Source=mscorlib
StackTrace:
at System.Collections.Hashtable.Insert(Object key, Object nvalue, Boolean add)
at System.Collections.Hashtable.Add(Object key, Object value)
at System.Configuration.Internal.InternalConfigRoot.GetConfigRecord(String configPath)
at System.Configuration.ClientConfigurationSystem.EnsureInit(String configKey)
InnerException:
Interestingly the faulting code is:
internal static PerformanceCounterLib GetPerformanceCounterLib(string machineName, CultureInfo culture) {
SharedUtils.CheckEnvironment();
string lcidString = culture.LCID.ToString("X3", CultureInfo.InvariantCulture);
if (machineName.CompareTo(".") == 0)
machineName = ComputerName.ToLower(CultureInfo.InvariantCulture);
else
machineName = machineName.ToLower(CultureInfo.InvariantCulture);
...
the line that calls ComputerName.ToLower(CultureInfo.InvariantCulture) causes the exception.
You can reproduce the same behavior just calling code
new SecureString().AppendProtectedData(Convert.FromBase64String(ProtectedSecret));
string lower = "Something".ToLower(CultureInfo.InvariantCulture);
Somehow in the constructor of the TextInfo class
this.m_dataHandle = CompareInfo.InternalInitSortHandle(m_textInfoName, out handleOrigin);
returns invalid data if this is not called before CryptUnprotectData function.
This seems like a bug in the framework. You can submit it to Microsoft. In the meantime you can call this line beforehand to prevent the error.
"".ToLower(CultureInfo.InvariantCulture);
I was recently experiencing similar symptoms, using the same code from http://www.griffinscs.com/?p=12: any call to CryptUnprotectData would lead to an exception in some unrelated code. Interestingly, the failure only occurred on a Windows 10 machine; the same code worked fine on a Windows 7 machine.
I fixed the problem by changing the declarations of the szDataDescr parameters in both CryptProtectData and CryptUnprotectData from string to IntPtr, and passing IntPtr.Zero instead of string.Empty in the two calls.

'System.TypeInitializationException' occurred in RdKafka.dll

when i try to implement a consumer like the example mentionened in readme section the following
line
var config = new Config() { GroupId = "example-csharp-consumer" };
causes this exception
System.TypeInitializationException was unhandled
HResult=-2146233036
Message=Der Typeninitialisierer für "RdKafka.Internal.LibRdKafka" hat eine Ausnahme verursacht.
Source=RdKafka
TypeName=RdKafka.Internal.LibRdKafka
StackTrace:
bei RdKafka.Internal.LibRdKafka.conf_new()
bei RdKafka.Internal.SafeConfigHandle.Create()
bei RdKafka.Config..ctor()
bei kafka_consumer_example.Program.Main(String[] args) in C:\Users\stc\Development\git\kafka-consumer-example\Program.cs:Zeile 18.
bei System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
bei System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
bei Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
bei System.Threading.ThreadHelper.ThreadStart_Context(Object state)
bei System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
bei System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
bei System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
bei System.Threading.ThreadHelper.ThreadStart()
InnerException:
HResult=-2146233052
Message=Die DLL "librdkafka": Das angegebene Modul wurde nicht gefunden. (Ausnahme von HRESULT: 0x8007007E) kann nicht geladen werden.
Source=RdKafka
TypeName=""
StackTrace:
bei RdKafka.Internal.LibRdKafka.NativeMethods.rd_kafka_version()
bei RdKafka.Internal.LibRdKafka.version()
bei RdKafka.Internal.LibRdKafka..cctor()
InnerException:
the stacktrace looks like
in RdKafka.Internal.LibRdKafka.NativeMethods.rd_kafka_version()
in RdKafka.Internal.LibRdKafka.version()
in RdKafka.Internal.LibRdKafka..cctor()
i integrated the library via Nuget from https://www.nuget.org/packages/RdKafka/0.9.1-ci-131
can anyone tell me which assemblie i'm missing ?
You need install Visual C++ Redistributable Packages for Visual Studio 2013
https://www.microsoft.com/en-US/download/details.aspx?id=40784

PerlEmbed - C# doesn't work with Interpreter.Language = #"PerlScript"

Regarding to the method in:
PerlEmbed - C# - Mono - Linux
I got the following error when I tried to run the code above, at line
Interpreter.Language = #"**PerlScript**"
I can run a VBScript but unfortunately I couldn't run a PerlScript. Should I do/setup/add etc. something else?
System.Runtime.InteropServices.COMException was unhandled
HelpLink="MSSCRIPT.HLP"
Message="***A script engine for the specified language can not be created.***"
Source="ScriptControl"
ErrorCode=-2146827908
StackTrace:
at MSScriptControl.ScriptControlClass.set_Language(String pbstrLanguage)
at fpu_Parsing.Perl_Interpreter.Perl_Output_returnString() in D:\Documents and Settings\labuser\My Documents\Visual Studio 2005\Projects\fpu_Parsing\fpu_Parsing\Perl_Interpreter.cs:line 77
at fpu_Parsing.frmFpuAnalyzer..ctor() in D:\Documents and Settings\labuser\My Documents\Visual Studio 2005\Projects\fpu_Parsing\fpu_Parsing\frmFpuAnalyzer.cs:line 24
at fpu_Parsing.Program.Main() in D:\Documents and Settings\labuser\My Documents\Visual Studio 2005\Projects\fpu_Parsing\fpu_Parsing\Program.cs:line 17
at System.AppDomain.nExecuteAssembly(Assembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()

Amazon S3 - The remote server returned an error: (407) Proxy Authentication

I am having the following code to upload a file in s3.
AmazonS3 s3Client = AWSClientFactory.CreateAmazonS3Client("AWSAccessKey", "AWSSecretKey");
String strS3KEY = "JSON_FILE_NAME";
PutObjectRequest request = new PutObjectRequest();
request.WithBucketName("AWS_BUCKET");
request.WithKey(strS3KEY);
request.WithContentBody("Test");
request.CannedACL = S3CannedACL.PublicRead;
s3Client.PutObject(request);
This works find in the local system. When I run the application from deployment server in the line s3Client.PutObject(request); it gives the following error-
The remote server returned an error: (407) Proxy Authentication Required.
The stack trace is -
at System.Net.HttpWebRequest.GetRequestStream(TransportContext& context)
at System.Net.HttpWebRequest.GetRequestStream()
at Amazon.S3.AmazonS3Client.getRequestStreamCallback[T](IAsyncResult result)
at Amazon.S3.AmazonS3Client.endOperation[T](IAsyncResult result)
at Amazon.S3.AmazonS3Client.EndPutObject(IAsyncResult asyncResult)
at Amazon.S3.AmazonS3Client.PutObject(PutObjectRequest request)
at XMLandCloudConsole.Program.Main(String[] args) in C:\Users\spxc\Desktop\consoletest \XMLandCloudConsole\XMLandCloudConsole\Program.cs:line 29
at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()

(SEH)Exception initializing Nlog

I get the error at the end when I try to start a project I'm working on from Visual Studio. It worked fine until a few hours ago. After some minor unrelated changes it stopped working when starting from Visual Studio. It works fine when run from explorer. Even old version vom revision control (where this part of the code is exactly the same and has worked without any problems) behave the same way so it doesn't seem to be a problem in my code.
The code at Program.cs:line 14 is the following:
private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
Any ideas on how to solve this?
System.TypeInitializationException was unhandled
Message=The type initializer for ...' threw an exception.
Source=...
TypeName=...
StackTrace:
at ....Main(String[] args)
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException: System.Runtime.InteropServices.SEHException
Message=External component has thrown an exception.
Source=mscorlib
ErrorCode=-2147467259
StackTrace:
at System.Security.Policy.PEFileEvidenceFactory.GetLocationEvidence(SafePEFileHandle peFile, SecurityZone& zone, StringHandleOnStack retUrl)
at System.Security.Policy.PEFileEvidenceFactory.GenerateLocationEvidence()
at System.Security.Policy.PEFileEvidenceFactory.GenerateEvidence(Type evidenceType)
at System.Security.Policy.AssemblyEvidenceFactory.GenerateEvidence(Type evidenceType)
at System.Security.Policy.Evidence.GenerateHostEvidence(Type type, Boolean hostCanGenerate)
at System.Security.Policy.Evidence.GetHostEvidenceNoLock(Type type)
at System.Security.Policy.Evidence.GetHostEvidence(Type type, Boolean markDelayEvaluatedEvidenceUsed)
at System.Security.Policy.AppDomainEvidenceFactory.GenerateEvidence(Type evidenceType)
at System.Security.Policy.Evidence.GenerateHostEvidence(Type type, Boolean hostCanGenerate)
at System.Security.Policy.Evidence.GetHostEvidenceNoLock(Type type)
at System.Security.Policy.Evidence.RawEvidenceEnumerator.MoveNext()
at System.Security.Policy.Evidence.EvidenceEnumerator.MoveNext()
at System.Configuration.ClientConfigPaths.GetEvidenceInfo(AppDomain appDomain, String exePath, String& typeName)
at System.Configuration.ClientConfigPaths.GetTypeAndHashSuffix(AppDomain appDomain, String exePath)
at System.Configuration.ClientConfigPaths..ctor(String exePath, Boolean includeUserConfig)
at System.Configuration.ClientConfigPaths.GetPaths(String exePath, Boolean includeUserConfig)
at System.Configuration.ClientConfigurationHost.RequireCompleteInit(IInternalConfigRecord record)
at System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject)
at System.Configuration.BaseConfigurationRecord.GetSection(String configKey)
at System.Configuration.ClientConfigurationSystem.System.Configuration.Internal.IInternalConfigSystem.GetSection(String sectionName)
at System.Configuration.ConfigurationManager.GetSection(String sectionName)
at NLog.Config.XmlLoggingConfiguration.get_AppConfig()
at NLog.LogFactory.get_Configuration()
at NLog.LogFactory.GetLogger(LoggerCacheKey cacheKey)
at NLog.LogFactory.GetLogger(String name)
at NLog.LogManager.GetCurrentClassLogger()
at ....Program..cctor() in C:\...\Program.cs:line 14
InnerException:
Check the following post on the Avira support site for details of the problem and a work around. The issue is related to the last product update:
http://www.avira.com/en/support-for-business-knowledgebase-detail/kbid/805

Categories

Resources