MVC LInk from Web Config AppSettings - asp.net-mvc-2

I created a new mvc 2 project to learn mvc. I'm trying to do something like the following:
Webconfig
<appSettings>
<!-- WEB SITES -->
<add key="LiveWebAddress" value="www.mydomain.org"/>
<add key="DevWebAddress" value="localhost/mydomain"/>
<add key="TestWebAddress" value="test-2/mydomain"/>
</appSettings>
in the controller I am trying to do this:
public ActionResult link()
{
//return View();
return RedirectToAction(
System.Configuration.ConfigurationManager
.AppSettings["LiveWebAddress"]
.ToString()
);
}
Am I headed in the right direction? I'm getting a null reference exception.

You should probably use WebConfigurationManager instead. In addition, I'm not sure doing this in the controller is the best option.

Related

Microsoft.Practices.EnterpriseLibrary.Data.DLL but was not handled in user code

Searched google and using Enterprise library data access to connect database.
Installed only data access pack using https://www.nuget.org/packages/EnterpriseLibrary.Data/.
After added to the project, I've set the configuration as follows,
<configSections>
<section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" />
</configSections>
<dataConfiguration defaultDatabase="dProvider" />
<connectionStrings>
<add name="dProvider" connectionString="server=local;Initial Catalog=n;uid=sa;pwd=pwd"
providerName="System.Data.SqlClient" />
</connectionStrings>
Called through the application like the following,
Database db;
string sqlCommand;
DbCommand dbCommand;
db = DatabaseFactory.CreateDatabase("dProvider"); or DatabaseFactory.CreateDatabase();
After run the application, I got the following exception,
{"Database provider factory not set for the static DatabaseFactory. Set a provider factory invoking the DatabaseFactory.SetProviderFactory method or by specifying custom mappings by calling the DatabaseFactory.SetDatabases method."}
What mistake I made ? How to solve this issue ?
Finally found the answer. It has been occurred because of the configuration section.
I've used version 6, but here I've mentioned like version 5 in the configuration section. So the error has occurred.
I've replaced the configuration section like following, It worked perfectly in good way. :-). Thanks a lot for the helpers.
<configSections>
<section name="dataConfiguration"
type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings,
Microsoft.Practices.EnterpriseLibrary.Data"/>
</configSections>
and used DataBaseProviderFactory class to create instance.
DatabaseProviderFactory factory = new DatabaseProviderFactory();
db = factory.Create("dProvider");

Share EF connection string from subproject in the main project

I have two projects
MyProject //MVC 3 app
MyProject.DAL //Class Library project type
Inside MyProject.DAL there is a folder EntityModels which contains generated entity (EF Code-First approach):
namespace MyProject.DAL.EntityModels
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class myEntities : DbContext
{
public myEntities() : base("name=myEntities")
{
...
}
}
}
app.config:
<add name="myEntities" connectionString="metadata=res://*/EntityModels.DBMainModel.csdl|res://*/EntityModels.DBMainModel.ssdl|res://*/EntityModels.DBMainModel.msl;provider=..." providerName="System.Data.EntityClient" />
then, I want to use that entity in my MyProject project, so I add the same connection string in the web.config file.
But, I get the Unable to load the specified metadata resource. error. I tried make some modifications in the web.config like
<add name="myEntities"
connectionString="metadata=res://*/MyProject.DAL.EntityModels.DBMainModel.csdl|
res://*/MyProject.DAL.EntityModels.DBMainModel.ssdl|
res://*/MyProject.DAL.EntityModels.DBMainModel.msl;provider=..." providerName="System.Data.EntityClient" />
<add name="myEntities"
connectionString="metadata=res://MyProject.DAL.EntityModels.DBMainModel.csdl|
res://MyProject.DAL.EntityModels.DBMainModel.ssdl|
res://MyProject.DAL.EntityModels.DBMainModel.msl;provider=..." providerName="System.Data.EntityClient" />
<add name="myEntities"
connectionString="metadata=res://MyProject.DAL/EntityModels.DBMainModel.csdl|
res://MyProject.DAL/EntityModels.DBMainModel.ssdl|
res://MyProject.DAL/EntityModels.DBMainModel.msl;provider=..." providerName="System.Data.EntityClient" />
but nothing works. How to fix it ?
If it's code-first, you should put pure connectionString value in your appropriate .config file (You're dealing with SqlClient not EntityClient).
To find out more about ConnectionString values, take a look at http://www.connectionstrings.com/sql-server/.
For SQL Server databases, basically it is like below:
<add name="MyEntities" connectionString="Data Source=myServerName\myInstanceName;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;" providerName="System.Data.SqlClient"/>

