Tuesday, March 24, 2009

Silverlight 3 : DataForm control features – Part 3

I am now going to talk a bit on DataForm control, I have already two articles on Silverlight 3 which was Lap around Silverlight 3 and Features of Blend 3.

From Silverlight 2, there were several discussions going on about Building “Line Of Business” application using Silverlight technology, I guess Controls like DataForm, DataPager etc. are the next step towards the vision of LOB applications using Silverlight 3 , since we already have excellent support of WCF,REST and rich controls.

DataForm basically will let you to push data from UI for processing, It will also enable to Enter data, provides UI to edit the existing data, We can also customize it to great extent and it also provides good validation support. Now lets discuss it step-by-step :

First you need to create blank Silverlight Project, then you need to add reference to following :

  • System.ComponentModel
  • System.ComponentModel.DataAnnotations
  • System.Windows.Controls.Data
  • System.Windows.Controls.Data.DataForm

There are two ways by which you can bind DataForm, Either by creating a resource to current User Control with set of properties in class or by creating Observable Collection. I am basically using both the approaches, but main focus is on building resource, check this code ,Here I have created a separate class file in which I am declaring some public fields like this :

public class sigheads
   {
       public string FirstName { get; set; }
       public string LastName { get; set; }
       public string Email { get; set; }
       public int Age { get; set; }
       public string SIG { get; set; }
   }

<UserControl.Resources>
        <sig:sigheads FirstName="Vikram"
                      LastName="Pendse"
                      Email="vikram.pendse@puneusergroup.org"
                      Age="27"
                      SIG="Silverlight"
                      x:Key="mySIG"/>
    </UserControl.Resources>
    <Grid x:Name="LayoutRoot" Background="White">
        <mydf:DataForm CurrentItem="{StaticResource mySIG}"
                       Header="SEED Infotech Ltd .NET Center of Excellence"
                       Background="#FFEFDCDC"
                       FieldLabelPosition="Auto">
         <mydf:DataForm.Effect>
                <DropShadowEffect/>
         </mydf:DataForm.Effect>
    </mydf:DataForm></Grid>

Before this XAML Code, you need to add following lines to your main User Control :

xmlns:mydf="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data.DataForm"     
xmlns:sig="clr-namespace:SL_DataForm"

First xml namespace will allow you to have DataForm Control on your layout and second namespace sets a reference to the class [Project itself ] where we have declare those public fields like FirstName,Age,Mail etc.

1.Binding attribute with various modes :

Look at following Code :

[Bindable(true, BindingDirection.TwoWay)]
   public class sigheads
   {
       [Bindable(true, BindingDirection.TwoWay)]
       public string FirstName { get; set; }
       [Bindable(true, BindingDirection.OneWay)]
       public string LastName { get; set; }
       [Bindable(false)]
       public string Email { get; set; }
       [Bindable(true, BindingDirection.TwoWay)]
       public int Age { get; set; }
       [Bindable(true, BindingDirection.OneWay)]
       public string SIG { get; set; }
   }

Look carefully at top level attribute :

[Bindable(true, BindingDirection.TwoWay)] ,If we put “false” in place to “true”, data will not get bind to DataForm. BindingDirection basically provides you two modes “OneWay” and “TwoWay” ,Normally if binding direction is one way then the fields are read-only.

dfbinding

You can see some shadow kind of effect to DataForm, this is because if you observe the XAML above carefully, you can find I have applied DropShadow Effect. Observe screenshot above carefully, you will find some Pencil like symbol on rightmost top corner, that will allow you to change mode of DataForm to Edit mode, once you click on that, Fields will be in edit mode (Provided you have mentioned binding direction in two way) and you will get Save button too like shown below :

dfieditable

2. Implementing IEditableObject Interface :

To have more flexibility in operations like Edit,Save etc, Class can now implement interface IEditableObject which implements 3 methods as BeginEdit(),CancelEdit(),EndEdit(), Inside which you can implement your own logic.

public class sigheads : IEditableObject
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public int Age { get; set; }
    public string SIG { get; set; }

    #region IEditableObject Members

    public void BeginEdit()
    {
        //Logic while Record is about to getting edited
    }

    public void CancelEdit()
    {
        //Logic on Cancelling Edit
    }

    public void EndEdit()
    {
        //Logic on Ending Edit
    }

    #endregion
}

dfcodeIeditable

3 . Working with “Display” Attribute :

Consider the code below :

public class sigheads
    {
        [Display(Name = "First Name :", Description = "Enter Your First Name", Order = 5)]
        public string FirstName { get; set; }
        [Display(Name = "Last Name :", Description = "Enter Your Last Name", Order = 4)]
        public string LastName { get; set; }
        [Display(Name = "E-mail ID :", Description = "Enter Your E-Mail ID", Order = 3)]
        public string Email { get; set; }
        [Display(Name = "Age :", Description = "Enter Your Age", Order = 2)]
        public int Age { get; set; }
        [Display(Name = "SIG of :", Description = "Enter Your SIG Name", Order = 1)]
        public string SIG { get; set; }
    }

