Friday, March 23, 2012

Microsoft Dynamics CRM 2011 for Developers | Plug-ins

Contents

  1. Introduction
  2. Common Uses of Plug-ins
  3. Plug-ins Basics
    1. Event Framework
    2. Event Execution Pipeline
    3. Pipeline Stages
    4. Message Processing
    5. Inclusion in Database Transactions 
    6. Plug-in Isolation
    7. Trusts
  4. Develop Plug-ins
  5. Register Plug-ins

Introduction

A plug-in is .Net assembly that can be used to intercept events generated from the CRM system. Plug-ins subscribe to a set of events and run when the events occur regardless of how the event raised (or the method that is used to perform the activity that raised the event).

Any number of plug-ins can be associated with a given entity and event. When multiple plug-ins are registered for the same event on the same entity, they are called in a sequence based on the order specified on the step registration. This value is specified as the Rank and it is supplied when the plug-in is registered. This allows developer control over the sequence.

Common Uses of Plug-ins

Plug-ins have many uses like:

  • Performing complex business logic data validation
  • Performing complex update routines on CRM entities and/or attributes when it is impractical to use JavaScript.
  • Grabbing data from another system and updating CRM when an entity instance is being created or updated.
  • Updating another system programmatically from CRM

Plug-ins Basics

Event Framework Event framework is the term that is used to describe the technology and mechanisms available in Microsoft Dynamics CRM to enable you to extend or customize functionality with custom code. Your custom code will run on top of Dynamics CRM either synchronously as part of the main Microsoft Dynamics CRM execution path, or asynchronously from a managed queue.

Event Execution Pipeline Event framework executes plug-ins based on a message pipeline execution model. A user action in the Microsoft Dynamics CRM Web application or an SDK method call by a plug-in or other application results in a message being sent to the organization Web service. The message contains business entity information and core operation information. The message is passed through the event execution pipeline where it can be read or modified by the platform core operation and any registered plug-ins.

The event execution pipeline processes events either synchronously or asynchronously. The platform core operation and any plug-ins registered for synchronous execution are executed immediately. Synchronous plug-ins that are registered for the event are executed in a well-defined order. Plug-ins registered for asynchronous execution are queued by the Asynchronous Queue Agent and executed at a later time by the asynchronous service.

Pipeline Stages The event execution pipeline is divided into multiple stages, four of them are available to register custom developed plug-ins. Multiple plug-ins that are registered in each stage can be further be ordered (ranked) within that stage during plug-in registration.

Event

Stage name

Stage number

Description

Pre-Event Pre-validation 10
  • For plug-ins that execute before the main system operation.
  • Plug-ins may execute outside the database transaction.
  • For plug-ins run prior to making security checks on the calling user.  
Pre-Event Pre-operation 20
  • For plug-ins that execute before the main system operation.
  • Plug-ins execute within the database transaction.
Platform Core Operation MainOperation 30
  • Dedicated to main system operations.
  • For internal use only, no custom plug-ins can register in this stage.
Post-Event Post-operation 40
  • For plug-ins that execute after the main operation.
  • Plug-ins execute within the database transaction.
Post-Event Post-operation
(Deprecated)
50
  • For Dynamics CRM 4.0 based plug-ins ONLY.

Message Processing as we saw in a previous post, any web service method call is done through OrganizationRequest message. This call raises an event. Information in this message is passed to first plug-in registered for that event. Plug-in receives the message information in the form of context that is passed to its Execute method, where it can be read or modify its contents before passing it to the next registered plug-in for that event and so on. The message then passed to the platform core operation. After the core platform operation has completed, the message is then known as the OrganizationResponse. This response is passed to the registered post-event plug-ins which may modify it before a copy of the response is passed to any registered asynchronous plug-ins. Finally, the response is returned to the application or workflow that initiated the original Web service method call.

Because a single Microsoft Dynamics CRM server can host more than one organization, the execution pipeline is organization specific. Plug-ins registered with the pipeline can only process business data for a single organization.

Inclusion in Database Transactions Plug-ins can execute or not execute within the database transaction of the Dynamics CRM platform. Within the plug-in, you can detect that through the IsInTransaction property in IPluginExecutionContext that is passed to the plug-in. Any registered plug-in that executes during the database transaction and that passes an exception back to the platform cancels the core operation. This results in a rollback of the core operation. In addition, any pre-event or post event registered plug-ins that have not yet executed and any workflow that is triggered by the same event that the plug-in was registered for will not execute.

