HTTP Post Request with Windows Phone Webclient C# - c#

I have a php file on my local server which looks like this: (The database variables are in the config.php and are correct!)
<?php
require_once "config.php";
try
{
$con = new PDO("mysql:host=".$db_host.";dbname=".$db_name,$db_user,$db_password);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e)
{
echo "Error: ".$e->getMessage();
exit();
}
if (empty($_POST["number"]) || !isset($_POST["number"]))
{
echo "Error: no number!";
exit();
}
else if (empty($_POST["password"]) || !isset($_POST["password"]))
{
echo "Error: no password!";
exit();
}
else
{
$number = $_POST["number"];
$password = md5($_POST["password"]);
$salt = sha1($_POST["password"]);
}
if (!empty($_POST["login"]))
{
$sql = $con->prepare("SELECT COUNT(`ID`) FROM ".$db_table_login_students." WHERE `number` = ? AND `password` = ? AND `salt` = ? AND user_deleted=0");
$sql->bindParam(1, $number);
$sql->bindParam(2, $password);
$sql->bindParam(3, $salt);
$sql->execute();
if($sql->fetchColumn() > 0)
{
$login = array('Login' => 'Yes');
echo json_encode($login);
$_sql = $con->prepare("UPDATE ".$db_table_login_students." SET last_login=NOW() WHERE number = ?");
$_sql->bindParam(1, $matrikelnummer);
$_sql->execute();
exit();
}
else
{
$login = array('Login' => 'No');
echo json_encode($login);
exit();
}
}
?>
And now I want to make a HTTP Post Request with Windows Phone in C# and it looks now like this:
void PostJsonRequestWebClient()
{
WebClient webclient = new WebClient();
Uri uristring = null;
uristring = new Uri("http://localhost/login.php?");
webclient.Headers["ContentType"] = "application/x-www-form-urlencoded";
string WebUrlRegistration = "";
string JsonStringParams = "login=yes&number=4340490&password=test";
webclient.UploadStringCompleted += wc_UploadStringCompleted;
webclient.UploadStringAsync(uristring, "POST", JsonStringParams);
}
private void wc_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
try
{
if (e.Result != null)
{
string response = e.Result.ToString();
textblock1.Text = response;
}
}
catch
{
}
}
The login data with number and password are correct in my database. When I make a Get request instead of a Post I became as answer from the php script "{Login:Yes}". But when I make a Post request like the one above I became "Error: no number!". So I think the Post query string is false, but I find nothing. Can anybody help me?

Maybe, the HTTP Header should be Content-Type instead of ContentType.

Related

Storing a JSON Object value in a Integer c# . Windows forms app

I have created a Windows Form Application Function to validate an Api. But the code is breaking ar Deserialize Line. I need to check for Status . If Status=1 is stored in StatusCode string. I can proceed ahead. Please assist.
Function Code :
private void Validate_CW_Account(string Company_Code , string Username , string Password)
{
try
{
string sURL = "";
string baseURL = "https://www.compelapps.in/efacilito_UAT_Api/api/CocktailWorld/Validate_CW_Account_Migration?";
sURL = baseURL+ "StrCompanyCode=" + Company_Code + "&StrUsername=" + Username + "&StrPassword=" + Password;
var client = new RestClient(sURL);
client.Timeout = -1;
var request = new RestRequest(Method.GET);
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", sURL, ParameterType.QueryString);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
string json_response = response.Content.ToString();
CW_API_Response cw = JsonConvert.DeserializeObject<CW_API_Response>(json_response);
string StatusCode = cw.Status;
if (StatusCode == "1")
{
lbl_AccountConn_Status.Text = "SUCCESSFUL";
lbl_AccountConn_Status.BackColor = System.Drawing.Color.GreenYellow;
lbl_AccountConn_Status.ForeColor = System.Drawing.Color.Black;
}
else
{
lbl_AccountConn_Status.Text = "AUTHENTICATION FAILED";
lbl_AccountConn_Status.BackColor = System.Drawing.Color.Red;
lbl_AccountConn_Status.ForeColor = System.Drawing.Color.White;
}
}
catch (Exception ex)
{
throw ex;
}
}
Class File Code :
public class CW_API_Response
{
public string Status { get; set; }
public string Company_ID { get; set; }
}
If the JSON returned by API is [ { "Company_ID": 11, "Status": 1 } ] then you need to read JSON List. You are not reading list. You are assuming single value.
Try this:
List<CW_API_Response> cw = JsonConvert.DeserializeObject<List<CW_API_Response>>(json_response);
string StatusCode = cw[0].Status.ToString();

