Recursively Adding tree structure to a List C# - c#

So I have some code that performs a Neo4j cypher query that returns an IEnumerable of type FolderObject like so:
public IEnumerable<FolderObject> GetChild(string parentId)
{
IEnumerable<FolderObject> childNode = null;
var query = GraphConnection.Cypher
.Start(new { n = Node.ByIndexLookup("node_auto_index", "ObjectId", parentId) })
.Match("(n)-[r:HAS_FOLDER]->(b)")
.Where("b.ParentId = n.ObjectId")
.Return<FolderObject>("b");
childNode = query.Results;
return childNode;
}
FolderObject looks like so:
public string ObjectId { get; set; }
public string ParentId {get; set;}
public List<GraphObject> Children { get; set; }
Then I have this method which works fine:
public List<FolderObject> GetChildren(string repositoryId, string folderId)
{
List<FolderObject> items;
QueryOperations query = new QueryOperations(GraphConnection);
var queryResult = query.GetChild(folderId);
string childId = null;
if (queryResult != null)
{
foreach (var item in queryResult)
{
childId = item.ObjectId;
items = new List<FolderObject>();
items.Add(item);
var nextChild = GetChildren(repositoryId, childId);
}
}
else
{
throw new Exception("The Folder with Id: " + folder + " could not be found.");
}
return items
}
Now the problem comes when I try and do this recursively. What I need to do is get the top most folder add that to a list then get the next folder below the top most and add that in as a child. Then repeat until there are no more children.
The structure as follows:
-Folder
-Folder
-Folder
-Folder
and return this structure as a List?
Here is the Json
{
"ParentId": "0",
"ObjectId": "1",
"children": [
{
"ParentId": "1",
"ObjectId": "2",
"children": [
{
"ParentId": "2",
"ObjectId": "3"
}
]
}
]
}

You could use a Stack<FolderObject> which is similar to a recursive method, the only difference is that it's not recursive. Imho it's more readable and less complex.
public List<FolderObject> GetChildren(string repositoryId, string folderId)
{
List<FolderObject> items = new List<FolderObject>();;
QueryOperations query = new QueryOperations(GraphConnection);
var queryResult = query.GetChild(folderId);
Stack<FolderObject> folders = new Stack<FolderObject>(queryResult);
while (folders.Count > 0)
{
FolderObject currentFolder = folders.Pop();
var childId = currentFolder.ObjectId;
items.Add(currentFolder);
var nextChildren = GetChildren(repositoryId, childId);
foreach (FolderObject child in nextChildren)
folders.Push(child);
}
return items;
}

Related

How do i insert Adds many objects to the the List In c# MongoDB.Driver