Plug-in Isolation The execution of plug-ins can be in an isolated environment, known as a sandbox, where a plug-in can access and use the organization Web service only. Plug-ins can’t access system resources but can access to external endpoints (only through HTTP and HTTPS). CRM platform collects run-time statistics and monitors plug-ins that execute in the sandbox, if it exceeded certain thresholds or became unresponsive, it kills the sandbox worker process (this makes all currently executing plug-ins in the current organization fail).

Trusts

  • Full trust Plug-ins run outside the sandbox, available in on-premises and internet facing deployments.
  • Partial trust Plug-ins run inside the sandbox, available in all deployments.

Develop Plug-ins

Simply plug-ins are classes that implement the IPlugin interface. You can write a plug-in in any .NET Framework 4 CLR-compliant language.

Now let’s consider a simple case that plug-ins may be its appropriate solution. Let say that your company wants leads to be numbered automatically when they are created. In order to achieve our goal, we will add a custom field to the Lead entity and add it to the form. We will disable this field on the form. We will create a plug-in and register it for the Pre-event for the Create message on the Lead entity. When a lead is created, it will look for the next available number in the system and assign it to the newly created Lead.

Step 1: Create Customizations

Now we will quickly customize the Lead entity and form to accommodate our solution. Navigate to Settings > Customizations > Customize the System. In the left navigation pane, expand Entities, expand Lead, select Fields, and click New.  
In the New for Lead form, set the Display Name to Auto Number, the Type to Whole Number, and then click Save and Close. In the left navigation Pane, select Forms. Click the Main Information form > Drag the field, new_autonumber, to the Name section of the General section. Select the field, click Change Properties, mark the Field is read-only check box, and then click OK. Click Save and Close, and then Publish.

Step 2: Create the Plug-in

1- Open Visual Studio and Create a new project of type Class Library.

2- Add references to Microsoft.Xrm.Client.dll, Microsoft.Xrm.Sdk.dll, and Microsoft.crm.sdk.proxy.dll [located at %SDK%\bin folder].

3- Add references to System.Data.Services, System.Data.Services.Client, System.Runtime.Serialization, and System.ServiceModel.

4- Add reference to Microsoft.IdentityModel.dll from "C:\Program Files\Reference Assemblies\Microsoft\Windows Identity Foundation\v3.5\”. Then go to reference properties and set Copy Local to True for the DLL. The DLL will be included in the package. If you don’t have the dll you need to install Windows Identity Foundation.

5- Make your class implement the IPlugin interface, and implement its member method Execute method. This identifies your class as a plugin to the CRM platform when registering your assembly later. Plug-in code will be placed in the Execute method which takes a parameter of type IServiceProvider. This parameter is a container of many objects that will be utilized by our code.

First get the IPluginExecutionContext. This context object gives you access to all the property values associated with the entity and event context where the method is being executed.

IPluginExecutionContext context = (IPluginExecutionContext) serviceProvider.GetService(typeof(IPluginExecutionContext));


InputParameters property of the context is a collection of the request parameters associated with the event. We use it to check the entity of which the event is fired.



if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
{
Entity entity = (Entity)context.InputParameters["Target"];
if (entity.LogicalName != "lead")
return;


Then we get the OrganizationServiceFactory to use it to create an OrganizationService. We also get the TracingService. Then we edited our auto number field with the next maximum number in the organization. GetMaxLeadNumber is a typical method that passes a QueryExpression to the OrganizationService to get the next max lead number.



IOrganizationServiceFactory orgServiceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
IOrganizationService orgService = orgServiceFactory.CreateOrganizationService(context.UserId);

try
{
entity.Attributes["new_autonumber"] = GetMaxLeadNumber(orgService);
}
catch (Exception ex)
{
tracingService.Trace("xRM_Demo03 | {0}", ex.ToString());
throw;
}
}
}


Now your class should look like:



using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Security;
using System.ServiceModel.Description;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Query;
using System.Collections;

