Convert to nested pojo class using inner class - jackson

My Json:
[
{
"accountId": "1005003805",
"status": "1000",
"internalStatus": "ACTIVE",
"associations": [
{
"id": "1000004114",
"type": "reseller"
}
],
"preferredLanguage": "it-IT",
"address": {
"country": "IT",
"phoneNumber": "408-536-3538",
"city": "SESTO FIORENTINO",
"postalCode": "50019",
"addressLine1": "345 Park Ave",
"addressLine2": "VIA DONINZETTI 17",
"region": "32"
},
"name": "UPLOAD DI RICCI LUCA E PROCELLI SNC anil",
"type": "customer",
"externalReferenceId": "Su66353456234",
"contacts": [
{
"firstName": "su",
"lastName": "ku",
"phoneNumber": "408-536-3538",
"type": "ADMIN",
"email": "dis+testingapi#adobetest.com",
"adminId": "6436457474D"
}
],
"createdDate": "2019-11-08T13:54:30.000+0000",
"statusReason": "Account is activated",
"accountCode": "21",
"tenantId": "5tetewt3532",
"cotermDate": ""
},
{
"accountId": "1000004114",
"status": "1000",
"internalStatus": "ACTIVE",
"associations": [
{
"id": "1655325",
"type": "distributor"
}
],
"preferredLanguage": "it-IT",
"address": {
"country": "IT",
"phoneNumber": "",
"city": "San Giuliano",
"postalCode": "20098",
"addressLine1": "Via L. Tolstoi 65",
"addressLine2": "",
"region": "47"
},
"name": "Ad6745e53262362",
"type": "reseller",
"externalReferenceId": "re634le75358932",
"contacts": [
{
"firstName": "Abc",
"lastName": "An",
"phoneNumber": "408-536-3538",
"type": "ADMIN",
"email": "a#adobe.com",
"adminId": ""
}
],
"createdDate": "2019-11-08T06:35:58.000+0000",
"statusReason": "Account is activated",
"accountCode": "11",
"tenantId": "",
"cotermDate": ""
},
{
"accountId": "16364649",
"status": "1000",
"internalStatus": "ACTIVE",
"associations": [],
"preferredLanguage": "en-US",
"address": {
"country": "IT",
"phoneNumber": "",
"city": "San Giuliano",
"postalCode": "20098",
"addressLine1": "Via L. Tolstoi 65",
"addressLine2": "",
"region": "47"
},
"name": "Stage Tech Data Italy",
"type": "distributor",
"externalReferenceId": "invalid",
"contacts": [
{
"firstName": "arr",
"lastName": "dummy",
"phoneNumber": "",
"type": "ADMIN",
"email": "aty+vmp8#adobetest.com",
"adminId": ""
}
],
"statusReason": "Manually created for testing",
"accountCode": "01",
"tenantId": "6456",
"cotermDate": ""
}
]
package adobe_Partner_Api_ECCS_PojoClasses;
import java.util.ArrayList;
import com.fasterxml.jackson.annotation.JsonFormat;
#JsonFormat(shape = JsonFormat.Shape.ARRAY)
public class ECCSGetExtraCustomer {
private String accountId;
private String status;
private String internalStatus;
private String statusReason;
private String externalReferenceId;
private String tenantId;
private String type;
private String name;
private String marketSegment;
private String preferredLanguage;
private String cotermDate;
private String creationDate;
private Address address;
private ArrayList<Contacts> contacts;
private ArrayList<Associations> associations;
public ArrayList<Contacts> getContacts() {
return contacts;
}
public void setContacts(ArrayList<Contacts> contacts) {
this.contacts = contacts;
}
public ArrayList<Associations> getAssociations() {
return associations;
}
public void setAssociations(ArrayList<Associations> associations) {
this.associations = associations;
}
public String getAccountId() {
return accountId;
}
public void setAccountId(String accountId) {
this.accountId = accountId;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getInternalStatus() {
return internalStatus;
}
public void setInternalStatus(String internalStatus) {
this.internalStatus = internalStatus;
}
public String getStatusReason() {
return statusReason;
}
public void setStatusReason(String statusReason) {
this.statusReason = statusReason;
}
public String getExternalReferenceId() {
return externalReferenceId;
}
public void setExternalReferenceId(String externalReferenceId) {
this.externalReferenceId = externalReferenceId;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMarketSegment() {
return marketSegment;
}
public void setMarketSegment(String marketSegment) {
this.marketSegment = marketSegment;
}
public String getPreferredLanguage() {
return preferredLanguage;
}
public void setPreferredLanguage(String preferredLanguage) {
this.preferredLanguage = preferredLanguage;
}
public String getCotermDate() {
return cotermDate;
}
public void setCotermDate(String cotermDate) {
this.cotermDate = cotermDate;
}
public String getCreationDate() {
return creationDate;
}
public void setCreationDate(String creationDate) {
this.creationDate = creationDate;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public static class Address {
private String country;
private String region;
private String city;
private String addressLine1;
private String addressLine2;
private String postalCode;
private String phoneNumber;
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getAddressLine1() {
return addressLine1;
}
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
public String getAddressLine2() {
return addressLine2;
}
public void setAddressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
}
public static class Contacts {
private String type;
private String firstName;
private String lastName;
private String email;
private String phoneNumber;
private String adminId;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getAdminId() {
return adminId;
}
public void setAdminId(String adminId) {
this.adminId = adminId;
}
}
public static class Associations {
private String type;
private String id;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
}
Error Message:com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token
at [Source: (String)"[{"accountId":"1005003805","status":"1000","internalStatus":"ACTIVE","associations":[{"id":"1000004114","type":"reseller"}],"preferredLanguage":"it-IT","address":{"country":"IT","phoneNumber":"408-536-3538","city":"SESTO FIORENTINO","postalCode":"50019","addressLine1":"345 Park Ave","addressLine2":"VIA DONINZETTI 17","region":"32"},"name":"UPLOAD DI RICCI LUCA E PROCELLI SNC anil","type":"customer","externalReferenceId":"Su66353456234","contacts":[{"firstName":"surendra1","lastName":"kumar","pho"[truncated 1565 chars]; line: 1, column: 2] (through reference chain: adobe_Partner_Api_ECCS_PojoClasses.ECCSGetExtraCustomer["accountId"])

You got this error because you put the #JsonFormat(shape = JsonFormat.Shape.ARRAY) annotation on top of your class, which I think is unnecessary in your case.
There are also some errors in your POJO class, it misses the accountCode field, and the createdDate field is named creationDate.
public class ECCSGetExtraCustomer {
private String accountId;
private String accountCode;
private String createdDate;
//... + Getters and setters
}
To deserialize your json as list you can do it this way :
public class LaunchDebug {
public void main() throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
List<ECCSGetExtraCustomer> eccsGetExtraCustomer = Arrays.asList(objectMapper.readValue(value, ECCSGetExtraCustomer[].class));
System.out.println(eccsGetExtraCustomer.toString());
}
}

Related

System.Text.Json.JsonException - Error deserializing

Here is my code:
public class Element
{
public string? Group { get; set; }
public int Position { get; set; }
public string? Name { get; set; }
public int Number { get; set; }
[JsonPropertyName("small")]
public string? Sign { get; set; }
public double Molar { get; set; }
public IList<int>? Electrons { get; set; }
public override string ToString()
{
return $"{Sign} - {Name}";
}
}
public List<Element> LoadJson()
{
using (StreamReader r = new StreamReader("jsondata/elements.json"))
{
string json = r.ReadToEnd();
var ElementObject = JsonSerializer.Deserialize<List<Element>>(json);
return ElementObject;
}
}
elements.json
{
"elements": [
{
"group": "Other",
"position": 0,
"name": "Hydrogen",
"number": 1,
"small": "H",
"molar": 1.00794,
"electrons": [
1
]
},
{
"group": "Noble Gas (p)",
"position": 17,
"name": "Helium",
"number": 2,
"small": "He",
"molar": 4.002602,
"electrons": [
2
]
}
]
}
while I am trying to deserialize I get
System.Text.Json.JsonException: 'The JSON value could not be converted to System.Collections.Generic.List`1[BlazorApp4.Shared.Entities.Element]. Path: $ | LineNumber: 0 |
What am I missing?
The JSON doesn't represent a List<Element>. It represents an object which has a property which is a List<Element>.
Create that object:
public class Root
{
public List<Element> Elements { get; set; }
}
And deserialize into that:
var root = JsonSerializer.Deserialize<Root>(json);
return root.Elements;

Injecting settings into service from appsettings.JSON

I have a service which read the data from a queue (Rabbit MQ - ProduceQueue), takes action on the message and publishes the status on a separate status queue (Rabbit MQ - StatusQueue).
The issue I am facing is I am not able to instantiate the Producer and Consumer with separate settings when I resolve the service instance.
JSON Settings:
"RabbitMQConnection": {
"UserName": "guest",
"Password": "guest",
"HostName": "localhost",
"QueueName": "TaskExecutorPublisher",
"ExchangeName": "TaskProducerExchange",
"Port": "9090"
},
"RabbitMQStatusConnection": {
"UserName": "guest",
"Password": "guest",
"HostName": "localhost",
"QueueName": "SequenceStatusPublisher",
"ExchangeName": "StatusExchange",
"Port": "9091"
}
Program.cs:
IHost host = Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration(app => { app.SetBasePath(Directory.GetCurrentDirectory()); app.AddJsonFile("appsettings.json"); })
.ConfigureServices((context, services) =>
{
//services.AddMvcCore();
//services.AddMvc();
services.AddLogging();
services.AddSingleton<IMQConsumer, RabbitMQConsumer>()
.AddOptions<IMQConnectionConfiguration>().Configure(options =>
{
options.HostName = context.Configuration["RabbitMQConnection:HostName"];
options.Port = Convert.ToInt32( context.Configuration["RabbitMQConnection:Port"]);
options.UserName = context.Configuration["RabbitMQConnection:UserName"];
options.Password = context.Configuration["RabbitMQConnection:Password"];
options.ExtensionProperties = new Dictionary<string, string>() {
{ "QueueName", context.Configuration["RabbitMQConnection:QueueName"] },
{ "ExchangeName",context. Configuration["RabbitMQConnection:ExchangeName"] }};
});
services.AddSingleton<IMQProducer, RabbitMQProducer>()
.AddOptions<IMQConnectionConfiguration>().Configure(options =>
{
options.HostName = context.Configuration["RabbitMQStatusConnection:HostName"];
options.Port = Convert.ToInt32(context.Configuration["RabbitMQStatusConnection:Port"]);
options.UserName = context.Configuration["RabbitMQStatusConnection:UserName"];
options.Password = context.Configuration["RabbitMQStatusConnection:Password"];
options.ExtensionProperties = new Dictionary<string, string>() {
{ "QueueName", context.Configuration["RabbitMQStatusConnection:QueueName"] },
{ "ExchangeName",context. Configuration["RabbitMQStatusConnection:ExchangeName"] }};
});
services.AddHostedService<ExecutorServiceAPI>();
services.AddSingleton<IMQConnectionConfiguration, ConnectionConfiguration>(option =>
{
var connectionConfig = new ConnectionConfiguration();
connectionConfig.HostName = context.Configuration["RabbitMQConnection:HostName"];
connectionConfig.Port = Convert.ToInt32(context.Configuration["RabbitMQConnection:Port"]);
connectionConfig.UserName = context.Configuration["RabbitMQConnection:UserName"];
connectionConfig.Password = context.Configuration["RabbitMQConnection:Password"];
connectionConfig.ExtensionProperties = new Dictionary<string, string>() {
{ "QueueName", context.Configuration["RabbitMQConnection:QueueName"] },
{ "ExchangeName",context. Configuration["RabbitMQConnection:ExchangeName"] }};
return connectionConfig;
});
}).UseWindowsService()
ExecutorService code :
public class ExecutorServiceAPI : IHostedService
{
private readonly ILogger _logger;
private IMQConsumer _consumerConnection;
private IMQProducer _producerConnection;
public ExecutorServiceAPI(ILogger<ExecutorServiceAPI> logger, IMQConsumer consumerConnection, IMQProducer producerConnection)
{
if (consumerConnection == null)
throw new ArgumentNullException(nameof(consumerConnection));
_logger = logger;
_consumerConnection = consumerConnection;
_producerConnection = producerConnection;
}
}
In appsettings.json:
"Settings": {
"RabbitMQConnection": {
"UserName": "guest",
"Password": "guest",
"HostName": "localhost",
"QueueName": "TaskExecutorPublisher",
"ExchangeName": "TaskProducerExchange",
"Port": "9090"
},
"RabbitMQStatusConnection": {
"UserName": "guest",
"Password": "guest",
"HostName": "localhost",
"QueueName": "SequenceStatusPublisher",
"ExchangeName": "StatusExchange",
"Port": "9091"
}
}
Settings:
public class Settings
{
public SettingProperties RabbitMQConnection { get; set; }
public SettingProperties RabbitMQStatusConnection { get; set; }
}
SettingProperties:
public class SettingProperties
{
public string UserName { get; set; }
public string Password { get; set; }
public string HostName { get; set; }
public string QueueName { get; set; }
public string ExchangeName { get; set; }
public string Port { get; set; }
}
In Progarm.cs (.net 6) , add below code:
builder.Services.Configure<Settings>(builder.Configuration.GetSection("Settings"));
Then in HomeController:
public class HomeController : Controller
{
private readonly Settings _MysettingsM;
public HomeController(IOptions<Settings> APPsettings)
{
_MysettingsM = APPsettings.Value;
}
public IActionResult Index()
{
var R1= _MysettingsM.RabbitMQConnection;
var R2 = _MysettingsM.RabbitMQStatusConnection;
return View();
}
}
result:

SQL syntax Error on Java Jersey GET CRUD operation

I'm trying to retrieve the information of the faculty with the students attending it and the subjects corresponding to the student.
Here is the SQL error:
java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM faculty f
inner join student_faculty sf on sf.student_id=s.user_id'
Here is the picture in line 116 the s.user_id is not on yellow color indicating something not right:
Here is it how I want it to look like:
{
"fid": "1",
"name": "Mathematcis",
"enrolled_students": [
{
"id": "student1",
"username": "user",
"full_name": "userstudent",
"subjects": [
{
"id": 1,
"name": "Programim 1"
},
{
"id": 2,
"name": "Programim 2"
},
{
"id": 3,
"name": "Calculus"
},
{
"id": 4,
"name": "Discrete mathematics"
}
]
}
]
Here is how postman shows it:
Here is my code:
public Faculty getFacultyStudent(int id) throws Exception {
Connection connection = null;
Faculty faculty = new Faculty();
Student student = new Student();
student.setSubjectList(new ArrayList<>());
faculty.setStudentList(new ArrayList<>());
try {
connection = new MysqlDbConnectionService().getConnection();
String select = "SELECT f.fid,\n" +
" f.fname,\n" +
" f.university_id,\n" +
" s.user_id,\n" +
" s.username,\n" +
" s.password,\n" +
" s.fullname,\n" +
" s.email,\n" +
" subj.id,\n" +
" subj.name,\n" +
"FROM faculty f\n" +
" inner join student_faculty sf on sf.student_id=s.user_id\n" +
" INNER JOIN student s ON sf.student_id=s.user_id\n" +
" INNER JOIN faculty_subject fs on f.fid = fs.faculty_id\n" +
" inner join subject subj on fs.subject_id = subj.id\n" +
"WHERE fid = ?;";
PreparedStatement ps = connection.prepareStatement(select);
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
if(faculty.getFid()==0) {
faculty.setFid(rs.getInt("fid"));
faculty.setFname(rs.getString("fname"));
}
student.setId(rs.getString("user_id"));
student.setUsername(rs.getString("username"));
student.setPassword(rs.getString("password"));
student.setFullName(rs.getString("fullname"));
student.setEmail(rs.getString("email"));
Subject subject=new Subject();
subject.setId(rs.getInt("id"));
subject.setName(rs.getString("name"));
student.getSubjectList().add(subject);
faculty.getStudentList().add(student);
}
} catch (Exception e) {
System.out.println(e + "Retrieve not successful");
}
return faculty;
}
Faculty Class:
package com.common.db.domain;
import com.google.gson.annotations.SerializedName;
import java.util.Collections;
import java.util.List;
public class Faculty {
#SerializedName("id")
private int fid;
#SerializedName("university_id")
private int university_id;
#SerializedName("name")
private String fname;
#SerializedName("Enrolled Students:")
private List<String> studentList;
public Faculty() {
this.fid = fid;
this.university_id=university_id;
}
public void setFid(int fid)
{
this.fid = fid;
}
public int getFid()
{
return fid;
}
public void setUniversityid(int university_id)
{
this.university_id=university_id;
}
public int getUniversityid()
{
return university_id;
}
public void setFname(String fname)
{
this.fname = fname;
}
public String getFname()
{
return fname;
}
public void setStudentList(List<String> studentList) {
this.studentList = studentList;
}
public List<Object> getStudentList()
{
return Collections.singletonList(studentList);
}
}
Student Class:
package com.common.db.domain;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class Student {
#SerializedName("id")
private String id;
#SerializedName("username")
private String username;
#SerializedName("password")
private String password;
#SerializedName("fullname")
private String fullName;
#SerializedName("email")
private String email;
#SerializedName("subjects")
private List<Subject> subjectList;
public Student() {
}
public Student(String id, String username, String password, String fullName, String email) {
super();
this.id = id;
this.username = username;
this.password = password;
this.fullName = fullName;
this.email = email;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public List<Subject> getSubjectList() {
return subjectList;
}
public void setSubjectList(List<Subject> subjectList) {
this.subjectList = subjectList;
}
}
Subject Class:
package com.common.db.domain;
import com.google.gson.annotations.SerializedName;
public class Subject {
#SerializedName("id")
private int id;
#SerializedName("name")
private String name;
public Subject() {
this.id = id;
this.name=name;
}
public void setId(int id)
{
this.id=id;
}
public int getId()
{
return id;
}
public void setName(String name)
{
this.name=name;
}
public String getName()
{
return name;
}
}
Here is my ER Diagram:
I was reading through the code and the error and it appears to be just your sentence.
"subj.name , \n" + "FROM faculty f\n" +
That comma after the column name and before the FROM clause is causing that error.
Try to remove it and test it again

Masstransit not consuming non MassTransit messages

I have to publish a message using Python and consume it using MassTransit (.Net core app).
To test, I created a Console Application to produce the messages using the Azure.ServiceBuss library.
The consumer is a MassTransit implementation of the ServiceBus.
When I send the message to the queue (using my console application), MassTransit is not able to consume it.
I am aware of the Interoperability and all the headers we must send in order to MassTransit consume the messages, but I am not able to make the consumer work.
The producer:
namespace MassTransit.MultipleBus.ServiceBus.Models.Commands
{
class Program
{
const string ServiceBusConnectionString = "connstring";
const string QueueName = "topic";
static IQueueClient queueClient;
public static async Task Main(string[] args)
{
queueClient = new QueueClient(ServiceBusConnectionString, QueueName);
// Send messages.
await SendMessagesAsync();
Console.WriteLine("ENVIOU");
Console.ReadKey();
await queueClient.CloseAsync();
}
private static async Task SendMessagesAsync()
{
try
{
while (true)
{
string messageBody = JsonConvert.SerializeObject(new EnviarExemploPocAzureServiceBusCommand(
NewId.NextGuid(),
NewId.NextGuid(),
new Proposta()
)
{
Headers = new Dictionary<string, object>() { },
Host = new HostInfo()
});
var message = new Message(Encoding.UTF8.GetBytes(messageBody));
Console.WriteLine($"Enviando mensagem: {messageBody}");
await queueClient.SendAsync(message);
Console.WriteLine("Enviado. Enviar outro?");
Console.ReadKey();
}
}
catch (Exception exception)
{
Console.WriteLine($"{DateTime.Now} :: Exception: {exception.Message}");
}
}
}
}
The class I'm sending:
namespace MassTransit.MultipleBus.ServiceBus.Models.Commands
{
public class EnviarExemploPocAzureServiceBusCommand
{
public EnviarExemploPocAzureServiceBusCommand(Guid msgId, Guid convId, Proposta msg)
{
MessageId = msgId.ToString();
ConversationId = convId.ToString();
MessageType = new[]
{
"urn:message:MassTransit.MultipleBus.ServiceBus.Models.Commands:Proposta"
};
Message = msg;
SourceAddress = "";
DestinationAddress = "sb://organization.servicebus.windows.net/topic";
}
public string DestinationAddress { get; set; }
public string MessageId { get; set; }
public string ConversationId { get; set; }
public string SourceAddress { get; set; }
public HostInfo Host { get; set; }
public IDictionary<string, object> Headers { get; set; }
public Proposta Message { get; set; }
public string[] MessageType { get; set; }
}
public class Proposta
{
public Proposta()
{
Nome = "TESTE 2";
AcaoId = 2;
Mensagem = "TESTE 2";
}
public string Nome { get; set; }
public int AcaoId { get; set; }
public string Mensagem { get; set; }
}
public class HostInfo
{
public HostInfo()
{
MachineName = "NOTEXXXXX";
ProcessName = "iisexpress";
ProcessId = 34188;
Assembly = "MassTransit.MultipleBus";
AssemblyVersion = "1.0.0.0";
FrameworkVersion = "3.1.5";
MassTransitVersion = "7.0.2.0";
OperatingSystemVersion = "Microsoft Windows NT 10.0.19041.0";
}
public string MachineName { get; set; }
public string ProcessName { get; set; }
public int ProcessId { get; set; }
public string Assembly { get; set; }
public string AssemblyVersion { get; set; }
public string FrameworkVersion { get; set; }
public string MassTransitVersion { get; set; }
public string OperatingSystemVersion { get; set; }
}
}
The message queued in ServiceBus:
{
"DestinationAddress": "sb://organization.servicebus.windows.net/topic",
"MessageId": "00010000-0faa-0009-6939-08d854e183aa",
"ConversationId": "00010000-0faa-0009-69f0-08d854e183aa",
"SourceAddress": "",
"Host": {
"MachineName": "NOTEXXXXX",
"ProcessName": "iisexpress",
"ProcessId": 32608,
"Assembly": "MassTransit.MultipleBus",
"AssemblyVersion": "1.0.0.0",
"FrameworkVersion": "3.1.5",
"MassTransitVersion": "7.0.2.0",
"OperatingSystemVersion": "Microsoft Windows NT 10.0.19041.0"
},
"Headers": {
},
"Message": {
"nome": "TESTE 2",
"acaoId": 2,
"mensagem": "TESTE 2"
},
"MessageType": [
"urn:message:MassTransit.MultipleBus.ServiceBus.Models.Commands:Proposta"
]
}
The consumer startup:
services.AddMassTransit<IAzureServiceBusService>(x =>
{
x.AddConsumer<EnviarExemploPocAzureServiceBusCommandHandler>();
x.UsingAzureServiceBus((context, cfg) =>
{
cfg.UseConcurrencyLimit(serviceBusSettings.AzureServiceBusSettings.ExemploAplicacaoPocA.ConcurrencyLimit);
cfg.Host("connString", h =>
{
h.OperationTimeout = TimeSpan.FromSeconds(serviceBusSettings.AzureServiceBusSettings.ExemploAplicacaoPocA.OperationTimeout);
h.TransportType = Microsoft.Azure.ServiceBus.TransportType.AmqpWebSockets;
});
cfg.UseServiceBusMessageScheduler();
});
});
services.AddMassTransitHostedService();
services.AddSettings(configuration);
The handler:
namespace MassTransit.MultipleBus.ServiceBus.Handlers.CommandHandlers
{
public class EnviarExemploPocAzureServiceBusCommandHandler : IConsumer<Proposta>
{
public async Task Consume(ConsumeContext<Proposta> context)
{
await Task.CompletedTask;
}
}
public class EnviarExemploPocAzureServiceBusFaultCommandHandler : IConsumer<Fault<EnviarExemploPocAzureServiceBusCommand>>
{
public async Task Consume(ConsumeContext<Fault<EnviarExemploPocAzureServiceBusCommand>> context)
{
await Task.CompletedTask;
}
}
}
When I send the message using MassTransit as well, the consumer works and the message is queued like:
{
"messageId": "00010000-0faa-0009-6497-08d854edbfe1",
"conversationId": "00010000-0faa-0009-3b83-08d854edbfe5",
"sourceAddress": "sb://organization.servicebus.windows.net/XXXX",
"destinationAddress": "sb://organization.servicebus.windows.net/topic",
"messageType": [
"urn:message:MassTransit.MultipleBus.ServiceBus.Models.Commands:Proposta"
],
"message": {
"nome": "TESTE DOIS",
"acaoId": 2,
"mensagem": "TESTE DOIS"
},
"sentTime": "2020-09-09T18:25:37.6127127Z",
"headers": {
"MT-Activity-Id": "|1e87ff49-4beb56732bfd4887.3."
},
"host": {
"machineName": "NOTEXXXXXX",
"processName": "iisexpress",
"processId": 37092,
"assembly": "MassTransit.MultipleBus",
"assemblyVersion": "1.0.0.0",
"frameworkVersion": "3.1.5",
"massTransitVersion": "7.0.2.0",
"operatingSystemVersion": "Microsoft Windows NT 10.0.19041.0"
}
}
What am I doing wrong?
The namespace seems to be correct, I did everything I found about it and I can't make it work.
Can someone help me?

ASP.NET core POST request fail

I have a model:
public class CoreGoal
{
[Key]
public long CoreGoalId { get; set; }
public string Title { get; set; }
public string Effect { get; set; }
public string Target_Audience { get; set; }
public string Infrastructure { get; set; }
public virtual ICollection<Benefit> Benefits { get; set; }
public virtual ICollection<Step> Steps { get; set; }
public virtual ICollection<Image> Images { get; set; }
public virtual ICollection<SubGoal> SubGoals { get; set; }
public CoreGoal()
{
}
}
And Image model is as following:
public class Image
{
[Key]
public long ImagelId { get; set; }
public byte[] Base64 { get; set; }
[ForeignKey("CoreGoalId")]
public long CoreGoalId { get; set; }
public Image()
{
}
}
My controller class:
[Route("api/[controller]")]
public class CoreGoalController : Controller
{
private readonly ICoreGoalRepository _coreGoalRepository;
//Controller
public CoreGoalController(ICoreGoalRepository coreGoalRepository) {
_coreGoalRepository = coreGoalRepository;
}
//Get methods
[HttpGet]
public IEnumerable<CoreGoal> GetAll()
{
return _coreGoalRepository.GetAllCoreGoals();
}
[HttpGet("{id}", Name = "GetCoreGoal")]
public IActionResult GetById(long id)
{
var item = _coreGoalRepository.Find(id);
if (item == null)
{
return NotFound();
}
return new ObjectResult(item);
}
//Create
[HttpPost]
public IActionResult Create([FromBody] CoreGoal item)
{
if (item == null)
{
return BadRequest();
}
_coreGoalRepository.CreateCoreGoal(item);
return CreatedAtRoute("GetCoreGoal", new { id = item.CoreGoalId }, item);
}
}
Repository:
public class CoreGoalRepository : ICoreGoalRepository
{
private readonly WebAPIDataContext _db;
public CoreGoalRepository(WebAPIDataContext db)
{
_db = db;
}
//Add new
public void CreateCoreGoal(CoreGoal coreGoal)
{
_db.CoreGoals.Add(coreGoal);
_db.SaveChanges();
}
//Get all
public IEnumerable<CoreGoal> GetAllCoreGoals()
{
return _db.CoreGoals
.Include(coreGoal => coreGoal.Benefits)
.Include(coreGoal => coreGoal.Steps)
.Include(coreGoal => coreGoal.Images)
.Include(coreGoal => coreGoal.SubGoals)
.ToList();
}
//Find specific
public CoreGoal Find(long key)
{
return _db.CoreGoals.FirstOrDefault(t => t.CoreGoalId == key);
}
}
public interface ICoreGoalRepository
{
void CreateCoreGoal(CoreGoal coreGoal);
IEnumerable<CoreGoal> GetAllCoreGoals();
CoreGoal Find(long key);
void DeleteCoreGoal(long id);
void UpdateCoreGoal(CoreGoal coreGoal);
}
When I do a POST request from swagger I get a template like:
{
"coreGoalId": 0,
"title": "string",
"effect": "string",
"target_Audience": "string",
"infrastructure": "string",
"benefits": [
{
"benefitId": 0,
"what": "string",
"coreGoalId": 0
}
],
"steps": [
{
"stepId": 0,
"what": "string",
"coreGoalId": 0
}
],
"images": [
{
"imagelId": 0,
"base64": "string",
"coreGoalId": 0
}
],
"subGoals": [
{
"subGoalId": 0,
"title": "string",
"priority": "string",
"audience": "string",
"social_aspects": "string",
"coreGoalId": 0,
"issues": [
{
"issueId": 0,
"title": "string",
"subGoalID": 0
}
]
}
]
}
If I POST like like this, my request fails with status 400, however if I remove
"images": [
{
"imagelId": 0,
"base64": "string",
"coreGoalId": 0
}
],
from this request, then it is successful. Why is it happening? All other models i.e. Benefit, Step are exactly identical to Image in structure.
UPDATE:
Changing base64 type from byte[] to string eliminates this problem but in that case while saving to my MySql database the big base64 string is chopped and kind of becomes useless to again form the image.