Geeks With Blogs

Post Categories

Peter Tweed Exploring and explaining the mysteries of .NET

This is the first post in a series to demonstrate how to use the standard MSFT technologies to implement a CRUD data application in .  This post is beginners stuff - there’s nothing advanced here.  Most readers with some experience of Silverlight will learn nothing from this post, but I want to start at the beginning so those of you who are relatively new to Silverlight can see 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 1 is here.                                                 

Database preparation:

I have a database in SQL Server with the following table definition:

With the following data:

Steps:

1.       Create the Silverlight application project SimpleCRUDApp

2.       Add an ASP.NET web app to host the Silverlight project

 

3.       Replace the user control in Page.xaml with the following XAML that will be used to display the persons data in a list box.  Note: you’ll have to update the namespace in the x:Class declaration of the user control tag if you named your project something other than SimpleCRUDApp

    <UserControl x:Class="SimpleCRUDApp.Page"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >

    <Grid x:Name="LayoutRoot" Background="Azure" >

        <StackPanel Orientation="Vertical" HorizontalAlignment="Left" VerticalAlignment="top" Margin="50,20,0,0" >

 

            <Border Background="LightBlue" Width="200" Height="225" BorderBrush="CornflowerBlue" BorderThickness="3" CornerRadius="10" >

                <ListBox x:Name="lstPersons" Background="AliceBlue" HorizontalAlignment="Center" Margin="0,10,0,0" MaxHeight="200" MaxWidth="150" VerticalAlignment="Top" >

                    <ListBox.ItemTemplate>

                        <DataTemplate>

                            <StackPanel Orientation="Horizontal">

                                <TextBlock Text="{Binding FirstName}" FontSize="16" />

                                <TextBlock Text="{Binding LastName}" FontSize="16" Margin="5,0,0,0"/>

                            </StackPanel>

                        </DataTemplate>

                    </ListBox.ItemTemplate>

                </ListBox>

            </Border>

        </StackPanel>

        <Border x:Name="bWorking" VerticalAlignment="Center" HorizontalAlignment="Center" Background="green" Height="50" Width="200" Visibility="Collapsed" >

            <TextBlock Text="WORKING..." Foreground="White" FontSize="16" HorizontalAlignment="Center" VerticalAlignment="Center" />

        </Border>

    </Grid>

</UserControl>

 

The list box above has an item template to bind text blocks to the FirstName and LastName properties of the list box bound objects to display their values to the user.  The FirstName and LastName properties match the names of the fields in the Person table definition in the Database preparation section above.

4.       Add an ADO.NET Entity Data Model to the SimpleCRUDApp.Web project and choose to generate the model from the database, selecting your database and the Person table (see the Database preparation section above)

5.       Add a Silverlight enabled WCF service to the SimpleCRUDApp.Web project

6.       Replace the generated DoWork() function with the following code and build the SimpleCRUDApp.Web project

        [OperationContract]

        public List<Person> GetPeople()

        {

            CRUDEntities ctx = new CRUDEntities();

            var people = from p in ctx.Person

                         select p;

 

            return people.ToList();

        }

The function returns a list of Person records from the database in the form of the entity framework generated Person entities.

7.       Add a service reference to the SimpleCrudApp project, click the Discover button and expand the Services tree view to ensure our GetPeople function has been detected.  Click OK.

8.       In the Page.xaml.cs file in the SimpleCrudApp project replace the constructor with the following code

        public Page()

        {

            InitializeComponent();

            this.Loaded += new RoutedEventHandler(Page_Loaded);

        }

 

        void Page_Loaded(object sender, RoutedEventArgs e)

        {

            LoadPeople();

        }

 

        private void LoadPeople()

        {

            bWorking.Visibility = Visibility.Visible;

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

 

            proxy.GetPeopleCompleted += new EventHandler<SimpleCRUDApp.CRUDSvc.GetPeopleCompletedEventArgs>(proxy_GetPeopleCompleted);

            proxy.GetPeopleAsync();

        }

 

        void proxy_GetPeopleCompleted(object sender, SimpleCRUDApp.CRUDSvc.GetPeopleCompletedEventArgs e)

        {

            lstPersons.ItemsSource = e.Result;

            bWorking.Visibility = Visibility.Collapsed;

        }

The above code does the following things:

·         Once the page has been initialized in the constructor, it sets up an event handle to fire when the client has loaded the page

·         Once loaded the app shows the “working” message (in the bWorking border XAML control), creates a service proxy for the CRUD service and sets up the event handler that will be fired once the call to the GetPeople function in the service has completed.  REMEMBER: all calls to web services in Silverlight are asynchronous – you have no option for synchronous calls – so all calls to a service will be set up similar to this.

·         The app then calls the GetPeople service function.

·         In the event handler for the GetPeople function, the list of person records (a list of entity framework generated Person entities) returned as the result of the service function call are bound to the items source property of the XAML list box in Page.xaml.

·         As the list box has an item template that displays the FirstName and LastName properties in text blocks of the objects bound to the list box, the first and last name will be displayed for each Person entity.

 

9.       Run the solution and you should see the following screen where the first and last names of the records in the Person table in our SQL Server database are displayed successfully.

What have we covered?

We have covered using the Visual Studio templates for creating the different core components that are needed to create a basic forms over data business application in Silverlight.

  • A Silverlight application with web application to host it
  • An entity framework model to handle data access and entity generation on the server side and DTOs for the client. (Yes this leads to the discussion of where do business objects exist vs use of simple DTOs for data transfer in distributed apps - but that is a more complex discussion for a later post)
  • A WCF service to enable the communication between the Silverlight client and the server.  One option for the communication mechanism - there are others to explore in later posts.
  • How to hook up the calling of the asynchronous WCF services in the Silverlight client.

