how to write async web api for get method in web api 2? - asp.net-web-api2

showing warning of "this asynch method lacks await". kindly suggest where to add await in my asynch method?
public async Task<IHttpActionResult> GetEmployeeDetails(string id,string StartDate, string EndDate)
{
DateTime sd = Convert.ToDateTime(StartDate);
DateTime ed = Convert.ToDateTime(EndDate);
using (EmployeeEntities db = new EmployeeEntities ())
{
try
{
return Ok(db.employees.Where(x => x.TimeStamp >= sd && x.TimeStamp <= ed && x.DeviceImei ==id).OrderByDescending(x => x.id).ToListAsync());
}
catch (Exception)
{
return BadRequest("Sorry Error Found!!!");
}
}
}

You can use it in the return statement where you are using ToListAsync()
return Ok(await db.employees.Where(x => x.TimeStamp >= sd && x.TimeStamp <= ed && x.DeviceImei ==id).OrderByDescending(x => x.id).ToListAsync());

Related

receive null value SQLITE

I create the following function to calculate total between two dates but always get null value what was wrong ?
void calcul_total_period() async {
var totalSumPeriod = (await databaseHelper.claculTotalPeriod(startDate, endDate))[0]['TOTAL']; //['$startDate''$endDate'];
print(' $totalSumPeriod');
setState(() {
somme_period = totalSumPeriod ?? 00;
somme_total_period = somme.toStringAsFixed(2);
});
}
function in db
Future claculTotalPeriod (String startDate, String endDate) async {
var totalClientperiod = await database;
var result = await totalClientperiod.rawQuery("SELECT SUM($colPrix) AS TOTAL from $clientTable WHERE $colDate BETWEEN '$startDate' AND '$endDate'");
print('$result');
return result.toList();
}
What's somme ?
void calcul_total_period() async {
var totalSumPeriod = (await databaseHelper.claculTotalPeriod(startDate, endDate))[0]['TOTAL']; //['$startDate''$endDate'];
print(' $totalSumPeriod');
setState(() {
somme_period = totalSumPeriod ?? 00;
somme_total_period = ---> somme <----.toStringAsFixed(2);
});
}

Need to get total counts of a record from table in database using ASP.NET Core Web API

