How can i receive json data on PHP file? - c#

I am new in Xamarin and C# ,I want from my app to insert Books name and author to MySql database ,so I made class with name BooksInsert.cs:
using System;
using System.Collections.Generic;
using System.Text;
namespace NewTest.Model
{
class BooksInsert
{
public string book_name { get; set; }
public string book_auther { get; set; }
}
}
then another class with name WebHelper.cs for GET and POST :
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Linq;
using System.Net;
namespace NewTest.Model
{
class WebHelper
{
public string Post(Uri url, string value)
{
var request = HttpWebRequest.Create(url);
var byteData = Encoding.ASCII.GetBytes(value);
request.ContentType = "application/json";
request.Method = "POST";
try
{
using (var stream = request.GetRequestStream())
{
stream.Write(byteData, 0, byteData.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
return responseString;
}
catch (WebException)
{
return null;
}
}
public string Get(Uri url)
{
var request = HttpWebRequest.Create(url);
request.ContentType = "application/json";
request.Method = "GET";
try
{
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
return responseString;
}
catch (WebException)
{
return null;
}
}
}
}
in the adding page NewBookPage.xaml I have this contents :
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Class="NewTest.NewBookPage">
<ContentPage.Content>
<StackLayout>
<Entry x:Name="b_name" Placeholder="Name of Book"/>
<Entry x:Name="b_auther" Placeholder="auther of Book"/>
<Button Text="Save"
Clicked="Button_Clicked"/>
</StackLayout>
</ContentPage.Content>
</ContentPage>
and NewBookPage.xaml.cs :
using NewTest.Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace NewTest
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class NewBookPage : ContentPage
{
public NewBookPage()
{
InitializeComponent();
}
private void Button_Clicked(object sender, EventArgs e)
{
WebHelper webHelper = new WebHelper();
BooksInsert item = new BooksInsert();
item.book_name= b_name.Text;
item.book_auther = b_auther.Text;
string request = JsonConvert.SerializeObject(item);
Uri url = new Uri(string.Format("localhost/API/insert.php"));
string response = webHelper.Post(url, request);
if (response != null)
{
//Handle your reponse here
}
else
{
//No Response from the server
}
}
}
}
Now i don't know how to continue send json file to insert.php file and in insert.php how can i receive json data ,can any one help me?

Your Post method in WebHelper.cs is expecting an Uri entity as the first argument to be passed to HttpWebRequest.Create. But as the documentation states, it seems to expect a string as parameter, not an Uri class. Besides HttpWebRequest is obsolete and should not be used for new developments. MS states you should use HttpClient instead.
Try using WebRequest.Create instead as in this tutorial from MS: https://learn.microsoft.com/en-us/dotnet/framework/network-programming/how-to-request-data-using-the-webrequest-class.
WebRequest request = WebRequest.Create("http://localhost/API/insert.php");
If you change the Post method signature, then you don't need to use the Uri class in NewBookPage.xaml.cs, just send the URI as string to Post.

I don't know how it is correct ,but i tried simple way to insert data's to MySql database ,I just did this NewBookPage.xaml :
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Class="NewTest.NewBookPage">
<ContentPage.Content>
<StackLayout>
<Entry x:Name="b_name" Placeholder="Name of Book"/>
<Entry x:Name="b_auther" Placeholder="auther of Book"/>
<Button Text="Save"
Clicked="Button_Clicked"/>
<WebView x:Name="webView"
WidthRequest="1000"
HeightRequest="500"/>
</StackLayout>
</ContentPage.Content>
</ContentPage>
NewBookPage.xaml.cs :
using NewTest.Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace NewTest
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class NewBookPage : ContentPage
{
public NewBookPage()
{
InitializeComponent();
}
private void Button_Clicked(object sender, EventArgs e)
{
webView.Source = " https://Mywebsite/insert.php?bn=" + b_name.Text + "&ba=" + b_auther.Text;
}
}
}
insert.php
$bname=$_GET['bn'];
$bauthor=$_GET['ba'];
$query = "INSERT INTO books VALUES ('','$bname','$bauthor')";
mysqli_query($berikane,$query);
data inserted correctly ,how is this solution possible?

Finally I have sent Post data from Xamarin to PHP file and received it as post value :
private void Button_Clicked(object sender, EventArgs e)
{
using (var client = new WebClient())
{
var values = new NameValueCollection();
values["book_name"] = b_name.Text;
values["book_auther"] = b_auther.Text;
var response = client.UploadValues("https://MyWeb/insert.php", values);
var responseString = Encoding.Default.GetString(response);
if (response != null)
{
DisplayAlert("Success" ,"Data Inserted Successfully" ,"OK");
}
}
}

