Lab Manual - Martin Moesby Foto

auburnhairSoftware and s/w Development

Dec 13, 2013 (3 years and 6 months ago)

162 views





Hands
-
On Lab

Silverlight



Lab version:



1.0.0

Last updated:


12/13/2013











Contents

OVERVIEW

................................
................................
................................
................................
...................

3

EXERCISE 1: CREATING

A SILVERLIGHT CUSTOM

CONTROL

................................
............................

4

Task 1
-

Create a new Silverlight Application

................................
................................
........................

4

Task 2


Creating the Web Resource for the Slider Control

................................
................................
.

8

Task 3


Add the Slider control to the form

................................
................................
..........................

9

EXERCISE 1 VERIFICAT
ION
................................
................................
................................
.....................

13

EXER
CISE 2: INTERACTING
WITH THE CRM FORM

................................
................................
.............

13

Task 1
-

Open the solution you created in Exercise 1 in Microsoft Visual Studio

...............................

13

Task 2


Set the value when the Slider Changes

................................
................................
.................

14

EXERCISE 2 VERIFICAT
ION
................................
................................
................................
.....................

15

EXER
CISE 3: USING THE DA
TA PARAMETER

................................
................................
......................

15

Task 1
-

Open the solution you created in Exercise 2in Microsoft Visual Studio

................................

16

Task 2


Modify the Web Resource on the Account form

................................
................................
..

16

Task 3


Capture Data parameter on application startup

................................
................................
..

16

Task 4


Change to set the value on the configured field

................................
................................
...

17

EXERCISE 3 VERIFICAT
ION
................................
................................
................................
.....................

19

EXERCISE 4: GENERATI
NG TYPED ENTITY CLAS
SES

................................
................................
........

19

Task 1


Save the metadata from the CRM Server

................................
................................
.............

19

Task 2


Add Generated Types to a Project

................................
................................
.......................

21

EXERCISE 5: ACCESSIN
G DATA USING ODATA

................................
................................
..................

22

Task 1
-

Open the solution you created in Exercise 4 in Microsoft Visual
Studio

...............................

22

Task 2


Add Silverlight Application for LifeStyle Profile

................................
................................
....

22

Task 3


Add an Accordion Control to Show the Profiles

................................
................................
...

23

Task 4


Setup Data Service Context

................................
................................
................................
...

27

SUMMARY

................................
................................
................................
................................
..................

32



Overview

Dynamics
CRM 2011

introduces

support for using Silverlight as a first class component for extending the
user interface.
In prior versions of CRM you could do this but had to use IFrames

and there was not
support to upload and store the Silverlight application on the CRM server.
Silverlight applications
are
now uploaded

and published as Web Resources

on the Microsoft Dynamics CRM 2011 sever. Once
published they are available for inserti
ng onto a form or available for navigation from the sitemap.
When placed on a form, Silverlight applications can interact with the CRM record data using the same
client scripting calls. Additionally, Silverlight applications can retrieve and manipulate o
ther CRM Data
using the OData (Open Data Protocol) REST service that is now available in Microsoft Dynamics CRM
2011.


Scenario

Contoso is an independent software vendor (ISV) building solutions that are used by Gyms / Workout
facilities around the wor
ld to manage their operations. Contoso has chosen Microsoft
Dynamics
CRM
2011

as the application platform to build their next generation Fitness Center Management product.
Contoso will be selling this solution to Gym/Workout facilities and will allow the
m to further customize
it to fit their individual operating needs. Gym facilities will be able to install the appropriate solution
packages into their
Dynamics
CRM 2011

server in order to realize the benefits of the Fitness Center
Management application.

C
ontoso’s Fitness Center Management solution is a modular application that allows customers to select
just the modules that they need.

We have been asked to build a slider control that can be used on the
forms for numeric input in place of just providing a

textbox for input. The slider control should be able
to be reused with any numeric field. Additionally, d
uring the course of this lab you will be building a
Silverlight application for use on a form to collect gym member Life Style profiles. If you did

the
JQUERY/HTML lab previously then you will notice this is a Silverlight version of the same component.
This allows you to compare and contrast the two development techniques.


Objectives

After completing this lab you will have accomplished the
following objectives:



Understand how to build a Silverlight Application



Understand how to deploy a Silvelright Application to CRM



How to generate a service reference to the OData endpoint



How to interact with the CRM Form


System Requirements

You must have

the following items to complete this lab:



Microsoft Visual Studio
2010



Dynamics
CRM 2011

-

Beta



Exercises

This Hands
-
On Lab comprise
s

the following exercises:

1.

Creating a Custom Silverlight Control

2.

Interacting with the CRM Form data

3.

Accepting input
parameters from the Form

4.

Using OData with Silverlight


Estimated time to complete this lab:
30

minutes
.



Exercise 1:
Creating a Silverlight Custom
Control

In this exercise we will build a
Silverlight application that will be used as a custom control on
a form.
CRM has a limited set of built
-
in controls and does not have a Slider control. Using Silverlight we are
going to build an application that will interact with the form fields and allow the user to manipulate a
fields value using a slider. The sli
der control will be built in a way that it can be reused on any form.



Task 1
-

Create a new
Silverlight

Application

In this
task,

you will
setup a new Silverlight application for use with CRM 2011. If you have built a
Silverlight application before
much of this task should seem familiar.

