Spring + Thymeleaf : Getting function argument value from HTML - spring-boot

So I have this function :
public List<Hotels> returnHotels(String city){
//somecode
return hotelsList;
}
That returns a list. I want the city parameter to actually come from the html.
I've created this class for the city
#Controller
public class City {
public City() {
}
public String city;
public String getCity() {
return city;
}
public void setCity(String City) {
city = City;
}
}
But I have no idea how to make city value to come from the HTML file

Related

Web API PUT 400 Bad Request

I have a HttpPut annotated Insert method in a controller and when I want to insert a new dto with it it returns a Bad Request 400 error.
public class BaseDto
{
public int Id { get; set; }
...
}
public class ModelDto : BaseDto
{
public string Name { get; set; }
...
}
[Produces("application/json")]
[Route("api/[controller]")]
public class ExampleController : MyControlle
{
...
[HttpPut]
public IActionResult Insert([FromBody] ModelDto model)
{
_service.Insert(model, _user);
return Ok();
}
}
I tried it with an API client in Edge with this URL:
http://localhost:52073/api/Example
with this JSON:
``
{
"award_Id":1,
"nameOfTheAwardee":"zgghjggf",
"titleOfTheAwardee":"XXX",
"reasonForAwarding":"zzhfhf",
"numberOfDecision":"876",
"yearOfAwarding":"2022"
}
``

Converting entity class to record how can I do it in the right way

I want to convert this class to record
public partial class PathCategory
{
public PathCategory()
{
DocumentPaths = new HashSet<DocumentPath>();
}
public Guid Id { get; set; }
public string Category { get; set; } = null!;
public virtual ICollection<DocumentPath> DocumentPaths { get; set; }
}
so all I do is replace partial class with record to be like this
public record PathCategory
Is that it, or are there any best practices I should follow?
public record PathCategory(Guid Id, string Category = null,ICollection<DocumentPath> DocumentPaths = null);
OR
public record PathCategory(Guid Id, string Category = null,ICollection<DocumentPath> DocumentPaths = documentPaths)
{
readonly ICollection<DocumentPath> documentPaths = new();
}

MassTransit Sub-Class when published is not consumed

I am trying to create Generic Implementation to publish messages with MassTransit.
BasePublisher
public abstract class BasePublisher
{
private readonly IPublishEndpoint publishEndpoint;
public BasePublisher(IPublishEndpoint publishEndpoint)
{
this.publishEndpoint = publishEndpoint;
}
public Task Publish(IntegrationBaseEvent message)
{
return publishEndpoint.Publish(message);
}
}
IntegrationBaseEvent
public class IntegrationBaseEvent
{
public IntegrationBaseEvent(Guid id, string name, DateTime createdDate)
{
Id = id;
Name = name;
CreationDate = createdDate;
}
public IntegrationBaseEvent()
{
Id = Guid.NewGuid();
CreationDate = DateTime.UtcNow;
}
public Guid Id { get; private set; }
public string Name { get; set; }
public DateTime CreationDate { get; private set; }
}
And I've created events using the abstraction IntegrationBaseEvent.
public class BusinessCreatedEvent : IntegrationBaseEvent
{
public Guid BusinessId { get; set; }
public string BusinessName { get; set; }
}
With the interface below, I am trying to publish the message but it not at all consumed
public interface IPublisher
{
Task Publish(IntegrationBaseEvent message);
}
It is consumed only when I create a separate publisher for the inherited event BusinessCreatedEvent something like below
public interface ISubscriptionPublisher
{
Task Publish(BusinessCreatedEvent message);
}
I don't want to create a different publisher and just want to use the abstract publisher like below.
public class BusinessCreatedEventHandler
{
private readonly IPublisher _publisher;
public BusinessCreatedEventHandler(IPublisher publisher)
{
_publisher = publisher;
}
public Task Handle(string id, string name)
{
var message = new BusinessCreatedEvent
{
BusinessId = id,
BusinessName = name
};
_publisher.Publish(message);
return Task.CompletedTask;
}
}
Any ideas to make it generic, please?
MassTransit leverages generics extensively, and limits types to the generic type specified. Since you're specifying the base interface as the generic type in the call to Publish, that base interface type is all that is published.
Your question is similar to the this one, and my answer – and the solution is the same. Convert it to object and use the Publish(object message) overload instead. That way, MassTransit will use the object type (MassTransit will call message.GetType() and properly dispatch the message type.
Or, you could make your interface include a generic method as well:
public interface IPublisher
{
Task Publish<T>(T message)
where T : class, IntegrationBaseEvent;
}

Url syntax with List property on complex type

Model:
[DataContract]
public class Employee
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
[DataMember(Name ="id")]
public int Id{ get; set; }
[DataMember(Name = "fullName")]
public string FullName { get; set; }
}
[DataContract]
public class Department
{
public Department()
{
this.Employees = new List<Employee>();
}
[DatabaseGenerated(DatabaseGeneratedOption.None)]
[DataMember(Name = "id")]
public int Id { get; set; }
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "employees")]
public List<Employee> Employees { get; set; }
}
Controller
public HttpResponseMessage Get([FromUri]Department model)
{
if (ModelState.IsValid)
{
}
return new HttpResponseMessage(HttpStatusCode.OK);
}
Url : "http://localhost:2070/home/get/?id=1&name=IT&Employees=1,John"
I am trying to invoke above URL and the Model does not read the Employees. Other property like int,double,string,decimal are read by the Model.
Can anyone help me on what is the correct format in passing List thru Url.
Also, I dont want to decorate each of my class with modelbinders nor the parameter in my controller.
Tech : WebApi, .Net3.5
You need to specify the index of the list and property to bind with when using FromUri and list/array
Try it this way
http://localhost:2070/home/get/?id=1&name=IT&Employees[0].Id=1&Employees[0].Name=John

