Add default Items in class - c#

I have a class and want to add some data on construction so i can used it without using database like :
public partial class ActionTypeList
{
public ActionTypeList()
{
new ActionTypeList { Id= "2", FName= "hanumanji" };
new ActionTypeList { Id= "4", FName= "temples" };
new ActionTypeList { Id= "38", FName= "books" };
new ActionTypeList { Id= "28", FName= "stories" };
}
public string Id{ get; set; }
public string FName{ get; set; }
}
I just given an example, how to do it I don't know.

If you need some data to work with then you will want to create separate instances outside the class not in it, that is a bad practice. If you truly feel that you must have data in this class then add a static method to get some your default stuff.
public partial class ActionType
{
public string Id { get; set; }
public string FName { get; set; }
public static IEnumerable<ActionType> GetDefaultActionTypes() {
return new List<ActionType> {
new ActionType { Id = "2", FName = "hanumanji" },
new ActionType { Id = "4", FName = "temples" },
new ActionType { Id = "28", FName = "books" },
new ActionType { Id = "38", FName = "stories" },
};
}
}
You can then use the static method like this
var myDefaultActionTypes = ActionType.GetDefaultActionTypes();

Create a new class ActionType and store your items in the ActionTypeList:
public class ActionType {
public ActionType() {
}
public string Id { get; set; }
public string FName { get; set; }
}
public class ActionTypeList : List<ActionType> {
public ActionTypeList() {
Add(new ActionType() { Id = "2", FName = "hanumanji" });
Add(new ActionType { Id = "4", FName = "temples" });
Add(new ActionType { Id = "38", FName = "books" });
Add(new ActionType { Id = "28", FName = "stories" });
}
}

You can define a static method inside of your class
public static List<ActionTypeList> GetActionTypes()
{
return new List<ActionTypeList>
{
new ActionTypeList { Id= "2", FName= "hanumanji" };
new ActionTypeList { Id= "4", FName= "temples" };
new ActionTypeList { Id= "38", FName= "books" };
new ActionTypeList { Id= "28", FName= "stories" };
}
}
And whenever you want to get your sample list you can call this method.
var list = ActionTypeList.GetActionTypes();

Related

Fluent Assertions between two collection class

I have a class with collection class inside
public class SearchResult {
public int Id { get; set; }
public int Total { get; set; }
public IEnumerable<Book> Books { get; set; }
}
public class Book {
public int BookId { get; set; }
public string BookName { get; set; }
public string Publisher { get; set; }
public string ISBNCode { get; set; }
public IList<catagory> Catagories { get; set; }
}
I have a question , if I create the other object , with same structure of SearchResult and I want to copy SearchResult to SearchResultClone, which inside Books only copy BookId and BookName remain is empty.
Just like below
{
"Id": 0,
"Total": 3,
"Books": [
{
"BookId": 1,
"BookName": "Book A",
"Publisher": "",
"ISBNCode": "",
"Catagories": []
},
{
"BookId": 2,
"BookName": "Book B",
"Publisher": "",
"ISBNCode": "",
"Catagories": []
},
{
"BookId": 3,
"BookName": "Book C",
"Publisher": "",
"ISBNCode": "",
"Catagories": []
}
]
}
Event the original result have value of Publisher, ISBNCode ..etc
How to do it in LINQ ?
My second question is , if I want to make a fluent assertions as above object
var result = await sut.search(query);
result.Should().BeEquivalentTo ({the SearchResultClone })
How to write this fluent assertion ?
You need to create new instances of the classes based on the old instances:
var ans = result.Select(sr => new SearchResult {
Id = sr.Id,
Total = sr.Total,
Books = sr.Books.Select(b => new Book { BookId = b.BookId, BookName = b.BookName }).ToList()
}).ToList();
result.Should().BeEquivalentTo ({the SearchResultClone })
How to write this fluent assertion ?
If your expectation (the object you pass into BeEquivalentTo) is of the type SearchResult, then FA will try to compare the empty values of ISBN to the same property on the sut. You can solve that by doing something like:
sut.Should().BeEquivalentTo(new
{
Id = "some value",
Total = 123,
Books = new[]
{
new
{
BookId = 123,
BookName = "some book"
}
}
});

