PHP to C# variables - c#

I have the following PHPcode:
include 'db.php';
$user = $_POST['username'];
$q = $connection->query('SELECT id FROM myTable WHERE username=".$user."');
foreach($q AS $row) {
echo $row['id'];
}
I'm trying to make a C# application post a variable to a PHP page that then queries the db and echos a string that will be used in the C# app. My C# code looks like this:
public string getId(string url)
{
string test = "testing123";
NameValueCollection formData = new NameValueCollection();
formData["username"] = test;
using (WebClient wc = new WebClient())
{
byte[] resp = wc.UploadValues(url, "POST", formData);
string responsefromserver = Encoding.UTF8.GetString(resp);
wc.Dispose();
Console.WriteLine(responsefromserver);
return responsefromserver;
}
}
As you can see, I just want to write what the app gets back from the PHP page to the console and then return it, but when I run the app, it returns nothing. At least it appears to. Does anyone have any idea why? Sorry if this is blatantly obvious, I'm still pretty new to the whole C# thing.

replace
$q = $connection->query('SELECT id FROM myTable WHERE username=".$user."');
with
$q = $connection->query('SELECT id FROM myTable WHERE username='.$user.';');
and try again.
As a best practise, use prepared statement to avoid SQL injection.

Related

Sending a string from C# to insert into a PHP file to be immediately used in a mysql select query with the results returned

So I have this php file with the following query
$query = "select Customer.CustID, LastName,FirstName,DOB,CustPhone,
Max(TransDate) as LatestTransaction from Customer, History where
Customer.AuthKey='A111' and Customer.AuthKey=History.AuthKey and
Customer.CustID=History.CustID Group by CustID;";
$result = mysqli_query($con,$query);
$rows = array();
while($r = mysqli_fetch_array($result)) {
$rows[] = $r;
}
echo json_encode($rows);
mysqli_close($con);
And then I do this C# here to get the results and put them into a datagridview
WebClient wc = new WebClient();
var json = wc.DownloadString(URL);
List<Customer> customers =
JsonConvert.DeserializeObject<List<Customer>>(json);
CustomerDataViewGrid.DataSource = customers;
There are no problems with this, however I would like to take
Customer.AuthKey = 'A111'
From the above select query in the php And instead pass the value from my C# code to it
$aKey = $_POST['Authkey'];
Customer.AuthKey = '$aKey'
I have tried to do this within the same button click event but I am not quite understanding how I can send this string and then immediately get the Downloading string. When I hard code the Customer.Authkey it returns my results, but when I try to send this string it does not return anything. How can I do this from the same event?
Thanks
NameValueCollection formData = new NameValueCollection() {
{ "Authkey", "A111" },
};
byte[] result = wc.UploadValuesTask("<your_url_here>", "POST", formData);
string json = Encoding.UTF8.GetString(result);
By this was you can send your auth key to your PHP script. The rest is up to you. Sorry if I misunderstood you, feel free to correct me.

How to use sended post data on server side

I have a simple script to upload a file. Actually everything is working fine.
private void UploadCSV()
{
Uri address = new Uri("https://www.mydomain.xy/inc.upload.php");
string fileName = #"C:\test.csv";
using (WebClient client = new WebClient())
{
var parameters = new NameValueCollection();
parameters.Add("test", "aaaa");
client.QueryString = parameters;
client.UploadProgressChanged += WebClientUploadProgressChanged;
client.UploadFileCompleted += WebClientUploadCompleted;
client.UploadFileAsync(address, "POST", fileName);
}
}
Now as you can see, I try so send some data via POST test what contains aaaa. But now matter how I try to select the data serverside... there is nothing....
I tried $_POST['test'], $_POST['data']['test'].... but no results.
How can I access the extra Data ?
client.QueryString = parameters;
This will append a query string to the URL that you send the data to.
Even though the request method is POST, PHP always provides the query string parameters in $_GET.

WCF HTTP GET api

In my .NET project, I have to use HTTP GET request to get weather info for my city from API. Because of my JavaScript background I thought "OK, so all I need is something like app.get(url, body)", so I started with something like this:
using (var client = new WebClient())
{
var responseString = client.DownloadString("http://www.webservicex.net/globalweather.asmx/GetWeather?CityName=" + city + "&CountryName=" + country);
string xmlString = DecodeXml(responseString);
return xmlString;
}
Unfortunately for me it turned out, that I have to use WCF to get the data. I searched the web for some tutorials, but I couldn't find anything with getting the data from outer sources, just creating own API.
I'm not a native speaker, so maybe I'm just out of words to look for the solution, but it would be awesome if you could give me some advice.
Assuming you are using Visual Studio. Add Service Reference, and then type "http://www.webservicex.net/globalweather.asmx" into the address and hit Go. It'll auto-generate the end point for you to use.
Then the code is something like:
ServiceReference1.GlobalWeatherSoapClient client = new ServiceReference1.GlobalWeatherSoapClient("GlobalWeatherSoap");
string cities = client.GetCitiesByCountry("Hong Kong");
If you want to just use HTTP GET, you can do something like this:
var city = "Dublin";
var country = "Ireland";
WebRequest request = WebRequest.Create(
"http://www.webservicex.net/globalweather.asmx/GetWeather?CityName=" +
city +
"&CountryName=" + country);
request.Credentials = CredentialCache.DefaultCredentials;
WebResponse response = request.GetResponse();
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
Console.WriteLine(responseFromServer);
reader.Close();
response.Close();
Console.ReadLine();
Please note, I have not HTML decoded the response here, you can simply use HttpUtility.HtmlDecode for that.
Also, you will need to include the following using statements:
using System.IO;
using System.Net;

