How insert new array into existing embedded array in C#? - arrays

I have a little bit problem with an data update in mongoDB. I have an array embedded in an other array who is embedded in a document (yaaaaay ^^). So my collection is like that :
{
"_id" : ObjectId("5965e0b4f1042c4c3f1d8edc"),
"Builder" : "Google",
"Family" : "Car",
"ProductName" : "ABCD_80A_PU170017",
"ProductNumber" : "N 1",
"Test" : [
{
"Num_Test" : "PU170017",
"Date_Start" : ISODate("2017-07-12T00:00:00.000Z"),
"Bench": [
{
"Room": 1,
"Num" : 1,
"Designation" : "AC1; AC3",
"IP" : "123.456.78.9",
"Capacity" : 12,
}
],
"User" : [
{
"Number" : "EBBW396",
"Password" : "titi",
"Name" : "NDJO",
"Surname" : "Charles",
"Tel" : "06XXXXXX",
"isAdmin" : true
}
]
}
]
}
And i want to insert a new array embedded in "Test".
So i found my happiness here : https://docs.mongodb.com/getting-started/csharp/update/ AND How to use C# to insert document into existing embedded documents?
And i have write this code :
static void Main(string[] args)
{
IMongoClient client = new MongoClient("mongodb://10.194.157.199:27017");
IMongoDatabase database = client.GetDatabase("PINEA");
IMongoCollection<Product> collection = database.GetCollection<Product>("Product");
var filter = Builders<Product>.Filter.Eq("Test.Num_Test", "PU170017");
var meter = new Meter();
meter.Value= 12;
meter.Date = DateTime.Now;
var meterList = new List<Meter>();
meterList.Add(meter);
var update = Builders<Product>.Update.Push("Result", new Result
{
MeterList = meterList
});
var result = collection.UpdateOne(filter, update);
}
But nothing happens, nothing has added or modified. I miss something important but i don't understand what is it.
Finally, here are my classes:
class Result
{
public List<Meter> MeterList { get; set; }
public List<Problem> Problem { get; set; }
}
class Meter
{
public int? Value { get; set; }
public DateTime? Date { get; set; }
}
class Test
{
public string Num_Test { get; set; }
public DateTime? Date_Start { get; set; }
public List<Bench> Bench { get; set; }
public List<User> User { get; set; }
public List<Result> Result { get; set; }
}
class Product
{
public string Builder { get; set; }
public string Fammily { get; set; }
public string ProductName { get; set; }
public string ProductNumber { get; set; }
public List<Test> Test { get; set; }
}
To explain the context, I need to update the array "result" regularly and maintain data arborescence like that. After the end of the test, data aren't modify anymore.
PS : I'm still a student but I work part time
Thanks

Related

ASP NET Core reading complex configuration with array and JsonConverter

