Silverlight Help


  • Silverlight 3 Could Not download the silverlight Application

    I created a simple Silverlight 3 app.

     

    <UserControl x:Class="SilverlightApplication2.MainPage"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480">
        <Grid x:Name="LayoutRoot">
            <TextBlock Text="Hello World!" ></TextBlock>
        </Grid>
    </UserControl>

     

    When I run it I get this error

    image

    Line: 56
    Error: Unhandled Error in Silverlight Application
    Code: 2104   
    Category: InitializeError      
    Message: Could not download the Silverlight application. Check web server settings   

     

    Well if you look in the ClientBin folder you will see it is empty so the xap file is not available to be used

     

    To fix this right click on the web application and select Build Order.  On the Dependencies tab make sure the Checkbox next to the Silverlight app is checked.

    image

    Full story

    Comments (16)

  • John Papa speaking at Space Coast .Net

    John Papa - Ado.Net Data Services

    6/17/2009 6:30:00 PM

    6/17/2009 8:00:00 PM

    About

    jp2

    John Papa is a Microsoft C# MVP, INETA speaker, member of the WPF and Silverlight Insiders, consultant, speaker, author, and trainer for ASPSOFT who specializes in professional application development with Microsoft technologies including Silverlight, WPF, C#, .NET and SQL Server. John has written over 70 articles and authored 9 books including his latest book Data Driven Services with Silverlight 2 by O’Reilly Media. John is currently working on a follow up to his Silverlight book, with a working title of Silverlight for Business.

    He can often be found speaking at industry conferences such as MIXVSLive and DevConnections, speaking at user groups around the country, and viewed on MSDN Web Casts. John also spearheaded the 1st annual Silverlight MIXer, a gathering of some of the most influential members of the Silverlight community for a great night a MIX09. You can always find John at johnpapa.net.

    John Papa will be showing Astoria using Silverlight 3 beta as the client.

    ADO.NET Data Services (codenamed Astoria) exposes entity models through RESTful services. It can dramatically simplify the code required to expose business objects through web services and reduce a tremendous amount of code. This session will show how to expose entity models using ADO.NET Data Services, how to consume and save data, and how to debug the communications using various tools. When the technology does not quite do what you need out of the box, it also allows for customizations to create custom service operations, intercept queries, and enforce permissions. Attendees will walk away with an understanding of the capabilities of ADO.NET Data Services, how to use them with Silverlight, and when and where it is ideal to use in an application architecture and when there are better options.

    Street: 8045 N. Wickham Road
    City: melbourne
    Country: USA
    State: Florida

    Full story

    Comments (0)

  • 2009 Orlando Code Camp

    I attended and spoke at the 2009 Orlando Code Camp today.  Thanks Jessica and Fabio for doing such a great job organizing the code camp.  There were some really great speakers there today.  There was some great silverlight content at todays code camp

    http://www.orlandocodecamp.com/

     

    You can download the slides and sample code from my Silverlight 2 Databinding presentation here

    http://www.silverlight-help.com/Libraries/Downloads/Silverlight_DataBinding.sflb.ashx?download=true

     

    Full story

    Comments (2838)

  • Formatting bound data in Silverlight 2

    To format a bound item you need to use a class that implements the IValueConverter interface.

     

    First lets create a simple class to bind to

     

       public class BindTo : INotifyPropertyChanged
        {
            public event PropertyChangedEventHandler PropertyChanged;
    
            private void NotifyPropertyChanged(String info)
            {
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs(info));
                }
            }
    
            private string _Name;
            public string Name
            {
                get
                {
                    return _Name;
                }
                set
                {
                    if (value != _Name)
                    {
                        _Name = value;
                        NotifyPropertyChanged("Name");
                    }
                }
            }
    
            private double _Price;
            public double Price
            {
                get
                {
                    return _Price;
                }
                set
                {
                    if (value != _Price)
                    {
                        _Price = value;
                        NotifyPropertyChanged("Price");
                    }
                }
            }
    
        }

     

    Now lets create the IValueConverter to display the price as currency. The convert has 2 functions we must implement  Convert and ConvertBack. In covert we will convert the decimal to a string.  In the convertBack we will remove the $ so the text can be converted to a decimal

    using System;
    using System.Net;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Documents;
    using System.Windows.Ink;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Animation;
    using System.Windows.Shapes;
    using System.Windows.Data;
    using System.Globalization;
    
    namespace SilverlightApplication8
    {
        public class CurrencyConverter : IValueConverter
        {
            public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
            {
                double d;
                if (double.TryParse(value.ToString(), out d))
                {
                    if (d >= 0.0)
                    {
                        return d.ToString("c");
                    }
                }
                return value;
            }
    
            public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
            {
                double d;
                string s = value.ToString();
                if (s.StartsWith("$"))
                {
                    s = s.Substring(1);
                }
                if (double.TryParse(s, out d))
                {
                    return d;
                }
                return value;
            }
        }
    
    }
    

     

    To use an IValueConverter we need to register it as a StaticResource for the page

     

        <UserControl.Resources>
            <local:CurrencyConverter x:Key="MyConverter"></local:CurrencyConverter>
        </UserControl.Resources>

     

    In the binding we can specify the converter

            <TextBox Text="{Binding Price, Mode=TwoWay, Converter={StaticResource MyConverter}, NotifyOnValidationError=true,  ValidatesOnExceptions=true}" Grid.Column="1" Grid.Row="1" Margin="5,5,5,120"></TextBox>

    Pages complete xaml

    <UserControl x:Class="SilverlightApplication8.Page"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
        xmlns:local="clr-namespace:SilverlightApplication8"
        Width="400" Height="300">
        <UserControl.Resources>
            <local:CurrencyConverter x:Key="MyConverter"></local:CurrencyConverter>
        </UserControl.Resources>
        <Grid x:Name="LayoutRoot" Background="White">
            <Grid.ColumnDefinitions>
                <ColumnDefinition></ColumnDefinition>
                <ColumnDefinition></ColumnDefinition>
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition></RowDefinition>
                <RowDefinition></RowDefinition>
            </Grid.RowDefinitions>
            <TextBlock Text="Product Name" Grid.Column="0" Grid.Row="0"></TextBlock>
            <TextBlock Text="Unit Price" Grid.Column="0" Grid.Row="1"></TextBlock>
            <TextBox Text="{Binding Name, Mode=TwoWay}" Grid.Column="1" Grid.Row="0" Margin="5,5,5,120"></TextBox>
            <TextBox Text="{Binding Price, Mode=TwoWay, Converter={StaticResource MyConverter}, NotifyOnValidationError=true,  ValidatesOnExceptions=true}" Grid.Column="1" Grid.Row="1" Margin="5,5,5,120"></TextBox>
        </Grid>
    </UserControl>

     

    Here is the code for page which creates the object and binds it

     

        public partial class Page : UserControl
        {
            BindTo b = new BindTo();
    
            public Page()
            {
                InitializeComponent();
                this.Loaded += new RoutedEventHandler(Page_Loaded);
            }
    
            void Page_Loaded(object sender, RoutedEventArgs e)
            {
                b.Name="Apple Juice";
                b.Price = 1.39;
                LayoutRoot.DataContext = b;
            }
        }

    Full story

    Comments (2)

  • Microsoft Patterns & Practices’ Composite Application Guidance for WPF and Silverlight now in VB.NET!

    The Patterns and Practices team has released VB versions of the Quick Starts, Hands on Labs, and How to Topics. You can download them here

     

    http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=537da1cd-43e1-4799-88e7-a1da9166fb46

    Full story

    Comments (1)

  • Rendering problems with IE8

    Microsoft released IE8 during Mix 2009.  Microsoft spent a lot of time making IE8 comply with the browser standards.  When you upgrade your browser to IE8 if you find the web site does not render right.  Do not worry there is a simple fix for this. 

     

    There is a tag you can place in the Head section of your webpage which will force IE8 into IE7 compatibility mode.

     

    <html>
    <head>
      <!-- Mimic Internet Explorer 7 -->
      <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
      <title>My Web Page</title>
    </head>
    
    

     

     


    For more info on IE8 compatibility read this article

    http://msdn.microsoft.com/en-us/library/cc288325(VS.85).aspx

     

    Hope this helps

    Full story

    Comments (2)

  • Silverlight 2.0 Interacting with html

    With SilverLight 2.0 you can interact and handle events with the html elements on your page.  Here is a simple example that places a select (drop down control) on a web page which will change the color of a ellipse on a SilverLight app.  So lets start with the html

     

    <body style="height: 100%; margin: 0;"> 
        <form id="form1" runat="server" style="height: 100%;"> 
        <asp:ScriptManager ID="ScriptManager1" runat="server"> 
        </asp:ScriptManager> 
        <br /> 
        <span>Select a Color </span> 
        <select id="ddColor"> 
            <option>Red</option> 
            <option>Blue</option> 
            <option>Green</option> 
        </select> 
        <br /> 
        <br /> 
        <div style="height: 100%;"> 
            <asp:Silverlight ID="Xaml1" runat="server" Source="~/ClientBin/HtmlAndSilverlight.xap" 
                MinimumVersion="2.0.30923.0" Width="100%" Height="100%" /> 
        </div> 
        </form> 
    </body> 

     

     

    Now the XAML

     

    <body style="height: 100%; margin: 0;"> 
        <form id="form1" runat="server" style="height: 100%;"> 
        <asp:ScriptManager ID="ScriptManager1" runat="server"> 
        </asp:ScriptManager> 
        <br /> 
        <span>Select a Color </span> 
        <select id="ddColor"> 
            <option>Red</option> 
            <option>Blue</option> 
            <option>Green</option> 
        </select> 
        <br /> 
        <br /> 
        <div style="height: 100%;"> 
            <asp:Silverlight ID="Xaml1" runat="server" Source="~/ClientBin/HtmlAndSilverlight.xap" 
                MinimumVersion="2.0.30923.0" Width="100%" Height="100%" /> 
        </div> 
        </form> 
    </body> 

     

     

    Now build the app so we have intellisense for the controls.  Ok first off lets get access to the drop down (select) on the web page. Then we can use AttachEvent to handle the onchange event.   

     

    Dim cbo As HtmlElement 
    Private Sub Page_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded 
        cbo = HtmlPage.Document.GetElementById("ddColor") 
        cbo.AttachEvent("onchange", AddressOf ColorChanged) 
    End Sub 

     

    Once the user selects a color we will change the color of the ellipse.  Here is the complete code listing

     

    Imports System.Windows.Browser 
    
    Partial Public Class Page 
        Inherits UserControl 
    
        Public Sub New() 
            InitializeComponent() 
        End Sub 
        Dim cbo As HtmlElement 
        Private Sub Page_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded 
            cbo = HtmlPage.Document.GetElementById("ddColor") 
            cbo.AttachEvent("onchange", AddressOf ColorChanged) 
        End Sub 
    
        Private Sub ColorChanged(ByVal sender As Object, ByVal e As HtmlEventArgs) 
            Dim x = CInt(cbo.GetAttribute("selectedIndex").ToString) 
            Select Case x 
                Case 0 
                    el.Fill = New SolidColorBrush(Colors.Red) 
                Case 1 
                    el.Fill = New SolidColorBrush(Colors.Blue) 
                Case 2 
                    el.Fill = New SolidColorBrush(Colors.Green) 
            End Select 
        End Sub 
    End Class 
    

     

    Hope this helps

    Full story

    Comments (0)

  • Silverlight 2 GDR released

    This week Microsoft Release an GDR to silverlight 2 which included some minor fixes.

     

    Here is a list of the main changes in the GDR (build 2.0.40115.0):

    • Fixes problems that were caused by Silverlight and McAfee scanning tools interactions
    • UI automation stability fixes, including:
      • graceful failures when attempting to use features that require .NET Framework 3.0 or 3.5 on machines that do not have either framework installed
      • improved Tablet support
    • Fixes an issue that arises when Mac users customize their environment by removing Arial and Verdana fonts
    • Fixes a known issue with Isolated Storage IncreaseQuotaTo method (see this post for more information)

    The one fix which bothered me a lot is the graceful failures when attempting to use features that require .Net framework 3.0 or 3.5 on machines that do that nave either framework installed. Silverlight 2 has its own version of the .net framework why should it use .net 3.0 or 3.5 and of course the .net framework is not available for the mac.  Well after looking around some I found this in the comments on Tim Sneath's Blog

      " apologies - we could probably be clearer here on what this means. Essentially, this was a bug that could be triggered in certain situations where you were using the accessibility tools (e.g. magnifier) on Silverlight content on a machine without .NET Framework installed. In short, the bug was an accidental dependency that has now been removed." - Tim Sneath

      http://blogs.msdn.com/tims/archive/2009/02/18/silverlight-2-gdr1-now-available.aspx

    For More info on the Update please check out Tim Heuer's Blog entry

     http://timheuer.com/blog/archive/2009/02/19/silverlight-2-gets-minor-update-gdr1.aspx

    Full story

    Comments (0)

  • Silverlight 2 RC0 DataGrid CommittingEdit work around

    In Silverlight 2 Beta 2 DataGrid had a CommittingEdit event which was a great event to update the data in an ado.net dataservice.   Unfortunately this event was removed in the RC0 of the datagrid.  As a work around Jonathan Shen suggested using a template column and using the LostFocus event to update your dataservice data.

     

     

                    <data:DataGridTemplateColumn Header="Command">
                            <data:DataGridTemplateColumn.CellTemplate>
                                <DataTemplate>
                                    <TextBlock Text="{Binding FirstName}"></TextBlock>
                                </DataTemplate>
                            </data:DataGridTemplateColumn.CellTemplate>
                            <data:DataGridTemplateColumn.CellEditingTemplate>
                                <DataTemplate>
                                    <TextBox Text="{Binding FirstName}" LostFocus="TextBox_LostFocus"></TextBox>   //you can detect other events.
                                </DataTemplate>
                            </data:DataGridTemplateColumn.CellEditingTemplate>
                        </data:DataGridTemplateColumn> 

     

    Well this works fine but I don't want to have to define all my columns this way.  Sometimes it is nice to just let the datagrid autogenerate the columns. So I decided to use the DataGrid's PreparingCellForEdit to add the handler for the LostFocus event.  Couple of other things you need to do.  First Remove the old event handler so the event does not fire multiple times.  Second we need a variable to keep track of the item that was edited when the lost focus event is fired we will be on another record.

     

    Dim prod As Northwind.Products 
    
    Private Sub dgProducts_PreparingCellForEdit(ByVal sender As Object, ByVal e As System.Windows.Controls.DataGridPreparingCellForEditEventArgs) Handles dgProducts.PreparingCellForEdit
        RemoveHandler e.EditingElement.LostFocus, AddressOf Textbox_LostFocus
        AddHandler e.EditingElement.LostFocus, AddressOf Textbox_LostFocus
        prod = DirectCast(dgProducts.SelectedItem, Northwind.Products)
    End Sub 
    
    Friend Sub Textbox_LostFocus(ByVal sender As Object, ByVal e As EventArgs)
        proxy.UpdateObject(prod)
    End Sub 
    
    

     

    Here is the complete code

     

    Imports System.Collections.ObjectModel
    Imports System.Data.Services.Client
    Imports System.Diagnostics 
    
    Partial Public Class Page
        Inherits UserControl 
    
        Public Sub New()
            InitializeComponent()
        End Sub 
    
        Dim q As DataServiceQuery(Of Northwind.Products)
        Dim proxy As Northwind.NorthwindEntities 
    
        Private Sub Page_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
            Dim address = New Uri(Application.Current.Host.Source, "../WebDataService1.svc") 
    
            proxy = New Northwind.NorthwindEntities(address) 
    
            Dim qry = From p In proxy.Products Select p
            q = CType(qry, Global.System.Data.Services.Client.DataServiceQuery(Of Northwind.Products)) 
    
            q.BeginExecute(AddressOf ProductsLoaded, Nothing) 
    
        End Sub 
    
        Friend Sub ProductsLoaded(ByVal ar As System.IAsyncResult)
            Dim c = q.EndExecute(ar)
            Dim d As New ObservableCollection(Of Northwind.Products)
            For Each p In c
                d.Add(p)
            Next
            Dim GetOnRightThread As New SetTheDataSource(AddressOf SetDataSource)
            Dispatcher.BeginInvoke(GetOnRightThread, New Object() {d})
        End Sub 
    
        Delegate Sub SetTheDataSource(ByVal d As ObservableCollection(Of Northwind.Products)) 
    
        Friend Sub SetDataSource(ByVal d As ObservableCollection(Of Northwind.Products))
            dgProducts.ItemsSource = d
        End Sub 
    
        Dim prod As Northwind.Products 
    
        Private Sub dgProducts_PreparingCellForEdit(ByVal sender As Object, ByVal e As System.Windows.Controls.DataGridPreparingCellForEditEventArgs) Handles dgProducts.PreparingCellForEdit
            RemoveHandler e.EditingElement.LostFocus, AddressOf Textbox_LostFocus
            AddHandler e.EditingElement.LostFocus, AddressOf Textbox_LostFocus
            prod = DirectCast(dgProducts.SelectedItem, Northwind.Products)
        End Sub 
    
        Friend Sub Textbox_LostFocus(ByVal sender As Object, ByVal e As EventArgs)
            proxy.UpdateObject(prod)
        End Sub 
    
        Friend Sub SaveComplete(ByVal ar As System.IAsyncResult)
            proxy.EndSaveChanges(ar)
        End Sub 
    
        Private Sub btnSave_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnSave.Click
            proxy.BeginSaveChanges(AddressOf SaveComplete, Nothing)
        End Sub
    End Class 
    


    kick it on DotNetKicks.com

    Full story

    Comments (0)

  • Silverlight 2.0 Create a context menu

    Silverlight 2 does not come with a context menu control.  You could always handle the html document's oncontextmenu event and open a popcontrol to use as a context menu.  This sample should help you get started.

     

    <UserControl x:Class="SilverlightContextMenu.Page"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
        Width="400" Height="300">
        <Grid>
            <Rectangle x:Name="LayoutRoot" Fill ="Green" ></Rectangle >
            <Popup x:Name="menu">
                <StackPanel>
                    <Button x:Name="btnRed" Content="Red"></Button>
                    <Button x:Name="btnWhite" Content="White"></Button>
                    <Button x:Name="btnBlue" Content="Blue"></Button>
                </StackPanel>
            </Popup>
        </Grid>
    </UserControl>
    
    Imports System.Windows.Browser
    
    Partial Public Class Page
        Inherits UserControl
    
        Dim WithEvents cm As ContextMenuCatcher
    
        Public Sub New()
            InitializeComponent()
        End Sub
    
        Private Sub btnBlue_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnBlue.Click
            LayoutRoot.fill = New SolidColorBrush(Colors.Blue)
            menu.IsOpen = False
        End Sub
    
        Private Sub btnRed_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnRed.Click
            LayoutRoot.fill = New SolidColorBrush(Colors.Red)
            menu.IsOpen = False
        End Sub
    
        Private Sub btnWhite_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnWhite.Click
            LayoutRoot.fill = New SolidColorBrush(Colors.White)
            menu.IsOpen = False
        End Sub
    
        Private Sub Page_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
            cm = New ContextMenuCatcher(LayoutRoot)
            menu.IsOpen = False
        End Sub
    
        Private Sub cm_RightClick(ByVal sender As Object, ByVal e As RightClickEventArgs) Handles cm.RightClick
            menu.HorizontalOffset = e.AbsolutePoint.X
            menu.VerticalOffset = e.AbsolutePoint.Y
            menu.IsOpen = True
        End Sub
    
        Private Sub menu_MouseLeave(ByVal sender As Object, ByVal e As System.Windows.Input.MouseEventArgs) Handles menu.MouseLeave
            menu.IsOpen = False
        End Sub
    
    End Class
    
    Public Class ContextMenuCatcher
        Public Event RightClick(ByVal sender As Object, ByVal e As RightClickEventArgs)
        Dim ctrl As UIElement
    
        Public Sub New(ByVal c As UIElement)
            ctrl = c
    
            HtmlPage.Document.AttachEvent("oncontextmenu", AddressOf OnContextMenu)
        End Sub
    
        Private Sub OnContextMenu(ByVal sender As Object, ByVal e As HtmlEventArgs)
            System.Diagnostics.Debug.WriteLine(e.OffsetX.ToString)
            System.Diagnostics.Debug.WriteLine(e.OffsetY.ToString)
            Dim pt As New Point(e.OffsetX, e.OffsetY)
            e.PreventDefault()
            e.StopPropagation()
            RaiseEvent RightClick(Me, New RightClickEventArgs(ctrl, pt))
        End Sub
    
    End Class
    
    Public Class RightClickEventArgs
    
        Dim m_Source As UIElement
        Public Property Source() As UIElement
            Get
                Return m_Source
            End Get
            Set(ByVal value As UIElement)
                m_Source = value
            End Set
        End Property
    
        Dim m_RelativePoint As Point
        Public Property RelativePoint() As Point
            Get
                Return m_RelativePoint
            End Get
            Set(ByVal value As Point)
                m_RelativePoint = value
            End Set
        End Property
    
        Dim m_AbsolutePoint As Point
        Public Property AbsolutePoint() As Point
            Get
                Return m_AbsolutePoint
            End Get
            Set(ByVal value As Point)
                m_AbsolutePoint = value
            End Set
        End Property
    
        Friend Sub New(ByVal source As UIElement, ByVal absolutePoint As Point)
            Me.Source = source
            Me.AbsolutePoint = absolutePoint
            Me.RelativePoint = GetPosition(source)
        End Sub
    
        Public Function GetPosition(ByVal relativeTo As UIElement) As Point
            Dim transform As GeneralTransform = Application.Current.RootVisual.TransformToVisual(relativeTo)
            Return transform.Transform(AbsolutePoint)
        End Function
    End Class
     
    You also have to make the silverlight control windowless for this to work
    <asp:Silverlight ID="Xaml1" runat="server" Source="~/ClientBin/SilverlightContextMenu.xap" MinimumVersion="2.0.30923.0" Width="100%" Height="100%" Windowless="true" />

    Full story

    Comments (0)

  • Publishing a VB Silverlight 2 app which uses a WCF service

    Note this works with the released version of Silverlight 2

     

    I created a Silverlight 2 app which uses a WCF Silverlight service which worked fine localy but did call the service when I published it to my web host.  After playing around with the different settings I finally came across an entry in the Silverlight Forums by sladapter with a solution. 

     

    http://silverlight.net/forums/t/19021.aspx 

     

    So lets create a simple Silverlight 2 App to demo how to do this.  I created a silverlight app with a web application project.   I prefer web applications to web sites but a web site will work the same.  

     

    Add a WCF Silverlight- enabled service named  service1 to the web application. 

     

    This is the code I am using for the service

     

    Imports System.ServiceModel
    Imports System.ServiceModel.Activation 
    
    <ServiceContract(Namespace:="")> _
    <AspNetCompatibilityRequirements(RequirementsMode:=AspNetCompatibilityRequirementsMode.Allowed)> _
    Public Class Service1 
    
        <OperationContract()> _
        Public Function SayHello() As String
            ' Add your operation implementation here
            Return "Hello World"
        End Function
    End Class 
    
    

     

    Lets add a TextBlock to the Page.xaml to display our message.

     

    Imports System.ServiceModel
    Imports System.ServiceModel.Activation 
    
    <ServiceContract(Namespace:="")> _
    <AspNetCompatibilityRequirements(RequirementsMode:=AspNetCompatibilityRequirementsMode.Allowed)> _
    Public Class Service1 
    
        <OperationContract()> _
        Public Function SayHello() As String
            ' Add your operation implementation here
            Return "Hello World"
        End Function
    End Class 
    
    

     

    Now run the app.  Once that is done we can add a service reference to our silverlight app.  Press the arrow on the Discover button and select services in the solution.  You should windup with something like this.

     

    image

     

    In the silverlight app open up the file ServiceReferences.ClientConfig

     

    <configuration>
        <system.serviceModel>
            <bindings>
                <basicHttpBinding>
                    <binding name="BasicHttpBinding_Service1" maxBufferSize="65536"
                        maxReceivedMessageSize="65536">
                        <security mode="None" />
                    </binding>
                </basicHttpBinding>
            </bindings>
            <client>
                <endpoint address="http://localhost:1205/Service1.svc" binding="basicHttpBinding"
                    bindingConfiguration="BasicHttpBinding_Service1" contract="ServiceReference1.Service1"
                    name="BasicHttpBinding_Service1" />
            </client>
        </system.serviceModel>
    </configuration> 

     

    In the endpoint address change the contract to include the project name.

     

    <configuration>
        <system.serviceModel>
            <bindings>
                <basicHttpBinding>
                    <binding name="BasicHttpBinding_Service1" maxBufferSize="65536"
                        maxReceivedMessageSize="65536">
                        <security mode="None" />
                    </binding>
                </basicHttpBinding>
            </bindings>
            <client>
                <endpoint address="http://localhost:1205/Service1.svc" binding="basicHttpBinding"
                    bindingConfiguration="BasicHttpBinding_Service1" contract="SilverlightApplication2.ServiceReference1.Service1"
                    name="BasicHttpBinding_Service1" />
            </client>
        </system.serviceModel>
    </configuration> 

     

    Now lets add some code to call the service. Page.Xaml.VB

     

    Partial Public Class Page
        Inherits UserControl
        Dim current As String 
    
        Public Sub New()
            InitializeComponent()
        End Sub 
    
        Private Sub Page_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
            Dim ws As New ServiceReference1.Service1Client
            AddHandler ws.SayHelloCompleted, AddressOf HelloComplete
            ws.SayHelloAsync()
        End Sub 
    
        Private Sub HelloComplete(ByVal sender As Object, ByVal e As ServiceReference1.SayHelloCompletedEventArgs)
            txt.Text = e.Result
        End Sub 
    
    End Class 
    

     

    Now if we run the app you should see Hello World but when published you will only see loading.   So lets change how we create the service so that this will work once deployed.  Basically we tell the service to use the current web address.

     

    Private Sub Page_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
        Dim address = New Uri(Application.Current.Host.Source, "../Service1.svc") 
    
        Dim ws As New ServiceReference1.Service1Client("BasicHttpBinding_Service1", address.AbsoluteUri)
        AddHandler ws.SayHelloCompleted, AddressOf HelloComplete
        ws.SayHelloAsync()
    End Sub 
    

     

    Hope this helps

    Full story

    Comments (1)