How to connect json file with c# - c#

I have Json file connected with database: http://222.255.29.210:9000/pk/api/index.php/fbids
In code boder red: If I set "des = true" in database then tool run, if I set "des = false" then Winform c# close. Use Json data

I guess that your data on JSON come from database right ?
So, use Json.net to determine your program in c#
to read that json object and check is "des = true" or not.

Related

Keep special characters in File When i save it

I have a file that contains some HTML code. I am trying to load this data into a C# Console app and transfer it into a JSON file to upload somewhere. When loading the file i am losing some of the encoding immediately when bringing the data in.
Example data
<li>Comfort Range: -60°F to 30°F / -50°C to -1°C</li>
Basic read file
//Load the file
String HTML_File = File.ReadAllText(location);
//Output the file to see the text
Console.WriteLine(HTML_File);
Console Output
<li>Comfort Range: -60??F to 30?F / -50?C to -1?C</li>
After i split the data how I need to, I than save the class to a JSON File
File.WriteAllText(OutputPath,JsonConvert.SerializeObject(HTMLDATA));
JSON file Data
<li>Comfort Range: -60�F to 30�F / -50�C to -1�C</li>
How can i go about loading this data and converting it to JSON without losing the encoding? I am still pretty new when it comes to encoding like this.
#JeremyLakeman helped me solve this, thank you sir!! When reading the text into the utility i needed to set the Encoding but not by the default ones.
File.WriteAllText(OutputPath,JsonConvert.SerializeObject(HTMLDATA), Encoding.GetEncoding("iso-8859-1"));
#JeremyLakeman helped me solve this, thank you sir!! When reading the text into the utility i needed to set the Encoding but not by the default ones.
File.WriteAllText(OutputPath,JsonConvert.SerializeObject(HTMLDATA), Encoding.GetEncoding("iso-8859-1"));

How to open Image manager through Enterprise Architect API