namespace xRM_Demo03
{
public class Plugin:IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
IPluginExecutionContext context =
(IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
{
Entity entity = (Entity)context.InputParameters["Target"];
if (entity.LogicalName != "lead")
return;

IOrganizationServiceFactory orgServiceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService orgService = orgServiceFactory.CreateOrganizationService(context.UserId);
ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

try
{
Random rand = new Random();
entity.Attributes["new_autonumber"] = GetMaxLeadNumber(orgService);
}
catch (Exception ex)
{
tracingService.Trace("xRM_Demo03 | {0}", ex.ToString());
throw;
}
}
}

private int GetMaxLeadNumber(IOrganizationService orgService)
{
QueryExpression qe = new QueryExpression("lead");
qe.ColumnSet.AddColumn("new_autonumber");
qe.AddOrder("new_autonumber", OrderType.Descending);
qe.PageInfo.Count = 1;
qe.PageInfo.PageNumber = 1;

Entity entity = (Entity)orgService.RetrieveMultiple(qe)[0];
if (entity.Attributes["new_autonumber"].ToString()!= string.Empty)
return int.Parse(entity.Attributes["new_autonumber"].ToString()) + 1;
else
return 1;
}
}
}


Now the last step is to sign your assembly. Double click Properties under your plugin project.



xRM_Demo03 - Microsoft Visual Studio (Administrator)_2012-03-19_12-33-32



then click Signing from the left tabs



xRM_Demo03 - Microsoft Visual Studio (Administrator)_2012-03-19_12-34-21



select Sign the assembly checkbox, choose New from the dropbox or choose an existing key. Build the project. Now we are ready to register our plugin into Dynamics CRM.



Step 3: Register the Plug-in







The Dynamics CRM SDK have a tool to register plugins located as a source code at %CRMSDK%\tools\pluginregistration. Open the solution, build it, and run it.



1- Click the Create New Connection on the toolbar. Enter a name for the connection, organization URL, and the email you used for creating this organization.Plugin Registration Tool_2012-03-19_12-20-45



Click Connect, it will ask you for the password.



Connect to CRM Web Service_2012-03-19_12-21-24



Enter your password and click Ok to connect to the CRM organization web service.



After getting connected click Register > Register New Assembly



Plugin Registration Tool_2012-03-19_12-27-20



This will open Register New Plugin dialog.



Register New Plugin_2012-03-19_12-27-57



Click the three dots button in the top right of the dialog, browse to your plugin dll. Ensure that your plugin is listed and checked. Also ensure that you selected Sandbox as isolation mode, and to store your assembly in the Database as shown below.



Register New Plugin_2012-03-19_12-29-50



Click Register Selected Plugins. You will see in the log the steps done by the tool and when it is done it will show message box showing how many assemblies and plugins have been registered (you could have multiple plugins in one assembly). Click Ok.



xRM_Demo03 - Microsoft Visual Studio (Administrator)_2012-03-19_12-36-58



Now select your assembly from the list



Plugin Registration Tool_2012-03-19_12-39-46



and click Register > Register New Step. This will open Register New Step dialog. This dialog used to define mainly the message, the entity, and the stage that your plugin will execute within. We will register for Message Create, Entity lead, Pre-operaton stage. Click Register New Step.



Register New Step_2012-03-19_12-42-08



You will see child step added under your assembly.



Plugin Registration Tool_2012-03-19_12-43-20





Now our assembly is registered and our plugin will run for create messages on the lead entity. Go to the CRM web interface and create a new lead, save it, open it again and see the Auto Number populated.



In this post we explored the plug-in basics, and developed a simple plug-in. To complete the picture, you also explored how to register our plug-in into Dynamics CRM and see it in action.

Tuesday, March 13, 2012

Microsoft Dynamics CRM 2011 for Developers | Creating Custom Reports Using Microsoft SQL Server 2008 Reporting Services

Contents

  1. Introduction
  2. Setup the Development Environment
  3. Report Development Process
  4. Create Custom Reports Using Business Intelligence Development Studio
    1. Create a Custom SQL-Based Report
    2. Create a Custom Fetch-Based Report
  5. Import Custom Reports into Dynamics CRM

Introduction

Microsoft Dynamics CRM provides many out-of-box reports for viewing business data. You can view a list of reports you have access to by navigating to Workplace > My Work > Reports. You can also see a list of all reports available by navigating to Settings > Customization > Customizations > Customize the System > Report [left navigation]. In both lists, you can select a report and click Run Report from the ribbon to preview the report in running mode.

