Kentico Kontent runtime resolution - kentico-kontent

I am having issue with kentico kontent a bit. Basically when I call _deliveryClient.GetItemsAsync<object> I am getting null even though the json below is being brought back.
{
"item": {
"system": {
"id": "0b9e6cf0-a9aa-422b-9e14-1576adfb6324",
"name": "Home",
"codename": "home",
"language": "default",
"type": "home",
"sitemap_locations": [],
"last_modified": "2020-04-30T17:16:48.706142Z"
},
"elements": {
"header": {
"type": "text",
"name": "Header",
"value": "This is my name"
},
"description": {
"type": "text",
"name": "Description",
"value": ".net specialist"
},
"background": {
"type": "modular_content",
"name": "Background",
"value": [
"universe"
]
}
}
},
"modular_content": {
"universe": {
"system": {
"id": "a8898eef-0f4b-4646-af72-c0a1e41ab165",
"name": "Universe",
"codename": "universe",
"language": "default",
"type": "background",
"sitemap_locations": [],
"last_modified": "2020-04-30T17:19:02.9586245Z"
},
"elements": {
"user_vid_or_imag": {
"type": "multiple_choice",
"name": "User Vid or Imag",
"value": [
{
"name": "Video",
"codename": "video"
}
]
},
"background_item": {
"type": "asset",
"name": "Background Item",
"value": [
{
"name": "Time Lapse Video Of Night Sky.mp4",
"description": null,
"type": "video/mp4",
"size": 2076845,
"url": "https://preview-assets-us-01.kc-usercontent.com:443/..."
}
]
}
}
}
}
}
However, if I use the concretion I get the Model back as expected. This is an issue even for members of a class e.g. linked items. The problem is that we have lots of models so we have opted to use the ModelGenerator kentico provides. The thing is we cannot tell the the Generator not to generate some of the objects so it will overwrite everything even though we only want to update one model. So this means I cannot go into every model and change the to some concretion because that will be overwritten.
The documentation says that should always work so is this a bug? or am I making a mistake somewhere.

You should always use the model generator in combination with partial classes. To enable customization via partial classes use the --generatepartials true switch. This will output something like:
Article.Generated.cs (will be always regenerated)
public partial class Article
{
public const string Codename = "article";
public const string TitleCodename = "title";
public const string BodyCopyCodename = "body_copy";
public const string RelatedArticlesCodename = "related_articles";
public string Title { get; set; }
public IRichTextContent BodyCopy { get; set; }
public IEnumerable<object> RelatedArticles { get; set; }
}
Article.cs (will be generated when it doesn't already exist, it will never be overwritten by the generator)
public partial class Article
{
// Space for your customizations
public IEnumerable<Article> ArticlesTyped => RelatedArticles.Cast<Article>();
}
Feel free to suggest improvements for the code generator at https://github.com/Kentico/kontent-generators-net/issues/new/choose
The most probable reason why your code doesn't work at the moment is that you haven't registered the implementation of the ITypeProvider interface. You can do so by adding it to the DI container (IServiceCollection):
services
.AddSingleton<ITypeProvider, CustomTypeProvider>();
.AddDeliveryClient(Configuration);
or by passing it to the DeliveryClientBuilder
CustomTypeProvider customTypeProvider = new CustomTypeProvider();
IDeliveryClient client = DeliveryClientBuilder
.WithProjectId("975bf280-fd91-488c-994c-2f04416e5ee3")
.WithTypeProvider(customTypeProvider)
.Build();
as described in the docs. You can either generate the CustomTypeProvider by the model generator utility or implement it by hand. It should look similar to this:
public class CustomTypeProvider : ITypeProvider
{
private static readonly Dictionary<Type, string> _codenames = new Dictionary<Type, string>
{
// <CLI type, model codename in Kontent>
{typeof(Article), "article"}
};
public Type GetType(string contentType)
{
return _codenames.Keys.FirstOrDefault(type => GetCodename(type).Equals(contentType));
}
public string GetCodename(Type contentType)
{
return _codenames.TryGetValue(contentType, out var codename) ? codename : null;
}
}
Alternatively, you can specify the type when calling GetItemsAsync() in the following way: _deliveryClient.GetItemsAsync<Article>() but this will resolve only the 1st level type. Any nested models will be null because the SDK won't know how to resolve them (that's what the ITypeProvider is for). So I'd avoid this.

