Cannot await 'long' when calling an async method inside asp.net mvc5 - asp.net

I have the following async method inside my asp.net mvc 5 web application with EF6:-
public async Task<Resource> GetResourceByName(string resourcename)
{
return await entities.Resources.SingleOrDefaultAsync(a => a.RESOURCENAME.ToLower() == resourcename.ToLower());
}
now i am trying to get the ID for the returned object from the above method as follow:-
var temp = await GetResourceByName(FQDN).Result.RESOURCEID;
but this will raise the following error:-
Error 1 Cannot await 'long'
now to fix this i did the following :-
var temp = await GetResourceByName(FQDN);
id = temp.RESOURCEID;
so not sure why my first apporach did not work. now i await the Task, and when it finises i will retrieve the .Result and get the ResourceID ... so why this will not work ?
here is the model for the Resource:-
public partial class Resource
{
public long RESOURCEID { get; set; }
public string RESOURCENAME { get; set; }
public Nullable<long> ACQUISITIONDATE { get; set; }
public Nullable<long> WARRANTYEXPIRY { get; set; }
public Nullable<long> EXPIRYDATE { get; set; }
public long COMPONENTID { get; set; }
public string ASSETTAG { get; set; }
public string SERIALNO { get; set; }
public string BARCODE { get; set; }
public Nullable<long> PURCHASELOTID { get; set; }
public Nullable<long> VENDORID { get; set; }
public long RESOURCESTATEID { get; set; }
public Nullable<long> SITEID { get; set; }
public Nullable<long> CIID { get; set; }
public bool ISDEPRECIATIONCONFIGURED { get; set; }
public bool ISDEPRECIATIONCALCULATED { get; set; }
public bool ISPERSONAL { get; set; }
public virtual ComponentDefinition ComponentDefinition { get; set; }
public virtual ResourceLocation ResourceLocation { get; set; }
public virtual ResourceState ResourceState { get; set; }
public virtual SiteDefinition SiteDefinition { get; set; }
}

Awaiting the task will give you the result. If you then want to descend into a property of the result, you'll need to use parenthesis if you want it all in one expression:
var temp = (await GetResourceByName(FQDN)).RESOURCEID;

Calling .Result on a task blocks the thread until the operation completes. The result object is of the type specified in TResult for the Task.
Your call did not work, because you can't await the Result of the task, only the task itself. Once you call .Result there is nothing to await.

Related

postman error in POST - the field is required

Someone can help me, I'm trying send a POST requisition. But I dont undertand why it is not working.
this is my model:
public partial class LineModel : IModel
{
public LineModel()
{
UsersNavigation = new HashSet<UserModel>();
LineUsersNavigation = new HashSet<LineUserModel>();
}
public long Id { get; set; }
public string ProfitCenter { get; set; }
public string LineName { get; set; }
public string Customer { get; set; }
public long PlantId { get; set; }
public long TeamId { get; set; }
public virtual TeamModel TeamNavigation { get; set; }
public virtual PlantModel PlantNavigation { get; set; }
public virtual ICollection<UserModel> UsersNavigation { get; set; }
public virtual ICollection<LineUserModel> LineUsersNavigation { get; set; }
}
}
This is my controller:
[HttpPost]
public async Task<ActionResult<UserModel>> SaveUserAsync(UserModel user)
{
await _dbContext.Users.AddAsync(user);
await _dbContext.SaveChangesAsync();
return Ok();
}
and this is the print of my POSTMAN

Refit me showing an error when initializing

I am trying to consume a service using Refit and I have the following problem. I was looking at the documentation but I can't find a solution and I don't know if I should do anything else.
This is my model
public partial class Global
{
[JsonProperty("updated")]
public long Updated { get; set; }
[JsonProperty("country")]
public string Country { get; set; }
[JsonProperty("countryInfo")]
public List<CountryInfo> CountryInfo { get; set; }
}
My second class:
public partial class CountryInfo
{
[JsonProperty("_id")]
public long? Id { get; set; }
[JsonProperty("iso2")]
public string Iso2 { get; set; }
[JsonProperty("iso3")]
public string Iso3 { get; set; }
[JsonProperty("lat")]
public double Lat { get; set; }
[JsonProperty("long")]
public double Long { get; set; }
[JsonProperty("flag")]
public Uri Flag { get; set; }
}
Application with Refit
Link : https://corona.lmao.ninja/v2/countries
[Get("/v2/countries")]
Task<CountryInfo> GetCountry();
In my viewModel
private async Task GetTaskInterf()
{
var webApp = RestService.For<ICovidInterface>("https://corona.lmao.ninja");
var result = await webApp.GetGlobalCountry();
}
At the time of initialization