Wait for a response from the mysql server in a easy way

I'm new to programming and wrote a basic login script (or rather watched a tutorial), but my output in Unity is at first "User nicht gefunden" and about one second later "User gefunden".
My question: Can I somehow wait for a response from the mysql server in a easy way and still recognize a missing connection?
Unityscript:
public string inputusername;
public string inputpassword;
public string URL = "http://localhost/login.php";
void Start () {
}
void Update () {
if (Input.GetKeyDown(KeyCode.L))
{
StartCoroutine(LoginToDB(inputusername, inputpassword));
}
}
IEnumerator LoginToDB(string username, string password)
{
WWWForm form = new WWWForm();
form.AddField("usernamePost", username);
form.AddField("passwordPost", password);
WWW www = new WWW(URL, form);
yield return www;
if(www.text == "wrong")
{
Debug.Log("User nicht gefunden");
}
if(www.text == "correct")
{
Debug.Log("User gefunden");
}
}
Phpscript:
$servername = "localhost";
$username = "root";
$password = "********";
$dbName = "test";
$user_username = $_POST["usernamePost"];
$user_password = $_POST["passwordPost"];
$conn = new mysqli($servername, $username, $password, $dbName);
if(!$conn){
die("Verbindung Fehlgeschlagen!". mysqli_connect_error());
}
$sql = "SELECT password FROM users WHERE username = '".$user_username."' ";
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
if($row['password'] == $user_password){
echo "correct";
}
else{
echo "wrong";
}
}
}else {
echo"not here";
}
Sorry in advance for the probably simple question.
I see three issues here:
while($row = mysqli_fetch_assoc($result)){
if($row['password'] == $user_password){
echo "correct";
}
else{
echo "wrong";
}
}
You aren't checking that the passed in user matches the user in the database. Multiple users with the same password could log in add each other!
You are returning multiple responses, this is why you see "wrong password" initially
You aren't salting and hashing your passwords. This is inherently insecure.

Connect C Sharp (login) to a online PHP plugin (MySQL database) through JSON

