Serialize Json Array with Asp.net MVC - c#

Could someone helpe me?
How can I code 'Shippings' class as an Array to get the json example below?
{
"seller_id": "123",
"amount": 100,
"order": {
"order_id": "1111",
"sales_tax": 0,
"product_type": "service"
},
"shippings": [{
"first_name": "John",
"phone_number": "5551999887766",
"shipping_amount": 3000,
"address": {
"street": "Street 35 Conts",
"number": "1000",
"complement": "ap1",
"postal_code": "90230060"
}
}],
"credit": {
"delayed": false,
"authenticated": false
}
}
I am doing this below, using asp.net mvc, but don't know how to get Shippings as Array [].
Can someone give me some exemplo or anything else... I'll appreciate.
var request = new GetNetRoot() {
SellerId = seller_id,
Amount = orderItens.Amount
Order = new GetNetPagOrder() {
OrderId = order.id.ToString(),
SalesTax = orderItens.Tax,
ProductType = orderItens.ProdType
},
Shippings = new GetNetPagShippings() {
FirstName = "",
PhoneNumber = usr.PhoneNumber,
ShippingAmount = orderItens.AmountShip,
Address = new GetNetPagAddress() {
Street = catEnd.IdEnderecoLogradouroNavigation.IdRuaNavigation.Nome,
Number = catEnd.NumEndereco,
Complement = catEnd.Complemento,
PostalCode = catEnd.IdEnderecoLogradouroNavigation.Cep
}
},
Credit = new GetNetPagCredit() {
Delayed = false,
Authenticated = false
}
};
var requestBody = JsonConvert.SerializeObject(request)

You should initialize Shippings like an array:
Shippings = new[] {
new GetNetPagShippings()
{
FirstName = "",
PhoneNumber = usr.PhoneNumber,
ShippingAmount = orderItens.AmountShip,
Address = new GetNetPagAddress()
{
Street = catEnd.IdEnderecoLogradouroNavigation.IdRuaNavigation.Nome,
Number = catEnd.NumEndereco,
Complement = catEnd.Complemento,
PostalCode = catEnd.IdEnderecoLogradouroNavigation.Cep
}
}
public class GetNetPagamentoRoot
{
...
public GetNetPagShippings[] Shippings { get; set; }
}

You can use array initializer syntax. Simplistic example would be array of int:
int[] myArray = new [] { 1, 2, 3 }
In your code Shippings should be initialized as an array.
var request = new GetNetRoot()
{
SellerId = seller_id,
Amount = orderItens.Amount
Order = new GetNetPagOrder()
{
OrderId = order.id.ToString(),
SalesTax = orderItens.Tax,
ProductType = orderItens.ProdType
},
// Array initializer with 2 elements.
Shippings = new[] {
new GetNetPagShippings()
{
FirstName = "",
PhoneNumber = usr.PhoneNumber,
ShippingAmount = orderItens.AmountShip,
Address = new GetNetPagAddress()
{
Street = catEnd.IdEnderecoLogradouroNavigation.IdRuaNavigation.Nome,
Number = catEnd.NumEndereco,
Complement = catEnd.Complemento,
PostalCode = catEnd.IdEnderecoLogradouroNavigation.Cep
}
},
new GetNetPagShippings()
{
FirstName = "",
PhoneNumber = usr.PhoneNumber,
ShippingAmount = orderItens.AmountShip,
Address = new GetNetPagAddress()
{
Street = catEnd.IdEnderecoLogradouroNavigation.IdRuaNavigation.Nome,
Number = catEnd.NumEndereco,
Complement = catEnd.Complemento,
PostalCode = catEnd.IdEnderecoLogradouroNavigation.Cep
}
}
},
Credit = new GetNetPagCredit()
{
Delayed = false,
Authenticated = false
}
};
var requestBody = JsonConvert.SerializeObject(request);

Your GetNetRoot outer class needs to define the "Shippings" property as a list or array of the GetNetPagShippings class as opposed to a single instance. When you serialize it to JSON, it will be represented as a JSON array of the object.
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
var myClassInstance = new MyOuterClass()
{
OuterProperty = "Outer Property",
MyInnerClassList = new List<MyInnerClass>()
{
new MyInnerClass()
{
InnerProperty = "Inner Property Item 1"
},
new MyInnerClass()
{
InnerProperty = "Inner Property Item 2"
}
}
};
string json = JsonConvert.SerializeObject(myClassInstance);
Console.WriteLine(json);
}
}
public class MyOuterClass
{
public string OuterProperty { get; set; }
public List<MyInnerClass> MyInnerClassList { get; set; }
}
public class MyInnerClass
{
public string InnerProperty { get; set; }
}
}