I need to count the total rows of a table when I pass a date as a parameter.
IService:
Task<int?> ScoresUpdated(DateTime date);
Service implementation:
public async Task<int?> ScoresUpdated(DateTime date)
{
var result = await _eventScheduleContext
.ViewPersonEventScore
.Where(x => x.DateTimeUtc.Date == date
&& x.ExamModeId == 1
&& x.EventStatusId == 8).ToListAsync();
return result.Count();
}
Controller:
public async Task<IActionResult> ScoresUpdated(DateTime date)
{
var result = await _examDetailService.ScoresUpdated(date);
return Ok(result);
}
But the output I'm getting is 0. In the database, I can see 80 rows.
Is there anything wrong with my code? Can you give me some suggestions how to fix it?
Suspect that it is due to this line
x.DateTimeUtc.Date == date
In SQL expression, I believe it translated to
CONVERT(date, DateTimeUtc) = #date
which #date is DateTime type. So this results that you are unable to query any records.
Use date.Date so that the translated SQL expression will be:
CONVERT(date, DateTimeUtc) = CONVERT(date, #date)
public async Task<int?> ScoresUpdated(DateTime date)
{
var result = await _eventScheduleContext
.ViewPersonEventScore
.Where(x => x.DateTimeUtc.Date == date.Date
&& x.ExamModeId == 1
&& x.EventStatusId == 8)
.ToListAsync();
return result.Count();
}
While seems you are only returning the count of the query result, you may consider applying CountAsync<TSource>(IQueryable<TSource>, CancellationToken).
This would improve the query performance as it will return the count, but not return all columns to the result.
public async Task<int?> ScoresUpdated(DateTime date)
{
return await _eventScheduleContext
.ViewPersonEventScore
.CountAsync(x => x.DateTimeUtc.Date == date.Date
&& x.ExamModeId == 1
&& x.EventStatusId == 8);
}
I don't see a reason for defining optional return type for the task (Task<int?>). I suggest using Task. refer to this Microsoft documentation for further details.
However, despite having 80 rows or entries in the DB as mentioned, you need to check which one of them match the condition you have defined (Where(x => x.DateTimeUtc.Date == date.Date
&& x.ExamModeId == 1
&& x.EventStatusId == 8))
If no entry meets the condition, the count of course would be zero.
Try removing the condition and check.

Best practice to check duplicate string data before insert data using Entity Framework Core in C#

I need an advice for my code. What I want to do is insert a row into a table using Entity Framework Core in ASP.NET Core.
Before inserting new data, I want to check if email and phone number is already used or not.
I want to return specifically, example if return = x, email used. If return = y, phone used.
Here's my code
public int Insert(Employee employee)
{
var checkEmail = context.Employees.Single(e => e.Email == employee.Email);
if (checkEmail != null)
{
var checkPhone = context.Employees.Single(e => e.Phone == employee.Phone);
if (checkPhone != null)
{
context.Employees.Add(employee);
context.SaveChanges();
return 1;
}
return 2;
}
return 3;
}
I'm not sure with my code, is there any advice for the best practice in my case?
I just don't like these "magic numbers" that indicate the result of your checks.... how are you or how is anyone else going to know what 1 or 2 means, 6 months down the road from now??
I would suggest to either at least create a constants class that make it's more obvious what these numbers mean:
public class CheckConstants
{
public const int Successful = 1;
public const int PhoneExists = 2;
public const int EmailExists = 3;
}
and then use these constants in your code:
public int Insert(Employee employee)
{
var checkEmail = context.Employees.Single(e => e.Email == employee.Email);
if (checkEmail != null)
{
var checkPhone = context.Employees.Single(e => e.Phone == employee.Phone);
if (checkPhone != null)
{
context.Employees.Add(employee);
context.SaveChanges();
return CheckConstants.Successful;
}
return CheckConstants.PhoneExists;
}
return CheckConstants.EmailExists;
}
and also in any code that calls this method and need to know about the return status code.
Alternatively, you could also change this to an enum (instead of an int):
public enum CheckConstants
{
Successful, PhoneExists, EmailExists
}
and then just return this enum - instead of an int - from your method:
public CheckConstants Insert(Employee employee)
{
var checkEmail = context.Employees.Single(e => e.Email == employee.Email);
if (checkEmail != null)
{
var checkPhone = context.Employees.Single(e => e.Phone == employee.Phone);
if (checkPhone != null)
{
context.Employees.Add(employee);
context.SaveChanges();
return CheckConstants.Successful;
}
return CheckConstants.PhoneExists;
}
return CheckConstants.EmailExists;
}
merge two database check to one Query
use SingleOrDefault instance of Single
public int Insert(Employee employee)
{
var checkEmail = context.Employees.Select (e=>new {e.Email , e.Phone }).SingleOrDefault(e => e.Email == employee.Email || e.Phone == employee.Phone);
if (checkEmail == null)
{
context.Employees.Add(employee);
context.SaveChanges();
return 1;
}
else if (checkEmail.Email == employee.Email)
return 3;
else
return 2;
}

MVC Entity Framework, Query returns null

Hi guys can you help me understand why i keep getting a null instead of get the value.
Need to receive the saidaservicoid to be able to update. I receive the value from the view but can't update elemento. Stays null.
Thanks in advance for the help.
[Database]
[elementoRepository]
public async Task UpdateElementoSaidaServicosAsync(AddSaidasServicoViewModel model)
{
var saidaServico = await _context.SaidaServicos.FindAsync(model.SaidaServicoId);
var elemento = await _context.Elementos.FindAsync(model.ElementoId);
if (elemento == null)
{
return;
}
var updateElementoSaida = _context.Elementos.Where(e => e.Id == model.ElementoId).FirstOrDefault();
if (updateElementoSaida == null)
{
updateElementoSaida = new Elemento
{
saidaServico = saidaServico,
};
_context.Elementos.Update(updateElementoSaida);
}
else
{
int SaidaServicos = model.SaidaServicoId;
updateElementoSaida.saidaServico = saidaServico;
}
await _context.SaveChangesAsync();
return;
}
Ok. the best way that i found to solve this issue was to get the last ID.
int SaidaServicos = _context.SaidaServicos.Max(item => item.Id);

Function Doesn't Return a value in Dart Language

I am trying to connect my app to an API and search using the API. If the search is successful and found the name, it will return Success and if not, will return Failed, but it doesn't return anything.
import 'dart:convert';
import 'package:http/http.dart' as http;
main() {
getData();
}
String linearSearch(List<dynamic> list, String x) {
for (var i = 0; i < list.length; i++){
if(x == list[i]["name"]){
return 'Success';
}
}
return 'Failed';
}
void getData() async {
List data;
var response = await
http.get("http://localhost:3000/data");
data = jsonDecode(response.body);
linearSearch(data, 'karim');
}
Your function returns String value without any additions. You just need to assign result of your function to String variable and do something with it, if needed.
Or you just could print result of the function
void getData() async {
List data;
var response = await
http.get("http://localhost:3000/data");
data = jsonDecode(response.body);
print(linearSearch(data, 'karim'));
}
Solved by editing my linearSearch function
linearSearch(List<dynamic> list, String x) {
for (var i = 0; i < list.length; i++){
if(x == list[i]["name"]){
return print('Success');
}
}
return print('Failed');
}