Service Bus Route Query - azure-iot-hub

I have set a endpoint and a route on service bus with this criteria in query:
$body.Temperature.AlarmPrius = 1
where the format of message I set is like
public async void InvioDati(ProbDATA msgRicevuto)
{
var messageString = JsonConvert.SerializeObject(msgRicevuto);
var message = new Message(Encoding.UTF8.GetBytes(messageString));
message.ContentType = "application/json";
message.ContentEncoding = "utf-8";
await dispositivo.SendEventAsync(message);
}
}
ProbDATA is set as:
public class ProbDATA
{
public int ID { get; set; }
public int Funzione { get; set; }
/******/
public int Registro_1 { get; set; }
/******/
public int Registro_2 { get; set; }
/******/
public int Registro_3 { get; set; }
/******/
public int Alarm_123 { get; set; }
/******/
public int Registro_4 { get; set; }
/******/
public int Alarm_4 { get; set; }
/******/
public DateTime _TimeStamp { get; set; }
/******/
public override string ToString()
{
return $"Temperature ::ID {ID.ToString()}, Funzione {Funzione.ToString()}, Registro_1 {Registro_1.ToString()}, Registro_2 {Registro_2.ToString()}, Registro_3 {Registro_3.ToString()}, AlarmPrius {Alarm_123.ToString()}, Registro_4 {Registro_4.ToString()}, Alarm_4 {Alarm_4.ToString()}, _TimeStamp {_TimeStamp.ToString("yyyy-MM-dd HH:mm:ss")}";
}
}
but no message enters the service bus queue... I'm aware of other topics similar to mine (I use MQTT connection) and they suggest, like here, to use devices/{yourDeviceId}/messages/events/$.ct=application%2Fjson&$.ce=utf-8 but how can I implement this? any example?

Thanks to #roman Kiss I solved the issue, wich was a wrong written query.
correct one was query $body.Alarm_123 = 1. thanks again!

Related

Searching method in asp.net core

I'm building an asp.net core searching API which should return a list of videos who has the same searched QR code(the QR code is a ForeignKey)
This is the video model:
public class Video
{
[Key]
public int VideoId { get; set; }
public string Exercice { get; set; }
public string Titre { get; set; }
public int Sexe { get; set; }
public int Categorie { get; set; }
public int Level { get; set; }
public string FilePath { get; set; }
public DateTime DateUpload { get; set; } = DateTime.Now;
[ForeignKey("Machine")]
public string Machine_Qr { get; set; }
public Machine machine { get; set; }
public Coache Coache { get; set; }
}
And this is the search controller:
[HttpGet("{Qr}")]
public async Task<IEnumerable<Video>> Search(string qr)
{
IEnumerable<Video> query = _context.videos.Where(e => e.Machine_Qr == qr);
if ((query != null))
return query;
else
return Enumerable.Empty<Video>().ToList();
}
but I tested it and I got an empty list every time.
Edit: your edit fixed the first logic issue in the original question. But the query also needs to have an await since the function is an async Task.
Since your function returns an IEnumerable, you shouldn't need to call .ToList() ... try this:
[HttpGet("{Qr}")]
public async Task<IEnumerable<Video>> Search(string qr)
{
return await _context.videos.Where(e => e.Machine_Qr == qr) ?? Enumerable.Empty<Video>()
}

Convert Generic API Response in Blazor

I'm developing a Blazor WASM project and I'm stuck in this point.
I'm using a DataAccess Service to make the requests to EndPoints;
The endpoints return a ResultList, that is a Generic Object that needs to be parsed in Client side. The object definition:
public class ResultList
{
public ResultList(List<object> resultados, string codigoErro = null, string mensagemErro = null)
{
this.Resultados = resultados;
this.CodigoErro = codigoErro;
this.MensagemErro = mensagemErro;
}
public string MensagemErro { get; set; }
public List<object> Resultados { get; set; }
public string CodigoErro { get; set; }
}
In the client side, I receive the same type:
public async Task<ResultList> GetEmpresas()
{
try
{
ResultList Result = await _httpClient.GetFromJsonAsync<ResultList>("api/EmpCadBasico/GetEmpresas");
return Result;
}
catch (Exception ex)
{
return new ResultList(null, null, ex.Message);
}
}
The problem is: I can't convert the List<Object> to other type like List<Empresa>.
The C# compilation doesn't notify bug, but in execution time, it happens.
I tried Serialize and Deserialize, and it doesn't work too:
public async Task GetEmpresas()
{
ResultList Resultado = await _dataAccess.GetEmpresas();
if (await RetornoOk(Resultado))
{
string x = JsonSerializer.Serialize(Resultado.Resultados); // Here, that's fine.
List<Empresa> y = JsonSerializer.Deserialize<List<Empresa>>(x); // Here, it finds the objects, but all of them with null values.
}
}
The X value: '[{"id":1,"nomeEmpresa":"Alamo","cnpj":"00072619000101","dataCadastro":"2020-01-01T00:00:00","colaborador":[],"marca":[]}]'
The Y value: Y value after Deserialization
According to the json return data you provided, I did the following restoration and successfully returned the data, you can refer to it.
Model:
public class TestModel
{
public int id { get; set; }
public string nomeEmpresa { get; set; }
public string cnpj { get; set; }
public string dataCadastro { get; set; }
public List<colaborador> colaborador { get; set; }
public List<marca> marca { get; set; }
}
public class colaborador
{
public int id { get; set; }
public string test { get; set; }
}
public class marca
{
public int id { get; set; }
public string test { get; set; }
}
Then I gave values to individual attributes, and the results are as follows:

