Table Of Content
Required Knowledge
Required Tools
WHY Do
This
Getting
Started, lets build a simple RSS feed
The PHP code to install
database table
The PHP Code.
Silverlight Client.
Building a class to manage the
feed
Create a serialiser
PHP Error Handling
So Far
Doing some JavaScript
Some VB
RequestRssFeed
Respond To Request
Wire Up JavaScript
Place the data into our control
StartTimer method
timer_Tick Event
Are We There Yet
Run
insertrecordstorss.php to put some records in the table
Required Knowledge
Required Tools
- VS2008
- Apache server with PHP
extensions installed - MYSQL on server
- PHP Editor. I have the free
PHP4Vs2008 works great in Visual Studio - FTP Program to Upload your files
WHY Do This
My ISP provides me web space as
part of my account. This Server been Apache Server also provides MYSQL Database
and PHP Server side scripting. As a home account there’s certain limitation to
the service for security and commercial reasons.
So how can I use this
service to consume data in a Silverlight application? So first I tried building
a Web Service. This all tested great in PHP however when I tried to hook in
Silverlight I had a Security Exception. What I needed is was a
clientaccesspolicy.xml file. So ok I set about doing creating this file and hole
and behold this file is required in the root of the apache server. Something
only the Administrator can do. FAILED!!!!
Ok let’s try Json Still the
same issue Web Client refuses to call PHP files even though it is stated in the
Silverlight Beta 2.2 Documentation that local files do not need an access policy
file. STUCK!!!!
Then I came across the bridging Managed code to HTML. HUH
I THINK I HAVE GOT IT!!!
So ok, why not consume the data in the Host Page
and use this data in my Silverlight Application.
Getting Started, lets
build a simple RSS feed
So first we need a Data source. My Case
MYSQL.
So let’s create a Table to hold the data.
The sql
Statement
CREATE TABLE `rssfeed` (
`rssId` TINYINT( 18 ) NOT NULL
AUTO_INCREMENT PRIMARY KEY COMMENT 'Id of feed',
`createdate` TIMESTAMP ON
UPDATE CURRENT_TIMESTAMP NOT NULL ,
`headline` VARCHAR( 50 ) NOT NULL ,
`bodytext`
TEXT NOT NULL ,
`uri` VARCHAR( 60 ) NOT NULL
) ENGINE = MYISAM ;
The PHP code to install
database table
The statement include_once points to my database connector
that includes all the security settings.
createrssfeed.php
<?php
include_once (‘dbsettings.php’)
$sql = 'CREATE TABLE `rssfeed` ('
. ' `rssId`
TINYINT(18) NOT NULL AUTO_INCREMENT PRIMARY KEY COMMENT \'Id of feed\', '
. '
`createdate` TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL, '
. ' `headline`
VARCHAR(50) NOT NULL, '
. ' `bodytext` TEXT NOT NULL, '
. ' `uri`
VARCHAR(60) NOT NULL'
. ' )'
. ' ENGINE = myisam;';
$result=connect_db($sql);
?>
“dbsettings.php”
<?php
// Place in your connection php file
$DATABASEHOST=’localhost’;
$DATABASEUSER= ‘SomeUser’;
$DATABASEPASSWD=’mypassword’;
$DATABASENAME=’mydatabase’;
//generic database handler
function
connect_db ($sql)
{
if(isset($result))
{
mysql_free_result($result);
}
if(empty($cnn))
{
$cnn=@mysql_connect($DATABASEHOST,$DATABASEUSER,$DATABASEPASSWD);
if(!$cnn)
{
die('error message:' .mysql_error());
}
}
mysql_select_db($DATABASENAME);
if($result=mysql_query($sql,$cnn))
{
return $result;
}else
echo ('error message:' .mysql_error());
return
false;
}
?>
We now should have a table for our `rssfeed`. If
you ran this createfeed.php on a public server delete the file from the server
to avoid running it again of extend the file to do security checks to avoid
others from running the script. You only need this create feed once to create
the table.
You can now insert some records into your table.
The SQL
For this is
INSERT INTO `rssfeed` ( `rssId` , `createdate` , `headline` , `bodytext`
, `uri` )
VALUES (
NULL , NOW( ) , 'Chrisos Great Poker Night', 'Chrisos
is having a poker night on Thursday all welcome if you bring some beer.',
'http://www.somewhere.com'
), (
NULL , NOW( ) , 'Free beer at Chrisos on
friday', 'Chrisos is giving away free beer on Friday until stock runs out. Those
who where not their Thursday for the poker night are invited.',
'http://www.somewhere.com'
);
The PHP Code.
insertrecordstorss.php
<?php
include_once(‘db.php’);
$sql =
'INSERT INTO `rssfeed` (`rssId`, `createdate`, `headline`, `bodytext`, `uri`)
VALUES (NULL, NOW(), \'Chriso Great Poker Night\', \'Chriso is having a poker
night on Thursday all welcome if you bring some beer.\',
\'http://www.somewhere.com\'), (NULL, NOW(), \'Free beer at Chriso on friday\',
\'Chriso is giving away free beer on friday until stock runs out. Those who
where not their Thursday for the poker night are invited.\',
\'http://www.somewhere.com\');';
$result=connect_db($sql);
?>
You could merger the two scripts together and call this once but for the
purpose of the article I have done this is steps.
So we now have 2
records in the rssfeed table and ready to build our application.
So while
still working with PHP we need one more file that will act as our rss server.
The purpose of this file is to return an xml document from the server.
Create a file rssserver.php and call it from your PHP server and if you get an
xml document everything is fine.
‘rssserver.php’
<?php
ob_start();
header('Content-Type: text/xml');
header("Cache-Control: no-cache,
must-revalidate");
//A date in the past
header("Expires: Mon, 26 Jul 1997
05:00:00 GMT");
// Above must be the first thing in the file to create a xml
header
// Declare as xml
echo '<?xml version="1.0"
encoding="ISO-8859-1"?>';
include_once('db.php');
// Get the
records for today
$sql = 'SELECT * FROM `rssfeed`';
$result=connect_db($sql);
// error handler
if (!$result)
{
// note the xml element tags here
die ('<rssfeed>< errormessage >ERROR: Server Error Getting Feed From MySql</
errormessage ><logedin>0</logedin></rssfeed>');
exit;
}
// you have
a result
// function in db.php
echo createXmlFromResult($result,’rss’);
exit;
// Parse a dbresult to the function to get xml doc return
function createXmlFromResult($dbresult, $tablename)
{
$str='';
if($dbresult)
{
if ($count=mysql_num_rows($dbresult)>0)
{
// $str="<" .
mysql_field_table($dbresult) .">";
while($row = mysql_fetch_array($dbresult))
{
$str="<" . $tablename .">";
$a=mysql_num_fields($dbresult);
for
($i=0; $i<=($a-1); $i++)
{
$str= $str .'<' . mysql_field_name($dbresult,
$i) .'>'.checkfieldfornull($row[$i])
.'</'.mysql_field_name($dbresult,$i).'>';
//
}//end for
$str=$str .'</' . $tablename .'>';
}//end while
}
//end if count
}
return $str;
}?>
There is one line missing here
and that’s the namespace has not been declared. I will come back to this later
as vs2008 has a neet way to get this right.
So appart from that we are
all set up to create a client for our feed.
So we need a Silverlight
Application consume the xml file. As I said before the documented methods failed
in my case. So I need another way.
Silverlight Client
.Start a new app SilverlightRss
When ask
select Dynamic Web Page for this application.
You can make a new control
or just use Page.xaml
For this I using page.xaml
You can do this in
Vs2008 or Expression Blend. Because of the simplicity of this control I will use
Vs2008.
Lets change a few items. First lets change the size of the page
control to Width="300" Height="250"
I myself don’t like the grid control
so I use canvas but this is up to you.
<Canvas x:Name="LayoutRoot"
Background="White">
</Canvas>
I now add an image, rectangle and a
textbox. The image is the rss logo file, the textbox is to display RSS, and the
rectangle is for a background
<Image Source="icon_rss.png" Canvas.Left="245"
Canvas.ZIndex="2"></Image>
<TextBlock Text="RSS" Canvas.Left="270" Canvas.Top="3"
Foreground="Blue" Canvas.ZIndex="3"></TextBlock>
<Rectangle Height="30"
Width="300" Canvas.ZIndex="1"/>
Last thing I need is a container to hold
my feed.
I am going to use a Stackpanel for this and call it lbRSS.
<StackPanel x:Name="spRSS" Height="220" Canvas.Top="30" Canvas.Left="0"
Width="600"
MaxWidth="600">
</StackPanel>
That’s it the control is
built.
Building a class
to manage the feed
The first class we need is Rss class.
In your project create a class Rss.vb.
You need to
create some fields for the class
rssId
createdate
headline
bodytext
uri
rss.vb code
‘Imports
Imports
System.Xml.Serialization
'Note you may need to set a reference to
'System.Xml.Serialization
'now declare as xml type by adding the declartion to the class
<XmlType()>
_
Public Class rss
'declare some fields that match our database as its
'xml been returned the field can be strings in this
'case. You can have
complex types but that’s
'another subject.
Public rssId As String
Public createdate As String
Public headline As String
Public bodytext As
String
Public uri As String
End Class
<XmlType()> _
Public Class
RssMessages
Inherits List(Of rss)
Sub New()
End Sub
End Class
That’s it. We will use this class to bind to our Rssfeed control later in the
artical.
Save your work and test it by runing the f5 to debug
Create a serialiser
I now have a simple
console application to serlialise our rss
class.
Create a new VB console application in Vs2008.
Call it
MySerialiser.
Now in Solution Explorer import an excisting Item into
MySerialiser. Browse for your Rss.vb File.
Now your imports, you will
need these 3 references
Here is the code.
Imports System.Xml
Imports System.IO
Imports System.Xml.Serialization
Module Module1
Sub Main()
' call the method
serialise()
End Sub
Private Sub
serialise()
'Declare as RssMessage Instance
Dim MyRssMessages As
RssMessages = New RssMessages
'Add some data to the MyRssMessages
Dim
msg As Rss
For i As Integer = 1 To 6
msg = New Rss
msg.rssId = i
msg.headline = "This is the number " & i & " I have done this"
msg.createdate
= Now().ToString
msg.bodytext = " This is the body text of the number” & i &
“ headline"
msg.uri = "http://home.people.net.au/~chriso/rss/index.php"
MyRssMessages.Add(msg)
Next
' Insert code to set properties and fields
of the object.
Dim mySerializer As XmlSerializer = New XmlSerializer(GetType(RssMessages))
' To write to a file, create a StreamWriter object.
Dim myWriter As
StreamWriter = New StreamWriter("rss.xml")
mySerializer.Serialize(myWriter,
MyRssMessages)
Console.Write(myWriter.ToString())
myWriter.Close()
End Sub
End Module
Pres f5 to Run this code and it will create a
xml file for you.
Here is the xml file rss.xml
<?xml version="1.0"
encoding="utf-8"?>
<RssMessages xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<rss>
<rssId>1</rssId>
<createdate>29/08/2008
8:40:20 AM</createdate>
<headline>This is the number 1 I have done
this</headline>
<bodytext> This is the body text of the number1 headline</bodytext>
<uri>http://home.people.net.au/~chriso/rss/index.php</uri>
</rss>
<rss>
<rssId>2</rssId>
<createdate>29/08/2008 8:40:20 AM</createdate>
<headline>This is the number 2 I have done this</headline>
<bodytext> This is
the body text of the number2 headline</bodytext>
<uri>http://home.people.net.au/~chriso/rss/index.php</uri>
</rss>
<rss>
<rssId>3</rssId>
<createdate>29/08/2008 8:40:20 AM</createdate>
<headline>This is the number 3 I have done this</headline>
<bodytext> This is
the body text of the number3 headline</bodytext>
<uri>http://home.people.net.au/~chriso/rss/index.php</uri>
</rss>
<rss>
<rssId>4</rssId>
<createdate>29/08/2008 8:40:20 AM</createdate>
<headline>This is the number 4 I have done this</headline>
<bodytext> This is
the body text of the number4 headline</bodytext>
<uri>http://home.people.net.au/~chriso/rss/index.php</uri>
</rss>
<rss>
<rssId>5</rssId>
<createdate>29/08/2008 8:40:20 AM</createdate>
<headline>This is the number 5 I have done this</headline>
<bodytext> This is
the body text of the number5 headline</bodytext>
<uri>http://home.people.net.au/~chriso/rss/index.php</uri>
</rss>
<rss>
<rssId>6</rssId>
<createdate>29/08/2008 8:40:20 AM</createdate>
<headline>This is the number 6 I have done this</headline>
<bodytext> This is
the body text of the number6 headline</bodytext>
<uri>http://home.people.net.au/~chriso/rss/index.php</uri>
</rss>
</RssMessages>
Now you have a test file for your Silverlight
Rss Control
Now here is the namespace you need for your php file.
<RssMessages
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
You will need to modify rssserver.php
After
// Declare as
xml
echo '<?xml version="1.0" encoding="ISO-8859-1"?>';
//Insert this
to send the namespace
echo ‘<RssMessages xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">’
//and before here
include_once('db.php');
You can see that the namespace is RssMessages the
name of our class.
PHP Error Handling
Now we all know that computers are not the most relaible thing on earth and things do go wrong. I aways say:
quote If we made it then it will break.
So if it breaks what do we do.
Well those thieves from the insuance company know about this. Prepare for
the worst.
PHP like other codes can break.
How does silverlight
know when it breaks? Simple, format the error so that its in our xml format.
So when we write code in PHP to handle a error then exit like using die
function we must close the xml tag with </RssMessages>
$result=connect_db($sql);
// error handler
if (!$result)
{
// note the xml element tags here
die ('<errormessage>ERROR: Server Error Getting Feed From MySql</errormessage>
</RssMessages>');
exit;
}
Now we know our namespace we need to
change line 22 of our rssserver.php file from this
die ('<rssfeed><
errormessage >ERROR: Server Error Getting Feed From MySql</ errormessage ><logedin>0</logedin></rssfeed>');
To This.
die ('<errormessage>ERROR: Server Error Getting Feed From MySql</errormessage>
</RssMessages>');
And on the very last line before the program exits you
will need to add this line
//Closes the xml document
echo '<rssMessages>';
So now the server is complete and ready to serve our feed. GREAT MATE!!!!
So Far
So far we have a database, an install script,
a test script and a RSS server.
We also have a RSS control that does not do anything, Rss
class that’s lonely, a useful tool to create xml documents from our class.
Nearly forgot the xml file to runs some test with ‘Rss.xml’.
Check List:
createrssfeed.php (For creating database)
db.php (database connector)
rssserver.php (our RSS server)
In our SillverlightRss Project We Have
Page.Xaml
Page.Xaml.vb
App.xaml
App.xaml.vb
Rss.vb
Our
console application we have
Module.vb
Rss.vb
Tie it all together
in a tight knot
Doing some JavaScript
Open your SilverlightRss
Project.
Add a new item myrss.js JavaScript file.
Add this to the file
to create an Ajax request.
//////////////////////////////////////////////////////////
//ajax Request
//Creates a request object pending browser platform
//////////////////////////////////////////////////////////
function
ajaxRequest()
{
var activexmodes=["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"]
//activeX versions to check for in IE
if (window.ActiveXObject)
{
//Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is
broken)
for (var i=0; i<activexmodes.length; i++){
try{
return new
ActiveXObject(activexmodes[i])
}
catch(e){
//suppress error
}
}
}
else if (window.XMLHttpRequest)
// if Mozilla, Safari etc
return new
XMLHttpRequest()
else
return false
}
// to hold the request
var
myrequest;
//Now we need a method for Silverlight to call and //some data
from our server.
////////////////////////
//Generic Call to server
//data array Parameters, pagename is the name //serverfile to call
/////////////////////////
function genericCall(data)
{
//return
"This is from login";
var path=data(0);
// var path="games.xml"
// var
slctl=document.getElementById("silverlightControlHost").getHost();
var
myrequest=new ajaxRequest()
myrequest.open("POST", path, true)
myrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
myrequest.send(encodeURI(data))
//
if (myrequest.overrideMimeType)
myrequest.overrideMimeType('text/xml')
myrequest.onreadystatechange=function(){
if (myrequest.readyState==4){
if (myrequest.status==200){
var txt=myrequest.responseText;
sl.Content.mySLRssapp.ResponseText=txt;
}
else{
alert("<error>An
error has occured making the request<error>");
}
}
}
}
////////////////////////
//Sets a reference to silverlight host
///////////////////////
var sl;
function silverlightLoaded(sender)
{
sl=sender.getHost();
}
//end myrss.js
///////////////////////////////////////////////////
Ok so we now have
JavaScript file communicating with the server. Later we will reference this in
our html file. I add the javascript Silverlight error handler to this file for
ease of use but you can leave it in the html document.
What now? !!! This
still cannot work.
Some VB
Well I thought of that and decided that we
need to do more work with our SilverlightRss app.
What came first? The
Chicken or the Egg?
Well let’s create a request to get the data and then
handle the response.
However first the Egg or was that the chicken.
We
need a new class to manage the data and make a request.
Create a new
class and name it RssHandler.
Import the following assemblies. You may
need to set references for System.Windows.Browser
Imports System
Imports System.IO
Imports System.Text
Imports System.Xml
Imports
System.Threading
Imports System.Xml.Serialization
Imports
System.Windows.Browser
Add a few properties
‘This will accept the text
returned from the server
Private m_ResponseText As String
Public Property
ResponseText() As String
Get
Return m_ResponseText
End Get
Set(ByVal
value As String)
m_ResponseText = value
If m_ResponseText.Length > 0
Then
'we got something
CreateFromResponseText()
End If
End Set
End Property
‘Add the method
Private Sub CreateFromResponseText()
End Sub
‘We need more Properties before we write the method
''' <summary>
''' Stores an instance of RssMessages from the Response
''' </summary>
'''
<remarks>Use this to populate your control</remarks>
Private m_Messages As
New RssMessages
Public ReadOnly Property Messages() As RssMessages
Get
Return m_Messages
End Get
End Property
''' <summary>
''' Informs
yo if we succeded with the request and created a valid RssMessage Object
'''
</summary>
''' <remarks>Used to validate the request</remarks>
Private
m_Valid As Boolean
Public ReadOnly Property Valid() As Boolean
Get
Return m_Valid
End Get
End Property
''' <summary>
''' Informs you
that there has been a response recieved
''' </summary>
''' <remarks>Could
create an event for this but there is a chance of an endles loop of
errors</remarks>
Private m_ResponseRecieved As Boolean
Public ReadOnly
Property ResponseRecieved() As Boolean
Get
Return m_ResponseRecieved
End Get
End Property
''' <summary>
''' Stores the errors if any.
'''
(Programers view and a testers nightmare.)
''' </summary>
'''
<remarks>Server side error are in the rssmessage object </remarks>
Private
m_ErrorMessages As List(Of String)
Public ReadOnly Property ErrorMessages()
As List(Of String)
Get
Return m_ErrorMessages
End Get
End Property
RequestRssFeed
Our Class will have two methods. One to handle the request
the other to handle the response.
‘Method 1 Request
''' <summary>
''' Makes a request to the server though javascript
''' </summary>
''' <param
name="Data">String Array of Parameters for the requsest. Data Sent to server in
the POST</param>
''' <remarks></remarks>
Public Sub RequestRssFeed(ByVal
Data() As String)
Try
' you cannot run it under debug
' this will stop
you
If Not System.Diagnostics.Debugger.IsAttached Then
HtmlPage.Document.Invoke("genericCall", Data)
'genericCall is the JavaScript
Method
End If
Catch ex As Exception
ErrorMessages.Add("RequestRssFeed
Error: " & ex.Message & " Trace:" & ex.StackTrace
End Try
End Sub
Respond To Request
Replace the method CreateFromResponseText we created
earlier place this code.
<summary>
''' Processes the data from the
response text recieved from the our javascript
''' </summary>
'''
<remarks></remarks>
Private Sub CreateFromResponseText()
'clear the
message bank
m_ErrorMessages.Clear()
'set Valid to false
m_Valid =
False
'create a string reader with the response text
Dim sr As New
StringReader(ResponseText)
Dim reader As XmlReader = XmlReader.Create(sr)
'Create a serialiser
Dim serializer As New XmlSerializer(GetType(RssMessages))
'If we are any good at this we should have a list of messages from the server
Try
m_Messages = CType(serializer.Deserialize(reader), RssMessages)
m_Valid = True
'Response Recievied and done
m_ResponseRecieved = True
'And if we are no good handle the error
Catch ex As Exception
m_Valid =
False
ErrorMessages.Add("CreateFromResponseText Failed. " & ex.Message & "
Trace: " & ex.StackTrace)
End Try
End Sub
Fantastic Effort. Cannot
go to bed yet as this is almost happening for you. We have two more jobs todo.
1.Wire up the JavaScript Response
2.Bind The Data to our SilverlightRss
Control
Wire Up JavaScript
As far as I know you have to do this in
app.xaml.vb as I have tried in other files without success. But it took a few
goes to get it to work this way.
For those of you who type the code from
this page may well remember in the javascript method stateChanged we had a line
Javascript code
{
sl.Content.mySLRssapp.ResponseText=myrequest.responseText;
}
sl.content is your host Silverlight Control.
mySLRssapp is an alais
to an instance SilverlightRss.RssHandler
ResponseText is a property of
our instance of RssHandler
In your App.xaml.vb file import.
Imports System.Windows.Browser
Declare a RssHandle Just after Inherits
Application
Public MyRssHandler As New RssHandler
This creates the
instance
In Application_Startup place these line after Me.RootVisual =
New Page()
‘vb code
'Avoids problems running in the debugger
If Not
System.Diagnostics.Debugger.IsAttached Then
HtmlPage.RegisterScriptableObject("mySLRssapp",
MyRssHandler)
End If
‘cut here
Well Done Guys and Girls. But
just before you leave I have one last task for you to do.
Place the data
into our control
It is now only a case of referencing myapp. MyRssHandler
to use the client server
Ok Open page.xaml.vb
Here are your china
men. Sorry Imports!
Imports System.Windows.Threading
Imports
System.Windows.Controls
‘Create a timer for our feed
After
Inherits UserControl
‘The time is used to provide a checking system to see if
there is any data
WithEvents timer As New DispatcherTimer
Dim rssData As
RssHandler
Now we need two sub methods to handle our feed.
StartTimer
Timer_tick Event
StartTimer method
Sub
StartTimer()
'get as reference to app
Dim myapp As App = TryCast(App.Current,
App)
' get a reference to the handler
RssData = myapp.MyRssHandler
'setup the timer give it time to get a response
'This is set to 2 seconds.
adjust to your liking
timer.Interval = New TimeSpan(0, 0, 2)
'call the
request
'Create a String array
'if you had a query for the server you
would add
'?varname=value&varname2=value to the data array as the next
element
‘example: Dim data() as string={"filename=rssserver.php",”?varname=value&varname2=value”
}
Dim data() As String = {"filename=rssserver.php"}
'This gets it running
‘Call the method we created earlier in RssHandler
RssData.RequestRssFeed(data)
'Start the timer
timer.Start()
End Sub
This is Strait forward
so far. Next thing to do is handle the tick event for the timer and grab our
data.
timer_Tick Event
The timer_Tick event handles the data from the
RssHandler Class
First we check the flags to see if we came home with the
goods.
ResponseRecieved Flag tells us that we got a response from the
server. If that passed then we need to know if the data was valid. Checking the
Valid Flag tells us this.
Both test have passed we can the enumerate the
Messages (RssMessages Class) and fill the controls
When the both codition
fail the TimerCounter increments to 6 and finaly stops.
We then check the
messages to see if we had a client side error.
Note that the server side
error will be in the message and if you do not have messages then you can not
find the server error. Another night of no sleep.
There is an error
raised with uri class if you don’t pass a valid url so we need to test before we
add it to the HyperlinkButton.
'TimerCounter is used to trap an
endless loop
Dim TimerCounter As Integer
''' <summary>
''' Event when
timer fires
''' </summary>
''' <param name="sender">timer</param>
''' <param
name="e"></param>
''' <remarks></remarks>
Private Sub timer_Tick(ByVal
sender As Object, ByVal e As System.EventArgs) Handles timer.Tick
'Declare a
HyperLink Button and as TextBox
Dim hyperlink As HyperlinkButton
Dim tbox
As TextBox
'look to see if we got a response
If
RssData.ResponseRecieved Then
' if we have then is it valid
If
RssData.Valid Then
'Your a winner
'bind to control
'enumerate the
messages
For Each msg As rss In RssData.Messages
'Create a new
HyperlinkButton
hyperlink = New HyperlinkButton
'Make the headline its
content
hyperlink.Content = msg.headline
'adjust the font sise
hyperlink.FontSize = 12
'Add the uri
'Ensure we have a URL else this will
fail
If Not msg.uri Is Nothing Then
hyperlink.NavigateUri = New
Uri(msg.uri)
End If
'Add the HyperlinkButton to the ListBox Control
lbRSS.Items.Add(hyperlink)
'Create a new TextBox
tbox = New TextBox
tbox.TextWrapping = TextWrapping.Wrap
'Add the Text Body
tbox.Text =
msg.bodytext
'Add it to the control
lbRSS.Items.Add(tbox)
'should work
Next
Else
'look at errors
If RssData.ErrorMessages.Count > 0 Then
'we logged some errors
For Each StringErr As String In RssData.ErrorMessages
'not goo practice live to show user your errors but
'for the purpose this
will do
' you could write a debug condition here but I am tired
tbox =
New TextBox
tbox.TextWrapping = TextWrapping.Wrap
tbox.Text = StringErr
'Add to your list box
lbRSS.Items.Add(tbox)
Next
End If
End
If
Else
'Still waiting
'Add 1 to counter to prevent endless loops of
the timer
TimerCounter += 1
'Stop after 12 seconds. Again you can adjst to
your liking
'Realy its timer.Intervals X 6
If TimerCounter = 6 Then
timer.Stop()
'We stop the time so there could be errors
'See if there are
errors
If RssData.ErrorMessages.Count > 0 Then
'we logged some errors
For Each StringErr As String In RssData.ErrorMessages
'not goo practice live
to show user your errors but
'for the purpose this will do
' you could
write a debug condition here but I am very tired
tbox = New TextBox
tbox.TextWrapping = TextWrapping.Wrap
tbox.Text = StringErr
'Add to
listbox
lbRSS.Items.Add(tbox)
Next
End If
End If
End If
End Sub
So all go from here mate! Nearly time to feed the cat.
Are We There Yet?
No we are not there yet. One last thing to do is to get
Silverlight to listen for the response from the server, “Or JavaScript I don’t
know anymore”
Oh Yea. Upload the files to your server after testing of
course dur!
Here is a variable ‘or use to variable now called field’ to
help you debug the application. This worked on my old box so it should work on
your flash new one.
For those who type out the code in this article I
suggest that you copy and paste this into your RssHandler Class to avoid further
errors.
Dim xmlstring As String = "<?xml version='1.0'
encoding='utf-8'?>" _
& "<RssMessages xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xmlns:xsd='http://www.w3.org/2001/XMLSchema'>" _
& "<rss>" _
& "<rssId>1</rssId>"
_
& "<createdate>29/08/2008 8:40:20 AM</createdate>" _
& "<headline>This
is the number 1 I have done this</headline>" _
& "<bodytext> This is the body
text of the number1 headline</bodytext>" _
& "<uri>http://home.people.net.au/~chriso/rss/index.php</uri>"
_
& "</rss>" _
& "<rss>" _
& "<rssId>1</rssId>" _
& "<createdate>29/08/2008
8:40:20 AM</createdate>" _
& "<headline>This is the number 1 I have done
this</headline>" _
& "<bodytext> This is the body text of the number1
headline</bodytext>" _
& "<uri>http://home.people.net.au/~chriso/rss/index.php</uri>"
_
& "</rss>" _
& "<rss>" _
& "<rssId>1</rssId>" _
& "<createdate>29/08/2008
8:40:20 AM</createdate>" _
& "<headline>This is the number 1 I have done
this</headline>" _
& "<bodytext> This is the body text of the number1
headline</bodytext>" _
& "<uri>http://home.people.net.au/~chriso/rss/index.php</uri>"
_
& "</rss>" _
& "</RssMessages>"
To use the variable you need to
modify your RequestRssFeed Method of RssClass
If Not
System.Diagnostics.Debugger.IsAttached Then
HtmlPage.Document.Invoke("genericCall",
Data)
'genericCall is the JavaScript Method
‘Modified for test purposes
‘adds local xml to the application
Else
'Just Prentend that we have
data
ResponseText = xmlstring
End If
Now is the time to see the
winners and the loosers.
Press f5 hold your breath and wait.
Kool
Bananas. It tested ok.
Create your HTML page for the app and set a
reference to your myrss.js file in the script tags.
<script type="text/javascript"
src="myrss.js">
</script>
Uplaod your files to the server and run your
php files in the browser to make sure we done it right.
First run
Createrssfeed.php .
Check your database to see if we have the rss table.
Run insertrecordstorss.php to put some records in the table
Run
rssserver.php to test your xml file. You should see xml rendered in your
browser. If it has the same files as your class then you have got it right
again.
That’s it.. Bed time.. you now have a rss for silverlight using
cross platform technology.
Sorry if your not asleep yet but I need to
inform you that this is demo software and no warranties or liabilty claims
accepted. Run at your own Risk.
One more thing before you go. With this
knowledge you could build a client that enters data into your database with
little or no more code than an UI for this and the two methods in Page.xaml.vb
StartTimer and timer_Tick
I Hope you follow the Ausie humor and accent
ok. Thank you for taking the time to read to here.
Good Luck
Chriso
daddysgreat@hotmail.com
No comments:
Post a Comment