Can anyone help me with the correct notation of receiving a JSON POST request in PHP and a working (and aligned) C Sharp script for sending the POST request. I want a decentral login on my PC (with C Sharp software) which uses a JSON POST request to connect to my MySQL database (through a PHP 7.1.1 plugin) on my webspace. I can see the Exceptions (so the JSON feedback is received properly) which the script returns but the PHP POST superglobal keeps coming up empty (on the request side).
My C Sharp script:
using Newtonsoft.Json;
using System;
using System.IO;
using System.Net;
using System.Windows.Forms;
namespace HBI_Statistics_UI
{
public partial class Login : Form
{
public class API_Response
{
public bool IsError { get; set; }
public string ErrorMessage { get; set; }
public string ResponseData { get; set; }
}
public Login()
{
InitializeComponent();
}
private void buttonLogin_Click(object sender, EventArgs e)
{
try
{
// request params
var apiUrl = "http://www.home-business-intelligence.net/plugin/HBI-Statistics/login.php";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(apiUrl);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "json=" + "{\"Email\":\"" + textBox1.Text + "\"," +
"\"Pwd\":\"" + textBox2.Text + "\"}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
API_Response r = JsonConvert.DeserializeObject<API_Response>(result);
// check response
if (r.ResponseData == "Success")
{
this.Hide();
ProgramMainUI pr = new ProgramMainUI();
pr.Show();
}
else
{
MessageBox.Show(r.ErrorMessage, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
catch (System.Net.WebException ex)
{
MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch (Newtonsoft.Json.JsonReaderException ne)
{
MessageBox.Show(ne.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
My PHP Script:
include ("library.php");
try
{
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
// Post Request
$api_data = strip_tags(isset($_POST['json']) ? $_POST['json'] : '');
// Validate Request
if (empty($api_data))
{
throw new Exception('Invalid request!! Please provide login details.' . print_r($api_data));
}
if (!empty($api_data))
{
// Decode json
$data = json_decode($api_data, true);
// Set connection
$conn = Connection::Conn_2();
// Sanitize data for query
$pwd = mysqli_real_escape_string($conn, $data->json->Pwd);
$email = mysqli_real_escape_string($conn, $data->json->Email);
$pwd2 = VanillaSpecial::Hash($pwd); // Hashed Password
// Insert Query of SQL
$result = mysqli_query($conn, $sql = "SELECT * FROM `Management-employees` WHERE email='$email' AND password = '$pwd2'") or die(json_encode(array(
'IsError' => 'true',
'ErrorMessage' => 'Invalid Request!! Oops, something went wrong. Please try again!!'
)));
if (mysqli_num_rows($result) == 1)
{
// output data of each row
while ($row = mysqli_fetch_assoc($result))
{
$functionCategory = $row[functionCategoryID];
}
switch ($functionCategory)
{
case "Management":
// echo "You have got clearance for this page!";
exit(json_encode(array(
'IsError' => 'false',
'ResponseData' => 'Success'
)));
break;
default:
throw new Exception('Invalid clearance!!');
}
}
else
{
throw new Exception('ERROR: Could not be able to execute ' . $sql . ' - ' . mysqli_error($conn));
}
}
}
else
{
throw new Exception('Invalid access method!!');
}
}
catch(Exception $e)
{
exit(json_encode(array(
'IsError' => 'true',
'ErrorMessage' => $e->getMessage()
)));
}
using (var client = new HttpClient())
{
var values = new Dictionary<string, string>
{
{ "thing1", "hello" },
{ "thing2", "world" }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("http://www.example.com/recepticle.aspx", content);
var responseString = await response.Content.ReadAsStringAsync();
}

How to check valid URL address?

I have simple code , wich get url path and redirect to this url:
private void Redirect(String path)
{
Uri validatedUri = null;
var result = Uri.TryCreate(HelpURL + path, UriKind.Absolute, out validatedUri);
if (result&&validatedUri!=null)
{
var wellFormed = Uri.IsWellFormedUriString(HelpURL + path, UriKind.Absolute);
if(wellFormed)
{
Response.Write("Redirect to: " + HelpURL + path);
Response.AddHeader("REFRESH", "1;URL=" + HelpURL + path);
}
else //error
{
Response.Write(String.Format("Validation Uri error!", path));
}
}
else
{
Response.Write(String.Format("Validation Uri error!", path));
}
}
Example of Url:http://web-server/SomeSystemindex.html. It is not valid address, but:
at my code result is true, wellFormed is true too!
How to validate url address?
P.S. HelpUrl+path=http://web-server/SomeSystemindex.html for this case. Where HelpUrl is 'http://web-server/SomeSystem', and path=index.html
P.P.S. I do as Martin says- create connection and check the status code.
HttpWebRequest req = WebRequest.Create(HelpURL + path) as HttpWebRequest;
req.UseDefaultCredentials = true;
req.PreAuthenticate = true;
req.Credentials = CredentialCache.DefaultCredentials;
var statusCode= ((HttpWebResponse)req.GetResponse()).StatusCode;
if (statusCode == HttpStatusCode.NotFound)
isValid = false;
else if (statusCode == HttpStatusCode.Gone)
isValid = false;
else
{
isValid = true;
}
As far as I know, the only way to determine whether an address is valid or not, is by opening a connection. If the connection lives, the address is valid. If not, the connection is not valid. There are some tricks to filter out bad URL's, but to know whether an adress is valid, you need to open a connection.
An example has already been posted on StackOverflow here
Or here:
URL url;
URL wrongUrl;
try {
url = new URL("http://google.com");
wrongUrl = new URL( "http://notavalidurlihope.com");
HttpURLConnection con = (HttpURLConnection ) url.openConnection();
System.out.println(con.getResponseCode());
HttpURLConnection con2 = (HttpURLConnection ) wrongUrl.openConnection();
System.out.println(con2.getResponseCode());
} catch (IOException e) {
System.out.println("Error connecting");
}
Note: Do disconnect afterwards
output:
200
Error connecting
This simple helper method uses regex to ensure that a website URL is in correct format. It will also fail if there is any white space (which is important).
The following URL's pass:
google.com
www.google.com
http://google.com
http://www.google.com
https://google.com/test/test
https://www.google.com/test
It fails on:
www.google.com/a bad path with white space/
Below is the helper method I created:
public static bool ValidateUrl(string value, bool required, int minLength, int maxLength)
{
value = value.Trim();
if (required == false && value == "") return true;
if (required && value == "") return false;
Regex pattern = new Regex(#"^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]#!\$&'\(\)\*\+,;=.]+$");
Match match = pattern.Match(value);
if (match.Success == false) return false;
return true;
}

How to get result from UploadValuesAsync - WebClient C#

I'm doing on a Xamarin Android app and I have a class with bunch of methods for interaction with web service. Every of these methods should return something (true/false to be sure if the database transaction is completed or some other data from database). For example, I have a method:
public bool AddNewUser(User user)
{
WebClient client = new WebClient();
Uri url = new Uri(web + "AddNewUser.php");
NameValueCollection parameters = new NameValueCollection();
bool result = false;
parameters.Add("FirstName", user.FirstName);
parameters.Add("LastName", user.LastName);
parameters.Add("Email", user.Email);
parameters.Add("MobileNumber", user.MobileNumber);
client.UploadValuesAsync(url, parameters);
client.UploadValuesCompleted += (object sender, UploadValuesCompletedEventArgs e) =>
{
if (Encoding.UTF8.GetString(e.Result) == "true")
{
result = true;
}
};
return result;
}
This method returns the result as true or false(if the transaction is completed or if the transaction is not completed).
This is my PHP file:
<?php
require_once(dirname(__FILE__).'/Connection.php');
if(isset($_POST['FirstName']) && isset($_POST['LastName']) && isset($_POST['Email']) && isset($_POST['MobileNumber']))
{
$firstName = $_POST['FirstName'];
$lastName = $_POST['LastName'];
$email = $_POST['Email'];
$mobileNumber = $_POST['MobileNumber'];
$connection = new Connection();
$connection->GetConnection();
if(!$connection->conn)
{
echo 'Error: '.mysqli_connect_error();
}
else
{
$sql = 'INSERT INTO tb_user(name,lastname,mail,phone) VALUES ("'.$firstName.'","'.$lastName.'","'.$email.'","'.$mobileNumber.'")';
$result = mysqli_query($connection->conn,$sql);
if(!$result)
{
echo 'Error: '.mysqli_error($connection->conn);
}
else
{
echo true;
}
}
}
?>
But app crashes with no error and also user is not added. Now, I'm wondering what I'm doing wrong.
Thank you in advance.
UPDATE:
Error in UploadValuesCompletedEventArgs is equal to null. Is then something wrong with my PHP file?
UPDATE 2:
So, I used only UploadValues instead of UploadValuesAsync,like this:
WebClient client = new WebClient();
Uri url = new Uri(web + "AddNewUser.php");
NameValueCollection parameters = new NameValueCollection();
bool result = false;
parameters.Add("FirstName", user.FirstName);
parameters.Add("LastName", user.LastName);
parameters.Add("Email", user.Email);
parameters.Add("MobileNumber",user.MobileNumber);
byte[] r = client.UploadValues(url,parameters);
if (Encoding.UTF8.GetString(r) == "true")
{
result = true;
}
return result;
In android device logging this error is written:
FATAL EXCEPTION: main
java.lang.RuntimeException: java.lang.reflect.InvocationTargetException

Categories

Resources