Calling PHP Web -Service from C# Windows Form - c#

I am trying to verify username, password, and software token number of a C# Windows Form to values in MySQL database.
My C# Code:
private void btnlogin_Click(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(txtusername.Text))
{
MessageBox.Show("Please insert username");
}
if (String.IsNullOrEmpty(txtpassword.Text))
{
MessageBox.Show("Please insert password");
}
var username = txtusername.Text;
var password = txtpassword.Text;
string Token = "28956";
var SoftwareToken = token;
WebRequest request = WebRequest.Create("https://mydomain.com.au/Verification.php?username=username&password=password&Token=SoftwareToken");
request.Method = "GET";
WebResponse response = request.GetResponse();
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
var responseFromServer = reader.ReadToEnd();
responseFromServer.ToArray();
/*I have tried:
responseFromServer.ToArray();(because result on php page is an array.
I have tried responseFromServer.ToString();*/
MessageBox.Show(responseFromServer);
}
My PHP code (Web service):
<?php
// Database Structure
require_once('connect.php');
//Get password from the database for the user
$stmtus = $conn->prepare("SELECT password from `Users` where `email` = :Username");
$stmtus->bindParam(':Username', $username);
$username= $_GET['username'];;
$stmtus -> execute();
$password = $stmtus->fetch();
$un = $_GET['username'];
$pw = $_GET['password'];
$ust = $_GET['Token'];
if(password_verify($pw, $password[0])){
$stmt = $conn->prepare("SELECT
COUNT(Token) AS cnt FROM `SoftwareToken`
LEFT JOIN User ON iduser = SoftwareToken.Consultant
WHERE Token = '$ust'
AND username = '$un'");
$stmt->bindValue(':Username', $un);
$stmt->bindValue(':Token', $ust);
$stmt->execute();
$result= array();
while($SToken= $stmt->fetch(PDO::FETCH_OBJ)){
array_push($result, $SToken->cnt);
}
echo json_encode($result);
}
$conn = null;
?>
I am battling to understand how I call the web service from the C# application, how do I pass the variables from the C# application to the web service and how do I return the json_encode to the C# application from the web service.
I am not a full-time programmer and this is my first encounter with web services. If there are any suggestions on how to improve either of the codes, I would much appreciate.
UPDATE
I have updated my code as assisted. When I run the php code with variables it runs and gives me a $result (array). A numeral answer 1.
When I test my code to display the result in a MessageBox, the MessageBox is empty. Why ?

Of course you can call WebService from C#.
There is a built in calss in System.
One Way:
WebRequest request = WebRequest.Create("http://localhost:8080/?username=john");
request.Method="GET";
WebResponse response = request.GetResponse();
Other Way:
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:8080/");
HttpResponseMessage response = await client.PostAsJsonAsync( "api/user", userName);
response.EnsureSuccessStatusCode();

Code which I used:
var username = txtusername.Text;
var password = txtpassword.Text;
string Token = "28956";
var url = "https://mydomain.com.au/LoginVerification.php?";
var var = "username=" + username + "&password=" + password + "&Token=" + Token ;
var URL = url + var;
//MessageBox.Show(URL);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
var responseFromServer = reader.ReadToEnd();
//MessageBox.Show(responseFromServer);
// Display the content.
if (responseFromServer == "\n Allow")
{
MessageBox.Show("Success");
}

Related

Problems with authentication on Huawei b525s-23a

I have a Huawei b525-23a router. Using it's web interface you can send/check SMS but I want to do it automatically from an C# app. I didn't found any API documentation for it so any link will be very good.
I managed to find some HTTPRequests using Chrome but when I use it from C# I get the 125003 error that is according to some google search an authentication problem.
Here are some parts of my code :
private void button4_Click(object sender, EventArgs e)
{
// getting SenInfo and TokInfo
string urlTokenInfo = "http://192.168.8.1/api/webserver/SesTokInfo";
HttpWebRequest requestTokenInfo = (HttpWebRequest)WebRequest.Create(urlTokenInfo);
requestTokenInfo.Method = "GET";
WebResponse responseTokenInfo = requestTokenInfo.GetResponse();
Stream responseTokenInfoStream = responseTokenInfo.GetResponseStream();
string responseTokenInfoString = new StreamReader(responseTokenInfoStream).ReadToEnd();
var rootElement = XElement.Parse(responseTokenInfoString);
string sessionId = rootElement.Element("SesInfo").Value;
string tokenInfo = rootElement.Element("TokInfo").Value;
//_________________________________________________________________________________
// trying to log
String urlLogin = "http://192.168.8.1/api/user/login";
HttpWebRequest requestLogin = (HttpWebRequest)WebRequest.Create(urlLogin);
requestLogin.Method = "POST";
String XMLLogin;
String base64Passwd = Base64Encode(passwd); //function for base64 encode
XMLLogin = " <request ><Username> " + userName + " </Username><Password> " + base64Passwd + " </Password></request> ";
byte[] requestInFormOfBytes = System.Text.Encoding.ASCII.GetBytes(XMLLogin);
requestLogin.ContentType = "text/xml;charset=utf-8";
requestLogin.ContentLength = requestInFormOfBytes.Length;
Stream requestStream = requestLogin.GetRequestStream();
requestStream.Write(requestInFormOfBytes, 0, requestInFormOfBytes.Length);
requestLogin.Headers.Add("__RequestVerificationToken", tokenInfo);
requestLogin.Headers.Add("Cookie", sessionId);
WebResponse raspuns = (HttpWebResponse)requestLogin.GetResponse();
Stream responseStreamLogin = raspuns.GetResponseStream();
string responseStrlogin = new StreamReader(responseStreamLogin).ReadToEnd();
}
}
The response that I get is
<?xml version="1.0" encoding="UTF-8"?><error><message></message><code>125003</code></error>
Thank you for your time reading this and any response will be apreciated.
Mihai Stanciu
125003 error means token verification failed.
Check the session and token values in the first html resource request file

