What does it mean by "segment variables matched by the URL pattern" in the following? - asp.net-core

Reading the book Pro ASP.NET Core 3, by Adam Free Man, I saw some lines saying as follow:
The endpoint in Listing 13-7 enumerates the HttpRequest.RouteValues property to generate
a response that lists the names and value of the segment variables matched by the URL pattern.
I got confused with the highlighted part above. Could anyone explain about the following part:
the names and value of the segment variables matched by the URL pattern.
Here is the full text I mentioned in above:
endpoints.MapGet("{first}/{second}/{third}", async context => {
foreach (var kvp in context.Request.RouteValues) {
await context.Response.WriteAsync($"{kvp.Key}: {kvp.Value}\n");
} } ```
The RouteValuesDictionary class is enumerable, which means that it can
be used in a foreach loop to generate a sequence of
KeyValuePair<string, object> objects, each of which corresponds to the
name of a segment variable and the corresponding value extracted from
the request URL. The endpoint in Listing 13-7 enumerates the
HttpRequest.RouteValues property to generate a response that lists
the names and value of the segment variables matched by the URL
pattern. The names of the segment variables are first, second, and
third, and you can see the values extracted from the URL by
restarting ASP.NET Core and requesting any three-segment URL, such as
http://localhost:5000/apples/oranges/cherries, which produces the
response shown in Figure 13-8.

The string "{first}/{second}/{third}" is a URL pattern(route template) which is used to configure how the endpoint is matched.
In your case,"{first}/{second}/{third}"would match url like
https://localhost:7192/a/b/c
https://localhost:7192/1/2/3
but the url like
https://localhost:7192/a/b/c/d
https://localhost:7192/a/b
won't match
And the first segment of url path awould be bound to the {first} parameter,b would be bound to {second} and so on.all of them would be stored in HttpRequest.RouteValues in a key value format:
first:a,
second :b,
thrid :c
The official document related

Related

How to access values from list of maps in Apache camel message body

Perhaps this is easy, but I am somehow not able to crack it yet. Message body for an exchange is basically a list of maps with both key & value being string. As example,
[{'key'='val1'}, {'key'='val2'},...]
I am using simple expression to set this as a property which I would be using in subsequent routes. This is how I am setting it:
.setProperty("myProperty", simple("${body}"))
But this sets the complete body. I just want to (somehow) set only the values part to avoid setting the entire list of maps. What I have tried and not working so far:
.setProperty("myProperty", simple("${body}['key']"))
.setProperty("myProperty", simple("${body}[*]['key']"))
.setProperty("myProperty", simple("${body}[0]['key']")) // this returns only the first value, I want all
Any idea/suggestion how can I achieve this ?
You can access every level of your body with Simple expressions:
${body} // get whole list of maps
${body[0]} // get first map in the list (index 0)
${body[0][key]} // get value of key "key" from the first map in the list
What you cannot do in a Simple expression is a conversion of your data structure in another one.
However, you can simply plug a Java bean into your route
from("direct:start")
...
.bean(MyConversionBean.class)
...;
And do the conversion with Java
public class MyConversionBean {
public List<String> convertBody() {
// extract all values (or whatever) with Java;
return listOfValues;
}
}

grpc-java, available field names for the method:ManagedChannelBuilder.defaultServiceConfig()

Class : ManagedChannelBuilder
Method : defaultServiceConfig(Map<String,?> serviceConfig)
Available field names : MethodConfig, retryPolicy etc...
https://grpc.github.io/grpc-java/javadoc/io/grpc/ManagedChannelBuilder.html#defaultServiceConfig-java.util.Map-
I am trying to create a parameter for the method but cannot find the available field names. I need a list of the field names for the serviceConfig.
Where can I find the list or do I need to look into the source code to find them out?
Service config definition is defined in this proto.
Service config object (Map<String, Object>) is a JSON like representation of the ServiceConfig protobuf. Note that field names in the map should be in lower camel case.

How to replace relationship field type object IDs with names / titles in KeystoneJS list CSV download / export?

In Keystone admin list view the handy download link exports all list items in a CSV file, however, if some of the fields are of Relationship type, the exported CSV contains Mongo ObjectIDs instead of nmeaningful strings (name, title, etc) which would be useful.
How can one force the ObjectIDs to be mapped / replaced by another field?
Keystone has an undocumented feature that allows you to create your own custom CSV export function. This feature was added back in April (see KeystoneJS Issue #278).
All you need to do is add a method to the schema called toCSV. Keystone will inject any of the following dependencies when specified as arguments to this method.
- req (current express request object)
- user (currently authenticated user)
- row (default row data, as generated without custom toCSV())
- callback (invokes async mode, must be provided last)
You could, for example, use the Mongoose Model.Populate method to replace the Object Ids of any relationship field with whatever data you want.
Assume you have a Post list with an author field of Types.Relationship to another list (let's say User) which has a name field. You could replace the author Object Id with the author's name (from the User list) by doing the following.
Post.schema.methods.toCSV = function(callback) {
var post = this,
rtn = this.toJSON();
this.populate('author', function() {
rtn.author = post.author.name; // <-- author now has data from User list
callback(null, rtn);
});
};
.toCSV() will be called for every document returned with the Model as the context. When used asynchronously (as above) you should return a JSON representation of the new CSV data by passing it as the second argument of the callback. When using it synchronously simply return the updated JSON object.

Orchard Search multiple fields with same term

I am trying to create a custom search module based on the Orchard.Search. I have created a custom field called keywords which I have successfully added to the index. I want to match content where the title, body or keywords match. Adding these using .WithField or passing a string array of fields tests for each field matching the term, I need these to return content if there is a match in any of the fields. I have included examples of how I am using both methods below.
Examples of how I am using the search builder:
var searchBuilder = Search()
.WithField("type", "Cell").Mandatory().ExactMatch()
.WithField("body", query)
.WithField("title", query);
.WithField("cell-keywords", query);
String Array FieldNames:
string[] searchFields = new string[2] { "body", "title", "cell-keywords"};
var searchBuilder = Search().WithField("type", "Cell").Mandatory().ExactMatch().Parse(searchFields, query, false);
If anyone could point me in the right direction that would fantastic :)
A colleague wrote an article on this on his blog, should prove helpful http://breakoutdeveloper.com/orchard-cms/creating-an-advanced-search
I have resolved my issue!
The problem was when I was adding my keywords field to the index on the part handler. There were content items with NULL which was causing an error which I missed!!

Should we always validate resource id in url and body in HTTP PUT request?

Suppose I am updating a employee record
url - /api/employees/10
body -
{
id : 10,
name : xyz
}
Should I validate for the employee id in url is same as in response? Because one employee can hit the url himself but update the data of another employee by sending another value in the PUT body.
If you have to validate, it's likely that you want to use POST. A POST is not idempotent and you are supposed to manage the change.
PUT is idempotent, and it just creates a resource. It implies that you don't actually care what id 10 is and whether it is a new id or an existing id. You just replace id 10 with the resource you supply. You only use PUT when you know what the uri should be.
Yes, if the representation of the object in the body contains its own key, you should validate that it matches the key from the URL. It's an error for the client to try to PUT an object at /api/employees/10 that isn't a valid value for employee #10's record, so you should check for that and report it as an error just as you would check that the object has correct syntax.
I believe that the best error code to return in this case is 422 Unprocessable Entity, but I might be wrong about that.
Another thing you can do instead is don't include the key at all in the body. However I find that keeping the key in makes sense for consistency with the way the same type of object is represented in other parts of the API (possibly embedded inside other objects). This is especially true when using XML (although it looks like you are using JSON here).