Silverlight 4 Business Application Part 4 od n


Implementation of the DBNavigation control in Silvelright 4

naslovThis is 4th part of the series of Silverlight Business Application development, which I am writing. Today we will try to implement DBNavigator control.

With Silverlight 4 and RIA services you can develop full business application with backend SQL database on the similar way as you can do in Windows Forms and Windows Presentation Foundation. In the previous posts we have seen how easy connect database to your Silverlight application, and also how to use some patterns in Silvelright aplication like MVVM.
I this post we will see how to implement Database Navigation control like BindingNavigator from Windows Forms. On the other hand we will also see how to extend functionality of the existing Silverlight control by developing custom control derived from existing one, as well as the procedure how to create Silverlight User control.

Our Tutorial will start from the previous blog post, so you need to download source code sample, and start our today’s tutorial. When you download source code, open it in Visual Studio 2010.

 

  • Right click on the solution and chose  Add->New  Project
  • Select Silvelright Class Library project template, give it the name SLCustomCtrl, and click OK button.

sl1

Now that you have the new Silverlit Class Library project in your solution, you have to add reference to your main Silverlight project.

  • Right click on References of theSLDemoPart2 project,  and chose Add->Reference, click Project Tab in the new dialog, and chose SLCustomCtrl project.

Implementation of Custom Control

If you want to extent functionality from the existing Silverlight control you have to add the new Silverlight Templated Control, and starting extend the new functionality from the existing one.

  • Right click on the SLCustomCtrl project, chose Add->New Item, and choose Silverlight Templated Control, name it SLDBNavigator.cs, and hit Add button.

sl2Open SLDBNavigator.cs and put the following source code:

public class DBNavigationBaseCtrl : Grid
{
    public event RoutedEventHandler AddNew;
    public event RoutedEventHandler DeleteCurrent;
    public event RoutedEventHandler DomainDataChanged;

    public DBNavigationBaseCtrl()
    {

    }
    public DomainDataSource DomainData
    {
        get { return (DomainDataSource)GetValue(DomainDataProperty); }
        set
        {
            SetValue(DomainDataProperty, value);
            OnDomainDataChanged(new RoutedEventArgs());

        }
    }

    private void OnDomainDataChanged(RoutedEventArgs e)
    {
        if (DomainDataChanged != null)
            DomainDataChanged(new object(),e);
    }

    public static readonly DependencyProperty DomainDataProperty =
        DependencyProperty.Register("DomainData", typeof(DomainDataSource), typeof(DBNavigationBaseCtrl), new PropertyMetadata(null));
    public bool IsCustomDelete
    {
        get { return (bool)GetValue(IsCustomDeleteProperty); }
        set { SetValue(IsCustomDeleteProperty, value); }
    }

    public static readonly DependencyProperty IsCustomDeleteProperty =
        DependencyProperty.Register("IsCustomDelete", typeof(bool), typeof(bool), new PropertyMetadata(false));

    protected void OnEventAddNew(RoutedEventArgs e)
    {
        if (AddNew != null)
            AddNew(new object(), e);
    }
    protected void OnEventDeleteCurrent(RoutedEventArgs e)
    {
        if (DeleteCurrent != null)
            DeleteCurrent(new object(), e);
    }
}

Implementation of the previous source code contains the three Routed Event Handlers, and two properties. The source code is very simple so you can see very quickly what’s going on in the source code.

Implementation of User Control

Now that we have base custom control for manipulation database tables and views, we need to implement custom Silvelright control derived from it  to expose implemented properties and events from the base class in to XML.

  • Right click on SLCustmCtrls project, chose Add->New Item, select Silverlight User Control, name it DBNavigatorCtrl.xaml, and click Add button.

sl3

Implementation is achieved with putting  several buttons in to controls and subscribe to corresponded click events. The implementation of the DBNavigationCtrl is in the following two listing:

