When i try to execute this
MainPage.xaml.cs code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Windows;
using System.Net.Http.Json;
using Windows.UI;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Media;
using System.Net.Http;
namespace OpenSilverApplication3
{
public partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
TestTod();
}
private async void TestTod()
{
using (HttpClient client = new HttpClient())
{
var response = await client.GetAsync("http://89.208.81.184:1337/DnD1C/hs/DNDAPI/V1/GETINFO");
response.EnsureSuccessStatusCode();
if (response.IsSuccessStatusCode)
{
Testing.Text = await response.Content.ReadAsStringAsync();
}
else
{
Testing.Text = $"Server error {response.StatusCode}";
}
}
}
}
}
MainPage.xaml code:
<sdk:Page
x:Class="OpenSilverApplication3.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
xmlns:local="clr-namespace:OpenSilverApplication3"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Title="Page1" Background="White" >
<ScrollViewer HorizontalScrollBarVisibility="auto" VerticalScrollBarVisibility="auto">
<Grid>
<TextBlock x:Name="Testing" Width="450" Height="250" Text="Test" HorizontalAlignment="Center" VerticalAlignment="Bottom" Background="#FFD9D9D9" TextWrapping="Wrap"/>
</Grid>
</ScrollViewer>
</sdk:Page>
nothing happens.
If i enter this link("http://89.208.81.184:1337/DnD1C/hs/DNDAPI/V1/GETINFO") in browser, then page opens with data in JSON format. The database I'm connecting to is on a private server, so it doesn't have a domain name. This server use Apache 2.4.
I replace link("http://89.208.81.184:1337/DnD1C/hs/DNDAPI/V1/GETINFO") on this link("https://jsonplaceholder.typicode.com/todos") and then code execute correctly.
I use VS 2022. Using OpenSilver(https://opensilver.net/)
Maybe I need give permissions to the application for connect to external ip-addresses?
I test this link("http://89.208.81.184:1337/DnD1C/hs/DNDAPI/V1/GETINFO") in fiddler. Result
Test with this link("http://89.208.81.184:1337/DnD1C/hs/DNDAPI/V1/GETINFO")
Result
Test with this link("https://jsonplaceholder.typicode.com/todos")
Result
I changed code to catch error.
namespace OpenSilverApplication3
{
public partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
TestTod();
}
private async void TestTod()
{
using (HttpClient client = new HttpClient())
{
try
{
var response = await client.GetAsync("http://89.208.81.184:1337/DnD1C/hs/DNDAPI/V1/GETINFO");
response.EnsureSuccessStatusCode();
if (response.IsSuccessStatusCode)
{
Testing.Text = await response.Content.ReadAsStringAsync();
}
else
{
Testing.Text = $"Server error {response.StatusCode}";
}
}
catch (Exception ex)
{
Testing.Text = ex.ToString();
}
}
}
}
}
Here is the error I got:
System.Net.Http.HttpRequestException: TypeError: Failed to fetch
---> System.Runtime.InteropServices.JavaScript.JSException: TypeError: Failed to fetch
at System.Net.Http.BrowserHttpHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
--- End of inner exception stack trace ---
at System.Net.Http.BrowserHttpHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.HttpClient.<SendAsync>g__Core|83_0(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationTokenSource cts, Boolean disposeCts, CancellationTokenSource pendingRequestsCts, CancellationToken originalCancellationToken)
at OpenSilverApplication3.MainPage.TestTod() in C:\Users\NyComp\source\repos\OpenSilverApplication3\OpenSilverApplication3\MainPage.xaml.cs:line 30
Related
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:
I have the following Code in Visual Studio
using System;
using System.Windows.Forms;
using System.Net.Http;
using System.Web;
using System.Net;
using System.IO;
namespace Xml_Trial
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void LoadUrl_click(object sender, EventArgs e)
{
Xmlcheck(TxtUrl.Text);
}
private static async void Xmlcheck(string TxtUrl)
{
try
{
HttpClient client = new HttpClient() ; //httpclient
var request = new HttpRequestMessage(HttpMethod.Get, TxtUrl);
HttpResponseMessage response = await client.GetAsync(request.RequestUri);
if (response.StatusCode == HttpStatusCode.OK)
{
// Console.WriteLine((int)response.StatusCode); More code here
}
response.Dispose();
}
catch (HttpRequestException e)
{
MessageBox.Show(e.Message);
}
}
}
}
I have written the code this way to get the 200 status code Console.WriteLine((int)response.StatusCode)
What Code is else posssible to get more out of the httpstatuscode description rather than just "OK" or "200"....
I believe you're looking for the ReasonPhrase property, which is "the reason phrase which typically is sent by servers together with the status code."
For example:
Console.WriteLine($"{(int)response.StatusCode} {response.ReasonPhrase}");
A list of all valid status codes (including my favourite, 418) with their default reason phrases is here: HTTP response status codes
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");
}
}
}
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.
My problem
I have my Universal Windows Application and i want work with rest api.
I always get error CS 4032 in this :
httpResponseBody = await httpClient.GetStringAsync(requestUri);
Like you can't call that method when it is not async.
Whole code
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using System.Net;
using Windows.Web.Http;
namespace UniversalCA
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
Send();
}
public string Send()
{
HttpClient httpClient = new HttpClient();
Uri requestUri = new Uri("http://restapic.azurewebsites.net/WebForm1.aspx?func=dd&hodn=WW");
HttpResponseMessage httpResponse = new HttpResponseMessage();
string httpResponseBody = "";
try
{
httpResponseBody = await httpClient.GetStringAsync(requestUri);
}
catch (Exception ex)
{
httpResponseBody = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message;
}
string tt = httpResponseBody.Split('>')[1].Split('<')[0];
return httpResponseBody;
}
}
}
The problem is that you cannot use await keyword inside a not async function. Your Send function does not have async keyword in declaration. Adding async keyword will solve the problem
public async Task<string> Send()
Just To add to #Ruben Vardanyans answer.
simply:
add using System.Threading.Tasks;
add Wait() keyword on your Send(); call
public MainPage()
{
this.InitializeComponent();
Send().Wait();
}
and finally on your Send() method
add async Task<T>
public async Task<string> Send()
Please check out this answer for calling an asynchronous method inside a constructor. Call asynchronous method in constructor?
do not use await Send(); for calling the method you will have a compiler error.