1.

Start

Microsoft Visual Studio 2010 from
Start | All Programs | Microsoft Visual Studio 2010 |
Microsoft Visual Studio 2010
.

2.

Click
File | New | Project

to launch the New Project dialog.

3.

Select Silverlight on the left side list of Installed Templates and on the middle list
s
elect
Silverlight Application

/ Visual C#
.


Figure
1

Create a new Silverlight Application

4.

In the name input area type CRMSilverlightSlider and

type
E:
\
TrainingKit
\
Labs

in the Location
input area.

Note:
The Silverlight Application template is the most generic Silverlight application template
and will be the most common you probably use when creating Silverlight content for CRM.
Silverlight Clas
s Library is the next common used to create class libraries for reuse of code
across different Silverlight applications. The other Silverlight templates that come with the
SDK have additional template code to help you get started if you are building stand
alone type
Silverlight applications.

5.

Click
OK

to start creating the project.

6.

Next, the New Silverlight Application dialog will
be
show
n,

allowing you a chance to either
create a web project to host the application or choose to link to an existing application.


Figure
2

New Silverlight Application Options

7.

Confirm the options are similar to the prior image and click

OK.

8.

The project
will

now be created and the MainPage.xaml
will

be showing in the designer area.

9.

In the center of the designer surface, right click and select Properties so we can adjust the
background to coordinate with the CRM style.

10.

In the search area t
ype “Back” as in Background and the property list shown should filter and
show Background.


Figure
3

Find Background

Note:
Property Search is a quick way to find a property on a control that has a lot of different
options.

11.

In the
value for Background


replace White with #
FFF6F8FA

12.

Next, i
n the Toolbox, locate the Slider Control

and drag it onto the page.


Figure
4

Locate the Slider control

Note:
A quick way to find a control in the Toolbox is to select any control and then start typing
the name of the control you are looking for. If you type Slider it will take you right to the
slider control in the list.

13.

Select the Slider control on the designe
r, right Click and Select Properties.


Figure
5

Select the Slider control

14.

In the Property panel search input
area, type Margin to locate the Margin property.

15.

Type 0 into the Margin property value to indicate you don’t wish to have

any margin applied.

Note:
It’s also possible to modify this value using Microsoft Expression Blend as well as simply
typing the value in the XAML.

16.

In the Property Panel type Width to locate the Width property.

17.

Type 300 into the value of the Width property
.

18.

From the Build menu, select Build Solution

19.

At this
point,

you should have a successful build and have completed building a very basic
Silverlight application. In future steps we will load this into CRM and also hookup the slider to
the
number of employe
es field.




Task 2


Creating the Web Resource for the Slider Control

Silverlight applications are hosted by Microsoft Dynamics CRM 2011 as Web Resources. Web Resources
are created

in the context of a CRM Solution and make it easier to deploy Silverlight to customer servers
and offline end users. In this task, you will create a new Web Resource to host the custom Slider control
you just
built in the previous task
.

1.

Launch Internet Ex
plorer and navigate to
http://CRM/Contoso11
.

2.

Navigate to
Settings | Customization

| Customizations

| Publishers
.
We are going to create a
publisher for ABC’s Silverlight Components.

Publishers allow setting a specific prefix on Web
Resources that are unique to a product or company. Each Solution has an associated publisher.

3.

Click New to launch a new window to create a Publisher.

4.

Type
ABC Gym Silverlight Team

in the Display Name fi
eld.

5.

Change the Prefix field from
“new” to “abcgym”

6.

Click Save and Close to create the publisher.

7.

Navigate to
Settings |

Customization |

Solutions
.

8.

Click New to create a new solution that will
contain the

custom slider control making it easier to
reuse.

9.

On

the new Solution form, provide the information to match the following image. Use CRM
Slider Control for the name and select
ABC Gym Silverlight Team

for the
publisher

and 1.0.0.0
for the Version
.


Figure
6

Create new solution

10.

Cli
ck Save to create the solution.

11.

Click Add New on the toolbar and select Web Resource.


Figure
7

Adding a new Web Resource

12.

In the
input areas for the Web Resource provide the following values.


Figure
8

Create new Web Resource

13.

Click

the Browse button and navigate to the folder where you created the Silverlight
application. Most
likely,

this is E:
\
TrainingKit
\
Labs
\
CRM
Silverlight
Slider
.
W
eb

and locate the
ClientBin folder within the web project. Select
CRMSilverlightSlider
.xap from the list of files and
click OK.

14.

Click Save to upload the file to the CRM server.

15.

Click the Publish button to publish the Web Resource. Leave the dialog open, as we will use it
later to upload updates and leaving it open is ea
sier when you are doing repetitive updates.



Task 3


Add the Slider control to the form

In this task you will modify the form for Gym Locations to use the slider control for input of the
numberofemployee
s

field.

1.

Navigate to
Workspace |
Staff and Members

|
Locations
.

2.

C
lick on one of the rows
and double click
to open the record.

3.

On the ribbon c
lick

the

Customize tab.

4.

Click the Form button to open the Location form in the designer.

5.

In the field explorer locate the No. of Employees field and drag it onto the

form under the
Manager field.


Figure
9

Locate No. of Employees

6.

On the Ribbon, change to the Insert tab.

7.

Click the Web Resource button on the Insert tab to launch the Web Resource lookup dialog.


