A simple Silverlight CRUD application – part 4: doing the D in CRUD

This is the final post in a four part 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 3.  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.

This app is built on , , and the using .

The finished code for part 4 is here.

Steps:

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

        [OperationContract]

        public void DeletePerson(Person p)

        {

            CRUDEntities ctx = new CRUDEntities();

 

            ctx.AttachTo("Person", p);

            ctx.DeleteObject(p);

            ctx.SaveChanges();

        }

 

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

3.       Add the following code directly after the btnSave control in Page.xaml in the SimpleCRUDApp project

<Button Content="Delete" FontSize="16" x:Name="btnDelete" Margin="5,0,0,0" />

 

The above XAML adds a button next to the save button to allow the user to delete a Person record. 

4.       Add the Click attribute to the btnDelete control in Page.xaml and select “<New Event Handler>”; the click event handler for the button control will be generated in Page.xaml.cs

5.       Add the following code to the btnDelete_Click event handler in Page.xaml.cs

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

 

            if (p != null)

            {

                bWorking.Visibility = Visibility.Visible;

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

 

                proxy.DeletePersonCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(proxy_DeletePersonCompleted);

                proxy.DeletePersonAsync(p);

            }

This code retrieves the Person object from the data context of the details panel bDetails, sets the working message to visible to tell the user a asynchronous operation is in progress, defines the callback for the WCF service function and calls the WCF service function.

6.       Add the following definition for the proxy_DeletePersonCompleted event handler to Page.xaml.cs after the btnDelete_Click event handler

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

        {

            LoadPeople();

               bDetails.Visibility = Visibility.Collapsed;

        }

This code reloads all the Person records to the list box and hides the details panel.

7.       Run the application and select one of the Person records in the list box

8.       Click the delete button.  The person record will be deleted from the database

 

Congratulations!  You now have completed the full simple CRUD application!

What have we covered?

Over the course of this four part series we have shown how to develop a VERY simple CRUD application in Silverlight 2.0, utilizing WCF, Entity Framework and SQL Server 2008 in Visual Studio SP1.

Obviously to develop a useful enterprise grade business application in Silverlight there are many other aspects to consider in architecture, logical design and implementation.  The Silverlight runtime is a subset of the .NET runtime and so there are many functions that it simply doesn’t support – but I would argue that the typical real world implemented business application doesn’t use or need to use many of the functions that don’t exist in Silverlight compared to the full .NET runtime.

Silverlight still has a way to go in certain areas, but in other areas it far excels compared to many of the other client side browser technologies.  Silverlight 3.0 beta is out and available and is very exciting.  Also in development is .NET RIA services to support challenges of developing for multi-tier asynchronous business Silverlight and ASP.NET applications - which is very exciting.  We will get to these topics in time.

What’s next?

In my next post we will look at another common business application development task – developing re-usable user controls with custom data related properties.  This is easily done but to take advantage of the power of the data binding mechanisms in Silverlight developers need to understand what dependency properties are and how they work.

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

A simple Silverlight CRUD application – part 3: updating the U in CRUd

This is the third 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 2.  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 3 is here.

Steps:

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

        [OperationContract]

        public void UpdatePerson(Person p)

        {

            EntityKey key;

            object originalItem;

 

            using (CRUDEntities ctx = new CRUDEntities())

            {

                try

                {

                    key = ctx.CreateEntityKey("Person", p);

 

                    if (ctx.TryGetObjectByKey(key, out originalItem))

                    {

                        ctx.ApplyPropertyChanges(

                            key.EntitySetName, p);

                    }

 

                    ctx.SaveChanges();

                }

                catch (InvalidOperationException ex)

                {

                    Console.WriteLine(ex.ToString());

                }

            }

        }

2.       Add the following using statement above the namespace declaration at the top of the CRUDSvc.svc.cs file

using System.Data;

 

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

4.       Add the SelectionChanged attribute to the lstPersons list box control in Page.xaml and select “<New Event Handler>”; the selection changed event handler for the list box will be generated in Page.xaml.cs

5.       Add the following code to the lstPersons_SelectionChanged event handler in Page.xaml.cs

            CRUDSvc.Person p = lstPersons.SelectedItem as CRUDSvc.Person;

 

            if (p != null)

            {

                bDetails.DataContext = p;

                bDetails.Visibility = Visibility.Visible;

            }

This code retrieves the selected Person entity object from the selected item in the list box, sets it to the data context of the details panel bDetails and displays the details panel.

6.       Replace the UpdatePerson function and the proxy_AddPersonCompleted event handler with the following code

        private void UpdatePerson(CRUDSvc.Person p)

        {

            bWorking.Visibility = Visibility.Visible;

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

 

            if (p.PersonID == 0)

            {

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

                proxy.AddPersonAsync(p);

            }

            else

            {

                proxy.UpdatePersonCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(proxy_AddUpdatePersonCompleted);

                proxy.UpdatePersonAsync(p);

            }

        }

 

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

        {

            LoadPeople();

            bDetails.Visibility = Visibility.Collapsed;

        }

 

Notice that we have associated the update of the Person record also with the processing of the save button being clicked.  We use a simple test of the PersonID property of the Person entity to determine if this is a new record that is being added or whether it is an existing record.  The PersonID column in the Person table is the primary key that is an identity column with seed = 1 and increment  = 1, so any record committed to the database table is assigned a PersonID of greater than zero.  Once we know whether to add or update the Person object, we call the appropriate WCF service function.  Note that because in both cases in this simple example I would reload all the person objects and hide the details panel, we can use the same callback function for both.

7.       Run the application and select one of the entries in the list of people to display the Person details panel

8.       Update some piece of information about the person (I added a 1 to the end of the last name of Joe Bloggs).  Click the Save button and after the processing has occurred you’ll see the updated Person record is displayed in the list of person records

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

What have we covered?

We have added the ability to update existing Person records in our database from our Silverlight client.

We have shown how to add the update function to the WCF service, rebuild the service and update the service reference in the Silverlight client.

We have shown that the pattern of calling the added WCF service function is again the same as the previous ones we implemented in part 1 and part 2  – i.e. asynchronous with a callback event handler.  Please note: as in Part 2 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 selection changed event of a list box in the XAML file to the code behind event handler.

What’s next?

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

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

A simple Silverlight CRUD application – part 2: creating the C in CRud

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.

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati
«July»
SunMonTueWedThuFriSat
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678