Related

Pass Object Array into Request Body

I have an object defined as follows.
public class ILT
{
public items items;
public options options;
}
public class items
{
public string course_code { get; set; }
public string session_code { get; set; }
public string date_name { get; set; }
public string date { get; set; }
public string time_start { get; set; }
public string time_end { get; set; }
public string location_name { get; set; }
public string location_address { get; set; }
public string location_country { get; set; }
public items() { }
public items(string course_code, string session_code, string date_name,
string date, string time_start, string time_end, string location_name,
string location_address, string location_country)
{
this.course_code = course_code;
this.session_code = session_code;
this.date_name = date_name;
this.date = date;
this.time_start = time_start;
this.time_end = time_end;
this.location_name = location_name;
this.location_address = location_address;
this.location_country = location_country;
}
}
I'm trying to pass the object into a RestfulAPI request body. The "items" attribute is supposed to be an array of objects.
The JSon should be formatted as follows:
{
"items": [
{
"course_id": 6,
"session_code": "my session code",
"session_name": "my session name",
"session_maximum_enrollments": 20,
"session_last_subscription_date": "2018-10-27",
"completion_type": "Evaluation",
"score_base": 100,
"date_name": "my date name",
"date": "2018-10-28",
"timezone": "America/New_York",
"time_start": "08:00:00",
"time_end": "12:00:00",
"location_name": "my location name",
"location_address": "10850 W. Park Place Suite 600, Milwaukee, WI 53225",
"location_country": "UNITED STATES OF AMERICA"
}
],
"options": {
"update_session_info": true
}
}
I'm having difficulty getting the items into an array. I'm trying to initialize the object into the request body as follows:
public bool CreateILT()
{
if (String.IsNullOrEmpty(Token))
Token = request.GetToken();
ILT classroom = new ILT
{
items = new items[0]
(
course_code = "APS_CLASSROOM",
session_code = "APS_CLASSROOM",
date_name = "August 27, 2018",
date = "2018-10-27",
time_start = "08:00:00",
time_end = "17:00:00",
location_name = "Crisis Prevention Institute",
location_address = "10850 W. Park Place Suite 600, Milwaukee, WI 53225",
location_country = "UNITED STATES OF AMERICA"
),
options = new options
{
update_session_info = true
}
};
dynamic response = request.Request_POST("/learn/v1/ilt/session/batch", Token, classroom);
if (response.data.success.ToString() == "True")
success = true;
return success;
}
Am I able to initialize an object array like this? I'm getting errors of various types when tweaking around. The above code errors out on each of the object's member's saying it does not exist in the current context.
Your class variable decleration is wrong. It stores object, not array/list of objects. And I could not see your options class. Do you have it right?
It should be declared as follows:
public class ILT
{
public List<items> items;
public options options;
}
And you should initialize it as follows:
ILT classroom = new ILT
{
items = new List<items> {
new item(
course_code = "APS_CLASSROOM",
session_code = "APS_CLASSROOM",
date_name = "August 27, 2018",
date = "2018-10-27",
time_start = "08:00:00",
time_end = "17:00:00",
location_name = "Crisis Prevention Institute",
location_address = "10850 W. Park Place Suite 600, Milwaukee, WI 53225",
location_country = "UNITED STATES OF AMERICA")
},
options = new options
{
update_session_info = true
}
};

MongoDb c# driver consecutive SelectMany