Related

aws api gateway model design for dynamic key

I am designing an AWS API gateway request model. In my case the input key will change dynamically like below
[
{
"losAngeles": {
"weatherInCelcius": 84.5
}
},
{
"sanFrancisco": {
"weatherInCelcius": 80
}
}
]
Here the city name(losAngeles,sanFrancisco) will change dynamically
can anyone help me to create API model JSON for this dynamically changing key
I tried like below
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "weather",
"type": "object",
"properties": {
"TBD": {
"type": "string"
}
}
}
json-schema draft-04 has a patternProperties keyword that can be used here. Specifically, you can change your example into this:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "weather",
"type": "object",
"patternProperties": {
".*": {
"type": "string"
}
}
}
The ".*" defines that any name for a property is allowed. If you have more specific constraints, you can change that RegEx accordingly.

How to add x-code-samples for ReDoc with Swashbuckle.AspNetCore?

What's the best way to add x-code-samples for ReDoc to swagger.json through Swashbuckle.AspNetCore.Annotations?
EDIT (March 30, 2019)
I hope this is a better explanation.
There is a way in Swashbuckle.AspNetCore to add content to the generated swagger.json.
What's documented
(Example from GitHub-Page):
[HttpPost]
[SwaggerOperation(
Summary = "Creates a new product",
Description = "Requires admin privileges",
OperationId = "CreateProduct",
Tags = new[] { "Purchase", "Products" }
)]
public IActionResult Create([FromBody]Product product)
About what I try to achieve
What I'd like to do is something like this:
[MyCustomSwaggerOperation(
x-code-samples = [
{
"lang": "CSharp",
"source": "console.log('Hello World');"
},
{
"lang": "php",
"source": ...
}
]
)]
public IActionResult Create([FromBody]Product product)
Here is an IDocumentFilter that injects "x-code-samples" to a parameter
public class InjectSamples : IDocumentFilter
{
public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
{
PathItem path = swaggerDoc.Paths.Where(x => x.Key.Contains("Values")).First().Value;
path.Post.Parameters.FirstOrDefault().Extensions.Add("x-code-samples", "123456");
}
}
Yes you could complicate all this with annotations, but "x-code-samples" is not supported out of the box by Swashbuckle, so you will have to create your own and them use it on the iDocFilter.
In the comments you kept pointing out that IDocumentFilters are added after the swagger document has been generated, Yes we want that!
And the generated swagger.json with that looks like this:
"post": {
"tags": [ "Values" ],
"operationId": "ApiValuesPost",
"consumes": [ "application/json" ],
"produces": [],
"parameters": [
{
"name": "value",
"in": "body",
"required": false,
"schema": { "type": "string" },
"x-code-samples": "123456"
}
],
"responses": {
"200": { "description": "Success" }
}
}

Regular Expressions and Elastic Search

