Retrieve <caching> element from web.config - configuration

I've been trying to get the caching element from my web.config but have thus far failed.
When using this code:
Configuration conf = WebConfigurationManager.OpenWebConfiguration(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath);
I am able to get at the web.configh file.
When i use
conf.GetSection("system.web/membership");
I succefuly get the membership section.
When i use
conf.GetSection("system.web/caching");
I get null.
Any ideas ?
part of the web.config below:
<system.web>
<caching>
<sqlCacheDependency enabled="true" pollTime="1000">
<databases>
<clear />
<add name="Tests" pollTime="1000" connectionStringName="TestsConnectionString"/>
</databases>
</sqlCacheDependency>
</caching>
<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx" timeout="2880"/>
</authentication>
<membership>
<providers>
<clear/>
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/"/>
</providers>
</membership>
....

Have you casted the return type correctly as OutputCacheSection?
const string outputCacheKey = "system.web/caching/outputCache";
var outputCacheSection = ConfigurationManager.GetSection(outputCacheKey) as OutputCacheSection;
Now say you wanted to get an attribute named connectionString within the first provider node e.g.
<caching>
<outputCache enableOutputCache="true" defaultProvider="MyRedisOutputCache">
<providers>
<add name="MyRedisOutputCache" connectionString="myapp.redis.cache.windows.net:6380,password=hellopassword,ssl=True,abortConnect=False" type="Microsoft.Web.Redis.RedisOutputCacheProvider,Microsoft.Web.RedisOutputCacheProvider" />
</providers>
</outputCache>
</caching>
you could do something like this
string defaultProviderName = outputCacheSection.DefaultProviderName;
ProviderSettings ps = outputCacheSection.Providers[defaultProviderName];
var cs = ps.Parameters["connectionString"];

Related

RoleProvider .NET 2 - converted from MS Access to MySQL

I have an old site running on .NET 2 using an AccessMembershipProvide and I'm changing it to MySqlMemebrshipProvider - The membership side works fine, but the roles part seems to not provide the roles methods?
If I switch back to the OdbcRoleProvide in the Web.Config it works while still using the MySqlMembershipProvider.
I'm calling the roles with: Response.Write(Roles.IsUserInRole(User.Identity.Name, "Admin") & " -role exist- " & Roles.RoleExists("Admin"))
this returns false even with logged in user.?
NOTE: I'm running it on a hosted site and don't have access to Visual Studio (I know this makes debugging incredibly difficult)!!!
Web.Config:
<connectionStrings>
<clear />
<add name="OdbcServices" connectionString="Driver={Microsoft Access Driver (*.mdb)};Dbq=e:\App_Data\subsite.mdb;" />
<add name="ConnString" connectionString="Database=Training;Data Source=localhost;User Id=myuser;Password=mypassword" />
</connectionStrings>
<system.web>
<compilation debug="true" strict="false" explicit="true">
<codeSubDirectories>
<add directoryName="VBCode" />
<add directoryName="CSCode" />
</codeSubDirectories>
</compilation>
<!--
<membership defaultProvider="AccessMembershipProvider"
userIsOnlineTimeWindow="20">
<providers>
<clear />
<add name="AccessMembershipProvider"
type="AccessMembershipProvider"
enablePasswordReset="true"
enablePasswordRetrieval="true"
requiresQuestionAndAnswer="true"
connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=e:\App_Data\subsite.mdb;Persist Security Info=False"
/>
</providers>
</membership>
<roleManager defaultProvider="OdbcRoleProvider"
enabled="true"
cacheRolesInCookie="true"
cookieName=".ASPROLES"
cookieTimeout="30"
cookiePath="/"
cookieRequireSSL="false"
cookieSlidingExpiration="true"
cookieProtection="All" >
<providers>
<clear />
<add name="OdbcRoleProvider"
type="Samples.AspNet.Roles.OdbcRoleProvider"
connectionStringName="OdbcServices"
applicationName="SampleApplication"
writeExceptionsToEventLog="false" />
</providers>
</roleManager>
-->
<!-- http://www.codeproject.com/Articles/12301/Membership-and-Role-providers-for-MySQL -->
<roleManager defaultProvider="MySqlRoleProvider"
enabled="true"
cacheRolesInCookie="true"
cookieName=".ASPROLES"
cookieTimeout="30"
cookiePath="/"
cookieRequireSSL="false"
cookieSlidingExpiration="true"
cookieProtection="All" >
<providers>
<clear />
<add
name="MySqlRoleProvider"
type="Andri.Web.MySqlRoleProvider"
connectionStringName="ConnString"
applicationName="SampleApplication"
writeExceptionsToEventLog="false"
/>
</providers>
</roleManager>
<membership defaultProvider="MySqlMembershipProvider"
userIsOnlineTimeWindow="15">
<providers>
<clear />
<add
name="MySqlMembershipProvider"
type="Andri.Web.MySqlMembershipProvider"
connectionStringName="ConnString"
applicationName="ApplicationName"
enablePasswordRetrieval="true"
enablePasswordReset="true"
requiresQuestionAndAnswer="true"
requiresUniqueEmail="false"
passwordFormat="Clear"
writeExceptionsToEventLog="false"
/>
</providers>
</membership>
<authentication mode="Forms">
<forms loginUrl="~/Login.aspx" />
</authentication>
...
Not sure why reverting back to RolesProvider.vb did not cause the same response, however there was an erroneous SQL statement in the MembershipProvider.cs. This resolved the problem and the RolesProvider is responding as desired.

