First of all, I'm very new to C# and Json.
I wanted to plot a graph from mysql table data in a C# GUI. I made a PHP file to select the data from mysql database table and echoed the selected contents in json array using echo json_encode(array("result"=>$result))
here is my PHP:
<?php
define('HOST','*********************');
define('USER','*********************');
define('PASS','*********************');
define('DB','***********************');
if($_SERVER['REQUEST_METHOD']=='GET'){
$start = $_GET['start'];
$ending = $_GET['ending'];
}
$con = mysqli_connect(HOST,USER,PASS,DB);
$sql = "SELECT * FROM table WHERE date_time BETWEEN '$start' and '$ending'" ;
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,array('id'=>$row[0],'p_pairs'=>$row[1],'temp1'=>$row[2] ,'temp2'=>$row[3],'temp3'=>$row[4],'temp4'=>$row[5],'temp5'=>$row[6],'avg_current'=>$row[7],'avg_voltage'=>$row[8],'kw'=>$row[9],'kwh'=>$row[10]));
}
echo json_encode(array($result));
mysqli_close($con);
?>
using the link, I can see the json array clearly between the datetime gap.All I wanted is to plot the graph of temperature values (temp1, temp2,..), p-pairs values and others with the date_time in a line graph to read the historical data.
All I get when I access the PHP page is:
[[{"id":"1","p_pairs":"0000-00-00 00:00:00","temp1":"2","temp2":"100","temp3":"100","temp4":"100","temp5":"100","avg_current":"100","avg_voltage":"300","kw":"300","kwh":"300"},{"id":"2","p_pairs":"0000-00-00 00:00:00","temp1":"45","temp2":"105","temp3":"230","temp4":"100","temp5":"2500","avg_current":"570","avg_voltage":"100","kw":"250","kwh":"1000"},{"id":"3","p_pairs":"2016-01-07 21:10:00","temp1":"45","temp2":"105","temp3":"230","temp4":"100","temp5":"2500","avg_current":"570","avg_voltage":"100","kw":"250","kwh":"1000"},{"id":"4","p_pairs":"2016-01-07 21:10:00","temp1":"45","temp2":"105","temp3":"230","temp4":"100","temp5":"2500","avg_current":"570","avg_voltage":"100","kw":"250","kwh":"1000"}]]
NOTE: some datetime is set as default here. I just wanted to show this array. The correct one will be perfect to plot the graph.
I can can take these array in a string using a web request from C#. using the bellow code:
System.Net.WebClient wc = new System.Net.WebClient();
byte[] raw = wc.DownloadData("url to php");
string webData = System.Text.Encoding.UTF8.GetString(raw);
It'll be a big help If someone can help me to plot this in a line graph as date_time Vs temp1, temp2 or p_pairs and like that in C# GUI...
This is going to be a big help for me.
Thanking you in advance.
Firstly get a class to work from. You can dynamically create a class from Json
If you are happy to have a dependency upon the System.Web.Helpers assembly, then you can use the Json class:
dynamic data = Json.Decode(json);
It is included with the MVC framework as an additional download to the .NET 4 framework. Or use the NewtonSoft one.
Next get a chart component: https://msdn.microsoft.com/en-us/library/dd489237.aspx and bind your data to the chart
Related
I am trying to convert a Postman output file from JSON to a CSV. In the past I have just used a json to csv converter but I have some sensitive data for a particular file and do not feel comfortable using an online tool. Searched for some code that might be able to help me with this. When I run this in visual studio I do not see a file created. I will admit I have not done any C# in years and all I really am using it for is to convert this one json file to a csv. Can someone please take a quick look at this code and let me know what I am doing wrong? The jsonInput is not the actual input I am using. Just want to use that as an example. I plan to use a filename for the input but can try figuring that out on my own. Just hoping to get some help to just get a file created.
```
using Aspose.Cells;
using Aspose.Cells.Utility;
using DocumentFormat.OpenXml.Spreadsheet;
using Microsoft.AspNet.SignalR.Json;
// load JSON data
string jsonInput = "[{'nodeId':1,'reputation':1134},{'nodeId':2,'reputation':547},{'nodeId':3,'reputation':1703},{'nodeId':4,'reputation':-199},{'nodeId':5,'reputation':-306},{'nodeId':6,'reputation':-49},{'nodeId':7,'reputation':1527},{'nodeId':8,'reputation':1223}]";
// create a blank Workbook object
var workbook = new Aspose.Cells.Workbook();
// access default empty worksheet
var worksheet = workbook.Worksheets[0];
// set JsonLayoutOptions for formatting
var layoutOptions = new JsonLayoutOptions();
layoutOptions.ArrayAsTable = true;
// import JSON data to CSV
Aspose.Cells.Utility.JsonUtility.ImportData(jsonInput, worksheet.Cells, 0, 0, layoutOptions);
// save CSV file
workbook.Save("Test.csv", SaveFormat.Csv);
```
I have a Google Sheets form that has been set up to take form data, format it into a QBXML Invoice Add Request, then save it as a text document (.gdoc). My issue is that the QBFC C# sample code that I have found is all based around building the QBXML request and then sending that; I haven't been able to figure out how to send the ready-made QBXML document to Quickbooks Desktop as a request.
For example, this code doesn't work because DoRequests() needs to be passed an IMsgSetRequest and won't accept a string:
String xmlDoc = File.ReadAllText("J:\\My Drive\\XML Test Doc.gdoc");
IMsgSetResponse responseMsgSet = sessionManager.DoRequests(xmlDoc);
And this won't work either, because you can't convert form a string to an IMsgSetRequest:
String xmlDoc = File.ReadAllText("J:\\My Drive\\XML Test Doc.gdoc");
IMsgSetRequest requestMsgSet = xmlDoc;
IMsgSetResponse responseMsgSet = sessionManager.DoRequests(requestMsgSet);
I'm assuming (and hoping) that there's a simple solution that I'm just overlooking. But if there is, it's eluded me for long enough that I've decided that it's worth reaching out to you folks for assistance. Thanks in advance.
The QBSessionManager has a .DoRequestsFromXMLString that you could pass the full XML string to (which you read from your file).
Its definition is:
IMsgSetResponse DoRequestsFromXMLString(string qbXMLRequest);
You need to use QBXML instead of QBFC. QBFC is a wrapper that generates the QBXML. Since you already have the QBXML generated you can bypass QBFC. Include a reference to QBXMLRP2Lib and the following code should allow you to send the data to QuickBooks.
String xmlDoc = File.ReadAllText("J:\\My Drive\\XML Test Doc.gdoc");
QBXMLRP2Lib.IRequestProcessor5 rp = new QBXMLRP2Lib.RequestProcessor3();
rp.OpenConnection2("AppID", "AppName", QBXMLRP2Lib.QBXMLRPConnectionType.localQBD);
string ticket = rp.BeginSession("", QBXMLRP2Lib.QBFileMode.qbFileOpenDoNotCare);
string response = rp.ProcessRequest(ticket, xmlDoc);
You may find that this tool helps: SDKTestPlus3. The tool handles the connection to Quickbooks Desktop and you can then pass your XML file over.
I am getting data from a rest feed at regular intervals and want to copy this into a SQL table. Easy enough using SQLBulk copy.
The issue i am struggling with is that the fields I get from the feed could change and i want to be able to add any new columns dynamically to the table. Any columns that no longer exist i need to leave in the table. I can simply add those into the datatable.
My question. What options do i have to do this. Is there any free 3rd party .net frameworks that will do it or how can i write this manually.
Must all be done in .NET.
Thanks
as you stated that you are getting data from a rest feed then u can create a simple ASP WebPages Application
Add a page in which you are going to call the "Rest Feed".
Now what format the Rest Feed is offering
mostly JSON is used
you can parse JSON to a Model Class which corresponds to the data structure of that feed
then simply insert the data using SQLConnection , SQLCommand to the underlying database
here is a sample code which you can alter
string siteContent = string.Empty;
string url = "http://www.RESTFEEDURL.com";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
using(HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using(Stream responseStream = response.GetResponseStream())
using(StreamReader streamReader = new StreamReader(responseStream))
{
siteContent = streamReader.ReadToEnd();
}
//NOW PARSE THE DATA AND SEND TO DATABASE HERE
//data is in siteContent
//now you want to decode the data and get all the column names
var keyArray = Ext.Object.getKeys(Ext.JSON.decode(siteContent));
//if suppose data has following format
//{"ID":"1","name":"google","IP":"69.5.33.22","active":"true"}
//{"ID":"2","name":"bing","IP":"70.5.232.33","active":"false"}
console.log(keyArray);
// ["ID","name","IP","active"]
now
foreach(var item as keyArray)
{
sql = "IF COL_LENGTH('TABLENAME', item) IS NULL alter table [TABLENAME] add [item] int default 0 NOT NULL"
//run this sql query using sql command and see the magic
}
I have php website on server and c# winform on client.
is there any way to get field value of the php current page using c#?
for example, in the php I have firstName field of customer (he just typed it) and I need to use this value in the c# program.
Thanks in advance!
suppose u have a php script in which you get firstName (let's say getName.php):
<?php
$firstName = $_POST['firstName']; // or any other way to get it
$arr = array('firstname' => $firstName);
echo json_encode($arr);
?>
this will show something like this:
{"firstname": your_firstname }
so now this JSON can be used in any programming language that you want. In your case for C#:
Use the WebClient class in System.Net:
var json = new WebClient().DownloadString("url_of_php_file");
Keep in mind that WebClient is IDisposable, so you would probably add a using statement to this in production code. This would look like:
using (WebClient wc = new WebClient())
{
var json = wc.DownloadString("url_of_php_file");
}
My Class in C# which should be send to PHP:
MyData data = new MyData();
data.Name = "MyName";
data.Type = "MyType";
data.ID = 1;
data.Description = "MyLongDescription...";
How do I send it to PHP via C# in JSON format? And how do I retrieve it in PHP?
The next step should be to insert the submitted data/values into a MySQL DB.
C# -> Send some JSON Data to PHP -> Write JSON Data to MYSQL DB via PHP
Sample Database:
MyData(varchar Name, varchar Type, int ID, varchar Description)
My current PHP Code:
$json = json_decode($input,true);
$connection = mysql_connect("localhost","root","");
if (!$connection)
{
die(mysql_error());
}
mysql_select_db("MyDataDB", $con);
mysql_query("INSERT INTO MyData (Name, Type, OtherID, Description)
VALUES('$json[Name]','$json[Type]','$json[ID]','$json[Description]')");
Any ideas?
Thanks for your efforts.
C# code to encode:
var jsonSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string json = jsonSerializer.Serialize(yourCustomObject);
PHP code to decode:
$decoded = json_decode($received_json_string);
What have you tried, by the way?
I'll answer this, but to Quentin's point, you've got a lot going on.
There is no direct interop between C# and PHP so you'd need to expose a web service from PHP and consume it in your C#. Better yet, have the C# save directly to mysql and don't worry about interop.