No output of data in JSON - getting 204 error code - c#

I'm trying to output a Paymentplan for a specific customer with a specific order.
I keep getting this error:
info:Microsoft.AspNetCore.Mvc.Infrastructure.ObjectResultExecutor[1]
Executing ObjectResult, writing value of type 'null'.
There is something I'm doing wrong but I'm not sure what it is. Looked for solutions for a long time with no luck. I'm new to programming and C# so still trying to get hang of this. Really appreciate your help and guidance.
Here is what I have so far:
Models:
using System.Collections.Generic;
namespace Project.Models
{
public class Customer
{
public string CustomerId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string DateOfBirth { get; set; }
}
public class Order
{
public string OrderId { get; set; }
public string Product { get; set; }
public string Status { get; set; }
public double Price { get; set; }
}
public class CustomerOrder
{
public string CustomerId {get; set;}
public string OrderId { get; set; }
}
public class Repayment
{
public int Amount { get; set; }
public string DueDate { get; set; }
public string RepaymentId { get; set; }
}
public class Choice
{
public string ChoiceId { get; set; }
public List<Repayment> Repayments{ get; set; }
}
public class RepaymentPlan
{
public List<Choice> Choices{ get; set; }
}
}
Repositories:
using System.Collections.Generic;
using System.Linq;
using Project.Models;
using System.Net;
using System.Collections.Specialized;
using System.Text;
namespace Project.Repositories
{
public class OrderRepository
{
private static List<Order> _Orders;
private static List<CustomerOrder> _CustomerOrder;
private static List<RepaymentPlan> _RepaymentPlan;
static OrderRepository()
{
_Orders = new List<Order>();
_CustomerOrder= new List<CustomerOrder>();
_PaymentPlan = new List<PaymentPlan>();
_Orders.Add(new Order
{
OrderId = "124",
Product= "Shirts",
Status= "On it's way",
Price= 100.20,
});
_Orders.Add(new Order
{
OrderId= "122",
Product= "Pants",
Status= "Not ready",
Price= 300.30,
});
_Orders.Add(new Order
{
OrderId= "143",
Product= "Deadpool",
Status= "On it's way",
Price= 6.20,
});
_Orders.Add(new Order
{
OrderId= "156",
Product= "Socks",
Status= "Not ready",
Price= 3.30,
});
_CustomerOrder.Add(new CustomerOrder
{
CustomerId = "578",
OrderId = "156",
});
_RepaymentPlan.Add(new RepaymentPlan
{
choices = new List<Choice>
{
new Choice
{
choiceId = "cho1",
Repayments = new List<Repayment>
{
new Repayment
{
amount = 200,
dueDate = "2018-06-01"
},
new Repayment
{
amount = 100,
dueDate = "2018-08-01",
}
}
},
new Choice
{
choiceId = "cho2",
repayments = new List<Repayment>
{
new Repayment
{
repaymentId = "Choice1",
amount = 300,
dueDate = "2018-10-01"
},
new Repayment
{
repaymentId = "Choice2",
amount = 150,
dueDate = "2018-11-01"
},
}
}
},
});
}
public static RepaymentPlan GetRepaymentPlan(string customerId, string orderId)
{
var customerlist =_CustomerOrder.FindAll(c => c.CustomerId==customerId);
var orderlist= _CustomerOrder.FindAll(c => c.orderId==orderId);
var pplist= new RepaymentPlan();
if (customerlist == orderlist)
{
return pplist;
}
return null;
}
Controllers:
OrderController.cs:
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Project.Models;
using Project.Repositories;
namespace Project.Controllers
{
public class OrderController : Controller
{
[HttpGet("customers/{customerid}/orders/{orderId}/paymentPlan")]
public RepaymentPlan FindRepaymentPlan(string customerId, string orderId)
{
return OrderRepository.GetRepaymentPlan(customerId, orderId);
}
}
}

OK, after a closer scan of your code, I see that the problem is in this method
public static RepaymentPlan GetRepaymentPlan(string customerId, string orderId)
You will always return null because your condition will always evaluate to false. This is available for any (probably) programming language.
if (customerlist == orderlist) evaluates if the two objects are identical (they reference the same memory address), it doesn't evaluate the content of the objects. To see if two object have the same data, you can use a loop (for, while). But since you used Linq, it is enough to use multiple conditions in FindAll function.
public static RepaymentPlan GetRepaymentPlan(string customerId, string orderId)
{
var customerlist =_CustomerOrder.FindAll(c => c.CustomerId==customerId && c.orderId==orderId);
var pplist= new RepaymentPlan();
if (customerlist.Any())
{
return pplist;
}
return null;
}
Also, you may want to return customerlist.First() instead of pplist. If you return an empty object of type RepaymentPlan, it might not help you.

Related

Need help using Linq to transform a list into a different list

Lets say I have a list that contains 1 record:
[
{
"AccountNumber": 1234,
"eDocConfirms": true,
"eDocStatements": true,
"eDocTaxforms": false
}
]
This list is a strongly typed object with these properties:
public int AccountNumber { get; set; }
public bool? eDocConfirms { get; set; }
public bool? eDocStatements { get; set; }
public bool? eDocTaxforms { get; set; }
Using LINQ, I'd like to turn it into a list that looks like this:
[
{
"AccountNumber": 1234,
"EDocumentTypeName ": "Confirms"
},
{
"AccountNumber": 1234,
"EDocumentTypeName": "Statements"
}
]
This new list will a list of a different type:
public class DeliveryPreference
{
public int AccountNumber { get; set; }
public string EDocumentTypeName { get; set; }
}
Note that Taxforms was not included in the new list because it was set to false in the first list.
I know I could easily do this with some loops, but I would prefer using LINQ.
I understand that Stack Overflow prefers that I show what I have tried, but I am having trouble wrapping my brain around this.
For this case I would use additional function
public static IEnumerable<string> GetTrueProperties(Data t)
{
if (t.eDocConfirms == true) yield return "Confirms";
if (t.eDocStatements == true) yield return "Statements";
if (t.eDocTaxForms == true) yield return "Tax";
}
simply because it is an object and not a dictionary; else you could dynamically select properties which are true(or you could use reflection, but I think it would be too much here, since you have strongly typed object).
then it would look like
var list = new List<Data> {
new Data
{
AccountNumber = 1,
eDocConfirms = true,
eDocStatements = true,
eDocTaxForms = false
}
};
list.SelectMany(item => GetTrueProperties(item).Select(p => new DeliveryPreference
{
AccountNumber = item.AccountNumber,
EDocumentTypeName = p
}));
This is very ugly code, but it works. It should be easy to comprehend. Reflection can be extracted to a new function.
using System;
using System.Linq;
public class Program
{
public class Account {
public int AccountNumber { get; set; }
public bool? eDocConfirms { get; set; }
public bool? eDocStatements { get; set; }
public bool? eDocTaxforms { get; set; }
}
public class DeliveryPreference
{
public int AccountNumber { get; set; }
public string EDocumentTypeName { get; set; }
}
public static void Main()
{
var acc = new Account {
AccountNumber = 10,
eDocConfirms = true,
eDocStatements = false,
eDocTaxforms = true
};
var transformed = acc.GetType()
.GetProperties()
.Where(p => p.PropertyType == typeof(bool?)
&& ((bool?)p.GetValue(acc)).HasValue
&& ((bool?)p.GetValue(acc)).Value)
.Select(p => new DeliveryPreference {
AccountNumber = acc.AccountNumber,
EDocumentTypeName = p.Name.Substring(4)
});
foreach (var t in transformed) {
Console.WriteLine(t.AccountNumber);
Console.WriteLine(t.EDocumentTypeName);
}
}
}

Using a Parameter to Call a Class in C#

I have got a method with a single parameter of string class that I need to use to access another class in my project.
The following will be what I want it to do. Note that this syntax gives errors.
public string getId(string name) {
string Id = name.GetId();
return Id;
}
Assuming that the user enters "Joe" as the name, one would go to the class Joe.cs, which looks like this.
public class Joe {
public string Id = 32;
public string GetId() {
return Id;
}
}
What I want to happen here is for the first method to be able to get the GetId method from Joe if Joe is entered as a parameter. How would I do this? Thank you all.
This might point you in a better direction
The idea is to have a class called User that holds user information (funnily enough)
This way you can have a list of users (not a class for each one), as such you can easily look up a user and mess with them as much as you want
public class User
{
public string UserName { get; set; }
public string FavoriteColor { get; set; }
}
public class Program
{
// A List to hold users
private static List<User> _users = new List<User>();
private static void Main(string[] args)
{
// lets add some people
_users.Add(new User() { UserName = "Bob",FavoriteColor = "Red" });
_users.Add(new User() { UserName = "Joe", FavoriteColor = "Green" });
_users.Add(new User() { UserName = "Fred", FavoriteColor = "Blue" });
// use a linq query to find someone
var user = _users.FirstOrDefault(x => x.UserName == "Bob");
// do they exist?
if (user != null)
{
// omg yay, gimme teh color!
Console.WriteLine(user.FavoriteColor);
}
}
}
Output
Red
You can take it a step further and ask the user to look up other users (what a time to be a alive!)
Console.WriteLine("Enter a user (case sensitive)");
var userName = Console.ReadLine();
var user = _users.FirstOrDefault(x => x.UserName == userName);
if (user != null)
{
Console.WriteLine(user.FavoriteColor);
}
else
{
Console.WriteLine("Game over, you failed");
}
Console.ReadLine();
You could build a Class that can contain the details you want to store, then build a Manager class that exposes public methods that can extract informations from the stored objects:
public class Friend : IComparable<Friend>
{
public Friend() { }
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int FriendshipLevel { get; set; }
int IComparable<Friend>.CompareTo(Friend other)
{
if (other.FriendshipLevel > this.FriendshipLevel) return -1;
else return (other.FriendshipLevel == this.FriendshipLevel) ? 0 : 1;
}
}
public class MyFriends : List<Friend>
{
public MyFriends() { }
public int? GetID(string FriendName)
{
return this.Where(f => f.FirstName == FriendName).FirstOrDefault()?.ID;
}
public Friend GetFriendByID(int FriendID)
{
return this.Where(f => f.ID == FriendID).FirstOrDefault();
}
}
Build a sample class:
MyFriends myFriends = new MyFriends()
{
new Friend() { ID = 32, FirstName = "Joe", LastName = "Doe", FriendshipLevel = 100},
new Friend() { ID = 21, FirstName = "Jim", LastName = "Bull", FriendshipLevel = 10},
new Friend() { ID = 10, FirstName = "Jack", LastName = "Smith", FriendshipLevel = 50},
};
Then you can extract informations on single/multiple objects using the public methods of the "Manager" class:
int? ID = myFriends.GetID("Joe");
if (ID.HasValue) // Friend Found
Console.WriteLine(ID);
//Search a friend by ID
Friend aFriend = myFriends.GetFriendByID(32);
if (aFriend != null)
Console.WriteLine($"{aFriend.FirstName} {aFriend.LastName}");
Or you can use LINQ to get/aggregate the required informations directly if there isn't a public method that fits:
// Get your best friends using LINQ directly
List<Friend> goodFriends = myFriends.Where(f => f.FriendshipLevel > 49).ToList();
goodFriends.ForEach((f) => Console.WriteLine($"{f.FirstName} {f.LastName}"));
//Best friend
Friend bestFriend = myFriends.Max();
With respect to your Question : GetId method from Joe if Joe is entered as a
parameter.
You can achieve that in the following ways also:
2. Method Using Named Method.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Problem
{
// Simple Model Class.
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
class Program
{
// Delegate.
public delegate string PersonHandler(Person person);
static void Main(string[] args)
{
List<Person> _persons = new List<Person>()
{
new Person(){Id=1,Name="Joe"},
new Person(){Id=2,Name="James"},
new Person(){Id=3,Name="Nick"},
new Person(){Id=4,Name="Mike"},
new Person(){Id=5,Name="John"},
};
PersonHandler _personHandler = new PersonHandler(GetIdOfPerson);
IEnumerable<string> _personIds = _persons.Select(p => _personHandler.Invoke(p));
foreach (var id in _personIds)
{
Console.WriteLine(string.Format("Id's : {0}", id));
}
}
// This is the GetId Method.
static string GetIdOfPerson(Person person)
{
string Id = person.Id.ToString();
return Id;
}
}
}
2. Method Using Anonymous Moethod.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Problem
{
// Simple Model Class.
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
class Program
{
// Delegate.
public delegate string PersonHandler(Person person);
static void Main(string[] args)
{
List<Person> _persons = new List<Person>()
{
new Person(){Id=1,Name="Joe"},
new Person(){Id=2,Name="James"},
new Person(){Id=3,Name="Nick"},
new Person(){Id=4,Name="Mike"},
new Person(){Id=5,Name="John"},
};
PersonHandler _personHandler = delegate(Person person)
{
string id = person.Id.ToString();
return id;
};
// Retrieving all person Id's.
IEnumerable<string> _personIds = _persons.Select(p => _personHandler.Invoke(p));
foreach (var id in _personIds)
{
Console.WriteLine(string.Format("Id's : {0}", id));
}
}
}
}
2. Method Using a Lambda Expression.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Problem
{
// Simple Model Class.
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
class Program
{
// Delegate.
public delegate string PersonHandler(Person person);
static void Main(string[] args)
{
List<Person> _persons = new List<Person>()
{
new Person(){Id=1,Name="Joe"},
new Person(){Id=2,Name="James"},
new Person(){Id=3,Name="Nick"},
new Person(){Id=4,Name="Mike"},
new Person(){Id=5,Name="John"},
};
PersonHandler _personHandler = (Person person) => person.Id.ToString();
IEnumerable<string> _personIds = _persons.Select(p => _personHandler.Invoke(p));
foreach (var id in _personIds)
{
Console.WriteLine(string.Format("Id's : {0}", id));
}
}
}
}
Output:

how do i create a Generic List for the class batch and inside class batch i want to put student class information

Here I want to student class inside batch class and use them using the List class, how do I create object of both the classes for List...
Example if I want to find the name of a student from the batch how do I do it...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Challenge
{
class student
{
string student_name;
int age, rollnumber;
public student(string student_name, int age, int rollnumber)
{
this.age = age;
this.student_name = student_name;
this.rollnumber = rollnumber;
}
}
class batch
{
string batch_name;
int fees, duration;
public batch(string batch_name,int fees,int duration)
{
this.batch_name = batch_name;
this.fees = fees;
this.duration = duration;
}
}
class Program
{
static void Main(string[] args)
{
List<batch> obj = new List<batch>();
}
}
}
It is not very clear what you want to do, but I will try to help. From what I can understand, you want to create a collection of Batches, where every Batch contains a collection of Students.
Declare a List<Student> property in the Batch class:
public class Batch
{
public string Name { get; set; }
public int Fee { get; set; }
public int Duration { get; set; }
public List<Student> Students { get; set; }
}
public class Student
{
public string Name { get; set; }
public int RollNumber { get; set; }
// Date of birth instead of age, as explained in comment by Dour High Arch.
public DateTime DateOfBirth { get; set; }
}
You may now create a list of batches by:
var batches = new List<Batch>
{
new Batch
{
Name = "Batch 1",
Duration = 100,
Fee = 200,
Students = new List<Student>
{
new Student
{
Name = "Student 1",
DateOfBirth = DateTime.Today,
RollNumber = 1
},
new Student
{
Name = "Student 2",
DateOfBirth = DateTime.Today,
RollNumber = 2
}
}
}
};
Your batches list can be iterated as:
foreach (var batch in batches)
{
Console.WriteLine($"Batch: {batch.Name}");
foreach (var student in batch.Students)
{
Console.WriteLine($"Student: {student.Name}");
}
}

Get Collections from object using reflection and getCount (.net 4)

I have a requirement to reflect on a object get all properties that are collections and
1)GetCount for each collection
2)GetTotalCount (allCollectionCount)
3)Call a method with this collection.
Below is what I have done so far with a made up noddy structure for semplicity.
I am stuck in how to call this method and how to get count for collection.
Any suggestions?
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
namespace ConsoleApplication2
{
class Program
{
static void Main()
{
var request = GetDataRequest();
//Get all properties
List<PropertyInfo> propInfoList =
new List<PropertyInfo>(request.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public));
//Get collections only
var myClassCollections=propInfoList.Where(xxx => xxx.PropertyType.GetInterfaces().Any(x => x == typeof (IEnumerable))).ToList();
var totalCountForAllCollections=????
foreach (var col in myClassCollections)
{
//How do I call my Method DoSomething
// DoSomething<?>(col.?????)
}
}
public void DoSomething<T>(List<T> objectCollection)
{
//etc...
}
private static DataRequest GetDataRequest()
{
DataRequest request = new DataRequest();
request.Addresses.Add(new Address
{
Id = 1,
City = "London",
Postcode = "32131",
Street = "London Road"
});
request.Addresses.Add(new Address
{
Id = 2,
City = "NewYork",
Postcode = "3432",
Street = "NewYork Road"
});
request.Customers.Add(new Customer
{
Id = 1,
Name = "Jo",
Surname = "Bloggs",
});
request.Customers.Add(new Customer
{
Id = 1,
Name = "Jon",
Surname = "Bloggs2",
});
request.Customers.Add(new Customer
{
Id = 1,
Name = "Jonny",
Surname = "Bloggs3",
});
return request;
}
}
public class DataRequest
{
public DataRequest()
{
Customers = new List<Customer>();
Orders = new List<Order>();
Addresses = new List<Address>();
}
public List<Customer> Customers { get; set; }
public List<Order> Orders { get; set; }
public List<Address> Addresses { get; set; }
}
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
}
public class Order
{
public int Id { get; set; }
public string Name { get; set; }
public string OrderNo { get; set; }
}
public class Address
{
public int Id { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string Postcode { get; set; }
}
}
quick and dirty, here you go...
// ..
static class Program
{
static void Main()
{
var request = GetDataRequest();
//Get propertyValues for properties that are enumerable (i.e. lists,arrays etc)
var collectionProperties = request.GetType()
.GetProperties(BindingFlags.Instance | BindingFlags.Public)
.Where(propertInfo => propertInfo.PropertyType.GetInterfaces().Any(x => x == typeof(IEnumerable)))
.Select(p => p.GetValue(request, null))
.Cast<IEnumerable<object>>().ToList();
var totalCountForAllCollections = 0;
// iterate through the list of propertyValues
foreach (var collectionPropertyValue in collectionProperties)
{
totalCountForAllCollections += collectionPropertyValue.Count();
collectionPropertyValue.DoSomething();
}
System.Console.WriteLine("The total count for all collections is : {0}", totalCountForAllCollections);
System.Console.WriteLine("press any key to exit");
System.Console.ReadLine();
}
public static void DoSomething<T>(this IEnumerable<T> objectCollection)
{
//etc...
// N.B. you will have to use typeof(T) to implement logic specific to the type
// If the logic in this method is non-specific to the typeof(T) then Implement logic accordingly
System.Console.WriteLine("The type of the collection is: {0}", objectCollection.GetType());
System.Console.WriteLine("The count of items in this collection is:{0}", objectCollection.Count());
}
// ..
}
// ..

