What is the best way to inject configuration settings into Javascript in an MVC app? - asp.net-mvc-3

What is the best way to inject configuration settings into Javascript in an MVC app?
I've seen how it is done using ASP.NET webforms, but not sure how to do this with MVC.
#using System.Configuration
...
var checkTimer = #ConfigurationManager.AppSettings["CheckTimer"];
In Web.config:
<appSettings>
<!-- Polling timer to check for alerts -->
<add key="CheckTimer" value="10000"/>
</appSettings>
But in my rendered output I just get the following:
var checkTimer = ;

var checkTimer = #Html.Raw(Json.Encode(ConfigurationManager.AppSettings["CheckTimer"]));

Check out the Javascript serializer:
http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx

If it is not too fancy , you can have a hidden variable and then access it in javascript.

Related

Enabling CORS through Web.config vs WebApiConfig and Controller attributes

There seems to be two functionally different ways to enable cross-origin request sharing in Web API 2.
One is to import System.Web.Http.Cors, decorate a controller with the EnableCors attribute and to write config.EnableCors() in the WebApiConfig:
[EnableCors(origins: "http://111.111.111.111", headers: "*", methods: "*")]
public class GenericController : ApiController
{
// etc.
The other is to modify the Web.config:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="http://111.111.111.111" />
<add name="Access-Control-Allow-Methods" value="*" />
<add name="Access-Control-Allow-Headers" value="*" />
Is there a functional difference between these two different approaches? Which one is correct - don't these accomplish the same thing? If both methods are used to enable CORS, will things blow up?
If you add the headers to the web.config, every request that is served by that application will include the specified headers. This method is supported at the web server level and doesn't depend on config.EnableCors() being executed. You can use that method to add any HTTP header you want.
On the flip side, the EnableCors attribute requires WebAPI and you need to add some code to make it work. To the end user, the result is the same.
As for which way is better? I've liked keeping those settings in the application code by using the attribute so these settings are obvious to future developers. Depending on your needs, you may want to look into a abstract CorsApiController which your main ApiControllers could inherit to deliver the same CORS headers over and over. But this method won't work if the CORS headers need to vary from controller to controller or from action to action.

Trying to enable client side validation in Orchard

I am trying to get client side validation enabled in Orchard for the comments. I have followed the advice in this SO discussion. I have commented out:
//ModelValidatorProviders.Providers.Clear();
//ModelValidatorProviders.Providers.Add(new LocalizedModelValidatorProvider());
I have included the following in Resource Manifest in the Comments Module.
manifest.DefineScript("jQueryValidation").SetUrl("jquery.validate.js", "jquery.validate.min.js").SetVersion("1.7").SetDependencies("jQuery");
manifest.DefineScript("jQueryValidation_Unobtrusive").SetUrl("jquery.validate.unobtrusive.js", "jquery.validate.unobtrusive.min.js").SetDependencies("jQuery", "jQueryValidation");
I stuck the following inthe view:
this.Script.Require("jQueryValidation_Unobtrusive").AtHead();
Also I added DataAnnotation to the CommentPartRecord.cs file, decorating Author with [Required]
And the changes to the Web.config:
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
And despite all of this server side valdiation for the Comments is whjat works. There is no client side validation.
The DataAnnotation should'nt be on CommentPartRecord but on CommentPart.
But Orchard.Comments is not a good example because CommentPart doesn't define the same properties than the Record (it will be refactored in a future version).
Try this on another module o one that you create.

Is it possible to get standard ASP.NET MVC Unobtrusive Validation to work in Orchard CMS?

I'm trying to build a custom module to integrate with Orchard CMS to implement a business application. While Orchard CMS is an MVC application, it doesn't seem possible (or, at least easy) to do all the things that can be done "out of the box" with MVC.
I'm trying to get unobtrusive validation to work on my view but can't seem to get this to work.
Update: As per Rohan West's advice below, I've now got the scripts included in the page using the ResourceManifest class and the Script.Require calls.
However, the validation attributes on the actual HTML elements are not being generated despite having the .NET attributes on my properties for which I'm using #Html.EditorFor on.
I have set the appSettings in the web.config file as follows:
<appSettings>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
<add key="webpages:Enabled" value="false" />
<add key="log4net.Config" value="Config\log4net.config" />
</appSettings>
Still no joy!
Update 2: As per Rohan West's suggestion, modifying the OrchardStarter class to comment out the following lines "solves" the problem:
ModelValidatorProviders.Providers.Clear();
ModelValidatorProviders.Providers.Add(new LocalizedModelValidatorProvider());
There should be a better way of handling this though.
You need to define the script in the resource manifest for your module.
public class ResourceManifest : IResourceManifestProvider
{
public void BuildManifests(ResourceManifestBuilder builder)
{
var manifest = builder.Add();
manifest.DefineScript("jQueryValidation").SetUrl("jquery.validate.js", "jquery.validate.min.js").SetVersion("1.7").SetDependencies("jQuery");
manifest.DefineScript("jQueryValidation_Unobtrusive").SetUrl("jquery.validate.unobtrusive.js", "jquery.validate.unobtrusive.min.js").SetDependencies("jQuery", "jQueryValidation");
}
}
and then in your page
#{
this.Script.Require("jQueryValidation_Unobtrusive").AtHead();
}
Have a look at the following class
Orchard.Environment.OrchardStarter
In Orchard 1.4.2 there is a line which removes all ModelValidatorProviders
ModelValidatorProviders.Providers.Clear();
This is removing the default DataAnnotationsModelValidatorProvider from the collection.
You could try adding it to the collection,