Automapper missing type map configuration or unsupported mapping error

I am using Auto mapper and I am getting this error, I am getting this error within AddAsync() method. Please help me out to solve this issue.
Missing type map configuration or unsupported mapping.\r\n\r\nMapping types:\r\nDepartmentsViewModel -> Departments\r\nEmployeeAttendanceApp.ViewModels.DepartmentsViewModel -> EmployeeAttendanceApp.Models.StaffManagement.Departments
My class
public interface IMapperConfig
{
IMapper CreateMapper();
}
public class MapperConfig : IMapperConfig
{
public IMapper CreateMapper()
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<RegisterStaffs, RegisterStaffViewModel>();
cfg.CreateMap<AttendanceRecorder, AttendanceRecorderViewModel>();
cfg.CreateMap<ManageLeaves, ManageLeavesViewModel>();
cfg.CreateMap<RegisterDevices, RegisterDevicesViewModel>();
cfg.CreateMap<Departments, DepartmentsViewModel>();
});
return config.CreateMapper();
}
}
public class DepartmentsViewModel
{
[Key]
public int DepartmentId { get; set; }
[DisplayName("اسم القسم/ الادارة")]
[Required(ErrorMessage = "الرجاء ادخال اسم القسم")]
public string DepartmentName { get; set; }
[DisplayName("اضافة ملاحظات القسم")]
public string Remarks { get; set; }
public bool? IsUpdated { get; set; }
public bool? IsDeleted { get; set; }
public string CreatedBy { get; set; }
public string DeletedBy { get; set; }
public string UpdatedBy { get; set; }
[DisplayName("عدد الموظفيين")]
[Required(ErrorMessage = " الرحاء إدخال عدد موظفيين القسم")]
public long? StaffNumber { get; set; }
public DateTime? CreatedDate { get; set; }
public virtual ICollection<RegisterDevicesViewModel> RegisterDevices { get; set; }
public virtual ICollection<RegisterStaffViewModel> RegisterStaffs { get; set; }
}
public partial class Departments
{
[Key]
public int DepartmentId { get; set; }
public string DepartmentName { get; set; }
public string Remarks { get; set; }
public bool? IsUpdated { get; set; }
public bool? IsDeleted { get; set; }
public string CreatedBy { get; set; }
public string DeletedBy { get; set; }
public string UpdatedBy { get; set; }
public long? StaffNumber { get; set; }
public DateTime? CreatedDate { get; set; }
public virtual ICollection<RegisterDevices> RegisterDevices { get; set; }
public virtual ICollection<RegisterStaffs> RegisterStaffs { get; set; }
}
**I am getting the error in this method**
public async Task<bool> AddAsync(DepartmentsViewModel departmentsView)
{
try
{
var department = mapper.Map<DepartmentsViewModel, Departments>(departmentsView);
await context.Departments.AddAsync(department);
await context.SaveChangesAsync();
return true;
}
catch(Exception ex)
{
logger.LogError(ex, ex.Message);
return false;
}
}
//here is startup file where I have registered the services
services.AddSingleton<IMapperConfig, MapperConfig>();
services.AddTransient<IDepartmentManager, DepartmentManager>();
I have resolved this issue by adding .ReverseMap() inside MapperConfig class
cfg.CreateMap<Departments, DepartmentsViewModel>().ReverseMap();
but still I can't understand why it didn't work previously with out it because I have seen various examples never using ReverseMap()

Parse Complex JSON to ASP.NET MVC 3 using jQuery