How do I insert Adds many objects to the List In c# MongoDB.Driver?
my c# Entity
/// <summary>LogTest</summary>
public class VisitLog
{
/// <summary>MongoDB特有的字段</summary>
[MongoDB.Bson.Serialization.Attributes.BsonElement("_id")]
[JsonConverter(typeof(ObjectIdConverter))]
public MongoDB.Bson.ObjectId MongoId { get; set; }
/// <summary>YMD datetime</summary>
public int Yymmdd { get; set; }
/// <summary>Visitor</summary>
public string Visitor { get; set; }
/// <summary>VisitInfos</summary>
public List<VisitInfo> VisitInfos { get; set; }
}
In the MongoDBCode Like the code
// 1
{
"_id": ObjectId("5f506eb02000a9b52d72a600"),
"Yymmdd": NumberInt("20200903"),
"Visitor": "360spider",
"VisitInfos": [ ]
}
i will add objects to the "VisitInfos": [ ]
How do I insert Adds many objects to the List In c# MongoDB.Driver?
Way 1: insert only one object. my test code is:
var filter = Builders<VisitLog>.Filter.Eq("_id", item.MongoId);
var update = Builders<VisitLog>.Update.Push("VisitInfos", new VisitInfo { Visitor = Visitor, Browser = "IE", Ip = "192.168.1.1", Createtime = DateTime.Now.ToUnixTimeLocalIslong() });
var result = BB.UpdateOne(filter, update);
The Way 2: i want to insert InsertManyAsync
var items = BB.Find(x => x.Yymmdd.Equals(Yymmdd) && x.Visitor.Equals(Visitor)).Project<VisitLog>(fields).ToList();
if (items.Count > 0)
{
var item = items[0];
var VisitInfos = new List<VisitInfo>();
for (int j = 0; j < 10000; j++)
{
VisitInfos.Add(new VisitInfo { Visitor = Visitor, Browser = "IE", Ip = "192.168.1.1", Createtime = DateTime.Now.ToUnixTimeLocalIslong() });
}
var filter = Builders<VisitLog>.Filter.Eq("_id", item.MongoId);
var update = Builders<VisitLog>.Update.Push("VisitInfos", VisitInfos);
var result = BB.UpdateOne(filter, update);
}
the way 2 is failed.
please help me.
this very much.....
On the Builders<Order>.Update there's a PushEach which accepts an IEnumerable. This is equivalent to doing:
{ $push: { scores: { $each: [ 90, 92, 85 ] } } }
https://docs.mongodb.com/manual/reference/operator/update/push/#append-multiple-values-to-an-array
For simplicity here's an example of an order and order items.
In MongoDB we'll have:
> db.orders.find()
{ "_id" : ObjectId("5f50aef4d7d9f967d0322932"), "Items" : [ ] }
Then we'll execute the following C# Code.
var client = new MongoClient();
var db = client.GetDatabase("test");
var items = db.GetCollection<Order>("orders");
var filter = Builders<Order>.Filter.Empty;
var update = Builders<Order>.Update.PushEach(x => x.Items, new[]
{
new OrderItem{Name = "Order 1", Price = 10.1M},
new OrderItem{Name = "Order 2", Price = 20.2M}
});
await items.UpdateOneAsync(filter, update);
public class Order
{
public ObjectId Id { get; set; }
public List<OrderItem> Items { get; set; }
= new List<OrderItem>();
}
public class OrderItem
{
public string Name { get; set; }
public decimal Price { get; set; }
}
Now if we take a look at our document in MongoDB we'll have the 2 items added to our array
db.orders.find().pretty()
{
"_id" : ObjectId("5f50aef4d7d9f967d0322932"),
"Items" : [
{
"Name" : "Order 1",
"Price" : "10.1"
},
{
"Name" : "Order 2",
"Price" : "20.2"
}
]
}

How to put multiple values in Dictionary instances using LINQ?