PHP webpage shows empty string after passing Json through c# RESI API

I have already asked this question but need further help.
c# is not sending json request to PHP
I am trying to send data from c# to PHP webpage using the JSON & REST API HTTP request.
On PHP page I see "String (0)"
c# Code
user user = new user();
{
user.firstname = "aaaa";
user.secondname = "aaaaaaaaaaa";
user.email = "aaa";
user.phonenumber = "aaa";
};
string json = JsonConvert.SerializeObject(user);
HttpWebRequest request = WebRequest.Create("https://scs.agsigns.co.uk/test.php") as HttpWebRequest;
request.ContentType = "application/json";
//request.Accept = "application/json, text/javascript, */*";
request.Method = "POST";
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(json);
}
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
Stream stream = response.GetResponseStream();
string json1 = "";
using (StreamReader reader = new StreamReader(stream))
{
while (!reader.EndOfStream)
{
json1 += reader.ReadLine();
}
}
DisplayAlert("Alert", json1, "OK");
PHP
$content = file_get_contents("php://input");
var_dump($content);
In c# I get this alert
c# display alert message
In the PHP webpage, I see following
PHP page shows string(0)
What I want to get data which app sendand save into MySql.
EDIT
I have ammended the PHP file code to save data in MySQL.
I am getting error
Notice: Trying to get property 'name' of non-object in C:\inetpub\scs\test.php on line 16
This is my PHP code.
//Receive the RAW post data.
$content = file_get_contents("php://input");
$obj = json_encode($content);
$insert_stmt = $mysqli->prepare("INSERT INTO test (name,address) VALUES (?,?)");
$name =$obj->{'name'};
$address = $obj->{'address'};
$insert_stmt->bind_param("ss", $name, $address);
//Execute the statement
$insert_stmt->execute();
You should use HttpClient instead of HttpWebRequest
Your request would look like this with HttpClient
public async void SendUserDataToServer()
{
user user = new user();
{
user.firstname = "aaaa";
user.secondname = "aaaaaaaaaaa";
user.email = "aaa";
user.phonenumber = "aaa";
};
string json = JsonConvert.SerializeObject(user);
using (var client = new HttpClient())
{
var response = await client.PostAsync(
"https://scs.agsigns.co.uk/test.php",
new StringContent(json, Encoding.UTF8, "application/json"));
}
DisplayAlert("Alert", json, "OK");
}
Reference: this