Figure
10

Insert Web Resource

8.

In the
Web resource
field click Search.

9.

Select CRM Slider control from the list of controls.


Figure
11

Select Slider Web Resource

10.

In the Name field type NoEmployeeSlider

11.

I
n the Label field type “No. of E
mployees”.

12.

Confirm the fields match the following image.


Figure
12

Setup Web Resource

13.

Change to the Formatting tab

14.

Change the layout to one column

15.

In the Row Layout section make the number of rows 1.

16.

In the Silverlight Contro
l Properties section change size to Specific Size and provide 30
5

for the
width and 50 for the height.

17.

Confirm that the formatting table values look like the following image.


Figure
13

Formatting Options

18.

Click OK to finish adding

the Slider control to the form.

19.

On the main form, click the Home tab

on the ribbon

and then
Click Save.

20.

Click Publish to make the change visible.

21.

Click S
ave and Close to close the form.


Exercise 1 Verification

In order to verify that you have correctly performed all steps of
E
xercise

1
, proceed as follows:

Verification 1

In this verification, you will confirm the slider is working on the form.

1.

Navigate to
http://crm/contoso11

2.

Select
Workplace |
Staff and Members |
Locations

from the site navigation

3.

Open the first Location on the list

4.

Confirm you are able to see the Slider control on the form

Note:
The slider is not fully functional yet and hooked up to change the value
. T
hat
will be
done in the next exercise.




Exercise 2: Interacting with the CRM
Form

Important
:

In this Exercise navigate to
http://crm/Contoso11



In this exercise you will
use the HTML Bridge that is part of the Silverli
ght runtime to interact with the
CRM form to set the value when the slider changes. The HTML Bridge will allow the Silverlight
application to make calls to the CRM client scripting API.


Task 1
-

Open the solution you created in Exercise 1 in Microsoft
Visual Studio

In this task, you are going to open the solution you created in Exercise 1. If you did not complete
Exercise 1 you can open the completed solution from
E:
\
TrainingKit
\
Labs
\
Silverlight
\
Sources
\
Ex1
-
Slider
\
End
\
CRMSilverlightSlider
.sln
. The code

from Exercise 1

was a functional Silverlight application
that had a Slider control. The control however, was not yet hooked up to any form field.



Task 2


Set the value when the Slider Changes

In this task, you will add an event handler to the Slider c
ontrol that gets called whenever the value
changes. When the value changes you will use the HTML bridge to call the CRM client scripting API to
set the value of the field on the form. In this exercise, we will work with a hard coded field
numberofemploye
es that is on the Account entity.

1.

Double click on the Slider in the designer. This will cause a Value Changed event handler to be
hooked up to a shell method in the code behind.

2.

Insert the following using statement into MainPage.xaml.cs

C#

using System.Wi
ndows.Browser;

3.

L
ocate the slider1_ValueChanged method and insert the following code into the method.

C#

ScriptObject xrm = (ScriptObject)HtmlPage.Window.GetProperty("Xrm");

ScriptObject page = (ScriptObject)xrm.GetProperty("Page");

ScriptObject pageContext

= (ScriptObject)page.GetProperty("context");



4.

The code you just inserted uses the HTML Bridge via the HTMLPage class to access the client
scripting model and get a reference to the Xrm.Page.context property.

5.

You can also use the Dynamic Language Runtime

along with the dynamic keyword to interact
with the CRM client scripting API. Comment out the lines you just inserted and replace them
with the following code.

C#




dynamic xrm = (ScriptObject)HtmlPage.Window.GetProperty("Xrm");



6.

Add a reference to
Microsoft.CSharp.

7.

Now that you have xrm as a dynamic value you can simply reference the objects in the client
object model by name in a similar fashion to how you would do it directly from Jscript.

8.

Insert the following code into the handler to get a refer
ence to the numberofemployees
attribute.

C#

var numAttr = xrm.Page.data.entity.attributes.get("numberofemployees");


9.

Next, using the reference to the data attribute use the setValue method to set the value. Insert
the following code into the handler to h
andle setting the value from the value on the slider.

C#


numAttr.setValue(Math.Round(slider1.Value, 0));


10.

Build the application by selecting
Build | Build Solution

from the toolbar.

11.

Upload the updated application to CRM and Publish the Web Resource.

Navig
ate to
Settings |
Customization

|
Solutions

and double click on CRM Slider solution to open it.

12.

Select Web Resources in the left navigation

13.

In the list of Web Resources double click on CRM Slider Control

14.

Click the Browse button on the Upload File item. N
avigate to the .XAP file location we used in
the prior exercise

15.

Click Save to update the Web Resource

16.

Click Publish to publish the change to the Web Resource.


Exercise 2 Verification

In order to verify that you have correctly performed all steps of
E
xer
cise

2
, proceed as follows:

Verification 1

In this verification, you will confirm the slider is working on the form.

1.

Navigate to
http://crm/contoso11

2.

Select
Workplace
| Staff and Members
| Locations

from the site navigation

3.

Open the first Location on the list

4.

Confirm you are able to see the Slider control on the form.

5.

Move the slider and confirm the value in the other No. of employee field is changing.


Exercise 3: Using
the

Data Parameter

Important
:

In this Exercise navigate to
http://crm/Contoso11



In

