none
Get response from server to Silverlight

    Question

  • Thanks to another post in this forum I found out how to send information from Silverlight to a PHP-script on the server. 

    But what if I want to get information from the server? I want to create something similar to a file browser in silverlight to let members browse their accounts they have on the server. 

    How can I use the webclient to get that information? 

    Thanks for help!

    Monday, June 15, 2009 2:55 PM

Answers

  • Hi,

    I've updated the example with a new script "phpGetExample.php':

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

    And the Silverlight project:

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

     

    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("http://www.davidezordan.net/samples/php/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("http://www.davidezordan.net/samples/php/phpGetExample.php?name="+txtParameter.Text, UriKind.Absolute));

    }

    }

     

    The updated project is available at this link.

    Wednesday, June 17, 2009 4:55 PM

All replies

  • The easiest way would be to use a web service hosted on the server to expose the file system. Then you can consume that service from Silverlight.

    However, if you must do it using the webclient, I would assume that you could by returning XML in the response and then parsing the XML in Silverlight to create the list of files and folders.

    This thread may help: http://silverlight.net/forums/t/101083.aspx

    If not please let me know and we can dig a little deeper.

    Monday, June 15, 2009 3:02 PM
  • Thanks for the reply,

     and sorry for my late response. Would it be easier to have the file browser in php? So, when the user clicks the "open" button in the silverlight app a php file browser would pop up. The user can then navigate to the file he/she wants to open and open it by clicking on the file name.

    If this solution is not possible. Can you explain a bit more about the web service? I don't need to use webclient, I just didn't know there was any other way.

     Thanks for help! 

    Tuesday, June 16, 2009 2:44 PM
  • No problem at all.

    As for the php file browser, I personally wouldn't know how to tell Silverlight which file was selected in the pop up window. This doesn't mean it cannot be done by any means, just not something I have tried or seen before. So I would be no help with that solution.

    I would suggest keeping them in the Silverlight app to do the file selection using the web service. Since you are not dependent on using the web client this should be pretty simple, and allow you to have strong typed code for doing so. This code be done using WCF as well, but ASMX web services are easier to get started with typically.

    Here is a brief summary of what the web serivce would look like:

    <WebService(Namespace:="http://yournamespace.com/")> _
    <WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
    Public Class FileBrowserWebService
        Inherits System.Web.Services.WebService
    
    
        <WebMethod(Description:=" Get a list of folders in the folder supplied.")> _
          Public Function GetFolders(ByVal relativeParentFolderPath As String) As List(Of String)
    
            Try
                If String.IsNullOrEmpty(relativeParentFolderPath) Then
                    relativeParentFolderPath = "~/"
                End If
    
                Dim serverFolderPath As String = Server.MapPath(relativeParentFolderPath)
    
                Dim files = From f In IO.Directory.GetDirectories(serverFolderPath) _
                            Select f.Substring(f.LastIndexOf("\") + 1)
    
    
    
                Return files.ToList
    
            Catch ex As Exception
                'Log Exception 
    
                Return New List(Of String)
    
            End Try
    
        End Function
    
        <WebMethod(Description:=" Get a list of files in the folder supplied.")> _
              Public Function GetFiles(ByVal relativeFolderPath As String) As List(Of WebFileInfo)
    
            Try
                If String.IsNullOrEmpty(relativeFolderPath) Then
                    relativeFolderPath = "~/"
                End If
    
                Dim serverFolderPath As String = Server.MapPath(relativeFolderPath)
    
                Dim files = From f In IO.Directory.GetFiles(serverFolderPath) _
                        Select New WebFileInfo(f)
    
                Return files.ToList
    
            Catch ex As Exception
                'Log Exception 
    
                Return New List(Of WebFileInfo)
    
            End Try
    
        End Function
    
    
    
    End Class
    

     

    Here is an example of what the WebFileInfo could look like:

    <Serializable()> _
    Public Class WebFileInfo
        Private lastModifiedField As Date = Now
    
        Private info As IO.FileInfo
    
        Public Sub New()
    
        End Sub
    
        Public Sub New(ByVal filePath As String)
    
            Me.info = New IO.FileInfo(filePath)
    
        End Sub
    
    
        Public Property Extension() As String
            Get
                Return Me.info.Extension
            End Get
            Set(ByVal value As String)
                'No Op - cannot be readonly
    
            End Set
        End Property
    
        Property LastModified() As Date
            Get
                Return Me.info.LastWriteTime
            End Get
            Set(ByVal value As Date)
                'No Op - cannot be readonly
            End Set
        End Property
    
    
        Public Property FileName() As String
            Get
                Return Me.info.Name
            End Get
            Set(ByVal value As String)
                'No Op - cannot be readonly
            End Set
        End Property
    
        Public Property FilePath() As String
            Get
                Return Me.info.FullName
            End Get
            Set(ByVal value As String)
                'No Op - cannot be readonly
            End Set
        End Property
    
        Public Property Size() As Integer
            Get
                Return Me.info.Length
            End Get
            Set(ByVal value As Integer)
                'No Op - cannot be readonly
            End Set
        End Property
    
       
    End Class
      

    Notice the properties of this class are not marked as readonly because serializable types cannot have readonly properties. So just do not do anything with the setter if you are going to wrap the IO.FileInfo class like I did.

    Now you can add a reference to this in Silverlight and you will get a new API built to interact with the web service.

    Here is a link to some code I wrote to allow the DotNetNuke file structure to be exposed through a web service. This is more complex that what you are looking for and is not built for Silverlight. However it is a full implementation of how to expose files and folders through ASMX that might be handy to have for reference as well: http://iweb.codeplex.com/SourceControl/changeset/view/12386#6338

     

    Tuesday, June 16, 2009 3:35 PM
  • Thanks,

     this might be a stupid question. Don't have that much experience in this but can this really be used on an apache server supporting php and not asp.net?

    Tuesday, June 16, 2009 3:42 PM
  • Ugh, missed that it was running on apache Sad

    The Silverlight portion would not change regardless of how the web service is hosted as long as the service exposes SOAP 1.1. The logic \ concept that I explained in the VB web service is the same for the web service, but obviously the code would be different.

    There are some articles out there about creating a SOAP 1.1 web service using PHP, here are a few I found. Hopefully this will get you started in the right direction.

    http://webservices.xml.com/pub/a/ws/2004/03/24/phpws.html

    http://us3.php.net/soap

     

     

    Tuesday, June 16, 2009 3:56 PM
  •  or Java if it is more convinient to you ;-)

    Tuesday, June 16, 2009 4:52 PM
  • Hi,

    if you are using Apache on the server side, I suggest you to use WebClient to retrieve data returned from your PHP script:

    Hope this helps.

    Tuesday, June 16, 2009 5:25 PM
  •  Thanks for the replies guys,

    This post shows how to send a mail from a silverlight application through php (I mentioned it in my first post). He uses a webclient and then posts the message to the php-script.

    Can I use a similar approach but using the webclient and the DownloadStringAsync to get a string from a php-script? So for example, when I press a button a "Get"-request is sent to the php-script and then a string is sent in return to the silverlight app?

    If so, does anyone have an idea to this? I don't know how to move forward.

    Thanks for help!

    Wednesday, June 17, 2009 5:16 AM
  • have a look here for consuming a php webservice with a SL webclient

    http://code.dortikum.net/2008/08/03/silverlight-php/#more-41

    Wednesday, June 17, 2009 5:33 AM
  •  Thanks,

    I downloaded the example they had but it didn't work. However, I found another link on that page to something called webOrb . They seem to have developed something to make client/server communication easier. I'll check it out.

    But, I'm still interested in how this can be solved without third-party tools. I've found other samples:

    http://www.shinedraw.com/data-handling/flash-vs-silverlight-simple-http-post-request/

    http://alpascual.com/blog/silverlight-101-make-a-get-request-and-a-post-request/

    but I can't get them to work either. 

    I just want to make a request from a silverlight app to a php-script and when that happens I want the php-script to send a string in return (any string containg whatever for test purposes). The Silverlight app should the be able to read that string. Script and silverlight app are located on the same server so there should not be any need for cross-domain.

    A working sample for this would be highly appreciated!

    Thanks!

    Wednesday, June 17, 2009 7:48 AM
  • Hi,

    • insert this php script in a folder of your apache server and name it "phpInfo.php":

    <?=phpInfo() ?>

    • insert "clientaccesspolicy.xml" / "crossdomain.xml" in the root of your domain (if you are using linux, remember that it is case-sensitive!)
    • use this code to retrieve the string from your Silverlight application:

    xaml:

    <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"/>

    </StackPanel>

    </UserControl>

     

    code-behind:

    namespace phpTest

    {

    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("http://www.davidezordan.net/samples/php/phpInfo.php", UriKind.Absolute));

    }

    }

    }

    The php script is available for test here, the complete Silverlight 3 beta solution here.

    Hope this helps.

    Wednesday, June 17, 2009 12:56 PM
  •  Thanks,

    I downloaded your project and it worked straight away :-)

    Just wondering, now it downloads the complete page. What if I want the script to return a string? For example if the silverlight app post something to the php-script and then the script performs something with that string and send another string in return back to the silverlight app. How can that be achieved?

    Sorry for my many questions :-)

    Wednesday, June 17, 2009 3:14 PM
  • Hi,

    I've updated the example with a new script "phpGetExample.php':

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

    And the Silverlight project:

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

     

    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("http://www.davidezordan.net/samples/php/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("http://www.davidezordan.net/samples/php/phpGetExample.php?name="+txtParameter.Text, UriKind.Absolute));

    }

    }

     

    The updated project is available at this link.

    Wednesday, June 17, 2009 4:55 PM
  •  Thank you very much!

    Finally I get it. The php and sever side things are all really new to me that's why I've been a bit slow :-)

    I'll try to place the xml-file you posted earlier on my server and try it out myself.

    Wednesday, June 17, 2009 5:09 PM
  • Sweet, have a nice day Big Smile

    Wednesday, June 17, 2009 5:16 PM