Geeks With Blogs
Peter Tweed Exploring and explaining the mysteries of .NET

This is the second post in a series to demonstrate how to use the standard MSFT technologies to implement a CRUD data application in .  The steps in this post build upon those completed in part 1.  The goal of this series is to show those of you who are relatively new to Silverlight how analogous building such an app in Silverlight is to say building it in ASP.NET, Win Forms or WPF.

The finished code for part 2 is here.

Steps:

1.       Open the CRUDSvc.svc.cs file in the SimpleCRUDApp.Web project and add the following code below the GetPeople function

        [OperationContract]

        public void AddPerson(Person p)

        {

            CRUDEntities ctx = new CRUDEntities();

 

            ctx.AddToPerson(p);

            ctx.SaveChanges();

        }

2.       Rebuild the SimpleCRUDApp.Web project and update the CRUDSvc service reference in the SimpleCRUDApp project

3.       Add the following code to the end of the stack panel in Page.xaml in the SimpleCRUDApp project

            <Button x:Name="btnAdd" Content="Add Person" FontSize="16" Margin="0,5,0,0" Width="100" HorizontalAlignment="Center" />

 

The above XAML adds a button below the list box to allow the use to add a Person record.  When clicked it will display an empty Person details section to the right of the list box where the user can enter the details of the Person record.  We will add the XAML for the Person detail next.

4.       Add the following code below the stack panel in Page.xaml

        <Border x:Name="bDetails" HorizontalAlignment="Right" VerticalAlignment="top" Visibility="Collapsed" >

            <StackPanel Orientation="Vertical" HorizontalAlignment="Center"  >

                    <Border Background="Yellow" BorderBrush="Orange" BorderThickness="3" CornerRadius="10" Width="300" Height="225" Margin="0,50,50,0" >

                    <StackPanel Orientation="Vertical" Width="Auto" HorizontalAlignment="Center" Margin="0,10,0,0"  >

                        <StackPanel Orientation="Horizontal" >

                            <TextBlock Text="First Name:" FontSize="16" TextAlignment="Right" Width="100"/>

                            <TextBox Text="{Binding FirstName, Mode=TwoWay}" Width="100" FontSize="16" />

                        </StackPanel>

                        <StackPanel Orientation="Horizontal" Margin="0,10,0,0" >

                            <TextBlock Text="Last Name:" FontSize="16" TextAlignment="Right" Width="100"/>

                            <TextBox Text="{Binding LastName, Mode=TwoWay}" Width="100" FontSize="16" />

                        </StackPanel>

                        <StackPanel Orientation="Horizontal" Margin="0,10,0,0" >

                            <TextBlock Text="Fact:" FontSize="16" TextAlignment="Right" Width="100"/>

                            <TextBox Text="{Binding InterestingFact, Mode=TwoWay}" FontSize="16" Width="100" Height="100" AcceptsReturn="True" TextWrapping="Wrap" VerticalScrollBarVisibility="Auto"  />

                        </StackPanel>

                    </StackPanel>

                </Border>

                <StackPanel Orientation="Horizontal" Margin="0,5,35,0" HorizontalAlignment="Center"  >

                    <Button Content="Save" FontSize="16" x:Name="btnSave" />

                </StackPanel>

            </StackPanel>

        </Border>

The above XAML defines the controls to display the details of the Person record and two buttons – one to save the Person record and one to delete it.

A few things to note:

The bindings for the text boxes to edit details are defined as two way.  That means that as users update the text boxes the bound entity properties are updated with the new data, i.e. we don’t need to manage the bindings once we have declared it in the XAML.

The button controls in this and the prior step have not been hooked them up to the code behind.  We will do that next.

5.       Add the Click attribute to the btnAdd and btnSave controls in Page.xaml and select “<New Event Handler>”; the click event handlers for the button controls will be generated in Page.xaml.cs

6.       Add the following code to the btnAdd_Click event handler in Page.xaml.cs

            CRUDSvc.Person p = new CRUDSvc.Person();

 

            bDetails.DataContext = p;

            bDetails.Visibility = Visibility.Visible;

 

This code creates a new Person entity and assigns it to the data context of the details bDetails border.  As the data context flows down in the visual control hierarchy in Silverlight, the text boxes contained in the bDetails border control can bind to the properties of the data context object.  As those bindings are declared as two way, when the user updates the text boxes the bound properties of the object in the data context will be automatically updated by the Silverlight property system.  That’s the magic of Silverlight data binding!

7.       Take a break at this time and run the application.  When you click the Add button the details panel is displayed – WOW! EXCITING ISN’T IT!!!!!

OK so it doesn’t do much but we’ll add the saving logic to call our updated WCF service next.

8.       Add the following code to the btnSave_Click event handler in the Page.xaml.cs file

            CRUDSvc.Person p = bDetails.DataContext as CRUDSvc.Person;

 

            if (p != null)

            {

                UpdatePerson(p);

            }

This code gets the Person entity that is the data context of the bDetails border and passes it to a function we will define next that will call the WCF service to carry out the save of the entity to the database.

9.       Add the following code below the btnSave_Click event handler in the Page.xaml.cs file

        private void UpdatePerson(CRUDSvc.Person p)

        {

            bWorking.Visibility = Visibility.Visible;

            CRUDSvc.CRUDSvcClient proxy = new CRUDSvc.CRUDSvcClient();

 

            proxy.AddPersonCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(proxy_AddPersonCompleted);

            proxy.AddPersonAsync(p);

        }

 

        void proxy_AddPersonCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)

        {

            LoadPeople();

            bDetails.Visibility = Visibility.Collapsed;

        }

 

This code shows the “working” message to allow the user to know that an asynchronous process is occurring, adds the AddPersonCompleted event handler to a proxy for the CRUDSvc WCF service and calls the WCF service Add Person function with the Person entity that is passed in from the btnSave_Click event handler.  The AddPersonCompleted event handler fired on completion of the AddPerson function then tells the page to reload all the Person records from the database and then hides the details panel.

10.   Run the application, click the add button and enter some information about the new Person

11.   Click the Save button and after the processing has occurred you’ll see the new Person record is displayed in the list of person records

Congratulations!  You now have the CR in the CRUD application!

What have we covered?

We have added the ability to add new Person records to our database from our Silverlight client.

We have shown how to add a function to the WCF service, rebuild the service and update the service reference in the Silverlight client so the client can call the added service.

We have shown that the pattern of calling the added WCF service function is the same as the previous one we implemented in part 1 – i.e. asynchronous with a callback event handler.  Please note: I recommend a more elegant mechanism than creating a service proxy each time you want to call a WCF service.

We have seen how to hook up the click events of buttons in the XAML files to the code behind event handlers.

We have seen how to bind object properties to the data context object of visual controls (in this case text boxes).

What’s next?

In the next post we will add the ability to update our Person records in our CRUd Silverlight application.

Posted on Friday, July 3, 2009 12:00 AM Silverlight | Back to top


Comments on this post: A simple Silverlight CRUD application – part 2: creating the C in CRud

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © PeterTweed | Powered by: GeeksWithBlogs.net