this exercise you will modify the custom Slider control from Exercise 2 to allow it to determine the
field it is working with at runtime. So far in the
exercises it has been hard coded to
numberofemployees.
Microsoft Dynamics CRM 2011 allows spe
cification of a Data
parameter for

each
use of the Web Resource on a form. By using the Data parameter you can pass in the name of the field
the Slider should be

representing.



Task 1
-

Open the so
lution you created in Exercise 2
in Microsoft Visual Studio

In this task, you are going to open the solution you created in

Exercise 2
. If you did not complete
Exercise 1 you can open the completed solution from
E:
\
Tra
iningKit
\
Labs
\
Silverlight
\
Sources
\
Ex2
-
Slider
\
End
\
CRMSilverlightSlider
.sln
. The code from Exercise 2

was a functional Silverlight application
that had a Slider control.
In Exercise
2,

a solution was also created in CRM and the Silverlight application
was u
ploaded as a Web Resource. If you skipped that step you also need to import the
CRMSilverlightSlider solution that is in E:
\
TrainingKit
\
Labs
\
Silverlight
\
Sources
\
Ex2
-
Slider.



Task 2


Modify the Web Resource on the Account form

In this task, you will
modi
fy the Slider Web Resource on the Account form to pass the name of the
field
to the Silverlight control. Microsoft Dynamics CRM 2011 allows specification of a Data parameter on
each Web Resource placed on a form. The contents of this field is passed to t
he Silverlight application as
part of the init parameters.

1.

Navigate to
Workplace

| Staff and Members

| Location
s

(remember location is what Account
has been renamed to) and open up the first records form.

2.

Change to the
Customize
tab and click Form
from the ribbon.

3.

Locate the slider control on the form and double click on it to open the properties page.

4.

Locate the
Custom Parameter (d
ata
)

property
on the form Web Resource property page
and
input “numberofemployees” into the Data property field.

5.

Click
OK to save the change to the field properties.

6.

Click Save on the Main form dialog to save the change to the form.

7.

Click Publish to make the change visible to users of the form.


Task 3


Capture Data parameter on application startup

In this task, you will
modify the Slider Silverlight application to capture the value of the Data parameter
and store it in the application Resources. The Data parameter is passed to the Silverlight application as
an init parameter. The init parameters are available to the Si
lverlight application in the application
startup event handler. By adding the value to the application resources it is easy to use the value later.
There are other approaches you could use to store the value for use later such as a static variable.


1.

Open

the app.xaml.cs
in the Silverlight application
.


Figure
14

Open App.xaml.cs

2.

In the app.xaml.cs file add the following helper method that will enumerate each of the values
in the init parameters dictionary.

For each value, the
value will be stored into the application
level Resources collection and prefixed by InitParam_ to keep them unique.

C#

public

void

CaptureInitValues(
IDictionary
<
string
,

string
>

values)

{


foreach

(
var

val

in

values)


{



if

(!
Application
.Current.Resources.Contains(
"InitParm_"

+

val.Key))


{


Application
.Current.Resources.Add(
"InitParm_"

+

val.Key,

val.Value
);


}



}

}



3.

In the app.xaml.cs file locate the Application_Startup method. This method is called

during the
startup of the Silverlight application. The second parameter “e” provides access to the
StartupEventArgs class which contains the init parameters.

4.

Insert the following code into the Application_Startup method.

C#

CaptureInitValues(e.InitParams
);



Task 4


Change to set the value on the configured field

In this task, you will modify the Slider Silverlight application

to use the field passed in the init parameters
to set the field value
.


1.

Open the MainPage.xaml.cs file and locate the slider1_Val
ueChanged method. This method
needs to be modified to take the value passed on the Web Resources when it was configured
on the form.

2.

Locate the line of code shown in the following image where the name of the field is hard
coded.


Figure
15

Locate the hard coded field name

3.

Insert the following line of code to retrieve the field name from the application level
resources.

C#