How to separate between debug and release for connections etc in mvc4

So I am fairly new MVC4 and many patterns are new to me.
However the one thing I am curious about is best practice about release/debug modes.
There are a bunch of things for me that differ between live and debug mode and I would like for all of them to be automatic so I don't need to change anything to publish.
So for instance I have done like this in my repo (domain project)
public class EFAccountRepository : IAccountRepository
{
private EFDbContext _context;
public EFAccountRepository()
{
#if DEBUG
_context = new EFDbContext("name=Debug");
#else
_context = new EFDbContext("name=Live");
#endif
}
and like this in my DI (webui)
#if DEBUG
EFDbContext efcontext = new EFDbContext("name=Debug");
#else
EFDbContext efcontext = new EFDbContext("name=Live");
#endif
Or would it be smarter to simply have
EFDbContext efcontext = new EFDbContext("name=MyApp");
And then change with web.config transform what MyApp means?
Any other tips of automating debug/release-publish is warmly welcomed.
I would strongly recommend not hardcoding your connection strings into your code. Please consider pointing your code to a web.config transform. You can add the connection string there and depending on the version of code the proper transform can be applied so that you simply need to use the following code once in your app to cover all environments.
ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString
Inside of the debug version you could have something similar to
<configuration xmlns:xdt="...">
<connectionStrings>
<add name="MyConnectionString" connectionString="debugstring"
providerName="debugprovider" />
</connectionStrings>
</configuration>
Inside your release version you can tell the transform to replace your old string as so
<configuration xmlns:xdt="...">
<connectionStrings>
<add name="MyConnectionString" connectionString="newstring"
providerName="newprovider"
xdt:Transform="Replace" />
</connectionStrings>
</configuration>
for more reference check out
http://msdn.microsoft.com/en-us/library/dd465326.aspx
The selected answer will not work if you have more than one connection string. in the release config add below tags for all your connectionstrings
xdt:Transform="SetAttributes" xdt:Locator="Match(name)"
This is what I have in my Web configuration files
in Web.Debug.Config
<add name="MyConnectionString"
connectionString="Data Source=dev;Initial Catalog=DevDB;Integrated Security=True;
providerName="System.Data.SqlClient"/>
and in Web.Release.Config
<add name="MyConnectionString"
connectionString="Data Source=LIVESERVER;Initial Catalog=DB98;Integrated Security=True;
providerName="System.Data.SqlClient"
xdt:Transform="SetAttributes"
xdt:Locator="Match(name)"/>
Use web.config transformations http://msdn.microsoft.com/en-us/library/dd465326.aspx

Simulating timeout on ASP.NET MVC

Problem:
I need to create a web project with a controller that times out.
What I have done:
Create a new web application
Empty the web.config, and write the values below:
.
<?xml version="1.0"?>
<configuration>
<system.web>
<httpRuntime executionTimeout="1" />
<compilation debug="false" />
<httpModules>
<add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</httpModules>
</system.web>
</configuration>
Write the following code to the controller:
.
public class DefaultController : Controller
{
public EmptyResult Index()
{
System.Threading.Thread.Sleep(3000);
Response.Write("ScriptTimeout: " + HttpContext.Server.ScriptTimeout);
return new EmptyResult();
}
}
When run, the server sleeps for 3 seconds, then returns the response without any timeout error. ScriptTimeout value is 1.
Question:
Any idea what went wrong?
Do you want a 408 Request Timeout HTTP status code?
public ActionResult Index()
{
return new HttpStatusCodeResult(408);
}
http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
The executionTimeout attribute on the <httpRuntime/> element is only taken into account if debug="false" on the <compilation/> element.
Try removing the debug attribute or explicitly setting it to false. Of course, you'll have to run your application without debugging to test it.
See http://msdn.microsoft.com/en-gb/library/vstudio/e1f13641(v=vs.100).aspx for more details.

iis7.5 mvc2 404 and 500.24 error

This is my first time deploying an MVC2 app (.NET4) on IIS7.5. I'm using StructureMap and Fluent NHibernate, and everything runs fine locally using integrated security. The application does render the first page (controllername/pagename), but throws an error on the next one which is (controllername/pagename/id).
I have ran %windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -ir.
HttpRedirection and HttpExceptions are enabled.
This is the 404 error from View Source:
[HttpException]: The controller for path '/conrollername/pagename/1' was not found or does not implement IController.
at System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType)
at CustomerResponses.Infrastructure.StructureMapControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) in C:\Apps\Development Source\CustomerResponsesApplication\trunk\CustomerResponses\Infrastructure\StructureMapControllerFactory.cs:line 19
at System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName)
at System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory)
at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Another link gives me 500.24 error:
HTTP Error 500.24 - Internal Server Error
An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode.
Does anyone have any ideas?
Thanks
Part on Web.Config
system.webServer - section
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true"/>
<handlers>
<add name="UrlRoutingHandler"
preCondition="integratedMode"
verb="*" path="UrlRouting.axd"
type="System.Web.HttpForbiddenHandler,
System.Web, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a" />
</handlers>
<!--<handlers>
<remove name="MvcHttpHandler" />
<add name="MvcHttpHandler" preCondition="integratedMode" verb="*" path="*.mvc" type="System.Web.Mvc.MvcHttpHandler" />
<add name="UrlRoutingHandler" preCondition="integratedMode" verb="*" path="UrlRouting.axd" type="System.Web.HttpForbiddenHandler, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</handlers>-->
Global.asax
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");
routes.IgnoreRoute("{resource}.gif/{*pathInfo}");
routes.IgnoreRoute("{*datepick}",
new { datepick = #"(.*/)?jquery.datepick.css(/.*)?" });
// ignore datepick.css file
routes.IgnoreRoute("{*favicon}",
new { favicon = #"(.*/)?favicon.ico(/.*)?" });
routes.IgnoreRoute("{*chevron}",
new { chevron = #"(.*/)?Images/Chevron.gif(/.*)?" });
routes.IgnoreRoute("{*iconhome}",
new { iconhome = #"(.*/)?Images/IconHome.gif(/.*)?" });
routes.MapRoute("test", "testroute",
new { controller = "compresponses", action = "list" });
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new {
controller = "compresponses",
action = "list",
id = UrlParameter.Optional
} // Parameter defaults
);
One of the problems is:
your web.config file contains too much information.
IIS 7.5 when runs in intergated mode does not require any additional settings.
I would recomend to create blank mvc application and publish it onto webserver.
also i have seen
the error :
[HttpException]: The controller for path '/conrollername/pagename/1' was not found or does not implement IController. at System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) at
where it says that the dll either system.web or system.web.mvc is not referenced from project.
My solution( might be not the best) but is: Right button on project where the error occured and copy the dlls local and this should help with the error.
as for error:
Another link gives me 500.24 error: HTTP Error 500.24 - Internal Server Error An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode.
the best is to have iis console installed and open the project using iis console.
Change your application pool properties to:
.NET Framework Version
-- .NET Framework *version*
Pipeline Mode
-- Classic