asp.net mvc 3: web.config is not being read? - asp.net-mvc-3

I created a link to my web.config which is defnined as a central config file defined at solution level. So the project I am having troubles contains a reference to this config file:
web.config:
<configuration>
<connectionStrings>
<add name="NorthwindEntities" connectionString="metadata=res://*/NWind.csdl|res://*/NWind.ssdl|res://*/NWind.msl;provider=System.Data.SqlClient;provider connection string="data source=.\SQLEXPRESS;initial catalog=Northwind;integrated security=True;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration
Also I created a .edmx file and the connectionstring is like:
<configuration>
<connectionStrings>
<add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient" />
<add name="NorthwindEntities" connectionString="metadata=res://*/NWind.csdl|res://*/NWind.ssdl|res://*/NWind.msl;provider=System.Data.SqlClient;provider connection string="data source=.\SQLEXPRESS;initial catalog=Northwind;integrated security=True;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>
The issue is that my .edmx file wont read the connectionstring:
I am getting an error:
Object reference not set to an instance of an object?
string constrng = ConfigurationManager.ConnectionStrings["NorthwindEntities"].ToString();

Related

Dev Database connection persisting on production environment

as the title suggests i'm having a little problem with a persisting database connection. Here, we have 2 databases, one for dev and testing and the oficial, production one. We used to change manually the different connection strings when testing and deploying and sometimes a strange error happened. When we stopped the dev database suddenly the entire production application stopped to work, saying that the SQL connection was lost. But the web.config was pointing to production not testing environment!
After some research, we found the web.config transformation and thought that would solve our problem. It didn't. The problem still persists as if our application is tight to the dev environment even when our web.config doesn't make a single reference to it.
To make things clearer, i'll post the connection strings, the transformation and the latest SQL error that happened (when we limited the dev database to single-user for some updates), plus the way we connect it to our DBML (L2SQL).
CONNECTION STRINGs
<add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient"/>
<!--ConnectionString Central-->
<add name="OperationsBD" connectionString="Data Source=DEVSERVER\DEV;Initial Catalog=OPERATION;Persist Security Info=True;User ID=lab;Password=devPassword" providerName="System.Data.SqlClient"/>
<add name="AnalisysBD" connectionString="Data Source=DEVSERVER\DEV;Initial Catalog=ANALISYS;Persist Security Info=True;User ID=lab;Password=devPassword" providerName="System.Data.SqlClient"/>
<!--Production ConnectionString-->
<!--<add name="OperationsDB" connectionString="Data Source=PRODSERVER\COMPANY;Initial Catalog=OPERATION;Persist Security Info=True;User ID=company;Password=prodPassword" providerName="System.Data.SqlClient"/>
<add name="AnalisysDB" connectionString="Data Source=PRODSERVER\COMPANY;Initial Catalog=ANALISYS;Persist Security Info=True;User ID=company;Password=prodPassword" providerName="System.Data.SqlClient"/>-->
WEB.CONFIG TRANSFORMATION (PRODUCTION)
<connectionStrings>
<add name="OperationsDB"
connectionString="Data Source=PRODSERVER\COMPANY;Initial Catalog=OPERATION;Persist Security Info=True;User ID=company;Password=prodPassword"
providerName="System.Data.SqlClient"
xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
<add name="AnalisysDB"
connectionString="Data Source=PRODSERVER\COMPANY;Initial Catalog=ANALISYS;Persist Security Info=True;User ID=company;Password=prodPassword"
providerName="System.Data.SqlClient"
xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
</connectionStrings>
WEB.CONFIG TRANSFORMATION (DEV)
<connectionStrings>
<add name="OperationsDB"
connectionString="Data Source=DEVSERVER\DEV;Initial Catalog=OPERATION;Persist Security Info=True;User ID=lab;Password=devPassword"
providerName="System.Data.SqlClient"
xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
<add name="AnalisysDB"
connectionString="Data Source=DEVSERVER\DEV;Initial Catalog=ANALISYS;Persist Security Info=True;User ID=lab;Password=devPassword"
providerName="System.Data.SqlClient"
xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
</connectionStrings>
SQL ERROR (single-user limitation on dev environment)
Cannot open database "operation" requested by the login. The login failed. Login failed for user 'lab'.
And lastly, the way we connect it to the LINQ to SQL DBML
public partial class OperationDataContext
{
private const string OPERATION_CONN_STRING = "OperationsDB";
public OperationDataContext()
: base(System.Configuration.ConfigurationManager.ConnectionStrings[OPERATION_CONN_STRING].ConnectionString, mappingSource)
{
OnCreated();
}
}
public partial class AnalisysDataContext
{
private const string ANALISYS_CONN_STRING = "AnalisysDB";
public AnalisysDataContext()
: base(System.Configuration.ConfigurationManager.ConnectionStrings[ANALISYS_CONN_STRING].ConnectionString, mappingSource)
{
OnCreated();
}
}
This may be just a typo, but I did notice that the "Name" on Dev was "OperationsBD" and "AnaylsisBD", but the Transforms are set to match on name of "OperationsDB" and "AnaylsisDB". If this isn't a typo, it would never match, thus never replacing the connection strings.

