Lint for ASP.NET MVC? - asp.net-mvc

Is there a lint utility for ASP.NET MVC? Given that I frequently specify views and links via strings, when I move things around or change entity names I often break things, which I then only find out about when something fails at runtime.

ReSharper's v6 (whose nightlies are now available, if you don't mind living on the edge) will catch this kind of error for you.

You can use Refactor -> Rename and enable Search in Strings to replace every string in the solution

Other option -- use the strongly typed helpers (which might still be in the futures assemblies). EG, Html.Action<ProductsController>(x => x.ShowProduct(id)) ; really the only way to fly.

I don't know that there's something like that, but I'll tell you what I do: All my view names are in a struct that contains string constants. It's a pain to keep it sync'ed as the project changes, but it's worth it because you're far more likely to catch errors if you're using
ViewNames.Customer
rather than
"customer"

Related

Using Strongly Typed models in Umbraco 7.6.9?

I have tried looking into using Strongly Typed models (setting Umbraco.ModelsBuilder.ModelsMode to either AppData or Dll) for a while now, and I never fully understood how it works.
I already changed the Umbraco.ModelsBuilder.ModelsMode value and I generated the models inside the backoffice ModelsBuilder, then I included the App_Data\Models into Visual Studio, but what then?
#inherits Umbraco.Web.Mvc.UmbracoTemplatePage<ContentModels.Home>
#using Our.Umbraco.Vorto.Models;
#using Our.Umbraco.Vorto.Extensions;
#using ContentModels = Umbraco.Web.PublishedContentModels;
This is the code for my Home view. No matter what I try, I cannot access the #Model.PROPERTY or #CurrentPage.PROPERTY from my content. I can see the different properties inside my MODEL.generated.cs files.
What steps do I need to take, in order to do things like #Model.PROPERTY?
Okay, so it seems like there has been some changes in the newest 7.6.9 release (or maybe 7.6.8). This is what I had to do now:
<add key="Umbraco.ModelsBuilder.Enable" value="true" />
<add key="Umbraco.ModelsBuilder.ModelsMode" value="Dll" />
Then I can go into the backoffice and generate the models. The models are included into the project (location: ~\App_Data\Models\). Umbraco.Web.PublishedContentModels.dll from the ~\bin\ folder has to be included as well.
Then, because of .NET Core I think, I got an error when I tried loading my application saying this:
More than one type want to be a modle for content type File
This was caused because I had included everything inside ~\bin\, which means I had also included my Project.dll, Project.dll.config, and Project.pdb files. The Project.dll file also includes the same models, apparently, so I had to exclude those 3 files.
Now it simply works and I can now do #Model.Content.PROPERTY flawlessly.
You're not talking about "Dynamic" models, but Strongly Typed Models generated by Models Builder. By default Umbraco ships with PureLive setting which is keeping models in memory and generates them on the fly. It can be considered as "dynamic".
The tool and it's behaviour is well documented here: https://github.com/zpqrtbnk/Zbu.ModelsBuilder/wiki
Regarding modes of it, you can find all about it exactly in this place: https://github.com/zpqrtbnk/Zbu.ModelsBuilder/wiki/Builder-Modes
But answering your question - after you've changed the configuration, you need to compile your application as you need to keep those classes inside the DLL with which you're shipping your website. You're also able to regenerate models straight from your Developer's dashboard in Umbraco Backoffice.
You need to remember that if you would like to use DLL, LiveDLL or PureLive configuration - you need to get rid of classes generated inside your AppData or any other directory used with this mode as you'll experience errors saying about 'More that one type want to be a model for content type File'.
After that you should be able to access all properties of the document type via Model.Content.PropertyAlias. You probably missed the Content object, which is the strongly typed, IPublishedContent representation of you document.
Hope it will help you to make it work :)

Can I use url parameters in LESS css?

