I'm using IConfiguration.GetSection to retrieve configuration information from a config file:
var loggingProviders = Config.GetSection( "Logging" ).Get<LoggingProviders>();
which works just fine, but I want to only retrieve entries that are enabled, so I want to do either of these:
var loggingProviders = Config.GetSection( "Logging" ).Get<LoggingProviders>().Where( x => x.Enabled == true );
var loggingProviders = Config.GetSection( "Logging" ).Where( x => x.Enabled == true ).Get<LoggingProviders>();
But I keep getting hitting a dead end, any advice would be appreciated!
If you want to use .Where,it needs to be a list,here is a demo:
public class LoggingProviders
{
public int Id { get; set; }
public bool Enabled { get; set; }
}
appsettings.json:
"Logging1": [
{
"Id": "1",
"Enabled": "true"
},
{
"Id": "2",
"Enabled": "true"
},
{
"Id": "3",
"Enabled": "false"
}
]
startup:
public IConfiguration Configuration { get; }
...
List<LoggingProviders> loggingProviders = Configuration.GetSection("Logging1").Get<List<LoggingProviders>>().Where(x => x.Enabled == true).ToList();
result:
If you don't get a list,and want to use .where,you can try to change it to list first.Here is a demo.
appsettings.json:
"Logging1":
{
"Id": "1",
"Enabled": "true"
},
startup:
public IConfiguration Configuration { get; }
...
List<LoggingProviders> l= new List<LoggingProviders>();
l.Add(Configuration.GetSection("Logging1").Get<LoggingProviders>());
List<LoggingProviders> loggingProviders = l.Where(x => x.Enabled == true).ToList();
result:
Related
I am trying to use datatables.js in my .NET 5 Web App. When I go to run the app in Visual Studio (IIS) I get a 500 error Incorrect Content-Type. I followed the video found here: https://www.youtube.com/watch?v=NITZdsE5Keg There were no comments on the video. I have tried troubleshooting but I have not been able to figure out what is wrong with my controller and why it is throwing this error:
System.InvalidOperationException: Incorrect Content-Type:
at Microsoft.AspNetCore.Http.Features.FormFeature.ReadForm()
at Microsoft.AspNetCore.Http.DefaultHttpRequest.get_Form()
at DatatableSample.Controllers.StudentController.GetStudents() in C:\path\DatatableSample\DatatableSample\Controllers\StudentController.cs:line 30
Here is my Controller:
{
[Route("api/[controller]")]
[ApiController]
public class StudentController : ControllerBase
{
private readonly ApplicationDbContext context;
public StudentController(ApplicationDbContext context)
{
this.context = context;
}
[HttpPost]
public IActionResult GetStudents()
{
try
{
var draw = Request.Form["draw"].FirstOrDefault();
var start = Request.Form["start"].FirstOrDefault();
var length = Request.Form["length"].FirstOrDefault();
var sortColumn = Request.Form["columns[" + Request.Form["order[0][column]"].FirstOrDefault() + "][name]"].FirstOrDefault();
var sortColumnDirection = Request.Form["order[0][dir]"].FirstOrDefault();
var searchValue = Request.Form["search[value]"].FirstOrDefault();
int pageSize = length != null ? Convert.ToInt32(length) : 0;
int skip = start != null ? Convert.ToInt32(start) : 0;
int recordsTotal = 0;
var customerData = (from tempstudent in context.Students select tempstudent);
if(!string.IsNullOrEmpty(sortColumn) && string.IsNullOrEmpty(sortColumnDirection))
{
customerData = customerData.OrderBy(sortColumn + "" + sortColumnDirection);
}
if(!string.IsNullOrEmpty(searchValue))
{
customerData = customerData.Where(m => m.FirstName.Contains(searchValue) || m.LastName.Contains(searchValue) || m.Email.Contains(searchValue));
}
recordsTotal = customerData.Count();
var data = customerData.Skip(skip).Take(pageSize).ToList();
var jsonData = new { draw = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = data};
return Ok(jsonData);
}
catch (Exception)
{
throw;
}
}
}
}
Here is my JS file for the datatable:
$(document).ready(function () {
$("#studentDatatable").DataTable({
"processing": true,
"severSide": true,
"filter": true,
"ajax": {
"url": "/api/student",
"type": "POST",
"datatype": "json"
},
"columnDefs": [{
"targets": [0],
"visable": false,
"searchable": false
}],
"columns": [
{ "data": "Id", "name": "Id", "autoWidth": true },
{ "data": "FirstName", "name": "First Name", "autoWidth": true },
{ "data": "LastName", "name": "Last Name", "autoWidth": true },
{ "data": "Email", "name": "Email", "autoWidth": true }
]
}); });
Here is what I have in StartUp.cs to add the database:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"), b => b.MigrationsAssembly(typeof(ApplicationDbContext).Assembly.FullName)));
services.AddControllers();
services.AddRazorPages();
}
Any help or suggestions is appreciated. I am really at a loss as to what is happening.
I am trying to replicate this DSL query in NEST. Basically a structured filter that will return all of the products that have the color red.
{
"query": {
"bool": {
"filter": [
{
"nested": {
"path": "keywordFacets",
"query": {
"bool": {
"filter": [
{ "term": { "keywordFacets.name": "color" } },
{ "term": { "keywordFacets.value": "Red" } }
]
}
}
}
}
]
}
}
}
Here is the POCO with attribute mapping.
[ElasticsearchType]
public class Product
{
[Keyword]
public long ProductId { get; set; }
[Nested]
public List<KeywordFacet> KeywordFacets { get; set; }
// other properties...
}
[ElasticsearchType]
public class KeywordFacet
{
[Keyword]
public string Name { get; set; }
[Keyword]
public string Value { get; set; }
}
I can't figure out how to get the two terms inside the nested filter array. This is my failed attempt so far:
var searchRequest = new SearchDescriptor<Product>()
.Query(q => q
.Bool(b => b
.Filter(bf => bf
.Nested(nq => nq
.Path(nqp => nqp.KeywordFacets)
.Query(qq => qq
.Bool(bb => bb
.Filter(ff => ff
.Term(t => t
.Field(p => p.KeywordFacets.First().Name)
.Value("color")
.Field(p2 => p2.KeywordFacets.First().Value).Value("Red")))))))));
Here is some sample data that is returned when I run the DSL query in Postman:
{
"productId": 183150,
"keywordFacets": [
{
"name": "color",
"value": "Red"
},
{
"name": "color",
"value": "Blue"
},
{
"name": "color",
"value": "Grey"
}
]
}
Here's the proper syntax after fumbling around for a while.
var searchRequest = new SearchDescriptor<Product>()
.Query(q => q
.Bool(b => b
.Filter(bf => bf
.Nested(nq => nq
.Path(nqp => nqp.KeywordFacets)
.Query(qq => qq.Bool(bb => bb
.Filter(ff => ff
.Term(t => t
.Field(p => p.KeywordFacets[0].Name).Value("color"))))
&& qq.Bool(bb => bb
.Filter(ff => ff
.Term(t => t
.Field(p2 => p2.KeywordFacets[0].Value).Value("Red"))))
)
)
)
)
);
I have serverside pagination datatable with defination below, it works fine but the thing is;one of the field contains too long so I need to set a details button instead of it, when its clicked pop up showns up and view the data of descripotion.
I tried add success:function(aaData){..} to ajax but it brokes the datatable any suggestion? and I dont want to edit tho model in controller I have data in browser so I want to handle this here..
$(document).ready(function () {
var table = $('#dtBooks').DataTable({
"processing": true,
"serverSide": true,
"filter": false,
"orderMulti": false,
"ajax": {
"url": "#Url.Action("GetBooks", "Home")",
"type": "POST",
"datatype": "json"
},
"columns": [
{ "data": "Title", "name": "Title", "autoWidth": true },
{ "data": "Publisher", "name": "Publisher", "autoWidth": true },
{ "data": "Description", "name": "Description", "autoWidth": true },
{ "data": "Authors", "name": "Authors", "autoWidth": true },
]
});
});
here is the model defination contorller response list of this model to datatable.
public class Book
{
public string Title { get; set; }
public string Publisher { get; set; }
public string Description { get; set; }
public string[] Authors { get; set; }
}
You can use ajax.dataSrc option to manipulate the data returned from the server.
For example:
$('#example').DataTable( {
"ajax": {
"url": "data.json",
"dataSrc": function ( json ) {
for ( var i=0, ien=json.data.length ; i<ien ; i++ ) {
json.data[i][0] = '<a href="/message/'+json.data[i][0]+'>View message</a>';
}
return json.data;
}
}
});
I am using JsonPatchDocument to update my entities, this works well if the JSON looks like the following
[
{ "op": "replace", "path": "/leadStatus", "value": "2" },
]
When i create the object it converts it with the Operations node
var patchDoc = new JsonPatchDocument<LeadTransDetail>();
patchDoc.Replace("leadStatus", statusId);
{
"Operations": [
{
"value": 2,
"path": "/leadStatus",
"op": "replace",
"from": "string"
}
]
}
if the JSON object looks like that the Patch does not work. I believe that i need to convert it using
public static void ConfigureApis(HttpConfiguration config)
{
config.Formatters.Add(new JsonPatchFormatter());
}
And that should sort it out, the problem is i am using .net core so not 100% sure where to add the JsonPatchFormatter
I created the following sample controller using the version 1.0 of ASP.NET Core. If I send your JSON-Patch-Request
[
{ "op": "replace", "path": "/leadStatus", "value": "2" },
]
then after calling ApplyTo the property leadStatus will be changed. No need to configure JsonPatchFormatter. A good blog post by Ben Foster helped me a lot in gaining a more solid understanding - http://benfoster.io/blog/aspnet-core-json-patch-partial-api-updates
public class PatchController : Controller
{
[HttpPatch]
public IActionResult Patch([FromBody] JsonPatchDocument<LeadTransDetail> patchDocument)
{
if (!ModelState.IsValid)
{
return new BadRequestObjectResult(ModelState);
}
var leadTransDetail = new LeadTransDetail
{
LeadStatus = 5
};
patchDocument.ApplyTo(leadTransDetail, ModelState);
if (!ModelState.IsValid)
{
return new BadRequestObjectResult(ModelState);
}
return Ok(leadTransDetail);
}
}
public class LeadTransDetail
{
public int LeadStatus { get; set; }
}
Hope this helps.
This question regards querying nested dictionaries.
I have a case which can be simplified into the following setup with a style containing a list of SKUs containing a list of Collis.
CLASS DEFINITIONS:
public class Style
{
public string Name { get; set; }
public Dictionary<string, Sku> Skus = new Dictionary<string, Sku>();
}
public class Sku
{
public string Name { get; set; }
public Dictionary<string, Colli> Collis = new Dictionary<string, Colli>();
}
public class Colli
{
public string Name { get; set; }
}
JSON DATA IN RAVEN DB:
{
"Skus": {
"Sku1": {
"Collis": {
"Right": {
"Name": "Right"
},
"Right again": {
"Name": "Right again"
},
"Wrong": {
"Name": "Wrong"
}
},
"Name": "Sku1"
},
"Sku2": {
"Collis": {
"Wrong 1": {
"Name": "Wrong 1"
},
"Wrong 2": {
"Name": "Wrong 2"
},
"Wrong 3": {
"Name": "Wrong 3"
}
},
"Name": "Sku2"
}
},
"Name": "Style1"
}
VALID QUERIES:
(Ask for style with skus of specific names)
var existingStyleWithSku1 = session.Query<Style>().Where(s => s.Skus["Sku1"] != null).ToList();
var nonexistingStyleWithSku4 = session.Query<Style>().Where(s => s.Skus["Sku4"] != null).ToList();
INVALID NESTED QUERY
(Ask for style containing a sku named "Sku1" that contains a colli named "Right")
var styleWithSpecificColli = session.Query<Style>().Where(s => s.Skus["Sku1"].Collis["Right"] != null).ToList();
When i attempt to execute the last query, I get the message:
{ "Url":
"/indexes/dynamic/Styles?query=-Skus.get_Item(%2522Sku1%2522).Collis.Right%253A%255B%255BNULL_VALUE%255D%255D%2520AND%2520Skus.get_Item(%2522Sku1%2522).Collis.Right%253A*&start=0&pageSize=128&aggregation=None",
"Error": "System.ArgumentException: The field ')CollisRight' is not
indexed, cannot query on fields that are not indexed\r\n at
Raven.Database.Indexing.Index.IndexQueryOperation.AssertQueryDoesNotContainFieldsThatAreNotIndexes()
in c:\Builds\raven\Raven.Database\Indexing\Index.cs:line 628\r\n
at
Raven.Database.Indexing.Index.IndexQueryOperation.d__1c.MoveNext()
in c:\Builds\raven\Raven.Database\Indexing\Index.cs:line 542\r\n
at
System.Linq.Enumerable.WhereSelectEnumerableIterator2.MoveNext()\r\n
at
System.Linq.Enumerable.WhereSelectEnumerableIterator2.MoveNext()\r\n
at System.Collections.Generic.List1.InsertRange(Int32 index,
IEnumerable1 collection)\r\n at
........
Is there a way that I can be able to execute the last query? Maybe defining what to index in RavenDB?
Thankyou in advance.
I posted the example above as failing test, but synhershko corrected my code in order to make it work.
It is actually possible to do this. The query just looks like this instead:
WRONG:
var styleWithSpecificColli = session.Query<Style>()
.Where(s => s.Skus["Sku1"].Collis["Right"] != null)
.ToList();
RIGHT:
var styleWithSpecificColli = session.Query<Style>()
.Select(s => s.Skus["Sku1"])
.Where(c => c.Collis["Right"] != null)
.ToList();