How to create the MVC equivalent of WIF PassiveSignInStatus Control? - model-view-controller

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.

Related

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,

MVC view can't see model in separate project

I have an MVC view in one project (my web project). I'm trying to specify that it should inherit from a class (the model) in another project, but that class isn't visible to my view. The model class's project is in the References of the project in which the view resides. Why can't my view see the model class? Here's the view in its entirety:
<%# Page Title="Title"
Language="C#"
Inherits="System.Web.Mvc.ViewPage<Models.PropertyDetailsModel>"
MasterPageFile="../MvcMasterPage.Master" %>
Models.PropertyDetailsModel is highlighed in red and when I hover over it, it says that it can't resolve the symbol PropertyDetailsModel.
Ideas?
In your ~/web.config make sure that in the <assemblies> section you have the assembly containing this model:
<assemblies>
...
<add assembly="TheAssemblyContainingYourModel" />
</assemblies>
Then run the project to see if it works. Don't pay attention to the red squiggles. Visual Studio Intellisense in views is not to be trusted.
P.S: in ~/web.config there's also a <namespaces> section where you could put the namespace that contains your model which will DRY your views:
<pages>
<namespaces>
<add namespace="TheNamespaceContainingYourModel" />
</namespaces>
</pages>
and then in all your views in the entire application you can directly reference the models without the need to fully qualify them:
<%# Page Title="Title"
Language="C#"
Inherits="ViewPage<PropertyDetailsModel>"
MasterPageFile="../MvcMasterPage.Master" %>
Actually, all I had to do was change this:
Inherits="System.Web.Mvc.ViewPage<Models.PropertyDetailsModel>"
to this:
Inherits="System.Web.Mvc.ViewPage`1[Models.PropertyDetailsModel]"
Wacky!

What is the best way to inject configuration settings into Javascript in an MVC app?

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.

From web forms to Razor

I've got an .net 2.0 web forms site that has just been upgraded to .net 4. Now I'd like to use the Razor syntax and some mvc helpers. Could anyone give a step by step procedure to start using it?
(Yes, I know mixing different view engines is not straight forward, but I'm not asking for that. Just to be able to create a new _layout, and a new ContentPage.cshtml and start using some of the mvc helpers and get that to work in parallell with the old pages - I'll duplicate the masterpage functionality, so that new pages will be written using razor, and old pages bugfixed in webform with the old masterpage)
I just need to know the following:
What assemblies do I need to include
What changes to web.config do I need
Any other changes?
Thanks for any help
Larsi
Scott hanselman has a great post about this:
Integrating ASP.NET MVC 3 into existing upgraded ASP.NET 4 Web Forms applications
You need to include System.Web.Mvc version 3.0.
In your web.config, you need to make sure that the UrlRoutingModule is registered as an HttpModule. Your IHttpHandler is created by the IRouteHandler implementation, which is an MvcRouteHandler in ASP.NET Mvc.
You also will need to register your routes in your Global.asax to setup routing. The default Route registration (for an MVC2 project) looks like this:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
}
I'm not sure if they have made any changes to that in Mvc 3 or not, but you can find out by creating a new Mvc Web Application project in Visual Studio and opening up the Global.asax
You may take a look at the upgrading an ASP.NET MVC 2 Project to ASP.NET MVC 3 guide. If you have a classic WebForms application (not MVC) then there is no migration => there is a rewrite.
This converter tool will get you a head start:
http://visualstudiogallery.msdn.microsoft.com/d2bfd1ca-9808-417c-b963-eb1ea4896790
Telerik wrote a command-line converter from aspx/ascx to cshtml for asp.net mvc. You can find that at: https://github.com/telerik/razor-converter
There is also a nice plugin for Visual Studio that uses the Telerik code at: http://visualstudiogallery.msdn.microsoft.com/d2bfd1ca-9808-417c-b963-eb1ea4896790

How to develop JSP/Servlets Web App using MVC pattern?

I'm developing a JSP/Servlet web app (no frameworks). I want to use MVC pattern. I am going to design my project like this:
Controller: a servlet that reads a request, extracts the values,communicates with model objects and gives information to a JSP page.
View: JSP Pages.
Model: Java Classes / Java Beans .. etc.
The problem: Index.jsp is the starting point (default page) in my web site. So, the Index.jsp becomes the controller to parse the request. For example, the following request:
index.jsp?section=article&id=10
is parsed in index.jsp as following :
<div class="midcol">
<!-- Which section? -->
<%String fileName = request.getParameter("section");
if (fileName == null) {
fileName = "WEB-INF/jspf/frontpage.jsp";
} else {
fileName = "WEB-INF/jspf/" + fileName + ".jsp";
}
%>
<jsp:include page='<%= fileName%>' />
</div>
Here, I can't force the servlet to be a controller, because the index.jsp is the controller here since it's the starting point.
Is there any solution to forward the request from index.jsp to the servlet and then go back to index.jsp? Or any solution that achieves the MVC goal - the servlet should be the controller?
I'm thinking of making a FrontPageController servlet as default page instead of index.jsp, but I don't know if it's a perfect idea?
Get rid of index.jsp and just let the controller servlet listen on a specific url-pattern of interest. The controller itself should forward the request to the JSP page of interest using RequestDispatcher.
request.getRequestDispatcher("/WEB-INF/page.jsp").forward(request, response);
Alternatively you can let index.jsp forward or redirect to an URL which is covered by the controller servlet which in turn shows the "default" page (which seems to be frontpage.jsp).
That said, in a correct MVC approach, you should have no scriptlets in JSP files. Whenever you need to write some raw Java code inside a JSP file which can't be replaced reasonably by taglibs (JSTL and so on) or EL, then the particular Java code belongs in any way in a real Java class, like a Servlet, Filter, Javabean, etcetera.
With regard to the homegrown MVC approach, you may find this answer and this article useful as well.

Resources