I am trying to retrieve some company results using elasticsearch. I want to get companies that start with "A", then "B", etc. If I just do a pretty typical query with "prefix" like so
GET apple/company/_search
{
"query": {
"prefix": {
"name": "a"
}
},
"fields": [
"id",
"name",
"websiteUrl"
],
"size": 100
}
But this will return Acme as well as Lemur and Associates, so I need to distinguish between A at the beginning of the whole name versus just A at the beginning of a word.
It would seem like regular expressions would come to the rescue here, but elastic search just ignores whatever I try. In tests with other applications, ^[\S]a* should get you anything that starts with A that doesn't have a space in front of it. Elastic search returns 0 results with the following:
GET apple/company/_search
{
"query": {
"regexp": {
"name": "^[\S]a*"
}
},
"fields": [
"id",
"name",
"websiteUrl"
],
"size": 100
}
In FACT, the Sense UI for Elasticsearch will immediately alert you to a "Bad String Syntax Error". That's because even in a query elastic search wants some characters escaped. Nonetheless ^[\\S]a* doesn't work either.
Searching in Elasticsearch is both about the query itself, but also about the modelling of your data so it suits best the query to be used. One cannot simply index whatever and then try to struggle to come up with a query that does something.
The Elasticsearch way for your query is to have the following mapping for that field:
PUT /apple
{
"settings": {
"index": {
"analysis": {
"analyzer": {
"keyword_lowercase": {
"type": "custom",
"tokenizer": "keyword",
"filter": [
"lowercase"
]
}
}
}
}
},
"mappings": {
"company": {
"properties": {
"name": {
"type": "string",
"fields": {
"analyzed_lowercase": {
"type": "string",
"analyzer": "keyword_lowercase"
}
}
}
}
}
}
}
And to use this query:
GET /apple/company/_search
{
"query": {
"prefix": {
"name.analyzed_lowercase": {
"value": "a"
}
}
}
}
or
GET /apple/company/_search
{
"query": {
"query_string": {
"query": "name.analyzed_lowercase:A*"
}
}
}

Navigation from one form to another using Alpacajs

I have one form with one button next. On clicking this next button,it should navigate to other form.
I have created two forms but I am not able to link them.
$("#field1").alpaca({
"schema": {
"title": "Name Info",
"type": "object",
"properties": {
"firstName": {
"title": "First Name",
"type": "string"
},
"lastName": {
"title": "Last Name",
"type": "string"
}
}
},
"options": {
"form": {
"buttons": {
"next": {
"click": function() {}
}
}
}
}
});
Have you tried using the Wizards, I think that might help you. Tell me If this is not what you're looking for, I'll try to help you.
#smileisbest and #Shabbir-Dhangot, I've implemented two forms in the same page. Use the JSON library to serialize the data and send to the next form:
"click" : function() {
var editJsonData = JSON.stringify(this.getValue(), null, " ");
doNext(editJsonData);
}
Then add the call to the next form as a function:
// If JSON data is not null, the next form will display.
var doNext = function(jsonData) {
$("#NextForm").empty();
if (null != jsonData) {
// Validate user or data...
// This starts the Editor form
$("#NextForm").alpaca({
"data" : jsonData,
"schema" : {
"type" : "object",
"properties" : { ...
Use show/hide appropriately to hide the prior form:
$("#field1").hide();
$("#NextForm").show();

AlpacaJS: programmatically change value of TextField after selecting Select

I'm new to AlpacaJS and getting crazy trying to figure out how to do a simple stuff like changing dinamically the content of a text field with the value of a "Select".
The code looks like
$("#form1").alpaca({
"data": {
"name": "Default"
},
"schema": {
"title": "What do you think of Alpaca?",
"type": "object",
"properties": {
"name": {
"type": "string",
"title": "Name"
},
"flavour":{
"type": "select",
"title": "Flavour",
"enum": ["vanilla", "chocolate", "coffee", "strawberry", "mint"]
}
}
},
"options": {
"helper": "Tell us what you think about Alpaca!",
"flavour": {
"type": "select",
"helper": "Select your flavour.",
"optionLabels": ["Vanilla", "Chocolate", "Coffee", "Strawberry", "Mint"]
}
}
},
"postRender": function(control) {
var flavour = control.childrenByPropertyId["flavour"];
var name = control.childrenByPropertyId["name"];
name.subscribe(flavour, function(val) {
alert("Val = " + val);
this.schema.data = val;
this.refresh();
});
}
});
I can see that the function in postRenderer is called (as I can see the alert with relevant value) but (maybe I'm brain dead at this stage) I cannot refresh the text field with that value.
Cheers
I was probably looking at the wrong attribute to be set... After I changed to
this.schema.data = val;
it worked fine :)