What's the use of the Name parameter in RouteAttribute? - asp.net

Looking at this:
[Route("", Name = "GetChanges")]
What's the use of the Name parameter? The only useful usage of this is I am able to refer to the action when calling CreatedAtRoute such that:
return CreatedAtRoute("GetChanges", new { id = model.ChangeId }, model);
So why and what's the use case for the "Name" in RouteAttribute?

I think the use case is simply ambiguity resolution. If there are more than two actions on a controller that may qualify somehow the name is not ambiguous. I would prefer not to use a name unless needed, but I could see organizations adopt the ‘though shall use names to resolve unambiguously” approach as well. Count me as not a proponent, but the mechanism is there should you need it.

WebAPI by itself doesn't allows function overloading. So if there are two functions with same name but differing in parameters (overloading within the implementing class), the name attribute allows for those methods to be called by a specific names.
Along with, the class naming may be governed by different coding standards, whereas route names are those exposed to client, hence may have to be following different guidelines

Related

Write OCL restrictions related to associations with other classes

How do you model the following restriction?
A place is popular if it has been bookmarked by 2 or more than 2 users.
Here the corresponding uml diagram:
uml
I tried several ways, for example:
context place inv: place.popular = (self.user.place.popular>=2)
but nothing worked well...
The constraint that you expressed is an interesting start but does not work because self.user in the place context is a collection. Your expression moreover attempts to use popular as if it were an integer.
If there would be an unambiguous user, you’d just need to check its size():
context place inv:
place.popular = (self.user->size()>1)
Unfortunately, there are two associations with User: one for the favorites (bookmarks) and for for historic (past visits whether they appreciated or not). This makes that expression ambiguous. To disambiguate, in absence of a role name (name at the association end), you’ll need to qualify the user with the association name:
context place inv:
place.popular = (self.favorites::user->size()>1)
(Btw, in case of absence of association name, you'd need to use the default name A_place_user instead of favorites).
See also section 7.5.3 of the OCL specifications for more information about navigating associations.
Edit: more complex navigations**:
You could also navigate to properties of associated classes. It works like the navigation above, but with the help of the collect() operation. You can then perform collection oprations such as sum()
context route inv:
self.totalDistance = self.step->collect(distanceFromPreviousStep)->sum()
Navigating to a specific object in a collection of linked objects is more delicate. In the case of the steps, we see that the association is ordered (by the way, it should be {ordered} and not «ordered»). This allows to use last() to get the last element in the given order:
context route inv:
self.destination::place = self.step->last().place

JSON-LD, is there any way to specify the default URI for the #id of a #type or the values of a property?

(I've already asked this on the W3/JSON mailing list, I'll try here too.)
I'm fairly new to JSON-LD, although I have significant experience with Semantic Web technologies.
I've read the guideline document (https://www.w3.org/TR/json-ld/) and I haven't get if the feature at issue is supported:
Suppose you have JSON objects of #type Person and #type Address, both having the #id property. Typical API-coming data will have values like integers or some internal, context-dependant IDs. It's pretty common to RDF-translate those values to prefix-based URIs like http://www.example.com/Person/123 or http://www.example.com/Address/xh324m44.
What I would like to do is to specify those prefixes and keep data telling #id = '123', with the value joins happening at RDF serialisation stage (the same specification would make it possible to do the opposite conversion too). Clearly, in such a use case, the prefixes depend on the #type of objects, and the #base mechanism is not enough. Moreover, it would be useful to have this mechanism available for properties too, e.g., to associate the address URI prefix to the values of the "address" JSON property.
It doesn't seem that this is currently available in JSON-LD, or am I missing something? Any plan for future extensions?
You can use #base in the context to create a URI base for values of #id, but this will not include something from #type. This sounds like something you might get by defining a URI template and using variables to expand type and id to create a URI. You can do this in a templating language and create the JSON-LD, but not directly in JSON-LD itself. Not likely to be a feature included by the language in the future, either, as it's application is pretty narrow.

Defining Symfony Services to maximize maintainability

I'm working on a big domain, for which maintainability is very important.
There are these general workers called ExcelHandlers that implement ExcelHandlerInterface (more on the interface in the ideas section) and basically get an UploadedFile as their input, upload them wherever they want and return the read data as an associative array. Now I have created this base class ExcelFileHandler which does all of these tasks for all excel files given two arguments:
1. The Directory to upload the file
2. the mapping of the excel columns to the indexes of the associative array.
Some ExcelHandlers might have to extend the ExcelFileHandler and do some more processing, in order to get the associative array of data.
The UploadedFile is always passed to the ExcelHandler from the controller.
Now here is the question. Given the generic structure of the ExcelFileHandler how should I define services for specific ExcelHandlers given that some only differ with the original one in the directory to upload the file and the mapping array.
My Ideas:
1. The first approach involves giving the directory and the mapping as the function arguments to ExcelHandleInterface::handle this will make the prototype something like handle(UploadedFile $file, array $mapping, $dir), $mapping and $dir are given to the function as arguments and passed to the handler by the controllers which has the parameters as constructor injections.
2.1 Defining the prototype of handle to be handle(UploadedFile $file), this would require the ExcelHandlers to have knowledge of $dir and $mapping. $dir will always be injected from the constructor.
2.1.1 Foreach individual ExcelHandler in the application, define a separate class e.g: UserExcelHandler, ProductExcelHandler, .... Which extend the ExcelFileHandler and leaves us again with two choices.
2.1.1.1 inject $mapping from outside. e.g:
// in the child class
public function __construct($dir, $mapping){
parent::__construct($dir, $mapping);
}
2.1.1.2 define $mapping in the constructor of the child class. e.g:
// in the child class
public function __construct($dir){
$mapping = array(0 => 'name', 1 => 'gender');
parent::__construct($dir, $mapping);
}
2.1.2 Not to create a class for each separate ExcelHandler and instead define the ExcelFileHandler as an abstract service and decorate with the right parameters to get the concrete ExcelHandler Service with the desired functionality, obviously ExcelHandlers with custom logic must be defined seperately, and to create a uniform code base, $mapping will always be injected from the Container in this case.
In your experience, what other paths can I take and which ones yield better results in the long term?
First of all, it seams as you've already put two separate things into one.
Uploading a file and reading it's contents are two separate concerns, which can change separately (like you said, $directory and $mapping can change case-by-case). Thus I would suggest to use separate services for uploading and reading the file.
See Single responsibility principle for more information.
Furthermore, due to very similar reasons, I would not recommend base classes at all - I'd prefer composition over inheritance.
Imagine that you have 2 methods in your base class: upload, which stores file to a local directory, and parse, which reads excel file and maps columns to some data structure.
If you need to store file in a remote storage (for example FTP), you need to override upload method. Let's call this service1.
If you need to parse file differently, for example combining data from 2 sheets, you need to override parse method. Let's call this service2.
If you need to override both of these methods, while still being able to get service1 and service2, you're stuck, as you'll need to copy-and-paste the code. There's no easy way to use already written functionality from (1) and (2).
In comparison, if you have interface with upload method and interface with parse method, you can inject those 2 separate services where you need them as you need them. You can mix any implementations of those already available. All of them are already tested and you do not need to write any code - just to configure the services.
One more thing to mention - there is absolutely no need to create (and name) classes by their usage. Name them by their behaviour. For example, if you have ExcelParser, which takes $mapping as an argument to a constructor, no need to call it UserExcelParser if the code itself has nothing to do with users. If you need to parse data from several sheets, just create SheetAwareExcelParser etc., not ProductExcelParser. This way you can reuse the code. Also correct naming lets understand the code more easily.
In practice, I've seen when function or class is named by it's usage, and then it's just used in another place with no renaming, refactoring etc. These cases are really not what you're looking for.
Service names (in another words concrete objects, not classes), can of course be named by their purpose. You just configure them with any required functionality (single vs separate sheets etc.)
To summarize, I would use 2.1.2 above all other of your given options. I would inject $dir and $mapping via DI in any case, as these do not change in runtime - these are configuration.

What is the proper way to inject (via constructor) different types that implement that same interface?

For example, let's say I have an interface 'IFeed' and two concrete types ('Feed1' and 'Feed2') that implement this interface. Now let's say I have a 'FeedManager' type that takes multiple parameters that will get resolved dynamically, two of which are of type 'IFeed' and I'd like both concrete type to be injected via constructor injection, not via manual resolve (I only use resolve once at the composition root). I have a feeling that I should be using a factory but I wanted to see what the proper way of doing this might be. Many thanks in advance.
If you want ALL implementations of IFeed, you can use array syntax in your constructor and then nothing special is needed at type registration time.
container.RegisterType<IFeedManager, FeedManager>();
container.RegisterType<IFeed, FeedA>("FeedA"); // The name doesn't matter
container.RegisterType<IFeed, FeedB>("FeedB"); // The name doesn't matter
Then the manager constructor...
public FeedManager(IFeed[] feeds) {...}
or if you want to add a little flare for calling the constructor directly...
public FeedManager(params IFeed[] feeds) {...}
Assuming you want to determine the actual concrete instances at runtime, you need to use named type registrations and then tell unity which one you want. So, use a factory method to construct the types required and pass those in as parameter overrides. Unity will use the overrides and resolve any remaining dependencies.
// register the types using named registrations
container.RegisterType<IFeedManager,FeedManager>()
container.RegisterType<IFeed, Feed1>("Feed1")
container.RegisterType<IFeed, Feed2>("Feed2")
Assuming your feed manager has the following named constructor parameters
class FeedManager : IFeedManager
{
public FeedManager (IFeed Feed1, IFeed Feed2, string someOtherDependency)
{
}
}
and create your feed manager:
static IFeedManager CreateFeedManager()
{
ParameterOverride feed1 = new ParameterOverride("Feed1"
,_container.Resolve<IFeed>("feed1"));
ParameterOverride feed2 = new DependencyOverride("Feed2"
,_container.Resolve<IFeed>("feed2"));
IFeedManager = _container.Resolve<IFeedManager>(feed1,feed2)
return IFeedManager;
}
Obviously this is overly simplified, but you you insert your own logic to determine which instance is to be resolved and then injected for each of the IFeed instances required by the FeedManager.
With Unity you would do this like so:
container.RegisterType<IFeed, Feed1>("Feed1");
container.RegisterType<IFeed, Feed2>("Feed2");
container.RegisterType<FeedManager>(new InjectionConstructor(new ResolvedParameter<IFeed>("Feed1"),
new ResolvedParameter<IFeed>("Feed2")));
This has now configured Unity so that when it needs to resolve a FeedManager, it will resolve Feed1 for the first parameter and Feed2 for the second parameter.

What is main advantage of Tuple?

Can anyone tell me what is the main advantage of using tuple? In what scenarios do I need to use these?
I assume that you're talking about the Tuple<> type and not anonymous tuple classes.
Like an anonymous type, Tuple<> allows you to avoid declaring a new class just to group a few objects. Unlike anonymous types, tuple types have known names and thus can be used as method return and parameter values, etc.
Personally, I try to avoid heavy use of Tuple<> because it can make for difficult to understand code, expecially when used with primitive types (e. g. if you see a Tuple it's not obvious what each field represents).
One place I have found tuples to be very useful is as dictionary keys. Because Tuples implement Equals() and GetHashCode() (not ==, though!), they are perfect for things like private dictionaries that cache information based on a compound key.
It's used mostly to avoid declaring a class / struct with a few properties only for the sake of passing a group of objects around, where only one object can be passed.
Lets say I have a list of urls to go through and if i get an error (4xx or 5xx) I want to build a list and then either later display it to the user or just look at it in my debugger.
I'd catch the web exception and have a Tuple<string, int> (url, http error code) instead of creating a struct for one or two functions to use. Heck it might even be a foreach loop with a breakpoint on if the list has more then 0 items. Thats when it is useful.

Resources