var fieldName = Application.Current.Resources["InitParm_
data
"];


4.

In the line that gets the attr
ibute, replace “numberofemployees” with
fieldName
.

5.

After changing the code confirm the code looks like the following image.


Figure
16

Updated code

6.

Build the solution in Visual Studio

7.

Upload the updated application to CRM and Publ
ish the Web Resource. Navigate to
Settings
|
Customization |
Solutions

and double click on CRM Slider solution to open it.

8.

Select Web Resources in the left navigation

9.

In the list of Web Resources double click on CRM Slider Control

10.

Click the Browse button
on the Upload File item. Navigate to the .XAP file location we used in
the prior exercise

11.

Click Save to update the Web Resource

12.

Click Publish to publish the change to the Web Resource.



Exercise 3 Verification

In order to verify that you have correctly performed all steps of
E
xercise

3
, proceed as follows:

Verification 1

In this verification, you will confirm the slider is working on the form.

1.

Navigate to
http://crm/contoso11

2.

Select
Workplace |
Staff and Members |
Locations

from the site navigation

3.

Open the first Location on the list

4.

Confirm you are able to see the Slider control on the form.

5.

Move the slider and confirm the value in the other No. of employee field is changing.



Exercise
4
:
Generating Typed Entity
Classes

Important
:

In this Exercise navigate to
http://crm/Contoso11



In this exercise you will
generate typed classes for working with the CRM data from Silverlight.
Microsof
t Dynamics CRM 2011 exposes an OData endpoint for use with Silverlight applications. The
OData service includes metadata that allows for generation of typed classes representing the entities in
the CRM system.

Task 1



Save the metadata from the CRM Serv
er

In this
task,

you will
save the metadata from the CRM server for use with the DataSvcUtil utility
.

For on
-
premise installs it is possible to just use the built
-
in Visual Studio Add Service Reference feature,
however this will not work if you are not using Active Directly integrated authentication. In general the
save of the metadata and running DataSvcUtil works in all deployment configurations.

1.

Navigate to
http://crm/co
ntoso 11
.

2.

Navigate to
Settings | Customization

| Customizations
| Developer Resources

3.

In the lower part of the screen
click on the icon next to the Organization Data Service


Figure
17

Link to download Metadata


Note:
The CSDL is the conceptual representation of the data model and is part of OData to
make that available. If you have done any development with ADO.NET Entity Framework, the
CSDL published by an OData service is the same used in
an

Entity Data Model concep
tual layer.
The CSDL is used as input to the DataSvcUtil to produce the typed classes.

4.

Press the

Alt

key
-

and
File |
Save
As

to save a copy of the metadata locally

to
e:
\
TrainingKit
\
Labs
\
OrganizationData.csdl
.

Use the following options for file location and type
of file.
It’s important that you

change the File type to All Files and
save the file with the .csdl
extension otherwise the utility will not run against the file
.


Figure
18

Save as .csdl file

5.

Run the DataSvcUtil utility against the saved CSDL file by running the following command from a
Windows Command Prompt

(Windows
Start | Run

).

Command Line Command

"%windir%
\
Microsoft.NET
\
Framework
\
v4.0.30319
\
datasvcutil.exe" /dataservic
ecollection
/Version:2.0 /language:CSharp /in:
e:
\
TrainingKit
\
Labs
\
OrganizationData
.
csdl
/out:
e:
\
TrainingKit
\
Labs
\
OrganizationData
.cs

Note:
If you run this from a directory other than the same one you saved the CSDL file to you
must update the /in: paramete
r file name to include the correct location of the file.

6.

After the command completes it will have written a .cs file out that will contain a class for each
entity it found in the data model. The following is an example of what messages should look
like wh
en the tool completes.


Figure
19

Successful DataSVcUtil executation


Task 2


Add Generated Types to a Project

In this task, you will create a new project and add the generated types to the project. The generated
types file can

be added directly to a Silverlight application project or to its own class library project. A
class library project makes it easier to re
-
use in multiple Silverlight applications.

1.

Start Microsoft Visual Studio 2010 from the start menu

2.

Click
File | New

|

Project

3.

Choose Other Project Types | Visual Studio Solutions from the left side list of Installed
Templates.

4.

Select
Blank Solution

in the list of templates in the middle of the dialog.

5.

Type

ABCGymSilverlight

for the name of the solution.

6.

In the locati
on field use
E:
\
TrainingKit
\
Labs

or another location that you will remember.

7.

Click

OK

to create the Solution.

8.

From the Solution Explorer, Right Click on the Solution and select
Add | New Project
.

9.

Select

Silverlight

on the left side list of Installed Temp
lates

10.

Select
Silverlight Class Library

in the center list of templates.

11.

Type

ABCOData

in the name field

12.

Click

OK

to create the project.

13.

On the Silverlight version selection dialog, confirm it has Silverlight 4 selected and click OK

14.

In the ABCOData Project,

select References and click Add Reference

15.

Locate
System.Data.Services.Client

and click OK to add the reference.

16.

Right click on the ABCOData project and select
Add | Existing Item
.

17.

In the add existing dialog browse to the location of the file output from D
ataSvcUtil

(typically
e:
\
TrainingKit
\
Labs
\
OrganizationData.cs)

, select the file and click OK to add it to the project.

18.

From the Build menu select Build Solution



Exercise
5
: Accessing data using OData

Important
:

In this Exercise navigate to
http://crm/Contoso11


In

this exercise you will use the OData endpoint published by CRM to access the data for the life style
profiles.
The OData endpoint provides a similar server style interaction with the CRM Data. The typed
classes generated in Exerc
ise 4 will be used in the queries.



Task 1
-

Open the solution you created in Exe
rcise 4

in Microsoft Visual Studio

In this task, you are going to open the solution you created in Exercise
4
. If you did not complete
Exercise 1 you can open the completed
solution from
E:
\
TrainingKit
\
Labs
\
WCF
\
Sources
\
Ex4
-
LifeStyleProfile
\
End
\

ABCGymSilverlight
.sln
.



Task 2


Add Silverlight Application for LifeStyle Profile

In this task, you will add a
new Silverlight application that will be the LifeStyle Profile
.

You w
ill then add
a reference to the ODataLib that was created in Exercise 4.

1.

Right click on Solution Explorer and click
Add | New Project

2.

Select Silverlight from the list of Installed Templates and pick Silverlight Application from the
middle list. In the Nam
e field for the project type SLLifeStyleProfile and click
OK

to create the
project.

3.

Click
OK

on the next
dialog for creating a Website to host the control.

4.

Inside the SLLifeStyleProfile project right click on the References node and select Add
Reference.

5.

C
lick on the Project tab and select ABCOData form the list.

This sets up the reference to the
class library that has the generated proxy classes.




Task 3


Add an Accordion Control to Show the Profiles

In this task, you will
an Accordion control from the

Toolbox and set it up for displaying the data from the
profiles.


1.

Locate the Accordion control in the Toolbox and drag it onto the MainPage design surface.

2.

Right click Properties on the Accordion control.

3.

Locate the Margin property and clear its value.

4.

L
ocate the Height property and clear its value.

5.

Locate the Width property and clear its value.

6.

Locate the HorizontalAlignment property and set it to Stretch

7.

Locate the VerticalAlignment propert
y

and set it to
Stretch

8.

Locate the ExpandDirection property and
set it to Left

9.

Open the App.xaml file and add the following to the namespace definition

XAML

xmlns
:
d
=

http://schemas.microsoft.com/expression/blend/2008


xmlns
:
mc
="http://schemas.openxmlformats.org/markup
-
compatibility/2006"

mc
:
Ignorable
="d"




10.

After adding the app.xaml namespace definitions
, it
should look like the following


Figure
20

After insert of namespace

11.

Locate the
Application.Resources section in app.xaml


Figure
21

Application Resources

12.

Next, we need templates for the items in the Accordion control.
Typically,

a designer would
provide the XAML for this. Insert the following designer cre
ated XAML into the
Applicatio
n.Resources element in the App.xaml file.

XAML

<
DataTemplate

x
:
Key
="LifeStyleDetailTemplate">


<
Grid

Margin
="3,0">


<
Grid.RowDefinitions
>


<
RowDefinition

Height
="Auto"

/>


<
RowDefinition

Height
="Auto"

/>


<
RowDefinition

Height
="Auto"

/>


<
RowDefinition

Height
="Auto"

/>


<
RowDefinition

Height
="Auto"

/>


</
Grid.RowDefinitions
>



<
Grid.ColumnDefinitions
>


<
ColumnDefinition

Width
="150"

/>


<
ColumnDefinition

Width
="Auto"

/>


<
ColumnDefinition

Width
="Auto"

/>


<
ColumnDefinition

Width
="Auto"

/>


</
Grid.ColumnDefinitions
>


<
TextBlock

TextWrapping
="Wrap"



Text
="Profile

Year"



VerticalAlignment
="Center"



d
:
LayoutOverrides
="Width"




HorizontalAlignment
="Left"



FontSize
="18.667"

/>


<
TextBlock

TextWrapping
="Wrap"



Text
="{
Binding

abc_name
}"