Related

How to populate a text box with data from another .cs files' class

Hi im so sorry for the generic question i am really new to C#. I am using a previous colleagues code but im looking to populate a textbox on a form with the data from a class.
This is the code for the thing i want to reference
public string GetToken(string username, string password) {
var request = SvcRequest
.Get(_url)
.WithAuthentication(this.CreateHeader(username, password))
.ReturningXml();
var response = _svc.Send(request);
return this.ExtractToken(response.Body);
I need to populate my text box with this.ExtractToken(response.Body). How do i do this?
Thanks a lot!
Code for main .cs file
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using System.Configuration;
using System.IO;
namespace EbsWebServices
{
internal sealed class EbsAuthManager
{
private readonly string _url;
private readonly SvcUtility _svc = new SvcUtility();
public EbsAuthManager()
{
_url = "URL_HERE";
if(!_url.EndsWith("/"))
{
_url += "/";
}
_url += "Rest/Authentication";
}
public string GetToken(string username, string password)
{
var request = SvcRequest
.Get(_url)
.WithAuthentication(this.CreateHeader(username, password))
.ReturningXml();
var response = _svc.Send(request);
return this.ExtractToken(response.Body);
}
private string CreateHeader(string username, string password)
{
var credentials = String.Format("{0}:{1}", username, password);
var encoded = Convert.ToBase64String(Encoding.UTF8.GetBytes(credentials));
return String.Format("Basic {0}", encoded);
}
private string ExtractToken (string xml)
{
var doc = new XmlDocument();
doc.LoadXml(xml);
var navigator = doc.DocumentElement.CreateNavigator();
var success = navigator
.SelectChildren("Success", string.Empty)
.Cast<XPathNavigator>()
.First();
var token = navigator
.SelectChildren("Token", string.Empty)
.Cast<XPathNavigator>()
.First();
return Convert.ToBoolean(success.InnerXml)
? token.InnerXml
: null;
}
}
}
Code for my form
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using EbsWebServices;
namespace EBSGetTokenForm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
}
}
}

Xamarin picker not showing the date from the list

I have the following code:
<ContentPage.BindingContext>
<local:PisterosViewModel/>
</ContentPage.BindingContext>
<Picker x:Name="pck_Pisteros"
ItemDisplayBinding="{Binding PisteroN}"
ItemsSource="{Binding PisterosLista}"
SelectedItem="{Binding PisterosLista}"
Title="Seleccione el usuario..."/>
Then my Model:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.Contracts;
using System.Text;
namespace ServLottery.Models
{
public class Pisteros
{
public string PisteroID { get; set; }
public string PisteroN { get; set; }
}
}
and the view model:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
namespace ServLottery.Models
{
public class PisterosViewModel
{
public IList<Pisteros> PisterosLista { get; set; }
public PisterosViewModel()
{
try
{
PisterosLista = new ObservableCollection<Pisteros>();
GetPisteros();
}
catch (Exception ex)
{
throw ex;
}
}
private async void GetPisteros()
{
try
{
RestClient client = new RestClient();
var pist = await client.Get<Models.Pisteros>("https://servicentroapi.azurewebsites.net/api/Pisteros");
if (pist != null)
{
PisterosLista = pist;
}
}
catch (Exception ex)
{
throw ex;
}
}
}
}
I set an breakpoint in var pist and it does have the values, then Pisteros list seems to get the values too, and this is executed when the page load, so I don't understand what's the problem, but the picker never shows the options.
Welcome to SO !
It seems like BindingContext in Xaml can not deal with the dynamical data ,such API data from web server .
There is a workaround binding ItemSource dynamically by using coding in ContentPage , also can refer to this officail sample .
Therefore , adding code in Page.Xaml.cs as follow :
protected override async void OnAppearing()
{
pck_Pisteros.ItemsSource = await GetTasksAsync();
base.OnAppearing();
}
private async Task<List<Pisteros>> GetTasksAsync()
{
List<Pisteros> PisterosLista = new List<Pisteros>();
HttpClient client = new HttpClient();
Uri uri = new Uri(string.Format("https://servicentroapi.azurewebsites.net/api/Pisteros", string.Empty));
HttpResponseMessage response = await client.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
string content = await response.Content.ReadAsStringAsync();
PisterosLista = JsonConvert.DeserializeObject<List<Pisteros>>(content);
Console.WriteLine("content :: " + content);
Console.WriteLine("Data :: " + PisterosLista);
}
return PisterosLista;
}
Now it will show:

System.Net.WebException: 'Error: ConnectFailure (Connection refused)'

I have this page below ,I want send data with json to my PHP page to insert users to MySQL database.
but the connection failed :"System.Net.WebException: 'Error: ConnectFailure (Connection refused)'"
My page in xaml:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Class="fullApp.MainPage">
<StackLayout Margin="0,30,0,0" Padding="20">
<Entry x:Name="user" Placeholder="UserName"></Entry>
<Entry x:Name="pass" Placeholder="Password" ></Entry>
<Entry x:Name="phone" Placeholder="Phone Number"></Entry>
<Entry x:Name="gover" Placeholder="Governorate"></Entry>
<Entry x:Name="city" Placeholder="City"></Entry>
<Entry x:Name="street" Placeholder="Street"></Entry>
<Button x:Name="rigister" Clicked="Rigister_Clicked"></Button>
</StackLayout>
</ContentPage>
My page on cs :
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace fullApp
{
// Learn more about making custom code visible in the Xamarin.Forms previewer
// by visiting https://aka.ms/xamarinforms-previewer
[DesignTimeVisible(false)]
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
pass.IsPassword = true;
}
void Rigister_Clicked(object sender, EventArgs e)
{
PostJson("http://localhost:3308/test/API/rigister_user.php", new users
{
username = user.Text,
password = pass.Text,
PhoneNumber = phone.Text,
Governorate = gover.Text,
City = city.Text,
Street = street.Text
});
void PostJson(string uri, users postParameters)
{
string postData = JsonConvert.SerializeObject(postParameters);
byte[] bytes = Encoding.UTF8.GetBytes(postData);
var httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
httpWebRequest.Method = "POST";
httpWebRequest.ContentLength = bytes.Length;
httpWebRequest.ContentType = "text/xml";
using (Stream requestStream = httpWebRequest.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Count());
}
var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
if (httpWebResponse.StatusCode != HttpStatusCode.OK)
{
string message = String.Format("POST failed. Received HTTP {0}", httpWebResponse.StatusCode);
throw new ApplicationException(message);
}
}
}
}
public class users
{
public string username { get; set; }
public string password { get; set; }
public string PhoneNumber { get; set; }
public string Governorate { get; set; }
public string City { get; set; }
public string Street { get; set; }
}
}
the debuging stop on this line whis i get error message :"System.Net.WebException: 'Error: ConnectFailure (Connection refused)'":
using (Stream requestStream = httpWebRequest.GetRequestStream())
Login page
Registration Page
After sign in or registering
You can use HttpClient and make it an asynchronous function:
async Task<string> PostJson(string uri, users postParameters)
{
string postData = JsonConvert.SerializeObject(postParameters);
using (var client = new HttpClient());
var response = await client.PostAsync(uri, new StringContent(postData));
if (!response.IsSuccessStatusCode)
{
string message = String.Format("POST failed. Received HTTP {0}", response.StatusCode);
throw new ApplicationException(message);
}
return await response.Content.ReadAsStringAsync();
}
Update:
I know this doesn't solve to OPs question but it's just a much more elegant way to do it.

GET, POST to a rest api