You can create custom reports using one of the out-of-box reports as templates, or create a custom report from scratch. There are two types of reports in Microsoft Dynamics CRM:

  • SQL-Based Reports Use SQL queries to retrieve data from filtered views defined by the system. The default out-of-box reports are SQL-based reports. You can’t deploy SQL-based reports for Dynamics CRM online.
  • Fetch-Based Reports Use FetchXML queries to retrieve data. They are introduced in Dynamics CRM 2011 and can be deployed both on on-premise and online. All reports created using the Report Wizard in the web interface, are fetch-based reports.

Setup the Development Environment

To write custom reports for Microsoft Dynamics CRM you need the following:

  • Microsoft SQL Server 2008 Reporting Services (or 2008 R2) in native mode installation.
  • Business Intelligence Development Studio. This is the report authoring environment in Visual Studio that hosts the Report Designer (available on the Microsoft SQL Server setup CD).
  • Microsoft Dynamics CRM Report Authoring Extension. You will need this when creating a custom fetch-based reports. You can install it from http://www.microsoft.com/download/en/details.aspx?id=27823 or from the BIDSExtension folder in the Microsoft Dynamics CRM setup DVD.

Report Development Process

The following lists the steps for developing custom Microsoft Dynamics CRM reports. You may have to repeat some steps while you develop a report:

  1. Develop a report concept or specification based on what business information is to be displayed.
  2. Decide on the type of report you want to create: SQL-based or Fetch-based. Microsoft Dynamics CRM Online users can only create custom Fetch-based reports.
  3. Download an existing Microsoft Dynamics CRM report definition (.rdl), and modify it or create a new report by using Business Intelligence Development Studio.
  4. Create basic report parameters.
  5. Specify datasets and filtering criteria for retrieving data:
    • For SQL-based reports, create datasets that contain Microsoft Dynamics CRM data obtained from the filtered views.
    • Enable pre-filtering on the primary entities.
  6. Define the basic layout of the report, including headers and footers.
  7. Add report items as required based on the report specification.
  8. Preview the report in Microsoft Visual Studio, and resolve any errors.
  9. Deploy the report to the reporting server by using Microsoft Dynamics CRM.
  10. Run the deployed report to verify.

Create Custom Reports Using Business Intelligence Development Studio

Create a Custom SQL-Based Report

To create a custom SQL-based report using Business Intelligence Development Studio:

1- Open Business Intelligence Development Studio, and create a report server project.

xRM_Demo2 - Microsoft Visual Studio_2012-03-12_17-50-44

2- In Solution Explorer, right-click the Reports folder, and then click Add New Report.

xRM_Demo2 - Microsoft Visual Studio_2012-03-12_17-51-26

3- Click Next on the Report Wizard welcome screen.

4- On the Select the Data Source page, click New Data Source, and specify the following details:

  • Name: Type a name for the data source.
  • Type: Select Microsoft SQL Server.

Report Wizard_2012-03-12_17-53-25

  • Connection String: Specify the connection string to connect to the instance of the Microsoft SQL Server database. To build the connection string, click Edit. To supply credentials, click Credentials. Click Next.

Connection Properties_2012-03-12_17-54-53

3- On the Design the Query page, type the SQL query to use in the report. You could also click Query Builder button to open the Query Builder window. Right click in the empty area at the top of the dialog and choose Add Table

xRM_Demo2 - Microsoft Visual Studio_2012-03-12_17-58-43

then click on the Views tab, hold the CTRL key and and select the views that you will use in your report and click Add

Add Table_2012-03-12_17-59-13

select the columns you want, test your query results [We just retrieved the account name, city, country]

Query Designer_2012-03-12_18-02-20

when you satisfied with your query results, click Ok to use the query in the report

Report Wizard_2012-03-12_18-03-19

click Next.

4- On the Select the Report Type page, select a Tabular report or a Matrix report, and click Next. [we used Tabular, which is the most common report format]

Report Wizard_2012-03-12_18-03-24

5- Specify the fields that will be included in the report. You can add fields in three different sections [Page, Group, Details]. Page can be used for granular grouping like Country in our case, it will displayed on the page header only. Group can be used to more specific grouping within the page, like City in our case. Details is the place where individual records will be rendered, like our accounts names. Select each column name from the list on the left and click the designated section button to add the column to it.

