Getting Error code -1120 while creating table in the SAP B1 - c#

`Hello All,
I am trying to create a table in the SAP B1. But I am getting an error code "-1120".
For creating a table I have fetched a data from the json file.
And by using that data I tried to create the tables in the SAP B1.
But I am getting an error code "-1120".
Here is the code
string text = File.ReadAllText(#"C:\Users\vijay\Documents\Visual Studio 2015\Projects\TestAddon_03\TestAddon_03\json1.json");
var tableInfo = JsonConvert.DeserializeObject<TableInfo>(text);
try
{
foreach (var table in tableInfo.tables)
{
string tbName = table.tableName;
string tbDis = table.tableDescription;
string tbType = table.tableType;
GC.Collect();
SAPbobsCOM.UserTablesMD objUserTableMD = (SAPbobsCOM.UserTablesMD)oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oUserTables);
objUserTableMD.TableName = tbName;
objUserTableMD.TableDescription = tbDis;
switch (tbType)
{
case "Document":
objUserTableMD.TableType = SAPbobsCOM.BoUTBTableType.bott_Document;
break;
case "MasterData":
objUserTableMD.TableType = SAPbobsCOM.BoUTBTableType.bott_MasterData;
break;
case "NoObject":
objUserTableMD.TableType = SAPbobsCOM.BoUTBTableType.bott_NoObject;
break;
default:
Application.SBO_Application.MessageBox("Invalid Table Type");
break;
}
int result = objUserTableMD.Add();
//Application.SBO_Application.MessageBox(Convert.ToString(result));
if(result != 0)
{
Application.SBO_Application.MessageBox("Table Not Created" + "\n --------- \n" + oCompany.GetLastErrorDescription() );
}
else
{
Application.SBO_Application.MessageBox("Table Created");
foreach (var field in table.fields)
{
string fieldNm = field.fieldName;
string fieldType = field.fieldType;
int fieldSize = field.fieldSize;
SAPbobsCOM.UserFieldsMD objUserFieldsMD = (SAPbobsCOM.UserFieldsMD)oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oUserFields);
objUserFieldsMD = null;
objUserFieldsMD.TableName = tbName;
objUserFieldsMD.Name = field.fieldName;
switch (fieldType)
{
case "Numeric":
objUserFieldsMD.Type = SAPbobsCOM.BoFieldTypes.db_Numeric;
break;
case "String":
objUserFieldsMD.Type = SAPbobsCOM.BoFieldTypes.db_Alpha;
break;
case "Date":
objUserFieldsMD.Type = SAPbobsCOM.BoFieldTypes.db_Date;
break;
case "Float":
objUserFieldsMD.Type = SAPbobsCOM.BoFieldTypes.db_Float;
break;
case "Memo":
objUserFieldsMD.Type = SAPbobsCOM.BoFieldTypes.db_Memo;
break;
default:
Application.SBO_Application.MessageBox("Invalid FieldType");
break;
}
objUserFieldsMD.Size = field.fieldSize;
int fieldResult = objUserFieldsMD.Add();
if (fieldResult != 0)
{
Application.SBO_Application.MessageBox("Fields Not Created");
}
else
{
Application.SBO_Application.MessageBox("Fields Created");
}
}
// Application.SBO_Application.MessageBox(tbName + " " + tbDis + " " + tbType + " " + fieldNm + " " + fieldType + " " + fieldSize);
}
}
}
catch(Exception Create)
{
Application.SBO_Application.MessageBox(Create.ToString());
}
And This is a sample json file
{
"tables": [
{
"tableName": "SAMP1",
"tableDescription": "SampleTable 1",
"tableType": "Document",
"fields": [
{
"fieldName": "CF1",
"fieldType": "String",
"fieldSize": 100
}
]
},
{
"tableName": "SAPM2",
"tableDescription": "SampleTable 2",
"tableType": "MasterData",
"fields": [
{
"fieldName": "CF2",
"fieldType": "Numeric",
"fieldSize": 8
},
{
"fieldName": "CF3",
"fieldType": "String",
"fieldSize": 50
}
]
}
]
}
I am getting the error at the below line:
Application.SBO_Application.MessageBox("Table Not Created" + "\n --------- \n" + oCompany.GetLastErrorDescription() );
Error:
SAPbobsCOM.ICompany.GetLastErrorDescription returend "Ref Count for this object is higher then 0".

You need to set objUserTableMD to null and do another garbage collection after creating the table and before adding its fields. You might also need to call Marshal.ReleaseComObject() on the reference.
B1 only allows a single instance of schema modifying objects to exist.

Related

How to prevent logging from cluttering your code?

I have been refactoring some of my code, and I can't help but feeling it's very cluttered, complex and confusing. After looking into it more and more, I've begun to notice that the code isn't so much complex as it is verbose.
We're using NLog and providing very verbose output to a debug log, as the application is incredibly prone to failure, and we're trying to be very thorough.
Here's an example of one of the more simple methods
[HttpGet]
public ActionResult Zendesk(long? id)
{
if (!GlobalVariables.AllSyncSettings.SyncEnabled || !GlobalVariables.AllSyncSettings.ZdSyncEnabled)
return Json(new { Enabled = "False" });
if (id == null || id == 0)
return Json(new { Error = "Missing or malformed ticket ID." }, AG);
if (CheckZdIdExists((long)id))
return Json(new { status = "error, in queue." }, AG);
GlobalVariables.TicketsInQueue.Add((long)id);
Log("-------------- STARTING NEW CASE [ZENDESK]["+ id +"] --------------");
var zdHelper = new ZendeskHelpers();
var zdTicket = zdHelper.GetTicketById((long)id);
if (zdTicket == null)
{
Log("--------------- ENDING CASE [ZENDESK][" + id + "] ---------------");
GlobalVariables.TicketsInQueue.Remove((long)id);
return Json(new { Error = "Error fetching ticket" }, AG);
}
var sfHelper = new SalesForceHelpers();
if (!sfHelper.checkTicketOwner(zdTicket))
{
Warn(id + " | Case generation not necessary. Ticket doesn't meet criteria.");
Log("--------------- ENDING CASE [ZENDESK][" + id + "] ---------------");
GlobalVariables.TicketsInQueue.Remove((long)id);
return Json(new { success = "case was not generated" }, AG);
}
Log(id + " | Generating SalesForce case for Zendesk");
var sfCase = sfHelper.GenerateCase(zdTicket);
if (sfCase == null)
{
Warn(id + " | Case was not generated successfully. Cannot continue.");
Log("--------------- ENDING CASE [ZENDESK][" + id + "] ---------------");
GlobalVariables.TicketsInQueue.Remove((long)id);
return Json(new { Error = "Case was not generated successfully. Cannot continue." }, AG);
}
GetZDAttachments(zdHelper, sfHelper, (long)id, sfCase);
if (!zdTicket.Status.ToLower().Contains("closed") && ZendeskHelpers.GetCustomField(zdTicket, ZdCustomFields.SfCaseNo) == null)
zdHelper.SetSfId(zdTicket, sfCase.CaseNumber);
Log("--------------- ENDING CASE [ZENDESK][" + id + "] ---------------");
GlobalVariables.TicketsInQueue.Remove((long)id);
return Json(new { SFCase = sfCase }, AG);
}
Your code is full of conditionals (too many ifs) and that is the reason for verbosity. You should replace your conditionals with polymorphism. A good article for that is provided here
http://www.refactoring.com/catalog/replaceConditionalWithPolymorphism.html

SimpleJSON Unity Exception: Error deserializing JSON. Unknown tag: 123

I'm Getting this error when accessing data from a json file.
I'm trying to follow the following tutorial: http://wiki.unity3d.com/index.php/SimpleJSON
and created a test.json file, that I want to extract data from containing:
{
"version": "1.0",
"data": {
"sampleArray": [
"string value",
5,
{
"name": "sub object"
}
]
}
}
using the following code in Unity:
void LoadFiles()
{
FileInfo f = m_info[0]; //Array of Files in Folder
// I had a foreach loop here, but wanted to specify the file for testing before I tried to parse through one of my own
print("I Found : " + f);
var N = JSONNode.LoadFromFile(f.FullName);
var versionString = N["version"].Value; // versionString will be a string containing "1.0"
var versionNumber = N["version"].AsFloat; // versionNumber will be a float containing 1.0
var name = N["data"]["sampleArray"][2]["name"];// name will be a string containing "sub object"
print("vs=" + versionString + " vn=" + versionNumber + " name=" + name);
}
and all i get is Unknown tags, from what I gather from the source :
public static JSONNode Deserialize(System.IO.BinaryReader aReader)
{
JSONBinaryTag type = (JSONBinaryTag)aReader.ReadByte();
switch(type)
{
case JSONBinaryTag.Array:
{
int count = aReader.ReadInt32();
JSONArray tmp = new JSONArray();
for(int i = 0; i < count; i++)
tmp.Add(Deserialize(aReader));
return tmp;
}
case JSONBinaryTag.Class:
{
int count = aReader.ReadInt32();
JSONClass tmp = new JSONClass();
for(int i = 0; i < count; i++)
{
string key = aReader.ReadString();
var val = Deserialize(aReader);
tmp.Add(key, val);
}
return tmp;
}
case JSONBinaryTag.Value:
{
return new JSONData(aReader.ReadString());
}
case JSONBinaryTag.IntValue:
{
return new JSONData(aReader.ReadInt32());
}
case JSONBinaryTag.DoubleValue:
{
return new JSONData(aReader.ReadDouble());
}
case JSONBinaryTag.BoolValue:
{
return new JSONData(aReader.ReadBoolean());
}
case JSONBinaryTag.FloatValue:
{
return new JSONData(aReader.ReadSingle());
}
default:
{
throw new Exception("Error deserializing JSON. Unknown tag: " + type);
}
}
}
I'm falling all the way through the Switch, but with .Value or .AsFloat I should hit those case statements. Any Idea what's going on, is this code to old for Unity 5.0 ?
It seems like I was under false pretenses, that the JSON file was like XML, text, well it seems it is not, or at least assumed to be binary by SimpleJson when reading files. I tried writing the "Text" to a file, and then reading it and it worked fine. So this is an error where I assumed the data in the examples to be text.
JSONNode.LoadFromFile function instead to JSONNode.Parse(string) convert stream to string
System.IO.FileStream fs = System.IO.File.OpenRead(f.FullName);
long length = fs.Length;
byte[] stream = new byte[length];
fs.Read(stream, 0, (int)length);
string json = System.Text.Encoding.UTF8.GetString(stream);
var N = JSONNode.Parse(json);

Format values as a valid json file in C#

I'm trying to write lines in a valid JSON format using C# in a efficient way
What the file should look like:
[
{
"uuid": "c92161ba-7571-3313-9b59-5c615d25251c",
"name": "thijmen321"
},
{
"uuid": "3b90891d-e6fc-44cc-a1a8-e822378ec148",
"name": "TehGTypo"
},
{
"uuid": "5f820c39-5883-4392-b174-3125ac05e38c",
"name": "CaptainSparklez"
}
]
I already have the names and the UUIDs, but I need a way to write them to a file. I want to do this one by one, so, first the file looks like this:
[
{
"uuid": "c92161ba-7571-3313-9b59-5c615d25251c",
"name": "thijmen321"
}
]
Then like this:
[
{
"uuid": "c92161ba-7571-3313-9b59-5c615d25251c",
"name": "thijmen321"
},
{
"uuid": "3b90891d-e6fc-44cc-a1a8-e822378ec148",
"name": "TehGTypo"
}
]
etc. But of course, the UUIDs and the names are different, so how can I do this in a efficient way without using any APIs etc.?
My current (really inefficient) code:
public void addToWhitelist()
{
if (String.IsNullOrEmpty(whitelistAddTextBox.Text)) return;
string player = String.Empty;
try
{
string url = String.Format("https://api.mojang.com/users/profiles/minecraft/{0}", whitelistAddTextBox.Text);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(url));
request.Credentials = CredentialCache.DefaultCredentials;
using (WebResponse response = request.GetResponse())
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
player = reader.ReadToEnd();
}
catch (WebException ex)
{
Extensions.ShowError("Cannot connect to http://api.mojang.com/! Check if you have a valid internet connection. Stacktrace: " + ex, MessageBoxIcon.Error);
}
catch (Exception ex)
{
Extensions.ShowError("An error occured! Stacktrace: " + ex, MessageBoxIcon.Error);
}
if (String.IsNullOrWhiteSpace(player)) { Extensions.ShowError("This player doesn't seem to exist.", MessageBoxIcon.Error); return; }
player = player.Replace(",\"legacy\":true", "")
.Replace("\"id", " \"uuid")
.Replace("\"name", " \"name")
.Replace(",", ",\n")
.Replace("{", " {\n")
.Replace("}", "\n },");
File.WriteAllText(Program.programPath + #"\Servers\" + servers[currentIndex].Name + #"\whitelist.json", "");
try
{
using (StreamWriter sw = File.AppendText(Program.programPath + #"\Servers\" + servers[currentIndex].Name + #"\whitelist.json"))
{
sw.WriteLine("[");
foreach (string s in File.ReadAllLines(Program.programPath + #"\Servers\" + servers[currentIndex].Name + #"\whitelist.json"))
if (s.Contains("[") || s.Contains("]") || s.Equals(Environment.NewLine)) continue;
else sw.WriteLine(s);
sw.WriteLine(player);
sw.WriteLine("]");
whitelistListBox.Items.Add("\n" + whitelistAddTextBox.Text);
}
}
catch (Exception ex) { Extensions.ShowError("An error occured while update whitelist.json! Stacktrace: " + ex); }
whitelistAddTextBox.Clear();
}
The recommand "Microsoft" way is with a data contract and the DataContractJsonSerializer.. see here
https://msdn.microsoft.com/de-de/library/system.runtime.serialization.json.datacontractjsonserializer%28v=vs.110%29.aspx
an example of the contact would be:
[DataContract]
internal class Person
{
[DataMember]
internal string name;
[DataMember]
internal string Uuid ;
}
you use the class in the following way (obviously)
Person p = new Person();
p.name = "John";
p.Uuid = "3b90891d-e6fc-44cc-a1a8-e822378ec148";
and serialize it with the Contract Serializer
MemoryStream stream1 = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Person));
ser.WriteObject(stream1, p);
example to show the serialzed data:
stream1.Position = 0;
StreamReader sr = new StreamReader(stream1);
Console.WriteLine(sr.ReadToEnd());
Try json.net it will do the serialization job for you: http://www.newtonsoft.com/json
I would use a JSON Serializer like http://www.newtonsoft.com/json
This would allow you to roll your uuid/name as a class, instead of doing the parsing yourself
So something like:
internal class UuidNamePair
{
string Uuid { get; set; }
string Name { get; set; }
}
Then when calling this, you would just do something like this:
List<UuidNamePair> lst = new List<UuidNamePair>();
lst.Add(new UuidNamePair() { Name = "thijmen321", Uuid = "c92161ba-7571-3313-9b59-5c615d25251c" });
lst.Add(new UuidNamePair() { Name = "TehGTypo", Uuid = "3b90891d-e6fc-44cc-a1a8-e822378ec148" });
string json = JsonConvert.SerializeObject(lst, Formatting.Indented);
Console.WriteLine(json);
Instead of the Console.WriteLine, you could do your POST to a web service or however you're trying to use this json.

Creating tree view dynamically according to json text in Winforms

I am building an application that gets in run-time JSON message from external source.
I don't know anything about the structure of the message text.
I want to take this JSON text, render it to a tree view (or something equivalent, UI regarding),
edit this JSON in that tree view that I just dynamically created, and send the text back to the source.
I really don't know where to start..Any suggestions?
private void btn_Convert_MouseClick(object sender, MouseEventArgs e)
{
try
{
string json = rbt_display.Text;
JObject obj = JObject.Parse(json);
tvw_display.Nodes.Clear();
TreeNode parent = Json2Tree(obj);
parent.Text = "Root Object";
tvw_display.Nodes.Add(parent);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "ERROR");
}
}
private TreeNode Json2Tree(JObject obj)
{
//create the parent node
TreeNode parent = new TreeNode();
//loop through the obj. all token should be pair<key, value>
foreach (var token in obj)
{
//change the display Content of the parent
parent.Text = token.Key.ToString();
//create the child node
TreeNode child = new TreeNode();
child.Text = token.Key.ToString();
//check if the value is of type obj recall the method
if (token.Value.Type.ToString() == "Object")
{
// child.Text = token.Key.ToString();
//create a new JObject using the the Token.value
JObject o = (JObject)token.Value;
//recall the method
child = Json2Tree(o);
//add the child to the parentNode
parent.Nodes.Add(child);
}
//if type is of array
else if (token.Value.Type.ToString() == "Array")
{
int ix = -1;
// child.Text = token.Key.ToString();
//loop though the array
foreach (var itm in token.Value)
{
//check if value is an Array of objects
if (itm.Type.ToString() == "Object")
{
TreeNode objTN = new TreeNode();
//child.Text = token.Key.ToString();
//call back the method
ix++;
JObject o = (JObject)itm;
objTN = Json2Tree(o);
objTN.Text = token.Key.ToString() + "[" + ix + "]";
child.Nodes.Add(objTN);
//parent.Nodes.Add(child);
}
//regular array string, int, etc
else if(itm.Type.ToString() == "Array")
{
ix++;
TreeNode dataArray = new TreeNode();
foreach (var data in itm)
{
dataArray.Text = token.Key.ToString() + "[" + ix + "]";
dataArray.Nodes.Add(data.ToString());
}
child.Nodes.Add(dataArray);
}
else
{
child.Nodes.Add(itm.ToString());
}
}
parent.Nodes.Add(child);
}
else
{
//if token.Value is not nested
// child.Text = token.Key.ToString();
//change the value into N/A if value == null or an empty string
if (token.Value.ToString() == "")
child.Nodes.Add("N/A");
else
child.Nodes.Add(token.Value.ToString());
parent.Nodes.Add(child);
}
}
return parent;
}
sample json
{
"firstName": "John",
"lastName": "Smith",
"isAlive": true,
"age": 25,
"height_cm": 167.6,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021-3100"
},
"phoneNumbers": [
{
"type": "home",
"number": "212 555-1234"
},
{
"type": "office",
"number": "646 555-4567"
}
],
"children": [],
"spouse": null
}
Note: This example uses NewtonSoft Json. Right-click solution and click manage NuGet packages to install the reference.
This code will handle both JArray or JObject as an input:
string jsonString = "your json string here";
string rootName = "root", nodeName = "node";
JContainer json;
try {
if (jsonString.StartsWith("["))
{
json = JArray.Parse(jsonString);
treeView1.Nodes.Add(Utilities.Json2Tree((JArray)json, rootName, nodeName));
}
else
{
json = JObject.Parse(jsonString);
treeView1.Nodes.Add(Utilities.Json2Tree((JObject)json, text));
}
}
catch(JsonReaderException jre)
{
MessageBox.Show("Invalid Json.");
}
public class Utilities
{
public static TreeNode Json2Tree(JArray root, string rootName = "", string nodeName="")
{
TreeNode parent = new TreeNode(rootName);
int index = 0;
foreach(JToken obj in root)
{
TreeNode child = new TreeNode(string.Format("{0}[{1}]", nodeName, index++));
foreach (KeyValuePair<string, JToken> token in (JObject)obj)
{
switch (token.Value.Type)
{
case JTokenType.Array:
case JTokenType.Object:
child.Nodes.Add(Json2Tree((JObject)token.Value, token.Key));
break;
default:
child.Nodes.Add(GetChild(token));
break;
}
}
parent.Nodes.Add(child);
}
return parent;
}
public static TreeNode Json2Tree(JObject root, string text = "")
{
TreeNode parent = new TreeNode(text);
foreach (KeyValuePair<string, JToken> token in root)
{
switch (token.Value.Type)
{
case JTokenType.Object:
parent.Nodes.Add(Json2Tree((JObject)token.Value, token.Key));
break;
case JTokenType.Array:
int index = 0;
foreach(JToken element in (JArray)token.Value)
{
parent.Nodes.Add(Json2Tree((JObject)element, string.Format("{0}[{1}]", token.Key, index++)));
}
if (index == 0) parent.Nodes.Add(string.Format("{0}[ ]", token.Key)); //to handle empty arrays
break;
default:
parent.Nodes.Add(GetChild(token));
break;
}
}
return parent;
}
private static TreeNode GetChild(KeyValuePair<string, JToken> token)
{
TreeNode child = new TreeNode(token.Key);
child.Nodes.Add(string.IsNullOrEmpty(token.Value.ToString()) ? "n/a" : token.Value.ToString());
return child;
}
}
You can try this code :
public class JsonTag
{
public JsonTag(JsonReader reader)
{
TokenType = reader.TokenType;
Value = reader.Value;
ValueType = reader.ValueType;
}
public JsonToken TokenType { get; set; }
public object Value { get; set; }
public Type ValueType { get; set; }
}
private void JsonToTreeview(string json)
{
tvwValue.BeginUpdate();
var parentText = string.Empty;
TreeNodeCollection parentNodes = tvwValue.Nodes;
TreeNode current = null;
tvwValue.Nodes.Clear();
var reader = new JsonTextReader(new StringReader(json));
while (reader.Read())
{
switch (reader.TokenType)
{
case JsonToken.None:
break;
case JsonToken.StartObject:
current = new TreeNode("{}") { Tag = new JsonTag(reader) };
parentNodes.Add(current);
parentNodes = current.Nodes;
break;
case JsonToken.StartArray:
current = new TreeNode("[]") { Tag = new JsonTag(reader) };
parentNodes.Add(current);
if (current.PrevNode != null)
{
if (((JsonTag)current.PrevNode.Tag).TokenType == JsonToken.PropertyName)
current.Parent.Text += "[]";
parentText = current.Parent.Text;
if (current.Parent.Parent.Text.Length > 2)
parentText = ", " + parentText;
current.Parent.Parent.Text = current.Parent.Parent.Text.Insert(current.Parent.Parent.Text.Length - 1, parentText);
}
parentNodes = current.Nodes;
break;
case JsonToken.StartConstructor:
break;
case JsonToken.PropertyName:
current = new TreeNode("\"" + reader.Value + "\" : ");
parentNodes.Add(current);
if (current.PrevNode != null)
current.PrevNode.Text += ",";
parentNodes = current.Nodes;
current = new TreeNode(reader.Value.ToString()) { Tag = new JsonTag(reader) };
parentNodes.Add(current);
break;
case JsonToken.Comment:
break;
case JsonToken.Raw:
break;
case JsonToken.Date:
case JsonToken.Integer:
case JsonToken.Float:
case JsonToken.Boolean:
case JsonToken.String:
var readerValue = "";
if (reader.TokenType == JsonToken.String)
readerValue = "\"" + reader.Value + "\"";
else
readerValue = reader.Value.ToString();
current = new TreeNode(readerValue) { Tag = new JsonTag(reader) };
parentNodes.Add(current);
current.Parent.Text += readerValue;
parentText = current.Parent.Text;
if (current.Parent.Parent.Text.Length > 2)
parentText = ", " + parentText;
current.Parent.Parent.Text = current.Parent.Parent.Text.Insert(current.Parent.Parent.Text.Length - 1, parentText);
if (((JsonTag)current.PrevNode.Tag).TokenType == JsonToken.PropertyName)
current = current.Parent;
current = current.Parent;
parentNodes = current.Nodes;
break;
case JsonToken.Bytes:
break;
case JsonToken.Null:
break;
case JsonToken.Undefined:
break;
case JsonToken.EndObject:
if (current.FirstNode.Tag != null &&
((JsonTag)current.FirstNode.Tag).TokenType == JsonToken.PropertyName)
current = current.Parent;
current = current.Parent;
if (current == null)
parentNodes = tvwValue.Nodes;
else
parentNodes = current.Nodes;
break;
case JsonToken.EndArray:
if (((JsonTag)current.PrevNode.Tag).TokenType == JsonToken.PropertyName)
current = current.Parent;
current = current.Parent;
if (current == null)
parentNodes = tvwValue.Nodes;
else
parentNodes = current.Nodes;
break;
case JsonToken.EndConstructor:
break;
default:
throw new ArgumentOutOfRangeException();
}
}
tvwValue.EndUpdate();
}
Lots of questions there, really. If you really need guidance on every part of that then it's a lot to try and answer here.
There are classes for reading JSON structures, readily available. As Yosi indirectly linked, there's JSON.net
Once you can read the JSON, you can use it to construct the TreeView
Editing is simple enough, as the TreeView has a property for LabelEdit that supports editing in-place. From there, it's just a matter of reacting to that and keeping track of the changes. Or perhaps reading it all back out in one fell swoop at the end, your choice. Either way, the TreeView has events such as BeforeLabelEdit, AfterLabelEdit, etc., all of which can be found on the TreeView link above.
From the package manager console:
PM> Install-Package Newtonsoft.Json
Then cleaning up #vinceg 's answer, I rolled a static class:
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Windows.Forms;
public static class clsJSON2treeview
{
/// <summary>Parse JSON string, individual tokens become TreeView Nodes ~mwr</summary>
/// <param name="oTV">TreeView control to display parsed JSON</param>
/// <param name="sJSON">Incoming JSON string</param>
/// <param name="rootName">Title of top node in TreeView wrapping all JSON</param>
public static void JsonToTreeview(TreeView oTV, string sJSON, string rootName)
{
JContainer json = sJSON.StartsWith("[")
? (JContainer)JArray.Parse(sJSON)
: (JContainer)JObject.Parse(sJSON);
oTV.Nodes.Add(Ele2Node(json, rootName));
}
private static TreeNode Ele2Node(object oJthingy, string text = "")
{
TreeNode oThisNode = new TreeNode(text);
switch (oJthingy.GetType().Name) //~mwr could not find parent object for all three JObject, JArray, JValue
{
case "JObject":
foreach (KeyValuePair<string, JToken> oJtok in (JObject)oJthingy)
oThisNode.Nodes.Add(Ele2Node(oJtok.Value, oJtok.Key));
break;
case "JArray":
int i = 0;
foreach (JToken oJtok in (JArray)oJthingy)
oThisNode.Nodes.Add(Ele2Node(oJtok, string.Format("[{0}]", i++)));
if (i == 0) oThisNode.Nodes.Add("[]"); //to handle empty arrays
break;
case "JValue":
oThisNode.Nodes.Add(new TreeNode(oJthingy.ToString()));
break;
default:
throw new System.Exception("clsJSON2Treeview can't interpret object:" + oJthingy.GetType().Name);
}
return oThisNode;
}
}

Convert JSON as String to DataTable in C#

I have pass the JSON value as String & in C# need to convert to DataTable.
I have done in android part,(making a json as String)
public void getUploadTableData(){
DBAdapter dbAdapter = DBAdapter.getDBAdapterInstance(this);
dbAdapter.openDataBase();
try {
if(uploadTable.size() > 0){
for (Map.Entry<Integer, String> entry : uploadTable.entrySet()) {
int key = entry.getKey();
String value = entry.getValue();
JSONObject invHeader = new JSONObject();
if(value.equals("WMInvoiceHeader")){
String query = "SELECT BusinessUnit,ExecutiveCode,InvoiceNo,SalesCategory,RetailerCode," +
" RetailerCodeSon,InvoiceDate,GrossValue,InvoiceValue,TotalLineDiscount," +
" FROM WMInvoiceHeader " +
" WHERE (CancelFlag IS NULL OR CancelFlag ='0')";
ArrayList<?> stringList = dbAdapter.selectRecordsFromDBList(query, null);
if(stringList.size() > 0){
for (int i = 0; i < stringList.size(); i++) {
ArrayList<?> arrayList = (ArrayList<?>) stringList.get(i);
ArrayList<?> list = arrayList;
invHeader.put("BusinessUnit",(String)list.get(0));
invHeader.put("ExecutiveCode",(String)list.get(1));
invHeader.put("InvoiceNo",(String)list.get(2));
invHeader.put("SalesCategory",(String)list.get(3));
invHeader.put("RetailerCode",(String)list.get(4));
invHeader.put("RetailerCodeSon",(String)list.get(5));
invHeader.put("InvoiceDate",(String)list.get(6));
invHeader.put("GrossValue",(String)list.get(7));
invHeader.put("InvoiceValue",(String)list.get(8));
invHeader.put("TotalLineDiscount",(String)list.get(9));
}
System.out.println("----invHeader---" + invHeader.toString());
}
soapPrimitiveData("WMInvoiceHeader", strBusinessUnit, strExecutive, invHeader.toString());
}
// System.out.println("----invHeader---" + invHeader.toString());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
This is my webservice part....
// ksoap2 calling wcf
public SoapPrimitive soapPrimitiveData(String tablename,String strBusinessUnit, String strExecutive,String jsonString) throws IOException,XmlPullParserException {
SoapPrimitive responsesData = null;
SoapObject requestData = new SoapObject(NAMESPACE, METHOD_NAME); // set
requestData.addProperty("strBusinessUnit", strBusinessUnit);
requestData.addProperty("strExecutive", strExecutive);
requestData.addProperty("strTableName", tablename);
requestData.addProperty("jsonContent", jsonString);
SoapSerializationEnvelope envelopes = new SoapSerializationEnvelope(SoapEnvelope.VER11); // put all required data into a soap//// envelope
envelopes.dotNet = true;
envelopes.setOutputSoapObject(requestData);
AndroidHttpTransport httpTransport = new AndroidHttpTransport(APPURL);
httpTransport.debug = true;
try {
httpTransport.call(SOAP_ACTION, envelopes);
responsesData = (SoapPrimitive) envelopes.getResponse();
} catch (SocketException ex) {
Log.e("Error : " , "Error on soapPrimitiveData() " + ex.getMessage());
ex.printStackTrace();
} catch (Exception e) {
Log.e("Error : " , "Error on soapPrimitiveData() " + e.getMessage());
e.printStackTrace();
}
return responsesData;
}
This is my C# code
public bool convertJSONToDataSet(string strBusinessUnit, string strExecutiveCode, string strTableName, string jsonContent)
{
bool status =false;
DataTable dataTable = JsonConvert.DeserializeObject<DataTable>(jsonContent);
status = UpdateUploadData(strBusinessUnit, strExecutiveCode, strTableName, dataTable);
return status;
}
When i call webservice this method conversion part giving error .It say Additional text found in JSON string after finishing deserializing object.
This is my json result in C#
{
"SpecialDiscountFlag": "0",
"TotalLineDiscount": "0",
"ExecutiveCode": "TEST001",
"InvoiceValue": "3000",
"InvoiceDate": "2011-11-17",
"RouteCode": "VRT002",
"RetailerCode": "TEST0007",
"HeaderDiscountFlag": "1",
"GrossValue": "3000",
"UploadedOn": "2011-11-17",
"SalesType": "O",
"VisitNumber": "26",
"UploadFlag": "1",
"InvoiceNo": "26",
"SalesCategory": "VSAO",
"BusinessUnit": "MASS",
"VisitSequence": "1",
"UploadedBy": "TEST001",
"TotalHeaderDiscount": "0"
}
Please tell me what is wrong here.
I want to do the Convert JSON as String to DataTable in C#
Json string should be like below:
{
"List": [
{
"ProjectId": 504,
"RowId": 1,
"ProjectName": "Google",
"Member": "Private"
},
{
"ProjectId": 503,
"RowId": 2,
"ProjectName": "Facebook",
"Member": "Public"
}
]
}
Where "List" treated as your table name and data inside curly brackets treated as row for DataTable
To validate json string you can use this site: http://jsonlint.com/

Categories

Resources