If I have objects, lets call them Group that has list of some other objects I will call it Brand, and this object has a list of objects called Model.
Is there a way to get only list of Models using MongoDb c# driver.
I tried using SelectMany multiple times but with no success. If I put more than one SelectMany I always get an empty list.
Code should be self-explanatory.
At the end is comment that explains what confuses me.
class Group
{
[BsonId(IdGenerator = typeof(GuidGenerator))]
public Guid ID { get; set; }
public string Name { get; set; }
public List<Brand> Brands { get; set; }
}
class Brand
{
public string Name { get; set; }
public List<Model> Models { get; set; }
}
class Model
{
public string Name { get; set; }
public int Produced { get; set; }
}
class Program
{
static void Main(string[] args)
{
MongoClient client = new MongoClient("mongodb://127.0.0.1:32768");
var db = client.GetDatabase("test");
var collection = db.GetCollection<Group>("groups");
var fca = new Group { Name = "FCA" };
var alfaRomeo = new Brand { Name = "Alfra Romeo" };
var jeep = new Brand { Name = "Jeep" };
var ferrari = new Brand { Name = "Ferrari"};
var laFerrari = new Model { Name = "LaFerrari", Produced = 4 };
var wrangler = new Model { Name = "Wrangler", Produced = 3 };
var compass = new Model { Name = "Compass", Produced = 8 };
var giulietta = new Model { Name = "Giulietta", Produced = 7 };
var giulia = new Model { Name = "Giulia", Produced = 8 };
var _4c = new Model { Name = "4C", Produced = 6 };
fca.Brands = new List<Brand> { ferrari, alfaRomeo, jeep };
ferrari.Models = new List<Model> { laFerrari };
jeep.Models = new List<Model> { wrangler, compass };
alfaRomeo.Models = new List<Model> { giulietta, giulia, _4c };
collection.InsertOne(fca);
Console.WriteLine("press enter to continue");
Console.ReadLine();
var models = collection.AsQueryable().SelectMany(g => g.Brands).SelectMany(b => b.Models).ToList();
Console.WriteLine(models.Count); //returns 0 I expected 6
Console.ReadLine();
}
}
Try
var models = collection.AsQueryable()
.SelectMany(g => g.Brands)
.Select(y => y.Models)
.SelectMany(x=> x);
Console.WriteLine(models.Count());
Working output (with extra Select())
aggregate([{
"$unwind": "$Brands"
}, {
"$project": {
"Brands": "$Brands",
"_id": 0
}
}, {
"$project": {
"Models": "$Brands.Models",
"_id": 0
}
}, {
"$unwind": "$Models"
}, {
"$project": {
"Models": "$Models",
"_id": 0
}
}])
OP Output without extra Select()
aggregate([{
"$unwind": "$Brands"
}, {
"$project": {
"Brands": "$Brands",
"_id": 0
}
}, {
"$unwind": "$Models"
}, {
"$project": {
"Models": "$Models",
"_id": 0
}
}])

Invalid JSON Response MVC API