What's next?

The next post will move on to show how we add the functionality to create records in our CRud application.

Later posts will complete all parts of the CRUD application, will then migrate the application into an MVVM model and then start to address some of the more complex aspects of enterprise application development in Silverlight.

Posted on Wednesday, July 1, 2009 7:29 PM Silverlight | Back to top


Comments on this post: A simple Silverlight CRUD application – Part 1: putting the R in cRud

# re: A simple Silverlight CRUD application – Part 1: putting the R in cRud
Requesting Gravatar...
Thanks for the post. It's perfect for where I'm at with respect to adding Silverlight to my skillset, and I found this really helpful to get more of the basic foundation.
Left by Mic on Jul 03, 2009 12:51 PM

# re: A simple Silverlight CRUD application – Part 1: putting the R in cRud
Requesting Gravatar...
You're welcome Mic - thanks for the feedback. I'lll be continuing the thread of developing business apps with Silverlight and discussing the challenges with where the technology is at this time and options of how get past those issues.
Left by Peter on Jul 03, 2009 2:44 PM

# re: A simple Silverlight CRUD application – Part 1: putting the R in cRud
Requesting Gravatar...
hi , thx for article.
but i have a error when running
error is :
An error occurred while trying to make a request to URI 'http://localhost:2411/CRUDSvc.svc'. This could be due to attempting to access a service in a cross-domain way without a proper cross-domain policy in place, or a policy that is unsuitable for SOAP services.
Left by mehmet on Jul 04, 2009 4:34 AM

# re: A simple Silverlight CRUD application – Part 1: putting the R in cRud
Requesting Gravatar...
Hi mehmet! The code is supplied as reference but won't run straight out of the zip file for a couple of reasons - I have a SQL database and the service references in the Silverlight project were generated on my dev machine.
What I would suggest:

1. Ensure you have a SQL server database and table with the definition given in this post and ensure the connectionstring to the database is for your environment. (It's hard coded for my machine petert-pc1 - see the web.config in the web project).
2. Delete and recreate the ADO.NET Entity Data Model in step 4 in this post.
3. Rebuild the web app.
4. Delete the WCF service reference from the Silverlight project and add it again as in step 7 in this post.
5. Build the solution and run.

Let me know how you get on.
Left by Peter on Jul 04, 2009 10:07 AM

# re: A simple Silverlight CRUD application – Part 1: putting the R in cRud
Requesting Gravatar...
The tight binding is good reason not to use EF for something like this. Just use plain ADO.NET to connect to the data - you can then map to the |DataDirectory| macro and avoid the pathing and machine specific configuration problems.
Left by Jason Short on Jul 06, 2009 8:33 PM

# re: A simple Silverlight CRUD application – Part 1: putting the R in cRud
Requesting Gravatar...
Thanks for the feedback Jason! I just checked and what I should have done (given I wanted to still use EF deliberately) was to use a SQLEXPRESS database file in App_Data directory in the web project like you say, but still use the EF model generated from it. EF works fine with SQLEXPRESS for this simple demo app and the connection string would be <add name="myDBEntities" connectionString="metadata=res://*/MYEFM.csdl|res://*/MYEFM.ssdl|res://*/MYEFM.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\myDB.mdf;Integrated Security=True;User Instance=True;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient"/>

and as you say would avoid the machine specific config prodblems. It'd also allow me to include the DB in the zip file.

Thanks for pointing it out.
Left by Peter on Jul 07, 2009 9:07 AM

# re: A simple Silverlight CRUD application – Part 1: putting the R in cRud
Requesting Gravatar...
Thank you! we really needed a simple example like this.
Left by daniel williams on Sep 21, 2009 1:11 PM

# re: A simple Silverlight CRUD application – Part 1: putting the R in cRud
Requesting Gravatar...
Thanks for the feedback Daniel! This helps me know if I'm targeting my writing to where I want to help others understand how to use the technology.
Left by Peter on Sep 27, 2009 11:41 AM

# re: A simple Silverlight CRUD application – Part 1: putting the R in cRud
Requesting Gravatar...
The article is well written and does a good job at introducing fundamental concepts to Silverlight newcomers such as myself. I'm about to browse to the next part of the tutorial series now :)
Left by Sameegh on Mar 02, 2010 1:49 AM

# re: A simple Silverlight CRUD application – Part 1: putting the R in cRud
Requesting Gravatar...
Hi,
I am building a schedular application in silverlight for a schoolproject.
I used this tutorial to get data from the database to the application. What is the code if I only want the names in the listbox with lastname Jones.

I have tried it whit a query but then i can't delete the items anymore.
Can you please help me with that. :-)

thanks
Left by Pieter Hermans on Nov 29, 2010 8:48 AM

# Adeel
Requesting Gravatar...
Thanx for such a nice post, but i m getting error CRUDEntities could not be found. please make me correct if i m wrong on any step

Regards,
Left by Ahmed on May 27, 2011 9:24 AM

# re: A simple Silverlight CRUD application – Part 1: putting the R in cRud
Requesting Gravatar...
Good article on CRUD. I am having some issues with my queries.. Using VB.
Left by Water Damage Restoration Softwar on Jun 05, 2011 2:19 PM

# re: A simple Silverlight CRUD application – Part 1: putting the R in cRud
Requesting Gravatar...
Found very easy and good for beginners. Mostly the good thing is well explained.
Left by Irfan on Feb 20, 2013 1:21 AM

Your comment:
 (will show your gravatar)


Copyright © PeterTweed | Powered by: GeeksWithBlogs.net