Intro:
I'm trying out LESS in an asp.net mvc environment.
I use dotless for server side processing (and I wouldn't want to use client side processing especially afer publishing the complete project).
I have to apply a design where there are different color schemes depending on different things (e.g. time of the day).
Less felt very powerful in this case as designing a parameterized css and only changing like 10 variables at the beginning of the file for every theme was really uplifting.
Problem:
But I would need to somehow change the color themes from an outside parameter.
Ideas:
First I thought that an URL parameter like style.less?theme=fuschia would be good, but I found no way to parse something like this.
Then I thought that making a very short blue.less, green.less, orange.less consisting only declared color variables, and including the main.less in every one of them would be a solid solution.
I had no chance to try out the second solution, but I thought this would be a good time to ask for advice on the most robust way of doing this.
The problem again is: I want to control some things in my less file from the outside.
Yes you can (because I implemented that feature for exactly that reason).
Dotless supports parameters from the outside via the querystring parameter.
<link rel="stylesheet" href="style.less?foo=bar" />
Will let you use the following less:
#foo = bar;
The parameter injection code is very simple. it just prepends the variable declarations to your normal less file, so anything that comes as a querystring parameter will follow the above syntax.
The code in question is very simple: https://github.com/dotless/dotless/blob/master/src/dotless.Core/Engine/ParameterDecorator.cs
AFAIK, you cannot pass parameters for dotnetless to use to do the compile.
As a suggestion, why not just call different less files? This would be fairly easy to do by using a Viewbag property.
To make the different less ones, You first create a less file with each set of colors in them. Then you import your base css file. dotnetless will merge the color definations in the parent file with the usages in the base file. So you have something like -
#baseGray: #ddd;
#baseGrayDark: darken(#baseGray, 15%);
#baseGrayLight: lighten(#baseGray, 10%);
#import "baseCss.less";
I just tested this on and MVC3 project and it works.

Would you like ASP.NET MVC view engine in which a view is created entirely in Code?

Recently I created a spike of a view engine, in which views are plain classes, and the content is created by using funny using-scope blocks.
The code together with a simple sample site is available at http://code.google.com/p/sharp-view-engine/
Here I'd like to hear your opinions regarding such an idea. Is it completely weird or maybe someone likes it?
I would actually not like that.
I can agree with DSLs (such as a Parser-Combinator or for generating XML Nodes in a data-context), but in this case I think that too much is being put in code that. And, in the end, this just complicates boundaries and leads to hard-to-maintain code. (You can already do the same, but with more verbosity just using the "standard" Web Controls. You can always use {subblock} in C# to limit a variables scope.)
The approach I prefer to use is templates with bindings (but no "code in templates"). That makes it easy for the "designer" (hopefully not me, or the next person to come along and) edit the layout of the view how they see fit. However, the core logic (the available controls and bindings) are kept in the code -- uncluttered. (Another advantage with the templates is that if they externally housed they do not require a recompile for every little change.)
Simplicity and maintainability are like ... zen.
This is an interesting idea taken to the extreme I'd say. At my shop we're using html conventions for pretty much everything except our layout. The only real html we have in the project is our Spark master page. For generating the content itself we use a convention engine that that spits out a semantic html model. (We're using the HtmlTags library from FubuMVC to build the semantic model.)
An example convention for rendering a multiline text box looks like:
public static HtmlTag Build(ElementRequest req)
{
return Tags.TextArea
.Rows(6)
.Id(req.ElementId)
.Attr("name", req.ElementId)
.Text(req.StringValue());
}
These conventions get triggered from reflecting on the view model (or we can manually call them from a helper method). The output is rendered (via ToString()) into the content section of our master page. We're joking that pretty soon we won't even need a view engine.
ps here's how we handle nesting. (Your using blocks look cluttered!)
return Tags.Div.Nest(
Tags.Button("save").AddClass("positive"),
Tags.Span.Text(" or "),
Tags.Anchor.Text("cancel").AddClass("negative")
);
Nest() is an extension method that simply takes a params array of HtmlTag and appends them to the parent's children collection.

ASP.NET MVC ViewData (using indices)

I had a working solution using ASP.NET MVC Preview 3 (was upgraded from a Preview 2 solution) that uses an untyped ViewMasterPage like so:
public partial class Home : ViewMasterPage
On Home.Master there is a display statement like this:
<%= ((GenericViewData)ViewData["Generic"]).Skin %>
However, a developer on the team just changed the assembly references to Preview 4.
Following this, the code will no longer populate ViewData with indexed values like the above.
Instead, ViewData["Generic"] is null.
As per this question, ViewData.Eval("Generic") works, and ViewData.Model is also populated correctly.
However, the reason this solution isn't using typed pages etc. is because it is kind of a legacy solution. As such, it is impractical to go through this fairly large solution and update all .aspx pages (especially as the compiler doesn't detect this sort of stuff).
I have tried reverting the assemblies by removing the reference and then adding a reference to the Preview 3 assembly in the 'bin' folder of the project. This did not change anything. I have even tried reverting the Project file to an earlier version and that still did not seem to fix the problem.
I have other solutions using the same technique that continue to work.
Is there anything you can suggest as to why this has suddenly stopped working and how I might go about fixing it (any hint in the right direction would be appreciated)?
We made that change because we wanted a bit of symmetry with the [] indexer. The Eval() method uses reflection and looks into the model to retrieve values. The indexer only looks at items directly added to the dictionary.
I've decided to replace all instances of ViewData["blah"] with ViewData.Eval("blah").
However, I'd like to know the cause of this change if possible because:
If it happens on my other projects it'd be nice to be able to fix.
It would be nice to leave the deployed working code and not overwrite with these changes.
It would be nice to know that nothing else has changed that I haven't noticed.
How are you setting the viewdata? This works for me:
Controller:
ViewData["CategoryName"] = a.Name;
View:
<%= ViewData["CategoryName"] %>
BTW, I am on Preview 5 now. But this has worked on 3 and 4...
Re: Ricky
I am just passing an object when I call the View() method from the Controller.
I've also noticed that on my deployed server where nothing has been updated, ViewData.Eval fails and ViewData["index"] works.
On my development server ViewData["index"] fails and ViewData.Eval works...
Yeah, so whatever you pass into the View is accessible in the View as ViewData.Model. But that will be just a good old object if you don't do the strongly typed Views...

Multiple languages in an ASP.NET MVC application?

What is the best way to support multiple languages for the interface in an ASP.NET MVC application? I've seen people use resource files for other applications. Is this still the best way?
If you're using the default view engines, then local resources work in the views. However, if you need to grab resource strings within a controller action, you can't get local resources, and have to use global resources.
This makes sense when you think about it because local resources are local to an aspx page and in the controller, you haven't even selected your view.
I found this resource to be very helpful
Its a wrapper round the HttpContext.Current.GetGlobalResourceString and HttpContext.Current.GetLocalResourceString that allows you to call the resources like this...
// default global resource
Html.Resource("GlobalResource, ResourceName")
// global resource with optional arguments for formatting
Html.Resource("GlobalResource, ResourceName", "foo", "bar")
// default local resource
Html.Resource("ResourceName")
// local resource with optional arguments for formatting
Html.Resource("ResourceName", "foo", "bar")
The only problem I found is that controllers don't have access to local resouce strings.
Yes resources are still the best way to support multiple languages in the .NET environment. Because they are easy to reference and even easier to add new languages.
Site.resx
Site.en.resx
Site.en-US.resx
Site.fr.resx
etc...
So you are right still use the resource files.
The Orchard project uses a shortcut method called "T" to do all in-page string translations. So you'll see tags with a #T("A String to Translate").
I intend to look at how this is implemented behind the scenes and potentially use it in future projects. The short name keeps the code cleaner since it will be used a lot.
What I like about this approach is the original string (english, in this case) is still easily visible in the code, and doesnt require a lookup in a resource tool or some other location to decode what the actual string should be here.
See http://orchardproject.net for more info.
Some of the other solutions mentioned as answer do not work for the released version of MVC (they worked with previous versions of alpha/beta).
Here is a good article describing a way to implement localization that will be strongly-typed and will not break the unit testing of controllers and views: localization guide for MVC v1
This is another option, and you'll have access to the CurrentUICulture in the controller:
Check MVC3-multi-language

Resources