I am working on Enterprise Architect through C# add-ins. I need to display the image manager through automation where user can add directly add images on an "add image" button click in form.
I use the API Repository.InvokeConstructPicker() but it only opens the select package/class/component window. Is there an EA API available to open the Image Manager.
No, there is none. There is the undocumented Respository.CustomCommand which can open several properties windows. But the image manager is not part of that (or it has not been discovered what parameters to supply).
Please see Edit2 below about adding new values to the table.
Edit: Based on another question I had to dig into this a bit deeper.
I found out that, although EA imports a number of different image formats, it internally uses PNG to store the image. Obviously their BMP-importer does not like all BMP formats (not so deep in that, but I seem to remember there's some 8/16 bit stuff; typical Windoze weirdness). Anyhow, I used this Python code snippet to retrieve some test image data, previously imported into EA:
import sys
import win32com.client
import base64
import xml.etree.ElementTree
eaRep = None
try:
eaApp = win32com.client.GetActiveObject(Class="EA.App")
eaRep = eaApp.repository
except:
print "failure to open EA"
sys.exit(2)
def dump():
sqlRes = eaRep.SQLQuery("SELECT * FROM t_image")
root = xml.etree.ElementTree.fromstring(sqlRes)
for dataset in root:
for data in dataset:
for row in data:
name = row[1].text
print name
data = row[3].text
png = base64.standard_b64decode(data)
file = open("c:/" + name + ".png", "wb")
file.write(png)
file.close()
dump()
This correctly extracted the images from the database.
Edit2: I was assuming that EA stores the png as base64, but that's not true. EA only delivers base64 on return of SQLQuery. But they internally just store the raw png in Image. So, unfortunately, you can not use Repository.Execute since it can not transport binary data - or at least I have not figured out how to do that. As a work around you can look into Repository.ConnectionString and open a native connection to the database. Once you have plugged the new picture(s) in the table you can use them via thier ImageID.
Contents of t_image:
ImageID : You just need to create an unique ID
Name : an arbitrary string
Type : fixed string Bitmap
Image : blob of a png
Here's a Python snippet that connects natively to an EAP file:
import pyodbc
db_file = r'''C:\Documents and Settings\Administrator\Desktop\empty.eap'''
odbc_conn_str = 'DRIVER={Microsoft Access Driver (*.mdb)};DBQ=' + db_file
conn = pyodbc.connect(odbc_conn_str)
cursor = conn.cursor()
cursor.execute("select * from t_image")
row = cursor.fetchone()
if row:
print(row)
Rather than printing the row with the image data (which shows that its contents is a png-blob) you can use it to actually issue an INSERT or UPDATE to modify t_image.

Dynamic JSON schema validation using c#

I am trying to do a JSON schema validation dynamically. We are taking the JSON from an uploaded file and trying to validate this is exact JSON or not. This is an On premise application.I cannot use JSON.net. I cannot install any other third party tools to validate this. I have tried two ways as below.
1.I used System.Web.Helper and Using the below code, i am getting the error
code :
var jsonstring = "{\"user\":{\"name\":\"asdf\",\"age\":\"26\",\"teamname\":\"b\",\"email\":\"c\",\"players\":[\"1\",\"2\"]}}";
var jsonObject = Json.Decode(jsonstring);
Error is "Attempt by method 'System.Web.Helpers.Json.Decode(System.String)' to access field 'System.Web.Helpers.Json._serializer' failed". I searched for solutions and found that we need to uncheck a check box in debug properties of solution.But this only works in Console application for me.But not working in our VS 2012 solution. Is there any way to solve this issue?
Next is, i tried to use JavaScriptSerializer as given below and successfully got the results in my objJson.
JavaScriptSerializer serializer = new JavaScriptSerializer();
string inputContent;
StreamReader inputStreamReader = new StreamReader(FileUploadControl.PostedFile.InputStream);
inputContent = inputStreamReader.ReadToEnd();
inputContent = inputContent.Replace("\r", "").Replace("\n", "").Replace("\t", "");
var objJson= serializer.Deserialize>(inputContent);
But when i am trying to get values of this resulted key values pair, i am getting error as in image. Error is Dynamic operations can only be performed in homogenous AppDomain. for this the solution found was to change the attribute "legacyCasModel=true" to "legacyCasModel=false" in web.config file. But as this is OnPremise application i cannot change this attribute.Please help on this.
Suggest you to have a look at this stackoverflow post
In nutshell what you want to do is :
Perform some basic checks i.e. if JSON string starts with either
'{'
or '['
Try to parse JSON string using JToken.Parse if there
is an exception while parsing simply log or display this to end user and move on ! you are just
trying to validate JSON string not attempting to clean it right ?
PS : Please do refer the linked question for greater details.

How to read file in C# from POST data from web

Basically, I'm building a website that allows user to upload file.
From the front end (JavaScript), the user will browse a file, I can get the site to send POST data (the parameter "UploadInput" and it's value, which the value is the file)
In the backend (C#), I want to make a copy of the file and save it in a specific path.
Below is the way I did it.
var files = Request.Files;
file[0].SaveAs("\temp\\" + file[0].FileName);
The problem I ran into is that I got the error message saying index out of range. I tried Response.Write(files.Count) and it gives me 0 instead of 1.
I'm wondering where I did wrong and how to fix it, or if there's a better way of doing it.
Thanks!
Edit:
I am using HttpFox to debug. From HttpFox, I can see that under POST data, parameter is "UploadInput" and the value is "test.txt"
Edit 2:
So I tried the way Marc provides, and I have a different problem.
I am able to create a new file, however, the content is not copied over. I tried opening the new created file in notepad and all it says is "UploadInput = test.txt"
If they simply posted the file as the body content, then there will be zero "files" involved here, so file[0] will fail. Instead, you need to look at the input-stream, and simply read from that stream. For example:
using(var file = File.Create(somePath)) {
Request.InputStream.CopyTo(file);
}

write to specific position in .json file + serilaize size limit issue C#

I have a method that retrieves data from a json serialized string and writes it to a .json file using:
TextWriter writer = new StreamWriter("~/example.json");
writer2.Write("{\"Names\":" + new JavaScriptSerializer().Serialize(jsonData) + "}");
data(sample):
{"People":{"Quantity":"4"}, ,"info" :
[{"Name":"John","Age":"22"}, {"Name":"Jack","Age":"56"}, {"Name":"John","Age":"82"},{"Name":"Jack","Age":"95"}]
}
This works perfectly however the jsonData variable has content that is updated frequently. Instead of always deleting and creating a new example.json when the method is invoked,
Is there a way to write data only to a specific location in the file? in the above example say to the info section by appending another {"Name":"x","Age":"y"}?
My reasoning for this is I ran into an issue when trying to serialize a large amount of data using visual studio in C#. I got "The length of the string exceeds the value set on the maxJsonLength property” error. I tried to increase the max allowed size in the web.config using a few suggested methods in this forum but they never worked. As the file gets larger I feel I may run into the same issue again. Any other alternatives are always welcome. Thanks in advance.
I am not aware of a JSON serializer that works with chunks of JSON only. You may try using Json.NET which should work with larger data:
var data = JsonConvert.SerializeObject(new { Names = jsonData });
File.WriteAllText("example.json", data);

Categories