json format output from JavaScriptSerializer

var singleItems = new List<Products>();
singleItems.Add(new Products() { product_id = 1, title = "Bryon Hetrick", price = 50 });
singleItems.Add(new Products() { product_id = 2, title = "Nicole Wilcox", price = 20 });
var serializer = new JavaScriptSerializer();
var serializedResult = serializer.Serialize(serializer);
From above example code i am getting Json output like bellow.
[{"product_id":1,"title":"Bryon Hetrick","price":50},
{"product_id":2,"title":"Nicole Wilcox","price":20}]
But my Json need one more value called- "config" also i need whole data formatted exactly like bellow. How to edit my c# code to achieve that value?
{ "products":[{"product_id":"B071H6TBM5","title":"New Iphone 5S","price":"23.45"},{"product_id":"B071DM968J","title":"Iphone 4 old","price":"23.45"}],"config":{"token":"","Site":"Us","Mode":"ListMyItem"}}
You could make a Config class with the properties you require and then a composite class with Prodcuts and Config, i.e. ProductConfig:
public class Products
{
public string product_id { get; set; }
public string title { get; set; }
public string price { get; set; }
}
public class Config
{
public string token { get; set; }
public string site { get; set; }
public string mode { get; set; }
}
public class ProductConfig
{
public List<Products> Products { get; set; }
public Config Config { get; set; }
}
You can then create/populate the ProductConfig class with the new properties.
public string SerializeProductConfig()
{
ProductConfig pc = new ProductConfig();
pc.Config = new Config { token = "DDTest", site = "US", mode = "Test Mode" };
pc.Products = new List<Products>();
pc.Products.Add(new Products() { product_id = "1", title = "Bryon Hetrick", price = "50" });
pc.Products.Add(new Products() { product_id = "2", title = "Nicole Wilcox", price = "20" });
var serializer = new JavaScriptSerializer();
return serializer.Serialize(pc);
}
and serialize the ProductConfig object using the JavaScript serializer or NewtonSoft which will give you the following JSON
{ // ProductConfig
"Products": [
{
"product_id": "1",
"title": "Bryon Hetrick",
"price": "50"
},
{
"product_id": "2",
"title": "Nicole Wilcox",
"price": "20"
}
],
"config": {
"token": "DDTest",
"site": "US",
"mode": "Test Mode"
}
}

Create json object with multiple array in c#