d
:
LayoutOverrides
="Width,

Height"



Grid.Column
="1"



Margin
="15,0,0,0"



HorizontalAlignment
="Left"



VerticalAlignment
="Center"



FontSize
="18.667"

/>



<
CheckBox

x
:
Name
="checkBoxDiabetes"




Content
="Diabeties"



d
:
LayoutOverrides
="Width,

Height"



HorizontalAlignment
="Left"



VerticalAlignment
="Center"




Grid.Row
="1"



Margin
="0,20,0,0"



IsChecked
="{
Binding

abcgym_Diabetes
}"

IsEnabled
="Fal
se"

/>


<
CheckBox

x
:
Name
="checkBoxRegularExercise"



Conten
t
="Regular

Exercise"



d
:
LayoutOverrides
="Width,

Height"



HorizontalAlignment
="Left"



VerticalAlignment
="Center"



Grid.Row
="2"



Margin
="0,5,0,0"



IsChecked
="{
Binding

abcgym_RegularExercise
}"



IsEnabled
="False"

/>


<
TextBlock

HorizontalAlignment
="Left"



TextWrapping
="Wrap"




Text
="Days

exercise

per

week"



d
:
LayoutOverrides
="Height"



Grid.Row
="3"



Margin
="10,0,0,0"



VerticalAlignment
="Center"

/>


<
TextB
ox

x
:
Name
="txtBoxExercisePerWeek"




HorizontalAlignment
="Left"



TextWrapping
="Wrap"



Text
="{
Binding

abcgym_DaysExerciseperWeek
}"



d
:
LayoutOverrides
="Height"



Grid.Row
="3"



Grid.Column
="1"



Width
="100"



VerticalAlignment
="Top"



IsReadOnly
="True"

/>


<
TextBlock

HorizontalAlignmen
t
="Right"



TextWrapping
="Wrap"



Text
="Average

hours

per

exercise

session"



d
:
LayoutOverrides
="Height"



Grid.Row
="4"



Margin
="1
0,0,0,0"

/>


<
TextBox

x
:
Name
="txtBoxHoursExercise"


HorizontalAlignment
="Left"



TextWrapping
="Wrap"



Text
="{
Binding

abcgym_AverageHoursperExerciseSession
}
"




d
:
LayoutOverrides
="Height"



Grid.Row
="4"



Grid.Column
="1"



Width
="100"



VerticalAlignment
="Top"



IsReadOnly
="True"

/>


<
CheckBox

x
:
Name
="checkBoxSmoker"




Content
="Smoker"



HorizontalAlignment
="Left"



d
:
LayoutOverrides
="Height"



Grid.Row
="1"




Grid.Column
="2"



Margin
="0,20,0,0"



IsChecked
="{
Binding

abcgym_Smoker
}"



IsEnabled
="False"

/>


<
TextBlock

