How to convert Directory Folders and Files to json string - winforms

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; }
}

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

Receive file in Dictionary<string,IFormFile>

I'd like to receive files with special name - currently I have model like this:
public class SampleResultModel : SampleResult
{
public Dictionary<int, LayoutData> DataLayout { get; set; }
.
.
.
}
public class LayoutData
{
public int LayoutId { get; set; }
public Dictionary<string, string> Data { get; set; }
public Dictionary<string, string> Limits { get; set; }
public Dictionary<string, IFormFile> Attachments { get; set; }
public string DataType { get; set; }
public LayoutData() { }
}
Currently I'm able to receive any string data without problems with choosen structure, but when I need to receive files, then the "Attachments" property is always null.
Sent data:
dataLayout[0][layoutId]:
1101
dataLayout[1][layoutId]:
5
dataLayout[1][data][Conclusion]:
dataLayout[1][data][Result]:
1
dataLayout[0][Attachments][0]:
(binary)
dataLayout[0][Attachments][1]:
(binary)
What am I missing?
EDIT:
Tested also:
public List<IFormFile> Attachments { get; set; }
and still null and :
public class LayoutData
{
public int LayoutId { get; set; }
public Dictionary<string, string> Data { get; set; }
public Dictionary<string, string> Limits { get; set; }
public IFormFile Attachments { get; set; }
public string DataType { get; set; }
public LayoutData() { }
}
sent data:
dataLayout[0][layoutId]:
1101
dataLayout[1][layoutId]:
5
dataLayout[1][data][Conclusion]:
dataLayout[1][data][Result]:
1
dataLayout[0][attachments]:
(binary)
but data is still null...

how to display data from both two tables in database in a View in mvc4 razor

