NetCore3 API not returning/serializing my data - asp.net-core

I have the following controller:
[HttpGet("idfull/{id}")]
public async Task<IActionResult> GetAccountByIdFull(int id)
{
try
{
var response = await _accountFacade.GetAccountByIdAsync(id, full: true).ConfigureAwait(false);
if (response == null)
return NoContent();
return Ok(response);
}
catch (KeyNotFoundException kEx)
{
return NotFound();
}
catch (Exception ex)
{
return StatusCode((int)HttpStatusCode.InternalServerError);
}
}
The Facade layer:
public async Task<AccountViewModel> GetAccountByIdAsync(int accountId, bool full = false)
{
try
{
var unmappedResponse = await _accountService.GetAccountByIdAsync(accountId, full);
var mappedResponse = _mapper.Map<AccountViewModel>(unmappedResponse);
return mappedResponse;
}
catch
{
throw;
}
}
The service layer:
public async Task<Account> GetAccountByIdAsync(int accountId, bool full = false)
{
try
{
Account account;
if (full)
{
account = await _repo.GetOneAsync<Account>(x => x.AccountId == accountId);
account.Company = await _repo.GetOneAsync<Company>(filter: x => x.CompanyId == account.CompanyId,
includes: source => source
.Include(c => c.CompanyTransferType)
.ThenInclude(ctt => ctt.PartnerCompanyAccountType)
.Include(c => c.CompanyTransferType).ThenInclude(ctt => ctt.TransferType)
.Include(c => c.CompanyEquipment).ThenInclude(ce => ce.Equipment)
.Include(c => c.CompanyAccountGroup)
.Include(c => c.CompanyAccountType));
account.AccountContact = await _repo.GetAsync<AccountContact>(filter: x => x.AccountId == accountId);
account.AccountEquipment = await _repo.GetAsync<AccountEquipment>(filter: x => x.AccountId == accountId,
includes: source => source
.Include(ae => ae.AccountEquipmentFee).Include(ae => ae.CompanyEquipment).ThenInclude(ce => ce.Equipment));
account.AccountPickVolumeDefaultAccount = await _repo.GetAsync<AccountPickVolumeDefault>(filter: x => x.AccountId == accountId,
includes: source => source
.Include(a => a.Equipment).Include(a => a.PartnerAccount));
}
else
{
account = await _repo.GetByIdAsync<Account>(accountId);
}
if (account == null)
throw new KeyNotFoundException($"Could not find Account with ID: {accountId}");
return account;
}
catch
{
throw;
}
}
What I do not understand is, the controller returns OK status and all of my fields are populated. However, the API hangs and does not return my data, in other words, the Swagger API (including front-end application) does not receive the response and keeps on showing the loading button.
I have a funny feeling it has something to do with Serialization, but not sure how to fix it.
I have made sure to turn off SelfRefenceLooping, as can be seen here:
services.AddControllers().AddNewtonsoftJson(setup =>
{
setup.SerializerSettings.ContractResolver = new DefaultContractResolver();
setup.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
Why is the API not returning the JSON object?

Can you try without the .ConfigureAwait(false)?
Except for that, you code seems ok and the API should work fine.
If you don't have it, I would recommend adding Swagger to your API, it's just a matter of 5-10 lines and it helps a lot in the development phase (and also avoid manual mistakes while testing). Here is the official documentation: ASP.NET Core web API help pages with Swagger / OpenAPI
You can also try to add a very dumb action in your controller, to try to identify where the issue comes from (Controller layer? Service layer? Facade layer?)

Related

Flutter : How to delete Rest Api Using Http.Client?

I develope App for CRUD Operation rest api using Http Client. GET and POST work perfectly, but problem come after DELETE Operation.
Console Message show me response code Bad Request 400 **, I Check code rest Api (in my codeigniter) **Bad Request 400 it's means the ID is null or not passing the ID on URL Rest Api.
It's Console Message Image
But I try on POSTMAN and **DELETE* is perfectly work , i dont know why in flutter http.delete not working.
It's Result POSTMAN Working
My Api Url for Delete
http://192.168.43.159/wpu-rest-server/apii/mahasiswa/delete/
It's My API.dart :
Future<bool> checkPost(Map<String, dynamic> id) async {
final client = http.Client();
try {
final response = await client.send(http.Request(
"DELETE", Uri.parse("${Urls.BASE_API_URL}mahasiswa/delete/"))
..headers['Content-type']= 'application/x-www-form-urlencoded'
..body = jsonEncode(id));
print(response.reasonPhrase);
print(response.statusCode.toString());
print(response.request.toString());
return response.statusCode == 204;
} finally {}
}
It's My list.dart :
void _checkPost() async{
final post = {"id":widget.id};
bool result = await api.checkPost(post);
if (result) {
_showSnackBar(
context, 'Success ');
} else {
_showSnackBar(context, 'Failed');
return null;
}
}
If you need Rest Api Code :
Controller
public function delete_delete()
{
$id = $this->delete('id');
$msgDelete = ['id' => $id, 'message' => 'Deleted the resource'];
$msgEmpty = ['status' => false, 'message' => 'ID Not Found'];
$msgBadRequest = ['status' => false, 'message' => 'Provide an ID'];
if ($id === null) {
$this->set_response($msgBadRequest, 400);
} else {
if ($this->mahasiswa->deleteMahasiswa($id) > 0) {
$this->set_response($msgDelete, 204);
} else {
$this->set_response($msgEmpty, 404);
}
}
}
Model
public function deleteMahasiswa($id = null)
{
if ($id === null) {
return false;
} else {
$this->db->delete('mahasiswa', ['id' => $id]);
return $this->db->affected_rows();
}
}
I'm mistake something ?
I ever heard httpclient.delete can't add body , but in POSTMAN need add body for deleting data, how to handle this ?

Kendo UI Scheduler incorrectly calling WebAPI

I have been looking around the Telerik forums & Stackoverflow for an answer for this and I am completely stuck and unable to figure out the issue.
I am using the Kendo UI for Asp.Net Core Scheduler Control. I have it reading the data from my controller fine. However, I cannot get it call the HttpPut handler correctly.
When checking the traffic I get the following response, and therefor my breakpoint inside my HttpPut handler will never be hit.
400 - Bad Request
{"":["The input was not valid."]}
My code in my view is:
#(Html.Kendo().Scheduler<MeetingViewModel>()
.Name("SchedulerView")
.Height(500)
.Date(DateTime.Now.ToUniversalTime())
.StartTime(new DateTime(2018, 11, 28, 0, 00, 00).ToUniversalTime())
.MajorTick(30)
.ShowWorkHours(false)
.Footer(false)
.Editable(edit =>
{
//edit.Resize(false);
edit.Create(false);
})
.Views(views =>
{
views.TimelineView(timeline => timeline.EventHeight(50));
//views.TimelineWeekView(timeline => timeline.EventHeight(50));
//views.TimelineWorkWeekView(timeline => timeline.EventHeight(50));
//views.TimelineMonthView(timeline =>
//{
// timeline.StartTime(DateTime.Now);
// timeline.EndTime(DateTime.Now.AddMonths(1));
// timeline.MajorTick(1440);
// timeline.EventHeight(50);
//});
})
.Timezone("Etc/UTC")
.Group(group => group.Resources("WorkCenters" /*,"Attendees"*/).Orientation(SchedulerGroupOrientation.Vertical))
.Resources(resource =>
{
resource.Add(m => m.ScheduleRowID)
.Title("Work Center")
.Name("WorkCenters")
.DataTextField("Text")
.DataValueField("Value")
.DataColorField("Color")
.BindTo(#Model.AvailableWorkCenters);
})
.DataSource(d => d
.ServerOperation(true)
.WebApi()
.Model(m =>
{
m.Id(f => f.ActivityID);
m.Field(f => f.Title).DefaultValue("No title");
//m.RecurrenceId(f => f.RecurrenceID);
m.Field(f => f.Description).DefaultValue("No Description");
})
.Events(events => events.Error("error_handler"))
.Read(read => read.Action("GetActivities", "Scheduler").Data("setRequestDateTimes"))
//.Create(create => create.Action("Post", "Scheduler"))
.Update(update => update.Action("PutActivity", "Scheduler", new { id = "{0}" }).Type(HttpVerbs.Put))
//.Destroy(destroy => destroy.Action("Delete", "Scheduler", new { id = "{0}" }))
)))
And my API Controller is as follows:
[Route("Api/[controller]")]
[ApiController]
public class SchedulerController : DawnController
{
public SchedulerController(DatabaseContext context) : base(context)
{
}
[HttpGet]
public DataSourceResult GetActivities([DataSourceRequest] DataSourceRequest request, DateTime requestStartDateTime, DateTime requestEndDateTime)
{
//Kendo doesnt seem to send the full date range. so + 1 day to end
requestEndDateTime = requestEndDateTime.AddDays(1);
List<MeetingViewModel> test = new List<MeetingViewModel>();
foreach (JobTask jobTask in Context.JobTask)
{
if (JobTask.HasActivityInDateRange(jobTask, requestStartDateTime, requestEndDateTime))
{
foreach (Activites jobTaskAct in jobTask.Activites)
{
test.Add(new MeetingViewModel()
{
JobTaskID = jobTask.JobTaskId,
ActivityID = jobTaskAct.ActivityId,
Title = jobTaskAct.Name,
Description = jobTaskAct.Description,
Start = jobTaskAct.StartTime.ToUniversalTime(),
End = jobTaskAct.EndTime.ToUniversalTime(),
IsAllDay = false,
ScheduleRowID = jobTaskAct.Workcenter.WorkCenterId,
});
}
}
}
return test.ToDataSourceResult(request);
}
[HttpPut("{id}")]
public IActionResult PutActivity(int id, MeetingViewModel task)
{
if (ModelState.IsValid && id == task.ActivityID)
{
try
{
//breakpoint here
bool a = true;
//update the db here
}
catch (DbUpdateConcurrencyException)
{
return new NotFoundResult();
}
return new StatusCodeResult(200);
}
else
{
return BadRequest(ModelState.Values.SelectMany(v => v.Errors).Select(error => error.ErrorMessage));
}
}
}
Thanks
The URL exposing your controller method PutActivity in your controller example is PUT api/scheduler/{id}
To access that URL use this Update method.
.Update(update => update.Action("Put", "Scheduler", new { id = "{0}" }))
See this demo as example
Alternatively
If you want to implment the URL api/Scheduler/PutActivity/{id} (similar pattern to your GET) then you will need to modify the attribute over the put method as follows.
[HttpPut("PutActivity/{id}")]
public IActionResult PutActivity(int id, MeetingViewModel task)
Then you can call api/Scheduler/PutActivity/{id} with this asp.net action call.
.Update(update => update.Action("PutActivity", "Scheduler", new { id = "{0}" }).Type(HttpVerbs.Put))

Get JavaScript Array of Objects to bind to .Net Core List of ViewModel

I have a JS Array of Objects which, at time of Post contains three variables per object:
ParticipantId,
Answer,
ScenarioId
During post, there is an Array the size of 8 (at current anyway) which all correctly contain data. When I call post request, the Controller does get hit as the breakpoint triggers, the issue is when I view the List<SurveyResponse> participantScenarios it is shown as having 0 values.
The thing I always struggle to understand is that magic communication and transform between JS and .Net so I am struggling to see where it is going wrong.
My JS Call:
postResponse: function () {
var data = JSON.stringify({ participantScenarios: this.scenarioResponses})
// POST /someUrl
this.$http.post('ScenariosVue/PostScenarioChoices', data).then(response => {
// success callback
}, response => {
// error callback
});
}
My .Net Core Controller
[HttpPost("PostScenarioChoices")]
public async Task<ActionResult> PostScenarioChoices(List<SurveyResponse> participantScenarios)
{
List<ParticipantScenarios> addParticipantScenarios = new List<ParticipantScenarios>();
foreach(var result in participantScenarios)
{
bool temp = false;
if(result.Answer == 1)
{
temp = true;
}
else if (result.Answer == 0)
{
temp = false;
}
else
{
return StatusCode(400);
}
addParticipantScenarios.Add(new ParticipantScenarios
{
ParticipantId = result.ParticipantId,
Answer = temp,
ScenarioId = result.ScenarioId
});
}
try
{
await _context.ParticipantScenarios.AddRangeAsync(addParticipantScenarios);
await _context.SaveChangesAsync();
return StatusCode(201);
}
catch
{
return StatusCode(400);
}
}

Yii2-How to access a variable from model to a controller?

I am working on yii2. I have came across a point in which I have to send an email to a person when a meter is installed and it's images are uploaded to the server. Fro this I have already configured the swift mailer.
There is a model named Installations which have a function which saves all the installation data.
public static function saveAll($inputs){
$coutner = 0;
$arr_status = [];
foreach ($inputs as $input) {
$s = new Installations;
foreach ((array)$input as $key => $value) {
if($key != 'image_names') {
if ($s->hasAttribute($key)) {
$s->$key = $value;
}
}
}
$user = Yii::$app->user;
if (isset($input->auth_key) && Users::find()->where(['auth_key' => $input->auth_key])->exists()) {
$user = Users::find()->where(['auth_key' => $input->auth_key])->one();
}
$s->created_by = $user->id;
if (Installations::find()->where(['ref_no' => $input->ref_no])->exists()) {
$arr_status[] = ['install_id' => $input->install_id, 'status' => 2, 'messages' => "Ref # Already exists"];
continue;
}
$s->sync_date = date('Y-m-d H:i:sā€Šā€Š');
if($s->save()){
if ($s->istallation_status == 'Installed') {
Meters::change_status_byinstall($s->meter_msn, Meters::$status_titles[4]);
}
else if ($s->istallation_status != 'Installed' && $s->comm_status =='Failed')
{
Meters::change_status_byinstall($s->meter_msn, Meters::$status_titles[5]);
}
$arr_status[] = ['install_id' => $input->install_id, 'status' => 1];
$coutner++;
if (isset($input->doc_images_name)) {
foreach ($input->doc_images_name as $img) {
$image = new InstallationImages;
$image->image_name = $img->image_name;
$image->installation_id = $s->id;
$image->save();
}
}
if (isset($input->site_images_name)) {
foreach ($input->site_images_name as $img2) {
$image2 = new InstallationImagesSite;
$image2->image_name = $img2->image_name;
$image2->installation_id = $s->id;
$image2->save();
}
}
}else{
$arr_status[] = ['install_id' => $input->install_id, 'status' => 0, 'messages' => $s->errors];
}
$status = $s->istallation_status;
$msn = $s->meter_msn;
$com = $s->comm_status;
// want to pass these variables to the controller function
}
return ['status' => 'OK', 'details' => $arr_status, 'records_saved' => $coutner];
}
Now There Is a Controller name InstallationController. This controller contains all the APIs for my mobile application. Below are two main functions in it
public function actionAddnew()
{
$fp = fopen('debugeeeeeee.txt', 'w+');
fwrite($fp, file_get_contents('php://input'));
fclose($fp);
$inputs = json_decode(file_get_contents('php://input'));
return Installations::saveAll($inputs);
}
public function actionSavephoto()
{
try {
$count = 0;
foreach ($_FILES as $f) {
$dd = pathinfo($f['name']);
if (!isset($dd['extension']) || !in_array($dd['extension'], array('jpg', 'png', 'gif'))) {
return ['status' => 'ERROR', 'uploaded_files' => $count, 'message' => 'Invalid File'];
break;
}
if (move_uploaded_file($f['tmp_name'], Installations::UPLOAD_FOLDER . $f['name'])) {
$count++;
return ['status' => 'OK', 'uploaded_files' => $count];
break;
} else {
return ['status' => 'ERROR', 'uploaded_files' => $count];
break;
}
}
} catch (Exception $x) {
return ['status' => 'ERROR', 'message' => $x->getMessage()];
}
}
The mobile application will call the Addnew() api and after that it will call the savephoto. Now I want to pass $msn,$status and $com values from the Model to the controller function Savephoto.
For this I have tried to use session variables but still I am unable to get by desired result(s).
I have also checked the question Yii, how to pass variables to model from controller?
but it didn't worked for me.
How can I achieve it?
Any help would be highly appreciated.
The only way to get those values out of saveAll() is to return them. Presently, they are defined on an object in $s that is overwritten each loop. The best way to do that seems to be creating an array outside of your foreach ($inputs... loop and appending each created Installations object.
Return that at the end, and pass it (or just the relevant element from it) into actionSavephoto() as a parameter. Then, those values will be accessible of properties of that passed object. This handling will occur in the code that is not pictured which calls actionAddNew() and then actionSavephoto()

Magento product.create websites argument

I have a question about the websites argument in the magento api.
Nowhere can I find an explanation of what this variable is.
Does this variable represent a storeview? a store? a website?
Where in the api can I retrieve a list of available options?
If I cannot retrieve a list from the API, where in the backend menu can I find the static variable that I can use?
Do I need the website ID or storeID?
I use soap v1
function call($which,$vars=null)
{
// retourneer de output soap client api call
if($vars !== null)
{
return $this->soapclient->call($this->sessiontoken,$which,$vars);
}
else
{
return $this->soapclient->call($this->sessiontoken,$which);
}
}
function createProduct($productname,
$websites,
$shortdescription,
$description,
$status,
$weight,
$tax_class_id,
$categories,
$price,
$attributesetid,
$producttype,
$sku)
{
$attributeSets = $this->call('product_attribute_set.list');
$set = current($attributeSets);
try
{
$x = $this->call('product.create', array($producttype, $set['set_id'], $sku, array(
'name' => $productname,
// websites - Array of website ids to which you want to assign a new product
'websites' => $websites, // array(1,2,3,...)
'short_description' => $shortdescription,
'description' => $description,
'status' => $status,
'weight' => $weight,
'tax_class_id' => $tax_class_id,
'categories' => $categories, //3 is the category id(array(3))
'price' => $price
);));
}
catch(Exception $e)
{
$x = 0xABED + 0xCAFE + 0xBAD + 0xBED * 0xFACE;// abed went to a cafe... the alcohol went bad.... he stumbled into bed and fell face down...
}
return $x;
}
Looking at Mage_Catalog_Model_Product_Api::create():
public function create($type, $set, $sku, $productData, $store = null)
{
//[...]
$product = Mage::getModel('catalog/product');
$product->setStoreId($this->_getStoreId($store))
->setAttributeSetId($set)
->setTypeId($type)
->setSku($sku);
//[...]
$this->_prepareDataForSave($product, $productData);//this does some processing
Now, looking at Mage_Catalog_Model_Product_Api::_prepareDataForSave():
protected function _prepareDataForSave($product, $productData)
{
if (isset($productData['website_ids']) && is_array($productData['website_ids'])) {
$product->setWebsiteIds($productData['website_ids']);
}
//....
we see that website_ids (numeric array) are expected