Using a Class Library for ASP.NET Membership Provider with MySQL

I am attempting to use the ASP.NET Membership Provider with a MySQL database with mixed success. My solution currently contains an ASP.NET MVC project that has been configured to use MySQL and another project that handles all calls to the database in which I also want to handle membership functions such as creating and validating users.
Both projects have MS .NET EnityFramework v6.1.3, Microsoft.AspNet.Identity.EntityFramework v2.2.1 and MySql.Data.Entity v6.9.7 installed.
I configured the ASP.NET project as per the instructions at http://k16c.eu/2014/10/12/asp-net-identity-2-0-mariadb/. My "web.config" is configured as follows;
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<remove name="LocalMySqlServer" />
<add name="LocalMySqlServer"
connectionString="Server=localhost; Database=rb-web; Uid=root; Pwd=password; Convert Zero Datetime=True; Allow User Variables=True;"
providerName="MySql.Data.MySqlClient" />
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
<provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6, Version=6.9.7.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
</providers>
</entityFramework>
<system.data>
<DbProviderFactories>
<remove invariant="MySql.Data.MySqlClient" />
<add name="MySQL Data Provider"
invariant="MySql.Data.MySqlClient"
description=".Net Framework Data Provider for MySQL"
type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.9.7.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
</DbProviderFactories>
</system.data>
</configuration>
The instructions at http://k16c.eu/2014/10/12/asp-net-identity-2-0-mariadb/ required creating two new classes, ApplicationUser.cs and ApplicationContext.cs however these were basically replicating the code in IdentityModels.cs which was already included in my project. The identity model code is;
using System.Data.Entity;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using MySql.Data.Entity;
namespace RB.Client.Models
{
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
return userIdentity;
}
}
[DbConfigurationType(typeof(MySqlEFConfiguration))]
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext() : base("LocalMySqlServer", throwIfV1Schema: false) { }
public ApplicationDbContext(string connStringName) : base(connStringName, throwIfV1Schema: false) { }
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
// Primary keys can easily get too long for MySQL's (InnoDB's) stupid 767 bytes limit.
// The following lines rewrite the generation to keep those columns "short" enough.
modelBuilder.Entity<IdentityRole>()
.Property(c => c.Name)
.HasMaxLength(128)
.IsRequired();
// Declare the table name here, otherwise IdentityUser will be created.
modelBuilder.Entity<ApplicationUser>()
.ToTable("AspNetUsers")
.Property(c => c.UserName)
.HasMaxLength(128)
.IsRequired();
}
}
}
Once these changes were made I ran the Enable-Migrations from Package Manager Console and modified the Configuration.cs class as follows;
namespace RB.Client.Migrations
{
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
internal sealed class Configuration : DbMigrationsConfiguration<RB.Client.Models.ApplicationDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
SetSqlGenerator("MySql.Data.MySqlClient", new MySql.Data.Entity.MySqlMigrationSqlGenerator());
}
protected override void Seed(RB.Client.Models.ApplicationDbContext context)
{
}
}
}
I then ran the Add-Migration "Initial" and Update-Database command from the Package Manager Console which created the aspnetroles, aspnetuserclaims, aspnetuiserlogins, aspnetuserroles and aspnetusers tables in MySQL.
I then use the following code in my persistence project;
public UserDto RegisterUser(UserDto user)
{
var appUser = Membership.CreateUser(user.Email, user.Password);
}
Which raises the exception;
"Unable to initialize provider. Missing or incorrect schema."
"MySql.Web at MySql.Web.Common.SchemaManager.CheckSchema(String connectionString, NameValueCollection config)
at MySql.Web.Security.MySQLMembershipProvider.Initialize(String name, NameValueCollection config)
at System.Web.Configuration.ProvidersHelper.InstantiateProvider(ProviderSettings providerSettings, Type providerType)"
However, if I add the following entries to the "web.config";
<system.web>
<roleManager defaultProvider="MySQLRoleProvider">
<providers>
<remove name="MySQLRoleProvider" />
<add name="MySQLRoleProvider"
type="MySql.Web.Security.MySQLRoleProvider, MySql.Web, Version=6.9.7.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"
applicationName="/RBWeb"
description="RB Role Provider"
connectionStringName="LocalMySqlServer"
writeExceptionsToEventLog="True"
autogenerateschema="True"
enableExpireCallback="False" />
</providers>
</roleManager>
<membership defaultProvider="MySQLMembershipProvider">
<providers>
<remove name="MySQLMembershipProvider" />
<add name="MySQLMembershipProvider"
type="MySql.Web.Security.MySQLMembershipProvider, MySql.Web, Version=6.9.7.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"
applicationName="/RbWeb"
description="RB Membership Provider"
connectionStringName="LocalMySqlServer"
writeExceptionsToEventLog="True"
autogenerateschema="True"
enableExpireCallback="False"
enablePasswordRetrieval="False"
enablePasswordReset="True"
requiresQuestionAndAnswer="False"
requiresUniqueEmail="True"
passwordFormat="Hashed"
maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="6"
minRequiredNonalphanumericCharacters="1"
passwordAttemptWindow="10"
passwordStrengthRegularExpression="" />
</providers>
</membership>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
The user is successfully created and a System.Web.Security.MembershipUser object is returned. However the call has now generated a number of new tables in the database, my_aspnet_users, my_aspnet_roles, etc along with all of the tables for profiles, personalisation, and session management even though these options weren't included in the web.config settings and the user record was created in these tables. There seems to be a disconnect between my web and persistence projects.
I have reviewed all of the articles I could find in MySQL however these all appear to be out of date and were of no help. At this point I am now writing a custom membership provider to try and get around these problems but to be honest I'm also considering ditching MySQL due to the problems I have faced trying to get this to work.