Calling MVC HttpPost method (with Parameter) using HttpwebRequest

I have the following MVC method.
[System.Web.Mvc.HttpPost]
public ActionResult Listen(string status)
{
CFStatusMessage statusMessage = new CFStatusMessage();
if (!string.IsNullOrEmpty(status))
{
statusMessage = Newtonsoft.Json.JsonConvert.DeserializeObject<CFStatusMessage>(status);
}
return Content(Server.HtmlEncode(status));// View(statusMessage);
}
I am trying to call the above method from Other application .. (Console). I am using HttpWebRequest to make a call to the MVC Method. Using the below code its able to call the method but the Parameter is always coming as empty string.
string content = "{\"status\":\"success\",\"payload\":\"some information\"}";
string url = "http://myrl.com";
var httpWRequest = (HttpWebRequest) WebRequest.Create(url);
httpWRequest.Method = "POST";
httpWRequest.ContentType = "text/json";
var encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(string.Format("status={0}", Uri.EscapeDataString(content)));
httpWRequest.ContentLength = data.Length;
Stream stream = httpWRequest.GetRequestStream();
stream.Write(data, 0, data.Length);
var response = (HttpWebResponse)httpWRequest.GetResponse();
With this its making a call to Listen method but status parameter is always coming blank. whereas I want the json string {status:"success",payload:"some information"} as parameter.
What am I doing wrong?
P.S.: I tried the below statement as well, while sending the actual content.
byte[] data = encoding.GetBytes(content);
Regards,
M
If do you need to provide any kind of service from MVC tryout WebApi instead. You can use HTTP REST to do this easily.
Read more here ASP.NET WebApi
You appear to be saying the request is json, but sending it using wwwencoding.
Remove the status={0} line bit & just send the json as is.
You can try something like this
using (var sw = new StreamWriter(httpWRequest.GetRequestStream()))
{
sw.Write(content);
sw.Flush();
sw.Close();
}

C# JSON response does an second JSON request

I'm working with JSON for a while now, but this is a problem I can't solve.
The program is written in C# and has a method called CreateWebRequest():
public void CreateWebRequest()
{
CurrentTime = DateTime.Now;
target = link;
request = WebRequest.Create(target) as HttpWebRequest;
request.ContentType = "application/json; charset=utf-8";
request.Method = "PUT";
request.ServicePoint.Expect100Continue = false;
string postData = jsonString;
System.Console.WriteLine("POSTDATA: " + postData);
StreamWriter requestWriter;
using (requestWriter = new StreamWriter(request.GetRequestStream()))
{
requestWriter.Write(postData);
}
}
The other function to fetch the result is called: CreateWebResponse():
public void CreateWebResponse()
{
WebResponse response;
string text;
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException e)
{
MessageBox.Show(e.Message);
return;
}
using (var sr = new StreamReader(response.GetResponseStream()))
{
text = sr.ReadToEnd();
}
APIresult apiresult = JsonConvert.DeserializeObject<APIresult>(text); //Deserialize the text
}
These functions work all fine, there is only one problem: the code does two requests.
When I put the same JSON in the RESTClient in mozilla FireFox the JSON works fine. It also works great when I'm only using CreateWebRequest(), but when I use both of the methods it seems the code creats a second request?
Is it possible to create only a response? Combine these two functions to one which creates directly an response?
I tried other solutions and put them just together, none of them seems to work. When I call for a response the code doesn't work properly anymore and creates two requests.
Has anyone a solution?
Thanks in advance.
The JSON function I call has several if statements and work fine according to RESTClient in Firefox.
The code below shows the code which is called correct by RESTClient and twice by the C# code:
$sql = 'SELECT...';
$result = $db->sql_query($sql);//search for member id.
if($row = $db->sql_fetchrow($result)){//when found, the user has access.
$member_id = $row['member_id'];
$sql = 'SELECT ...';
$result = $db->sql_query($sql);//search for last login today.
if($row = $db->sql_fetchrow($result)){//if the user has logged in today update the row.
$row_check_in_timestamp = $row['check_in_timestamp'];
$sql = 'UPDATE ...';//update the row with the check out timestamp
$db->sql_query($sql);
break;
}else{//the user hasn't logged in yet today, log in.
$start_session_array = array(
'club_id' => (int)$club_id,
'member_id' => (int)$member_id,
'check_in_timestamp' => (int)time(),
);
$sql = 'INSERT ...';//check user in and add a new row in the database
$db->sql_query($sql);
break;
}
}else{
break;
}
SOLVED: I'm sorry every one and thanks for all the responses, but I've found the problem. I had an older version as service running all the time and made the second JSON call.
I've found it by logging on the server side the calls and blocked code which call the JSON in my own code to figure this out.

Categories

Resources