I want to create JSON object with following format:-
{
"result": [
{
"name": "John",
"address": "US",
},
{
"name": "Josh",
"address": "Japan",
}
],
"error": [
{
"message": "error-message"
}
],
"success": [
{
"message": "success-message"
}
]
}
I have tried the following, but it doesn't help me.
dynamic record = new { result = new {name="", address=""},
error = new {message=""},
success = new {message=""} };
Update 1:-
Here is my code:-
List addressList = new List();
// Loop over items within the container and URI.
foreach (var item in items)
{
dynamic record = new { result = new object[] {
new {name = item.name, address = item.address} } };
addressList.Add(record);
}
Result:-
[ {
"result": [
{
"name": "John",
"address": "US"
}
]
},
{
"result": [
{
"name": "Jack",
"address": "CA"
}
]
}
]
Expected json result:-
[{
"result": [{
"name": "John",
"address": "US"
}]
},
{
"result": [{
"name": "Jack",
"address": "CA"
}],
"error": [{
"message": "error-message"
}],
"success": [{
"message": "success-message"
}]
}
]
How do I update my code to get above expected json result?
You...create arrays. You're not doing that. You're creating individual objects.
Something along the lines of:
dynamic record = new {
result = new object[] {
new {name = "John", address = "US"},
new {name = "Josh", address = "Japan"}
},
error = new object[] /*...*/,
success = new object[] /*...*/
};
If you want exactly JSON, then newtonsoft.Json makes it easier:
Json json = new Json();
json.result = new object[] {
new {name = "John", address = "US"},
new {name = "Josh", address = "Japan"}
};
// json.error = ... and so on
string output = JsonConvert.SerializeObject(product);
The output you will have is:
{
"result": [
{
"name": "John",
"address": "US",
},
{
"name": "Josh",
"address": "Japan",
}
],
"error": [
{
...
}
]
}
To deserialize it back, use:
Json deserializedJson = JsonConvert.DeserializeObject<Json>(output);
you are not creating an array
if you want to create JSON arrays from c# you have to use the following POCO
public class Result
{
public string name { get; set; }
public string address { get; set; }
}
public class Error
{
public string message { get; set; }
}
public class Success
{
public string message { get; set; }
}
public class RootObject
{
public List<Result> result { get; set; }
public List<Error> error { get; set; }
public List<Success> success { get; set; }
}
and then use Json.net
var json = JsonConvert.SerializeObject( "your instance of the root Object")
//You need to make this class structure first
public class Response
{
public List<Result> result { get; set; }
public List<Error> error { get; set; }
public List<Success> success { get; set; }
}
public class Result
{
public string name { get; set; }
public string address { get; set; }
}
public class Error
{
public string message { get; set; }
}
public class Success
{
public string message { get; set; }
}
// And then you can use it like this
var response = new Response()
{
result = new List<Result>
{
new Result() {name = "Jhon", address = "US"},
new Result() {name = "Jhon", address = "US"},
},
error = new List<Error>()
{
new Error() {message = "error-message 1"},
new Error() {message = "error-message 2"}
},
success = new List<Success>()
{
new Success(){message = "success-message 1"},
new Success(){message = "success-message 2"},
}
};
The Model Class
public class MegaMenu
{
public int department_id { get; set; }
public string department_name { get; set; }
public List<SectionListData> sectionListData { get; set; }
}
public class SectionListData
{
public int section_id { get; set; }
public string section_name { get; set; }
public List<ItemHeadList> itemHeadList { get; set; }
}
public class ItemHeadList
{
public int item_head_id { get; set; }
public string item_name { get; set; }
}
public class WrapperMegaMenu
{
public List<MegaMenu> megaMenuList { get; set; }
public string error { get; set; }
}
The Services
dept_result is the array of all department,section_result is the array of all section,Item_result is the array of all items
List<MegaMenu> listmenu = new List<MegaMenu>();
foreach (var each_dept in dept_result)
{
MegaMenu megaMenu = new MegaMenu();
megaMenu.department_id = each_dept.shopdepartment_id;
megaMenu.department_name = each_dept.name_en;
var temSectionList = section_result
.Where(item => item.shopdepartment_id == each_dept.shopdepartment_id).ToList().Select(sectionData => new SectionListData
{
section_id = sectionData.shopsection_id,
section_name = sectionData.name_en,
itemHeadList = Item_result.Where(itemHead => itemHead.shopsection_id == sectionData.shopsection_id).ToList().Select(itemHeadData => new ItemHeadList {
item_head_id = itemHeadData.item_head_id,
item_name = itemHeadData.name_en
}).ToList()
}).ToList();
megaMenu.sectionListData = temSectionList;
listmenu.Add(megaMenu);
}
//wrapperDept.departmentList = dept_result.ToList();
wrapper.megaMenuList = listmenu.ToList();
Result
{
"megaMenuList": [
{
"department_id": 71,
"department_name": "Baby's Hygiene",
"sectionListData": [
{
"section_id": 56,
"section_name": "Diapers",
"itemHeadList": []
},
{
"section_id": 57,
"section_name": "Wipes",
"itemHeadList": [
{
"item_head_id": 142,
"item_name": "Telivision"
}
]
}
]
}
]
}

How can I declare and populate a collection at the same time?