I have to post this javascript object to asp.net controller:
The model in server side is:
public class UserExperience
{
public class competences
{
public string id { get; set; }
public string level { get; set; }
public string name { get; set; }
public bool isNew { get; set; }
public bool isSaved { get; set; }
}
public long id { get; set; }
public string startDate { get; set; }
public string endDate { get; set; }
public string projectName { get; set; }
public string company { get; set; }
public string customerIndustry { get; set; }
public string jobTitle { get; set; }
public string projectDescription { get; set; }
public string responsabilities { get; set; }
public List<competences> competence { get; set; }
public List<int> deletedCompetences { get; set; }
public bool isNew { get; set; }
public bool isSaved { get; set; }
}
I tried to send the json like this:
$.ajax("/candidate/saveUserExperience", {
data : JSON.stringify({ue: is.Candidate.BO.userExperience[id]}),
//dataType: "text",
contentType : "application/json",
type : 'POST'
})
And this is the controller where I receive it:
public JsonResult saveUserExperience(UserExperience ue)
{
bool success;
success = true;
return Json(new { success, ue }, JsonRequestBehavior.AllowGet);
}
And I receive a null object.
I tried to do with:
UserExperience userExperience = new JavaScriptSerializer().Deserialize<UserExperience>(ue);
and I do not receive the competence subclass object.
Is there a solution to this problem ?
Thanks.
Why are you trying to pass is.Candidate.BO.userExperience[id] when you expect UserExperience object? Just write data: ue in ajax call parameters,

ASP.NET MVC 4 Code First Many to Many Adding to Collection

I am using ASP.NET MVC 4 code first pattern for database layer. I have a many to many relationship between UserProfile and Task. When I try to add a task to the the collection of tasks of a user, it's added but if I try to query it and see if it's there it's not showing up.
My model:
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public string FirstName { get; set; }
public string SirName { get; set; }
public string Position { get; set; }
public string Email { get; set; }
public ICollection<TaskModels> Tasks {get; set; }
public bool? isActive { get; set; }
public UserProfile()
{
Tasks = new HashSet<TaskModels>();
}
}
public class TaskModels
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
public ICollection<UserProfile> Employees { get; set; }
public int TimeNeeded { get; set; }
public int TimeWorked { get; set; }
public string Status { get; set; }
public bool isActive { get; set; }
public TaskModels()
{
Employees = new HashSet<UserProfile>();
}
}
public class WorkLogModels
{
public int Id { get; set; }
public UserProfile Author { get; set; }
public DateTime TimeBeganWorking { get; set; }
public int TimeWorkedOn { get; set; }
public TaskModels Task { get; set; }
public string Description { get; set; }
}
public class TimeTrackerDb : DbContext
{
public TimeTrackerDb() : base("DefaultConnection")
{
}
public DbSet<UserProfile> UserProfiles { get; set; }
public DbSet<TaskModels> Tasks { get; set; }
public DbSet<WorkLogModels> WorkLogs { get; set; }
}
I try to check if a UserProfile already exists in a Task's Employees list and it's always empty.
[HttpPost]
public ActionResult Create(WorkLogModels worklogmodels)
{
var tasks = db.Tasks.Where(x => x.Name == worklogmodels.Task.Name).SingleOrDefault();
if (tasks == null)
{
return View(worklogmodels);
}
if (ModelState.IsValid)
{
var user = db.UserProfiles.Where(x => x.UserId == WebSecurity.CurrentUserId).FirstOrDefault();
var task = db.Tasks.Where(x => x.Name == worklogmodels.Task.Name).FirstOrDefault();
WorkLogModels log = new WorkLogModels();
log.Description = worklogmodels.Description;
log.TimeBeganWorking = worklogmodels.TimeBeganWorking;
log.TimeWorkedOn = worklogmodels.TimeWorkedOn;
log.Author = user;
log.Task = task;
db.WorkLogs.Add(log);
if (!db.UserProfiles.Where(x => x.UserId == WebSecurity.CurrentUserId).First().Tasks.Any(x=> x.Name == worklogmodels.Task.Name))
{
db.UserProfiles.Where(x => x.UserId == WebSecurity.CurrentUserId).FirstOrDefault().Tasks.Add(task);
db.Tasks.Where(x => x.Name == worklogmodels.Task.Name).FirstOrDefault().Employees.Add(user);
}
db.SaveChanges();
return RedirectToAction("Index");
}
return View(worklogmodels);
}
I've been fighting with this for two days now.
Any help will be greatly appreciated
EDIT:
I am not sure if I made myself clear. In the Crate action for the WorkLog Controller I am trying to put the current user in the current task's collection and vice versa. It works correctly the first time, but then if I do it again it fails to skip the if statement and tries to add it once again and throws an exception : System.Data.SqlClient.SqlException. It's trying to add the same record to the intermediate table.

Resources