Insert Data using Json in C# - c#

I have some problem in inserting data to my free webhost mysql using JSON in C#. This is what I have done :
Php
<?php
/*
* Following code will create a new product row
* All product details are read from HTTP REQUEST Request
*/
require_once __DIR__ . '/db_connect.php';
//require_once __DIR__ . '/generateIDrandom.php';
require_once __DIR__ . '/Configuration.php';
$db = new DB_CONNECT();
$connstring = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);
// array for JSON response
$response = array();
// check for required fields
if (isset($_REQUEST['WSID'])) {
$wsid = $_REQUEST['WSID'];
$jenismesin = $_REQUEST['JenisMesin'];
$merk = $_REQUEST['MerkMesin'];
$lokasi = $_REQUEST['Lokasi'];
$inlok = $_REQUEST['InisialLokasi'];
$limit = $_REQUEST['LimitMesin'];
$denom = $_REQUEST['Denom'];
$tim4 = $_REQUEST['Tim4'];
$tim5 = $_REQUEST['Tim5'];
$status = "1";
// connecting to db
$result = mysqli_query($connstring, "insert into MasterATM (WSID, JenisMesin, MerkMesin, Lokasi, InisialLokasi, LimitMesin, Denom, Tim4, Tim5, Status) values ('$wsid','$jenismesin','$merk','$lokasi', '$inlok', '$limit', '$denom','$tim4','$tim5','$status')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Upload Successfully";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
C#
private void InputBtn_Click(object sender, EventArgs e)
{
try
{
WebRequest request = WebRequest.Create("https://xxx.000webhostapp.com/php/InsertDataMesin.php?WSID =" + WSIDBox.Text + "& JenisMesin = " + TipeMesinBox.SelectedItem + "& MerkMesin = " + MerkMesinCB.SelectedItem + "& Lokasi= " + LokasiBox.Text + "& InisialLokasi = " + InisialLokasiBox.Text + "& LimitMesin= " + LimitBox.Text + "& Denom= " + DenomBox.Text + "& Tim4= '" + Tim4CB.SelectedItem + "& Tim5= '" + Tim5CB.SelectedItem + "& Status = 1");
WebResponse response = request.GetResponse();
StreamReader stream = new StreamReader(response.GetResponseStream());
string json = stream.ReadToEnd();
stream.Close();
var result = JsonConvert.DeserializeObject(json);
MessageBox.Show("Data berhasil ditambahkan !");
TampilDataEdit();
}
catch
{
MessageBox.Show("Data gagal ditambahkan. Silakan coba lagi");
}
}
When I run my program, there is no some error. But when I see to my database, there is no data inserted. So, How can I insert data using json c# ?

Related

c# - How to call/link a workflow on a web application from a c# program?

I have a C# (WinForms) application that can scan documents via a printer. After scanning, I will be able to enter document details on it and have a button to finalize the documents. The documents details and info will be stored in my database ABC in certain tables.
Now, I have another web application written in Java(IntelliJ) that has some button functionality to upload documents and then start a workflow and route it to another user to approve the document. I won't go into detail on the specifics. This application also connects to the same database ABC.
So now comes the tougher part, I need to link these two applications in a way that when I finalize my document
on the C# application, it has to auto trigger the workflow on the web application side. Rather than manually starting the workflow on the web application, it would just call or trigger the workflow, so I do not need to access the web application at all for the process to start.
private void FinButton_Click(object sender, EventArgs e)
{
int count = 0;
var txtBoxFields = new List<TextBox>
{
textBox1,
textBox2,
textBox3,
textBox4,
textBox5,
textBox6,
textBox7,
textBox8,
textBox9,
textBox10,
textBox11,
textBox12,
textBox13,
textBox14,
textBox15
};
var templateFields = new List<String>
{
"T1",
"T2",
"T3",
"T4",
"T5",
"T6",
"T7",
"T8",
"T9",
"T10",
"T11",
"T12",
"T13",
"T14",
"T15"
};
//long tid = 0;
//Start insert query into templatebatch table in db
var dbConnection2 = DBConnection.Instance();
dbConnection2.DatabaseName = ConfigurationManager.AppSettings["dbName"];
if (dbConnection2.IsConnect())
{
bool test = true;
for (int i = 1; i <= 15; i++)
{
var input = txtBoxFields[i - 1].Text;
var insertQuery = "INSERT INTO templateinfo(TID, THEADER, " + templateFields[i - 1] + ") VALUES(#tid, #theader,#t" + i + ")";
var insertCmd = new MySqlCommand(insertQuery, dbConnection2.Connection);
insertCmd.Parameters.AddWithValue("#tid", tid);
insertCmd.Parameters.AddWithValue("#theader", "N");
if (String.IsNullOrEmpty(input))
{
count = 1;
insertCmd.Parameters.AddWithValue("#t" + i, String.Empty);
break;
}
else
{
if (test)
{
insertCmd.Parameters.AddWithValue("#t" + i, txtBoxFields[i - 1].Text);
insertCmd.ExecuteNonQuery();
test = false;
var selectQuery = "select TINFOID from templateinfo where TID=" + tid + " and THEADER = 'N'";
var selectCmd = new MySqlCommand(selectQuery, dbConnection2.Connection);
var selectReader = selectCmd.ExecuteReader();
using (MySqlDataReader dr = selectReader)
{
while (dr.Read())
{
tinfoid = Convert.ToInt32(dr["TINFOID"]);
}
}
}
else
{
var updateQuery = "update templateinfo set " + templateFields[i - 1] + "='" + txtBoxFields[i - 1].Text + "' where TINFOID = '" + tinfoid + "' and TID=" + tid + " and THEADER='N'";
var updateCmd = new MySqlCommand(updateQuery, dbConnection2.Connection);
var updateReader = updateCmd.ExecuteReader();
using (var reader = updateReader)
{
}
}
}
}
}
if (count == 1)
{
//MessageBox.Show("Input field(s) cannot be left empty.");
}
//Finalize here
var client = new LTATImagingServiceClient();
client.Finalize(userID, tid, tinfoid, batchID);
Debug.WriteLine(userID + ", " + tid + ", " + tinfoid + ", " + batchID);
var batchName = templateView.SelectedNode.Text;
var folderPath = #"C:\temp\batches\" + mastertemplatename + #"\" + subtemplatename + #"\" + batchName + #"\";
ThumbnailLists.Items.Clear();
// var img = Image.FromFile(#"C:\temp\batch-done.png");
if (ImageBox.Image != null)
{
ImageBox.Image.Dispose();
}
ImageBox.Image = null;
try
{
using (new Impersonation(_remoteDomain, _remoteUser, _remotePassword))
{
// MessageBox.Show(_remoteUser);
// MessageBox.Show(_remotePassword);
var tPath = #"\\126.32.3.178\PantonSys\SAM\Storage\3\" + mastertemplatename + #"\" + subtemplatename + #"\" + batchName + #"\";
bool exists = System.IO.Directory.Exists(tPath);
if (!exists)
{
System.IO.Directory.CreateDirectory(tPath);
}
string[] fileList = Directory.GetFiles(folderPath, "*");
foreach (var file in fileList)
{
File.Copy(file, tPath + Path.GetFileName(file));
}
CurrentPageBox.Text = "";
NumberPageBox.Text = "";
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
MessageBox.Show(ex.Message);
}
var dbConnection = DBConnection.Instance();
dbConnection.DatabaseName = ConfigurationManager.AppSettings["dbName"];
if (dbConnection.IsConnect())
{
var deleteBatchQuery = "DELETE FROM templatebatch WHERE batchname ='" + templateView.SelectedNode.Text + "'";
var deleteBatchCmd = new MySqlCommand(deleteBatchQuery, dbConnection.Connection);
var deleteBatchReader = deleteBatchCmd.ExecuteReader();
using (var reader = deleteBatchReader)
{
while (reader.Read())
{
}
}
templateView.Nodes.Remove(templateView.SelectedNode);
Directory.Delete(folderPath, true);
MessageBox.Show("Successfully Transferred.");
foreach (var txtFields in txtBoxFields)
{
txtFields.Text = "";
txtFields.Enabled = false;
}
finButton.Visible = false;
finButton.Enabled = false;
}
bindButton.Visible = false;
}
Would this be possible to achieve or just being far-fetched?
I would appreciate any suggestions or pointers on this. Do let me know if there is anything unclear in my explanation.
EDIT:
Request URL: http://126.32.3.178:8111/process/taskmanager/start/start.jsp
Request Method: POST
Status Code: 200 OK
Remote Address: 126.32.3.178:8111
Referrer Policy: no-referrer-when-downgrade
Is there a way I could call this from the C# application?
You can send your file directly from your C# app with use of Http client. Here is code sample:
private async Task<bool> Upload(string filePath)
{
const string actionUrl = #"http://126.32.3.178:8111/process/taskmanager/start/start.jsp";
var fileName = Path.GetFileName(filePath);
var fileBytes = File.ReadAllBytes(filePath);
var fileContent = new ByteArrayContent(fileBytes);
using (var client = new HttpClient())
using (var formData = new MultipartFormDataContent())
{
formData.Add(fileContent, fileName);
var response = await client.PostAsync(actionUrl, formData);
return response.IsSuccessStatusCode;
}
}
Also, note that there maybe some sort of authentication should be performed before you can post a request.

Retrieve PHP data on separate text block in window Phone 8.1

$query = "SELECT * FROM user";
$result = sqli_query($con,$query);
while(cvt=sqli_fetch_assoc($result))
{
echo $cvt['name'];
echo $cvt['age'];
echo $cvt['blood_group'];
echo ",";
}
PHP file which show information about user. It works correctly.
This is my Windows Phone 8.1 C# function which retrieves this data from PHP file.
public async void sndandrec(string feedingaddress, HttpResponseMessage response, TextBlock tblock, HttpClient myhttpClient, int work)
{
try
{
response = await myhttpClient.GetAsync(resourceUri);
response.EnsureSuccessStatusCode();
responseText = await response.Content.ReadAsStringAsync();
}
catch (Exception ex)
{
// Need to convert int HResult to hex string
tblock.Text = "Error = " + ex.HResult.ToString("X") +
" Message: " + ex.Message;
responseText = "";
}
tblock.Text = response.StatusCode + " " + response.ReasonPhrase;
tblock.Text = responseText.ToString();
}
This function also works correctly. It show the response from PHP file in tblock.Text.
The problem is that all the text are show in one text block. Is there a way to show the name,age and block group in separate text block.
The response from the above file is
adam23B+,david30AB+ .......
I want to separate them like
Nametexbock:adma
Agetextblock:23
BlockGptextblock:B+
I recommend you to use json_encode to pass data from one application to another
Replace this code
while(cvt=sqli_fetch_assoc($result)){
echo $cvt['name'];
echo $cvt['age'];
echo $cvt['blood_group'];
echo ",";
}
with
while(cvt=sqli_fetch_assoc($result)){
$d[] = array('Nametexbock'=>$cvt['name'],'Agetextblock'=>$cvt['age'],'BlockGptextblock'=>$cvt['blood_group'])
}
echo json_encode($d);

Read Credentials by txt file and try login c#?

I would create a loop for function and print message in catch for all logins failed and print "sucessful connected with...." for all good logins.
Now i tried with that code, but i get only one error in textbox of catch
Button1:
if (openFileDialog1.FileName != string.Empty)
{
using (StreamReader reader = new StreamReader(openFileDialog1.FileName))
{
int count = 0;
string lineoflistemail;
while ((lineoflistemail = reader.ReadLine()) != null)
{
UserData d = new UserData();
string[] parts = lineoflistemail.Split(':');
count = parts.Length;
d.UserName = parts[0].Trim();
d.Password = parts[1].Trim();
data.Add(d);
}
foreach(UserData ud in data)
{
textBox1.Text += ("LOL" + ud.UserName + ud.Password + Environment.NewLine);
}
Second button code:
if (data.Count() == 0)
{
MessageBox.Show("Load user info first");
return;
}
for( hola = 0; hola < data.Count(); hola++)
{
var url = #"https://mail.google.com/mail/feed/atom";
var encoded = TextToBase64(data[0].UserName + ":" + data[1].Password);
var myweb = HttpWebRequest.Create(url) as HttpWebRequest;
myweb.Method = "POST";
myweb.ContentLength = 0;
myweb.Headers.Add("Authorization", "Basic " + encoded);
var response = myweb.GetResponse();
var stream = response.GetResponseStream();
textBox1.Text += ("Connection established with");
MessageBox.Show(hola.ToString());
}
}
catch (Exception ex)
{
textBox1.Text += ("Error connection. Original error: " + ex.Message);
}
}
The problem is that your try...catch is outside of your for loop. The first exception will exit the for loop, append the message to textBox1, then exit the button handler.
If you want to keep looping through even if there is an error, move the try...catch inside of the loop. Here's an example:
for( hola = 0; hola < data.Count(); hola++)
{
var url = #"https://mail.google.com/mail/feed/atom";
var encoded = TextToBase64(data[0].UserName + ":" + data[1].Password);
var myweb = HttpWebRequest.Create(url) as HttpWebRequest;
myweb.Method = "POST";
myweb.ContentLength = 0;
myweb.Headers.Add("Authorization", "Basic " + encoded);
try
{
var response = myweb.GetResponse();
var stream = response.GetResponseStream();
textBox1.Text += ("Connection established with");
MessageBox.Show(hola.ToString());
}
catch (Exception ex)
{
textBox1.Text += ("Error connection. Original error: " + ex.Message);
}
}

How can I structure a try/catch with a variable definition

Writing in C# and I'm getting JSONReaderExceptions here:
var container = JsonConvert.DeserializeObject<HistoryResponseContainer> (responseData);
It's always something like a unterminated line or unrecognized character.
I know I need to catch and throw these errors, but it breaks if I try and define "container" inside a try/catch statement. Here's the whole method.
foreach (String StationID in StationIDList) {
string url = #"http://api.wunderground.com/api/" + wundergroundkey + "/history_" + Date + "/q/pws:" + StationID + ".json";
Uri uri = new Uri (url);
WebRequest webRequest = WebRequest.Create (uri);
WebResponse response = webRequest.GetResponse ();
StreamReader streamReader = new StreamReader (response.GetResponseStream ());
String responseData = streamReader.ReadToEnd ();
var container = JsonConvert.DeserializeObject<HistoryResponseContainer> (responseData);
foreach (var observation in container.history.observations) {
CurrentData.Write (StationID + " ");
// This makes easier access to the date. not perfect, but better.
DateTime date = observation.date.Value;
DateTime utc = observation.utcdate.Value;
// whatever you want to do with each observation
if (date.Minute == 0 || date.Minute % 5 == 0) {
CurrentData.Write (date.Hour + ":" + date.Minute + " " + observation.wdird + " " + observation.wspdi);
}//end if
CurrentData.Write ("\n");
} //End foreach observation
} //end foreach station
Put your second foreach loop inside try (because you're using your "container"). Otherwise it won't be defined if an exception is raised and you only "try/catch" your container instanciation:
foreach (String StationID in StationIDList)
{
string url = #"http://api.wunderground.com/api/" + wundergroundkey + "/history_" + Date + "/q/pws:" + StationID + ".json";
Uri uri = new Uri (url);
WebRequest webRequest = WebRequest.Create (uri);
WebResponse response = webRequest.GetResponse ();
StreamReader streamReader = new StreamReader (response.GetResponseStream ());
String responseData = streamReader.ReadToEnd ();
try
{
var container = JsonConvert.DeserializeObject<HistoryResponseContainer> (responseData);
foreach (var observation in container.history.observations)
{
CurrentData.Write (StationID + " ");
DateTime date = observation.date.Value;
DateTime utc = observation.utcdate.Value;
if (date.Minute == 0 || date.Minute % 5 == 0)
{
CurrentData.Write (date.Hour + ":" + date.Minute + " " + observation.wdird + " " + observation.wspdi);
}
CurrentData.Write ("\n");
}
}
catch(JsonReaderException ex)
{
// ...
}
}
I know I need to catch and throw these errors,
No you need just catch and handle these errors.
but it pukes if I try and define "container" inside a try/catch statement.
What do you mean here ? You need this:
try
{
// your code that throws exception
}
catch(JsonReaderException ex)
{
// handle your exception
}

C# Base-64 error when logging into server

I was testing my own method of logging into a database last night for a program I am working on and everything was fine. When I tried logging into the database this morning I get a Base-64 error. Here is the error in its entirety.
The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.
Before I put the program into production I need to fix this error but I cannot figure out what is causing it. Here is the login code (I am excluding the real server address and real encryption keys for security but it shouldn't make a difference).
private void login_Click(object sender, EventArgs e)
{
try
{
WebRequest request_user = WebRequest.Create("server address here");
WebResponse response_user = request_user.GetResponse();
StreamReader sr_user = new StreamReader(response_user.GetResponseStream());
string user = RC4.Decrypt("encryption key here", sr_user.ReadToEnd());
//show("Client: " + username.Text + "\nServer: " + user);
WebRequest request_pass = WebRequest.Create("server address here");
WebResponse response_pass = request_pass.GetResponse();
StreamReader sr_pass = new StreamReader(response_pass.GetResponseStream());
string pass = RC4.Decrypt("encryption key here", sr_pass.ReadToEnd());
//show("Client: " + password.Text + "\nServer: " + pass);
WebRequest request_key1 = WebRequest.Create("server address here");
WebResponse response_key1 = request_key1.GetResponse();
StreamReader sr_key1 = new StreamReader(response_key1.GetResponseStream());
string key1 = RC4.Decrypt("encryption key here", sr_key1.ReadToEnd());
//show("Client: " + RC4.Decrypt("encryption key here", AuthKey1) + "\nServer: " + key1);
WebRequest request_key2 = WebRequest.Create("server address here");
WebResponse response_key2 = request_key2.GetResponse();
StreamReader sr_key2 = new StreamReader(response_key2.GetResponseStream());
string key2 = RC4.Decrypt("encryption key here", sr_key2.ReadToEnd());
//show("Client: " + RC4.Decrypt("encryption key here", AuthKey2) + "\nServer: " + key2);
WebRequest request_ipv4 = WebRequest.Create("server address here");
WebResponse response_ipv4 = request_ipv4.GetResponse();
StreamReader sr_ipv4 = new StreamReader(response_ipv4.GetResponseStream());
string ipv4 = sr_ipv4.ReadToEnd();
//show("Client: " + IPAddress + "\nServer: " + ipv4);
if (user.Contains(username.Text) && pass.Contains(password.Text) && key1.Contains(RC4.Decrypt("encryption key here", AuthKey1)) && key2.Contains(RC4.Decrypt("encryption key here", AuthKey2)) && ipv4.Contains(IPAddress))
{
WebRequest request_tu = WebRequest.Create("server address here");
WebResponse response_tu = request_tu.GetResponse();
StreamReader sr_tu = new StreamReader(response_tu.GetResponseStream());
string tu = sr_tu.ReadToEnd();
show("Successfully logged into the Grand Theft Rape Server!\nCurrent TU: " + tu);
}
else
{
show("Username and/or Password incorrect!");
}
}
catch (Exception ex)
{
show(ex.Message);
}
}

Categories