Can anybody guide me how to display data from two tables in database in view page of MVC4 using razor?i googled it but i didnt find answer for this
LeadDetail.cs
public partial class LeadDetail
{
public int LeadID { get; set; }
public string LeadName { get; set; }
public virtual logintable logintable { get; set; }
}
EmployeDetail.cs
public partial class EmployeDetail
{
public int EmployeID { get; set; }
public int UserID { get; set; }
public string EmployeeName { get; set; }
public virtual logintable logintable { get; set; }
}
Parentview.cs in viewmodels folder
public class Parentview
{
public List<LeadDetail> LeadDetails { get; set; }
public List<EmployeDetail> EmployeDetails { get; set; }
public ParentsInformationViewModel(List<LeadDetail> _LeadDetails, List<EmployeDetail> _EmployeDetails) //Should i pass all the required parameters that i want to display in view ????
{
LeadDetails = _LeadDetails;
EmployeDetails = _EmployeDetails;
}
Homecontroller.cs
public ActionResult view()
{
List<LeadDetail> LeadObj = new List<LeadDetail> ();
List<EmployeDetail> EmployeObj = new List<EmployeDetail> ();
// get list of parents here
Parentview ParentInfoVMObj = new Parentview();
ParentInfoVMObj.LeadDetails = LeadObj;
ParentInfoVMObj.EmployeDetails = EmployeObj;
return View(ParentInfoVMObj);
}
see below sample
First Table
public class Table1
{
public int Id{ get; set; }
public string Name{ get; set; }
}
Second Table
public class Table2
{
public int Id{ get; set; }
public string Name{ get; set; }
}
ViewModel
public class ViewModelForTwoTables
{
public List<Table1> table1Data { get; set; }
public List<Table2> table2Data { get; set; }
}
see below example
public ActionResult TeamStat()
{
var players = db.Players().ToList();
var seasons = db.Seasons().ToList();
var view = new TeamStat()
{
Players = players,
Seasons = seasons
};
return View(view);
}
in view
#foreach (var player in Model.Players) { ....
#foreach (var player in Model.Seasons) { ....

Breeze saving strategy

I'm creating my first spa with angular and breeze. So for so good and i'm very happy with the progress I've made. But now I'm stuck on my editing and saving my entity product (example class below). When I edit a product i also call the related products, and I have a checkbox (on saving) that says "override related products with same info". But what is the best way to do this? Server side? Should i expand the model on the client side? Are there examples available?
Product:
public class Product
{
#region Fields
private ICollection<ProductCategory> _productCategories;
private ICollection<ProductManufacturer> _productManufacturers;
private ICollection<ProductPicture> _productPictures;
private ICollection<ProductSpecificationAttribute> _productSpecificationAttributes;
private ICollection<ProductTierPrice> _productTierPrices;
#endregion Fields
#region Properties
public int Id { get; set; }
public ProductType ProductType { get; set; }
public int ParentGroupedProductId { get; set; }
public bool VisibleIndividually { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string MetaTitle { get; set; }
public string MetaDescription { get; set; }
public int DisplayOrder { get; set; }
public bool LimitedToStores { get; set; }
public string Sku { get; set; }
public string UniqueCode { get; set; }
public decimal Price { get; set; }
public decimal OldPrice { get; set; }
public decimal? SpecialPrice { get; set; }
public DateTime? SpecialPriceStartDateTimeUtc { get; set; }
public DateTime? SpecialPriceEndDateTimeUtc { get; set; }
public decimal DiscountPercentage { get; set; }
public bool HasTierPrices { get; set; }
public TaxRate TaxRate { get; set; }
public bool SyncToShop { get; set; }
public bool Deleted { get; set; }
public bool Locked { get; set; }
public State State { get; set; }
public DateTime? DateChanged { get; set; }
public DateTime? DateCreated { get; set; }
#endregion Properties
#region Mapping
public virtual ICollection<ProductCategory> ProductCategories
{
get { return _productCategories ?? (_productCategories = new List<ProductCategory>()); }
protected set { _productCategories = value; }
}
public virtual ICollection<ProductManufacturer> ProductManufacturers
{
get { return _productManufacturers ?? (_productManufacturers = new List<ProductManufacturer>()); }
protected set { _productManufacturers = value; }
}
public virtual ICollection<ProductPicture> ProductPictures
{
get { return _productPictures ?? (_productPictures = new List<ProductPicture>()); }
protected set { _productPictures = value; }
}
public virtual ICollection<ProductSpecificationAttribute> ProductSpecificationAttributes
{
get { return _productSpecificationAttributes ?? (_productSpecificationAttributes = new List<ProductSpecificationAttribute>()); }
protected set { _productSpecificationAttributes = value; }
}
public virtual ICollection<ProductTierPrice> ProductTierPrices
{
get { return _productTierPrices ?? (_productTierPrices = new List<ProductTierPrice>()); }
protected set { _productTierPrices = value; }
}
#endregion Mapping
}
Related Product:
public class RelatedProduct
{
#region Fields
#endregion Fields
#region Properties
public int Id { get; set; }
public int ProductId1 { get; set; }
public int ProductId2 { get; set; }
public int DisplayOrder { get; set; }
public State State { get; set; }
#endregion Properties
//#region Mapping
//public virtual Product Product1 { get; set; }
//public virtual Product Product2 { get; set; }
//#endregion Mapping
}
Capture Changes of All Products in Clinent Jquery Array and send to Server Side..
Serverside change your controller method argument to IEnumerable products , so you can save all changes in Batch
If you want to update only change value use HttpPatch on server side and update changed value only

Classes and relationship design in mvc 3.0

I have currently have the following classes:
public class Ticket
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public int ClientId { get; set; }
public virtual Client Client { get; set; }
public virtual ICollection<Item> Items { get; set; }
public Ticket()
{
Items = new List<Item>();
}
}
public class Client
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public virtual ICollection<Ticket> Tickets { get; set; }
}
public class Item
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public double Price { get; set; }
public virtual ICollection<Ticket> Tickets { get; set; }
}
My Problem/Question is the following, let's say I create a new Item: "Item1" and set its price to "3.00", I add that Item to a few "Tickets", i.e., "Ticket1": "Item1", "3.00"; "Ticket2": "Item1", "3.00", etc. If after adding these items to the tickets I change "Item1"'s price to "4.00" it would change the price of the ticket I already created, how can I have it change the price for only ticket created after the price change?
This is my ticket controller:
[HttpPost]
public ActionResult Create(TicketViewModel ticketViewModel)
{
if (ModelState.IsValid)
{
var ticket = new Ticket();
ticket = ticketViewModel.Ticket;
AddOrUpdateItems(ticket, ticketViewModel.Item);
context.Tickets.Add(ticket);
context.SaveChanges();
return RedirectToAction("Index");
}
return View(ticketViewModel);
}
private void AddOrUpdateItems(Ticket ticket, ICollection<AssignedItem> assignedItems)
{
foreach (var assignedItem in assignedItems)
{
if (assignedItem.Assigned)
{
var item = context.Items.Find(assignedItem.ItemId);
ticket.Items.Add(item);
}
}
}

Resources