How to use POST request to create an object in C# API? - c#

So I'm trying to make this parking ticket system and I'm currently creating these objects manually in the code for testing. Now I've come to the step where my POST request in postman should be able to create an object in the memory of the app. I've got two classes one for a ''Car'' and one for the ''Ticket''.
public class Car
{
public string regNr { get; set; }
public string carBrand { get; set; }
public string carColor { get; set; }
public List<Ticket> ticketlist {get; set;}
public Car()
{
this.ticketlist = new List<Ticket>();
}
public void addNewTicket(Ticket newTicket)
{
ticketlist.Add(newTicket);
}
}
}
public class Ticket
{
public int ticketID { get; set; } = 0;
public DateTime date { get; set; }
public string comment { get; set; }
public int parkingAreaID { get; set; }
public int parkingsOfficerID { get; set; }
}
}
List<Bil> list = new List<Car>();
public void Post([FromBody]Bil val)
{
list.Add(val);
}
The GET requests work and I want to be able to add a new ticket to a registration number by using my post request.
My current output is this;
{
"regNr": "BT66358",
"carBrand": "BMW",
"carColor": "Yellow",
"ticketlist": [
{
"ticketID": 1,
"date": "2020-12-12T17:49:34.4000401+01:00",
"comment": "very bad parking",
"parkingsAreaID": 1,
"parkingsOfficerID": 2
},
{
"ticketID": 2,
"date": "2020-12-12T17:49:34.4000401+01:00",
"comment": "very bad parking",
"parkingsAreaID": 2,
"parkingsOfficerID": 2
}
]
}
---------------UPDATE-----------
Bil = Car
botliste = ticketlist
liste = list
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/q3UaO.png