Report Wizard_2012-03-12_18-04-41

Then click Next.

6- Select a stepped layout and click Next.

Report Wizard_2012-03-12_18-05-16

7- Select a style to apply to the report, and then click Next.

Report Wizard_2012-03-12_18-05-22

8- Verify the fields that will be included in the report, and name the report. Click Finish.

Report Wizard_2012-03-12_18-05-28

This will generate an .rdl file with the specified report name. You can use the .rdl file to publish your custom report in Microsoft Dynamics CRM.

xRM_Demo2 - Microsoft Visual Studio_2012-03-12_18-07-31

Create a Custom Fetch-Based Report

Creating a custom Fetch-based report is similar to creating a custom SQL-based report except for the data source name and the report query specified while creating the report definition.

Since you have the capability to create SQL-based reports for on-premise, most people will not use Fetch-based reports for on-premise. Let’s learn how to get the data source name for our CRM On-Line organization. It consists of:

  • Organization URL something like https://xrmdemo5.crm.dynamics.com
  • Organization unique name you can get it by navigating to Settings > Customization > Customizations > Developer Resources > it will be on this page

Developer res

Put the two parts separated by semi-colon will form your connection string, like https://xrmdemo5.crm.dynamics.com;4c69b8c565264033b4707c804cba7aa2 put that connection string in a text file for later use.

Now, lets learn how to create a query for our Fetch-based report. There are two ways to do that:

  1. Manually type the FetchXML query (which I don’t personally prefer)
  2. Obtain the FetchXML queries from the CRM web client and then modify it.

To obtain FetchXML queries you can navigate to any entity listing in CRM web client, like Accounts. Then click Advanced Find on the ribbon

adv fnd

This will open the Advanced Find dialog

adv fnd 2

Then click New to start creating a new query.

1- You can select the Entity (Table) from the Look For combo-box.

2- You can create your query where conditions. Click Select link to select the desired column

adv fnd 3

You can then click Equals link to specify the operator used in the where condition. You can then click Enter Text link to specify the value used in the condition

adv fnd 4adv fnd 5

when you have multiple conditions, you can select them and use the Group AND and Group OR on the ribbon to build your query logic.

3- You can specify the columns you want retrieve. Click Edit Columns in the ribbon, this will open the Edit Columns dialog

Edit Columns -- Webpage Dialog_2012-03-13_13-07-57

The area on the left shows the query columns and the sequence they appear. You can click Add Columns from the left to add more columns from this entity or any of entities related to it.

Add Columns -- Webpage Dialog_2012-03-13_13-10-04

Select Address 1: City and Address 1: Country and click Ok.

4- You can specify the query sorting. Click Configure Sorting on the left to open the Configure Sort Order dialog

Configure Sort Order

You can specify two columns only for the sorting criteria.

5- You can remove any column by click its name on the right and click Remove from the left.

When you done with editing the query columns click OK to return to the Advanced Find window. Now, click Download Fetch XML on the ribbon to download the Fetch query in a .xml file format to use inside SQL Business Intelligence Development Studio.

Now to add a custom Fetch-based report to our Report project, Right click Reports folder and click Add New Report. Click Next on the Report Wizard welcome screen.

1- On the Select the Data Source page, click New Data Source, and specify the following details:

  • Name: Type a name for the data source.
  • Type: Select Microsoft Dynamics CRM Fetch.
  • Connection String: copy the connection string we prepared earlier and past it here.
  • Click on Credentials and enter your live account and password you used in CRM Online and click Ok. Then click Next

Data Source Credentials_2012-03-13_15-07-56

2- On the Design the Query page, click on Query Builder. On the Query Designer dialog, click Import and browse to the xml file you downloaded earlier.

Query Designer_2012-03-13_15-24-04 

You can click on Run to test the query. Click Ok to close the Query Designer dialog, and Click Next.

Complete the Wizard steps just like the SQL-based report, it is the same.

As you can create queries using Business Intelligence Development Studio, you can also use it to modify complex queries.

Import Custom Reports into Dynamics CRM

To complete the cycle and let the report used by your organization, you need to import it into CRM. Follow the following steps to import our report:

1- Navigate to My Work > Reports > click New on the ribbon. The New Report window will open.

Report New - Windows Internet Explorer_2012-03-13_17-07-32

