I develop function for update user, but in backend, I have error:
System.NullReferenceException: 'The object reference is not defined to an instance of an object.' users was null.
I think because users is null, and I don't know how to make a call to fill users data. this error displays in the condition if(id!= users.ID) ,how to fix this problem, here is my code:
[ResponseType(typeof(void))]
// [HttpPut]
[AcceptVerbs("OPTIONS")]
public IHttpActionResult PutUsers(string id, Users users)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != users.Id)
{
return BadRequest();
}
db.Entry(users).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!UsersExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}
and this user.controller:
$scope.userEdit = function () {
console.log('edit');
var idsForEdit = [];
angular.forEach($scope.listeOfUsers, function (item,$uibModalInstance, index) {
console.log($scope.listeOfUsers);
if (item.checked) {
console.log(item.checked);
console.log(item.Id);
//idsForEdit.push(item);
$scope.registration.Email=item.Email;
$scope.registration.Password=item.PasswordHash;
$scope.registration.Users_Role=item.Role;
$scope.registration.Site=item.Site;
$scope.registration.Id=item.Id;
$scope.ok = function () {
console.log("ok");
// $scope.Action = "Update";
User.Update({
id: item.Id
}, $scope.Users=item.Users
, function (response) {
console.log(response);
console.log("ok");
SweetAlert.swal({
title: "Opération effectuée avec succès!",
text: "Click pour quitter!",
type: "success"
});
$state.go($state.current, $stateParams, {
reload: true,
inherit: false,
notify: true
});
$uibModalInstance.close();
},
function (err) {
});
console.log($scope.user);
};
}
});
//$scope.isEditDirty==true;
};
Your code should be -
[ResponseType(typeof(void))]
// [HttpPut]
[AcceptVerbs("OPTIONS")]
public IHttpActionResult PutUsers(string id, Users users)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if(users != null)
{
if (id != users.Id)
{
return BadRequest();
}
db.Entry(users).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!UsersExists(id))
{
return NotFound();
}
else
{
throw;
}
}
}
return StatusCode(HttpStatusCode.NoContent);
}
Using C# 6.0 new features - Null Conditional Operator
[ResponseType(typeof(void))]
// [HttpPut]
[AcceptVerbs("OPTIONS")]
public IHttpActionResult PutUsers(string id, Users users)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != users?.Id)
{
return BadRequest();
}
db.Entry(users).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!UsersExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}
Related
I am still new to flutter development and recently I've been trying to call API. I've managed to do so without placing data into the model and it worked fine. The issue is when I try to serialize the data. I've created a model using webinovers
https://run.mocky.io/v3/5c648026-c95a-4cf8-9a14-79f13cfb29d3
json data
{
"problems": [{
"Diabetes":[{
"medications":[{
"medicationsClasses":[{
"className":[{
"associatedDrug":[{
"name":"asprin",
"dose":"",
"strength":"500 mg"
}],
"associatedDrug#2":[{
"name":"somethingElse",
"dose":"",
"strength":"500 mg"
}]
}],
"className2":[{
"associatedDrug":[{
"name":"asprin",
"dose":"",
"strength":"500 mg"
}],
"associatedDrug#2":[{
"name":"somethingElse",
"dose":"",
"strength":"500 mg"
}]
}]
}]
}],
"labs":[{
"missing_field": "missing_value"
}]
}],
"Asthma":[{}]
}]}
here is my code
problem_models
class AllProblem {
late List<Problem>? problems;
AllProblem({this.problems});
AllProblem.fromJson(Map<dynamic, dynamic> json) {
if (json['problems'] != null) {
problems = <Problem>[];
json['problems'].forEach((v) { problems!.add( Problem.fromJson(v)); });
}
}
}
class Problem {
late List<Diabete> diabetes;
late List<Asthma> asthma;
Problem.fromJson(Map<dynamic, dynamic> json) {
if (json['Diabetes'] != null) {
diabetes = <Diabete>[];
json['Diabetes'].forEach((v) { diabetes.add( Diabete.fromJson(v)); });
}
if (json['Asthma'] != null) {
asthma = <Asthma>[];
json['Asthma'].forEach((v) { asthma.add( Asthma.fromJson(v)); });
}
}
}
class Diabete {
late List<Medication> medications;
late List<Labs> labs;
Diabete.fromJson(Map<dynamic, dynamic> json) {
if (json['medications'] != null) {
medications = <Medication>[];
json['medications'].forEach((v) { medications.add( Medication.fromJson(v)); });
}
if (json['labs'] != null) {
labs = <Labs>[];
json['labs'].forEach((v) { labs.add( Labs.fromJson(v)); });
}
}
}
class Medication {
late List<MedicationsClass> medicationsClasses;
Medication.fromJson(Map<dynamic, dynamic> json) {
if (json['medicationsClasses'] != null) {
medicationsClasses = <MedicationsClass>[];
json['medicationsClasses'].forEach((v) { medicationsClasses.add( MedicationsClass.fromJson(v)); });
}
}
}
class MedicationsClass {
late List<ClassName> className;
late List<ClassName> className2;
MedicationsClass.fromJson(Map<dynamic, dynamic> json) {
if (json['className'] != null) {
className = <ClassName>[];
json['className'].forEach((v) { className.add( ClassName.fromJson(v)); });
}
if (json['className2'] != null) {
className2 = <ClassName>[];
json['className2'].forEach((v) { className2.add( ClassName.fromJson(v)); });
}
}
}
class ClassName {
late List<AssociatedDrug> associatedDrug;
late List<AssociatedDrug> associatedDrug2;
ClassName.fromJson(Map<dynamic, dynamic> json) {
if (json['associatedDrug'] != null) {
associatedDrug = <AssociatedDrug>[];
json['associatedDrug'].forEach((v) { associatedDrug.add( AssociatedDrug.fromJson(v)); });
}
if (json['associatedDrug#2'] != null) {
associatedDrug2 = <AssociatedDrug>[];
json['associatedDrug#2'].forEach((v) { associatedDrug2.add( AssociatedDrug.fromJson(v)); });
}
}
}
class AssociatedDrug {
late String name;
String? dose;
late String strength;
AssociatedDrug.fromJson(Map<dynamic, dynamic> json) {
name = json['name'];
dose = json['dose'];
strength = json['strength'];
}
}
class Labs {
late String missingField;
Labs.fromJson(Map<dynamic, dynamic> json) {
missingField = json['missing_field'];
}
}
class Asthma {
Asthma();
Asthma.fromJson(Map<dynamic, dynamic> json) {
}
Map<dynamic, dynamic> toJson() {
final Map<dynamic, dynamic> data = <dynamic, dynamic>{};
return data;
}
}
resposiory_problem
import 'package:mvvp_simple/model/problems_model.dart';
abstract class ProblemsRepository{
Future<List<AllProblem>> getAllProblem();
}
this is resposiory_problem_API
import 'dart:convert';
import 'package:mvvp_simple/model/problems_model.dart';
import 'package:mvvp_simple/repository/problem/problems_repository.dart';
import 'package:http/http.dart' as http;
class ProblemsAPI extends ProblemsRepository{
//late AllProblem allProblem;
#override
Future<List<AllProblem>> getAllProblem() async{
List<AllProblem> problemList =[];
var apiURl = 'https://run.mocky.io/v3/5c648026-c95a-4cf8-9a14-79f13cfb29d3';
var response = await http.get(Uri.parse(apiURl));
if (response.statusCode == 200) {
var data = await jsonDecode(response.body.toString());
problemList = data.map((problems)=> AllProblem.fromJson(problems));
for(Map i in data){
problemList.add(AllProblem.fromJson(i));
}
print(problemList);
}
return problemList;
}
}
widget to fetch data
child: FutureBuilder(
future: HomeViewModel().fetchAllProblem(),
builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Loading();
} else {
print('this data loaded ${snapshot.data}' );
var problems = snapshot.data;
return Center(
child: ListView.builder(
itemCount: problems?.length,
itemBuilder: (context, index) => const ListTile(title: Text('Problem'),subtitle: Text('Medications'),),
));
}
},
))
I'm working on a angular application but I ran into a problem I cant find the solution to. I'm trying to patch some preselected values to a form control (mat-select multiple) but it just wont show the values. It works fine with the control above (food), but when I try to bind to the multiple choice list, the values wont show.
//Here is my code:
#Component({
selector: 'app-add-edit',
templateUrl: './add-edit.component.html',
styleUrls: ['./add-edit.component.less']
})
export class AddEditComponent implements OnInit {
pageTitle = '';
order: Order;
filteredUsers: User[] = [];
id: number;
orderToDisplay: Order = new Order();
orderForm: FormGroup = new FormGroup({
food: new FormControl('', [Validators.required]),
usersOrdering: new FormControl('', [Validators.required])
});
constructor(private dialogRef: MatDialogRef<AddEditComponent>,
private ordersService: OrdersService,
#Inject(MAT_DIALOG_DATA) public data: any,
private fb: FormBuilder) { }
usersSelected: User[];
ngOnInit(): void {
this.id = this.data.orderId;
if (this.id == 0) {
this.pageTitle = 'Add a new order';
this.order = new Order();
} else {
this.pageTitle = 'Edit the order';
this.getOrder(this.id);
}
this.filterUsers(this.id);
}
save(): void {
if (this.orderForm.valid) {
if (this.orderForm.dirty) {
this.usersSelected = this.orderForm.controls['usersOrdering'].value;
if (this.id == 0) {
this.order.food = this.orderForm.controls['food'].value;
this.order.orderCount = this.usersSelected.length;
this.order.restaurantId = this.data.restaurantId;
this.order.usersOrdering = this.usersSelected;
this.ordersService.addOrder(this.order)
.subscribe(data => {
this.dialogRef.close(true);
});
} else {
this.order.id = this.id;
this.order.food = this.orderForm.controls['food'].value;
this.order.orderCount = this.usersSelected.length;
this.order.usersOrdering = this.usersSelected;
this.ordersService.updateOrder(this.order)
.subscribe(data => {
this.dialogRef.close(true);
});
}
}
} else
console.log('form is invalid')
}
dismiss(): void {
this.dialogRef.close(false);
}
displayOrder(o: Order): void {
if (this.orderForm) {
this.orderForm.reset();
}
this.order = o;
console.log(this.order.usersOrdering);
this.orderForm.patchValue({
food: this.order.food,
usersOrdering: this.order.usersOrdering
});
this.orderForm.updateValueAndValidity();
}
filterUsers(orderId: number) {
this.ordersService.filterUsers(orderId)
.subscribe(data => {
this.filteredUsers = data;
});
}
getOrder(id: number) {
this.ordersService.getOrder(id)
.subscribe(data => {
this.order = data;
this.displayOrder(this.order);
});
}
I have a filter that is on ng-repeat and compares strings of all objects (including nested ones) to a search string. If the search string is found in the object, it returns true.
I'm looking for a way to extend this functionality so that when the search string matches with a string in the object, the filter will return true for that object and will return true for all nested objects in the matching object (this is a tree view, I'm searching for a node and want to show all children nodes when matched).
How would I do that?
My filter looks like this:
.filter('deepFilter', function ($filter) {
return function(text) {
return function (value) {
if(text && text.length > 0) {
var searchTerm = text;
if (angular.isObject(value)) {
var found = false;
angular.forEach(value, function(v) {
found = found || $filter('deepFilter')(searchTerm)(v);
});
return found;
} else if (angular.isString(value)) {
if (value.indexOf(searchTerm) !== -1) {
return true;
} else {
return false;
}
}
} else {
return true;
}
};
};
});
The solution I found is by using a function in the isString part of the filter, and iterating over the collection. If I find the object, I look for it's children using a recursive function and set a visibleAsAChild property for these. Then, I've added a condition in the isObject evaluation to return true for these object that have visibleAsAChild prop.
I'm not sure if this is the most efficient way to do it, but it certainly works.
.filter('deepFilter', function ($filter) {
var currentObject;
var setChildrenToVisible = function(node) {
angular.forEach(node.nodes, function(node) {
if(node.nodes) {
setChildrenToVisible(node);
}
node.visibleAsAChild = true;
});
};
var lookupChildren = function(o, value) {
// console.log(o);
angular.forEach(o.nodes, function(node) {
if (node.name === value) {
setChildrenToVisible(node);
}
});
};
return function(text) {
return function (value) {
if(text && text.length > 0) {
var searchTerm = text;
if (angular.isObject(value)) {
var found = false;
angular.forEach(value, function(v) {
found = found || $filter('deepFilter')(searchTerm)(v);
});
if(found && value.hasOwnProperty('id')) {
currentObject = value;
}
if(value.hasOwnProperty('id') && value.visibleAsAChild) {
return true;
}
return found;
} else if (angular.isString(value)) {
if (value.indexOf(searchTerm) !== -1) {
if(currentObject){
lookupChildren(currentObject, value);
}
return true;
} else {
return false;
}
}
} else {
return true;
}
};
};
I create service like this :
export class MDCurrencyService implements IMDCurrencyService {
httpService: ng.IHttpService;
handlerUrl: string;
constructor($http: ng.IHttpService) {
this.httpService = $http;
this.handlerUrl = '/Master/';
}
get(): MDCurrency[]{
var result: MDCurrency[] = [];
var resp: ng.IPromise<any> = this.httpService.get(this.handlerUrl +'GetAllCurrency')
.then((response: any): ng.IPromise<any> => this.handlerResponded(response, null));
resp.then((data) => {
if (data.is_success) {
data.data.forEach(c => {
var converted: MDCurrency = <MDCurrency>c;
converted.selectedCountry = null;
converted.selectedStatus = null;
result.push(converted);
});
return result;
}
else return null;
});
return result;
}
handlerResponded(response: any, params: any): any {
response.data.requestParams = params;
return response.data;
}
}
in my controller :
$scope.currencies = this.currencies = mdCurrencyService.get();
if ($scope.currencies.length > 0) {
console.log('entered'); //never executed
$scope.currencies.forEach(currency => {
for (var ii = 0; ii < this.statuses.length; ii++)
if ($scope.statuses[ii].Id == currency.Status)
currency.selectedStatus = this.statuses[ii];
});
}
but after $scope.currencies filled from service that forEach never executed.
how to execute that code when $scope.currencies is filled by data from service?
mdCurrencyService.get() should be implemented as an asynchronous service returning a promise. It can be utilized this way:
mdCurrencyService.get().then(function (currencies) {
// process result here
$scope.currencies = currencies;
});
i'm trying to override get: calls in Alloy model, very similar to Backbone, i wrote this but doesn't work
extendModel: function(Model) {
_.extend(Model.prototype, {
// extended functions and properties go here
get: function (attr) {
if (attr=='image')
{
return Ti.Utils.base64decode(this['image'])
}
return this[attr];
}
});
return Model;
},
Here is how i am overriding the set and add methods hope it helps you:
exports.definition = {
config: {
adapter: {
type: "properties",
collection_name: "careCenter",
idAttribute : "CareCenterID"
}
},
extendModel: function(Model) {
_.extend(Model.prototype, {
idAttribute : "CareCenterID"
// extended functions and properties go here
});
return Model;
},
extendCollection: function(Collection) {
_.extend(Collection.prototype, {
add : function(attrs, opts){
var isDuplicated = false;
if(attrs && attrs.get){
isDuplicated = this.any(function(model){
return model.get("CareCenterID") === attrs.get("CareCenterID");
});
}
if(isDuplicated){
return false;
} else {
Backbone.Collection.prototype.add.call(this, attrs, opts);
}
},
comparator : function(model){
return -model.get("state");
}
});
return Collection;
}
}
extendModel: function(Model) {
_.extend(Model.prototype, {
idAttribute : "RecipientID",
set : function(attrs, opts){
if(attrs.Age != null){
var age = attrs.Age;
var result = "";
if(age <= Alloy.CFG.INFANT){
result = "infant";
} else if(age <= Alloy.CFG.CHILD){
result = "child";
} else if(age <= Alloy.CFG.TEENAGER){
result = "teenager";
} else {
result = "adult";
}
attrs.Group = result;
}
return Backbone.Model.prototype.set.call(this, attrs, opts);
}
});
return Model;
},