<!--DB Navigator-->
    <StackPanel Margin="2" Orientation="Horizontal" HorizontalAlignment="Center" >
        <Button Content="&lt;|" Height="Auto" Name="btnFirst"  Width="30" Click="btnFirst_Click" />
        <Button Content="&lt;" Height="Auto"  Name="btnPrev"   Width="30" Click="btnPrev_Click" />
        <TextBlock Width="70" Name="textCurrentItem" Text="" TextAlignment="Center" VerticalAlignment="Center"></TextBlock>
        <Button Content="&gt;" Height="Auto"  Name="btnNext"  Width="30" Click="btnNext_Click" />
        <Button Content="|&gt;" Height="Auto" Name="btnLast"  Width="30" Click="btnLast_Click" />
        <Button Content="+" Height="Auto"  Name="btnAdd"  Width="30" Click="btnAdd_Click" />
        <Button Content="-" Height="Auto" Name="btnDelete"  Width="30" Click="btnDelete_Click" />
    </StackPanel>
public partial class DBNavigatorCtrl : DBNavigationBaseCtrl
{
    public DBNavigatorCtrl()
    {
        InitializeComponent();
        this.DomainDataChanged += new RoutedEventHandler(DBNavigatorCtrl_Loaded);

    }

    void DBNavigatorCtrl_Loaded(object sender, RoutedEventArgs e)
    {
        if (DomainData != null)
        {
            DomainData.DataView.CurrentChanged += (ss, ee) =>
            {
                var dds = ss as DomainDataSourceView;

                if (dds != null)
                    textCurrentItem.Text = (dds.IndexOf(dds.CurrentItem) + 1).ToString() + "/" + dds.Count.ToString();
                else
                    textCurrentItem.Text = "0/0";
            };
        }
    }

    private void btnFirst_Click(object sender, RoutedEventArgs e)
    {

        if (DomainData != null)
            DomainData.DataView.MoveCurrentToFirst();
    }

    private void btnPrev_Click(object sender, RoutedEventArgs e)
    {
        if (DomainData != null)
            if (DomainData.DataView.CurrentPosition > 0)
                DomainData.DataView.MoveCurrentToPrevious();
    }

    private void btnNext_Click(object sender, RoutedEventArgs e)
    {
        if (DomainData != null)
            if (DomainData.DataView.CurrentPosition + 1 < DomainData.DataView.Count)
                DomainData.DataView.MoveCurrentToNext();
    }

    private void btnLast_Click(object sender, RoutedEventArgs e)
    {
        if (DomainData != null)
            DomainData.DataView.MoveCurrentToLast();
    }

    private void btnAdd_Click(object sender, RoutedEventArgs e)
    {
        if (DomainData == null)
            return;
        RoutedEventArgs e1 = new RoutedEventArgs();
        OnEventAddNew(e1);
    }

