Swashbucke Date example showing time component/wrong format - swagger

We specify an input property with an example value as such
/// <summary>
/// Start date in format YYYY-MM-DD
/// </summary>
/// <example>2020-05-31</example>
[DataType(DataType.Date)]
public DateTime? From { get; set; }
And produces the following json
{
"name": "from",
"in": "query",
"description": "Start date in format YYYY-MM-DD",
"schema": {
"type": "string",
"description": "Start date in format YYYY-MM-DD",
"format": "date",
"nullable": true,
"example": "31/05/2020 12:00:00 AM"
}
}
it looks like the example is not respecting the swagger date format which is: full-date of format YYYY-MM-DD
The setup code I used:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSwaggerGen(swaggerGenOption =>
{
swaggerGenOption.SwaggerDoc("v1", new OpenApiInfo { Title = "API", Version = "v1" });
swaggerGenOption.IncludeXmlComments(XmlDocPath<Startup>());
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
app.UseSwagger();
app.UseSwaggerUI(config =>
{
config.RoutePrefix = string.Empty
config.SwaggerEndpoint("./swagger/v1/swagger.json", "TST");
});
app.UseEndpoints(endpoints => endpoints.MapControllers());
}

Related

How to stop .net core 6 webapp with Odata query from inlining dictionary?

I have a rather simple(for now) Odata controller that does not work in the way I expect.
Backend store is a Mongo database, but I don't think that is relevant.
Model class:
public class EventModel
{
[Key]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
public string EventName { get; set; }
public DateTime EventTime { get; set; }
// Fields omitted to shorten sample
public IDictionary<string,object?> Data { get; set; }
}
OData controller is added like so:
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<Repository.Model.EventModel>("Events");
services.AddControllers()
.AddOData(options => options
.Select()
.Filter()
.OrderBy()
.Expand()
.Count()
.SetMaxTop(null)
.AddRouteComponents("eventservice/odata", builder.GetEdmModel()));
And this is the controller:
public class EventODataController : ODataController
{
private readonly IEventRepository _repository;
public EventODataController(IEventRepository repository)
{
_repository = repository;
}
[HttpGet("eventservice/odata/Events")]
[EnableQuery]
public ActionResult Get()
{
var data = _repository.GetAsQueryable();
return Ok(data);
}
Expected result when doing a HTTP get to eventservice/odata/Events$top=100 should be along the lines of this:
{
"#odata.context": "http://127.0.0.1:7125/eventservice/odata/$metadata#Events",
"#odata.count": 1080302,
"value": [
{
"Id": "63dbbcc9920829279f559025",
"EventName": "Asset",
"EventTime": "2022-09-27T09:14:15.398+02:00",
// Omitted field data here
"Data": {
"Data1":"Foo",
"Data2":"Bar",
"SomeMore":4
}
}
But it turns out that OData somehow flattens/inlines the dictionary, so the result is this:
"#odata.context": "http://127.0.0.1:7125/eventservice/odata/$metadata#Events",
"#odata.count": 1080302,
"value": [
{
"Id": "63dbbcc9920829279f559025",
"EventName": "Asset",
"EventTime": "2022-09-27T09:14:15.398+02:00",
"AssetId#odata.type": "#Int64",
"AssetId": 1258,
"UniqueCode": "9404120007",
"DbId#odata.type": "#Int64",
"DbId": 1038118,
"SomeData": "ABC",
"MoreData": "108",
"AreaName": "Area51,
...
},
Simple question: How do I stop OData from behaving like this, and do what I expect?

index percolate queries using spring data jpa

Here is my Dto for percolator query class.
#Data
#Document(indexName = "#{#es.indexName}")
#Builder(builderClassName = "RuleBuilder")
public class Rule {
#Id
private String id = UUID.randomUUID().toString();
private QueryBuilder query;
private RuleDataDto data;
public static class RuleBuilder {
private String id = UUID.randomUUID().toString();
}
}
Index Mapping
{
"mappings": {
"properties": {
"query": {
"type": "percolator"
},
"data": {
"properties": {
"subType": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"type": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
}
}
},
"content": {
"type": "text"
}
}
}
}
based on criteria I am generating queries and trying to index those to percolator. but getting below exception
query malformed, no start_object after query name
what should be the query field Type? can someone help me on this
You are trying to store an Elasticsearch object (QueryBuilder) in Elasticsearch without specifying the mapping type.
You will need to annotate your query property as percolator type and might change the type of your property to a String:
#Document(indexName = "#{#es.indexName}")
public class Rule {
#Id
private String _id;
#Field(type = FieldType.Percolator)
private String query;
// ...
}
Or, if you want to have some other class for the query property you'll need a custom converter that will convert your object into a valid JSON query - see the documentation for the percolator mapping.

System.ArgumentNullException: 'Value cannot be null. (Parameter 'connectionString')'

This is the appsetting.json file
{
"Connection Strings": {
"EmployeeDBConnection": "server=(localhost)\\SQLEXPRESS ; database=EmployeeDB; Trusted_Connection =true"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"MyKey": "Value of MYKey from appsettings.json"
}
This is the startup.cs file
namespace EmployeeManagement
{
public class Startup
{
private IConfiguration _config;
public Startup(IConfiguration config)
{
_config = config;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IEmployeeRepository, SQLEmployeeRepository>();
services.AddControllersWithViews();
services.AddDbContextPool<AppDbContext>(options => options.UseSqlServer(_config.GetConnectionString("EmployeeDBConnection")));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseStaticFiles();
app.UseMvcWithDefaultRoute();
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World");
});
}
}
}
I have checked that "Connection Strings" has s in the end,
Changed the placement of the connection strings in the appsetting.json file
Instead of just writing the name of the connection string in Configuration.GetConnectionString() in Startup.cs, I put the entire ConnectionString there
I am still having this error.
Your key "Connection Strings" contains space. Change to "ConnectionStrings" for the intended behavior.
"Connection Strings" does not match your parameter "connectionStrings". You need to change that in appsettings.cs. It could also need to be "connectionString" instead, I am a bit confused by your wording. Regardless, your program is looking for "connectionString", not "Connection Strings".

APIs not getting detected by swagger on a Spring ROO project

I have tried a lot of things but APIs are not getting detected by swagger for some reason. Do i have to specify a package for swagger to scan? or some url include patterns?
My Swager Config :
#Configuration
#EnableSwagger
#EnableWebMvc
public class SwaggerConfiguration {
private final Logger log = LoggerFactory
.getLogger(SwaggerConfiguration.class);
/**
* Swagger Spring MVC configuration.
*/
#Bean
public SwaggerSpringMvcPlugin swaggerSpringMvcPlugin(
SpringSwaggerConfig springSwaggerConfig) {
log.debug("Starting Swagger");
StopWatch watch = new StopWatch();
watch.start();
SwaggerSpringMvcPlugin swaggerSpringMvcPlugin = new SwaggerSpringMvcPlugin(
springSwaggerConfig).apiInfo(apiInfo())
.genericModelSubstitutes(ResponseEntity.class);
swaggerSpringMvcPlugin.build();
watch.stop();
log.debug("Started Swagger in {} ms", watch.getTotalTimeMillis());
return swaggerSpringMvcPlugin;
}
/**
* API Info as it appears on the swagger-ui page.
*/
private ApiInfo apiInfo() {
return new ApiInfo("Title", "Description", "terms of service",
"contact", "license", "licenseUrl");
}
}
Sample Controller
#RequestMapping("/settings")
#Controller
#Api(value = "/settings", description = "Endpoint for settings management")
public class SettingsController {
#ApiOperation(value = "API Operation")
#RequestMapping(value = "/changepassword", method = RequestMethod.POST)
public #ResponseBody Map<String, Object> changePassword(#RequestParam Map<String, String> userProperties,
Model model, HttpServletRequest httpServletRequest, Locale locale) {
Map<String, Object> responseMap = new HashMap<String, Object>();
return responseMap;
}
}
I get an empty response
{
"apiVersion": "1.0",
"swaggerVersion": "1.2",
"apis": [ ],
"authorizations": [ ],
"info":
{
"title": "Title",
"description": "Description",
"termsOfServiceUrl": "terms of service",
"contact": "contact",
"license": "license",
"licenseUrl": "licenseUrl"
}
}
I am using swagger-springmvc version 1.0.2 and spring version 4.1.6.RELEASE
Follow the instructions in the following URL :
http://naddame.blogspot.in/2014/12/spring-roo-mvc-integration-for-swagger.html

How to parse a json in MVC view

I am getting the values of some datatypes in umbraco to my MVC view in cshtml I am getting a result in JSON how will I parse the JSON to bind it to a drop down list. What are the possible methods to do this. I have installed NetonSoft JSON in project also
if (home.GetProperty("residentsLogin") != null && !string.IsNullOrEmpty(home.GetPropertyValue("residentsLogin")))
{
var residentslog = home.GetPropertyValue("residentsLogin");
}
My JSON is in the corresponding format
[
{
"name": "Property1",
"url": "http://www.google.com",
"target": "_blank",
"icon": "icon-link"
},
{
"name": "Property2",
"url": "http://www.google.com",
"target": "_blank",
"icon": "icon-link"
}
]
Working code should look like this:
public class MyJsonObject
{
public string name{get;set;}
public string url { get; set; }
public string target { get; set; }
public string icon { get; set; }
}
var residentslog = #"[
{
'name': 'Property1',
'url': 'http://www.google.com',
'target': '_blank',
'icon': 'icon-link'
},
{
'name': 'Property2',
'url': 'http://www.google.com',
'target': '_blank',
'icon': 'icon-link'
}
]";
List<MyJsonObject> myJsonObjectList = JsonConvert.DeserializeObject<List<MyJsonObject>>(residentslog);
ViewBag.MySelectList = new SelectList(myJsonObjectList, "name", "url");

Resources