So I have a C# script which stores data to a database through my PHP script. My C# script uses WebClient to achieve this effect. But sadly my C# script doesn't send POST data to my PHP script and I don't know why. This is what I have so far:
C#
json = "{\"bedrijfsNaam\":\"" + bedrijfsNaam + "\"," +
"\"ContPers\":\"" + ContPers + "\"," +
"\"TelNum\":\"" + TelNum + "\"," +
"\"email\":\"" + email + "\"," +
"\"Land\":\"" + Land + "\"," +
"\"Plaats\":\"" + Plaats + "\"," +
"\"PostCode\":\"" + PostCode + "\"}";
var b64bytes = System.Text.Encoding.UTF8.GetBytes(json);
b64encode = System.Convert.ToBase64String(b64bytes);
using (WebClient client = new WebClient())
{
byte[] sendB64 = client.UploadData("http://" + ConfigurationManager.AppSettings["scripturi"].ToString() + "SalesKicker.php", "POST",
System.Text.Encoding.ASCII.GetBytes("b64string=" + b64encode + "&filename=" + dt.bedrijfsNaam));
MessageBox.Show(Encoding.UTF8.GetString(sendB64));
}
PHP
if($link ->connect_errno)
{
echo 'ERROR: no connection!';
}
else
{
if(isset($_POST['b64string']))
{
$jsonstring = base64_decode($_POST['b64string']);
$obj = json_decode($jsonstring);
$query_opslaan = "INSERT INTO SalesKicker (BedrijfsNaam, ContPers, TelNr, Email, Land, Plaats, POC) VALUES ('". $obj->bedrijfsNaam ."' , '". $obj->ContPers ."', '". $obj->TelNum ."', '". $obj->email ."', '". $obj->Land ."', '". $obj->Plaats ."', '". $obj->PostCode ."')";
mysqli_query($link, $query_opslaan) or die(mysqli_error($query_opslaan));
}
else
{
echo 'ERROR: no data!';
}
}
The problem is is that my PHP script returns
"ERROR: no data!"
This should obviously not happen. What should happen is that the PHP gets the POST data and saves it to my Database. Can someone please tell me why this isn't working correctly?
I should use the following c# method except of my current one:
var data = new NameValueCollection();
data["b64string"] = b64encode;
data["filename"] = dt.bedrijfsNaam;
using (WebClient client = new WebClient())
{
var uploadData = client.UploadValues("http://" + ConfigurationManager.AppSettings["scripturi"].ToString() + "SalesKicker.php", "POST",
data);
response = Encoding.UTF8.GetString(uploadData);
}
I should've been using the NameValueCollection instead of just a string.
Related
While sent email using below subject which apostrophe replacing with another characters
Actual Subject : We’ll make 100,800 cold calls for you
Mail Shows Subject : We’ll make 100,800 cold calls for you
Issue happens when I'm sent email via api , when sent email from SMTP it's working fine
Please check my api code below
string msg = "From: " + FromName + "<" + From + ">" + " \r\n" +
"To: " + ToName + "<" + To + ">" + " \r\n" +
"BCC: " + BCCEmail + " \r\n" +
"Subject: " + Subject + " \r\n" +
"Message-ID: mID_" + messageID + "\r\n" +
"References: "+encryptMessageID + "\r\n" +
"In-Reply-To: " + encryptMessageID + "\r\n" +
"Content-Type: " + contentType + "; charset=us-ascii\r\n\r\n" + Body;
dynamic objSendMsg = new { raw = commonFunction.Base64UrlEncode(msg) };
if (!string.IsNullOrEmpty(messageThreadID))
objSendMsg = new { raw = commonFunction.Base64UrlEncode(msg), threadId = messageThreadID };
var _objSendMsg = JsonConvert.SerializeObject(objSendMsg);
var strSendMsg = new StringContent(_objSendMsg, UnicodeEncoding.UTF8, "application/json");
When same content i'm applying in body with apostrophe working fine for body
Please check attached screenshot
Email copy
You need to base64_encode of the subject header your sending it as plain text. the API is getting confused.
Subject: " + Convert.ToBase64String(Subject) + " \r\n" +
I am calling ashx service for creating users on third party, I have URL and query string parameters set. the request accepts POST/GET http methods, and the response should return response code and response text as xml.
The weird thing is the users are being created but the response throws an exception [500 Internal Server error].
Here is the Code:
string URI = "https://thirdpartyservice.com/ApiHandler.ashx?";
string params = "ptf_cmd=403&ptf_method=md5" +
"&ptf_timer=" + sTimer +
"&ptf_check=" + sCheck +
"&ptf_client=" + rsaClient +
"&ptf_partner=" + sPartner +
"&ptf_offername=" + offername +
"&ptf_host=" + rsaHost +
"&ptf_login=" + sLogin +
"&ptf_password=" + password +
"&ptf_firstname=" + firstName +
"&ptf_lastname=" + lastName +
"&ptf_email=" + userEmail +
"&ptf_interfacelanguage=" + rsaInterfaceLanguage +
"&ptf_role=" + rsaUserRole +
"&ptf_pupildiscipline=" + rsaPupilDiscipline +
"&ptf_detailedResult=1" +
"&ptf_endingurl=" + rsaReturnUrl +
"&ptf_admingroup=" + rsaAdminGroup +
"&ptf_pedagroup=" + rsaPedaGroup +
"&ptf_usercreationmode=API";
using (var wc = new WebClient())
{
wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
string xmlResult = wc.DownloadString(URI + params); //throws exception [500 Internal Server Error].
//string xmlResult = wc.UploadString(URI, params);//throws exception [500 Internal Server Error].
}
I tried the request without setting the header and both POST/GET but also throws an exception.
Also I used HttpWebRequest class to send the request but it fails. Any suggestion(s) how to handle this?
I have a PHP script which get it's post data from my C# code. My C# code sends POST data to my PHP script including a base64 string and a filename. With these two pieces of data it should create a JSON file in the folder JSON with the filename and then it should write the decoded base64 string to the file it just created. After this it should save the JSON data to a database. But there's one problem, It doesn't create the JSON file and it saves blank data to my database. Here is what I have so far:
PHP:
<?php
$link = new mysqli($host, $user, $pass, $db);
if($link ->connect_errno)
{
echo 'Database connection wrong<br/>';
}
else
{
if(isset($_POST['filename']) && isset($_POST['b64string']))
{
$jsonstring = base64_decode($_POST['b64string']);
$filename = $_POST['filename'] . '.json';
$create = fopen(__DIR__. "/json/" . $filename, "W+");
fwrite($create, $jsonstring);
$json = fread($create, filesize(__DIR__. "/json/" . $filename));
fclose($create);
$obj = json_decode($json);
$query_opslaan = "INSERT INTO SalesKicker (BedrijfsNaam, ContPers, TelNr, Email, Land, Plaats, POC) VALUES ('". $obj->bedrijfsNaam ."' , '". $obj->ContPers ."', '". $obj->TelNum ."', '". $obj->email ."', '". $obj->Land ."', '". $obj->Plaats ."', '". $obj->PostCode ."')";
mysqli_query($link, $query_opslaan) or die(mysqli_error($query_opslaan));
}
else
{
echo 'ERROR: no data!';
}
}
?>
It get's the data from the following C# script:
if (reqCat == "bvg")
{
json = "{\"bedrijfsNaam\":\"" + bedrijfsNaam + "\"," +
"\"ContPers\":\"" + ContPers + "\"," +
"\"TelNum\":\"" + TelNum + "\"," +
"\"email\":\"" + email + "\"," +
"\"Land\":\"" + Land + "\"," +
"\"Plaats\":\"" + Plaats + "\"," +
"\"PostCode\":\"" + PostCode + "\"}";
var b64bytes = System.Text.Encoding.UTF8.GetBytes(json);
b64encode = System.Convert.ToBase64String(b64bytes);
using (WebClient client = new WebClient())
{
byte[] sendB64 = client.UploadData("http://" + ConfigurationManager.AppSettings["scripturi"].ToString() + "SalesKicker.php", "POST",
System.Text.Encoding.ASCII.GetBytes("b64string=" + b64encode + "&filename=" + dt.bedrijfsNaam));
}
}
This is my folder structure:
public_html (this is where all the PHP stuff is located) -> json (the folder where it should be saved)
I don't really know what to do at the moment so I came here to post my problem. Can someone please help me out and tell me what I'm doing wrong here?
Got it!
You sending 'filename' param in the POST body, but checking it in the GET array. So you don't even go into the your if(){} statement.
You need either change
if(isset($_GET['filename']) && isset($_POST['b64string']))
to
if(isset($_POST['filename']) && isset($_POST['b64string']))
either change in C#
byte[] sendB64 = client.UploadData("http://" + ConfigurationManager.AppSettings["scripturi"].ToString() + "SalesKicker.php", "POST",
System.Text.Encoding.ASCII.GetBytes("b64string=" + b64encode + "&filename=" + dt.bedrijfsNaam));
to
byte[] sendB64 = client.UploadData("http://" + ConfigurationManager.AppSettings["scripturi"].ToString() + "SalesKicker.php?filename=" + dt.bedrijfsNaam, "POST",
System.Text.Encoding.ASCII.GetBytes("b64string=" + b64encode));
I wasn't sure at first but after testing here the solution:
wrong:
$create = fopen(__DIR__. "/json/" . $filename, "W+");
correct:
$create = fopen(__DIR__. "/json/" . $filename, "w+");
It's kind of stupid but capital letters in the mode are not valid. Hope this solves the issue :)
That moment when a C# programmer forgets about the caches. I was a bit clumsy but after searching for the method how to clear a cache in PHP I found it. Behold, the legendary clearstatcache() method. My final working PHP code looks like this:
if(isset($_POST['filename']) && isset($_POST['b64string']))
{
clearstatcache();//the solution to my problem
$jsonstring = base64_decode($_POST['b64string']);
$filename = $_POST['filename'] . '.json';
$create = fopen(__DIR__. "/json/" . $filename, "w+");
fwrite($create, $jsonstring);
$json = fread($create, filesize(__DIR__. "/json/" . $filename));
fclose($create);
$obj = json_decode($json);
$query_opslaan = "INSERT INTO SalesKicker (BedrijfsNaam, ContPers, TelNr, Email, Land, Plaats, POC) VALUES ('". $obj->bedrijfsNaam ."' , '". $obj->ContPers ."', '". $obj->TelNum ."', '". $obj->email ."', '". $obj->Land ."', '". $obj->Plaats ."', '". $obj->PostCode ."')";
mysqli_query($link, $query_opslaan) or die(mysqli_error($query_opslaan));
}
I'm trying to write a tool to batch upload images to my website, but I'm having trouble receiving (or sending) the actual data to the server.
I'll start with some C# code as it should explain what I'm trying to do better that I can articulate:
private bool Upload( string LocalFile, int ItemID, string Description, DateTime Date, string Photographer )
{
WebClient oWeb = new System.Net.WebClient();
NameValueCollection parameters = new NameValueCollection();
parameters.Add( "Type", "1" );
parameters.Add( "ID", ItemID.ToString() );
parameters.Add( "Desc", Description );
parameters.Add( "Date", Date.ToString( "yyyy-MM-dd" ) );
parameters.Add( "Photographer", Photographer );
oWeb.QueryString = parameters;
var responseBytes = oWeb.UploadFile( "http://www.teamdefiant.co.uk/moveuploadedfile.php", LocalFile );
string response = Encoding.ASCII.GetString(responseBytes);
MessageBox.Show( "Response: \n\n" + response + "\n\nPost Data: \n\n" + LocalFile + "\n" + ItemID.ToString() + "\n" + Description + "\n" + Date.ToString("yyyy-MM-dd") + "\n" + Photographer );
Clipboard.SetText( "Response: \n\n" + response + "\n\nPost Data: \n\n" + LocalFile + "\n" + ItemID.ToString() + "\n" + Description + "\n" + Date.ToString("yyyy-MM-dd") + "\n" + Photographer );
return true;
}
When I receive the response, (as displayed in the MessageBox, and Clipboard.SetText) I get the following data:
Response:
Upload:
Type:
Size: 0kb
Stored in:
Post Data:
C:\Users\<MyFolder>\Pictures\Website\ExampleImage.png
4
Picture Description
2014-12-10
Photographer
And for completeness, here's the php code:
<?PHP
if ($_FILES["myfile"]["error"] > 0)
{
echo "Error: " . $_FILES["myfile"]["error"] . "\n";
}
else
{
echo "Upload: " . $_FILES["myfile"]["name"] . "\n";
echo "Type: " . $_FILES["myfile"]["type"] . "\n";
echo "Size: " . ($_FILES["myfile"]["size"] / 1024) . " Kb\n";
echo "Stored in: " . $_FILES["myfile"]["tmp_name"] . " \n";
echo $_POST["Type"] . " \n";
echo $_POST["ID"] . " \n";
echo $_POST["Desc"] . " \n";
echo $_POST["Date"] . " \n";
echo $_POST["Photographer"] . " \n";
}
?>
I've tried searching for answers but haven't been able to find a working solution that I can understand. (I'm still just learning C#.)
I don't get any code errors in Visual Studio, not do I get any POST errors server side, so I'm stumped.
Any and all help is appreciated!
EDIT
I tried visiting the webpage directly and get the same response, so it looks like no data is being sent to the server?? :(
your c# front-end code doesn't have few things
you need to define a content type octet stream
Client.Headers.Add("Content-Type","binary/octet-stream");
you also need to specify POST in your UploadFile
oWeb.UploadFile ("http://www.teamdefiant.co.uk/moveuploadedfile.php","POST", LocalFile);
try this simple code I found on the internet, create a different work branch and give it a try, this is a lot more basic and in a working condition:
the php script:
<?php
$uploaddir = 'upload/'; // Relative Upload Location of data file
if (is_uploaded_file($_FILES['file']['tmp_name'])) {
$uploadfile = $uploaddir . basename($_FILES['file']['name']);
echo "File ". $_FILES['file']['name'] ." uploaded successfully. ";
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully moved. ";
}
else
print_r($_FILES);
}
else {
echo "Upload Failed!!!";
print_r($_FILES);
}
?>
and this is the C# code:
System.Net.WebClient Client = new System.Net.WebClient ();
Client.Headers.Add("Content-Type","binary/octet-stream");
byte[] result = Client.UploadFile ("http://your_server/upload.php","POST","C:\test.jpg");
string s = System.Text.Encoding .UTF8 .GetString (result,0,result.Length );
we have a c# application that reads an email Inbox currently hosted on Exchange 2003 using the http service.
Now the mailbox is to be migrated to an Exchange 2010 server, so we are testing our code to confirm it will still work.
We are getting an error 'Bad request' with the below code (which tries to get all the mail):
public static XmlDocument GetUnreadMailAll()
{
HttpWebRequest loRequest = default(HttpWebRequest);
HttpWebResponse loResponse = default(HttpWebResponse);
string lsRootUri = null;
string lsQuery = null;
byte[] laBytes = null;
Stream loRequestStream = default(Stream);
Stream loResponseStream = default(Stream);
XmlDocument loXmlDoc = default(XmlDocument);
loXmlDoc = new XmlDocument();
try
{
lsRootUri = strServer + "/Exchange/" + strAlias + "/" + strInboxURL;
lsQuery = "<?xml version=\"1.0\"?>"
+ "<D:searchrequest xmlns:D = \"DAV:\" xmlns:m=\"urn:schemas:httpmail:\">"
+ "<D:sql>SELECT "
+ "\"urn:schemas:httpmail:to\", "
+ "\"urn:schemas:httpmail:displayto\", "
+ "\"urn:schemas:httpmail:from\", "
+ "\"urn:schemas:httpmail:fromemail\", "
+ "\"urn:schemas:httpmail:subject\", "
+ "\"urn:schemas:httpmail:textdescription\", "
//+ "\"urn:schemas:httpmail:htmldescription\", "
+ "\"urn:schemas:httpmail:hasattachment\", "
+ "\"urn:schemas:httpmail:attachmentfilename\", "
+ "\"urn:schemas:httpmail:senderemail\", "
+ "\"urn:schemas:httpmail:sendername\", "
+ "\"DAV:displayname\", "
+ "\"urn:schemas:httpmail:datereceived\", "
+ "\"urn:schemas:httpmail:read\", "
+ "\"DAV:id\" "
+ "FROM \"" + lsRootUri
+ "\" WHERE \"DAV:ishidden\" = false "
+ "AND \"DAV:isfolder\" = false "
+ "AND \"urn:schemas:httpmail:read\" = false "
+ "AND \"urn:schemas:httpmail:fromemail\" != 'emailAddy#domainName.co.uk' "
+ "</D:sql></D:searchrequest>";
loRequest = (HttpWebRequest)WebRequest.Create(lsRootUri);
loRequest.Credentials = new NetworkCredential(strUserName, strPassword);
loRequest.Method = "SEARCH";
laBytes = System.Text.Encoding.UTF8.GetBytes(lsQuery);
loRequest.ContentLength = laBytes.Length;
loRequestStream = loRequest.GetRequestStream();
loRequestStream.Write(laBytes, 0, laBytes.Length);
loRequestStream.Close();
loRequest.ContentType = "text/xml";
loRequest.Headers.Add("Translate", "F");
loResponse = (HttpWebResponse)loRequest.GetResponse();
loResponseStream = loResponse.GetResponseStream();
loXmlDoc.Load(loResponseStream);
loResponseStream.Close();
}
the exception is thrown on the line loResponseStream = loResponse.GetResponseStream();
here is the xml that we are sending:
<?xml version="1.0" ?>
- <D:searchrequest xmlns:D="DAV:" xmlns:m="urn:schemas:httpmail:">
<D:sql>SELECT "urn:schemas:httpmail:to", "urn:schemas:httpmail:displayto", "urn:schemas:httpmail:from", "urn:schemas:httpmail:fromemail", "urn:schemas:httpmail:subject", "urn:schemas:httpmail:textdescription", "urn:schemas:httpmail:hasattachment", "urn:schemas:httpmail:attachmentfilename", "urn:schemas:httpmail:senderemail", "urn:schemas:httpmail:sendername", "DAV:displayname", "urn:schemas:httpmail:datereceived", "urn:schemas:httpmail:read", "DAV:id" FROM "https://domain/Exchange/bbtest/Inbox" WHERE "DAV:ishidden" = false AND "DAV:isfolder" = false AND "urn:schemas:httpmail:read" = false AND "urn:schemas:httpmail:fromemail" != 'emailAddy#domainName.co.uk'</D:sql>
</D:searchrequest>
and from MSDN the answer is that WebDAV is deprecated after Exchange 2007, and replaced by Exchange Web Services
here are a couple of links:
MSDN Library: Get started with Exchange Web Services
OMEGACODER: Getting all emails from Exchange using Exchange Web Services
MSDN Code Downloads: Exchange - 101 samples