Display attributes basically use to change Label heading of fields and their order in list of fields, so you can set priority in your fields by Order attribute, Description attribute gives you more information about the field by displaying a tool-tip message on a information button created next to the field by same attribute, like this, there are several more attributes like AutoGenerateField,AutoGenerateFilter,Description,Name ,Order,Prompt,ResourceType,ShortName. Each one have their own implementation.

dfdisplayinfo

4. Validations :

You can provide Validations to your fields while entering data like this :

public class sigheads
    {
        [Display(Name = "First Name :", Description = "Enter Your First Name")]
        [Required(ErrorMessage = "Field Cannot be left Blank")]
        public string FirstName { get; set; }

        [Display(Name = "Last Name :", Description = "Enter Your Last Name")]
        public string LastName { get; set; }

        [Display(Name = "E-mail ID :", Description = "Enter Your E-Mail ID")]
        [RegularExpression(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", ErrorMessage = "Invalid E-Mail ID")]
        public string Email { get; set; }

        [Display(Name = "Age :", Description = "Enter Your Age")]
        [Range(0, 999, ErrorMessage = "Invalid Age")]
        public int Age { get; set; }

        [Display(Name = "SIG of :", Description = "Enter Your SIG Name")]
        public string SIG { get; set; }
    }

Attributes like [Required(ErrorMessage = "Field Cannot be left Blank")] makes your field as “Compulsory Field”

Attributes like [RegularExpression(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", ErrorMessage = "Invalid E-Mail ID")] allows you to put your own Regular Expressions to validate data.

Those who have worked with Dynamic Data and had customized it, they may find this similar to the way they add custom validations and fields there.

On error, Data Form make the particular field highlighted in Red and also shows the summary of error in Error Summary below the DataForm Control.

dlvalidation

dlvalidglow

  5. Showing Multiple Records :

Below screen shows how you get Pager control to navigate among records, I added multiple records using observable collection, I am not giving code of that since its very basic.

dfpager

Hope, this will encourage you to go ahead and start using DataForm in your Silverlight Project. Soon I am going for few new things like Navigation, Pixel Shading and effects with SlSvcUtil and Silverlight 3 Out of Browser applications, so more things are coming soon, keep visiting here and let me know your feedback.

Vikram.

11 comments:

Harald said...

great article!

Any ideas on adding the necessary attributes to generated code such as generated wcf-proxy classes?

Tnx,
Harald

srinivas said...

Hi,
Iam new to forums..
just posting my question here ..pls direct me to the correct forum if it not the correct platform..
the problem with me here is iam not able to get the edit mode (pencil mode shown at the top right corner) ..let me have some views ..iam just settings the 3properties of the person class with the resources you shown at the example..
Thanks in advance
Srinivas

Vikram Pendse said...

Hi Srinivas,

First I assume you are working on Silverlight 3 RTW version.

The article above I wrote when Silverlight 3 was in BETA version, Now there are lot of changes in DataForm controls, rather it all together got revamped. So I request you to kindly refer Silverlight 3 RTW Breaking Changes Documentation available on http://silverlight.net site.

For Edit Mode button, Try out with Attribute AutoEdit="False". Let me know how it works for you.

Pradnya said...

Thanks a lot.It was really helpful Vikram. I got what I needed.

vinayak said...

hi,I am vinayak. i have created one database application using silverlight. it is working well on local m/c. but when I try to access it on network using IIS as server its not working. I am using SQL SERVER 2005 as DATABASE. can you help me?

Email:salunke.vinayak1@gmail.com

parya said...

Hi Vikram,

Thanks a lot. Very good information in a concise way.

Do you have any idea what can we do if we have to print using Silverlight 3?

parya said...

Hi Virkam,

I have another query in Silverlight 3 can we have context menus on click of a row in a datagrid

Thanks in advance
Parag Kulkarni

Vikram Pendse said...

Hi Parya,

Answer to your questions :

1. There is no direct API exposed for Printing capability like in Silverlight 4, so if at all you want to do printing, you need to explore some exporting mechanism by which you can do printing further

2. Right Click/Context Menus are not directly supported in version 3 however in version 4 they are part of it, so if you still want to have such menus, you need to explore event handle for mouse and may be you can put some menus or list in some stack panel.

Thanks for your comments, Hope this helps

Vikram Pendse said...

@Pradnya : Thanks for your comments !

@Vinayak : You need to check configuration files according to deployment environment, Also if you are getting some resources from remote server, you need to explore about cross domain access and client policies, Check my old articles.

parya said...

Hi Vikram,

Thanks for the reply.

1) About Printing in Silverlight 3: One thing came into my mind is since we have JavaScript support. Using JavaScript if somehow we can capture the browser object then the content to be printed we can get. I will try & let you know.

2) For the context menu the same thing like you mentioned. I created a stack panel with a set of buttons in it. Applied a style to suppress button's 3D effect. Even subcontext menus are also possible in this way.

Thanks.
Parag Kulkarni

parixit said...

im not able to see user specified error msg in validation violation