Location > Blog

Web Development Blog

Using MySql as ASP.NET Session Store Provider

MySQL Connector/Net from version 6.1 has included a custom Session State Provider. This provider enables you to store session state in a MySQL database and is useful if you are running your site in a web farm and you don't want to use the build in MSSQL.


There is a article in the MySql documentation on how to get started, I did find that of course it wouldn't work correctly in Medium Trust. So I downloaded the source for the 6.6.5 version and started debugging. I had read there were some bugs in the earlier versions causing the session to lock.

First thing that needs to change is how the web.configuration file is accessed, in Medium Trust you will get a security error. This is due the

// Get <sessionState> configuration element.
Configuration webConfig = WebConfigurationManager.OpenWebConfiguration(HostingEnvironment.ApplicationVirtualPath);
sessionStateConfig = (SessionStateSection)webConfig.SectionGroups["system.web"].Sections["sessionState"];

To the following as the OpenWebConfiguration method  throws an exception, System.Security.Permissions.FileIOPermission, mscorlib, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089

// Get <sessionState> configuration element.
sessionStateConfig = (SessionStateSection)WebConfigurationManager.GetSection("system.web/sessionState");

I compiled my own version, if you have a Full Trust environment you could probably go with the original version.

You also need to configure the web.config file to uses the new provider.

        <remove name="LocalMySqlServer"/>
        <add name="LocalMySqlServer" connectionString="Server=;Database=aspnet_state;password=mypassword;User ID=myuser"/>
<sessionState cookieless="false" regenerateExpiredSessionId="true" mode="Custom" customProvider="MySqlSessionStateStore">
                <add name="MySqlSessionStateStore" type="MySql.Web.SessionState.MySqlSessionStateStore, MySql.Web" connectionStringName="LocalMySqlServer" writeExceptionsToEventLog="false" autogenerateschema="True" />

jQuery isChildOf - is an element a child of another element

Here i s a really quick note on creating a basic extension to jQuery to check if an element is a child of another element.

jQuery Function

(function($) {  
        isChildOf: function (filter) {  
            return $(filter).find(this).length > 0;  

Example HTML

Consider the simple HTML below.

<div id="parent"


Some basic usage of the function.


NHibernate with logging throws a Security Exception under Medium Trust

I am using NHibernate 3.2.0 under Medium Trust and all was going well until I turned on logging to try and trace a SQL error. It seems that when you set the log4net logging level to INFO that under a medium trust NHibernate throws a Security Exception.

Here is the Security Exception.

[SecurityException: Request for the permission of type 'System.Security.Permissions.FileIOPermission, mscorlib, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.]     System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet) +0     System.Security.CodeAccessSecurityEngine.Check(CodeAccessPermission cap, StackCrawlMark& stackMark) +31     System.Security.CodeAccessPermission.Demand() +46     System.Reflection.RuntimeAssembly.VerifyCodeBaseDiscovery(String codeBase) +118     System.Reflection.RuntimeAssembly.GetName(Boolean copiedName) +69     System.Reflection.Assembly.GetName() +12     NHibernate.Cfg.Environment.get_Version() +114     NHibernate.Cfg.Environment..cctor() +130  


You can see from the stack trace exactly where the error was occurring, its quite clear. In the NHibernate source the static constructor for the Environment you can see that the NHibernate Version is logged, I was picking that is where the the error was occurring.


        static Environment() 
            // Computing the version string is a bit expensive, so do it only if logging is enabled. 
            if (log.IsInfoEnabled) 
                log.Info("NHibernate " + Version); 
            GlobalProperties = new Dictionary<string, string>(); 
            GlobalProperties[PropertyUseReflectionOptimizer] = bool.TrueString; 
            BytecodeProviderInstance = BuildBytecodeProvider(GlobalProperties); 
            EnableReflectionOptimizer = PropertiesHelper.GetBoolean(PropertyUseReflectionOptimizer, GlobalProperties); 
            if (EnableReflectionOptimizer) 
                log.Info("Using reflection optimizer"); 


So what is wrong with accessing the Version property?


        public static string Version 
                if (cachedVersion == null) 
                    Assembly thisAssembly = Assembly.GetExecutingAssembly(); 
                    var attrs = 
                        thisAssembly.GetCustomAttributes(typeof (AssemblyInformationalVersionAttribute), false); 
                    if (attrs != null && attrs.Length > 0) 
                        cachedVersion = string.Format("{0} ({1})", thisAssembly.GetName().Version, attrs[0].InformationalVersion); 
                        cachedVersion = thisAssembly.GetName().Version.ToString(); 
                return cachedVersion; 


So it seemed the Security Exception was being thrown on the call to Assembly.ExecutingAssembly()

After quite a bit of searching Google it turned out Phil Haack had also come across the problem and had written a really good account of what the problem is and the solution.

Rather than compile my custom version of NHibernate version I decided just to debug my NHibernate HQL under under Full Trust and change it back to Medium Trust when I had sorted out my problems.