Can i add a parent record and a child record using the same _context.SaveChangesAsync()

I have the following 2 Parent/Child objects:-
public Submission()
{
SubmissionQuestionSubmission = new HashSet<SubmissionQuestionSubmission>();
}
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Npi { get; set; }
public bool Independent { get; set; }
public string Comment { get; set; }
public virtual ICollection<SubmissionQuestionSubmission> SubmissionQuestionSubmission { get; set; }
}
public partial class SubmissionQuestionSubmission
{
public int SubmissionQuestionId { get; set; }
public int SubmissionId { get; set; }
public string Answer { get; set; }
public virtual Submission Submission { get; set; }
}
and i created the following view model:-
public class SubmissionCreate
{
public Submission Submission {set; get;}
public IList<SubmissionQuestion> SubmissionQuestion { set; get; }
public IList<SubmissionQuestionSubmission> SubmissionQuestionSubmission { set; get; }
}
where i have the following action method to add a parent record (submission) and a child record (SubmissionQuestionSubmission ), but to do so, i have to issue 2 save requests to the database, one to save the parent and get its ID, while the other to save the child record and assign it the parent ID, as follow:-
public async Task<IActionResult> Create(SubmissionCreate sc)//Bind("Id,FirstName,LastName,Npi,Independent,Comment")]
{
if (ModelState.IsValid)
{
var newsubmission = _context.Submission.Add(sc.Submission);
await _context.SaveChangesAsync();
foreach (var v in sc.SubmissionQuestionSubmission)
{
v.SubmissionId = sc.Submission.Id;
_context.SubmissionQuestionSubmission.Add(v);
}
await _context.SaveChangesAsync();
TempData["message"] = "Thank You.. Your request has been submitted...";
return View("Confirmation");
}
return View(sc);
}
so my question is if i can do the above job, using one save statement instead of 2?
You don't need use two SaveChanges. You can assign newsubmission into Submission property instead of v.SubmissionId = sc.Submission.Id;.
In this case Id and ForeignKey created automatically by EF Core
var newsubmission = _context.Submission.Add(sc.Submission);
foreach (var v in sc.SubmissionQuestionSubmission)
{
v.Submission = newsubmission;
_context.SubmissionQuestionSubmission.Add(v);
}
await _context.SaveChangesAsync();
Another way
sc.Submission.SubmissionQuestionSubmission = new List<SubmissionQuestionSubmission>();
foreach (var v in sc.SubmissionQuestionSubmission)
{
sc.Submission.SubmissionQuestionSubmission.Add(v)
}
_context.Submission.Add(sc.Submission);
await _context.SaveChangesAsync();

AutoMapper Custom Value Resolvers async