My Json Response is Following below:
{"d":
{"RowData":
[{"GenreId":11,"GenreName":"Musical","subjecturl":"subjecturl_1","logourl":"logourl_1"},
{"GenreId":12,"GenreName":"kids","subjecturl":"subjecturl_2","logourl":"logourl_2"},
{"GenreId":13,"GenreName":"other","subjecturl":"subjecturl_3","logourl":"logourl_3"},
{"GenreId":14,"GenreName":"Musical","subjecturl":"subjecturl_4","logourl":"logourl_4"},
{"GenreId":15,"GenreName":"Music","subjecturl":"subjecturl_5","logourl":"logourl_5"},
{"GenreId":16,"GenreName":"Faimaly","subjecturl":"subjecturl_6","logourl":"logourl_6"},
{"GenreId":17,"GenreName":"other","subjecturl":"subjecturl_7","logourl":"logourl_7"},
{"GenreId":18,"GenreName":"other","subjecturl":"subjecturl_8","logourl":"logourl_8"},
{"GenreId":19,"GenreName":"kids","subjecturl":"subjecturl_9","logourl":"logourl_9"},
{"GenreId":20,"GenreName":"Musical","subjecturl":"subjecturl_10","logourl":"logourl_10"},
{"GenreId":21,"GenreName":"other","subjecturl":"subjecturl_11","logourl":"logourl_11"}]}}
Using the above Response I tried to make like below Response :
{"rows": [{
"title": "Musical",
"items": [{"hdsubjecturl": "subjecturl_1"},{"hdsubjecturl": "subjecturl_4"},{"hdsubjecturl": "subjecturl_10"}]
},{
"title": "kids",
"items": [{"hdsubjecturl": "subjecturl_2"},{"hdsubjecturl": "subjecturl_9"}]
},{
"title": "Music",
"items": [{"hdsubjecturl": "subjecturl_5"}]
},{
"title": "other",
"items": [{"hdsubjecturl": "subjecturl_3"},{"hdsubjecturl": "subjecturl_7"},{"hdsubjecturl": "subjecturl_8"},{"hdsubjecturl": "subjecturl_11"}]
},{
"title": "Faimaly",
"items": [{"hdsubjecturl": "subjecturl_6"}]
}]
}
My Code is below :
JObject Root = JObject.Parse(jsonData["d"].ToString());
var unique = Root["RowData"].GroupBy(x => x["GenreName"]).Select(x => x.First()).ToList(); // here fetch 5 record
foreach (var un in unique)
{
var GenreName = new
{
title = un["GenreName"],
items = new
{
hdsubjecturl = "logourl"
}
};
var GenreNamereq = JsonConvert.SerializeObject(GenreName, Newtonsoft.Json.Formatting.Indented);
genstr.Append(GenreNamereq, 0, GenreNamereq.Length);
genstr.Append(",");
using (System.IO.StreamWriter file = new System.IO.StreamWriter(subdir + "\\GenreName.json"))
{
string st = genstr.ToString().Substring(0, (genstr.Length - 1));
file.WriteLine("{\n\"rows\": [\n" + st + "\n}"); //seasion number 21 terminate
file.Close();
}
}
Using above code my output is below for First Field :
{"rows":
[{
"title": "Musical",
"items": {
"hdsubjecturl": "logourl"
}
}]
}
Using below code I tried to fetch Multiple values using specific Field :
List<string> CategoryList = new List<string>();
var unique = Root["RowData"].GroupBy(x => x["GenreName"]).Select(x => x.First()).ToList(); // here fetch 8 record
foreach (var cat in unique)
{
CategoryList.Add(cat["GenreName"].ToString());
}
List<List<string>> myList = new List<List<string>>();
for (int i=0;i<CategoryList.Count();i++)
{
var results = from x in Root["RowData"]
where x["GenreName"].Value<string>() == CategoryList[i]
select x;
foreach (var token in results)
{
Console.WriteLine(token["logourl"]);
}
// myList.Add(results);
}
In the First code, I used JObject for fetching a Root node. But, using the above query it takes by default JTocken. So, I used foreach loop here.
I used Dictionary instances for JSON Creation. Using this code I successfully fetched hdsubjecturl in for loop. But, I don't know how to put multiple values in Dictionary instances. Because I get title fields only single times using a unique query and items fields inside a hdsubjetcurl is more than one. Does anyone know how it's possible?
You can group your RowData by GenreName token, then use ToDictionary method to get a result dictionary and map it to desired structure (with title and hdsubjecturl). Finally create a result object using JObject.FromObject
var json = JObject.Parse(jsonString);
var data = json["d"]?["RowData"]
.GroupBy(x => x["GenreName"], x => x["subjecturl"])
.ToDictionary(g => g.Key, g => g.ToList())
.Select(kvp => new { title = kvp.Key, items = kvp.Value.Select(x => new { hdsubjecturl = x }) });
var result = JObject.FromObject(new { rows = data });
Console.WriteLine(result);
It gives you the expected result.
Edit: according to comments, GroupBy and Select expressions should be updated to map more then one property in result title item
var data = json["d"]?["RowData"]
.GroupBy(x => x["GenreName"])
.ToDictionary(g => g.Key, g => g.ToList())
.Select(kvp => new
{
title = kvp.Key,
items = kvp.Value.Select(x => new { hdsubjecturl = x["subjecturl"], url = x["logourl"] })
});
var result = JObject.FromObject(new { rows = data });
Consider trying this code, (using Newtonsoft Json deserializer);
public partial class Root
{
public D D { get; set; }
}
public partial class D
{
public RowDatum[] RowData { get; set; }
}
public partial class RowDatum
{
public long GenreId { get; set; }
public string GenreName { get; set; }
public string Subjecturl { get; set; }
public string Logourl { get; set; }
}
public partial class Response
{
public Row[] Rows { get; set; }
}
public partial class Row
{
public string Title { get; set; }
public Item[] Items { get; set; }
}
public partial class Item
{
public string Hdsubjecturl { get; set; }
}
public class Program
{
public static void Main(string[] args)
{
var json =
#"{""d"":{""RowData"":[{""GenreId"":11,""GenreName"":""Musical"",""subjecturl"":""subjecturl_1"",""logourl"":""logourl_1""},{""GenreId"":12,""GenreName"":""kids"",""subjecturl"":""subjecturl_2"",""logourl"":""logourl_2""},{""GenreId"":13,""GenreName"":""other"",""subjecturl"":""subjecturl_3"",""logourl"":""logourl_3""},{""GenreId"":14,""GenreName"":""Musical"",""subjecturl"":""subjecturl_4"",""logourl"":""logourl_4""},{""GenreId"":15,""GenreName"":""Music"",""subjecturl"":""subjecturl_5"",""logourl"":""logourl_5""},{""GenreId"":16,""GenreName"":""Faimaly"",""subjecturl"":""subjecturl_6"",""logourl"":""logourl_6""},{""GenreId"":17,""GenreName"":""other"",""subjecturl"":""subjecturl_7"",""logourl"":""logourl_7""},{""GenreId"":18,""GenreName"":""other"",""subjecturl"":""subjecturl_8"",""logourl"":""logourl_8""},{""GenreId"":19,""GenreName"":""kids"",""subjecturl"":""subjecturl_9"",""logourl"":""logourl_9""},{""GenreId"":20,""GenreName"":""Musical"",""subjecturl"":""subjecturl_10"",""logourl"":""logourl_10""},{""GenreId"":21,""GenreName"":""other"",""subjecturl"":""subjecturl_11"",""logourl"":""logourl_11""}]}}";
var root = JsonConvert.DeserializeObject<Root>(json);
var rows = root.D.RowData.ToLookup(d => d.GenreName)
.Select(g => new Row()
{
Title = g.Key,
Items = g.ToList().Select(rd => new Item() {Hdsubjecturl = rd.Logourl}).ToArray()
}).ToArray();
var response = new Response()
{
Rows = rows
}; // reponse is the type of Json Response you wanted to achieve
Console.WriteLine();
}
}