I have this appsettings.json
"TopLevel": [
{
"Name": "Name",
"TopChild": {
"File": {
"URL": "SomeUrl",
"Username": "Admin",
"Password": "123"
}
},
"TopChild2": [
{
"Name": "SimpleMapper",
"Mapper": {
"Param1": "",
"Param2": "",
"Param3": ""
}
},
{
"Name": "SimpleFileConverter",
"Converter": {
"ToWhat": "",
"Writer": ""
}
}
],
"TopChild3": {
"SomeProperty3": {
"WhatIsThis": "",
"SomeProp": "",
"Password": ""
}
}
},
{
"Name": "Name",
"TopChild": {
"DB": {
"ConnectionString": "String",
"Username": "Admin",
"Password": "123"
}
},
"TopChild2": [
{
"Name": "SomeConverter",
"Converter": {
"Param1": "",
"Param2": ""
}
},
{
"Name": "SimpleFileConverter",
"Mapper": {
"Param1": "",
"Param2": "",
"Param3": ""
}
}
],
"TopChild3": {
"SomePropety4": {
"SomeProp7": "",
"Password": ""
}
}
}
]
And this is the code I wrote for a model
public class TopLevelConfigRoot
{
[JsonProperty("TopLevel")]
public List<TestObject> TopLevel { get; set; }
}
public class TestObject
{
[JsonProperty("Name")]
public string Name { get; set; }
[JsonProperty("TopChild")]
[JsonConverter(typeof(TopChildConverter))]
public TopChildBase TopChild { get; set; }
[JsonProperty("TopChild2")]
[JsonConverter(typeof(TopChild2Converter))]
public List<TopChild2> TopChild2 { get; set; }
[JsonProperty("TopChild3")]
[JsonConverter(typeof(TopChild3Converter))]
public TopChild3Base TopChild3 { get; set; }
}
public abstract class TopChildBase { }
public abstract class TopChild3Base { }
public class File : TopChildBase
{
[JsonProperty("URL")]
public string URL { get; set; }
[JsonProperty("Username")]
public string Username { get; set; }
[JsonProperty("Password")]
public string Password { get; set; }
}
public class DB : TopChildBase
{
[JsonProperty("ConnectionString")]
public string ConnectionString { get; set; }
[JsonProperty("Username")]
public string Username { get; set; }
[JsonProperty("Password")]
public string Password { get; set; }
}
public interface ITopChild2
{
public string Name { get; set; }
public ITopChild2Type ITopChild2Type { get; set; }
}
public class TopChild2 : ITopChild2
{
[JsonProperty("Name")]
public string Name { get; set; }
[JsonProperty("ITopChild2Type")]
public ITopChild2Type ITopChild2Type { get; set; }
}
public abstract class ITopChild2Type
{ }
public class Mapper : ITopChild2Type
{
[JsonProperty("Param1")]
public string Param1 { get; set; }
[JsonProperty("Param2")]
public string Param2 { get; set; }
[JsonProperty("Param3")]
public string Param3 { get; set; }
}
public class Converter : ITopChild2Type
{
[JsonProperty("Param1")]
public string Param1 { get; set; }
[JsonProperty("Param2")]
public string Param2 { get; set; }
}
public class SomeProperty3 : TopChild3Base
{
[JsonProperty("WhatIsThis")]
public string WhatIsThis { get; set; }
[JsonProperty("SomeProp")]
public string SomeProp { get; set; }
[JsonProperty("Password")]
public string Password { get; set; }
}
public class SomePropety4 : TopChild3Base
{
[JsonProperty("SomeProp7")]
public string SomeProp7 { get; set; }
[JsonProperty("Password")]
public string Password { get; set; }
}
public class TopChildConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(TopChildBase);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JObject jo = JObject.Load(reader);
if (jo.ContainsKey(nameof(File)))
{
return jo[nameof(File)].ToObject<File>();
}
else if (jo.ContainsKey(nameof(DB)))
{
return jo[nameof(DB)].ToObject<DB>();
}
return null;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
public class TopChild3Converter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(TopChild3Base);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JObject jo = JObject.Load(reader);
if (jo.ContainsKey(nameof(SomeProperty3)))
{
return jo[nameof(SomeProperty3)].ToObject<SomeProperty3>();
}
else if (jo.ContainsKey(nameof(SomePropety4)))
{
return jo[nameof(SomePropety4)].ToObject<SomePropety4>();
}
return null;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
public class TopChild2Converter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(TopChild2);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JArray ja = JArray.Load(reader);
List<TopChild2> topChild2List = new List<TopChild2>();
foreach (var item in ja)
{
JObject jObject = (JObject)item;
TopChild2 TopChild2 = null;
string name = jObject[nameof(TopChild2.Name)].ToString();
if (jObject.ContainsKey(nameof(Mapper)))
{
var root = jObject[nameof(Mapper)];
Mapper mapper = new Mapper
{
Param1 = root[nameof(Mapper.Param1)].Value<string>(),
Param2 = root[nameof(Mapper.Param2)].Value<string>(),
Param3 = root[nameof(Mapper.Param3)].Value<string>()
};
TopChild2 = new TopChild2 { Name = name, ITopChild2Type = mapper };
}
else if (jObject.ContainsKey(nameof(Converter)))
{
var root = jObject[nameof(Converter)];
Converter converter = new Converter
{
Param1 = root[nameof(Converter.Param1)].Value<string>(),
Param2 = root[nameof(Converter.Param2)].Value<string>()
};
TopChild2 = new TopChild2 { Name = name, ITopChild2Type = converter };
}
topChild2List.Add(TopChild2);
}
return topChild2List;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
And now with that model I've tried using any known implementation of config inside of controller.
The only thing I came up is inserting IConfiguration via Dependency Injection and use _config = config;
And then selected it by
var section = _config.GetSection("TopLevel");
and then used it like this
var itemArray = section.AsEnumerable();
How can I then use this itemArray to convert this to either model, or a JsonString which i will then easily serialize it with Newtonsoft
var t = JsonConvert.DeserializeObject<TopLevelConfigRoot>(jsonString);
But I haven't find a way to map this itemArray to model I provided, nor I had success with writing recursive method to actually map it to JsonString.
Converter I wrote is
public string ConvertBackToJSonString(KeyValuePair<string, string>[] itemArray)
{
var root = new JObject();
var current = root;
foreach (var item in itemArray)
{
var parts = item.Key.Split(':');
var key = parts[parts.Length - 1];
var parent = current;
for (int i = 0; i < parts.Length - 1; i++)
{
var part = parts[i];
if (!current.ContainsKey(part))
current.Add(part, new JObject());
current = (JObject)current[part];
}
if (!string.IsNullOrEmpty(item.Value))
current.Add(key, new JValue(item.Value));
else
current.Add(key, new JObject());
current = parent;
}
return JsonConvert.SerializeObject(root, Formatting.Indented);
}
But that didn't work. How should this be approached to/done?
You could bind the section to a model directly with IConfigration.Bind() method
For example,in your case :
public class BindTarget
{
public string Name { get; set; }
public SomeChildClass1 TopChild { get; set; }
public List<SomeChildClass2> TopChild2 { get; set; }
public SomeChildClass3 TopChild3 { get; set; }
}
public class SomeChildClass1
{
public File File { get; set; }
public DB DB { get; set; }
}
public class SomeChildClass2
{
public string Name { get; set; }
public Mapper Mapper { get; set; }
public Converter Converter { get; set; }
}
public class SomeChildClass3
{
public SomeProperty3 SomeProperty3 { get; set; }
public SomePropety4 SomePropety4 { get; set; }
}
bind as below:
var targetobj = new List<BindTarget>();
Configuration.GetSection("TopLevel").Bind(targetobj);
var str = JsonConvert.SerializeObject(targetobj,new JsonSerializerSettings() { NullValueHandling=NullValueHandling.Ignore});
result:
The document related