I have one JSON Request as below :
{
"Products": [
{
"ProductId": 1,
"Barcode": "sample string 2",
"ProductExtId": "sample string 3",
"CategoryName": "sample string 4",
"BrandName": "sample string 5",
"StyleName": "sample string 6",
"ProductName": "sample string 7",
"Properies": [
{
"PropertyKey": "sample string 1",
"PropertyValue": "sample string 2"
},
{
"PropertyKey": "sample string 1",
"PropertyValue": "sample string 2"
}
]
}
]
}
As per above JSON Request my Class AS BELOW :
public class Propery
{
public string PropertyKey { get; set; }
public string PropertyValue { get; set; }
}
public class Product
{
public int ProductId { get; set; }
public string Barcode { get; set; }
public string ProductExtId { get; set; }
public string CategoryName { get; set; }
public string BrandName { get; set; }
public string StyleName { get; set; }
public string ProductName { get; set; }
public List<Propery> Properies { get; set; }
}
public class RootObject
{
public List<Product> Products { get; set; }
//public Product Products { get; set; }
}
My DataController :
[HttpGet]
[ResponseType(typeof(List<productGetData_Result>))]
public async Task<IHttpActionResult> GetProductData()
{
List<Product> prodata = new List<Product>();
var list = db.productGetData().ToList();
foreach (var listdata in list)
{
Product pdata = new Product();
pdata.Barcode = listdata.StockNo;
pdata.ProductExtId = "";
pdata.CategoryName = listdata.Class2Descr;
pdata.BrandName = listdata.Class1Descr;
pdata.StyleName = listdata.SubClass1Cd;
pdata.ProductName = listdata.AnalCode2;
pdata.ProductSubTitle = listdata.AnalCode2;
pdata.ProductImage = listdata.ImageID;
pdata.Color = listdata.SubClass2Cd;
pdata.ColorImage = "";
pdata.FabricName = "";
pdata.SeasonName = listdata.AnalCode3;
pdata.GroupName = listdata.Class2Descr;
pdata.SearchKeywords = listdata.ItemDesc;
pdata.MRP = Convert.ToInt16(listdata.Retail_Price);
pdata.BuyingPrice = Convert.ToInt16(listdata.CurrentCost);
pdata.StockQty = Convert.ToInt16(listdata.StockQty);
pdata.AllowedQty = Convert.ToInt16(listdata.StockQty);
pdata.ProductFor = "";
pdata.AgeType = "";
pdata.AgeFrom = 1;
pdata.AgeTo = 2;
pdata.Age = "";
pdata.KeyFeatures = "";
pdata.Description = listdata.ItemDesc;
pdata.Condition = "";
pdata.Disclaimer = "";
pdata.IsGiftAvailable = true;
pdata.IsPopular = true;
pdata.IsNewArrival = true;
pdata.IsSponsored = true;
pdata.IsShippingAvailable = true;
pdata.CompanyName = "Siddharth Creation";
pdata.ProductAgeDate = Convert.ToDateTime(listdata.Dateinsert);
pdata.IsActive = true;
pdata.IntegrationFor = "Siddharth Creation";
prodata.Add(pdata);
}
using (HttpClient client = new HttpClient())
{
//HttpRequestMessage requestmsg = new HttpRequestMessage(HttpMethod.Get, "http://retailerintegration.zoomi.in");
//requestmsg.Headers.Add("token", "");
string stringData = JsonConvert.SerializeObject(prodata);
client.BaseAddress = new Uri("");
MediaTypeWithQualityHeaderValue contentType =new MediaTypeWithQualityHeaderValue("application/json");
client.DefaultRequestHeaders.Accept.Add(contentType);
var contentData = new StringContent(stringData, System.Text.Encoding.UTF8, "application/json");
HttpResponseMessage response = client.PostAsync("/api/Product/ProductSave", contentData).Result;
var Message = response.Content.ReadAsStringAsync().Result;
}
return Ok(prodata);
}
AS per above class and DataController, i am returning below JSON Response :
[
{
"ProductId": 0,
"Barcode": "170604658",
"ProductExtId": "",
"CategoryName": "MENS SHIRTS",
"BrandName": "KRISS",
"StyleName": "PRN",
"ProductName": "FORMAL WEAR",
"Properies": null
},
{
"ProductId": 0,
"Barcode": "170604657",
"ProductExtId": "",
"CategoryName": "MENS SHIRTS",
"BrandName": "KRISS",
"StyleName": "PRN",
"ProductName": "FORMAL WEAR",
"Properies": null
}
]
currently i am returning product class & its items as per above.
So, now how to pass root object in datacontroller to get the JSON Response as per JSON Request.
List<Product> prodata = new List<Product>();
RootObject _rootObject = new RootObject();
var list = db.productGetData().ToList();
foreach (var listdata in list)
{
var _listOfProperties = new List<Property>();
//if product list contains data of properties
foreach(var _prop in listdata.Properies)
{
var property = new Property();
property.PropertyKey = _prop.PropertyKey;
property.PropertyValue = _prop.PropertyValue;
_listOfProperties.Add(property);
}
Product pdata = new Product();
pdata.Properties = _listOfProperties;
prodata.Add(pdata);
}
_rootObject.Products = prodata;
and now serialize it
string stringData = JsonConvert.SerializeObject(_rootObject);

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 create a JsonPatchDocument from comparing two c# objects?