InnerException : Table 'xxx.aspnetusers' doesn't exist

I have an ASP.NET MVC 4 Web API project which uses Entity Framework 6.1.1 and MySQL 6.9.5.0. When I call /api/Account/Register using DHC, the code breaks at
IdentityResult result = await UserManager.CreateAsync(user, model.Password);
in the AccountController and I get an InnerException which says
Table 'xxx.aspnetusers' doesn't exist
Here are pieces of my web.config
<connectionStrings>
<add name="ClockitDb" connectionString="Data Source=ClockitDb;port=3306;Initial Catalog=ClockitDb;Server=localhost;user id=root;password=m916600026;"
providerName="MySql.Data.MySqlClient" />
</connectionStrings>
<!-- Some code-->
<entityFramework codeConfigurationType="MySql.Data.Entity.MySqlEFConfiguration, MySql.Data.Entity.EF6">
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework"/>
<providers>
<provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6" />
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
<!-- Some code-->
<system.web>
<authentication mode="Forms" />
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<membership defaultProvider="MySQLMembershipProvider">
<providers>
<remove name="MySQLMembershipProvider" />
<add name="MySQLMembershipProvider" type="MySql.Web.Security.MySQLMembershipProvider, MySql.Web, Version=6.9.5.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" connectionStringName="LocalMySqlServer" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="true" applicationName="/" requiresUniqueEmail="false" passwordFormat="Clear" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="7" minRequiredNonalphanumericCharacters="1" passwordAttemptWindow="10" passwordStrengthRegularExpression="" />
</providers>
</membership>
<profile defaultProvider="MySQLProfileProvider">
<providers>
<remove name="MySQLProfileProvider" />
<add name="MySQLProfileProvider" type="MySql.Web.Profile.MySQLProfileProvider, MySql.Web, Version=6.9.5.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" connectionStringName="LocalMySqlServer" applicationName="/" />
</providers>
</profile>
<roleManager defaultProvider="MySQLRoleProvider">
<providers>
<remove name="MySQLRoleProvider" />
<add name="MySQLRoleProvider" type="MySql.Web.Security.MySQLRoleProvider, MySql.Web, Version=6.9.5.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" connectionStringName="LocalMySqlServer" applicationName="/" />
</providers>
</roleManager>
<siteMap defaultProvider="MySqlSiteMapProvider">
<providers>
<remove name="MySqlSiteMapProvider" />
<add name="MySqlSiteMapProvider" type="MySql.Web.SiteMap.MySqlSiteMapProvider, MySql.Web, Version=6.9.5.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" connectionStringName="LocalMySqlServer" applicationName="/" />
</providers>
</siteMap>
<webParts>
<personalization defaultProvider="MySQLPersonalizationProvider">
<providers>
<remove name="MySQLPersonalizationProvider" />
<add name="MySQLPersonalizationProvider" type="MySql.Web.Personalization.MySqlPersonalizationProvider, MySql.Web, Version=6.9.5.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" connectionStringName="LocalMySqlServer" applicationName="/" />
</providers>
</personalization>
</webParts>
<entityFramework codeConfigurationType="MySql.Data.Entity.MySqlEFConfiguration, MySql.Data.Entity.EF6">
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6" />
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
I had exactly the same problem .
I followed the following tutorial and it worked
How to set up application using ASP.NET Identity with MySQL Provider
It is important that you follow all the steps of the tutorial,even the migration setup, otherwise it gives the same error.
The exception clearly states that aspnetusers is missing from your database. However, on more findings, I think you would like to go through this answer from asp.net forum.
http://forums.asp.net/t/1977214.aspx?Mvc+5+Identity+Error+Invalid+object+name+dbo+AspNetUsers
For Role,Membership Provider, asp.net [entire asp.net stack/webapi included] with mysql, you need to have that providers specific to mysql in place. For this, you can refer to
http://www.codeproject.com/Articles/117157/Setting-up-MySql-Membership-with-Visual-Studio
Let me know, if this solves your problem.
I tried following the instructions on
http://www.codeproject.com/Articles/117157/Setting-up-MySql-Membership-with-Visual-Studio.
When I launch the security tab in ASP Website administration tool, I get an error saying
The pre-application start initialization method Start on type WebMatrix.WebData.PreApplicationStartCode threw an exception with the following error message: Could not load file or assembly 'MySql.Data, Version=6.9.5.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040) (C:\Users\Jaseem Abbas\Documents\Visual Studio 2013\Projects\MySQLSample1\MySQLSample1\web.config line 33).
My line 33 in web config starts as
<membership defaultProvider="MySQLMembershipProvider">
<providers>
<add name="MySQLMembershipProvider"
type="MySql.Web.Security.MySQLMembershipProvider,
MySql.Web, Version=6.9.5.0,
Culture=neutral,
PublicKeyToken=c5687fc88969c44d"
connectionStringName="LocalMySqlServer"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="false"
requiresUniqueEmail="true"
passwordFormat="Hashed"
maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="6"
minRequiredNonalphanumericCharacters="0"
passwordAttemptWindow="10"
applicationName="/"
autogenerateschema="true" />
</providers>
</membership>
<profile>ASP
<providers>
<clear />
<add type="MySql.Web.Security.MySQLProfileProvider,
MySql.Web, Version=6.9.5.0,
Culture=neutral,
PublicKeyToken=c5687fc88969c44d"
name="MySqlProfileProvider"
applicationName="/"
connectionStringName="LocalMySqlServer"
autogenerateschema="true" />
</providers>
</profile>
<roleManager enabled="true" defaultProvider="MySqlRoleProvider">
<providers>
<clear />
<add connectionStringName="LocalMySqlServer"
applicationName="/"
name="MySqlRoleProvider"
type="MySql.Web.Security.MySQLRoleProvider,
MySql.Web, Version=6.9.5.0,
Culture=neutral,
PublicKeyToken=c5687fc88969c44d"
autogenerateschema="true" />
</providers>