Hi i have a Api that i want to use to collect data from a backend that spits out json i need to get this via C# Application and it's http functionalities. My question is should i use a rest api and setup an async thread that downloads the data and then use the data as i want to from there or should i somehow use something close to a Web Api i have an authentication that is required to exist in a header. This has given me some hedaches because i keep on being split by what to use for what. I mean i need to do a Httprequest with a header. this i later on need to use for posting to another database. but the user of the program should not have to see the data itself. i have two examples that i have done but i don't know with what i should continue? this is my two examples in code...
Example 1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;
namespace Plugin
{
public enum HttpVerb
{
GET,
POST,
PUT,
DELETE
}
class Api
{
private HttpVerb HttpMethod { get; set; }
public Api()
{}
public string startDownload()
{
return (Download("sending token"));
}
private string Download(string token)
{
string strResponseValue = string.Empty;
string finnishedOutput = string.Empty;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("Url");
request.Headers.Add("Authorization", "Bearer " + token);
request.Method = HttpMethod.ToString();
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
strResponseValue = reader.ReadToEnd();
}
return strResponseValue;
}
catch (WebException e)
{
HttpWebResponse httpResponse = (HttpWebResponse)e.Response;
if ((int)httpResponse.StatusCode == 401)
{}
int errorCodeInt;
string errorCode;
errorCodeInt = (int)httpResponse.StatusCode;
errorCode = errorCodeInt.ToString();
return errorCode;
}
}
}
}
Example 2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace TestAPi
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Api.InitializeClient("");
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
namespace TestAPi
{
public class Api
{
private static HttpClient ApiClient { get; set;}
private string url { get; set;}
public static void InitializeClient(string token)
{
ApiClient = new HttpClient();
ApiClient.BaseAddress = new Uri("your url");
ApiClient.DefaultRequestHeaders.Accept.Clear();
ApiClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
ApiClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("Bearer Authentication"));
}
public async Task<Data> LoadData()
{
url = ApiClient.BaseAddress.ToString();
using (HttpResponseMessage response = await ApiClient.GetAsync(url))
{
if (response.IsSuccessStatusCode)
{
Data data = await response.Content.ReadAsAsync<data>();
return data;
}
else
{
throw new Exception(response.ReasonPhrase);
}
}
}
}
}

Post a message to slack from c# application

I am trying to post a message on the #general channel and this worked when was doing it through a console app but Now I am using MVC and the message doesn't seem to get posted. Also, earlier I was using the webhook URL and now I am using the access token that I have.
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
namespace SlackClient.Controllers
{
public class SlackClient
{
private readonly Uri _uri;
private readonly Encoding _encoding = new UTF8Encoding();
public SlackClient(string urlWithAccessToken)
{
_uri = new Uri(urlWithAccessToken);
}
//Post a message using simple strings
public void PostMessage(string text, string username = null, string channel = null)
{
Payload payload = new Payload()
{
Channel = channel,
Username = username,
Text = text
};
PostMessage(payload);
}
//Post a message using a Payload object
public void PostMessage(Payload payload)
{
string payloadJson = JsonConvert.SerializeObject(payload);
using (WebClient client = new WebClient())
{
NameValueCollection data = new NameValueCollection();
data["payload"] = payloadJson;
var response = client.UploadValues(_uri, "POST", data);
//The response text is usually "ok"
string responseText = _encoding.GetString(response);
}
}
}
//This class serializes into the Json payload required by Slack Incoming WebHooks
public class Payload
{
[JsonProperty("channel")]
public string Channel { get; set; }
[JsonProperty("username")]
public string Username { get; set; }
[JsonProperty("text")]
public string Text { get; set; }
}
}
And the other class is SlackClientTest.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace SlackClient.Controllers
{
public class SlackClientTest
{
void TestPostMessage()
{
string urlWithAccessToken = "https://srishti2604.slack.com/services/hooks/incoming-webhook?token=my-tokenHere.";
SlackClient client = new SlackClient(urlWithAccessToken);
client.PostMessage(username: "Mr. Torgue",
text: "THIS IS A TEST MESSAGE! SQUEEDLYBAMBLYFEEDLYMEEDLYMOWWWWWWWW!",
channel: "#general");
}
}
}
Could someone tell me what might me wrong?
My console app looks like this
SlackClient.cs
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace SlackProject1
{
public class SlackCient
{
private readonly Uri _webhookUrl;
private readonly HttpClient _httpClient = new HttpClient();
public SlackCient(Uri webhookUrl)
{
_webhookUrl = webhookUrl;
}
public async Task<HttpResponseMessage> SendMessageAsync(string message,
string channel = null, string username = null)
{
var payload = new
{
text = message,
channel,
username,
};
var serializedPayload = JsonConvert.SerializeObject(payload);
var response = await _httpClient.PostAsync(_webhookUrl,
new StringContent(serializedPayload, Encoding.UTF8, "application/json"));
return response;
}
}
}
And the Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SlackProject1
{
class Program
{
static void Main(string[] args)
{
Task.WaitAll(IntegrateWithSlackAsync());
}
private static async Task IntegrateWithSlackAsync()
{
var webhookUrl = new Uri("https://hooks.slack.com/services/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");
var slackClient = new SlackCient(webhookUrl);
while (true)
{
Console.Write("Type a message: ");
var message = Console.ReadLine();
var response = await slackClient.SendMessageAsync(message);
var isValid = response.IsSuccessStatusCode ? "valid" : "invalid";
Console.WriteLine($"Received {isValid} response.");
}
}
}
}

Categories