AutoMapper strings to enum descriptions

Given the requirement:
Take an object graph, set all enum type properties based on the processed value of a second string property. Convention dictates that the name of the source string property will be that of the enum property with a postfix of "Raw".
By processed we mean we'll need to strip specified characters e.t.c.
I've looked at custom formatters, value resolvers and type converters, none of which seems like a solution for this?
We want to use AutoMapper as opposed to our own reflection routine for two reasons, a) it's used extensively throughout the rest of the project and b) it gives you recursive traversal ootb.
-- Example --
Given the (simple) structure below, and this:
var tmp = new SimpleClass
{
CountryRaw = "United States",
Person = new Person { GenderRaw="Male" }
};
var tmp2 = new SimpleClass();
Mapper.Map(tmp, tmp2);
we'd expect tmp2's MappedCountry enum to be Country.UnitedStates and the Person property to have a gender of Gender.Male.
public class SimpleClass1
{
public string CountryRaw {get;set;}
public Country MappedCountry {get;set;}
public Person Person {get;set;}
}
public class Person
{
public string GenderRaw {get;set;}
public Gender Gender {get;set;}
public string Surname {get;set;}
}
public enum Country
{
UnitedStates = 1,
NewZealand = 2
}
public enum Gender
{
Male,
Female,
Unknown
}
Thanks
I did it with the ValueInjecter,
here is the whole thing:
I've added one more prop to the SimpleClass just to show you how it works
public class SixFootUnderTest
{
[Test]
public void Test()
{
var o = new SimpleClass1
{
CountryRaw = "United States",
GenderRaw = "Female",
Person = new Person { GenderRaw = "Male" }
};
var oo = new SimpleClass1();
oo.InjectFrom(o)
.InjectFrom<StrRawToEnum>(o);
oo.Person.InjectFrom<StrRawToEnum>(o.Person);
oo.Country.IsEqualTo(Country.UnitedStates);
oo.Gender.IsEqualTo(Gender.Female);
oo.Person.Gender.IsEqualTo(Gender.Male);
}
public class SimpleClass1
{
public string CountryRaw { get; set; }
public Country Country { get; set; }
public string GenderRaw { get; set; }
public Gender Gender { get; set; }
public Person Person { get; set; }
}
public class Person
{
public string GenderRaw { get; set; }
public Gender Gender { get; set; }
public string Surname { get; set; }
}
public class StrRawToEnum : LoopValueInjection
{
protected override bool UseSourceProp(string sourcePropName)
{
return sourcePropName.EndsWith("Raw");
}
protected override string TargetPropName(string sourcePropName)
{
return sourcePropName.RemoveSuffix("Raw");
}
protected override bool TypesMatch(Type sourceType, Type targetType)
{
return sourceType == typeof(string) && targetType.IsEnum;
}
protected override object SetValue(object sourcePropertyValue)
{
return Enum.Parse(TargetPropType, sourcePropertyValue.ToString().Replace(" ", ""), true);
}
}
public enum Country
{
UnitedStates = 1,
NewZealand = 2
}
public enum Gender
{
Male,
Female,
Unknown
}
}
also in case you need to do it from CountryRaw to MappedCountry
you could do it like this:
oo.InjectFrom(new StrRawToEnum().TargetPrefix("Mapped"), o);

Resources