Create complex JSON using C# object

I am trying to create the json from c# object which holds the data.
Data is in simple table format. Consist of Columns: Name, InputCode, DisplayID, CodeID, ParentID.
If Parent(Net) then ParentID is null. If Children(Subnet), has ParentID that holds CodeID of Parent(Net).
CodeID is Unique.
I am facing the issue with iternation under subnet using foreach. It dosen't allow.
public class CodeFrameJson
{
public string Name { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public int? InputCodeValue { get; set; }
public int DisplayId { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public List<CodeFrameJson> Subnet { get; set; }
}
List<CodeFrameJson> cfj = new List<CodeFrameJson>();
IEnumerable<CodeDTO> _cfd = new List<CodeDTO>();
_cfd = codeFrameJson.GetCodeFrame(questionId, projectName);
_cfd = _cfd.OrderBy(a => a.DisplayOrderNo).ToList();
foreach (var a in _cfd)
{
int CodesID = 0;
CodeFrameJson obj = new CodeFrameJson();
if (a.InputCodeValue == null)
{
var root = new CodeFrameJson()
{
Name = a.CodeName,
DisplayId = a.DisplayOrderNo,
InputCodeValue = null,
Subnet = new List<CodeFrameJson>()
{
//Start: Not allowing foreach
foreach (var x in _cfd)
{
if (x.ParentId == CodesID)
{
new CodeFrameJson()
{
Name = x.CodeName,
InputCodeValue = x.InputCodeValue,
DisplayId = x.DisplayOrderNo
};
}
}
//End: Not allowing foreach
}
};
obj = root;
}
else {
var root = new CodeFrameJson()
{
Name = a.CodeName,
DisplayId = a.DisplayOrderNo,
InputCodeValue = a.InputCodeValue,
Subnet = null
};
obj = root;
}
cfj.Add(obj);
}
var json = JsonConvert.SerializeObject(cfj, Formatting.Indented);
Final Output Something like this which can be distinguished easily
{
"Site": {
"Name": "Site",
"DisplayID": 1,
"Subnet": [
{
"Name": "Full Site",
"InputCodeValue": 1,
"DisplayId": 2
},
{
"Name": "Partial Site",
"InputCodeValue": 2,
"DisplayId": 3
}
]
},
"Test": {
"Name": "Test1",
"InputCodeValue": 3,
"DisplayId": 4
}
}
This doesn't really have to do anything with JSON, but with object (collection) initialization. You can only assign values there, but LinQ comes to the rescue:
Simply filter your list and create the new objects in the select statement:
Subnet = _cfd.Where(x => x.ParentId == CodesID).Select(x => new CodeFrameJson
{
Name = x.CodeName,
InputCodeValue = x.InputCodeValue,
DisplayId = x.DisplayOrderNo
}).ToList()

C# Conditionally looping through JSON values

I am new to this and apologize if it is a duplicate question. I have tried so many different things at this point I'm not sure the right way to do this.
I am trying to write a function to loop through a JSON and get the value of model for certain conditions (ie: qty != null, and sector = 1, position = 1.
I also need to count the number of occurrences for each unique model.
Any help would be greatly appreciated.
Here is what the JSON looks like.
[ { "sector": "1", "position": "1", "qty": "1", "model": "SBNHH-1D65C" },
{ "sector": "2", "position": "1", "qty": "1", "model": "" },
{ "sector": "3", "position": "1", "qty": "1", "model": "DC6-48-60-18-8F" },
{ "sector": "1", "position": "2", "qty": "1", "model": "SBNHH-1D65C" },
{ "sector": "2", "position": "2", "qty": "1", "model": "DC6-48-60-18-8F" } ]
public class AntennaItems
{
public AntennaItems[] root { get; set; }
public int sector { get; set; }
public int position { get; set; }
public string qty { get; set; }
public string model { get; set; }
}
string requestBodyString = await new StreamReader(req.Body).ReadToEndAsync();
var newJsonString = #"{root:" + requestBodyString + #"}";
List<string> modelList = new List<string>();
var jsonObj = JsonConvert.DeserializeObject<AntennaItems>(newJsonString);
foreach (var elem in jsonObj.root)
{
modelList.Add(elem.model);
}
return new OkObjectResult($"modelList = {modelList}");
Currently I'm getting this response:
modelList = System.Collections.Generic.List`1[System.String]
You'd return your modelList in interpolation with string name modelList and interpolation return you the type of your modelList and in your case its a System.Collections.Generic.List'1[System.String].
So this line
return new OkObjectResult($"modelList = {modelList}");
Give you
modelList = System.Collections.Generic.List`1[System.String]
So instead of returning like above try to return your modelList with anonymous type so you will be able to get actual data containing modelList like
return new OkObjectResult(new { modelList = modelList});
Or Simply
return new OkObjectResult(modelList);
I think you don't need root property. I have modified the class little bit and removed the root property from it:
public class AntennaItems
{
public int sector { get; set; }
public int position { get; set; }
public string qty { get; set; }
public string model { get; set; }
}
public HttpResponse ParseJson()
{
string requestBodyString = await new StreamReader(req.Body).ReadToEndAsync();
var newJsonString = #"{root:" + requestBodyString + #"}";
List<string> modelList = new List<string>();
var jsonObj = JsonConvert.DeserializeObject<List<AntennaItems>>(newJsonString);
foreach (var elem in jsonObj)
{
modelList.Add(elem.model);
}
return new OkObjectResult($"modelList = {modelList}");
}
You need to deserialize it in List. Let me know if it helps.
public class AntennaItems
{
public int sector { get; set; }
public int position { get; set; }
public string qty { get; set; }
public string model { get; set; }
[FunctionName("AntennaSort")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
List<string> modelList = new List<string>();
var jsonObj = JsonConvert.DeserializeObject<List<AntennaItems>>(requestBody);
foreach (var elem in jsonObj)
{
modelList.Add(elem.model);
}
return new OkObjectResult($"modelList = {modelList}");
}
The result is
modelList = System.Collections.Generic.List`1[System.String]

Finding a JSON entry and add a nested element

I have a .json file that looks like this:
[
{
"username": "John",
"currency": 8,
"pulls":
[
{
"character": "person"
},
{
"character": "loved one"
}
]
},
{
"username": "Mike",
"currency": 2,
"pulls":
[
{
"character": "noone"
}
]
},
{
"username": "Clara",
"currency": 5,
"pulls":
[
{
"character": "someone"
}
]
}
]
What I managed to do so far is modify "currency":
bool userExists = false;
string jsonPointsString = File.ReadAllText(userPath);
dynamic jsonObjects = JsonConvert.DeserializeObject(jsonPointsString);
foreach (var jsonObject in jsonObjects)
{
if (jsonObject["username"] == user)
{
jsonObject["currency"] += value;
string output = JsonConvert.SerializeObject(jsonObjects, Formatting.Indented);
File.WriteAllText(userPath, output);
userExists = true;
}
}
As well as add a completely new entry from scratch:
JsonCollection.User user = new JsonCollection.User();
user.username = username;
user.currency = 10;
using (StreamReader r = new StreamReader(userPath))
{
string json = r.ReadToEnd();
List<JsonCollection.User> users = JsonConvert.DeserializeObject<List<JsonCollection.User>>(json);
users.Add(user);
newJson = JsonConvert.SerializeObject(users, Formatting.Indented);
}
File.WriteAllText(userPath, newJson);
However, no matter what I try I can not add another element to "pulls". The idea is that I call a function with a username and a pull, two strings. Based on the username variable I have to find the corresponding Json Entry and create a new entry within the "pulls" tree based on the pull variable. This is what I could come up with:
public void AddPullToUser(string user, string newPull)
{
user = "Mike"; //test value
string jsonPointsString = File.ReadAllText(userPath);
dynamic jsonObjects = JsonConvert.DeserializeObject(jsonPointsString);
foreach (var jsonObject in jsonObjects)
{
if (jsonObject["username"] == user)
{
//jsonObject["pulls"] = newPull;
JsonCollection.Character pull = new JsonCollection.Character();
pull.character = newPull;
jsonObject["pulls"] = pull;
string output = JsonConvert.SerializeObject(jsonObjects, Formatting.Indented);
File.WriteAllText(userPath, output);
}
}
}
If I do it like this the system can't convert the JsonCollection to the JArray but without using the JArray I don't understand how to find the specific users tree.
In step two this will have to be expanded even further to not create duplicated "pulls", but first of all this has to work in general.
Any help would be greatly appreciated.
Something like this -
var json = "[{'username':'John','currency':8,'pulls':[{'character':'person'},{'character':'loved one'}]},{'username':'Mike','currency':2,'pulls':[{'character':'noone'}]},{'username':'Clara','currency':5,'pulls':[{'character':'someone'}]}]";
var obj = JsonConvert.DeserializeObject<List<RootObject>>(json);
var o = obj.FindIndex(a => a.username == "Mike");
obj[o].pulls.AddRange(new List<Pull>{
new Pull{
character = "Modified"
}
});
Console.WriteLine(JsonConvert.SerializeObject(obj));
Where
public class Pull
{
public string character { get; set; }
}
public class RootObject
{
public string username { get; set; }
public int currency { get; set; }
public List<Pull> pulls { get; set; }
}
alternatively, you might be interested in JSON Merge
A possible solution looks like -
var json = "[{'username':'John','currency':8,'pulls':[{'character':'person'},{'character':'loved one'}]},{'username':'Mike','currency':2,'pulls':[{'character':'noone'}]},{'username':'Clara','currency':5,'pulls':[{'character':'someone'}]}]";
var obj = JArray.Parse(json);
var idx = obj.IndexOf(obj.FirstOrDefault(a => a["username"].ToString() == "Mike"));
((JArray)obj[idx]["pulls"]).Add(JObject.Parse(#"{
'character': 'new one'
}"));
Console.WriteLine(obj[idx]);
/*output -
{
"username": "Mike",
"currency": 2,
"pulls": [
{
"character": "noone"
},
{
"character": "new one"
}
]
} */
After a bit more research and your help I was able to first of all change all the interaction with Json to the same code-style.
New entry has changed to this:
public void CreateUser(string username)
{
try
{
string jsonUserString = File.ReadAllText(userPath);
var users = JsonConvert.DeserializeObject<List<JsonCollection.User>>(jsonUserString);
users.AddRange(new List<JsonCollection.User> { new JsonCollection.User { username = username, currency = 10, pulls = new List<JsonCollection.Character> { new JsonCollection.Character { character = "TemmieHYPE" } } } });
string output = JsonConvert.SerializeObject(users, Formatting.Indented);
File.WriteAllText(userPath, output);
}
catch
{
Console.WriteLine("Error on CreateUser");
}
}
Update has changed to this:
public void UpdateUserStats(string username, decimal value, int selection)
{
try
{
string jsonUserString = File.ReadAllText(userPath);
var users = JsonConvert.DeserializeObject<List<JsonCollection.User>>(jsonUserString);
int user = users.FindIndex(a => (a.username == username));
if (user != -1)
{
switch (selection)
{
case 1:
users[user].currency += value;
break;
case 2:
users[user].secondsOnline += value;
break;
default:
break;
}
string output = JsonConvert.SerializeObject(users, Formatting.Indented);
File.WriteAllText(userPath, output);
//AddPullToUser(username, DateTime.Now.ToString()); //remove on live
}
else
{
CreateUser(username);
}
}
catch
{
Console.WriteLine("Error on UpdateCurrency");
}
}
Most importantly the Add Pull command to add a nested element to the Json now works with the following code:
public void AddPullToUser(string username, string pulledCharacter)
{
string jsonUserString = File.ReadAllText(userPath);
var users = JsonConvert.DeserializeObject<List<JsonCollection.User>>(jsonUserString);
int alreadyPulled = users.FindIndex(a => (a.username == username) && (a.pulls.FindIndex(b => b.character == pulledCharacter) > 0));
if (alreadyPulled == -1)
{
int user = users.FindIndex(a => (a.username == username));
users[user].pulls.AddRange(new List<JsonCollection.Character> { new JsonCollection.Character { character = pulledCharacter } });
string output = JsonConvert.SerializeObject(users, Formatting.Indented);
File.WriteAllText(userPath, output);
}
}
With the addition of the "if (alreadyPulled == -1)" duplicated pulls don't get added to the Json files either.

Categories

Resources