HorizontalAlignment
="Left"




TextWrapping
="Wrap"



Text
="Years

smoking"



d
:
LayoutOverrides
="Height"



Grid.Row
="2"



Grid.Column
="2"



Margin
="10,0,0,0"



VerticalAlignment
="Center"

/>


<
TextBox

x
:
Name
="txtBoxYearsSmoking"




HorizontalAlignment
="Left"



TextWrapping
="Wrap"



Text
="{
Binding

abcgym_Y
earsSmoking
}"



d
:
LayoutOverrides
="Height"



Grid.Row
="2"



Grid.Column
="3"



Width
="100"



VerticalAlignment
="Top"



IsReadOnly
="True"

/>


<
TextBlock

HorizontalAlignment
="Left"



TextWrapping
="Wrap"



Text
="Packs

per

week"



d
:
LayoutOverrides
="Height"



Grid.Row
="3"



Grid.Column
="2"



Margin
="10,0,0,0"



VerticalAlignment
="Center"

/>


<
TextBox

x
:
Name
="textBoxPacksPerWeek"




HorizontalAlignmen
t
="Left"



TextWrapping
="Wrap"



Text
="{
Binding

abcgym_PacksperWeek
}"



d
:
LayoutOverrides
="Height"



Grid.Row
="3"



Grid.Column
="3"




Width
="100"



VerticalAlignment
="Top"



IsReadOnly
="True"

/>


</
Grid
>


</
DataTemplate
>


<
DataTemplate

x
:
Key
="LifeStyleHeaderTemplate">


<
Grid
>


<
TextBlock

TextWrapping
="Wrap"




Text
="{
Binding

abcgym_name
}"



d
:
LayoutOverrides
="Width,

Height"



FontSize
="13.333"

/>


</
Grid
>


</
DataTemplate
>



13.

In the MainPage.xaml file, a
dd the following properties onto the Accordion con
trol to reference
the templates and set the ItemsSource binding.

These three lines set the templates to use and
bind it to the Data Context

XAML

ItemTemplate
="{
StaticResource

LifeStyleHeaderTemplate
}"

ContentTemplate
="{
StaticResource

LifeStyleDetailTemplate
}"

ItemsSource
="{
Binding
}"


14.

Confirm the accordion XAML looks similar to the following image.


Figure
22

After Setup of Binding and Templates


Task
4


Setup Data Service Context

In this task, you will setup a data services context that will be used to perform the queries against the
Lifestyle profile.

1.

With the
SLLifeStyleProfile project
, add a reference to

System.Data.Services.Client
.

2.

Add the followi
ng using statement
s

to MainPage.xaml.cs

C#


using

Microsoft.Crm.Sdk.Data.Services;


using

System.Windows.Browser;


using

System.
Data.Services.Client;



3.

Insert the following member variables into MainPage.xaml.cs that will be used

to hold the
server URL and the data context for working with the OData service.

C#



private

String

_serverUrl;


private

Contoso11
Context

_context;





4.

Insert the following helper methods into MainPage.xaml.cs
. These methods help build the
server url by interacting with the Page context.

C#




public

static

String

GetServerUrl()


{


String

serverUrl

=

String
.Empty;




//Try

to

get

the

ServerUrl

from

the

Xrm.Page

object


serverUrl

=

GetServerUrlFromContext();




return

serverUrl;


}




///

<summary>


///

Attempts

to

retrieve

the

ServerUrl

from

the

Xrm.Page

object


///

</summary>


///

<returns></returns>


priv
ate

static

String

GetServerUrlFromContext()


{


try


{


//

If

the

Silverlight

is

in

a

form,

this

will

get

the

server

u
rl


ScriptObject

xrm

=

(
ScriptObject
)
HtmlPage
.Window.GetProperty(
"
Xrm"
);



ScriptObject

page

=

(
ScriptObject
)xrm.GetProperty(
"Page"
);


ScriptObject

pageContext

=

(
ScriptObject
)page.GetProperty(
"con
text"
);




String

serverUrl

=

(
String
)pageContext.Invoke(
"getServerUrl"
);




return

serverUrl;


}


catch


{


return

String
.Empty;


}


}


5.

Insert the following event handler hookup
into the constructor for MainPage.xaml.cs after
the InitializeComponent() call.

C#




this
.Loaded

+=

new

RoutedEventHandler
(MainPage_Loaded);


6.

Insert the
following loaded event handler that will get the server URL using the helper
classes and call the load profiles method.

C#

void

MainPage_Loaded(
object

sender,

RoutedEventArgs

e)

{


//Get

the

ServerUrl

(ServerUrl

is

formatted

differently

OnPremise

than

On
Line)


_serverUrl

=

GetServerUrl();



if

(!
String
.IsNullOrEmpty(_serverUrl))


{


//Setup

Context


_context

=

new

Contoso11Context
(
new

Uri
(


String
.Fo
rmat(
"{0}/xrmservices/2011/organizationdata.svc/"
,

_serve
rUrl),

UriKind
.Absolute));



//This

is

important

because

if

the

entity

has

new

attributes

added

the

code

will

fail.


_context.IgnoreMissingProperties

=

true
;




LoadExistingProfiles();

}

}


7.

Add the following shell of a load method to MainPage.xaml.cs

C#



public

void

LoadExistingProfiles()



{







}



8.