Given I have two c# objects of the same type, I want to compare them to create a JsonPatchDocument.
I have a StyleDetail class defined like this:
public class StyleDetail
{
public string Id { get; set; }
public string Code { get; set; }
public string Name { get; set; }
public decimal OriginalPrice { get; set; }
public decimal Price { get; set; }
public string Notes { get; set; }
public string ImageUrl { get; set; }
public bool Wishlist { get; set; }
public List<string> Attributes { get; set; }
public ColourList Colours { get; set; }
public SizeList Sizes { get; set; }
public ResultPage<Style> Related { get; set; }
public ResultPage<Style> Similar { get; set; }
public List<Promotion> Promotions { get; set; }
public int StoreStock { get; set; }
public StyleDetail()
{
Attributes = new List<string>();
Colours = new ColourList();
Sizes = new SizeList();
Promotions = new List<Promotion>();
}
}
if I have two StyleDetail objects
StyleDetail styleNew = db.GetStyle(123);
StyleDetail styleOld = db.GetStyle(456);
I now want to create a JsonPatchDocument so I can send the differences to my REST API... How to do this??
JsonPatchDocument patch = new JsonPatchDocument();
// Now I want to populate patch with the differences between styleNew and styleOld - how?
in javascript, there is a library to do this https://www.npmjs.com/package/rfc6902
Calculate diff between two objects:
rfc6902.createPatch({first: 'Chris'}, {first: 'Chris', last:
'Brown'});
[ { op: 'add', path: '/last', value: 'Brown' } ]
but I am looking for a c# implementation
Let's abuse the fact that your classes are serializable to JSON!
Here's a first attempt at a patch creator that doesn't care about your actual object, only about the JSON representation of that object.
public static JsonPatchDocument CreatePatch(object originalObject, object modifiedObject)
{
var original = JObject.FromObject(originalObject);
var modified = JObject.FromObject(modifiedObject);
var patch = new JsonPatchDocument();
FillPatchForObject(original, modified, patch, "/");
return patch;
}
static void FillPatchForObject(JObject orig, JObject mod, JsonPatchDocument patch, string path)
{
var origNames = orig.Properties().Select(x => x.Name).ToArray();
var modNames = mod.Properties().Select(x => x.Name).ToArray();
// Names removed in modified
foreach (var k in origNames.Except(modNames))
{
var prop = orig.Property(k);
patch.Remove(path + prop.Name);
}
// Names added in modified
foreach (var k in modNames.Except(origNames))
{
var prop = mod.Property(k);
patch.Add(path + prop.Name, prop.Value);
}
// Present in both
foreach (var k in origNames.Intersect(modNames))
{
var origProp = orig.Property(k);
var modProp = mod.Property(k);
if (origProp.Value.Type != modProp.Value.Type)
{
patch.Replace(path + modProp.Name, modProp.Value);
}
else if (!string.Equals(
origProp.Value.ToString(Newtonsoft.Json.Formatting.None),
modProp.Value.ToString(Newtonsoft.Json.Formatting.None)))
{
if (origProp.Value.Type == JTokenType.Object)
{
// Recurse into objects
FillPatchForObject(origProp.Value as JObject, modProp.Value as JObject, patch, path + modProp.Name +"/");
}
else
{
// Replace values directly
patch.Replace(path + modProp.Name, modProp.Value);
}
}
}
}
Usage:
var patch = CreatePatch(
new { Unchanged = new[] { 1, 2, 3, 4, 5 }, Changed = "1", Removed = "1" },
new { Unchanged = new[] { 1, 2, 3, 4, 5 }, Changed = "2", Added = new { x = "1" } });
// Result of JsonConvert.SerializeObject(patch)
[
{
"path": "/Removed",
"op": "remove"
},
{
"value": {
"x": "1"
},
"path": "/Added",
"op": "add"
},
{
"value": "2",
"path": "/Changed",
"op": "replace"
}
]
You could use my DiffAnalyzer. It's based on reflection and you can configure the depth you want to analyze.
https://github.com/rcarubbi/Carubbi.DiffAnalyzer
var before = new User { Id = 1, Name="foo"};
var after= new User { Id = 2, Name="bar"};
var analyzer = new DiffAnalyzer();
var results = analyzer.Compare(before, after);
You can use this
You can install using NuGet, see SimpleHelpers.ObjectDiffPatch at NuGet.org
PM> Install-Package SimpleHelpers.ObjectDiffPatch
Use:
StyleDetail styleNew = new StyleDetail() { Id = "12", Code = "first" };
StyleDetail styleOld = new StyleDetail() { Id = "23", Code = "second" };
var diff = ObjectDiffPatch.GenerateDiff (styleOld , styleNew );
// original properties values
Console.WriteLine (diff.OldValues.ToString());
// updated properties values
Console.WriteLine (diff.NewValues.ToString());

Categories