Click Browse and select your .rdl report file. Enter the report name. Near the bottom of the window there is a Display In field which decides areas where your reports will be displayed. By default new reports will be displayed in Reports area,  You can click the eclipse button if you want to make it displayed in forms or lists of the related entities, then select desired values and move them to Selected Values list.

Select Values -- Webpage Dialog_2012-03-13_17-20-21

In the New Report window, if you want to make the report accessible by the whole organization click the Administration tab and change the Viewable By field from Individual to Organization.

Report New - Windows Internet Explorer_2012-03-13_17-14-18

Click Save and Close. Now our report will be available in the Reports area of configured accessibility level [Organization or Individual].

To copy a report between organizations or deployments, include the report and any custom entities the report uses in a solution. This ensures that the entity types are mapped automatically by the system

In this post we used the Business Intelligence Development Studio to create both SQL-based and Fetch-based custom reports for on-premise and on-line CRM deployments. We also learned how to upload our reports to Dynamics CRM and make them accessible to the whole organization and through many access points.

Sunday, March 11, 2012

Microsoft Dynamics CRM 2011 for Developers | Web Resources Part 1

Contents

  1. Introduction
  2. Types of Web Resources
  3. Where can Web Resources be Used ?
  4. Web Resources Limitations
  5. Web Resources Management
  6. Using Web Resources on a Form
  7. Using Web Resources from the Form Navigation 
  8. Using Web Resources on a Dashboard
  9. Using Web Resources Direct from SiteMap  
  10. Using Web Resources as a Solution Configuration Page
  11. Referencing Other Web Resources

Introduction

Web resources are a new feature of Dynamics CRM 2011 that allows storing of client side content in the CRM server database in order to be used for extending the Dynamics CRM web application. That content is then available to be delivered to users as needed during their interaction with the user interface. These resources can be used by URL, which also allows relative path referencing.

Based on that and using the appropriate development tools, a fully functional web site can be created on a development server by using file types that are compatible with web resources. Then, if using a consistent naming convention and relative path references, the web site will function after uploading all the files into Microsoft Dynamics CRM. These web resources can then be exported in a solution and installed on any Microsoft Dynamics CRM deployment (both on-premises and on-line). It will also available to users of Microsoft Dynamics CRM for Microsoft Office Outlook with Offline Access when offline because they are synchronized with the user’s data.

Types of Web Resources

Microsoft Dynamics CRM allows ten types to create web resources which fall into seven type categories. We will explore them here:

  • HTML Web Pages You can upload *.htm or *.html files as web resources, or you can use the Text Editor in the CRM interface to create your HTML web resources. Web pages can’t contain any code that must be executed on the server (no ASP.NET support). Web pages can only accept one custom query string parameter called data.
  • Images You can upload PNG, JPG, GIF, and ICO files. They can be used as icons for custom ribbon controls or Sitemape subareas, decoration for entity forms and web pages, background images.
  • Script Enables uploading JScripts for reuse of many parts in the CRM like web page, ribbon commands, or form and field-level events.
  • Style Sheet .css files linked to web page web resources to efficiently manage their appearance.
  • Data Enables you to upload some XML files to your system
  • Style Sheet enables you to upload *.xsl and *.xslt files to be used by Data and Web Page web resources, so you can apply the style on XML files.
  • Silverlight enables you to upload *.xap files which is the output of Silverlight application build process. Silverlight applications can be used on forms to create a more rich and visual components for users.

Where can Web Resources be Used ?

All web resources (except XML, XSL, XSLT, CSS) can be used on forms, on dashboards, from SiteMap, or from the application ribbon. All web resources can be used in the context of Web Page web resources.

Web Resources Management

Web resources can be created in the context of any unmanaged solution inside a CRM organization.

If you will create the web resource in the default solution navigate to Settings > Customizations > Customize the System > click on Web Resources from the left navigation > New. Enter the Name, Display Name, and select the web resource type. If you will create the web resource in a default solution other than the default solution, Settings > Customizations > Solutions > and click your solution and complete in the same steps as above.

After uploading a new or updating web resource, you have to publish the web resource before you use it in the application.

You can remove an unmanaged Web Resource at any time as long as it is not currently being by any component. If you attempt to remove a web resource while it is in use by another component you will get an error message.

