Handling Singular and Plural Controllers/Routes - asp.net

I'm a little confused on how I should handle singular and plural routes and controllers in my web application.
The website is a simple quotes site - think Einstein, Shakespeare etc. not Insurance. Within the project I have a controller called `QuoteController'. The controller name is singular, so does this mean that the controller should only handle the display of single quotes? I.E.
/quote/love-is-a-battlefield-1
Do I then need another controller for the display of multiple quotes (plural)? For example:
/quotes/ (would default to most recent)
/quotes/new
/quotes/shakespeare
/quotes/popular
Is it convention, or good practice, to have separate controllers for singular and plural routes? I hope that makes sense.

Just because the default controllers of asp-mvc have singular names, it doesn't mean you should implement singular form for all your controllers.
The correct answer is: it depends on the quantity of the entity that your controller represents.
Singular, example the AccountController is singular because it represents actions (action method) pertaining to a single account only.
Plural If your controller contains at least one action method that handles multiple entities at a single transaction.
Example plural format
users/update/3
The route above makes you think you are editing all users, which does not makes sense if you read it like a sentence. However, if you read your route like query, it will make much more sense.
If we think about it, a route IS a query: {entities}/{action}/{parameter} looks like a query to me.
users/ shorthand of users/all reads "select all users table"
users/123 reads "select single entity from users table"
users/update/123 reads "update single entity from users table"
Major sites use plural format, see sample below
stackoverflow.com/questions <- list of questions (multiple)
stackoverflow.com/questions/18570158 <- individual question (single)
stackoverflow.com/questions/ask <- new question (single)
stackoverflow.com/users <- display list of users (multple)
stackoverflow.com/users/114403 <- individual user (single)
asp.net/mvc/tutorials <- display list of tutorials (multiple)
asp.net/mvc/tutorials/mvc-5 <- individual tutorial (single)
facebook.com/messages/ <- Display list of messages (multiple)
facebook.com/messages/new <- Create a single message (single)
facebook.com/messages/john <- view individual messages (multiple)
I believe that English grammar should be strictly incorporated in every programming aspect. It reads more natural, and leads to good code hygiene.

Answer
Here's a question asked in programmers StackExchange that suggests keeping class names singular. I especially like the logic in one of the answers, "The tool to turn screws with is called "screw driver" not "screws driver"." Which I agree with. The names should be kept to nouns and adjectives.
As far as routing goes, best practices seems to favor that routes be pluralized nouns, and to avoid using verbs. This Apigee blog says, "avoid a mixed model in which you use singular for some resources, plural for others. Being consistent allows developers to predict and guess the method calls as they learn to work with your API." and suggests using singular or plural based off what popular websites have done. Their only example for using singular nouns in the route is the Zappos site, which has http://www.zappos.com/Product as a route; but if you examine the site, it's not exactly a route to a product resource but is instead a query, probably for all their products. You can enter http://www.zappos.com/anything and get a results page. So I wouldn't put too much stock into that.
Other blogs like this one from mwaysolutions (random find) say to "use nouns but no verbs" and "use plural nouns". Other points aside, most blogs/articles tend to say the same thing. Plural nouns and no verbs.
TL;DR: Use singular nouns for controllers and plural nouns for routes.
Controllers
Controllers and routes represent two different concepts. The controller is a class, or a blueprint. Similar to a stamper, I wouldn't say I had a UnicornsStamper I'd say I had a UnicornStamper that makes a stamp of a unicorn with which I could make a collection of unicorn stamps with. Collections, Enum types that are bit fields, static class that is a collection of properties (acts like a collection), and probably a few other edge cases are where I'd use a plural name.
Routes
A(n) URL is an address to a resource, thus the name Uniform Resource Locator. I disagree that "a route IS a query". Routes can contain queries (query string) to narrow down returned resources but the route is the location or the resource(s) that's being requested.
With the advent of attribute routing, pluralizing routes for controllers is as easy as adding a [RoutePrefix("quotes")] attribute to the QuoteController declaration. This also allows for easier design for associative routes. Looking at the sample routes provided in the original question:
/quotes
GET: Gets all quotes
POST: Creates a new quote
/authors/shakespeare/quotes
Associative route in the QuoteController
GET: Gets all Shakespeare quotes
/quotes/new
This is a bad route IMO. Avoid verbs.
Make a POST request to '/api/quotes' to create a new quote
/quotes/shakespeare
/quotes/popular
Although these would be nice to have, they're not practical for routing (see below)
The problem with the last two routes is that you have no simple way of differentiating between popular quotes and quotes by authors, not to mention that routes that link to quotes by name or Id. You would need actions decorated with [Route("popular")] followed by [Route("{author}")] (in that order) in order for the routing table to pick the routes up in the appropriate order. But the author route kills the possibility of having routes [Route("{quoteName}")] or [Route("{quoteId}")] (assuming quoteId is a string). Naturally, you'll want to have the ability to route to quotes by name and/or ID.
Slightly Off Topic
Getting quotes by author would best be done by an associative route. You could still probably get away with the popular route as a static route name, but at this point you're increasing route complexity which would be better suited for a query string. Off the top of my head, this is how I might design these routes if I really wanted to have the popular search term in the route:
a:/authors/{authorName}/quotes
b:/authors/{authorName}/quotes/popular
c:/authors/{authorName}/quotes?popular=true
d:/quotes/popular
e:/quotes/popular?author={authorName}
f:/quotes?author={authorName}&popular=true
g:/quotes/{quoteName|quoteId}
These could be spread across the QuoteController's actions. Assuming the controller has a [RoutePrefix("quotes")] attribute:
[HttpGet]
[Route("popular")]
[Route("~/authors/{authorName}/quotes/popular")]
// Handles routes b, d, & e
public ViewResult GetPopularQuotes(string authorName)
return GetQuotes(authorName, true);
[HttpGet]
[Route("")]
[Route("~/authors/{authorName}/quotes")
// Handles routes a, c, & f
public ViewResult GetQuotes(string authorName, bool popular = false)
// TODO: Write logic to get quotes filtered by authorName (if provided)
// If popular flag, only include popular quotes
[HttpGet]
[Route("{quoteId}")]
// Handles route g
public ViewResult GetQuoteById(string quoteId)
// TODO: Write logic to get a single quote by ID
Disclaimer: I wrote these attributes off the top of my head, there may be minor discrepancies that would need to be ironed out, but hopefully the gist how to get these routes to work comes through.
Hopefully this helps to clear up some confusion on the topic of controller and routing best practices on naming conventions. Ultimately the decision to use plural or singular controllers or routes is up to the developer. Regardless, be consistent once you pick a best practice to follow.

Name of controller can be plural or singular based on the logic it executes. Most likely we keep controller name as singular because ProductController sounds little better than ProductsController.
/product/list or /products/list
/product/add or /products/add
You can use both. But you must keep consistency and you should not mix them. Either all URL should be plural for every entity types or all should be singular.
In ASP.NET sample, they have used Singular controller names Such as HomeController, AccountController. In case of HomeController you can't use HomesController because that no longer represents current site Home.
With regards to logic, mostly we create Controller per database entity, in which we infer that Controller represents Actions to be performed on "Entity" So it is good to use Singular controller name and there is no harm.
Only if you want to create set of Controller representing collection of something that should look like or map to plural database table names then you can name that as plural.

Good question. Some contributors to this site would recommend you try Programmers website, but I'm willing to attempt an answer to your question.
Routing mechanism in ASP.NET MVC ,conceptually, is based on Resource-oriented architecture; the common guideline in ROA is
Applications should expose many URIs (possibly an infinite number of them), one for each Resource (any resources in your applications should be unambiguously accessible via a unique URI)
So, it's up to you to decide whether quote and quotes are two different resources or not.

Related

Symfony2: Why weren't query string parameters included in the routing component?

I am porting a legacy application to Symfony2 and I am struggling because routing doesn't include query string parameters. Some quick examples: Suppose you have a search page for books where you can filter results based on criteria:
http://www.bookstore.com/books?author=Stephen+King&maxPrice=20
The nice thing about query string parameters in a case like this is you can have any number of filters, use the ones you want for any given request, and not crowd the URL with filters you're not using.
Let's say we rewrote the routing for the above query using the Symfony2 routing component. It might look like this:
http://www.mybookstore.com/book/any_title/stephen%20king/any_release_date/max_price_20/any_min_price/any_format/any_category
Even not taking into account how arbitrarily long an unclean that URL is I still don't think it is as intuitive because each 'segment' of that route is not a key value pair but instead just a value (e.g. author=Stephen+King > /stephen%20king/).
You can of course access query string parameters in the controller by passing the Request object into the action method (e.g. indexAction(Request $request) {) but then validating them and passing them into other parts of the application becomes a hassle (i.e. where I find myself now). What if you are using the Knp Menu Bundle to build your sidebar and you want parts to be marked as .current based on query string parameters? There is no functionality for that, just functionality to integrate with Symfony2 routes.
And how to validate that your query string parameters are acceptable? I am currently looking at validating them like a form to then pass them into the database to generate a query. Maybe this is the way the Symfony2 team envisioned handling them? If so I'd just really like to know why. It feels like I'm fighting the application.
I ended up actually asking Fabien this question at Symfony Live San Francisco 2012. There was another talk at the same conference in regards to this question and I will share with you the slides here:
http://www.slideshare.net/Wombert/phpjp-urls-rest#btnNext
Basically in the slides you can see that the author agrees with me in that query string parameters should be used for filtering. What they should not be used for is determining a content source. So a route should point to a product (or whatever) and query string parameters should then be used in your controller to apply whatever logic you require to filter that content source (as per Fabien).
I ended up creating an entity in my application that I bind all my query string parameters to and then manipulate, much the same way forms are handled. In fact when you think about it it's basically the same thing.
Like in Symfony1, query strings are independent from the route parameters.
If you have a path defined as #Route("/page/{id}", name="single_page"), you can create a path in your view like this:
{{ path('single_page', { id: 3, foo: "bar" }) }}
The resulting URL will be /page/3?foo=bar.

What's the RESTful way of attaching one resource to another?

this is one of the few moments I couldn't find the same question that I have at this place so I'm trying to describe my problem and hope to get some help an ideas!
Let's say...
I want to design a RESTful API for a domain model, that might have entities/resources like the following:
class Product
{
String id;
String name;
Price price;
Set<Tag> tags;
}
class Price
{
String id;
String currency;
float amount;
}
class Tag
{
String id;
String name;
}
The API might look like:
GET /products
GET /products/<product-id>
PUT /prices/<price-id>?currency=EUR&amount=12.34
PATCH /products/<product-id>?name=updateOnlyName
When it comes to updating references:
PATCH /products/<product-id>?price=<price-id>
PATCH /products/<product-id>?price=
may set the Products' Price-reference to another existing Price, or delete this reference.
But how can I add a new reference of an existing Tag to a Product?
If I wanted to store that reference in a relational database, I needed a relationship table 'products_tags' for that many-to-many-relationship, which brings us to a clear solution:
POST /product_tags [product: <product-id>, tag: <tag-id>]
But a document-based NoSQL database (like MongoDB) could store this as a one-to-many-relationship for each Product, so I don't need to model a 'new resource' that has to be created to save a relationship.
But
POST /products/<product-id>/tags/ [name: ...]
creates a new Tag (in a Product),
PUT /products/<product-id>/tags/<tag-id>?name=
creates a new Tag with <tag-id> or replaces an existing
Tag with the same id (in a Product),
PATCH /products/<product-id>?tags=<tag-id>
sets the Tag-list and doesn't add a new Tag, and
PATCH /products/<product-id>/tags/<tag-id>?name=...
sets a certain attribute of a Tag.
So I might want to say something link this:
ATTACH /products/<product-id>?tags=<tag-id>
ATTACH /products/<product-id>/tags?tag=<tag-id>
So the point is:
I don't want to create a new resource,
I don't want to set the attribute of a resource, but
I want to ADD a resource to another resources attribute, which is a set. ^^
Since everything is about resources, one could say:
I want to ATTACH a resource to another.
My question: Which Method is the right one and how should the URL look like?
Your REST is an application state driver, not aimed to be reflection of your entity relationships.
As such, there's no 'if this was the case in the db' in REST. That said, you have pretty good URIs.
You talk about IDs. What is a tag? Isn't a tag a simple string? Why does it have an id? Why isn't its id its namestring?
Why not have PUT /products/<product-id>/tags/tag_name=?
PUT is idempotent, so you are basically asserting the existance of a tag for the product referred to by product-id. If you send this request multiple times, you'd get 201 Created the first time and 200 OK the next time.
If you are building a simple system with a single concurrent user running on a single web server with no concurrency in requests, you may stop reading now
If someone in between goes and deletes that tag, your next put request would re-create the tag. Is this what you want?
With optimistic concurrency control, you would pass along the ETag a of the document everytime, and return 409 Conflict if you have a newer version b on the server and the diff, a..b cannot be reconciled. In the case of tags, you are just using PUT and DELETE verbs; so you wouldn't have to diff/look at reconciliation.
If you are building a moderately advanced concurrent system, with first-writer-wins semantics, running on a single sever, you can stop reading now
That said, I don't think you have considered your transactional boundaries. What are you modifying? A resource? No, you are modifying value objects of the product resource; its tags. So then, according to your model of resources, you should be using PATCH. Do you care about concurrency? Well, then you have much more to think about with regards to PATCH:
How do you represent the diff of a hierarchial JSON object?
How do you know what PATCH requests that conflict in a semantic way - i.e. we may not care about DELETEs on Tags, but two other properties might interact semantically.
The RFC for HTTP PATCH says this:
With PATCH, however, the enclosed entity contains a set of
instructions describing how a resource currently residing on the
origin server should be modified to produce a new version. The PATCH
method affects the resource identified by the Request-URI, and it also
MAY have side effects on other resources; i.e., new resources may be
created, or existing ones modified, by the application of a PATCH.
PATCH is neither safe nor idempotent as defined by [RFC2616], Section
9.1.
I'm probably going to stop putting strange ideas in your head now. Comment if you want me to continue down this path a bit longer ;). Suffice to say that there are many more considerations that can be done.

Fat ASP.NET MVC Controllers

I have been reading about "Fat Controllers" but most of the articles out there focus on pulling the service/repository layer logic out of the controller. However, I have run into a different situation and am wondering if anyone has any ideas for improvement.
I have a controller with too many actions and am wondering how I can break this down into many controllers with fewer actions. All these actions are responsible for inserting/updating/removing objects that all belong to the same aggregate. So I'm not quiet keen in having a seperate controller for each class that belongs to this aggregate...
To give you more details, this controller is used in a tabbed page. Each tab represents a portion of the data for editing and all the domain model objects used here belong to the same aggregate.
Any advice?
Cheers,
Mosh
For all your tabs you can use one action, that have an tab parameter, that indicate what data you need to return.
The controller job is to cast this string tab into enum type variable. Then the tab will be send to the repository, and the repository job is to return data in response to the tab value.
The controller should do its job through to services: Input Validator and Mapper.
The mapper service job is to map the user input (typically strings) into actual typed value (int, System.DateTime, enum types, etc).
The validator job is to check that the input is valid.
Following this principles should keep your controllers really tiny.
If you wanted something simple and easy I'd suggest just splitting up the controller into partial classes based on the tabs. Of course, it's still a fat controller there's just some obvious separation between the various tab functionalities.

Looking for a good technique for storing email templates

I am building a site in which we are making moderate use of email templates. As in, HTML templates which we pass tokens into like {UserName}, {Email}, {NameFirst}, etc.
I am struggling with where to store these, as far as best practice goes. I'll first show the approach I took, and I'd be really excited to hear some expert perspective as a far as alternate approaches.
I created HTML templates in a folder called /Templates/.
I call a static method in my service layer, which takes in the following arguments:
UserName
UserID
Email
TemplatePath ("~/Templates")
Email Subject
Within the service layer I have my static method SendUserEmail() which makes use of a Template class - which takes a path, loads it as a string, and has a AddToken() Method.
Within my static SendUserEmail(), I build the token list off of the method signature, and send the email.
This makes for a quite long method call in my actual usage, especially since I am calling from the web.config the "TemplatePath", and "Email Subject". I could create a utility that has a shorter method call than the ConfigurationManager.AppSettings, but my concern is more that I don't usually see method signatures this long and I feel like it's because I'm doing something wrong.
This technique works great for the emails I have now, which at the most are using the first 3 tokens. However in the future I will have more tokens to pass in, and I'm just wondering what approach to take.
Do I create methods specific to the email needing to be sent? ie. SendNewUserRegistration(), SendMarketingMaterial(), and each has a different signature for the parameters?
I am using ASP.NET Membership, which contains probably the extend of all the fields I'll ever need. There are three main objects, aspnet_User, aspnet_Mebership and aspnet_profile. If it was all contained in one object, I would have just passed that in. Is there performance concerns with passing in all 3, to get all the fields I need? That is versus just passing in aspnet_User.UserID, aspnet_User.Email, etc?
I could see passing in a dictionary with the token entries, but I'm just wondering if that is too much to ask the calling page?
Is there a way to stick these in a config file of it's own called Templates.config, which has tags like -
<Templates>
<EmailTemplate Name="New User Registration">
<Tokens>
<UserName>
<UserID>
<Email>
</Tokens>
<Message Subject="Hi welcome...">
Hi {UserName}...
</Message>
</EmailTemplate>
</Templates>
I guess the main reason I'm asking, is because I'm having a hard time determining where the responsibility should be as far as determining what template to use, and how to pass in parameters. Is it OK if the calling page has to build the dictionary of TokenName, TokenValue? Or should the method take each in as a defined parameter? This looks out of place in the web.config, because I have 2 entries for and , and it feels like it should look more nested.
Thank you. Any techniques or suggestions of an objective approach I can use to ask whether my approach is OK.
First of all I would like to suggest you to use NVelocity as a template engine. As for main problem I think you can create an abstract class MailMessage and derive each one for every needed message (with unique template). So you will use this like following:
MailMessage message = new UserRegistrationMessage(tokens);
//some code that sends this message
Going this way you force each concrete XXXMessage class to be responsible for storing a template and filling it with the given tokens. How to deal with tokens? The simpliest way is to create a dictionary before passing it to the message, so each concrete message class will know how to deal with passed dictionary and what tokens it should contain, but you also need to remember what tokens it should contain. Another way (I like it more) is to create a general abstract type TokenSet and a derived one for every needed unique set of tokens. For example you can create a UserMessageTokenSet : TokenSet and several properties in it:
UserNameToken
SomeUserProfileDataToken
etc. So using this way you will always know, what data you should set for each token set and
UserRegistrationMessage will know what to take from this tokenSet.
There are a lot of ways to go. If you will describe you task better I think I will try suggest you something more concrete. But general idea is listed above. Hope it helps =)

ASP.NET MVC routing based on data store values

How would you tackle this problem:
I have data in my data store. Each item has information about:
URL = an arbitrary number of first route segments that will be used with requests
some item type = display will be related to this type (read on)
title = used for example in navigation around my application
etc.
Since each item can have an arbitrary number of segments, I created a custom route, that allows me to handle these kind of requests without using the default route and having a single greedy route parameter.
Item type will actually define in what way should content of a particular item be displayed to the client. I was thinking of creating just as many controllers to not have too much code in a single controller action.
So how would you do this in ASP.NET MVC or what would you suggest would be the most feasible way of doing this?
Edit: A few more details
My items are stored in a database. Since they can have very different types (not inheritable) I thought of creating just as many controllers. But questions arise:
How should I create these controllers on each request since they are related to some dynamic data? I could create my own Controller factory or Route handler or possibly some other extension points as well, but which one would be best?
I want to use MVC basic functionality of using things like Html.ActionLink(action, controller, linkText) or make my own extension like Html.ActionLink(itemType, linkText) to make it even more flexible, so Action link should create correct routes based on Route data (because that's what's going on in the background - it goes through routes top down and see which one returns a resulting URL).
I was thinking of having a configuration of relation between itemType and route values (controller, action, defaults). Defaults setting may be tricky since defaults should be deserialized from a configuration string into an object (that may as well be complex). So I thought of maybe even having a configurable relation between itemType and class type that implements a certain interface like written in the example below.
My routes can be changed (or some new ones added) in the data store. But new types should not be added. Configuration would provide these scenarios, because they would link types with route defaults.
Example:
Interface definition:
public interface IRouteDefaults
{
object GetRouteDefaults();
}
Interface implementation example:
public class DefaultType : IRouteDefaults
{
public object GetRouteDefaults()
{
return new {
controller = "Default",
action = "Show",
itemComplex = new Person {
Name = "John Doe",
IsAdmin = true
}
}
}
Configuration example:
<customRoutes>
<route name="Cars" type="TypeEnum.Car" defaults="MyApp.Routing.Defaults.Car, MyApp.Routing" />
<route name="Fruits" type="TypeEnum.Fruit" defaults="MyApp.Routing.Defaults.Fruit, MyApp.Routing" />
<route name="Shoes" type="TypeEnum.Shoe" defaults="MyApp.Routing.Defaults.Shoe, MyApp.Routing" />
...
<route name="Others" type="TypeEnum.Other" defaults="MyApp.Routing.Defaults.DefaultType, MyApp.Routing" />
</customRoutes>
To address performance hit I can cache my items and work with in-memory data and avoid accessing the database on each request. These items tend to not change too often. I could cache them for like 60 minutes without degrading application experience.
There is no significant performance issue if you define a complex routing dictionary, or just have one generic routing entry and handle all the cases yourself. Code is code
Even if your data types are not inheritable, most likely you have common display patterns. e.g.
List of titles and summary text
item display, with title, image, description
etc
If you can breakdown your site into a finite number of display patterns, then you only need to make those finite controllers and views
You them provide a services layer which is selected by the routing parameter than uses a data transfer object (DTO) pattern to take the case data and move it into the standard data structure for the view
The general concept you mention is not at all uncommon and there are a few things to consider:
The moment I hear about URL routing taking a dependency on data coming from a database, the first thing I think about is performance. One way to alleviate potentialy performance concerns is to use the built in Route class and have a very generic pattern, such as "somethingStatic/{*everythingElse}". This way if the URL doesn't start with "somethingStatic" it will immediately fail to match and routing will continue to the next route. Then you'll get all the interesting data as the catch-all "everythingElse" parameter.
You can then associate this route with a custom route handler that derives from MvcRouteHandler and overrides GetHttpHandler to go to the database, make sense of the "everythingElse" value, and perhaps dynamically determine which controller and action should be used to handle this request. You can get/set the routing values by accessing requestContext.RouteData.Values.
Whether to use one controller and one action or many of one or many of each is a discussion unto itself. The question boils down to how many different types of data do you have? Are they mostly similar (they're all books, but some are hardcover and some are softcover)? Completely different (some are cars, some are books, and some are houses)? The answer to this should be the same answer you'd have if this were a computer programming class and you had to decide from an OOP perspective whether they all have a base class and their own derives types, or whether they could be easily represented by one common type. If they're all different types then I'd recommend different controllers - especially if each requires a distinct set of actions. For example, for a house you might want to see an inspection report. But for a book you might want to preview the first five pages and read a book review. These items have nothing in common: The actions for one would never be used for the other.
The problem described in #3 can also occur in reverse, though: What if you have 1,000 different object types? Do you want 1,000 different controllers? Without having any more information, I'd say for this scenario 1,000 controllers is a bit too much.
Hopefully these thoughts help guide you to the right solution. If you can provide more information about some of the specific scenarios you have (such as what kind of objects these are and what actions can apply to them) then the answer can be refined as well.

Resources