If I understood you correctly, then most likely you just need to add some attributes, and you get something like this:
List<Car> list = new List<Car>();
[HttpPost]
[HttpPost("SomeRoute")]
public IActionResult Post([FromBody] Car val)
{
if (val == null)
{
return BadRequest("Car data must be filled");
}
if (string.IsNullOrEmpty(val.regNr))
{
return BadRequest("Reg number must be filled");
}
var car = list.FirstOrDefault(c => string.Equals(c.regNr, val.regNr));
if (car != null)
{
car.ticketlist.AddRange(val.ticketlist);
}
else
{
list.Add(val);
}
/// And return IActionResult
return Ok();
}
P.S. Give a description of the Bil type to get a more detailed answer.
upd:
You can also add attributes to the fields of your classes that will validate the values, for example:
...
public class Car
{
[MinLength(6, ErrorMessage = "regNr field must be at least 6 characters")]
public string regNr { get; set; }
...
The "MinLength" attribute indicates that the value for this property is required, and must be at least 6 characters.
More details here: https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations?view=net-5.0
upd2:
This is how I get to invoke this method:

Related

How to print the values not the object IEnumerable<IEnumerable<>()>()

I am trying to display the values of a list which is inside another list, but I am running into issues.
Here is the list containing values that I want to display:
"HotelAvailSideFilterResult": {
"listaServices": [
[
{
"code": "APCO",
"description": "Aptos./Hab. con cocina",
"font": null
},
{
So 2 things:
How do I print the description property using loops or whatever?
How do I query unique values? I tried this but repeat values are returned:
var services = resultado.Hotels.Select(h => h.Features.Distinct());//LISTA DE SERVICIOS
var hotelTypes = resultado.Hotels.Select(h => h.Type.Distinct()).Distinct();//LISTA DE TIPOS DE HOTEL
model resultadoFiltro = new model()
{
listaServices = services.ToList(),
};
Here are my models:
public IEnumerable<IEnumerable<RS.Feature>> listaServices { get; set; }
public partial class Hotel
{
public List<Feature> Features { get; set; }
}
public class Feature
{
[JsonProperty("code")]
public string Code { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("font")]
public string Font { get; set; }
}
Thank you very much
Finally the best way is this:
hotelAvailRS.Hotels.SelectMany(h => h.Features).ToList().GroupBy(f => f.Code).Select(f => f.First()).ToList()
Because you will have what you need and also later you will be able to use the property Code to bind when be required.
Hope it helps!!

Return JSON from API method

I am using ASP.net Core web api (c#) here
I have a JSON string as:
{
"userId":321,
"account":"new
"fname":"Adam",
"lname":"Silver"
"features":[
{
"available":true,
"status":open,
"admin":false
}
]
}
I want to test this data in my angular code so wanted to hardcode this into my API; then I want my API to return this back. What I am finding it hard is how to return this. Shall I return this as a string or need to parse it?
I have this method in my API:
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
return new string[] { "value1", "value2" };
}
Do I need to represent this into string or parse it someway?
Your JSON is invalid. We need to correct it. JSONLint can be helpful for that. I took your JSON and corrected the syntax errors until I got this:
{
"userId": 321,
"account": "new",
"fname": "Adam",
"lname": "Silver",
"features":[
{
"available": true,
"status": "open",
"admin": false
}
]
}
Then I need to generate a C# class structure to represent this JSON. I could manually create it, but the excellent json2csharp.com can generate it for me quickly. I fed this JSON into and received the following classes back:
public class Feature
{
public bool available { get; set; }
public string status { get; set; }
public bool admin { get; set; }
}
public class RootObject
{
public int userId { get; set; }
public string account { get; set; }
public string fname { get; set; }
public string lname { get; set; }
public List<Feature> features { get; set; }
}
I put these class definitions into my application. Then I need to modify my action method to create an instance of this RootObject class (you should change the name to actually match what it's intended for).
[HttpGet]
public ActionResult<RootObject> Get()
{
// Create an instance of our RootObject and set the properties
var myRootObject = new RootObject();
myRootObject.userId = 321;
myRootObject.account = "new";
myRootObject.fname = "Adam";
myRootObject.lname = "Silver";
myRootObject.features = new List<Feature>();
// Create an instance of a feature and set its properties
var feature = new Feature();
feature.available = true;
feature.status = "open";
feature.admin = false;
// Add the new feature to the features collection of our RootObject
myRootObject.features.Add(feature);
// Return the instance of our RootObject
// The framework will handle serializing it to JSON for us
return myRootObject;
}
Note that I changed the signature of your method. I made it no longer accept an IEnumerable because it wasn't clear why you had that. And I changed it to return an ActionResult after checking Microsoft's documentation.
Hi Please find correct JSON format for above one:
{
"userId": 321,
"account": "new",
"fname": "Adam",
"lname": "Silver",
"features": [{
"available": true,
"status": "open",
"admin": false
}]
}
you can use below class in your web API to pass respective data
public class Feature
{
public bool available { get; set; }
public string status { get; set; }
public bool admin { get; set; }
}
public class RootObject
{
public int userId { get; set; }
public string account { get; set; }
public string fname { get; set; }
public string lname { get; set; }
public List<Feature> features { get; set; }
}
then at the end, while returning data, convert the respective class object into JSON by serializing that into JSON format.
Hope it will fulfill your requirement.
Putting the comments into an answer:
If you are using ActionResult, I'll assume you are using asp.net mvc. What you want is JsonResult.
[HttpGet]
public JsonResult Get()
{
return new JsonResult
{
Data = new
{
userId = 321,
account = new
{
fname = "Adam",
lname = "Silver",
features = new object[]{
new
{
available = true,
status = "open",
admin = false
}
}
}
},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}

NEST Api SearchAfter return null in NEST but works in Kibana

We are using elastic search just for document search in our application so we don't have any one expert in it. I was able to use TermQuery, SimpleQueryStringQuery and MatchPhraseQuery successfully. But I found out in documentation that using From & Size for pagination is not good for production and Search After is recommended.
But my implementation return null. It is confusing for me what should be in <Project> parameter as shown in Nest API Object Initializer Syntax in docs here.
My code looks like this:
var request = new SearchRequest<ElasticSearchJsonObject._Source>
{
//Sort = new List<ISort>
//{
// new SortField { Field = Field<ElasticSearchJsonObject>(p=>)}
//},
SearchAfter = new List<object> {
},
Size = 20,
Query = query
};
Reality is I don't understand this. Over here ElasticSearchJsonObject._Source is the class to map returned results.
My documents are simple text documents and I only want documents sorted according to score so document Id is not relevant.
There was already a question like this on SO but I can't find it somehow.
Update
After looking at answer I updated my code and though query obtained does work. It return result in kibana but not in NEST.
This is the new updated code:
var request = new SearchRequest<ElasticSearchJsonObject.Rootobject>
{
Sort = new List<ISort>
{
new SortField { Field = "_id", Order = SortOrder.Descending}
},
SearchAfter = new List<object> {
"0fc3ccb625f5d95b973ce1462b9f7"
},
Size = 1,
Query = query
};
Over here I am using size=1 just for test as well as hard code _id value in SearchAfter.
The query generated by NEST is:
{
"size": 1,
"sort": [
{
"_id": {
"order": "desc"
}
}
],
"search_after": [
"0fc3ccb625f5d95b973ce1462b9f7"
],
"query": {
"match": {
"content": {
"query": "lahore",
"fuzziness": "AUTO",
"prefix_length": 3,
"max_expansions": 10
}
}
}
}
The response from the ES does say successful but no results are returned.
Results do return in Kibana
Query status is successful
But...
Total returned is 0 in NEST
Sort value is null in kibana I used TrackScores = true to solve this issue
Here is the debug information:
Valid NEST response built from a successful low level call on POST: /extract/_source/_search?typed_keys=true
# Audit trail of this API call:
- [1] HealthyResponse: Node: http://localhost:9200/ Took: 00:00:00.1002662
# Request:
{"size":1,"sort":[{"_id":{"order":"desc"}}],"search_after":["0fc3ccb625f5d95b973ce1462b9f7"],"query":{"match":{"content":{"query":"lahore","fuzziness":"AUTO","prefix_length":3,"max_expansions":10}}}}
# Response:
{"took":3,"timed_out":false,"_shards":{"total":5,"successful":5,"skipped":0,"failed":0},"hits":{"total":0,"max_score":null,"hits":[]}}
So please tell me where I am wrong and what can be the problem and how to solve it.
Update 2:
Code in Controller:
Connection String:
var node = new Uri("http://localhost:9200");
var settings = new ConnectionSettings(node);
settings.DisableDirectStreaming();
settings.DefaultIndex("extract");
var client = new ElasticClient(settings);
Query:
var query = (dynamic)null;
query = new MatchQuery
{
Field = "content",
Query = content,
Fuzziness = Fuzziness.Auto,
PrefixLength = 3,
MaxExpansions = 10
};
Query Builder
var request = new SearchRequest<ElasticSearchJsonObject.Rootobject>
{
Sort = new List<ISort>
{
new SortField { Field = "_id", Order = SortOrder.Descending}
},
SearchAfter = new List<object> {
documentid //sent as parameter
},
Size = 1, //for testing 1 other wise 10
TrackScores = true,
Query = query
};
JSON Query
I use this code to get query I posted above. This query is then passed to kibana with GET <my index name>/_Search and there it works
var stream = new System.IO.MemoryStream();
client.SourceSerializer.Serialize(request, stream);
var jsonQuery = System.Text.Encoding.UTF8.GetString(stream.ToArray());
ES Response
string responseJson = "";
ElasticSearchJsonObject.Rootobject response = new ElasticSearchJsonObject.Rootobject();
var res = client.Search<object>(request);
if (res.ApiCall.ResponseBodyInBytes != null)
{
responseJson = System.Text.Encoding.UTF8.GetString(res.ApiCall.ResponseBodyInBytes);
try
{
response = JsonConvert.DeserializeObject<ElasticSearchJsonObject.Rootobject>(responseJson);
}
catch (Exception)
{
var model1 = new LoginSignUpViewModel();
return PartialView("_NoResultPage", model1);
}
}
This is where things go wrong. Above debug information was captured from response
ElasticSearchJsonObject
Some how I think problem might be here somewhere? The class is generated by taking response from NEST in Search request.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ESAPI
{
public class ElasticSearchJsonObject
{
public class Rootobject
{
public int took { get; set; }
public bool timed_out { get; set; }
public _Shards _shards { get; set; }
public Hits hits { get; set; }
}
public class _Shards
{
public int total { get; set; }
public int successful { get; set; }
public int skipped { get; set; }
public int failed { get; set; }
}
public class Hits
{
public int total { get; set; }
public float max_score { get; set; }
public Hit[] hits { get; set; }
}
public class Hit
{
public string _index { get; set; }
public string _type { get; set; }
public string _id { get; set; }
public float _score { get; set; }
public _Source _source { get; set; }
}
public class _Source
{
public string content { get; set; }
public Meta meta { get; set; }
public File file { get; set; }
public Path path { get; set; }
}
public class Meta
{
public string title { get; set; }
public Raw raw { get; set; }
}
public class Raw
{
public string XParsedBy { get; set; }
public string Originator { get; set; }
public string dctitle { get; set; }
public string ContentEncoding { get; set; }
public string ContentTypeHint { get; set; }
public string resourceName { get; set; }
public string ProgId { get; set; }
public string title { get; set; }
public string ContentType { get; set; }
public string Generator { get; set; }
}
public class File
{
public string extension { get; set; }
public string content_type { get; set; }
public DateTime last_modified { get; set; }
public DateTime indexing_date { get; set; }
public int filesize { get; set; }
public string filename { get; set; }
public string url { get; set; }
}
public class Path
{
public string root { get; set; }
public string _virtual { get; set; }
public string real { get; set; }
}
}
}
I am sure this can be used to get response.
Please note that in case of simple search this code works:
so for this query below my code is working:
var request = new SearchRequest
{
From = 0,
Size = 20,
Query = query
};
Using from/size is not recommended for deep pagination because of the amount of documents that need to be fetched from all shards for a deep page, only to be discarded when finally returning an overall ordered result set. This operation is inherent to the distributed nature of Elasticsearch, and is common to many distributed systems in relation to deep pagination.
With search_after, you can paginate forward through documents in a stateless fashion and it requires
the documents returned from the first search response are sorted (documents are sorted by _score by default)
passing the values for the sort fields of the last document in the hits from one search request as the values for "search_after": [] for the next request.
In the Search After Usage documentation, a search request is made with sort on NumberOfCommits descending, then by Name descending. The values to use for each of these sort fields are passed in SearchAfter(...) and are the values of Project.First.NumberOfCommits and Project.First.Name properties, respectively. This tells Elasticsearch to return documents that have values for the sort fields that correspond to the sort constraints for each field, and relate to the values supplied in the request. For example, sort descending on NumberOfCommits with a supplied value of 775 means that Elasticsearch should only consider documents with a value less than 775 (and to do this for all sort fields and supplied values).
If you ever need to dig further into any NEST documentation, click the "EDIT" link on the page:
which will take you to the github repository of the documentation, with the original asciidoc markdown for the page:
Within that page will be a link back to the original NEST source code from which the asciidoc was generated. In this case, the original file is SearchAfterUsageTests.cs in the 6.x branch

System.Linq.Dynamic - No property or field exists in type ICollection

I'm using System.Linq.Dynamic with EntityFramework. My entities are below:
public class Customer
{
public Customer()
{
CustomerInterests = new List<CustomerInterest>();
}
public int Id { get; set; }
public string Name { get; set; }
public ICollection<CustomerInterest> CustomerInterests { get; set; }
}
public class CustomerInterest
{
public int Id { get; set; }
public int CustomerId { get; set; }
public int CourseId { get; set; }
public Course Course { get; set; }
}
public class Course
{
public int Id { get; set; }
public string Name { get; set; }
}
Below is my method:
public dynamic Get(long customerId)
{
var query = DbContext.Customers.Include("CustomerInterests").Include("CustomerInterests.Course").AsQueryable();
return query.Where(filter => filter.Id == customerId).Select("new(id,name,customerInterests)");
}
JSON result:
{
"id": 2003,
"name": "name customer",
"customerInterests": [
{
"customerId": 2003,
"courseId": 2,
"course": null,
"id": 2016
},
{
"customerId": 2003,
"courseId": 3,
"course": null,
"id": 2017
}
]
}
I'm trying to load the property Course, but it's always returning null as you can see in JSON result.
How can I create the selector new(....) to load correctly the property Course. I've already tried new (customerInterests.course) as customerInterests.course without success.
Do not forget that I am trying to navigate Customer (object) -> CustomerInterests (Collection) -> for each item load Course (object).
I would appreciate if you could help me on this matter.
I had faced that before, and my conclusion is: in Lambda extension methods you can load only 1st level of related object.
You can get list of customerInterests but you can't get foreign records for this list.
But you may use LINQ query instead.
var query=from c in DbContext.Customers
from ci in c.CustomerInterests
from co in ci.Courses
where /// your conditions
select new {
id=c.id,
name=c.name,
customerInterests= new {
customerId= ci.customerId,
courseId=ci.courseId ,
courses= new {
Name=co.Name
/// Other Courses attributes
}
}
}
EDITED
If you're using EF7 , you're able to load second level of foreign records by using ThenInclude method
db.Customers.Include( customer => customer.Orders). ThenInclude( order=> order.OrderDetails);

Data from model not passing to view

I have some code that is functioning oddly and was wondering if anyone else hase come across this issue.
I have a view model that collects data from a database via a stored procedure and a vb object (no I do not know vb this is legacy)
When I execute the program the data is collected as expected via the controller. When I debug it I can see all of my parameters populating with information. However when it comes to the view it says that the parameters are null. I have included my code
Models:
public class PersonIncomeViewModel
{
public string IncomeTypeDesc { get; set; }
public string IncomeDesc { get; set; }
public string Income { get; set; }
}
public class PersonIncomeListViewModel
{
public int? PersonId { get; set; }
public List<PersonIncomeListItem> Incomes { get; set; }
public PersonIncomeListViewModel()
{
Incomes = new List<PersonIncomeListItem>();
}
}
public class PersonLookupViewModel : Queue.QueueViewModel
{
public int Action { get; set; }
public bool ShowAdvancedFilters { get; set; }
//Person Search Variables
[Display(Name = #"Search")]
public string SpecialSearch { get; set; }
[Display(Name = #"Person Id")]
public int? PersonId { get; set; }
[Display(Name = #"Full Name")]
public string FullName { get; set; }
[Display(Name = #"SSN")]
public string SSN { get; set; }
public string AddressStatus { get; set; }
public string EmploymentStatus { get; set; }
public PersonIncomeViewModel Income { get; set; }
public List<PersonIncomeListItem> Incomes { get; set; }
public PersonLookupViewModel()
{
Income = new PersonIncomeViewModel();
Incomes = new List<PersonIncomeListItem>();
}
}
Controller:
public ActionResult _Income(int id)
{
var vm = new PersonLookupViewModel();
var personManager = new dtPerson_v10_r1.Manager( ref mobjSecurity);
//var person = personManager.GetPersonObject((int)id, vIncludeIncomes: true);
var person = personManager.GetPersonObject(id, vIncludeIncomes: true);
var look = JsonConvert.SerializeObject(person.Incomes);
foreach (dtPerson_v10_r1.Income income in person.Incomes)
{
if (income.IncomeType_ID == 0)
{
var item = new PersonIncomeListItem
{
IncomeTypeDesc = "Unknown",
IncomeDesc = income.IncomeDesc,
Income = mobjFormat.FormatObjectToCurrencyString(income.Income)
};
vm.Incomes.Add(item);
}
if (income.IncomeType_ID == 1)
{
var item = new PersonIncomeListItem
{
IncomeTypeDesc = "Alimony",
IncomeDesc = income.IncomeDesc,
Income = mobjFormat.FormatObjectToCurrencyString(income.Income)
};
vm.Incomes.Add(item);
}
if (income.IncomeType_ID == 2)
{
var item = new PersonIncomeListItem
{
IncomeTypeDesc = "Child Support",
IncomeDesc = income.IncomeDesc,
Income = mobjFormat.FormatObjectToCurrencyString(income.Income)
};
vm.Incomes.Add(item);
}
}
return PartialView(vm);
}
View:
#using dtDataTools_v10_r1
#using ds_iDMS.Models.Person
#model ds_iDMS.Models.Person.PersonLookupViewModel
#{
var format = new dtDataTools_v10_r1.CustomFormat();
var newInitials = (Model.Income.IncomeTypeDesc.First().ToString() + Model.Income.IncomeDesc.First().ToString() + Model.Income.Income.First().ToString()).ToUpper();
}
using (Html.DSResponsiveRow(numberOfInputs: ExtensionMethods.NumberOfInputs.TwoInputs))
{
using (Html.DSCard(ExtensionMethods.Icon.CustomText, iconInitials: newInitials, color: ExtensionMethods.Colors.PrimaryBlue))
{
<div>#Model.Income.IncomeTypeDesc</div>
<div>#Model.Income.IncomeDesc</div>
<div>#Model.Income.Income</div>
}
}
There are some extensions that we have built but they are irrelevant to the issue
The line that errors out is this one:
var newInitials = (Model.Income.IncomeTypeDesc.First().ToString() + Model.Income.IncomeDesc.First().ToString() + Model.Income.Income.First().ToString()).ToUpper();
Which drives all of the extension methods on the view and as I run the debugger over it all of the parameters read null, however like I said when I run the debugger and check them in the controller they are populated properly.
Sorry about the long post but I wanted to ensure all the detail was there
This is how to pass the Object model to your Partial View
return PartialView("YourViewName", vm);
or using the Views path
return PartialView("~/YourView.cshtml", vm);
EDIT
Try starting your Action Method like this
var vm= new Person();
vm.PersonLookupViewModel = new PersonLookupViewModel();
Problem solved I had issues with some of my vb objects and had the vb person take a look at them and she fixed them.
Thank you for all the help
EDIT
What had to happen is the vb object had to be re-written and my logic was just fine as it was in the beginning. I marked the one response to my question as the answer because had it been in true MVC without vb objects attached to it, that would have worked perfectly

Categories