Get values from one list inside one list using lambda expression

i am new to lambda expression so i try to solve one problem .but i can't. so can anyone suggest solution for this.
i have one class customer. inside i created another 3 class and create observable collection for 3 classes.i create one observable collection for this customer
ObservableCollection<Customer> customer2;
public class Customer
{
public string CusName { get; set; }
public int CusAge { get; set; }
public ObservableCollection<Bankdetails> bankdetails;
public ObservableCollection<order> orderlist;
public ObservableCollection<orderdetails> orderdetailslist;
public class Bankdetails
{
public string Bankaccno { get; set; }
public string bankname { get; set; }
public int bankid { get; set; }
}
public class order
{
public string ordername { get; set; }
public string orderid { get; set; }
}
public class orderdetails
{
public string orderid { get; set; }
public string itemname { get; set; }
public int itemqty { get; set; }
}
}
i write one linq query for getting values from customer2.anyhow its working .like this i tried to write one lambda query but i can't.
here i adding some values to observable collection.
customer2 = new ObservableCollection<Customer>
{
new Customer()
{
CusName="nixon",CusAge=24,
bankdetails=new ObservableCollection<Customer.Bankdetails>
{
new Customer.Bankdetails()
{
bankid=12,bankname="axis",Bankaccno="09876534"
}
},
orderlist=new ObservableCollection<Customer.order>
{
new Customer.order
{
orderid="Od123",ordername="Express"
}
},
orderdetailslist=new ObservableCollection<Customer.orderdetails>
{
new Customer.orderdetails
{
orderid="Od123",itemname="cpu",itemqty=5
}
}
}
};
this is my linq query
var customer1 = from cus in customer2
from bank in cus.bankdetails
from ord in cus.orderlist
from orddet in cus.orderdetailslist
where ord.orderid == orddet.orderid
select new
{
cus.CusAge,cus.CusName,
bank.Bankaccno,bank.bankid,bank.bankname,
ord.ordername,
orddet.itemname,orddet.itemqty
};
then what will be the lambda query.pls anyone suggest .
Matt's solution extended with the where from the question would be:
var xxx = customer2.SelectMany(cus =>
cus.bankdetails.SelectMany(bank =>
cus.orderlist.SelectMany(ord =>
cus.orderdetailslist.Where(orddet => orddet.orderid == ord.orderid)
.Select(orddet => new
{
cus.CusAge,
cus.CusName,
bank.Bankaccno,
bank.bankname,
orddet.itemname,
orddet.itemqty
}
)
)
)
);
var xxx = customer2.SelectMany(cus =>
cus.bankdetails.SelectMany(bank =>
cus.orderlist.SelectMany(ord =>
cus.orderdetailslist.Select(orddet => new
{
cus.CusAge,
cus.CusName,
bank.Bankaccno,
bank.bankname,
orddet.itemname,
orddet.itemqty
}
)
)
)
);

Categories