Web Page web resources are the container that can host (or link to) all the other web resource types, so we will explain all the ways to incorporate Web Page web resources in Dynamics CRM. Then we will explain how to link and integrate other types of web resources.

In order to proceed, we will create a simple "Hello World" page and upload it as a web resource. Create a simple page.html file like the following:

page

Now open your browser and navigate to your CRM organization, then navigate to Settings > Customizations > Customize the System > click on Web Resources from the left navigation > New. Enter a Name for our page, Display Name, and select Web Page (HTML) from the Type combo box. Click Save, then click Publish, then close the window.

Web Resource New

Now we create a simple web page web resource and ready to explore the different ways to use it in our Dynamics CRM. We will explore just the basic usage scenarios, advanced features will be explained in a future post.

Using Web Resources on a Form

Now let's put use our test HTML page web resource on a Form, e.g. Account. Navigate to Settings > Customizations > Customize the System > from the left navigation expand Entities, then expand Account, then expand Forms, then click on the form named Information which have Main in the Form Type column. The form designer will open. Just to make things easier for you, collapse the regions on the form (called tabs in Dynamics CRM) by clicking the small blue rectangle on the left-top corner of each of them. Then Click on Insert in ribbon

 insert

Then click One Column on the ribbon.

one column tab

This will insert a one column region (called Tabs in Dynamics CRM) below the currently selected region.

new tab

While your new region is selected, click Web Resource on the ribbon. new WR ribbon

This will open the Add Web Resource dialog. In the Web Resource textbox click the look-up icon on the right and select our Web Page web resource from the list (you can also search for it by name). Fill the required Name and Label fields, and click Ok.

Add Web Resource - filled

This will place our web page web resource on the new region we added previously to the form

Tab filled

Now click Save on the form designer then click Publish to publish your for customizations, then click Save and Close to close the window. Click Publish All to ensure that everything is published fine, then close the solution window. Refresh your browser and navigate to the form you have customized, it will be Account in our case and open any record to check that our HTML page web resource is published on the form correctly.

Account Blue Company - Microsoft Dynamics CRM - Windows Internet Explorer_2012-03-09_04-17-58

Using Web Resources from the Form Navigation

Using our web page web resource from the left navigation of a form is much more easier than using it on the form. There are two ways to do accomplish this task; one using the CRM web client interface and the other one is through editing the Entity Navigation via the FormXML directly. Now we will use the web interface and will talk about FormXML in a future post.

Use the same steps we did in the previous example to open the form designer of the entity you want to customize, for example Account. Click on Navigation in the ribbon

nav

This will disable the form controls except the left navigation area. Click on Insert tab on the ribbon. Then click Navigation Link

nav link

This will open the Navigation Link Properties dialog. Enter Name of the link which will be the text that will appear on the left navigation, then select our web page web resource from the Web Resource textbox (you can link to external URL which will be rendered inside the form at runtime).

nav lnk

Now If you open any account record, you will see our link added on the left, if you click it our web page web resource will be rendered on the right.

acc

Using Web Resources on a Dashboard

Using Web Page web resource on a CRM dashboard is pretty similar to using it on a form. The first step is to create a new dashboard by navigating to My Work > Dashboards > click New on the ribbon. This will open Select Dashboard Layout dialog, select the layout you want (for example, 3-Column Focused Dashboard), and click Create.

Dashboard Layouts

The dashboard designer window opens. Click on the Insert Web Resource icon on any region on the dashboard (indicated by arrows in the image)

New Dashboard Designer

This will open the same Add Web Resource dialog we worked with before. Do the same steps to add the web page, then gave a name to your dashboard and click Save and Close. This will close the close the designer window and open the new dashboard in your CRM main window. For example, I added the web page web resource to the left region on the dashboard and named it Test Dashboard, and below what I got.

new DB

Using Web Resources Direct From SiteMap

In order to make our web resource accessible directly from Sitemap, we have to edit the SiteMap. Unfortunately there is now way to edit the SiteMap from the Dynamics CRM web interface, you have to export the SiteMap in a temporary unmanaged solution, edit the SiteMap XML, then import the solution back again.

To create a new solution, navigate to Settings > Customizations > Solutions >  New

s

This will open the New Solution window, enter a Display Name, Name, Version, select a Publisher, and click Save

new s

After you click Save, the window will change to allow you adding your solution components. Click Add Existing > SiteMap