    private void btnDelete_Click(object sender, RoutedEventArgs e)
    {
        if (DomainData == null)
            return;
        if (IsCustomDelete)
        {
            RoutedEventArgs e1 = new RoutedEventArgs();
            OnEventDeleteCurrent(e1);
            return;
        }
        if (MessageBox.Show("Confirm delete by clicking the OK button",
                              "Deleting a record ...", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
        {
            DomainData.DataView.Remove(DomainData.DataView.CurrentItem);
        }
    }
}

Using DBNavigaorCtrl in Silvelright project

When we have DBNavigatorCtrl control, it is very easy to use it. Just put the control in to XAML, and in code behind assign it to domain data source of the Main Page.
Now select the main Silverlight project,and open MainPage.XAML, from the toolbox windows select DBNavigationCtrl item and drag and drop to mainpage, similar as picture shows below. If you don’t see DBNavigationCtrl in the ToolBox you have Rebuild the solution.

sl4

The result of our tutorial looks likes on the following picture:

sl5

The source code for this tutorial can be downloaded from here.
Implementation of the DBNavigation control in Silvelright 4

Silverlight 4 Business Application Part 2 od n


Connecting database to your Silverlight 4 Business application

The second article in series of the Silverlight Business application will cover Entity Framework and WFC RIA service, the two components by which you can achieve manipulation of database from your Silverlight Application.  A lot of blogs, articles and books you can find to learn about Silverlight Entity Framework and WFC RIA services. The blogs and book I would like to stress at the moment are http://jesseliberty.com/ the Silverlight and Windows Phone 7 Blog, and The book about Silverlight “Silverlight 4 UNLEASHED” by Laurent Bugnion . He is writing blog also at http://blog.galasoft.ch .

So, for now I will present how you can create Silverlight project from scratch, so you don’t need to use Visual Studio Template for Silverlight Business application. The reason is simple, if you don’t want to use ASP.Net generated database for users and logins, and want to use your own way of login the following tutorial is for you.

The requirements for the demo are the same as in previous post

1. First of all, Run Visual Studio 2010 any version (Ultimate, Professional or Express ), and chose File->New Project. The following picture shows New Project dialog and Silverlight Template projects.

image

2. Chose Silverlight from the left list box of project types, and select Silverlight  Application from the Silverlight project templates. Name the project as SLDemoPart2, and the Solution name let it be LSDemoPart2Solution.

After you click on OK button, another dialog appears, and you need to set some addition options about our Silverlight application. Check all option as picture show below, and click OK  button again.

image

Now, we have Silverlight empty project created within Visual Studio 2010. Every Silverlight application have to be hosted in Web page, so we need to create ASP.NET Application and host out Silverlight application in it.When the Visual Studio finished its jobs we can see the two projects: The Silverlight project we created, and ASP.NET Web application project  Visual Studio created for hosting our application.

Now that we have starting projects, we can start mapped our NorthWind database. If you need NorthWind database, please see previous post, where you can find the way you need to download NorthWind database.

Lets create Entity Framework Model and map the two common tables from the NorthWInd database: Orders and OrdersDetails.

3. Right Click on SLDemoPArt2.Web asp.net project, select Add –>New Item and chose ADO.NET Entity Data Model, name it the NorthWindModel.admx and click OK.

4. Follow the EF Wizard and define connection to your SQL Server database, and import mentioned tables. At the end finish the wizard window. When the VS 2010 finish rebuild the solution.The picture below shows the result:

image

We define our database model, but in this stage we cannot use it in Silverlight application, cause it is server component not client. To resolve this, we need such a service which can expose our database model to the client and make call to the database. RIA Services is component that you can achieve this. So lets create Domain data class one of the  component of the RIA Services.

5. Right Click on SLDemoPArt2.Web ASP.NETt project, select Add –>New Item and chose Domain Service Class . Type DDSNorthWindClient.cs in name edit box and click Add button.

Previously, if you rebuild your project now you can see the following dialog with Order and OrderDetails mapped tables. If you don’t see the tables, you have to rebuild the project.

image

Check the tables as well as check Enable Editing column, cause we want to read and modify the  data from the database as well. Click OK button. Now we are ready to use the NorthWind database from our Silverlight application.

Some of you may wonder, we didn’t touch Silverlight project, but how can we get our tables. The generated classes of the Domain Data Class, Visual Studio is exported to our Silverlight project in to Generated_Code folder, which is not included in to Silverlight project.

To prove that, click on Silverlight project, click on Show All Files toolbar of the the Solution Explorer Window, and we can see it. Try to open folder as well and generated file. You can see domain data class implementation in to Silverlight project.

image

Now that we convinced in to Domain Data Class implementation, we can use it in our Silverlight project.

6. Open MainPage.xaml in to XAML designer of the Silverlight project.

7. Chose main menu  Data->Show Data Sources, and we can see our tables within Data Sources Windows.

8. Drag  Orders table from Data Source Window in to MainPage XAML designer and what we can see?

image

We see completely the same technique like in WinForms application. Its Amassing !

Run the project and you can see Orders from your database in to your browser!

image

Source code for the tutorial can be downloaded from here.