Bernhard's profileBernhard Grojer - BlogPhotosBlogLists Tools Help

Blog


    April 08

    Silverlight: DataBinding zu WCF Service - Teil 1/2


    In Silverlight kann mittels DataBinding sehr einfach ein WCF-Service konsumiert werden.

    image 

    Mit Hilfe von INotifyCollectionChanged und INotifyPropertyChanged bekommen wir im Bereich DataBinding ausgezeichnete Möglichkeiten Änderungen ins UI zu puplizieren.

    Im Beispiel habe ich die Customer Tabelle der Northwind-Datenbank gewählt und diese über ein WCF Service (BasicHttpBinding mit AspNetCompatibility) bereitgestellt.

    [ServiceContract]
        public interface ICustomerService
        {
            [OperationContract]
            List<Customer> GetCustomers();
    
            [OperationContract]
            bool SaveCustomers(Dictionary<Customer, string> Customers);
        }
    
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
        public class CustomerService : ICustomerService
        {
            #region ICustomerService Members
    
            public List<Customer> GetCustomers()
            {
                using (var DB = new NorthwindDataContext())
                {
                    var query = from c in DB.Customers
                                select c;
                    return query.ToList();
                }
            }
    
            public bool SaveCustomers(Dictionary<Customer, string> Customers)
            {
                TODO: Implement Save
                return true;
            }
    
            #endregion
        }

    Damit dieses Service verfügbar ist muss noch die passende web.config (Service Configuration Editor) erstellt werden (passende .svc Datei nicht vergessen bei WCF Service unter WAS/IIS)

    image

    Dieses Service wird in Silverlight von der Klasse CustomerDataSource asynchron konsumiert. Dies hat natürlich den Vorteil, dass das UI sofort verfügbar ist wärend die Daten noch nachgeladen werden. Und das man von der ersten Sekunde an deklaratives DataBinding benutzen kann.

    Damit die Daten aber tatsächlich nachgeladen werden können brauchen wir zuerst einen Proxy den wir über “Add Service Reference” erzeugen lassen. (Meta-Daten müssen vom Service aktiviert/bereitgestellt werden).

    image

    Sobald der CustomerServiceCleint (generierter Code) nun verfügbar ist können wir eine passende Klasse erzeugen und das Service benutzen.

    public class CustomerDataSource
        {        
            public CustomerDataSource()
            {
                LoadCustomers();
            }
    
            private void LoadCustomers()
            {
                CustomerServiceClient client = new CustomerServiceClient();
                client.GetCustomersCompleted += (sender, e) =>
                {
                    foreach (var c in e.Result)
                    {
                        _Customers.Add(c);
                    }
    
                };
                client.GetCustomersAsync();
            }
    
            ObservableCollection<Customer> _Customers = new ObservableCollection<Customer>();
            public ObservableCollection<Customer> Customers
            {
                get {
                    return _Customers;
                }
    
            }     
        }


    Die Klasse stellt nun eine ObservableCollection<T> (Customers) bereit in Form eines Property. Gegen das wird in XAML deklarativ gebunden.

    Die Klasse CustomerDataSource beginnt beim Erzeugen das CustomerService aufzurufen. Sobald das Ergebnis vom Service da ist, wird die Liste _Customers befüllt. Da es sich hierbei um eine ObservableCollection<T> handelt und diese INotifyCollectionChanged implementiert wird das UI informiert sobald ein neuer Customer in die Liste wandert und DataGrid aktualisiert automatisch.

    In XAML fehlt und zuletzt noch das Binding:

    <UserControl xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"  x:Class="SilverlightConsumeWCF.MainPage"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:SilverlightConsumeWCF">
        <UserControl.Resources>
            <local:CustomerDataSource x:Key="Customers" />
        </UserControl.Resources>    
        <Grid x:Name="LayoutRoot" Background="White">
            <data:DataGrid ItemsSource="{Binding Path=Customers, Source={StaticResource Customers}}">
            </data:DataGrid>
        </Grid>
    </UserControl>

    Download: SilverlightConsumeWCF 08042009.zip

    Im Teil 2 wird noch editieren der Customer-Objekte ermöglicht. Das Service stellt die entsprechende Methodensignatur bereits bereit.

    Comments

    Please wait...
    Sorry, the comment you entered is too long. Please shorten it.
    You didn't enter anything. Please try again.
    Sorry, we can't add your comment right now. Please try again later.
    To add a comment, you need permission from your parent. Ask for permission
    Your parent has turned off comments.
    Sorry, we can't delete your comment right now. Please try again later.
    You've exceeded the maximum number of comments that can be left in one day. Please try again in 24 hours.
    Your account has had the ability to leave comments disabled because our systems indicate that you may be spamming other users. If you believe that your account has been disabled in error please contact Windows Live support.
    Complete the security check below to finish leaving your comment.
    The characters you type in the security check must match the characters in the picture or audio.

    To add a comment, sign in with your Windows Live ID (if you use Hotmail, Messenger, or Xbox LIVE, you have a Windows Live ID). Sign in


    Don't have a Windows Live ID? Sign up

    Trackbacks

    The trackback URL for this entry is:
    http://bgrojer.spaces.live.com/blog/cns!9D87CECB1EA8118F!591.trak
    Weblogs that reference this entry
    • None