I am trying the following:
public class ResultDTO
{
public int Id { get; set; }
public string Text { get; set; }
public int AnswerId { get; set; }
public string AnswerText { get; set; }
}
List<ResultDTO> result1 = new List<ResultDTO> () {
new ResultDTO () { Id:1, Text: "abc", AnswerId: "1", AnswerText: "Aab1" },
new ResultDTO () { Id:1, Text: "abc", AnswerId: "2", AnswerText: "Aab2" },
new ResultDTO () { Id:1, Text: "abc", AnswerId: "3", AnswerText: "Aab3" },
new ResultDTO () { Id:1, Text: "def", AnswerId: "4", AnswerText: "Aab4" },
new ResultDTO () { Id:1, Text: "def", AnswerId: "5", AnswerText: "Aab5" },
new ResultDTO () { Id:1, Text: "def", AnswerId: "6", AnswerText: "Aab6" }
}
This gives me many syntax errors in the IDE. Can someone advise what I am doing wrong?
This is not JSon object and array. the property can be assigned using = operator.
List<ResultDTO> result1 = new List<ResultDTO> () {
new ResultDTO () { Id=1, Text= "abc", AnswerId= 1, AnswerText= "Aab1" },
....
}
I would like to suggest you to create constructor which is having parameters for properties;
public class ResultDTO
{
public int Id { get; private set; }
public string Text { get; set; }
public int AnswerId { get; set; }
public string AnswerText { get; set; }
public ResultDTO(int id, string _text, int ansId, string ansText)
{
Id=id;
Text = _text;
AnswerId = ansId;
AnswerText = ansText;
}
}
then initialize the list like this.
List<ResultDTO> result1 = new List<ResultDTO> () {
new ResultDTO (1,"abc",1,"Aab1"),
new ResultDTO (1,"abc",2,"Aab2"),
new ResultDTO (1,"abc",3,"Aab3"),
....
}
This will give you some advantage when you specify the property readonly. Look at the above class I have declared Id property publicly readable and cannot be set out of the class.
When initializing a class you need to use = instead of :
public class ResultDTO
{
public int Id { get; set; }
public string Text { get; set; }
public int AnswerId { get; set; }
public string AnswerText { get; set; }
}
List<ResultDTO> result1 = new List<ResultDTO> () {
new ResultDTO () { Id=1, Text= "abc", AnswerId= 1, AnswerText= "Aab1" },
new ResultDTO () { Id=1, Text= "abc", AnswerId= 2, AnswerText= "Aab2" },
new ResultDTO () { Id=1, Text= "abc", AnswerId= 3, AnswerText= "Aab3" },
new ResultDTO () { Id=1, Text= "def", AnswerId= 4, AnswerText= "Aab4" },
new ResultDTO () { Id=1, Text= "def", AnswerId= 5, AnswerText= "Aab5" },
new ResultDTO () { Id=1, Text= "def", AnswerId= 6, AnswerText= "Aab6" }
}

Adding data to ObservableCollection in WPF

I have some problem here. Here it is:
I have this class
public class NewsFeedResources
{
public string Name { get; set; }
public string Id { get; set; }
public string Message { get; set; }
public static ObservableCollection<NewsFeedResources> _newsfeed = new ObservableCollection<NewsFeedResources>
{
new NewsFeedResources { Name = "Joe", Id = "1", Message="Foo" },
new NewsFeedResources { Name = "Wandy", Id = "2", Message="Bar" },
new NewsFeedResources { Name = "Yuliana", Id = "3", Message="Baz" },
new NewsFeedResources { Name = "Hardi", Id = "4", Message="Baz" },
};
public static ObservableCollection<NewsFeedResources> newsFeedResources
{ get { return _newsfeed; }
}
}
If I have another data such as
Name=John, Id=5, Message="Stack overflow"
Name=Jane, Id=6, Message="Hello world"
How can I add the data into the class, but not from the constructor? Thanks for the help
ObservableCollection exposes the Collection<T>.Add Method:
Adds an object to the end of the Collection.
So you'd have:
_newsfeed.Add(new NewsFeedResources {Name = "John",
Id = 5,
Message = "Stack overflow"});
_newsfeed.Add(new NewsFeedResources {Name = "Jane",
Id = 6,
Message = "Hello world"});
(typed from memory)
call a function from constructor or anywhere as u like and add items like below
NewsFeedResources NFR=new NewsFeedResources(){Name=John, Id=5, Message="Stack overflow"};
_newsfeed.add(NFR);
NewsFeedResources NFR1 =new NewsFeedResources(){Name=Jane, Id=6, Message="Hello world"};
_newsfeed.add(NFR);

Categories