n s m

Click on Export Solution icon

export

In the solution export dialog click Next > Next > ensure that the package type is Unmanaged then click Export. The Dynamics CRM server will package the solution files for you in a zip file and deliver it for you. You will see a file download message from your browser to download the zip file.

dn n s

Save the zip file, extract its contents, open the customizations.xml file in Visual Studio (or your favorite XML editor). If you collapsed all the nodes in the XML Editor, you will see that the SiteMap parent node have many Area nodes. Each node represents the major parts of CRM web client navigation, which are available on the left bottom part of the window.

sm Areas

Now expand the the area node with Id=”Workplace”, which represents the Workplace in the web client. You will see Group nodes for each sub-section of Workplace area

sm area wp

Now expand the group node with Id=”MyWork”, which represents MyWork in the web client. You will see SubArea nodes for each sub-section of the MyWork area.

sm group mw

Now let’s say we want to add the link to our web page web resource just next to Dashboards under MyWork. Locate the SubArea with Id="nav_dashboards" and insert the following XML after it to make our link

          


This xml adds two links on the SiteMap, both of them links to our web page web resource. The first one uses the web resource direct URL which can be used to access the web resource even from external systems (vice versa, you can link other URLs directly to your CRM). To get the web resource URL, navigate to Settings > Customizations > Customize the System > click Web Resources from left navigat > double click the desired web resource to open its properties dialog, you will find the URL in the bottom of the form



WR url



The second link uses the keyword $webresource to reference the web resource by name. We will talk about $webresource keyword in the “Referencing Other Web Resources” section of this post.



Now its time to get these SiteMap modifications into CRM. Save customizations.xml, Select all the exported solution files and add them to a .Zip file, navigate to Settings > Customization > Solutions > and click Import. In the solution import dialog upload your .Zip file, and click Publish All Customizations at the end. If you navigate to your CRM home page and refreshed the page you will see the links on the left



VER



Using Web Resources as a Solution Configuration Page



Solutions are containers that track customizations and allow it to be moved around from server to server. When building a custom solution you may want to add a page where you provide details about your solution and its features. Configuration pages for solutions can fulfill your requirement for such a page. Let’s see how we can use our web page web resource as a solution configuration page. Navigate to Settings > Customization > Solutions > click your solution > on the Solution dialog click on the Information from the left navigation



sol info



Then choose our web page web resource in the Configuration Page textbox



sol info 2



Then Click Save and then Click Publish. Now you will see a new link added on the left navigation after the Information link, it will be called Configuration



col cnfg



if you click it, you will see our web page web resource on the right.



col cnfg 2



Referencing Other Web Resources



While some web resources can be added directly to a form or a dashboard, others can only be referenced through their relative path. There are many ways you can use to reference Web Resources:



$webresource Directive You should use it when referencing a web resource from XML like from a ribbon control, or a SiteMap sub area (like what we did before). When using the $webresource directive, Microsoft Dynamics CRM will create or update solution dependencies.



Relative URL You can use relative URL when referencing from HTML or other areas that doesn’t support using $webresource. To make this works, it is recommend that you use a consistent naming convention for the web resources that reflect a virtual file structure. The solution publisher’s customization prefix will always be included as a prefix to the name of the web resource. This can represent a virtual ”root” folder for all web resources added by that publisher. You can then use the forward slash character (/) to simulate a folder structure that will be honored by the web server.



From another web resource, you should always use relative URLs to reference each other. For example, for the webpage web resource new_/content/contentpage.htm to reference the CSS web resourcenew_/Styles/styles.css, create the link as follows:





For the webpage web resource new_/content/contentpage.htm to open the webpage web resource isv_/foldername/dialogpage.htm, create the link as follows:



Dialog Page


Full URL As web resources are URL accessible, you can open the information dialog of any web resource and copy the URL in the bottom of the window and use it anywhere you can use a URL (as we did before).



In this post we introduced the web resources feature in Microsoft Dynamics CRM 2011. We started with exploring the different types of Web Resources, where can Web Resources be Used in our customization scenarios, and what is the limitations we have on using web resources. Because web Page web resources are the containers that can host (or link to) all the other web resource types, we explained all the ways to incorporate Web Page web resources in Dynamics CRM. Then we explained how to link to other types of web resources.