Failed to map the path '/' MySQL

I'm trying to connect to a MySQL using web.config and I used MySQL Website Configuration for it. Problem is it makes my site show an error when running instead of running it. :D
This is my web.config SQL connection:
<connectionStrings>
<remove name="LocalMySqlServer" />
<add name="LocalMySqlServer" connectionString="password=PASS****;user id=9b443f_users;server=MYSQL5008.myWindowsHosting.com;database=db_9b443f_users" providerName="MySql.Data.MySqlClient" />
</connectionStrings>
<system.web>
<sessionState mode="Custom" cookieless="true" regenerateExpiredSessionId="true" customProvider="MySqlSessionStateProvider">
<providers>
<add name="MySqlSessionStateProvider" type="MySql.Web.SessionState.MySqlSessionStateStore, MySql.Web, Version=6.8.3.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" applicationName="Sessions" description="Sessions" connectionStringName="LocalMySqlServer" writeExceptionsToEventLog="True" autogenerateschema="True" enableExpireCallback="False" />
</providers>
</sessionState>
<profile defaultProvider="MySQLProfileProvider">
<providers>
<remove name="MySQLProfileProvider" />
<add name="MySQLProfileProvider" type="MySql.Web.Profile.MySQLProfileProvider, MySql.Web, Version=6.8.3.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" applicationName="Profiles" description="Profiles" connectionStringName="LocalMySqlServer" writeExceptionsToEventLog="True" autogenerateschema="True" enableExpireCallback="False" />
</providers>
</profile>
<membership defaultProvider="MySQLMembershipProvider">
<providers>
<remove name="MySQLMembershipProvider" />
<add name="MySQLMembershipProvider" type="MySql.Web.Security.MySQLMembershipProvider, MySql.Web, Version=6.8.3.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" applicationName="MemRecords" description="MySQL default application" connectionStringName="LocalMySqlServer" writeExceptionsToEventLog="True" autogenerateschema="True" enableExpireCallback="False" enablePasswordRetrieval="False" enablePasswordReset="True" requiresQuestionAndAnswer="True" requiresUniqueEmail="True" passwordFormat="Hashed" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="7" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" passwordStrengthRegularExpression="" />
</providers>
</membership>
<roleManager enabled="true" defaultProvider="MySQLRoleProvider">
<providers>
<remove name="MySQLRoleProvider" />
<add name="MySQLRoleProvider" type="MySql.Web.Security.MySQLRoleProvider, MySql.Web, Version=6.8.3.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" applicationName="Roles" description="Roles" connectionStringName="LocalMySqlServer" writeExceptionsToEventLog="False" autogenerateschema="True" enableExpireCallback="False" />
</providers>
</roleManager>
<compilation debug="true" targetFramework="4.0" />
<identity impersonate="false" />
<authentication mode="Forms">
<forms loginUrl="default.aspx" />
</authentication>
</system.web>
And this is the stack trace it shows me:
[InvalidOperationException: Failed to map the path '/'.]
System.Web.Configuration.ProcessHostConfigUtils.MapPathActual(String
siteName, VirtualPath path) +224
System.Web.Configuration.ProcessHostMapPath.MapPathCaching(String
siteID, VirtualPath path) +865
System.Web.Configuration.ProcessHostMapPath.GetPathConfigFilenameWorker(String
siteID, VirtualPath path, String& directory, String& baseName) +13
System.Web.Configuration.ProcessHostMapPath.System.Web.Configuration.IConfigMapPath.GetPathConfigFilename(String
siteID, String path, String& directory, String& baseName) +37
System.Web.Configuration.HostingPreferredMapPath.GetPathConfigFilename(String
siteID, String path, String& directory, String& baseName) +75
System.Web.Configuration.WebConfigurationHost.GetStreamName(String
configPath) +9844796
System.Configuration.Internal.DelegatingConfigHost.GetStreamName(String
configPath) +11
System.Configuration.BaseConfigurationRecord.InitConfigFromFile() +134
[ConfigurationErrorsException: An error occurred loading a
configuration file: Failed to map the path '/'.]
System.Configuration.ConfigurationSchemaErrors.ThrowIfErrors(Boolean
ignoreLocal) +658656
System.Configuration.BaseConfigurationRecord.ThrowIfParseErrors(ConfigurationSchemaErrors
schemaErrors) +34 System.Configuration.Configuration..ctor(String
locationSubPath, Type typeConfigHost, Object[]
hostInitConfigurationParams) +328
System.Configuration.Internal.InternalConfigConfigurationFactory.System.Configuration.Internal.IInternalConfigConfigurationFactory.Create(Type
typeConfigHost, Object[] hostInitConfigurationParams) +29
System.Web.Configuration.WebConfigurationHost.OpenConfiguration(WebLevel
webLevel, ConfigurationFileMap fileMap, VirtualPath path, String site,
String locationSubPath, String server, String userName, String
password, IntPtr tokenHandle) +387
System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(String
path) +76
MySql.Web.SessionState.MySqlSessionStateStore.Initialize(String name,
NameValueCollection config) +437
System.Web.Configuration.ProvidersHelper.InstantiateProvider(ProviderSettings
providerSettings, Type providerType) +597
System.Web.SessionState.SessionStateModule.SecureInstantiateProvider(ProviderSettings
settings) +43
System.Web.SessionState.SessionStateModule.InitCustomStore(SessionStateSection
config) +87
System.Web.SessionState.SessionStateModule.InitModuleFromConfig(HttpApplication
app, SessionStateSection config) +9777245
System.Web.SessionState.SessionStateModule.Init(HttpApplication app)
+159 System.Web.HttpApplication.InitModulesCommon() +80 System.Web.HttpApplication.InitModules() +64
System.Web.HttpApplication.InitInternal(HttpContext context,
HttpApplicationState state, MethodInfo[] handlers) +792
System.Web.HttpApplicationFactory.GetNormalApplicationInstance(HttpContext
context) +336
System.Web.HttpApplicationFactory.GetApplicationInstance(HttpContext
context) +107
System.Web.HttpRuntime.ProcessRequestInternal(HttpWorkerRequest wr)
+525
I just found out that if I comment out these lines, the error won't appear and the site would work correctly:
<sessionState mode="Custom" cookieless="true" regenerateExpiredSessionId="true" customProvider="MySqlSessionStateProvider">
<providers>
<add name="MySqlSessionStateProvider" type="MySql.Web.SessionState.MySqlSessionStateStore, MySql.Web, Version=6.8.3.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" applicationName="Sessions" description="Sessions" connectionStringName="LocalMySqlServer" writeExceptionsToEventLog="True" autogenerateschema="True" enableExpireCallback="False" />
</providers>
</sessionState>
How do I fix it so I won't have to comment it out?
EDIT:
Used "MySQL Website Configuration" and fixed the error.