MVC3 web app / tutorial won't "log in" using ASPNETDB.mdf on IIS7 webserver

I have just uploaded my MVC3 ASP.net web application to my server 2008 R2 IIS 7.5 Express webserver.
The web app loads fine, but when clicking on the logon link and either trying to register a user account or log a existing user account on I get the following error:
"Sorry, an error occurred while processing your request."
If I browse the web app on my webserver (from within IIS7.5) and try the logon link I get the following ASP error:
"A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)"
"Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code."
"Exception Details: System.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)"
"Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below."
Would someone mind helping me trouble shoot please?
I have two databases configured in my Web.Config:
<connectionStrings>
<add name="DatabaseDBContext" connectionString="data source=|DataDirectory|Content_Database.sdf" providerName="System.Data.SqlServerCe.4.0"/>
<add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient"/>
</connectionStrings>
The SQL Compact (Content_Database.sdf) database works fine. I only get the error when trying to access the aspnetdb.mdf database.
The ASPNETDB.mdf database is practically in identical state to what you get given when loading the Microsoft MVC3 Razor template / tutorial from Visual Web Developer Express 2010.
I tried installing SQL Express 2008 on my webserver just in case this was the issue, made no difference.
The whole web application works perfectly on my Visual Web Developer 2010 Express development server (I can create users and log them on and off successfully). It just fails as soon as it is uploaded to the webserver.
Help appreciated - many thanks :-)
Full Web.Config:
<?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>
<connectionStrings>
<add name="DatabaseDBContext" connectionString="data source=|DataDirectory|\Content_Database.sdf" />
<add name="ApplicationServices" connectionString="data source=|DataDirectory|\aspnetdb.sdf" />
<!--<add name="ApplicationServices"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient" />-->
</connectionStrings>
<appSettings>
<add key="webpages:Version" value="1.0.0.0"/>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
<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.Helpers, Version=1.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=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</assemblies>
</compilation>
<authentication mode="Forms">
<forms loginUrl="~/Admin/LogOn" timeout="2880" />
</authentication>
<membership>
<providers>
<clear/>
<add name="SqlCeMembershipProvider" type="Project1.Domain.SqlCeMembershipProvider" connectionStringName="ApplicationServices" applicationName="/"
enablePasswordRetrieval="false" requiresQuestionAndAnswer="false" requiresUniqueEmail="true" passwordFormat="Hashed" writeExceptionsToEventLog="false" />
<!--<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 defaultProvider="SqlCeRoleProvider"
enabled="true"
cacheRolesInCookie="true"
cookieName=".ASPROLES"
cookieTimeout="30"
cookiePath="/"
cookieRequireSSL="false"
cookieSlidingExpiration="true"
cookieProtection="All">
<providers>
<clear/>
<add name="SqlCeRoleProvider" type="System.Web.Security.SqlCeRoleProvider" connectionStringName="ApplicationServices" applicationName="/" writeExceptionsToEventLog="true" />
<!--<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.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages"/>
</namespaces>
</pages>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true"/>
</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-2.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration
>
It looks like your DatabaseDBContext/SDF if a Sql Compact database. This engine is extremely different from an administrators point of view. Basically, it is very simple to setup and get working.
Your ApplicationServices/mdf file is not a Compact database, it uses the normal sql (express, dev, workgroup, standard, enterprise etc) engine. This does require a bit of tweaking to get working. Your data source= option is configuring the SqlClient to use a specific engine installed on the local machine to open the database (this would require sql to be installed on the local machine as an instanced install with the name SqlExpress) and properly configured to allow connections (possibly remote). The Integrated Security is configuring the SqlClient to connect to the server as the user configued in the AppPool to connect to the database, which requires that user to have access to the file where the database is stored, the database itself (inside as security), and all the other security requirements of SSPI (which I would highly recommend you keep).
Update
I have a few projects running exclusively on Compact Framework (because for small projects, it's so much easier to maintain/administer).
To use SQL Server Compact 4, you need to install the Visual Studio Tools for SQL Server Compact 4. I use erikej SQL Compact Providers (Membership and Role) for asp.net and haven't run into any issues. The nice part about the providers is that most of the code you've written against the current providers won't change, you're just replacing the provider and database.
Either way, happy coding!
Update 2
My web.config has the following entries:
<connectionStrings>
<add name="membershipDatabase"
connectionString="data source=|DataDirectory|\Membership.sdf" />
</connectionStrings>
<membership defaultProvider="SqlCeMembershipProvider">
<providers>
<clear />
<add name="SqlCeMembershipProvider"
type="Project1.Domain.SqlCeMembershipProvider"
connectionStringName="membershipDatabase"
applicationName="/"
enablePasswordRetrieval="false"
requiresQuestionAndAnswer="false"
requiresUniqueEmail="true"
passwordFormat="Hashed"
writeExceptionsToEventLog="false" />
</providers>
</membership>
<roleManager defaultProvider="SqlCeRoleProvider"
enabled="true"
cacheRolesInCookie="true"
cookieName=".ASPROLES"
cookieTimeout="30"
cookiePath="/"
cookieRequireSSL="false"
cookieSlidingExpiration="true"
cookieProtection="All">
<providers>
<clear />
<add name="SqlCeRoleProvider"
type="Project1.Domain.SqlCeRoleProvider"
connectionStringName="membershipDatabase"
applicationName="/"
writeExceptionsToEventLog="true" />
</providers>
</roleManager>

Why am I getting a "No attribute 'name' exists for the Match Locator" error when publishing?

I am so confused on this. I want to use the SQL Server on my desktop when I am developing and using the live SQL Server when I publish my project. I am playing with the transformation stuff in Visual Studio 2010.
I get the "No attribute 'name' exists for the Match Locator" when I try to publish my project.
My Web.config file contains:
<connectionStrings>
<add name="EFDbContext" connectionString="Data Source=.\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=db" providerName="System.Data.SqlClient"/>
</connectionStrings>
<system.web>
<sessionState mode="SQLServer" sqlConnectionString="Server=.\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=ASPState;Application Name=eGov" timeout="20" allowCustomSqlDatabase="true" />
</system.web>
I am still testing it, so for now, my Web.Release.config file contains:
<connectionStrings>
<add name="EFDbContext"
connectionString="Data Source=.\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=db"
providerName="System.Data.SqlClient"
xdt:Transform="SetAttributes" xdt:Locator="Match(name)" />
</connectionStrings>
<system.web>
<compilation xdt:Transform="RemoveAttributes(debug)" />
<sessionState mode="SQLServer"
sqlConnectionString="Server=.\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=ASPState;Application Name=app"
timeout="20" allowCustomSqlDatabase="true"
xdt:Transform="SetAttributes" xdt:Locator="Match(name)" />
</system.web>
Anything I am seeing online is only confusing me more. Any help to get me up and running?
xdt:Locator="Match(name) mean that system will match nodes to replace using name tag. If you don't have name attribute then it fails. You must have some unique attribute to use this type of transformation.
Doh! The problem was in the sessionState section. It should be:
<system.web>
<sessionState mode="SQLServer"
sqlConnectionString="Server=.\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=ASPState;Application Name=app"
timeout="20" allowCustomSqlDatabase="true"
xdt:Transform="SetAttributes" xdt:Locator="XPath(configuration/system.web/sessionState)" />
</system.web>
Using "name" in Match(name) is for a typical config setting like the following. The key in this case is "name".
<add name="errorAddress" email="me#google.com" xdt:Transform="SetAttributes" xdt:Locator="Match(name)" />
If the key in your setting is something else, that is what you need to use:
<add token="UserToken" value="23jkl2klk2j3kja9d8f" xdt:Transform="SetAttributes" xdt:Locator="Match(token)"/>

Config Transform does not work?

I have this config in my Web.config file:
<connectionStrings>
<add name="LocalConnString" connectionString="metadata=res://*/;provider=System.Data.SqlClient;provider connection string="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\NCU.Joberwocky.Db.mdf;Integrated Security=True;User Instance=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
</connectionStrings>
This in my Web.Release.config:
<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<connectionStrings>
<add name="LocalConnString" connectionString="metadata=res://*/;provider=System.Data.SqlClient;provider connection string="Data Source=192.168.10.3;Initial Catalog=AeorionJobs;User Id=aeorionjobs;Password=aejobs3695;MultipleActiveResultSets=True""
xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
</connectionStrings>
</configuration>
When I switch the build to release, it still uses the config from Web.config. Any idea what the problem is?
I am also struggling with configuration transforms. Actually I am trying to have a different configuration on my environment than the common one uploaded in code control.
I have been also trying the same thing as you are doing and I would say those transforms are only applied on the deployment packages that you can build.
Hope it helps.

VS2010 Build Deployment Package web.release.config transform error

I am getting the transformed web.config in the deployment package incorrectly transformed.
The result is as follows (notice how the connection string gets generated):
<connectionStrings>
<add name="xxxConnectionStringNamexxx"
connectionString="$(ReplacableToken_xxxConnectionStringNamexxx-Web.config Connection String_0)" providerName="System.Data.SqlClient" />
</connectionStrings>
Web.Config:
<connectionStrings>
<add name="xxxConnectionStringNamexxx"
connectionString="Data Source=.\sqlexpress2005;Initial Catalog=xxxx;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
Web.Release.config:
<connectionStrings>
<add name="xxxConnectionStringNamexxx" connectionString="Data Source=.\sqlexpress2005;Initial Catalog=xxxx;Integrated Security=True" providerName="System.Data.SqlClient" xdt:Transform="SetAttributes(connectionString)" xdt:Locator="Match(name)"/>
</connectionStrings>
Any ideas?
Thanks
So benoit found an answer on the asp.net forums : ReplacableToken_ when using web.config transform? .
I deployed to a folder on my desktop and the web.config file was transformed correctly.

Resources