Using Silverlight to consume a simple php service with WebClient

Suppose you have some php services which return a string using this simple code:

phpInfo.php:

<?=
phpInfo()
?>

phpGetExample.php:

<?
if($_GET['name'])
{
$name = $_GET['name'];
}
echo 'The service returned: ', $name
?>

You can consume this services by your Silverlight application using the WebClient class:

 

<UserControl x:Class="phpTest.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/ presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="300">

<StackPanel x:Name="LayoutRoot" Background="White">
<Button x:Name="btnCall" Click="btnCall_Click" Content="Call php"/>
<TextBlock Text="Result:"/>
<TextBlock Text="" x:Name="txtResult" Height="80"/>
<StackPanel Orientation="Horizontal">
<Button x:Name="btnCallPar" Click="btnCallPar_Click" Content="Call php with parameter"/>
<TextBox x:Name="txtParameter" Text="Enter your name" Width="200"/>
</StackPanel>

<TextBlock Text="Result:"/>
<TextBlock Text="" x:Name="txtResultPar"/>

</StackPanel>
</UserControl>

And in code behind:

 

<?
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
}

private void btnCall_Click(object sender, RoutedEventArgs e)
{
WebClient wc = new WebClient();
wc.DownloadStringCompleted += (s1, e1) => txtResult.Text = e1.Result;
wc.DownloadStringAsync(new Uri("<YourPhpUriHere>/phpInfo.php", UriKind.Absolute));
}

private void btnCallPar_Click(object sender, RoutedEventArgs e)
{
WebClient wc = new WebClient();
wc.DownloadStringCompleted += (s1, e1) => txtResultPar.Text = e1.Result;
wc.DownloadStringAsync(new Uri("<YourPhpUriHere>?name="+txtParameter.Text, UriKind.Absolute));
}
}

Read here the original post on the Siverlight forum and download the source code.


3 Responses to “Using Silverlight to consume a simple php service with WebClient”

  • Maggus Says:

    Getting crazy. The scipt works, however once i change the URI to a php file on my webserver (linux) it throws an NotSUpportedException.
    php file is completely the same…. Any idea?

  • Davide Says:

    Hi,
    - verify if you have a valid clientaccesspolicy.xml/crossdomain.xml in the root of your domain;
    - verify the phhp script is running properly on your server using internet explorer

    Hope this helps!

  • Maggus Says:

    You’re right. It happend I had no clientaccesspolicy and crossdomain xml files.
    Thanks!

Leave a Reply