I want to convert BotViewModel to Bot using AutoMapper.
There is an example input below from type BotViewModel. If I want to add a new bot to the database, that model should be matched/mapped to Bot model and Bot's foreign keys should be resolved.
In other words, BotViewModel.Symbol should be matched to CryptoPair.Symbol and BotViewModel.Interval to TimeInterval.Interval.
{
"id": 0,
"name": "Bot 1",
"status": true,
"symbol": "LTCBTC",
"interval": 6
}
My code below is working exactly as I described it above. It uses http://docs.automapper.org/en/stable/Custom-value-resolvers.html. The thing is that I want to make _context.CryptoPairs.FirstOrDefault async FirstOrDefault => FirstOrDefaultAsync.
I want to do that because I feel like that's not the best practice. Basically, I'm looking for an advice if that's okay or not. By the way, if the symbol or interval cannot be matched because it simply doesn't exist in the database, var bot = _mapper.Map<Bot>(botViewModel); should just throw an exception which is later handled by my controller.
public class CryptoPairResolver : IValueResolver<BotViewModel, Bot, int>
{
private readonly BinanceContext _context;
public CryptoPairResolver(BinanceContext context)
{
_context = context;
}
public int Resolve(BotViewModel source, Bot destination, int destMember, ResolutionContext context)
{
return _context.CryptoPairs.FirstOrDefault(p => p.Symbol == source.Symbol).Id;
}
}
public class TimeIntervalResolver : IValueResolver<BotViewModel, Bot, int>
{
private readonly BinanceContext _context;
public TimeIntervalResolver(BinanceContext context)
{
_context = context;
}
public int Resolve(BotViewModel source, Bot destination, int destMember, ResolutionContext context)
{
return _context.TimeIntervals.FirstOrDefault(i => i.Interval == source.Interval).Id;
}
}
public class MappingProfile : Profile
{
public MappingProfile()
{
CreateMap<BotViewModel, Bot>()
.ForMember(dest => dest.CryptoPairId, opt => opt.MapFrom<CryptoPairResolver>())
.ForMember(dest => dest.TimeIntervalId, opt => opt.MapFrom<TimeIntervalResolver>());
}
}
Models:
public class Bot
{
public int Id { get; set; }
public string Name { get; set; }
public bool Status { get; set; }
public int CryptoPairId { get; set; }
public CryptoPair CryptoPair { get; set; }
public int TimeIntervalId { get; set; }
public TimeInterval TimeInterval { get; set; }
}
public class BotViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public bool Status { get; set; }
public string Symbol { get; set; }
public KlineInterval Interval { get; set; }
}
public class CryptoPair
{
public int Id { get; set; }
public string Symbol { get; set; }
public List<Bot> Bots { get; set; }
}
public class TimeInterval
{
public int Id { get; set; }
public KlineInterval Interval { get; set; }
public List<Bot> Bots { get; set; }
}
Edit:
public async Task<Bot> CreateAsync(BotViewModel botViewModel)
{
// Map BotViewModel to Bot
var cryptoPair = await _context.CryptoPairs.FirstOrDefaultAsync(e => e.Symbol == botViewModel.Symbol);
if (cryptoPair == null)
{
throw new BadRequestException();
}
var timeInterval = await _context.TimeIntervals.FirstOrDefaultAsync(e => e.Interval == botViewModel.Interval);
if (timeInterval == null)
{
throw new BadRequestException();
}
var bot = new Bot
{
Name = botViewModel.Name,
Status = botViewModel.Status,
CryptoPairId = cryptoPair.Id,
TimeIntervalId = timeInterval.Id
};
// Create code
_context.Bots.Add(bot);
await _context.SaveChangesAsync();
return bot;
}

How to disable changestate tracking for a sub-entity in boilerplate AppService

I'm using aspnet core & ef core with boilerplate and would like to disable the changestate tracking for a sub-entity. How do I this this within AppService (ie AsyncCrudAppService).
For example:
Entity:
[Table("tblCategory")]
public class Category : FullAuditedEntity<int>, IMustHaveTenant
{
public const int MaxCodeLength = 128;
public const int MaxNameLength = 2048;
public virtual int TenantId { get; set; }
[Required]
[StringLength(MaxCodeLength)]
public virtual string Code { get; set; }
[Required]
[StringLength(MaxNameLength)]
public virtual string Name { get; set; }
[ForeignKey("GroupId")]
public virtual Group Group { get; set; }
[Required]
public virtual int GroupId { get; set; }
}
Dto:
[AutoMapFrom(typeof(Category))]
public class CategoryDto : FullAuditedEntityDto<int>
{
[Required]
[StringLength(Category.MaxCodeLength)]
public string Code { get; set; }
[Required]
[StringLength(Category.MaxNameLength)]
public string Name { get; set; }
[Required]
public int GroupId { get; set; }
[DisableValidation]
public GroupDto Group{ get; set; }
}
AppService Update Method:
public override async Task<CategoryDto> Update(CategoryDto input)
{
var cat = await _categoryManager.GetA(input.Id);
MapToEntity(input, cat);
//I'd like to disable the tracking of cat.Group here ?
await _categoryManager.UpdateA(cat);
return await Get(input);
}
I'd like to disable the change detection for cat.Group, how do I do this ?
Thanks in advance.
Using AsNoTracking when loading resolves the issue
Tracking can be skipped by adding .AsNoTracking() to the call.
For example:
var cat = await _yourDbContext.AsNoTracking().FirstAsync(m => m.Id == input.Id);
Which is fine for results that will not be edited during it's lifetime.