Retrieve PHP data on separate text block in window Phone 8.1 - c#

$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);

Related

Problem with consumer.receive MessageSelector

I have a problem in activemq. I want to receive a special message from my activemq queue. I have there over 300 Messages, and I want one of the message. I solved this with a multiselectcombobox. In this box I have all messages with all properties I need.
When I click on the 247 item, I want do select the item to receive the message, after them I want to send the message but first I have a problem with the receive.
I don't know why it doesn't work. Maybe someone has an idea?
ErrorMessageProperty prop = new ErrorMessageProperty();
IMessage message = null;
try
{
string MsgID = MSGID;
string desinationque = sourceQueue;
string selector = "ProducerId = '" + MsgID + "'";
IDestination dest = MQSession.GetDestination(desinationque);
Uri _activeMQURI = new Uri(conf.ActiveMqURL);
MQConnectionFactory = new NMSConnectionFactory(_activeMQURI);
using (MQConnection = MQConnectionFactory.CreateConnection(conf.ActiveMqUser, conf.ActiveMqPWD))
using (MQSession = MQConnection.CreateSession(AcknowledgementMode.AutoAcknowledge))
{
try
{
MQConnection.Start();
}
catch (Exception ex)
{
myLogger.NLogger.Info("MQReceiveTextMessage Connection fehlgeschlagen: " + ex.Message);
}
using (IMessageConsumer consumer = this.MQSession.CreateConsumer(dest, selector,false))
{
if (shallwait)
{
try
{
message = consumer.Receive();
}
catch (Exception ex)
{
myLogger.NLogger.Error("Error in consumer Receive (MQReceiveTextMessage): Message" + message + " Fehler-Exception: " + ex.Message);
}
}
else
{
message = consumer.Receive(TimeSpan.FromSeconds(1));
}
}
}
}
catch (Exception ex)
{
myLogger.NLogger.Error("Error in MQReceiveTextMessage: Parameter: sourceQueue: " + sourceQueue + " MSGID: " + MSGID + " Message: " + message + " Fehler-Exception: " + ex.Message);
}
return message;
}
My ProducerID is correct. But why doesn't this work? It stops at the line
message = consumer.receive();
I don't know anymore
With the selector ProducerId = 'MsgIDValue', the operation consumer.receive() is searching a Message in the queue with a custom property "ProducerId" with the value of the variable MsgID. If the message is not found the consumer waits new messages.
If you want to search for a default message field, message header field references are restricted to JMSDeliveryMode, JMSPriority, JMSMessageID, JMSTimestamp, JMSCorrelationID, and JMSType. JMSMessageID, JMSCorrelationID, and JMSType values may be null and if so are treated as a NULL value.
Source Message Selectors
I used Apache.NMS and Apache.NMS.ActiveMQ (1.7.1.3924)
is it possible to u se this api than the jms?
I try this since 1 Week and the selector does'nt work....
Maybe someone othe

How to send a POST in UWP c#