Retrieve/fetch data to display to my ASP.Net web application from PHP service thats connected to remote MySQL database

So I have a remote(hosted) MySQL database which I connect to with a PHP service. I need both my ASP.Net c# web application and my android to communicate with it. However, I'm struggling with populating my web application template with all the information I retrieve from the service. For instance, I would like to populate a profile page of the user.
Below would be my PHP connection and communication to the database:
`// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM Vendor Where VendorId = 2"; //this is just a test
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo . $row["id"]. . $row["BusinessName"]. . $row["Location"]. . $row["Email"]. .$row["Website"]. .$row["ProductType"]. .$row["Contact"]. .$row["PaymentOption"]. .$row["ProfileImg"]."<br>";
}
} else {
echo "0 results";
}
$conn->close();
`
and then (without sharing all my setups) this would be the code sample for asp.net c# to communicate with my PHP file/service.
public void getUserInfo(int id)
{
string BusinessName = lblBusiness.Text.Trim();
string email = lblEmail.Text.Trim();
string Contact = lblPhone.Text.Trim();
string location = lblLocation.Text.Trim();
string Website = lblWebsite.Text.Trim();
string payment = lblPayment.Text.Trim();
//Variables to get information from the service
Stream dataStream = null;
WebResponse response = null;
StreamReader reader = null;
//Stores the result from the server
string responseFromServer = null;
try
{
string requestMethod = "GET";
//Sending this data across the stream
string postData = "&Email=" + email + "&BusinessName=" + BusinessName + "&Website=" + Website + "&PaymentOption=" + payment + "&Location=" + location + "&ProductType=" + ProductType + "&Contact=" + Contact + "";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
string URL = "";// url of php service location
string contenttype = "application/x-www-form-urlencoded";
//Create link to web service
WebRequest request = WebRequest.Create(URL);
//Pass the request method
request.Method = requestMethod;
request.ContentType = contenttype;
request.ContentLength = byteArray.Length;
dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
//Get response from the server
response = request.GetResponse();
dataStream = response.GetResponseStream();
reader = new StreamReader(dataStream);
responseFromServer = reader.ReadToEnd();
}
catch (WebException ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
if (dataStream != null && reader != null && response != null)
{
dataStream.Close();
reader.Close();
response.Close();
}
//Getting the response from the service
//string result = responseFromServer.ToString();
}
}
also, Im not sure what to return from that function.
Please help.
Your php file is the "API" i pressume.
You basically need to return this from your php file.
$vendorArray = [
"Id" => $row["id"],
"BusinessName" => $row["BusinessName"],
// ... this is just pseudo code, convert the array or take the array or something like that
];
header('Content-type: application/json');
echo json_encode($vendorArray);
then in asp.net you do:
var deserializedVendor = JsonConvert.DeserializeObject<Vendor>(responseFromServer);
Your vendor class has to match your jsonObject to be Deserializable
public class Vendor {
public string Id {get;set;}
public string BusinessName {get;set;}
...
}
it depends on your jsonResponse...
you can also deserialize directly into a complex item with a list of vendors like this:
var allTheVendorsDeserialized = JsonConvert.DeserializeObject<AllTheVendors>(responseFromServer);
public class AllTheVendors {
public bool Success {get;set}
public List<Vendor> {get;set}
}
where php:
$arr = ["Success" => true, $myArrayOfVendors];
header('Content-type: application/json');
echo json_encode($arr);
I believe, your PHP web application is hosted and you can use the PHP service in ASP.NET with the following steps:
WebClient client = new WebClient(); //Create WebClient object
string url = "http://test.com/test.php"; //Get the URL of the PHP service
byte[] html = client.DownloadData(url); //Byte array to hold returned data from the service
Finally use the UTF8Encoding object to convert the byte array into sring:
UTF8Encoding utf = new UTF8Encoding(); //Create an object of the UTF8Encoding class
string str = utf.GetString(html); //Convert data into string

Can't create workitem via webrequest in RTC