Nested List Item reflecting type error

I have a model that contain variables and a list of another class instance..
here models:
public class patient
{
[XmlElement("firstname")]
public string name { get; set; }
[XmlElement("lastname")]
public string surname { get; set; }
[XmlElement("age")]
public int age { get; set; }
[XmlElement("gender")]
public string gender { get; set; }
[XmlArray("exams"), XmlArrayItem(typeof(exam), ElementName = "exam")]
public List<exam> exam { get; set; }
}
public class exam
{
[XmlElement("id")]
public string id { get; set; }
[XmlElement(ElementName = "date", DataType = "DateTime")]
public DateTime date { get; set; }
[XmlElement("comment")]
public string comment { get; set; }
}
List<exam> examsLocal = new List<exam>(){
new exam{ id = "id of patient 1", date = DateTime.Now, comment = "coomment exam1" },
};
List<patient> overview = new List<patient>();
try
{
var b = new List<patient>()
{
new patient{ name = "name of patient 1", surname = "surname of patient 1", gender = "Female", age = 31, exam=examsLocal },
};
var writer = new System.Xml.Serialization.XmlSerializer(typeof(List<patient>));//throw exception
the line throws exceptions works fine if I delete 'exam=examsLocal' varible from List..
What is the correct way of serialize nested List items
Update your class definition of exam to be looks like:
remove the DataType of Date Property because the System.DateTime not allowed in Xml Serialization:
public class exam
{
[XmlElement("id")]
public string id { get; set; }
[XmlElement(ElementName = "date")]
public DateTime date { get; set; }
[XmlElement("comment")]
public string comment { get; set; }
}
And update the Property declaration in patiant class:
[XmlArray("exams"), XmlArrayItem(typeof(exam), ElementName = "exams")]
public List<exam> exams { get; set; }

A circular reference was detected while serializing an object of type in AngularJs and asp.net mvc

Well I know it is well known error. There are lots of questions asked here. But after going through few questions I am not able to solve my problem I am getting this error my website.
This is my error
A circular reference was detected while serializing an object of type
My Controller Code is
[HttpGet]
public JsonResult Get(int currentPage, int recordsPerPage)
{
var pageNumber = currentPage;
var pageSize = recordsPerPage;
var begin = (pageNumber - 1) * pageSize;
var totalNumberOfRecords = db.Products.Count();
var productlist = db.Products.OrderBy(r => r.ProductID).Skip(begin).Take(pageSize).ToList();
db.Configuration.ProxyCreationEnabled = false;
//var productlist = db.Products.ToList();
var product = new { Product = productlist, TotalRecords = totalNumberOfRecords };
return Json(new { Products = productlist, RecordCount = totalNumberOfRecords }, JsonRequestBehavior.AllowGet);
}
My Angular Controller Code is this
function GetProducts() {
var productResult = productService.getProduct($scope.currentPage, $scope.recordsPerPage);
productResult.then(function (result) {
console.log("d",data);
if (result.data != '' || result.data != null) {
if (result.data != null || result.data != '') {
$scope.Products = result.data;
}
else if (result.data = 0) {
$scope.message = "No Product Found"
}
}
});
};
And Angular Service code is this
this.getProduct = function (currentPage, recordsPerPage) {
return $http.get('/Home/Get?currentPage=' + currentPage + '&recordsPerPage=' + recordsPerPage);
// return $http.get('/Home/Get');
};
I am missing something but I am unable to get that. Any expert please help me in this.. I spend my whole night with this error. I try every solution of stackoverflow which I read but nothing works for me
Here is My Model
namespace StylesStore.Models
{
using System;
using System.Collections.Generic;
public partial class Product
{
public Product()
{
this.Carts = new HashSet<Cart>();
this.OrdersDetails = new HashSet<OrdersDetail>();
}
public int ProductID { get; set; }
public Nullable<int> SKU { get; set; }
public Nullable<int> VendorProductID { get; set; }
public string ProductName { get; set; }
public string ProductDescription { get; set; }
public Nullable<int> SupplierID { get; set; }
public Nullable<int> CategoryID { get; set; }
public Nullable<int> QuantityPerUnit { get; set; }
public decimal UnitPrice { get; set; }
public Nullable<int> MSRP { get; set; }
public Nullable<int> AvailableSize { get; set; }
public string AvailableColor { get; set; }
public Nullable<int> Size { get; set; }
public string Color { get; set; }
public Nullable<int> Discount { get; set; }
public Nullable<int> UnitWeight { get; set; }
public Nullable<int> UnitsInStock { get; set; }
public string UnitsInOrder { get; set; }
public string Picture1 { get; set; }
public string Picture2 { get; set; }
public string Picture3 { get; set; }
public string Picture4 { get; set; }
public Nullable<decimal> ShippingCharges { get; set; }
public string Note { get; set; }
public Nullable<bool> InStock { get; set; }
public Nullable<int> CatID { get; set; }
public Nullable<decimal> wieght { get; set; }
public Nullable<int> totalview { get; set; }
public Nullable<int> Disable { get; set; }
public Nullable<System.DateTime> EntryDate { get; set; }
public virtual ICollection<Cart> Carts { get; set; }
public virtual Category Category { get; set; }
public virtual ICollection<OrdersDetail> OrdersDetails { get; set; }
public virtual Supplier Supplier { get; set; }
}
}
You should not serialize your entity objects. Your entity objects have virtual navigation properties which are detected by JsonSerializer. JsonSerializer thinks they are embedded properties of that object and tries to serialize them too. and this goes on. serializer finds itself trying to serialize all database. this is why your error occurs.
You should either mark fields that need to be serialized or use DTO's to serialize objects.
Note: you can use AutoMapper to map objects between Entity and DTO

How to convert Directory Folders and Files to json string

I am working on Windows Form and I want to convert Directory Folders and Files to Json string like below,I am using newton json and have a json string like below with multiple Folders and Files , dynamic.
{
"folder": {
"name": "abc",
"folders": {
"folder": {
"name": "child abc",
"folders": {
"folder": {
"name": "child abcd"
}
},
"assets": {}
}
},
"assets": {
"asset": {
"folder_id": 14,
"uploaded_file": {
"content_type": "image/png",
"filename": "settings.png",
"file_data": "iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAABsVJREFUeNrEV29"
}
}
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
The Classes i am using are below mentioned, how can i get a json string with multiple Folders and Files.??
Help me
public class Folders2
{
}
public class Assets
{
}
public class Folder2
{
public string name { get; set; }
public Folders2 folders { get; set; }
public Assets assets { get; set; }
}
public class Folders
{
public Folder2 folder { get; set; }
}
public class UploadedFile
{
public string content_type { get; set; }
public string filename { get; set; }
public string file_data { get; set; }
}
public class Asset
{
public int folder_id { get; set; }
public UploadedFile uploaded_file { get; set; }
}
public class Assets2
{
public Asset asset { get; set; }
}
public class Folder
{
public string name { get; set; }
public Folders folders { get; set; }
public Assets2 assets { get; set; }
}
public class RootObject
{
public Folder folder { get; set; }
}
////////////////////////////////////////////////////////////////////////////
I tried working on this getting Directories and Files in a List,
Can anyone tell me how to parse this like above json string
List<string> li = new List<string>();
li.Add(path);
foreach (string files in Directory.EnumerateFiles(path, "*.*", System.IO.SearchOption.TopDirectoryOnly))
{
bool exists2 = li.Exists(element => element.StartsWith(files));
if (exists2 == false)
{
li.Add(files);
}
}
foreach (string Folder in Directory.EnumerateDirectories(path, "*.*", System.IO.SearchOption.AllDirectories))
{
li.Add(Folder);
foreach (string file in Directory.EnumerateFiles(Folder, "*.*", System.IO.SearchOption.AllDirectories))
{
bool exists = li.Exists(element => element.StartsWith(file));
if (exists==false)
{
li.Add(file);
}
}
}
Well I can see two ways to create your JSON-string from the object.
) You manually create the json-string with iterateing through the object and its properties.
) Use for IE. JSON.NET (http://www.newtonsoft.com/json/help/html/Introduction.htm) Serialize your object to json.
But I think you also should rethink the design of the classes, but thats an other thing.
With help and effort from Fredrik M , I have achieved my desired task
public class FolderRoot1
{
public FolderSJ folder { get; set; }
}
public class FolderSJ
{
public FolderSJ()
{
assets =new List<AssetRoot> { };
folders = new List<FolderRoot1> { };
}
public string parent_id { get; set; }
public string name { get; set; }
public List<AssetRoot> assets { get; set; }
public List<FolderRoot1> folders { get; set; }
}
public class AssetSJ
{
public string filename { get; set; }
public string content_type { get; set; }
public string file_data { get; set; }
}
public class AssetRoot
{
public UploadedFileContent asset { get; set; }
}
public class UploadedFileContent
{
public AssetSJ uploaded_file { get; set; }
}

De serialize the JSON data in wpf

I have a url which return's json data in the following way
{"title":"Test Title","image_url":"http://i.imgur.com/aZO5Kol.jpg","random_window":2,"windows":{"1":{"title":"Random 1"},"2":{"title":"Other Window 2"}},"thankyou_url":"http://google.com"}
Now i want to De-serialize this so that i can write the conditions based on the data received.
I want achieve this
will have to print the image and Name which is received through JSON. And based on the number of windows i should show the windows
I have declared a class
public class JsonData
{
string title { get; set; }
string image_url { get; set; }
string random_window { get; set; }
string[] windows { get; set; }
string thankyou_url { get; set; }
}
and i have written like this
WebClient objWebClient = new WebClient();
var jss = new JavaScriptSerializer();
string strJsonURL = "url";
var vJsondata = string.Empty;
vJsondata = objWebClient.DownloadString(strJsonURL);
var data = jss.Deserialize<object>(vJsondata);
try
{
var x = ((IList)data).Cast<object>().Select(o => o.ToString()).ToList();
}
But getting this error:
Unable to cast object of type 'System.Collections.Generic.Dictionary`2[System.String,System.Object]' to type 'System.Collections.IList'.
It appears that windows is a Dictionary and not a string array as you have defined in JsonData. You'll have to test this but from what I can tell it should be more like this:
public class JsonData
{
string title { get; set; }
string image_url { get; set; }
string random_window { get; set; }
Dictionary<string, WindowData> windows { get; set; }
string thankyou_url { get; set; }
}
public class WindowData
{
string title { get; set; }
}

Resources