Windsor IHandlerSelector in RIA Services Visual Studio 2010 Beta2

I want to implement multi tenancy using Windsor and i don't know how to handle this situation:
i succesfully used this technique in plain ASP.NET MVC projects and thought incorporating in a RIA Services project would be similar.
So i used IHandlerSelector, registered some components and wrote an ASP.NET MVC view to verify it works in a plain ASP.NET MVC environment. And it did!
Next step was to create a DomainService which got an IRepository injected in the constructor. This service is hosted in the ASP.NET MVC application. And it actually ... works:i can get data out of it to a Silverlight application.
Sample snippet:
public OrganizationDomainService(IRepository<Culture> cultureRepository)
{
this.cultureRepository = cultureRepository;
}
Last step is to see if it works multi-tenant-like: it does not! The weird thing is this:
using some line of code and writing debug messages in a log file i verified that the correct handler is selected! BUT this handler seems not to be injected in the DomainService. I ALWAYS get the first handler (that's the logic in my SelectHandler)
Can anybody verify this behavior? Is injection not working in RIA Services? Or am i missing something basic??
Development environment: Visual Studio 2010 Beta2
Thanks in advance
So it seems i did a very weird thing in my OrganizationDomainServiceFactory.
The code which did NOT work is this:
public DomainService CreateDomainService(Type domainServiceType, DomainServiceContext context )
{
WindsorContainer container = new WindsorContainer(new XmlInterpreter(new ConfigResource("castle")));
IRepository<Culture> cultureRepository = container.Resolve<IRepository<Culture>>();
IRepository<Currency> currencyRepository = container.Resolve<IRepository<Currency>>();
DomainService ds = (DomainService)Activator.CreateInstance(domainServiceType, new object[] { cultureRepository,currencyRepository });
ds.Initialize(context);
return ds;
}
This is apparently not working, because of the creation of a new Container (which should not take place).
OK! So i thought i try to use ServiceLocator to get a reference to the Windsor Container (used in the WindsorControllerFactory - that's how i call it ... in the boot up of the ASP.NET MVC application), and changed the code to this:
public DomainService CreateDomainService(Type domainServiceType, DomainServiceContext context )
{
IRepository<Culture> cultureRepository = ServiceLocator.Current.GetInstance<IRepository<Culture>>();
IRepository<Currency> currencyRepository = ServiceLocator.Current.GetInstance<IRepository<Currency>>();
DomainService ds = (DomainService)Activator.CreateInstance(domainServiceType, new object[] { cultureRepository,currencyRepository });
ds.Initialize(context);
return ds;
}
and guess what: it works(!!!) multi-tenancy as it should be!
The only thing i don't know is: is there another way to "inject" the container (constructor injection seems not to work here , the compiler complains)
BTW: moved the project from VS2010Beta2 to VS2010RC (with RIA Services support), but this should not affect the outcome!
Yes i have seen this thread and i already have implemented this.
Firstly have in mind that i have used this line in Global.asax.cs to get the RIA services properly behave (hosted in an ASP.NET MVC view)
routes.IgnoreRoute("{*allsvc}", new { allsvc = #".*\.svc(/.*)?" });
Here is some code:
public class HostBasedComponentSelector : IHandlerSelector
{
private readonly Type[] selectableTypes;
public HostBasedComponentSelector(params Type[] selectableTypes)
{
this.selectableTypes = selectableTypes;
}
public bool HasOpinionAbout(string key, Type service)
{
foreach (var type in selectableTypes)
{
if (service == type) return true;
}
return false;
}
public IHandler SelectHandler(string key, Type service, IHandler[] handlers)
{
//only for debug
StreamWriter sw = new StreamWriter(#"c:\temp\Debug.log",true);
sw.WriteLine(DateTime.Now + " " + service.Name + " " + GetHostname() );
sw.WriteLine("Available handlers");
foreach(IHandler h in handlers )
{
sw.WriteLine ("Handler "+h.ComponentModel.Name);
}
var id = string.Format("{0}:{1}", service.Name, GetHostname());
var selectedHandler = handlers.Where(h => h.ComponentModel.Name == id).FirstOrDefault() ??
GetDefaultHandler(service, handlers);
sw.WriteLine("Selected handler " + selectedHandler.ComponentModel.Name);
sw.WriteLine("----------- END ----------");
sw.Flush();
sw.Close();
return selectedHandler;
}
private IHandler GetDefaultHandler(Type service, IHandler[] handlers)
{
if (handlers.Length == 0)
{
throw new ApplicationException("No components registered for service {0} With service.Name" + service.Name);
}
return handlers[0];
}
protected string GetHostname()
{
return HttpContext.Current.Request.ServerVariables["SERVER_NAME"];
}
}
Here is the complete web.config. Notice registering the OrganizationDomainServiceFactory (it is the implementation of the article you mentioned)
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=152368
-->
<configuration>
<configSections>
<section name="castle" type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler,Castle.Windsor"/>
</configSections>
<connectionStrings>
<add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient"/>
</connectionStrings>
<castle>
<properties>
<sqlConnStr>
<!--metadata=res://*/WebShop.csdl|res://*/WebShop.ssdl|res://*/WebShop.msl;provider=System.Data.SqlClient;provider connection string="Data Source=.\SQLEXPRESS;Initial Catalog=iWebShop;User ID=sa;Password=xxx;MultipleActiveResultSets=True"-->
</sqlConnStr>
</properties>
<components>
<component id="CommonObjectContext" service="TestRIA1.Abstract.IObjectContext, TestRIA1" type="TestRIA1.Concrete.ObjectContextAdapter, TestRIA1" lifestyle="PerWebRequest">
</component>
<component id="IConnectionStringProvider:test.gammasys.gr" service="TestRIA1.Abstract.IConnectionStringProvider, TestRIA1" type="TestRIA1.Concrete.ConnectionStringProvider, TestRIA1" lifestyle="transient">
<parameters>
<ConnectionString>
metadata=res://*/WebShop.csdl|res://*/WebShop.ssdl|res://*/WebShop.msl;provider=System.Data.SqlClient;provider connection string="Data Source=.\SQLEXPRESS;Initial Catalog=iWebShop;User ID=sa;Password=xxx;MultipleActiveResultSets=True"
</ConnectionString>
</parameters>
</component>
<component id="IConnectionStringProvider:test.deltasys.gr" service="TestRIA1.Abstract.IConnectionStringProvider, TestRIA1" type="TestRIA1.Concrete.ConnectionStringProvider, TestRIA1" lifestyle="transient">
<parameters>
<ConnectionString>
metadata=res://*/WebShop.csdl|res://*/WebShop.ssdl|res://*/WebShop.msl;provider=System.Data.SqlClient;provider connection string="Data Source=.\SQLEXPRESS;Initial Catalog=iWebShop2;User ID=sa;Password=xxx;MultipleActiveResultSets=True"
</ConnectionString>
</parameters>
</component>
<component id="Commonrepository" service="TestRIA1.Abstract.IRepository`1, TestRIA1" type="TestRIA1.Concrete.Repository`1, TestRIA1" lifestyle="PerWebRequest"/>
<component id="urlbased.handlerselector" service="Castle.MicroKernel.IHandlerSelector, Castle.MicroKernel" type="TestRIA1.HostBasedComponentSelector, TestRIA1" lifestyle="transient">
<parameters>
<selectableTypes>
<array>
<item>TestRIA1.Abstract.IConnectionStringProvider, TestRIA1</item>
</array>
</selectableTypes>
</parameters>
</component>
</components>
</castle>
<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</assemblies>
</compilation>
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880"/>
</authentication>
<membership>
<providers>
<clear/>
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/"/>
</providers>
</membership>
<profile>
<providers>
<clear/>
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/"/>
</providers>
</profile>
<roleManager enabled="false">
<providers>
<clear/>
<add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/"/>
<add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/"/>
</providers>
</roleManager>
<pages>
<namespaces>
<add namespace="System.Web.Mvc"/>
<add namespace="System.Web.Mvc.Ajax"/>
<add namespace="System.Web.Mvc.Html"/>
<add namespace="System.Web.Routing"/>
</namespaces>
</pages>
<httpHandlers>
<add verb="*" path="*.mvc" validate="false" type="System.Web.Mvc.MvcHttpHandler"/>
</httpHandlers>
<httpModules>
<add name="PerRequestLifestyle" type="Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule,Castle.MicroKernel " />
<add name="DomainServiceModule" type="System.Web.Ria.Services.DomainServiceHttpModule, System.Web.Ria, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</httpModules>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true">
<add name="DomainServiceModule" preCondition="managedHandler"
type="System.Web.Ria.Services.DomainServiceHttpModule, System.Web.Ria, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<remove name="PerRequestLifestyle"/>
<add name="PerRequestLifestyle" preCondition="managedHandler" type="Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule,Castle.MicroKernel" />
<!--to get IoC initialization of DomainService -->
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add name="OrganizationDomainServiceFactory" type="TestRIA1.OrganizationDomainServiceFactory"/>
<!-- End of IoC initial..... -->
</modules>
<handlers>
<remove name="MvcHttpHandler" />
<add name="MvcHttpHandler" preCondition="integratedMode" verb="*"
path="*.mvc" type="System.Web.Mvc.MvcHttpHandler" />
</handlers>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0" newVersion="2.0.0.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
</system.serviceModel>
</configuration>
Hope this is enough. In case you would like to have the complete project i can send you a copy (this is a pre-production test project).
Thank you very much for the time you spend!