I'm trying to create a .NET web application integration with RTC, where I would insert new workitems using RTC change management services, as defined in this article (specifically in "Create a Change Request"). I was able to get the URL-to-be-used inside services.xml file (/oslc/contexts/_0_iN4G09EeGGMqpyZT5XdQ/workitems/) and my goal is to insert data using JSON.
My code is basically the following:
CookieContainer cookies = new CookieContainer();
HttpWebRequest documentPost = (HttpWebRequest)WebRequest.Create(rtcServerUrl + "/oslc/contexts/_0_iN4G09EeGGMqpyZT5XdQ/workitems/order");//"Order" is the workitem name
documentPost.Method = "POST";
documentPost.CookieContainer = cookies;
documentPost.Accept = "application/json";
documentPost.ContentType = "application/x-oslc-cm-change-request+json";
documentPost.Timeout = TIMEOUT_SERVICO;
string json = "{ \"dc:title\":\"" + title + "\", \"rtc_cm:filedAgainst\": [ { \"rdf:resource\" : \"" + rtcServerUrl + "/resource/itemOid/com.ibm.team.workitem.Category/" + idCategory + "\"} ] }"; //dc:title and rtc_cm:filedAgainst are the only two mandatory data from the workitem I'm trying to create
using (var writer = new StreamWriter(documentPost.GetRequestStream()))
{
writer.Write(json);
writer.Flush();
writer.Close();
}
Encoding encode = System.Text.Encoding.UTF8;
string retorno = null;
//Login
HttpWebRequest formPost = (HttpWebRequest)WebRequest.Create(rtcServerUrl + "/j_security_check");
formPost.Method = "POST";
formPost.Timeout = TIMEOUT_REQUEST;
formPost.CookieContainer = request.CookieContainer;
formPost.Accept = "text/xml";
formPost.ContentType = "application/x-www-form-urlencoded";
String authString = "j_username=" + userName + "&j_password=" + password; //create authentication string
Byte[] outBuffer = System.Text.Encoding.UTF8.GetBytes(authString); //store in byte buffer
formPost.ContentLength = outBuffer.Length;
System.IO.Stream str = formPost.GetRequestStream();
str.Write(outBuffer, 0, outBuffer.Length); //update form
str.Close();
//FormBasedAuth Step2:submit the login form and get the response from the server
HttpWebResponse formResponse = (HttpWebResponse)formPost.GetResponse();
var rtcAuthHeader = formResponse.Headers["X-com-ibm-team-repository-web- auth-msg"];
//check if authentication has failed
if ((rtcAuthHeader != null) && rtcAuthHeader.Equals("authfailed"))
{
//authentication failed. You can write code to handle the authentication failure.
//if (DEBUG) Console.WriteLine("Authentication Failure");
}
else
{
//login successful
HttpWebResponse responseRetorno = (HttpWebResponse)request.GetResponse();
if (responseRetorno.StatusCode != HttpStatusCode.OK)
retorno = responseRetorno.StatusDescription;
else
{
StreamReader reader = new StreamReader(responseRetorno.GetResponseStream());
retorno = "[Response] " + reader.ReadToEnd();
}
responseRetorno.Close();
formResponse.GetResponseStream().Flush();
formResponse.Close();
}
As I was managed to search for in other forums, this should be enough in order to create the workitem (I have a very similar code working to update workitems using "" URL and PUT method). However, instead of create the workitem in RTC and give me some response with item's identifier, the request's response returns a huge JSON file that ends with "oslc_cm:next":"https:///oslc/contexts/_0_iN4G09EeGGMqpyZT5XdQ/workitems/%7B0%7D?oslc_cm.pageSize=50&_resultToken=_AAY50FEkEee1V4u7RUQSjA&_startIndex=50. It's a JSON representation of the XML I receive when I access /oslc/contexts/_0_iN4G09EeGGMqpyZT5XdQ/workitems/ directly from browser, like I was trying to do a simple query inside the workitem's collection (even though I'm using POST, not GET).
I also tried to use PUT method, but then I receive a 405 status code.
Does anyone have an idea of what am I missing here? My approach is wrong, even though with the same approach I'm able to update existing workitem data in RTC?
Thanks in advance.