Next, we need to build a query for the profiles. First, we need to create a member variable
of type
DataServiceCollection. Add the following variable.

C#


private

DataServiceCollection
<
abcgym_lifestyleprofile
>

_profiles;



9.

Insert the following met
hod into the LoadExistingProfile method to define the query for the
profiles.

C#


var

query

=

from

profile

in

_context.abcgym_lifestyleprofileSet


select

profile;


10.

Next, we are going to create an instance of the
DataServiceCollection, hookup the event
handler for completion and start the load of the data.

C#



_profiles

=

new

DataServiceCollection
<
abcgym_lifestyleprofile
>();


_profiles.LoadCompleted

+=

new

EventHandler
<
LoadCompletedEventArgs
>(profil
es_LoadCompleted);


_profiles.LoadAsync(query);


11.

Next, add the profile_LoadCompleted event handler that will be called

when the query is
finishes. This method will add a dummy new record to the collection and set the data
context to the collection that was retrieved.

C#



void

profiles_LoadCompleted(
object

sender,

LoadCompletedEventArgs

e)


{


_
profiles.Add(
new

abcgym_lifestyleprofile
()

{



abcgym_name

=

"New"

});


accordion1
.DataContext

=

_profiles;


}


12.

Build the solution in Visual Studio.

Task 5


Add the Life Style Profile to the Form

In this task, you will
a
dd the Silverlight Lifestyle Profile control to the form.


1.

Open
http://crm/Contoso11

in Internet Explorer

2.

Navigate to
Settings | Customization

|
Customizations |

Solutions
.

3.

Click
New

to create a new solution that will contain the Silverlight Lifestyle Profile control
making it easier to reuse.

4.

On the new Solution form,
u
se Silverlight Lifestyle Profile for the name and select
ABC Gym
Silverlight Team

for the publisher, and 1.0.0.0 for

the Version.

5.

Click
Save

to create the solution.

6.

Click
New

| Web Resource

on the toolbar and select Web Resource.


Figure
23

Adding a new Web Resource

7.

In the
Name
input area
, enter sllifestyleprofile
.

8.

Select Silverlight for the
Type.

9.

Click
Browse

and navigate to the ClientBin folder of the SLLifeStyleProfile.Web project.

10.

Click
Save

and then
Publish

11.

Click
Save and Close

to close the Web Resource

12.

On the Solution Toolbar click
Add Existing

13.

Select
Entity

from the Component Type drop

down

14.

Locate the
Person

entity, select it and click
OK
.

15.

In the Solution window, expand the Entities node in the left navigation and expand
Person
.

16.

Select
Forms
, and Click on the
Main

Form
in the list
to open the form editor

17.

Select the
Insert

Tab on the ribbon and click the
One Column

button in the Tab group.

18.

Locate the inserted tab, double click on it to open the Tab Properties.

19.

Modify the name from Tab to Silverlight Lifestyle Profile

20.

Click
OK

21.

Click in the center of the new tab, then Click

the
Web Resource

button on the Insert ribbon

22.

In the Web Resource dialog, type
abcgym_sllifestyleprofile
in the Web resource field and hit the
tab key to al
low it to auto resolve the name

or use the lookup button to find the same web
resource.

23.

Type sllifes
tyleprofile in the
Name

field.

It will auto fill the Label field, if you were going to show
the label on the form you would want to customize it to be user friendly.

24.

Check the “Pass record object
-
type code and unique identifier option

25.

Click on the
Formatt
ing

tab to change to the formatting options

26.

In the Row Layout section change Number of Rows to 10

27.

In the Silverlight Control Properties section change the
Size

dropdown to
Specific Size

and
provide 800 for width and 400 for height.

28.

Click
OK

to close the We
b Resource.

29.

Click the
Home

Tab, and then
Save
, followed by
Publish

30.

Close the Person form editor.


Exercise 5 Verification

In order to verify that you have correctly performed all steps of
E
xercise

5
, proceed as follows:

Verification 1

In this
verification, you will confirm the Silverlight Lifestyle Profile is working on the form.

1.

Navigate to
http://crm/contoso11

2.

Select
Workplace |
Staff and Members |
People

from the site navigation

3.

Open the first person on t
he list

4.

In the form left navigation select the
Common | Lifestyle

Profiles.

5.

If there are no records, click
Add

and create records for 2007,2008,2009 and 2010

choose a
few options on each of the records you create.

6.

In the form left navigation select
Silverl
ight Lifestyle Profile

7.

Click on 2008, 2009, etc to see the data you just input shown in the Silverlight control. If the
data doesn’t show sometimes it is necessary to press F5 to refresh the browser.



Summary

In this lab you have ex
p
erienced using

Silv
erlight to extend Microsoft Dynamics CRM 2011’s user
interface. Silverlight provides a rich way to extend the user interface. Silverlight can be used for a
simple control like you built with the slider control or larger full page content. Silverlight ca
n interact
with the form to work with the entity data or the form controls. Silvelright applications can use the
OData
REST

endpoint to work with data other than the primary entity on the form.
Silverlight
applications are stored on the CRM server as Web

Resources.

The Web Resources work with the
Solution Framework to allow the Silverlight applications to be distributed with the other customizations.
In addition to being able to build rich user experiences, Silverlight offers developers the productivity

from the tooling built into Visual Studio.