How to create the MVC equivalent of WIF PassiveSignInStatus Control?

I have included the below in my MVC View page
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Base.Master" Inherits="System.Web.Mvc.ViewPage" %>
<%# Register TagPrefix = "idfx" Assembly = "Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Namespace = "Microsoft.IdentityModel.Web.Controls" %>
<asp:Content ID="Content2" ContentPlaceHolderID="Content" runat="server">
<idfx:FederatedPassiveSignInStatus
ID="FederatedPassiveSignInStatus1"
runat="server"
OnSignedOut="FederatedPassiveSignInStatus1SignedOut"
SignOutText="Logout"
FederatedPassiveSignOut="true"
SignOutAction="FederatedPassiveSignOut" />
</asp:Content>
Since this is MVC, I cannot have runat=”server” attribute. When I remove the runat attribute, the page loads ok, but the control is not get displayed. How can I achieve this in MVC?
The Identity Training Kit or the samples in http://claimsid.codeplex.com/releases/view/62929 should show you ways of hooking WIF with MVC.
The problem is you cannot use event driven server-side controls in ASP.NET MVC like you can in ASP.NET webforms. If you are using webforms, than using the FederatedPassiveSignInStatus control to do sign-out is absolutely the easiest method.
In MVC we are going to have to issue the wa=wsignout1.0 command to the STS provider manually. If you look at the
Take a look at the 'FederationWithMultiplePartnersAndAcs' project in the Microsoft patterns & practices Cliams Identity Guide projects located on CodePlex here. If you look at the Logout() method on the HomeController, you will see the following code which does what we need:
public ActionResult Logout()
{
if (this.User.Identity.IsAuthenticated)
{
FederatedAuthentication.WSFederationAuthenticationModule.SignOut(false);
string issuer = FederatedAuthentication.WSFederationAuthenticationModule.Issuer;
var signOut = new SignOutRequestMessage(new Uri(issuer));
return this.Redirect(signOut.WriteQueryString());
}
return this.RedirectToAction("Index");
}
This is how you would need to implement the sign-out logic in MVC.

Set connectionstring for Membership Service via code

I have an ASP.NET web project and a membership provider configured via my web.config. Its fully working so no problem there.
We have an older system with a lot of users and I would therefor like to create a class library that can create users in this ASP.NET project but since its a class library it cannot have its own app.config-file.
is it possible to set all this information via code somehow?
<membership defaultProvider="ShidMembershipProvider">
<providers>
<clear/>
<add name="ShidMembershipProvider" type="SundaHus.AspNet.Membership.ShidMembershipProvider" connectionStringName="ShidConnectionString" enablePasswordRetrieval="true" enablePasswordReset="true" requiersQuestionAndAnswer="true" applicationName="ECB3-development" minRequiredPasswordLength="5"/>
</providers>
</membership>
You have a custom membership provider it looks like? This connects to your own custom database? You should be able to just point to that database for your code. Or, if you just inherit the functionality from the base class, you can also try overriding the Initialize method, look for the connection string, and change the value to something else.

Resources