I need to send a POST method but it says invalid JSON content, do somebody knows what im doing wrong in the JSON format ¿?, ill apreciate a lot.
Uri resourceAddress;
if (!Helpers.TryGetUri(pcHost + pcPort + "/api/code/scan", out resourceAddress))
{
rootPage.NotifyUser("Invalid URI.", NotifyType.ErrorMessage);
return;
}
try
{
terminalRef = "1";
//code = "Uc0E17G4nW";
IHttpContent jsonContent = new HttpJsonContent(JsonValue.Parse("{\"code\":\"" + code +
",\"ref\" : \""+ terminalRef +
"\"}"));
HttpResponseMessage response = await httpClient.PostAsync(resourceAddress, jsonContent).AsTask(cts.Token);
Debug.WriteLine(".");
//await Helpers.DisplayTextResultAsync(response, cts.Token);
rootPage.NotifyUser("Completed", NotifyType.StatusMessage);
}
catch (Exception ex)
{
rootPage.NotifyUser("Error: " + ex.Message, NotifyType.ErrorMessage);
String errorMessage = ex.Message.ToString();
}
Noted that your string is not correctly formatted. Can you try the parsing below string,
"{\"code\" : \"" + code + "\", \"ref\" : \"" + terminalRef + "\"}"
The first way was as the Jaliya Udagedara's suggestion, you would need to check your json string's format to make sure that it's correct.
Another a simple way is using the Newtownsoft.Json to convert a c# object.
For example:
string jsonstring = JsonConvert.SerializeObject(new {code="code", Ref = "terminalRef" });
IHttpContent jsonContent = new HttpStringContent(jsonstring, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json");
HttpResponseMessage response = await httpClient.PostAsync(resourceAddress, jsonContent).AsTask(cts.Token);
After multiple failures i found how to make it works ( at least for me) hope it can help people working with Windows 10 iot in Universal Windows Platform (UWP) i know how difficult can be to fin proper documentation.
Uri resourceAddress;
if (!Helpers.TryGetUri(Host + Port + "/XXX/YYY/directory", out resourceAddress))
{
return;
}
IHttpContent jsonContentCoordinates = new HttpJsonContent(JsonValue.Parse("{\"zzz\": \"" + something
+ "\", \"xxx\": \"" + somethingXXX
+ "\",\"yyy\": \"" + somethingYYY
+ "\" }"));
HttpResponseMessage httpResponseCoordinates = new HttpResponseMessage();
string httpResponseBodyCoordinates = "";
try
{
httpResponseCoordinates = await httpClient.PostAsync(resourceAddress, jsonContentCoordinates).AsTask(cts.Token);
httpResponseBodyCoordinates = await httpResponseCoordinates.Content.ReadAsStringAsync();
httpResponseCoordinates.EnsureSuccessStatusCode();
FlagInternetNotConnected = false;
}
catch (Exception)
{
//Catch it if it fails.
}

Insert Data using Json in 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# ?

I am getting raw text while reading emails using IMAP

I have taken some code from MSDN to read emails using IMAP Client. I have changed little bit code so i can only read unseen email.
I am writing all response in Richtextbox.
The problems is format of Body text of Email is unreadable while all other text is fine.
void ReadEmail()
{
try
{
// there should be no gap between the imap command and the \r\n
// ssl.read() -- while ssl.readbyte!= eof does not work because there is no eof from server
// cannot check for \r\n because in case of larger response from server ex:read email message
// there are lot of lines so \r \n appears at the end of each line
//ssl.timeout sets the underlying tcp connections timeout if the read or write
//time out exceeds then the undelying connection is closed
tcpc = new System.Net.Sockets.TcpClient("imap.gmail.com", 993);
ssl = new System.Net.Security.SslStream(tcpc.GetStream());
ssl.AuthenticateAsClient("imap.gmail.com");
receiveResponse("");
username = "charlie#gmail.com";
password = "********";
receiveResponse("$ LOGIN " + username + " " + password + " \r\n");
receiveResponse("$ LIST " + "\"\"" + " \"*\"" + "\r\n");
receiveResponse("$ SELECT INBOX\r\n");
receiveResponse("$ UID SEARCH UNSEEN\r\n");
MatchCollection collection= Regex.Matches(Result,#" (\d{1,4})");
foreach (Match m in collection)
{
UNREAD_UID.Add(int.Parse(m.Groups[1].Value));
}
foreach (int x in UNREAD_UID)
{
receiveResponse("$ FETCH " +x + " body[header]\r\n");
richTextBox1.Text += Environment.NewLine+"-----------------------------------------------------------------------------------------------------------------------"+Environment.NewLine;
receiveResponse("$ FETCH " +x + " body[text]\r\n");
richTextBox1.Text += Environment.NewLine + "###########################################################2" + Environment.NewLine;
richTextBox1.Update();
}
//receiveResponse("$ STATUS INBOX (MESSAGES)\r\n");
// int number = 1;
receiveResponse("$ LOGOUT\r\n");
}
catch (Exception ex)
{
Console.WriteLine("error: " + ex.Message);
}
finally
{
if (sw != null)
{
sw.Close();
sw.Dispose();
}
if (ssl != null)
{
ssl.Close();
ssl.Dispose();
}
if (tcpc != null)
{
tcpc.Close();
}
}
}
void receiveResponse(string command)
{
try
{
if (command != "")
{
if (tcpc.Connected)
{
dummy = Encoding.ASCII.GetBytes(command);
ssl.Write(dummy, 0, dummy.Length);
}
else
{
throw new ApplicationException("TCP CONNECTION DISCONNECTED");
}
}
ssl.Flush();
buffer = new byte[5120];
bytes = ssl.Read(buffer, 0, 5120);
sb.Append(Encoding.ASCII.GetString(buffer));
Result = sb.ToString();
richTextBox1.Text += Environment.NewLine + Environment.NewLine + Environment.NewLine + Environment.NewLine + sb.ToString();
sb = new StringBuilder();
}
catch (Exception ex)
{
throw new ApplicationException(ex.Message);
}
}
Here is Sample of what i am getting
108 FETCH (BODY[TEXT] {25656}
DQoNCg0KDQo8IURPQ1RZUEUgaHRtbD4NCjxodG1sPg0KPGhlYWQ+DQo8dGl0bGU+TWlj
cm9zb2Z0IHR1cm5zIChhbG1vc3QpIGFueSBjYW1lcmEgaW50byBhIEtpbmVjdDwvdGl0
bGU+DQo8bWV0YSBodHRwLWVxdWl2PSJDb250ZW50LVR5cGUiIGNvbnRlbnQ9InRleHQv
aHRtbDsgY2hhcnNldD1VVEYtOCI+DQo8bWV0YSBuYW1lPSJ2aWV3cG9ydCIgY29udGVu
dD0id2lkdGg9ZGV2aWNlLXdpZHRoIj4NCjwhLS0gRWZmaW5nIFdpbmRvd3MgOCBNYWls
IGNsaWVudC4gQWRkIC13ZWJraXQtbWluLWRldmljZS1waXhlbC1yYXRpbzogMSB0byBz
Y2FyZSBpdCBhd2F5IGZyb20gdGhpcyBiaXQuIC0tPg0KPHN0eWxlIHR5cGU9InRleHQv
Y3NzIj4NCkBtZWRpYSBzY3JlZW4gYW5kIChtYXgtZGV2aWNlLXdpZHRoOiA1MDBweCkg
YW5kICgtd2Via2l0LW1pbi1kZXZpY2UtcGl4ZWwtcmF0aW86IDEpIHsNCgkuYm9keS1j
b250YWluZXIgeyB3aWR0aDoxMDAlICFpbXBvcnRhbnQ7IH0NCgkuYmFubmVyICAgICAg
ICAgeyBkaXNwbGF5OiBub25lICFpbXBvcnRhbnQ7IH0NCgkubW9iaWxlLWJhbm5lciAg
eyBkaXNwbGF5OiBibG9jayAhaW1wb3J0YW50OyB3aWR0aDozNDBweCAhaW1wb3J0YW50
OyBiYWNrZ3JvdW5kOiB1cmwoaHR0cDovL3d3dy5jb2RlcHJvamVjdC5jb20vc2NyaXB0
L21haWxvdXRzL3RlbXBsYXRlcy9uZXdzbGV0dGVyLWluc2lkZXIucG5nKSBuby1yZXBl
YXQgdG9wIGxlZ
Kindly help me.
You need to examine the Content-Transfer-Encoding header to undo Transfer encoding (in this case, that's Base64. Other alternatives are 7-bit or Quoted Printable). Or, better, download the entire message (Body[]) and apply a MIME parser/decoder to it to get an object representation of the headers, body, and attachments.
Max's answer above is correct, but I'm going to illustrate how to implement his suggestion using my MailKit library:
using (var client = new ImapClient ()) {
client.Connect ("imap.gmail.com", 993, true);
// since we're not using an OAuth2 token, remove it from the set
// of possible authentication mechanisms to try:
client.AuthenticationMechanisms.Remove ("XOAUTH2");
client.Authenticate ("charlie#gmail.com", "*****");
// SELECT the INBOX folder
client.Inbox.Open (FolderAccess.ReadWrite);
foreach (var uid in client.Inbox.Search (SearchQuery.NotSeen)) {
var message = client.Inbox.GetMessage (uid);
// at this point, 'message' is a MIME DOM that you can walk
// over to get the particular MIME-part that you want. For
// example, we could get a body part with a filename of
// "test.txt" using LINQ like this:
var attachment = message.BodyParts.OfType<MimePart> ()
.FirstOrDefault (x => x.FileName == "test.txt");
// decode the content to a MemoryStream:
using (var memory = new MemoryStream ()) {
attachment.ContentObject.DecodeTo (memory);
}
// since the attachment is probably a TextPart
// (based on the file extension above), we can actually
// use a simpler approach:
var textPart = attachment as TextPart;
if (textPart != null) {
// decode the content and convert into a 'string'
var text = textPart.Text;
}
}
client.Disconnect (true);
}

C# - WebClient.UploadFile isn't receiving POST data

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 );

Categories