REST HttpWebResponse not returning xml data as string

Firstly, I understand this code isn't necessarily "safe" and is VERY basic. I'm learning how to consume rest services with web forms in C# (both are new topics for me). Pretty much the only thing there is 2 textboxes for authentication credentials, a query textbox and button to send the request with a label. I just want to enter the ID1 into the textbox, and then return the First and Last name for the entry with that ID.
I have tried many different ways after thoroughly searching the web but can't seem to figure out the issue.
The Issue: The StreamReader data from the WebResponse isn't coming back as XML.
The Question: How do I return the XML tags that I want? Do I need to parse them? If so, how?
The XDoc version is returning nothing while the straight stream reader is returning a string with some data in addition to numbers that shouldn't be there and no angle brackets. Below is the code as it stands now:
if (QueryTextBox2.Text != "")
{
string tableName = "Entry";
string requestURL = "https://myUrl.com/rest/services/" + tableName;
HttpWebRequest request = WebRequest.Create(requestURL) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "text/xml; encoding:='charset=utf-8'";
request.Headers["CustomUserName"] = TextBox1.Text;
request.Headers["CustomPassword"] = TextBox3.Text;
string xml = "<Entry><ID1>" + QueryTextBox2.Text + "</ID1></Entry>";
byte[] byteArray = Encoding.UTF8.GetBytes(xml.ToString());
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
if (response.StatusCode == HttpStatusCode.OK) {
Stream postData = response.GetResponseStream();
StreamReader reader = new StreamReader(postData, Encoding.UTF8);
string result = reader.ReadToEnd();
Label2.Text = result;
} else
{
Label2.Text = "There was an error: " + response.StatusDescription;
}
}
else
{
TextBox2.Text = "Please Enter an ID";
}
}
}
I have also tried using:
XDocument doc = new XDocument();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
doc = XDocument.Parse(reader.ReadToEnd());
string fname = doc.Root.Element("NameFirst").Value;
string lname = doc.Root.Element("NameLast").Value;
Label2.Text = fname + lname;
to replace the whole block within: if statusCode == OK.
The data returned from the firefox Poster add-on is:
<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom">
<title type="text">Search Results</title>
<id>https://myUrl.com/rest/services</id>
<updated>2015-10-07T09:51:32Z</updated>
<link rel="self" type="application/atom+xml" href="https://myUrl.com/rest/services" />
<entry>
<id>https://myUrl.com/rest/services</id>
<Entry>
<ID1>900009</ID1>
<NameLast>Smith</NameLast>
<NameFirst>Tom</NameFirst>
<NameTitle></NameTitle>
<NamePreferred>Alex</NamePreferred>
<NameWeb>tsmith</NameWeb>
<NameOther></NameOther>
<NameInitials></NameInitials>
</Entry></content></entry></feed>
I've removed a lot of the response data because it's so large and anonymized it all for the most part so keep that in mind.
I would use System.Net.Http.HttpClient, it has a much easier interface for consuming http requests.
I haven't tested the document parsing, but just follow the nested levels in until you find the element you want.
async void Main()
{
var textBox2String = "2"
if (!string.IsNullOrEmpty(textBox2String))
{
const string table = "Entry";
var client = new HttpClient();
var url = $"https://myurl.com/rest/services/{table}";
var xml = $"<Entry><ID1>{textBox2String}</ID1></Entry>";
client.DefaultRequestHeaders.TryAddWithoutValidation("CustomUserName", "username");
client.DefaultRequestHeaders.TryAddWithoutValidation("CustomPassword", "password");
var response = await client.PostAsync(url, new StringContent(xml, Encoding.UTF8, "text/xml"));
var content = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
var document = XDocument.Parse(content);
var entry = document.Root.Element(table);
var firstName = entry.Element("FirstName").Value;
var lastName = entry.Element("LastName").Value;
$"{firstName} {lastName}".Dump();
}
else
{
Console.WriteLine($"An error occurred processing this request: {content}");
}
}
else
{
textBox2String = "Please enter an ID";
}
}

Categories

Resources