dynamics retail functional 80640 ... - firebrand training uk
TRANSCRIPT
Table of Contents
1
Microsoft Dynamics® 80640 Training
Dynamics AX 2012 R3
Retail in Ecommerce Stores: Development and Customization
Microsoft Dynamics AX for Retail in ECommerce Stores: Development and
Customization
2
Module 1: ECOMMERCE TECHNICAL OVERVIEW
Lesson 1: Features and Components ...................................................................................................... 1-2
Lesson 2: Logical Design of Ecommerce Sites .................................................................................. 1-11
Lesson 3: Mapping Entities in AX and SharePoint .......................................................................... 1-17
Lesson 4: Ecommerce Publishing Architecture ................................................................................ 1-18
Module 2: DEVELOPMENT ENVIRONMENT
Lesson 1: Configure Development Environment ............................................................................... 2-2
Module 3: BRANDING THE ECOMMERCE SITE
Lesson 1: Customize the Visual Design of a Ecommerce Site ....................................................... 3-2
Lesson 2: Customize the Functionality of an Ecommerce Site ................................................... 3-23
Module 4: ECOMMERCE WEB PARTS
Lesson 1: Create a SharePoint WebPart ................................................................................................ 4-2
Lesson 2: Add a New AJAX Service to the Storefront ...................................................................... 4-7
Lesson 3: Customize Out-of-the-Box WebParts .............................................................................. 4-14
Module 5: SEARCH CONFIGURATION AND CUSTOMIZATION
Lesson 1: Configure Refiners and Faceted Navigation .................................................................... 5-2
Lesson 2: Manage Query Rules .............................................................................................................. 5-10
Module 6: COMMERCE RUNTIME SERVICES
Lesson 1: Commerce Runtime Extensibility .......................................................................................... 6-2
Lesson 2: Customize the Functionality of the Ecommerce Site ................................................. 6-20
Module 7: TESTING, DEPLOYMENT AND VERSIONING OF
ECOMMERCE SITES
Lesson 1: Testing Considerations ............................................................................................................. 7-2
Lesson 2: SharePoint Deployment Architecture Guidance ............................................................. 7-5
Lesson 3: Deployment .................................................................................................................................. 7-6
Table of Contents
3
Lesson 4: Versioning and Code Maintenance .................................................................................. 7-13
Module 8: ECOMMERCE LABS
Lab A: Customize the Functionality of an Online Store ................................................................... 8-2
Lab B: Configure the Refiner on the Search Results Page of the Ecommerce Site................ 8-4
Lab C: Change a Site Logo using MasterPage ..................................................................................... 8-6
Lab D: Online Store Design Elements ..................................................................................................... 8-8
Lab E: Customize Search Results ............................................................................................................ 8-13
Lab F: Extending a Commerce Entity ................................................................................................... 8-17
1 - 1
MODULE 1: ECOMMERCE TECHNICAL OVERVIEW
Module Overview
Microsoft Dynamics AX 2012 R3 introduces a new suite of features that help you
deploy, manage, and customize an online sales channel that is fully integrated
with Microsoft Dynamics AX. By using this new suite of Ecommerce features, you
can centrally manage products, merchandising, and order fulfillment for all
aspects of your online sales channel directly in Microsoft Dynamics AX. The
runtime component enables you to deliver content and retail services in a scalable
way. A new starter online store speeds up the development of a highly customized
online channel. The starter online store includes the patterns and best practices
that are required to support production-ready deployments. This includes
powerful, search-driven, adaptive experiences offered by the SharePoint Server
2013.
Objectives
The objectives are as follows:
Explain the features and components of the Ecommerce site.
Present the high level logical design of the Ecommerce site.
List the customizable controls available for Ecommerce.
Describe the entity mappings between SharePoint and Dynamics AX.
Technical Background
Microsoft Dynamics AX 2012 R3 Retail model includes Ecommerce features. The
Ecommerce functionality includes a starter online store. This is known as the
online storefront. This is built using Microsoft SharePoint Server 2013.
Commerce Runtime (CRT) is a set of .NET assemblies that connect to a custom
SQL database that is named CRT Database. The Ecommerce site uses Commerce
Data Exchange (CDE) – Real time or Sync Service or both to communicate with
back end AX (also known as the AX Headquarter).
To customize the appearance and behavior of the SharePoint Ecommerce site, you
must have HTML, CSS, and JavaScript skills. The core of the SharePoint platform is
built by using .NET technologies. Familiarity with .NET will help you customize or
extend the functionality of the ecommerce site.
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
1 - 2
Features and Components
Overview
This module provides an overview of the following major components of the
Microsoft Dynamics Ecommerce architecture in AX 2012 R3 and an understanding
of how these components interact with one another:
1. Commerce Data Exchange
2. Channel Database
3. Microsoft Dynamics AX connector for SharePoint
4. SharePoint Product Catalog
5. SharePoint Search & Web-Parts
6. SharePoint Publishing Site
7. Commerce Runtime Service
The “Components of Ecommerce Solution” figure displays the major components
of Ecommerce solution.
FIGURE 1.1: COMPONENTS OF ECOMMERCE SOLUTION
The Ecommerce site is built by using the Microsoft SharePoint Server 2013 cross-
site publishing platform. Cross-site publishing uses one or more authoring site
collections to author and store content, and one or more publishing site
collections to control the user interface of the site and to show content. The
authoring site collection can contain catalogs such as Pages libraries, and lists of
items that are tagged with metadata. These catalogs are indexed by the search
system and made available to the publishing site collection. The publishing site
collection displays previously indexed data on web pages by using search-driven
Web Parts.
Module 1: Ecommerce Technical Overview
1 - 3
In Ecommerce, the authoring site collection is called the “Product catalog site.”
This is an internal-only site that is accessed by content authors and internal
employees. However, the publishing site is the public-facing site that anonymous
users access for online shopping.
Reference Links: To learn more about the Cross-site publishing feature of
SharePoint 2013, please refer to the Cross-site publishing feature of SharePoint
2013 that is located at http://technet.microsoft.com/en-us/library/jj635883.
The “Detail Architecture of the Online Store” figure displays the logical
architecture and the flow of information between some features and components
that are discussed in this section.
FIGURE 1.2: DETAIL ARCHITECTURE OF THE ONLINE STORE
Commerce Runtime (CRT)
The Microsoft Dynamics AX commerce runtime (CRT) serves as the engine for a
retail channel. It connects to a CRT database that stores business data for the
Ecommerce site. The Microsoft Dynamics AX commerce runtime is a set of DLLs
that performs business logic and data processing for an online store. The CRT has
four layers (data access, services, workflow, and API) and a database. The CRT is
installed as part of the Ecommerce site.
The “Components of Commerce Runtime” diagram displays the components of
the CRT.
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
1 - 4
FIGURE 1.3: COMPONENTS OF COMMERCE RUNTIME
Channel Database Schema
The online store uses this database as a data store before pushing data into
SharePoint. The database is named AxRetailSP by default; however, you can
change this name during the deployment of the online store. This database
contains data that is used by the CRT, products-retailed data, and the hierarchy in
which the product should display on the Ecommerce site.
Dynamics AX 2012 R3 uses a single database schema for enterprise POS, modern
POS, and online stores. The channel database Table schema is mainly a subset of
the back-office schema. One channel database can contain data for one or more
stores.
The “Channel Database” diagram displays how the CRT enables the omni-channel
vision in Microsoft Dynamics AX2012 R3.
Module 1: Ecommerce Technical Overview
1 - 5
The following figure displays how the channel database is used in the Ecommerce
architecture.
FIGURE 1.4: CHANNEL DATABASE
You can customize the channel database by extending one or more of the
following database objects:
SQL stored procedures
SQL functions
SQL tables
SQL views
SQL types
Data Access
The data access layer is in addition to the CRT database. This is an abstraction
layer to access the CRT database. In the data access layer, raw data is translated
into objects in memory. For example, an object could be a product. Products have
attributes like price and color. The data access layer has functions that you can use
to manipulate these objects. Stored procedures and Views pass packets of data
from the database to data entities. You can use this data in services and
workflows. You can update the packets of data to include new fields that you add
in Microsoft Dynamics AX.
Services
The services layer is in addition to the data access layer. Services query for real-
time data. You can use these services to customize existing functionality or you
can add your own service that has new functionality. These services are scalable
and extensible and are empowered through a combination of the commerce data
exchange and the commerce runtime.
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
1 - 6
Workflow
In addition to the services layer is the workflow layer. A “workflow” is a collection
of services and business logic that together define business processes. For
example, when a customer adds an item to the cart, you could use a workflow to
obtain the price, perform validation, check inventory quantity, and calculate
shipping, tax, and discounts. You can use workflows that are included in Microsoft
Dynamics AX, or you can create new workflows. You can even use a workflow to
connect to a third-party system as part of your business processes.
Application Programming Interface (API)
In addition to the workflow layer is the API layer. You can use the API for tasks
such as retrieving information about items, price and shipping calculations, and
order placement. You can extend the API to fit your business processes.
Commerce Runtime Configuration
The CRT configuration file (commerceRuntime.config) contains an enumeration of
services as .NET types and controls which service types to load. You can add types
in the commerce runtime configuration file to control which services are loaded in
the commerce runtime.
Services are loaded in the order in which they are listed in the configuration file.
All default services are loaded automatically. However, if you add a new service
above one of the default services, the new service will replace the default service.
Commerce Data Exchange: Real-Time Service
Real-Time Service provides Retail POS and Commerce Runtime with real-time
access to Microsoft Dynamics AX data for scenarios such as the following:
Customer orders
Sales orders and invoices
Customer validation and creation
Inventory lookup
Cashier validation
Credit vouchers
Gift cards
Loyalty programs
Retail POS and Commerce Runtime can perform most operations without
connectivity to Microsoft Dynamics AX. However, for certain scenarios both may
retrieve and update data directly in Microsoft Dynamics AX.
Module 1: Ecommerce Technical Overview
1 - 7
Commerce Data Exchange: Real-time Service is a Windows Communication
Foundation (WCF) service that uses .NET Business Connector to facilitate
communication between Microsoft Dynamics AX Retail headquarters and the
Microsoft Dynamics AX commerce runtime (CRT). In previous releases, this service
was called the Retail Transaction Service. You use Microsoft Dynamics AX Setup to
install this service.
The following figure displays the interaction between AX 2012 R3 and Online
Store by using Real-time service.
FIGURE 1.5: DYNAMICS AX AND ONLINE STORE USING REAL-TIME SERVICE
You can extend Commerce Data Exchange: Real-time Service by adding extension
methods to the RetailTransactionServiceEx class.
Commerce Data Exchange: Async Service and Async Client
Commerce Data Exchange: Async Server is part of the system for asynchronous
data exchange between Microsoft Dynamics AX and retail channels. Async Server
is installed at headquarters and communicates with Microsoft Dynamics AX. You
can distribute the communication load at the head office by installing multiple
instances of Async Server.
Async Service: Async Server runs as a Windows Communication Foundation
(WCF) service on IIS.
Microsoft SQL Server change tracking on the Microsoft Dynamics AX database
determines the data changes that must be sent to channels. Based on a
distribution schedule, Async Server packages that data and saves it to a file
location. Commerce Data Exchange: Async Client periodically checks for new data
packages, collects the data packages, and then applies them at the channel.
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
1 - 8
Message Databases: Async Server uses a message database to store status
information for data transfers that are in progress or have completed. Async Client
contacts the message database to determine whether there are new data
packages to collect.
You can also transfer status messages from the message database to the Microsoft
Dynamics AX database so that they can be viewed in Microsoft Dynamics AX. Each
instance of Async Server can refer to only one message database. However, a
message database can have multiple instances of Async Server that refer to it.
There can be only one message database per partition in Microsoft Dynamics AX.
Commerce Data Exchange: Async Client is part of the system for asynchronous
data exchange between Microsoft Dynamics AX and retail channels. Async Client
is installed at the channel, and communicates with the channel database. Typically,
you install one instance of Async Client for each channel.
Async Client runs as a Windows service. At a configurable interval, Async Client
checks with Async Server to see whether new data packages are available. If there
is new data, Async Client takes the data from the working folder and applies it to
the local channel database. Async Client also uploads sales transactions from the
channel to Microsoft Dynamics AX.
Async Client uses the WS-ReliableMessaging protocol to transfer data by default.
Reliable messaging makes sure that the data is transferred successfully over the
network. However, the confirmation actions that are sent between the source and
the destination can cause data transfers to be slower. For better throughput, you
can use streaming instead. However, streaming does not handle network
problems. Streaming is ideal for initial high-speed data synchronization or for
ongoing synchronization of large amounts of data. If you have a reliable network
and high data volume, we recommend that you stream data.
Async Client uses a message database to store status information for data
transfers that are in progress or were completed
The following figure indicates how the Async server interacts with the Async client.
FIGURE 1.6: ASYNCHRONOUS DATA EXCHANGE
Module 1: Ecommerce Technical Overview
1 - 9
Synch Service
Note: Synch Service is required for Retail only in Microsoft Dynamics AX
2012 R2 and Microsoft Dynamics AX 2012 Feature Pack. In Microsoft Dynamics AX
2012 R3, this component is used only to support earlier versions of Retail POS while
you upgrade (N-1).
Microsoft Dynamics AX for Retail Commerce Data Exchange: Synch Service is
the integrated service that periodically replicates data between the head office
database and store databases, and among store databases.
Term Sets and Managed Navigation
A “term” is a word or a phrase that can be associated with an item in SharePoint
Server 2013. A “term set” is a collection of related terms. You can specify that a
column must contain a term from a specific term set. Managed metadata is a way
to refer to the fact that terms and term sets can be created and managed
independently from the columns themselves. “Managed metadata” is a
hierarchical collection of centrally managed terms that you can define, and then
use as attributes for items in SharePoint Server 2013.
You use term sets to tag catalog content such as pages or list items on the
authoring site. By doing this, terms categorize the content into a hierarchy. These
same terms are used later on the publishing site to issue queries, show
information about category and catalog item pages, create friendly URLs, and for
“managed navigation.”
Reference Links: For more information about managed metadata, term sets,
and enterprise keywords, refer to the article that is located at
http://technet.microsoft.com/en-us/library/ee424402.aspx.
The managed navigation feature in SharePoint Server 2013 enables you to build
navigation for a publishing site that is derived from a SharePoint managed
metadata taxonomy. Managed navigation also lets you create friendly URLs
without changing the structure of your site.
The Ecommerce publishing site uses the managed navigation feature to build the
site navigation. Categories that are created in AX Retail Headquarters are
published as term sets into the term store of the Publishing Site collection. These
terms then are displayed as navigation hierarchy in the publishing site collection.
Reference Links: For more information about Managed Navigation, refer to
the article that is located at http://technet.microsoft.com/en-
us/library/dn194311.aspx .
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
1 - 10
Search
The Microsoft SharePoint Server 2013 cross-site publishing platform uses
Microsoft SharePoint Search and search-driven pages to dynamically display
content for customers.
The Crawler service of SharePoint search crawls the product catalog lists and the
term store of the Product Catalog Site collection and stores the crawled data into
the Search Index.
The following figure displays how search driven pages work in SharePoint 2013.
FIGURE 1.7: SEARCH-DRIVEN EXPERIENCE.
The search system indexes content from the authoring site and the product
catalog site collection. When a user views a page on one of the publishing sites,
queries from Search Web Parts on that page are sent to the search index. The
search index returns results, and displays them in the Search Web Parts on the
page.
Reference Links: For more information about Search in SharePoint 2013,
refer to the article that is located at http://technet.microsoft.com/en-
us/library/jj219738.aspx.
Retail Store Databases
When you deploy the online store, the system creates the following databases in
Microsoft SQL Server.
Module 1: Ecommerce Technical Overview
1 - 11
CRT Database
The online store uses this database as a data store before pushing data into
SharePoint. By default, the database is named AxRetailSP. Settings for this
database are stored in the oob-topology.xml file under Settings/Channel.
Identity Provider Database
This database stores user credentials for forms-based authentication. By default,
the database is named SPFBA. Settings for this database are stored in the oob-
topology.xml file under Settings/IdentityProvider.
Custom Claims Provider Database
This database stores the mapping between user identify and their Microsoft
Dynamics AX customer number that was created when the user created an
account. By default, the database is named SPAuthZ. Settings for this database
are stored in the oob-topology.xml file under Settings/CustomClaimsProvider.
Logical Design of Ecommerce Sites
Once the Ecommerce site (online starter site) is deployed, it creates web
applications and site collections for hosting the site. Use the Cross-publishing
feature of SharePoint 2013 to separate the authoring content site from the
publishing content site, which is visible to the end-user.
Lesson Objectives
Explain the information architecture of the Ecommerce site
Present the major components of SharePoint that are used to build
the Ecommerce site
Review the customizable controls available for extensibility
Logical Architecture
The “Logical Architecture” figure provides a detailed view of the web applications
and site collections that are created on the SharePoint server when you deploy the
Retail online store. It also lists the associated classes and zones that were created
for the applications and site collections.
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
1 - 12
FIGURE 1.8: LOGICAL ARCHITECTURE
Site Collections
There are two main site collections created when you deploy the Retail Online
Channel. They are the Product Catalog site collection and the Retail Publishing
Portal site collection.
Product Catalog Site Collection
The Product Catalog contains catalogs such as Page libraries. This is a list of
product items that are tagged with metadata. All libraries and lists are shared as
catalogs. The site collection is located in an independent web application. The
product catalog content web application uses Windows authentication (Active
Directory) to authenticate content authors.
Retail Publishing Portal Site Collection
The publishing portal site collection is located in a separate web application. The
publishing portal web application uses Windows authentication (Active Directory)
for designers and forms-based authentication for web users. This web application
is configured to also enable anonymous access for web users.
Module 1: Ecommerce Technical Overview
1 - 13
The publishing site collection has an asset library, where you can store rich media
content like images and videos. Because the publishing site collections are outside
the firewall, the asset library is located in a separate site collection in the same
web application as the publishing site collections. This gives users on the
publishing sites read access to those assets. Internal users such as designers and
other content authors have Contribute permission level to add, update, and delete
items in the asset library. The asset library is added to the Suggested Content
Browser Locations list for the authoring and product catalog site collections so
that content authors can use those assets in their content.
Reference Links: For more information about SharePoint Site Collections,
refer to the article that is located at http://technet.microsoft.com/en-
us/library/cc262410.aspx.
Microsoft Dynamics AX Connector
The Microsoft Dynamics AX Connector (also named the Channel Connector) is a
SharePoint service publishing job that runs in the OWSTimer.exe service. The
publishing job retrieves updated product information from the CRT database and
pushes it into the product catalog site collection. This information then is crawled
by Search and stored in the Search Index.
Secure Token Service
The Secure Store Service is a claims-aware authorization service that includes an
encrypted database for storing credentials. The Secure Store Service is an
authorization service for SharePoint that runs on an application server and is used
for validated forms-based authentication users. The Secure Store Service provides
a database that is used to store credentials. These credentials usually consist of a
user identity and password, but can also contain other fields that you define.
Reference Links: To learn more about authentication in SharePoint, refer to
the following article located at http://technet.microsoft.com/en-
us/library/jj219571.aspx.
SharePoint Page Model
SharePoint uses templates to define and render the pages that a site displays. The
structure of a SharePoint page includes three main elements:
Master pages define the shared framing elements (the “chrome”) for
all pages in your site.
Page layouts define the layout for a specific class of pages.
Pages are created from a page layout by authors who add content to
page fields.
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
1 - 14
Master Pages
A master page defines the chrome (the shared framing elements) of your site.
These elements may include the header and footer, top navigation, breadcrumbs,
search box, site logo, and other branding elements. The master page remains
consistent as visitors move through your site.
A master page also defines regions called content placeholders that are
completed by content from matching regions on page layouts. The body of a
master page usually contains just a single content placeholder known as
PlaceHolderMain that is created automatically. All content from a page layout
displays inside this one content placeholder.
Page Layouts
A page layout is a template for a specific type of page in your site, such as an
article page or a product details page. As its name implies, you can think of a
page layout as defining the layout or structure for the body of a page.
Page layouts define regions or content areas that map to content placeholders on
the master page. Again, the most common scenario is that a page layout defines a
single content region that maps to the single content placeholder that is created
automatically on a master page
Page Field Controls
The main purpose of a page layout is to arrange page fields. When you design a
page layout, you insert, position, and style elements called page field controls.
These controls will eventually contain content when an author creates a page that
is based on that page layout. In addition to page fields, page layouts can also
contain Web Part zones, to which content authors can add Web Parts. Master
pages cannot contain Web Part zones.
You can define the styles that are used by the content with a page field control.
While authors can add content to a page, the designer has ultimate control over
how that content is rendered through the CSS that is applied to those controls.
Module 1: Ecommerce Technical Overview
1 - 15
FIGURE 1.9: SAMPLE SHAREPOINT PAGE
The SharePoint Page Model section explains the SharePoint page model as master
pages, page layouts (with page fields), and pages. These elements are common in
a publishing site in which authors regularly create and publish new content.
A SharePoint page contains these main elements:
Master pages
Page layouts
o Regular page layouts that you create for specific content types, as
described previously
o Category and item details page layouts that are created through
cross-site publishing of a catalog
Pages
Web Parts to display content to the user
o Search-driven Web Parts, such as the Content Search Web Part
o Custom Web Parts that integrate with CRT Services to access
information
Display templates to control which managed properties appear in the
search results of a search-driven Web Part and control the styling and
behavior of those search results:
o Control display templates that control the layout of search results
and any elements that are common to all results, such as paging,
sorting, and other links
o Item display templates that control how each search result is
displayed and repeated for each result
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
1 - 16
The Ecommerce site is based on cross-site publishing feature that uses search-
driven Web Parts to surface content on sites and typical web parts that connect to
the CRT Services to access information.
The “Master page, page layout, and page with Web Part” figure displays the
relationship of Master page, Page layout, Page and the Content Search Web part.
FIGURE 1.10: MASTER PAGE, PAGE LAYOUT, AND PAGE WITH WEB PART
Reference Links: For more information about the SharePoint 2013 Page
model, refer to the article that is located at http://msdn.microsoft.com/en-
us/library/jj191506.aspx.
Module 1: Ecommerce Technical Overview
1 - 17
Customizable Controls
The starter online store includes the following customizable controls.
FIGURE 1.11: CUSTOMIZABLE CONTROLS FOR THE STARTER ONLINE STORE
You can change the previous list of controls to alter the appearance and behavior
of the Ecommerce site, and to change behavior from the UI perspective.
Mapping Entities in AX and SharePoint
AX Entities to SharePoint
The following figure contains a list of Dynamics AX entities that map to SharePoint
entities.
Figure 1.12: AX Entity Mapping to SharePoint
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
1 - 18
Product Catalog Site Mapping to Public-Facing Site
The “Mapping between Internal-Facing Site and Public-Facing Site” figure
highlights how the entities of the Internal Authoring site (Product Catalog) are
mapped to the Public-Facing site.
FIGURE 1.13: MAPPING BETWEEN INTERNAL-FACING SITE AND PUBLIC-
FACING SITE
Module 1: Ecommerce Technical Overview
1 - 19
Ecommerce Publishing Architecture
This topic contains conceptual information to help developers and system
administrators understand how channels and catalogs are published from the
Microsoft Dynamics AX Retail module to an online store in Microsoft SharePoint
2013 Products.
Architecture of Publishing Process
The “High-Level Architecture of Retail Online Store Publishing Processes” figure
displays the architecture and flow of the publishing processes. These processes are
described in more detail in this topic.
FIGURE 1.14: HIGH-LEVEL ARCHITECTURE OF RETAIL ONLINE STORE
PUBLISHING PROCESSES
Publish a Channel
To publish the Retail online store channel means to replicate the basic structure of
your online store between Microsoft Dynamics AX and SharePoint. You create the
basic structure of your online store channel in the Microsoft Dynamics AX Retail
module.
The following set-up tasks must be completed before you can publish the
channel:
1. Add the online store to the organization hierarchy.
2. Create the online store and configure properties in Microsoft
Dynamics AX.
3. Configure the category hierarchy of your site.
4. Create the online store in SharePoint.
Note: For more information about how to publish a channel, click the
following link:
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
1 - 20
http://technet.microsoft.com/en-us/library/jj682095.aspx.
After you complete these steps, you are ready to publish the store, hierarchies,
and properties to SharePoint.
The “Process Flow for Publishing a Retail Online Store Channel” figure displays the
publishing process for a Retail online store channel.
FIGURE 1.15: PROCESS FLOW FOR PUBLISHING A RETAIL ONLINE STORE
CHANNEL
You create the online store in Microsoft Dynamics AX and publish it from the
Online stores form. The publish status changes from “Draft” to “In progress.”
1. Microsoft Dynamics AX takes a snapshot of the category hierarchies
(known as the Retail hierarchy) and properties.
2. The Commerce Data Exchange: Synch Service reads information
about the online store, hierarchies, and properties in the Retail store
database and sends it to the Commerce runtime (CRT).
3. The CRT synchronizes the tables in the CRT database.
4. The Retail publishing job that runs as a SharePoint timer job reads
these synchronized tables from the CRT database and creates
hierarchies for the site that you created in SharePoint.
5. The Retail publishing job creates term sets and standard content
types in SharePoint.
6. The Commerce Data Exchange: Real Time Service reads the status of
the Retail publishing job actions and publishes that status in Microsoft
Dynamics AX. The status displays either Published or Error.
Module 1: Ecommerce Technical Overview
1 - 21
Publish a Catalog
A Retail product catalog lets you identify the products that you want to offer in
your online stores. When you create a catalog, you identify the online stores
where the products will be offered, add products, and improve the product
offerings by adding merchandising details. After the catalog is approved, you
publish it to make products available in the online store. The following set up
tasks must be completed before you can publish a catalog:
1. Set up retail products and configure hierarchies, assortments, and
variants.
2. Set up retail product catalogs and configure attribute groups and
workflow.
The “Process Flow for Publishing a Retail Online Store Catalog” figure displays the
publishing process for a Retail online store catalog.
FIGURE 1.16: PROCESS FLOW FOR PUBLISHING A RETAIL ONLINE STORE
CATALOG
1. Microsoft Dynamics AX reads the product tables in the Retail
database (tables A-1040_OC and N-1040_OC) and creates a listing for
each variant. For example, a product might be jeans and the variant
might be red. The system creates a listing for red jeans.
2. The Commerce Data Exchange: Synch Service synchronizes all tables
that are related to the listing. For example, the system synchronizes all
tables that are related to the red jeans variant. These synchronized
tables might include attribute tables such as brand and style. This
information is synchronized in the Commerce runtime (CRT) database.
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
1 - 22
3. The system updates the price of the listing in the CRT database.
4. The system determines whether any new attributes were added for
the listing. For example if the listing red jeans includes a new attribute
called texture the system creates a custom site column for that
attribute. The system creates a new rule for this list item and finishes
the process in SharePoint by creating a new row for the red jeans
listing.
5. The CRT records the publishing status for the listing.
6. The Commerce Data Exchange: Synch Service synchronizes the
publishing status of the red jeans listing with all other publishing
statuses.
7. The Commerce Data Exchange: Real Time Service reads the catalog
publishing statuses and publishes an “all-up” or aggregated status in
Microsoft Dynamics AX. The status displays either Published or Error.
Module Review
This course highlighted the features and components of the Ecommerce site and
the inter-relationships between Dynamics AX and SharePoint Server. This course
also described the main elements of SharePoint that are used to build the
Ecommerce site and the controls and services that can be extended.
Test Your Knowledge
Test your knowledge with the following questions.
1. Which of the following layers is not a part of the CRT architecture?
( ) Data Access
( ) Services
( ) Workflow
( ) Messaging
Module 1: Ecommerce Technical Overview
1 - 23
Test Your Knowledge Solutions
Module Review and Takeaways
1. Which of the following layers is not a part of the CRT architecture?
( ) Data Access
( ) Services
( ) Workflow
(√) Messaging
2 - 1
MODULE 2: DEVELOPMENT ENVIRONMENT
Module Overview
Microsoft Dynamics AX 2012 R3 includes an online starter store (Ecommerce) that
is built on Microsoft SharePoint Server 2012. You can create your own online store
by using some elements of the starter store, customizing some elements, and
adding your own elements.
This module will help you set up a development environment specifically to
customize the starter store.
Objectives
The objectives are as follows:
Install Retail SDK
Install the Development tools
Configure the Storefront solution for development
Microsoft Dynamics for Retail in Ecommerce stores: Development and
Customization
2 - 2
Configure Development Environment
This lesson will help you set up a development environment so that you can
customize the online starter store (Ecommerce) site.
Before You Start
Before you start to set up your development environment for customizing the
online store, you must install and configure Microsoft Dynamics AX and Microsoft
Dynamics AX Retail components. After you install the Retail components, you
must configure the Retail online store.
Retail Online Channel includes components that you need to set up an online
sales channel by using Microsoft SharePoint products. This component lets you
integrate data from Microsoft Dynamics AX into the SharePoint site. You can also
administer the online channel by using the Microsoft Dynamics AX client.
Reference Links: You can also read the following TechNet article to install
and deploy the Dynamics AX Retail components: http://technet.microsoft.com/EN-
US/library/jj937972.aspx
Install Visual Studio 2012, Tools, and Client Components
When you install Visual Studio 2012, Office Developer Tools for Visual Studio
2012, and SharePoint client components, you receive all templates and tools to
develop and customize the Retail online store site by using SharePoint 2013 on
your local development computer and CRT services.
Reference Links: To install Visual Studio 2012, click here:
http://msdn.microsoft.com/en-us/library/e2h7fzkw(v=vs.110).aspx
After you have installed Visual Studio 2012, download and install Microsoft
Office Developer Tools for Visual Studio 2012 and the SharePoint Client
Components. Here is a list of tools and software and their relative URLs to
download and install.
Tools / Software URL
Install Visual Studio 2012 http://msdn.microsoft.com/en-
us/library/e2h7fzkw(v=vs.110).aspx
Install Microsoft Office
Developer Tools for Visual
Studio 2012
http://msdn.microsoft.com/en-
us/office/apps/fp123627
On the Downloads page of the Apps for Office
and SharePoint Developer Center, select the link
Module 2: Development Environment
2 - 3
Tools / Software URL
for the web-based platform installer (WebPI).
This installs the tools and assemblies that you
must have to develop apps for SharePoint.
Install SharePoint Client
Components that contain
the client assemblies.
http://www.microsoft.com/en-
us/download/details.aspx?id=30355
You can use the SharePoint Server Client
Components Preview to enable remote and local
development with SharePoint Server.
You can use the assemblies in the client
components to build a web application or a
client application that connects to SharePoint,
which is hosted or running on an x86-bit
platform. If you are targeting an x64-bit web
application, then you must install the x64-bit
versions of the required assemblies separately.
Install Retail SDK
The Retail Software Development Kit (SDK) includes sample code and templates
that you can use to customize Retail for Microsoft Dynamics AX.
Note: Retail SDK is available only with Microsoft Dynamics AX 2012 Feature
Pack and Microsoft Dynamics AX 2012 R3.
Install Retail SDK on the SharePoint server, where you have configured the
Storefront site (Ecommerce components).
Follow these steps to install Retail SDK. If you install other Microsoft Dynamics AX
components at the same time, the installation pages vary, depending on the
components that you are installing.
1. Start Microsoft Dynamics AX Setup. Under Install, select Microsoft
Dynamics AX components.
2. Advance through the first wizard pages.
3. If the Setup Support files have not been installed on this computer
yet, the Select a file location page is displayed. The Setup Support
files are required for installation. Provide a file location or accept the
default location, and then click Next. On the Ready to install page,
click Install.
4. On the Select installation type page, click Custom installation, and
then click Next.
5. On the Select components page, select Retail SDK, and then click
Next.
Microsoft Dynamics for Retail in Ecommerce stores: Development and
Customization
2 - 4
6. On the Prerequisite validation results page, resolve any errors.
When all errors are resolved, click Next. For more information about
how to resolve prerequisite errors, see Check prerequisites at
http://technet.microsoft.com/EN-US/library/gg731884.aspx
7. On the Ready to install page, click Install.
8. After the installation is complete, click Finish to exit the wizard.
After you install the Retail SDK, two folders are created in the Documents folder
inside the Retail SDK folder:
1. Commerce Run-time: This folder contains sample code, reference
assemblies (DLLs) that are used by CRT, and the Services code base.
Use this code base to customize the CRT services
2. POS Plug-ins: This folder contains sample code examples and the
Services and Triggers code base. You can use this codebase to
customize POS applications.
Install Cumulative Update 1 (CU1) for Dynamics AX 2012
R3
On the computer, where the Storefront is configured and the Retail SDK was
installed, deploy cumulative Update 1 (CU–1) for Microsoft Dynamics AX 2012 R3.
You can download the Cumulative update 1 for Microsoft Dynamics AX 2012 R3
here - http://go.microsoft.com/fwlink/?LinkId=296433
Note: As part of CU1, there are two executables: 459780_intl_i386_zip.exe –
extracts to DynamicsAX2012R2-KB2807685.zip. 459781_intl_i386_zip.exe –
extracts to DynamicsAX2012R2-KB2807685-BinaryOnly.zip.
Extract and install the DynamicsAX2012R2-KB2807685.zip version of Retail POS
Plugins and Retail online channel.
Use this procedure to install CU1. If you install other Microsoft Dynamics AX
components at the same time, the installation pages vary, depending on the
components that you are installing.
1. Start Microsoft Dynamics AX Update by using the axupdate.exe file.
2. Under Microsoft Dynamics AX Update Setup, click Next, and then
advance through the wizard page until the Select components page
is displayed.
3. On the Select components page, select Retail POS Plug-Ins and
Retail Online Channel under Retail Components, and then click
Next.
Module 2: Development Environment
2 - 5
4. After the installation is complete, click Finish to exit the wizard.
After you install the Cumulative update, a new folder is created in the Documents
> Retail SDK folder named Online Channel. A new PowerShell script file that is
named UpdateAssemblyIdentities.ps1 also is created.
After the installation of Retail SDK and CU1, the folders that you created are
displayed.
FIGURE 2.1: FOLDERS CREATED IN DOCUMENTS > RETAIL SDK FOLDER
AFTER YOU INSTALL RETAIL SDK AND CU1
Commerce Run-time (CRT) services solution
After you have installed all the tools and components that you must have, you can
start Visual Studio and open the Services Project that was installed as part of the
Retail SDK package.
1. Start Visual Studio.
2. Click File > Open > Project / Solution.
3. In the Open Project dialog box, browse to Documents > Retail SDK >
Commerce Run-time > Services folder.
4. Select the Services.sln solution file.
5. Click Open.
The Services solution contains three projects.
FIGURE 2.2: PROJECTS UNDER SERVICES SOLUTION
Storefront solution
After you have installed all tools that you must have, such as components and
CU1, you can start Visual Studio and open the Storefront solution. This was
Microsoft Dynamics for Retail in Ecommerce stores: Development and
Customization
2 - 6
installed as part of the CU1 installation.
1. Start Visual Studio in Administrator mode.
2. Click File > Open > Project / Solution.
3. In the Open Project dialog box, browse to Documents > Retail SDK >
Online Channel > StoreFront folder.
4. Select the StoreFront.sln solution file.
5. Click Open.
Note: When you open the StoreFront solution for the first time, you may
receive multiple confirmation messages (displayed here) asking whether you want
to upgrade the projects to a SharePoint 2013 solution. Click Yes for all messages.
Do you want to upgrade "SharePoint.Web.WebParts.csproj" to a SharePoint 2013
solution? As soon as the upgrade is complete, the solution cannot be deployed to
SharePoint 2010. Do you want to continue?
The StoreFront solution contains six C# projects as displayed in “Projects under
Storefront Solution.”
FIGURE 2.3: PROJECTS UNDER STOREFRONT SOLUTION
You can explore the projects within the solution and make sure that you can
browse through the code. Close Visual Studio after moving through the projects.
Strong Name for Code Signing
You must assign a new strong name to the source code because you will be
recompiling the source code. The fully qualified name of the rebuilt assemblies
will differ from the ones that were provided to you by Microsoft. Before you
compile the source code, you must provide your own code signing key file. You
can reuse your company’s key file or create a new strong name file for signing the
customized code.
Module 2: Development Environment
2 - 7
Follow these steps to create SNK file and update source code with new strong
name file:
1. Create a new SNK file either by using Visual Studio or Strong name
tool (sn.exe) and name it strongnamekey.snk.
2. Save the strongnamekey.snk file in the Documents > Retail SDK
folder.
3. Extract the thumbprint of the strong name.
Create a sample Class library project and enable code signing by using
the strongnamekey.snk. Build the Class library project. As soon as the DLL
is created (usually in the bin\debug folder), run the strong name tool to
extract the token. The command is:
Sn.exe –Tp <project.dll>
This command returns the token. Copy and paste it in the
UpdateAssemblyIdentities.ps1 script file.
4. Edit the UpdateAssemblyIdentities.ps1 script file that has the version
number and the thumbprint of the key file. The following two
parameter values should be changed in the PowerShell script file.
# configure these 2 below:
$newVersion = "1.0.0.0"
$newStrongNameKeyHash = "insert token here"
5. Execute the script “Retail SDK\UpdateAssemblyIdentities.ps1”. This
may take several minutes. This process changes any source code with
version references to the new strong name.
Map a network drive to the SharePoint 2013 files for
online stores.
You can map a network drive to access files that Microsoft SharePoint Server uses
to support a Microsoft Dynamics AX 2012 R3 Retail online store. First, you must
make sure that you have Web Distributed Authoring and Versioning (WebDAV)
installed and running on your computer.
These procedures work for Windows Server operating systems.
Note: For information about mapping a drive on other operating systems,
see How to: Map a network drive to the SharePoint 2013 Master Page Gallery that
is located at http://msdn.microsoft.com/en-us/library/jj733519.aspx.
Microsoft Dynamics for Retail in Ecommerce stores: Development and
Customization
2 - 8
To verify that WebDAV is installed and running:
1. Click Start > Administrative Tools, and then click Services.
2. Scroll through the list of services and verify that the WebClient
service is started.
3. If the WebClient service name is not present, you must install the
Desktop Experience Windows feature.
To install Windows Desktop Experience:
1. Click Start > Administrative Tools, and then click Server Manager.
2. Right-click the Features node and then click Add Features.
3. In the Add Feature Wizard, select Desktop Experience.
4. Click Next and install the feature. The installation may take several
minutes.
5. Right-click the Web Client service, and then click Properties.
6. On the General tab, set the Startup Type to Automatic.
To map a network drive
1. Open Windows Explorer.
2. Right-click My Computer and then click Map Network Drive….
3. Enter the path of the online store publishing portal in the Folder box.
The path typically resembles the following:
http://<your-server-name>:40003/sites/RetailPublishingPortal
4. Click Finish.
The drive appears in the list under Computer. The folders that contain the files
that SharePoint uses are listed when you expand the node for the drive. Master
pages are listed in the _Catalogs folder. This is a hidden folder.
To view hidden folders:
1. Click Start > Control Panel, and then click Folder Options.
2. On the View tab, select Show hidden files, folders, and drives.
3. Clear Hide protected operating system files.
4. Click OK to close the Folder Options window.
Module 2: Development Environment
2 - 9
Module Review
Test Your Knowledge
Test your knowledge with the following questions.
1. What are the prerequisites to map a network drive to SharePoint 2013 files?
2. Why is new strong naming required for the Storefront or Services solution
file?
Microsoft Dynamics for Retail in Ecommerce stores: Development and
Customization
2 - 10
Test Your Knowledge Solutions
Module Review and Takeaways
1. What are the prerequisites to map a network drive to SharePoint 2013 files?
MODEL ANSWER:
Web Distributed Authoring and Versioning (WebDAV) must be installed and
running on your computer.
2. Why is new strong naming required for the Storefront or Services solution
file?
MODEL ANSWER:
You must assign a new strong name to the source code because you will be
recompiling the source code. The fully qualified name of the rebuilt
assemblies will differ from the ones that were provided to you by Microsoft.
3 - 1
MODULE 3: BRANDING THE ECOMMERCE SITE
Module Overview
Microsoft Dynamics AX 2012 R3 Retail includes a sample online starter store. The
starter store is a site built by using the new site cross-site publishing model in
Microsoft SharePoint Server 2013.
You can customize the visual design of the starter Ecommerce site by changing
certain types of files. For example, you can change the store logo by changing
master pages, or you can change the background color of store pages by making
modifications to cascading style sheet (CSS) files.
You can change the functionality of the Ecommerce site by customizing the Web
Parts or the CRT Services, or both. In the starter Ecommerce site, there are two
types of Web parts that are used to surface information or control behavior on the
pages. They are Content Search Web parts (CSWP) and Custom Web Parts. The
CSWP uses the Search index database to display information, whereas the custom
Web Parts uses the CRT Services to control behavior or display content.
Objectives
The objectives of this module are as follows:
1. Explain how to change the appearance and behavior of the
Ecommerce site.
2. Describe how to change the behavior of the Ecommerce site.
3. Examine the different components for the Ecommerce site that can
be extended for customization purposes.
Microsoft Dynamics for Retail in Ecommerce stores: Development and
Customization
3 - 2
Customize the Visual Design of a Ecommerce Site
Every customer wants to apply their corporate brand to the appearance and
behavior of their Ecommerce site. In this lesson, we analyze the details of the
components that are available in the Ecommerce site. You can use these
components to change the visual design of your Ecommerce site.
The following list describes five types of files in which you can change the
elements on individual pages to customize the visual design of the starter store.
File Type Description
Master Pages Master pages define the shared framing elements,
such as the header and footer for all the pages in
your site.
Page Layouts Page layouts contain the page contents and its
layout. Each page layout uses a specific master page
and can act as a base page for multiple instances of
the page layout. Each instance has a different page
name. In the starter store, each page has a
corresponding page layout. For example,
Welcome.aspx has a corresponding file named
WelcomeLayout.aspx.
Cascading Style Sheets CSS files provide the page layouts with page content
styling and formatting.
JavaScript JavaScript files provide the page layouts with client-
side scripting functionality.
Display Templates Display templates are used in Web Parts. They use
search technology to display the results of a query
that was made to the search index. Display templates
control which managed properties are shown in the
search results and how they display in the Web Part.
Each display template is made of two files: an HTML
version of the display template that you can edit in
your HTML editor, and a .js file that SharePoint uses.
How to: Customize Master Pages
This topic shows how to customize a master page by updating the Welcome page
of the starter store. Log on your development environment by using
administrative credentials.
Module 3: Branding the Ecommerce Site
3 - 3
Note: For all customizations on the Ecommerce site, you must log in to your
development environment by using an administrator logon.
1. Open a web browser and browse to the Welcome page for the
starter store. Typically, the URL for the Welcome page resembles the
following:
http://<your-server-name>:40002/sites/RetailPublishingPortal
Note: View the behavior of the page. A slide show cycles through three
pictures representing product categories. At the top left side of the page, you can
see the Contoso logo.
2. Open a web browser on a computer where you are logged in by
using the administrative account for SharePoint.
3. Browse to the Site Settings page of the store. Use port 40003 and
sign in with administrative credentials. The link to the Site Settings
page is typically found at a URL that resembles the following:
http://<computer-
name>:40003/sites/RetailPublishingPortal/_layouts/15/settings.a
spx
Best Practice: Add this page to your web browser’s Favorites for convenience
in the future.
4. Click Master pages and page layouts in Web Designer Galleries to
view a list of files in the Master Page Gallery page.
5. Right-click a file that you want to edit, such as Storefront.master,
and then click Check Out.
6. Right-click the file, and then click Download a Copy.
7. Edit the file by using Visual Studio or another editor. For example, in
the following code from Storefront.master, you can change the logo
file that is displayed on each page. The file is named
logo_Contoso_main.png. You can edit that file or replace the file
name with the name of a file that contains a graphic of similar size to
display your company logo. The following code shows the path and
file name of the logo in the Storefront.master file:
<div class="msax-Main">
<div class="s4-notdlg msax-LogoBar">
<div class="msax-Logo">
<a id="A1" href="<% $SPUrl:~sitecollection/ %>" runat="server">
<img src="/_layouts/15/Images/Storefront/logo_Contoso_main.png" />
</a> </div>
8. To upload the file and add your changes to the site, click Upload
Document on the Files ribbon.
Microsoft Dynamics for Retail in Ecommerce stores: Development and
Customization
3 - 4
9. Refresh the Welcome page in your initial browser session to see your
changes.
The following are other ways and tools that you can use to access the master page
or any other files on SharePoint, required for customization:
1. Design Manager
2. SharePoint 2013 Designer
3. Visual Studio 2012
4. Mapped Network drive
For more information about how to use Microsoft SharePoint Server to change
the visual site design, see http://msdn.microsoft.com/en-us/library/jj733518.aspx.
Customize Page Layouts
Each page layout uses a specific master page, and each page has a corresponding
page layout. For example, the Welcome page for the site, Welcome.aspx, has a
corresponding page layout file that is named WelcomeLayout.aspx.
This topic demonstrates how to customize a page layout by updating the starter
store’s Welcome page layout.
To update a page layout
1. Open a web browser and browse to the Welcome page for the
starter store. Typically, the URL for the Welcome page resembles the
following:
http://<your-server-name>:40002/sites/RetailPublishingPortal
Note: View the behavior of the page. A slide show cycles through three
pictures that represent product categories. At the top left side of the page, you can
see the Contoso logo.
2. Open another web browser on a computer where you are logged in
by using the administrative account for SharePoint.
3. Browse to the Site Settings page of the store. Use port 40003 and
sign in with administrative credentials. The link to the Site Settings
page is typically found at a URL that resembles the following:
http://<computer-
name>:40003/sites/RetailPublishingPortal/_layouts/15/settings.a
spx
4. Click Master pages and page layouts in Web Designer Galleries to
view a list of files in the Master Page Gallery page.
Module 3: Branding the Ecommerce Site
3 - 5
5. Right-click a file that you want to edit, such as WelcomeLayout.aspx,
and then click Check Out.
6. Right-click the file and then click Download a Copy.
7. Edit the file by using Visual Studio or another editor. For example, the
following code from WelcomeLayout.aspx specifies the names of the
tabs on the Welcome page.
<div class="msax-tabs">
<ul>
<li><a onclick="return false;" href="#tabs-1">Customer
favorites</a></li>
<li><a onclick="return false;" href="#tabs-2">Staff
recommendations</a></li>
<li><a onclick="return false;" href="#tabs-3">Shop by
brand</a></li>
<li><a onclick="return false;" href="#tabs-4">Clearance
items</a></li>
8. Change the names of the tabs by editing the text. You can use the
following code to change the names of the tabs.
<div class="msax-tabs">
<ul>
<li><a onclick="return false;" href="#tabs-1">Your
favorites</a></li>
<li><a onclick="return false;" href="#tabs-2">Our
recommendations</a></li>
<li><a onclick="return false;" href="#tabs-3">Shop by
brand</a></li>
<li><a onclick="return false;" href="#tabs-4">Special
offers</a></li>
9. To upload the file and add your changes to the site, click Upload
Document on the Files ribbon.
10. Refresh the Welcome page in your initial browser session to see your
changes.
Change Appearance and Behavior by Using Display
Templates
Display templates in SharePoint Server 2013 are used in Web Parts that use search
technology (referred to in this article as Search Web Parts) to display the results of
a query that was made to the search index. Display templates control which
managed properties are displayed in the search results, and how they display in
the Web Part. Each display template is made of two files: an HTML version of the
display template that you can edit in your HTML editor, and a .js file that
SharePoint uses.
There are two primary types of display templates:
Control templates determine the overall structure of how results are
presented. Structures include lists, lists with paging, and slide shows.
Item templates determine how each result in the set is displayed.
Includes images, text, video, and other items.
Microsoft Dynamics for Retail in Ecommerce stores: Development and
Customization
3 - 6
To change an existing display template:
1. Open your mapped network drive to the Master Page Gallery.
2. Open the Content Web Part folders in the Display Templates folder.
3. Open an existing display template such as
Contoso_default_Item_ProductDetails.html in a HTML editor.
4. To prevent the storefront from displaying the available item count,
remove the following line from the display template.
Every time you save the HTML file, any changes are synched to the
associated .js file.
5. Browse to your publishing site.
6. In the right corner of the page, select Settings, and then select
Design Manager.
7. In Design Manager, in the left navigation pane, select Edit Display
Templates. Your HTML file now displays with a Status column that
shows one of two statuses:
o Warnings and Errors
o Conversion successful
Change Appearance and Behavior by Using Cascading
Style Sheets (CSS)
You can customize the visual design of the Microsoft Dynamics AX 2012 R2 starter
store by changing certain types of files. Cascading style sheet (CSS) provide the
page layouts with styling and formatting. For example, you can change the color
of elements on store pages by making modifications to CSS files.
For a typical installation, the path for the folder location of the CSS files resembles
the following:
…\Program Files\Common Files\Microsoft Shared\Web Server
Extensions\15\TEMPLATE\LAYOUTS\1033\STYLES\Storefront
The following table lists the cascading style sheets used in the online starter store.
Cascading Style Sheet Description
AddressEdit.css Defines the formatting for the components that
display on the AddressEdit page.
AssociateCustomer.css Defines the formatting for the components that
display on AssociateCustomer page.
Module 3: Branding the Ecommerce Site
3 - 7
Cascading Style Sheet Description
CheckoutConfirm.css Defines the formatting for the components that
display on CheckoutConfirm page.
Control_ProductVariant.css Defines the formatting that applies to the
control that was selected for the Item Details
display template.
Core.css Defines global formatting that applies to all
pages and UI components of the starter store.
CustomerEdit.css Defines the formatting for the components that
display on the Login page.
Item_ProductDetails.css Defines the formatting for the components that
display on the ProductDetails page.
Item_ProductGallery.css Defines the formatting for the components that
display on the ProductGallery page.
Item_Recommended Defines the formatting that applies to the
Item_Recommended display template that is
used by the following web parts: Related
Products, Customer Favorites, Shop By Brand,
Clearance items.
Login.css Defines the formatting for the components that
display on the Login page.
MyAccount.css Defines the formatting for the components that
display on the MyAccount page.
OrderCheckout.css Defines the formatting for the components that
display on the Checkout page.
OrderDetails.css Defines the formatting for the components that
display on the OrderDetails page.
OrderHistory.css Defines the formatting for the components that
display on the OrderHistory page.
ProgressBar.css Defines the formatting for the checkout
progress bar on the OrderCheckout page that is
displayed for Shipping information, Billing
Information, and Review.
Register.css Defines the formatting for the components that
display on the page that enables a user to
register a new account.
Reset.css Resets some default HTML formatting that is
defined in Core.css on the master page to make
the pages as browser-independent as possible.
ShoppingCart.css Defines the formatting for the components that
Microsoft Dynamics for Retail in Ecommerce stores: Development and
Customization
3 - 8
Cascading Style Sheet Description
display on the ShoppingCart page.
Tab.css Defines the formatting for the tab control that
displays on the Quickview and ProductDetails
pages.
Welcome.css Defines the formatting for the components that
display on the Welcome page.
The Welcome page for the starter store contains a slide show with a counter. The
topic demonstrates how to change the CSS file for the Welcome page to change
the colors that highlight the current slide number.
Update the CSS file for the Welcome Page to change the color of the
slide counter
1. Open a web browser and browse to the Welcome page for the
starter store. Typically, the URL for the Welcome page resembles the
following:
http://<your-server-name>:40002/sites/RetailPublishingPortal
Note: View the behavior of the page. A slide show cycles through three
pictures representing product categories. In the lower-right-hand corner of the
slides, a counter displays the current slide number. The following illustration shows
the counter displaying slide number one in the original colors of gray and white.
The following illustration displays the default Welcome page with the slide show
counter
FIGURE 3.2: DEFAULT WELCOME PAGE WITH SLIDE SHOW COUNTER
2. Browse to the folders on the computer where the online starter store
is deployed. The path for the folder location for CSS files typically
resembles the following:
Module 3: Branding the Ecommerce Site
3 - 9
…\Program Files\Common Files\Microsoft Shared\Web Server
Extensions\15\TEMPLATE\LAYOUTS\1033\STYLES\Storefront
3. Open the Welcome.css file. You can use Visual Studio or any editor
that you prefer. For example, consider the slide show on the
Welcome page. That is the first page that you see when you access
the store on port 40002. The indicator displays the number of the
current slide. In the starter store, these are numbered 1, 2, and 3, and
the numbers are white on a black background.
The following code from Welcome.css shows initial values for color
and border.
.msax-reel_paging a {
padding: 5px;
text-decoration: none;
color: #fff;
}
.msax-reel_paging a.active {
font-weight: bold;
background: #1c2023;
border: 1px solid #101315;
-moz-border-radius: 3px;
-khtml-border-radius: 3px;
-webkit-border-radius: 3px;
}
The following table lists the original colors that are used.
4. Change the values for color and border as shown in the following
code to create a display that has text in red (#f00) and highlights the
current slide number in green (#3c8a3c).
.msax-reel_paging a {
padding: 5px;
text-decoration: none;
color: #ff0;
}
.msax-reel_paging a.active {
font-weight: bold;
background: #1c2023;
border: 1px solid #3c8a3c;
-moz-border-radius: 3px;
-khtml-border-radius: 3px;
-webkit-border-radius: 3px;
}
Parameter Element Color Code Color
Color: Text #fff White
border Border for Text #101315 Dark gray
Microsoft Dynamics for Retail in Ecommerce stores: Development and
Customization
3 - 10
The following table lists the new colors that you have entered.
Parameter Element Color Code Color
Color: Text #f00 White
border Border for Text #3c8a3c Dark gray
5. Save and close the file.
6. Refresh the Welcome page in your initial browser session to view
your changes.
The following illustration displays the slide show counter with colors that
correspond to the changes that you made.
FIGURE 3.3: DEFAULT WELCOME PAGE WITH CHANGES IN COLOR OF SLIDE
SHOW COUNTER
Customize User Interface Behavior
The Microsoft Dynamics AX 2012 R3 Retail starter store is a site that is built by
using the commerce runtime (CRT) and the new site authoring and publishing
model in Microsoft SharePoint Server 2013. You can use the Retail starter store as
a basis for developing your own online store by using JavaScript methods for
supported events. The starter store includes events that correspond to certain
shopping activities, such as adding an item to the shopping cart and removing an
item from the shopping cart. You can use these events to add custom
functionality in a way that resembles using the jQuery eventing model. You can
turn your custom functionality on and off by using methods such as OnAddToCart
and OffAddToCart. For example, you can change the message that is displayed
Module 3: Branding the Ecommerce Site
3 - 11
when an item is added to the shopping cart.
Additional Reading: To learn more about jQuery, click here:
http://www.jquery.com . To learn more about the jQuery Eventing model, click here:
http://go.microsoft.com/fwlink/?LinkID=296268&clcid=0x409
The following topic shows how to change the message that is displayed when an
item is added to the shopping cart. It also lists the methods for the types of events
that are available to change the behavior of the starter store.
To change the message displayed when an item is added to the
shopping cart
1. Open a web browser and move to the Welcome page for the starter
store. The URL for the Welcome page typically resembles the
following:
http://<your-server-name>:40002/sites/RetailPublishingPortal
2. Add some items to the shopping cart.
3. Browse to the folders on the computer where the online starter store
is deployed. Files that contain JavaScript for the starter store pages
typically are found in a path that resembles the following.
…\Program Files\Common Files\Microsoft Shared\Web Server
Extensions\15\TEMPLATE\LAYOUTS\Storefront\js
4. Open the file Storefront.js. You can use Visual Studio or any editor
that you prefer.
5. Find the line that contains msaxServices.OnAddToCart. The following
example shows how to change the code after line 170.
msaxServices.OnAddToCart(function () {
// msaxPopupOverlay.show('Updating shopping cart...');
alert('Adding to cart...');
});
6. Refresh the store pages and add an item to the cart. The following
message is displayed in the message window: Adding to cart…. Click
OK to continue.
Extending the Functionality of the Online Store
The starter store is designed to be extensible at many points in the shopping
experience. For example, you can add the following JavaScript code in any
JavaScript file for a page that includes the shopping cart objects. The following
example causes a message to display before an item is added to the shopping
cart.
var addToCartVM = new
Microsoft.Dynamics.Retail.SharePoint.Web.UI.ViewModel.AddToCartViewModel(
services, $view);
Microsoft Dynamics for Retail in Ecommerce stores: Development and
Customization
3 - 12
// Performed before AddToCart
addToCartVM.OnAddToCart(function (event) {
alert('Adding item to cart');
});
Method Names for Supported Events and Objects
The following tables list the method names and objects that are available to turn
functionality on and off for supported events in the view models for the starter
store. The JavaScript code for the view models typically can be found in a path
that resembles the following after you map a drive to the SharePoint Server 2013
files. (Z:\Scripts\ViewModel)
The following table lists methods for
Microsoft.Dynamics.Retail.SharePoint.Web.UI.ViewModel.AddToCartViewModel.
The code for this view model is found in the file AddToCart.js.
Method Name Data Objects
Available
Description
OnAddToCart,
OffAddToCart
None Raised on a call to AddToCart.
OnAddToCartSuccess,
OffAddToCartSuccess
ShoppingCart Raised after a successful return
from AddToCart.
OnAddToCartFailure,
OffAddToCartFailure
None Raised if no response is returned
from a call to AddToCart.
The following table lists methods for the
Microsoft.Dynamics.Retail.SharePoint.Web.UI.ViewModel.CheckoutViewModel.
The code for this view model is found in the file Checkout.js.
Method Name Data Objects
Available
Description
OnCheckout, OffCheckout
None Raised on a call to the Checkout
method.
OnNoItemCheckout, OffNoItemCheckout
None Raised on a successful response to
the AddToCart method.
The following table lists methods for the
Microsoft.Dynamics.Retail.SharePoint.Web.UI.ViewModel.ShoppingCartViewModel
. The code for this view model is found in the file ShoppingCart.js.
Module 3: Branding the Ecommerce Site
3 - 13
Method Name Data Objects
Available
Description
OnBeforeRender,
OffBeforeRender
ShoppingCart Raised on a call to the Render
method of the shopping cart view.
OnAfterRender,
OffAfterRender
ShoppingCart Raised after execution of the
Render method of the shopping
cart view.
OnRemoveFromCart,
OffRemoveFromCart
ShoppingCart Raised on a call to the
RemoveFromTCart method.
OnUpdateQuantity,
OffUpdateQuantity
ShoppingCart Raised on a call to the
UpdateQuantitymethod.
The following table lists methods for the
Microsoft.Dynamics.Retail.SharePoint.Web.UI.ViewModel.MiniShoppingCartViewM
odel. The code for this view model is found in the file MiniShoppingCart.js.
Method Name Data Objects
Available
Description
OnBeforeRender,
OffBeforeRender
ShoppingCart Raised on a call to the Render method
of the MiniShoppingCartViewModel.
OnAfterRender,
OffAfterRender
ShoppingCart Raised after execution of the Render
method of the
MiniShoppingCartViewModel.
OnShow, OffShow None Raised on a call to the Show method
of the MiniShoppingCartViewModel.
OnHide, OffHide None Raised on a call to the Hide method of
the MiniShoppingCartViewModel.
Design and Import/Export Packages
In SharePoint 2013, Design Manager help web developers and designers build
and export the visual design of a SharePoint site collection as a package. This
package can be distributed easily to customers or other designated groups for
installation on their site collections. This new feature reduces the complexity of
transporting designs, and makes it easier for customers to outsource the visual
design of their sites. For example, some usage scenarios can include the following:
New Design - A company with limited web design capabilities might
contract a vendor agency to update their current SharePoint site with
a more modern interpretation. The agency can create the site and
easily package the contents for importing back into the company
SharePoint farm.
Microsoft Dynamics for Retail in Ecommerce stores: Development and
Customization
3 - 14
Cross-Site Publishing - An enterprise IT department that uses cross-
site publishing in SharePoint 2013 may have to share a visual design
across multiple site collections. They create the site in-house and want
a simple way to transport the design across several SharePoint
websites. The design package functionality through Device Manager
enables them to export and import with reduced administrative
support and complexity.
This topic can help you understand design packaging in SharePoint 2013 by
providing an overview of package creation. This topic also offers workflow
guidance for package exporting and importing and discusses required permissions
for specific operations and design package architecture.
Creating a design package
A user creates a design package, which is known as a SharePoint solution package
(.wsp file), on their SharePoint site through Design Manager in Site Settings. The
steps for creating the package follows other Design Manager steps for branding
and publishing a SharePoint site. This includes uploading design files, creating a
master page, and editing page layouts. After the site is published, it is a fairly
simple process to create the .wsp file for export.
This figure displays the option in Design Manager for naming and creating the
design package.
FIGURE 3.4: CREATING A DESIGN PACKAGE
You also can import a design package from another SharePoint 2013 site
collection through Design Manager on the Welcome page, or by selecting
Import design package in Site Settings.
There is a check box for including the search configuration in the design package.
Select this option if you are designing a site and creating conditional search
results or controlling the search experience. This configuration contains assets like
query rules, result sources, result types, and any schema and ranking models.
To make sure that the import of the search configuration does not fail, there must
not be duplicate names for any elements of the search configuration. For example,
if you have a query rule in a site collection named SampleQueryRule, and you
Module 3: Branding the Ecommerce Site
3 - 15
import it into another site collection with an existing rule named
SampleQueryRule, importing the search configuration fails. To prevent this, you
can rename or delete the query rule on the source or on the target. Result sources
and the schema also have to be uniquely named.
If you want to include a search configuration in your design package, you must
start the following features at the site level under Manage Site Features before
you export the design package:
Search Config Data Content Types
Search Config Data Site Columns
Search Config List Instance Feature
Search Config Template Feature
If you want your design to be published on the target of import, you should
publish all design assets or disable major versioning in design-related libraries on
the source of export. Design Manager exports only the most recent version of
each asset from the source. For example, if you have version 1.1 of a master page
on the source it will be copied to the target as a draft; however, version 1.0 is not
copied. Also, files that are checked out are not exported.
Exporting and importing a design package
You can approach an end-to-end packaging workflow in several ways, with much
of the approach depending on your objectives and available design resources.
You may decide to outsource to a vendor agency, or do the work in-house if you
have internal resourcing. The following table provides a sample workflow and
exchange between a client and a vendor agency over the design, exporting, and
importing of the design package. It also provides the required permissions for
design-related operations, and packaging operations.
ID Action Description
1 Customer
contracts vendor
agency to create
visual design.
The vendor designer creates site, based on
company requirements.
Note: The vendor designer must have the
Designers permission level to use Design Manager
and create and export packages. More specifically,
the vendor designer must have the Design
permission that enables viewing, adding, updating,
deleting, approving, and customizing of visual
designs.
2 Vendor designer
exports visual
design into a
The vendor designer exports the SharePoint
solution package (.wsp file) after the other required
Microsoft Dynamics for Retail in Ecommerce stores: Development and
Customization
3 - 16
ID Action Description
design package. branding and publishing steps are completed.
The design package is delivered to the customer by
using a security channel.
3
Customer
imports
visual
design into
their
specified
SharePoint
2013 site
collection.
The customer receives the design package by using
a security channel.
By using the Welcome page in Design Manager or
by selecting Import design package in Site
Settings, the customer imports the .wsp file and
applies the design package to the specified site
collection.
Note: The customer must have the
Designers permission level to use Design Manager
and import design packages.
Design Manager for Image Renditions
Image renditions enable you to display different sized versions of an image on
different pages in a publishing site based on the same source image. When you
create an image rendition, you specify the width and height for all images that use
that image rendition.
Image renditions are available for every image that is uploaded to a library in that
site collection. For example, designers can create an image rendition to display
thumbnail images and another image rendition to display banner images. When
an image is added to a page, the author can specify the image rendition to use on
that image. Authors can also crop the image rendition to specify the section of the
image to use in the image rendition. The correct image size is displayed when the
page is rendered.
Image renditions enable you to display a single image in multiple ways. You can
display an image in various sizes or with different cropping. The first time that an
image is requested, SharePoint Server uses the specified image rendition to
generate the image. When a user views a SharePoint site, the correctly sized
version of the image is downloaded to the client computer. This reduces the size
of the file that is downloaded to the client and improves site performance.
Create an image rendition
When an image rendition is created, SharePoint Server 2013 creates a unique ID
that identifies that image rendition. An image is generated when SharePoint
Module 3: Branding the Ecommerce Site
3 - 17
Server first receives a request for the image rendition.
During deployment of the Ecommerce site, several image renditions are created.
To create an image rendition
1. Verify that the user account that is performing this procedure has, at
a minimum, Design permissions to the top-level site of the site
collection.
2. In a browser, go to the top-level site of the publishing site collection.
3. Click the Settings icon. On the Site Settings page, in the Look and
Feel section, select Image Renditions.
Note: The Image Renditions page can also be opened from the default
home page of the publishing site. In the “I'm the Visual Designer” section, select
Configure image renditions.
4. On the Image Renditions page, select Add new item.
5. On the New Image Rendition page, in the Name box, enter a name
for the rendition. For example, enter Thumbnail_Small.
6. In the Width and Height text boxes, enter the width and height, in
pixels, of the rendition, and then click Save.
Edit an image rendition
When an image rendition is edited, the new dimensions take effect the next time
that the image is requested. If there is an image that was generated previously
from the image rendition, the image is regenerated with the new dimensions the
next time that the image is requested.
To edit an image rendition
1. Verify that the user account that is performing this procedure has, at
a minimum, Design permissions to the top-level site of the site
collection.
2. In a browser, go to the top-level site of the publishing site collection.
3. Select the Settings icon. On the Site Settings page, in the Look and
Feel section, select Image Renditions.
Note: The Image Renditions page can also be opened from the default
home page of the publishing site. In the ‘I'm the Visual Designer’ section, select
Configure image renditions.
4. On the Image Renditions page, select the image rendition that you
want to edit.
Microsoft Dynamics for Retail in Ecommerce stores: Development and
Customization
3 - 18
5. On the Edit Image Rendition page, change the name, width, or
height of the image rendition.
Add an image rendition
When you add an image to a page in a SharePoint publishing site, you can specify
the image rendition to use for that image. When the page is rendered in a
browser, the correct image size is displayed. You can specify the image rendition
in the Rich Text Editor, in an image field control, or in the image URL.
Specify the image rendition by using the Rich Text Editor
When an image is inserted in a page, you can specify the image rendition to use
so that the correct image size is displayed when the page is rendered. You can
specify the image rendition in the Rich Text Editor only for images that are stored
in the same site collection as the page that is being edited.
To specify an image rendition by using the Rich Text Editor
1. On the Page tab, select Edit.
2. Select the Settings icon, and then select Add a page.
3. In the Add a page window, enter a name for the page, and then
select Create.
4. Put the pointer in the Page Content field.
5. On the Insert tab, select Picture, and then select From SharePoint.
6. Locate the image that you want to add to the page, select the image,
and then select Insert. The image is displayed at full size.
7. On the Design tab, in the Select group, select Pick Rendition, and
then select an image rendition. The image is displayed according to
the size that is specified for the image rendition.
Note: The Pick Rendition command is available only for images that are
stored in the same site collection as the page that is being edited.
8. If you want to crop the image rendition, select Pick Rendition, and
then select Edit Renditions.
Specify the image rendition in the image URL
You can specify the image rendition by adding the RenditionID, Width, or Height
parameters to the image URL.
RenditionID: Use the RenditionID parameter to specify the ID of the image
rendition to use.
Module 3: Branding the Ecommerce Site
3 - 19
Width: Use the Width parameter to specify the width in pixels of the image
rendition. SharePoint Server attempts to find an image rendition with the
specified width. Next, SharePoint Server seeks an image rendition that has a width
that is larger than the specified width. If there are multiple image renditions that
match this criterion, SharePoint Server uses the image rendition with the closest
width to what was specified. If there is no image rendition with a width that is
equal to or larger than the specified width the original image is used.
Height: Use the Height parameter to specify the height in pixels of the image
rendition. SharePoint Server tries to find an image rendition with the specified
height. Next, SharePoint Server tries to find an image rendition that has a height
that is larger than the specified height. If there are multiple image renditions that
match this criterion, SharePoint Server uses the image rendition with the closest
height to what was specified. If there is no image rendition with a height that is
equal to or larger than the specified height the original image is used.
Width and Height: If both the Width parameter and the Height parameter are
specified, SharePoint Server tries to find an image rendition with the specified
width and height. Next, SharePoint Server tries to find a rendition that is closest to
the width/height ratio specified. If there are multiple matches, the image rendition
that has the closest larger width/height ratio to the requested size is selected.
Note: If the image URL includes the RenditionID parameter and Width and
Height parameters, the Width and Height parameters are ignored.
The following example displays how to use the RenditionID parameter.
HTML
<img src="/sites/pub/Assets/Lighthouse.jpg?RenditionID=2" />
The following example displays how to use the Width and Height parameters.
HTML
<img src="/sites/pub/Assets/Lighthouse.jpg?RenditionID=2" />
Specify the image rendition in the image field control
A developer can specify the image rendition to use in the image field control. Use
the RenditionId property to set the ID of the image rendition.
Crop an image rendition
By default, an image rendition is generated from the center of the image. You can
adjust the image rendition for individual images by cropping the section of the
image that you want to use. For example, if a photo shows a lighthouse scene but
the image rendition does not show the entire lighthouse (see “Original Image
Rendition”), you can change the selected image area so that the entire lighthouse
Microsoft Dynamics for Retail in Ecommerce stores: Development and
Customization
3 - 20
is displayed (see “Cropped image rendition”).
FIGURE 3.5: ORIGINAL IMAGE RENDITION
FIGURE 3.6: CROPPED IMAGE RENDITION
An image rendition can be cropped in the asset library or on a page without
changing the original image.
Image renditions can be cropped in the following ways:
Designers can crop an image rendition in the asset library. For
Module 3: Branding the Ecommerce Site
3 - 21
example, a designer may want to specify how an image is displayed in
the thumbnail image rendition.
Authors can crop an image rendition when they insert an image into
a page. This enables them to customize the look of their page. When
an author crops an image rendition, this also changes the image
rendition for that image. Anyone who uses that image rendition sees
the cropped image.
Note: An author can crop an image rendition only when the original image is
stored in a library that is in the same site collection as the page that is being edited.
For example, in cross-site publishing scenarios, an author can crop the image
rendition only if the image is stored in the same site collection as the catalog
content. Otherwise, the image rendition must be cropped in the asset library.
Designers can crop an image rendition in the asset library.
To crop an image rendition in the asset library
1. Verify that the user account that is performing this procedure has
Write permissions to the asset library where the image is located.
2. In a browser, go to the asset library.
3. Rest the pointer in the lower-right corner of the image whose
rendition you want to change, select the ellipses (...) that appears, and
then select EDIT RENDITIONS.
Note: You can also open the Edit Renditions page by putting the pointer
over the preview image in the asset library, and then selecting the check box that is
displayed at the bottom of the preview image. On the Design tab, select Edit
Renditions.
The Edit Renditions page displays a preview image for each image rendition that is
defined in the site collection.
4. Locate the image rendition that you want to change, and then select
Click to change.
5. In the Crop Rendition window, use the image tool to select the
section of the image that you want to use in the image rendition.
6. Click Save.
If the image and the page that is being edited are in the same site collection, you
can also crop an image rendition by using the Rich Text Editor.
Crop an image rendition on a page
Authors can crop an image rendition when they insert an image into a page. This
Microsoft Dynamics for Retail in Ecommerce stores: Development and
Customization
3 - 22
enables them to customize the look of their page. When an author crops an
image rendition, this also changes the image rendition for that image. Anyone
who uses that image rendition sees the cropped image.
To crop an image rendition on a page
1. Verify that the user account that is performing this procedure has
Write permissions to the asset library where the image is located.
2. In a browser, go to the SharePoint site that contains the image.
3. On the Page tab, select Edit.
4. Select the image that you want to crop.
5. In the Image tab of the ribbon, in the Select group, select Pick
Rendition, and then select Edit Renditions.
The Edit Renditions page displays a preview image for each image rendition that
is defined in the site collection.
Note: The Pick Rendition command is available only for images that are
stored in the same site collection as the page that is being edited.
6. Locate the image rendition that you want to change, and then select
Click to change.
7. In the Crop Rendition window, use the image tool to select the
section of the image to use in the image rendition.
8. Click Save.
Delete an image rendition
When an image rendition is deleted, that image rendition is no longer generated
for images. If a site requests the deleted image rendition, the original image is
returned.
To delete an image rendition
1. Verify that the user account that is performing this procedure has, at
a minimum, Design permissions to the top-level site of the site
collection.
2. In a browser, go to the top-level site of the publishing site collection.
3. Select the Settings icon. On the Site Settings page, in the Look and
Feel section, select Image Renditions.
Note: The Image Renditions page can also be opened from the default
home page of the publishing site. In the ‘I'm the Visual Designer’ section, select
Configure image renditions.
Module 3: Branding the Ecommerce Site
3 - 23
4. On the Image Renditions page, locate the image rendition that you
want to delete, and then click Delete.
Customize the Functionality of an Ecommerce Site
Microsoft Dynamics AX 2012 introduces a new suite of features that help you
deploy, manage, and customize an online sales channel that is fully integrated
with Microsoft Dynamics AX. Ecommerce investments include a starter online
store that is built on Microsoft SharePoint Server 2013, developer tools, and
administrative and runtime components that integrate the online channel with
Microsoft Dynamics AX. By using this new suite of Ecommerce features, you can
centrally manage products, merchandising, and order fulfillment for all aspects of
your online sales channel directly in Microsoft Dynamics AX. The runtime
component enables you to deliver content and retail services in a scalable way.
The new starter online store speeds up the development of a highly customized
Ecommerce site. The starter online store includes the patterns and best practices
that are required to support production-ready deployments. This includes
powerful, search-driven, adaptive experiences that are offered by the SharePoint
Server 2013.
In this lesson, we will discuss how to customize and extend the components that
are used in the Ecommerce site.
Lesson Objectives
The objectives of this lesson are as follows:
Explain how to change the UI behavior of the Ecommerce site.
Describe how to modify the UI behavior of the Ecommerce site.
Examine how to change and extend the functionality of the
Commerce Runtime (CRT).
Review how to extend the Commerce Data Exchange: Real time
Service.
Present how to customize or extend Search functionality.
Integrate a New Service in Commerce Runtime
Microsoft Dynamics AX retail services are scalable and extensible services that are
empowered through a combination of the commerce data exchange and the
commerce runtime.
The commerce runtime includes several services that represent particular areas of
functionality for your online store. If one of these services does not meet the
needs of your store, you can completely replace it with your own service and
continue to use the other services that are installed with the commerce runtime.
Microsoft Dynamics for Retail in Ecommerce stores: Development and
Customization
3 - 24
This topic describes how to create a new service and add it to the commerce
runtime configuration.
To create a new service, you must create three different objects. These objects are
Request object, Response object, and Service object. After you create the service,
you must change the Commerce Runtime configuration file. The following steps
highlight this process.
Creating a Service
A service handles any number of service messages. A service message is the
combination of a service request and response. To create a service, implement a
request, a response, and a service.
To create a request object
1. Create a class that inherits from the ServiceRequest class.
Note: The ServiceRequest class encapsulates a service request that is sent to
services. It exposes information about the context and operation context. This lets
you use logging and diagnostics functionality. It also exposes the Validate method
that lets you validate that the parameters that are passed in are valid. It also
exposes the ServiceRequest constructor. This includes the RequestContext object.
The RequestContext object has information about the current request that is being
executed.
2. Implement the ServiceRequest constructor.
3. Optionally implement any validation that you want to perform on the
request.
To create a response object
1. Create an object that inherits from the ServiceResponse class.
2. Implement code to perform the desired functionality. This would
typically be a get or set operation.
To create a service object
1. Create an object that implements the IService interface.
2. Implement an execute method that takes a request object and returns
a class that is a service response.
3. Cast the request as a type the service can handle. If the cast succeeds,
call a method to perform an action.
4. Return a response.
Changing the Commerce Runtime configuration file
Services are enumerated as types in the commerce runtime config file. The
Module 3: Branding the Ecommerce Site
3 - 25
commerce runtime config file controls which types to load. Services are loaded in
the order in which they are listed in the configuration file. All default services are
loaded automatically. However, if you add a new service above one of the default
services, the new service will replace the default service.
Note: You can also programmatically add a service to the catalog by using
the .NET API.
To change the commerce runtime config file
1. Open commerceRuntime.config in your solution.
Note: The location of this file varies based on your deployment. If you are
customizing the SharePoint starter store, you can find the file by using the Internet
Information Services (IIS) Manager. In IIS Manager, find the starter store under the
Sites node. Right-click the public starter store, and then click Explore.
2. Add a line to include your new service. To load an entire assembly,
add a line exactly like the following example from Walkthrough:
Integrating a new Shipping Service.
<add source="assembly" value="ContosoShippingCarrier,
Version=1.0.0.0, Culture=neutral,
PublicKeyToken=6598494e9dab8361, processorArchitecture=MSIL" />
To add a specific type, add a line exactly like the following.
<add source="type" value="Fully_Qualified_Name_Of_Type,
AssemblyName"/>
Customize the Data in Commerce Entity Class
The CommerceEntity class is the base class of all entities in the commerce runtime
(CRT). The CommerceEntity class is a property bag of key value pairs of C#
properties. These properties provide string representations of fields from the
database so that you do not have to remember the names of columns in your
database when you write code. When you use commerce runtime APIs, you must
use commerce entities because the base class expects all the parameters to be of
type CommerceEntity. But after you retrieve data from the database and return it
from the data manager, you can create regular C# objects that you can use in
workflow or services.
For any existing data type, if you add one or more new fields to a table in
Microsoft Dynamics AX, the commerce entity automatically includes those fields
as long as you change the stored procedure or view to return the additional field.
For example, you might want to verify the age of a customer for a particular
transaction. However, that information is not included in the customer object. To
enable the customer commerce entity to include the customer age automatically,
Microsoft Dynamics for Retail in Ecommerce stores: Development and
Customization
3 - 26
you can add a field in a Microsoft Dynamics AX table to store the customer age
and update the view in the commerce runtime to also return customer age.
Note: Adding customer age is an example to demonstrate this concept. You
can also access customer age using another way.
Updating properties in a commerce entity
To update the properties that are available in the commerce entity, you must do
the following:
Identify the field in Microsoft Dynamics AX that you want to expose in
the commerce entity. If the data that you want does not exist in an
existing table, you must create a new field on a new or existing table.
Change the stored procedure or view that specifies the data that is
passed from Microsoft Dynamics AX to the commerce entity.
Update the commerce entity to include the new field.
Create a field in Microsoft Dynamics AX
1. Create the field that you want to use to pass data from Microsoft
Dynamics AX to the commerce entity. Expand the appropriate table
node for the new field, right-click Fields, point to New, and then click
the data type that you want for the field.
Note: If the field that you want to use already exists, go directly to the next
section to change the view that corresponds to the commerce entity that you want
to update.
2. Specify properties for your new field.
3. Add the new field in the CRT database.
4. Update the Synch service to pass the new field.
Change the view to include the new field
1. Connect to your database server in SQL Server Management Studio.
2. Expand the Databases node, expand the node for your CRT database,
expand the Views node, and then find the view that corresponds to
the data entity that you want to change.
3. Right-click the view, point to Script View as, point to ALTER To, and
then click New Query Editor Window.
4. Update the view to include the field that you created.
Update the commerce entity
1. Open the commerce entity in Visual Studio.
2. Add a String variable to represent the property that you are adding.
Module 3: Branding the Ecommerce Site
3 - 27
private const string CustAge = “AGE”;
3. Add a method to cast the value from the field in Microsoft Dynamics
AX as a string and set it as the value for the property.
public string Age
{
get { return (string)this[CustAge]; }
set { this[CustAge] = value; }
}
Customize Workflows in Commerce Runtime
The commerce runtime includes workflow business logic that enforces rules for
your business. For example, after a customer places an order, you could use
workflow to make sure that there is sufficient quantity available, validate the tax
calculation, check for credit approval, and then place the order. You can use the
workflows that are included in commerce runtime or create your own.
A service encapsulates operations to perform one atomic task, while workflow
performs a set of tasks. A workflow contains a set of steps that calls into one or
more services.
Creating a Workflow
Exactly like services, workflow uses the request and response pattern. The request
object inherits from the base commerce runtime Request class. The response
object inherits from the base commerce runtime Response class. A workflow also
has a request handler class that extends the WorkflowRequestHandler<TRequest,
TResponse> class. To create a workflow, you create a request class and a response
class, and then create a request handler class that contains the business logic for
your workflow.
The following is an example workflow for managing promotions.
To create a request
Create a class that inherits from the base commerce runtime Request class, and
create any incoming parameters that you must have for your workflow. The
following example shows the GetPromotionsRequest class from the Promotions
workflow:
namespace Extensions.Promotions.Workflow
{
using Microsoft.Dynamics.Commerce.Runtime.Messages;
/// <summary>
/// Request Object for the PromotionsWorkFlowRequestHandler class.
/// </summary>
public class GetPromotionsRequest : Request
{
/// <summary>
/// Initializes a new instance of the <see cref="GetPromotionsRequest"/> class.
/// </summary>
public GetPromotionsRequest()
Microsoft Dynamics for Retail in Ecommerce stores: Development and
Customization
3 - 28
{
}
/// <summary>
/// Gets or sets the channel identifier.
/// </summary>
public long ChannelId { get; set; }
/// <summary>
/// Gets or sets the catalog identifier.
/// </summary>
public long CatalogId { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to get the summarized data set.
/// </summary>
public bool HasPromotionData { get; set; }
}
}
To create a response
Create a class that inherits from the base commerce runtime Response class. The
following example displays the GetPromotionsResponse class from the
Promotions workflow:
namespace Extensions.Promotions.Workflow
{
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Extensions.Promotions.Data;
using Microsoft.Dynamics.Commerce.Runtime;
using Microsoft.Dynamics.Commerce.Runtime.Messages;
/// <summary>
/// Creates the response object for the Workflow.
/// </summary>
public class GetPromotionsResponse : Response
{
/// <summary>
/// Initializes a new instance of the <see cref="GetPromotionsResponse"/> class.
/// </summary>
/// <param name="promotions">The summerized promotions.</param>
public GetPromotionsResponse(IEnumerable<ChannelPromotionsSummarizedData> promotions)
{
this.SummarizedPromotions = promotions.AsReadOnly();
}
/// <summary>
/// Initializes a new instance of the <see cref="GetPromotionsResponse"/> class.
/// </summary>
/// <param name="promotions">The promotions.</param>
public GetPromotionsResponse(IEnumerable<PromotionDetails> promotions)
{
this.Promotions = promotions.AsReadOnly();
}
/// <summary>
/// Gets all the summarized channel promotions.
/// </summary>
public ReadOnlyCollection<ChannelPromotionsSummarizedData> SummarizedPromotions {
get; private set; }
/// <summary>
/// Gets non-summarized channel promotions.
/// </summary>
public ReadOnlyCollection<PromotionDetails> Promotions { get; private set; }
Module 3: Branding the Ecommerce Site
3 - 29
}
}
To create a request handler
Create a class that inherits from the base commerce runtime
WorkflowRequestHandler<TRequest, TResponse> class. The following example
displays the GetPromotionsResponse class from the Promotions workflow:
namespace Extensions.Promotions.Workflow
{
using System;
using System.Collections.Generic;
using System.Linq;
using Extensions.Promotions.Data;
using Extensions.Promotions.Service;
using Microsoft.Dynamics.Commerce.Runtime.DataModel;
using Microsoft.Dynamics.Commerce.Runtime.Workflow;
using Microsoft.Dynamics.Commerce.Runtime.Workflow.Composition;
/// <summary>
/// Helper Class to call neccessary Services and perform Data Manipulation on it.
/// </summary>
[RequestHandlerMetadata(HandledRequestType = typeof(GetPromotionsRequest))]
internal class PromotionsWorkflowRequestHandlerRaw :
WorkflowRequestHandler<GetPromotionsRequest, GetPromotionsResponse>
{
/// <summary>
/// Executes the workflow to get the promotions.
/// </summary>
/// <param name="request">The request.</param>
/// <returns>The response.</returns>
protected override GetPromotionsResponse Process(GetPromotionsRequest request)
{
if (request == null)
{
throw new ArgumentNullException("request");
}
var serviceRequest = new GetPromotionsServiceRequest(this.Context);
IPromotions promotionsService = this.Context.Runtime.GetService<IPromotions>();
List<PromotionDetails> response = new List<PromotionDetails>();
List<ChannelPromotionsSummarizedData> summarizedResponse = new
List<ChannelPromotionsSummarizedData>();
serviceRequest.ChannelId = request.ChannelId;
serviceRequest.CatalogId = request.CatalogId;
foreach (PeriodicDiscountOfferType discount in
Enum.GetValues(typeof(PeriodicDiscountOfferType)))
{
serviceRequest.PromotionType = discount;
var serviceReply =
promotionsService.Execute<GetPromotionsServiceResponse>(serviceRequest).Promotions;
if (request.HasPromotionData)
{
summarizedResponse.AddRange(ConvertToSummarizedData(serviceReply,
discount));
}
else
{
response.AddRange(serviceReply);
}
}
if (request.HasPromotionData)
Microsoft Dynamics for Retail in Ecommerce stores: Development and
Customization
3 - 30
{
var summarizedResult = from s in summarizedResponse
orderby s.DiscountName
select s;
return new GetPromotionsResponse(summarizedResult);
}
else
{
var result = from s in response
orderby s.DiscountName
select s;
return new GetPromotionsResponse(result);
}
}
/// <summary>
/// Iterates through a list of promotions for:
/// 1. Generating a list of discount codes associated with an Item. This
generates duplicate records where the only difference is the discount codes.
/// 2. Removing above duplicates.
/// 3. Summarize the Promotion data into English Text for every unique record
being considered.
/// </summary>
/// <param name="promotionDetailsCollection">List containing promotion
details.</param>
/// <param name="typeOfDiscount">Discount Type associated with the list (eg.
MultiBuy/ MixNMatch, etc).</param>
/// <returns>A collection of summarized promotions.</returns>
private static List<ChannelPromotionsSummarizedData>
ConvertToSummarizedData(IEnumerable<PromotionDetails> promotionDetailsCollection,
PeriodicDiscountOfferType typeOfDiscount)
{
var returnObject = new List<ChannelPromotionsSummarizedData>();
var allDiscountOfferNames = promotionDetailsCollection
.Select(i => new { i.DiscountName })
.Distinct();
foreach (var currentOffer in allDiscountOfferNames)
{
var discountLineItems = from s in promotionDetailsCollection where
s.DiscountName == currentOffer.DiscountName orderby s.ItemId select s;
var lineItemsAfterPass1 = Pass1ConsolidateDiscountCodes(discountLineItems);
var lineItemsAfterPass2 =
Pass2GenerateSummarizedPromotionStatement(lineItemsAfterPass1, typeOfDiscount);
var lineItemsAfterPass3 =
Pass3GenerateConsolidatedPromotionStatement(lineItemsAfterPass2, typeOfDiscount);
returnObject.AddRange(lineItemsAfterPass3);
}
return returnObject;
}
/// <summary>
/// Consolidate all the discount codes available for a discount and then remove
redundant line items.
/// </summary>
/// <param name="offerCollection">Contains set of all Line Items for a particular
discount Offer.</param>
/// <returns>A collection of promotion details..</returns>
private static List<PromotionDetails>
Pass1ConsolidateDiscountCodes(IEnumerable<PromotionDetails> offerCollection)
{
var returnObject = new List<PromotionDetails>();
var element = new PromotionDetails();
var iterator = offerCollection.ToList();
for (int counter = 0; counter < offerCollection.Count(); counter++)
Module 3: Branding the Ecommerce Site
3 - 31
{
element = iterator.ElementAt(counter);
if (element.IsDiscountCodeRequired)
{
int index = 1;
while (counter + index < offerCollection.Count() &&
iterator.ElementAt(counter + index).ItemId == element.ItemId && iterator.ElementAt(counter +
index).IsDiscountCodeRequired == element.IsDiscountCodeRequired)
{
element.DiscountCode += ", " + iterator.ElementAt(counter +
index).DiscountCode;
index++;
}
counter += index;
}
returnObject.Add(element);
}
return returnObject;
}
/// <summary>
/// Generates a Summarized Promotion Statement for every line item, But it is still
not usable by the End-User.
/// </summary>
/// <param name="offerCollection">Contains set of all Line Items for a particular
discount Offer.</param>
/// <param name="typeOfDiscount">Is it MultiBuy/ Mix-n-Match/ Discount/ Price
Adjustment.</param>
/// <returns>A collection of summarized promotions.</returns>
private static List<ChannelPromotionsSummarizedData>
Pass2GenerateSummarizedPromotionStatement(IEnumerable<PromotionDetails> offerCollection,
PeriodicDiscountOfferType typeOfDiscount)
{
var returnObject = new List<ChannelPromotionsSummarizedData>();
ChannelPromotionsSummarizedData element;
foreach (var lineItem in offerCollection)
{
element = new ChannelPromotionsSummarizedData();
element.OfferId = lineItem.OfferId;
element.DiscountName = lineItem.DiscountName;
element.DiscountDescription = lineItem.DiscountDescription;
element.Disclaimer = lineItem.Disclaimer;
element.ProductName = lineItem.ProductName;
element.ProductOfferDescription = lineItem.ProductOfferDescription;
element.ProductImageLink = lineItem.ProductImageLink;
element.IsDiscountCodeRequired = lineItem.IsDiscountCodeRequired;
element.DiscountCodes = lineItem.DiscountCode;
switch (lineItem.DiscountMethod)
{
case 0: // Percentage Discount
if (lineItem.DiscountPercent == 0)
{
element.ProductPromotionStatement = String.Empty;
}
else if (lineItem.DiscountPercent == 100)
{
element.ProductPromotionStatement = "Get " + element.ProductName
+ " for free";
}
else
{
element.ProductPromotionStatement = (typeOfDiscount ==
PeriodicDiscountOfferType.MultipleBuy) ? "Buy atleast " +
Decimal.ToInt32(lineItem.MinimumQuantity) + " and " : String.Empty;
Microsoft Dynamics for Retail in Ecommerce stores: Development and
Customization
3 - 32
element.ProductPromotionStatement += "Get " +
decimal.ToInt32(lineItem.DiscountPercent) + "% Off on all " + lineItem.ProductName + "(s)";
}
break;
case 1: // Discount Amount
element.ProductPromotionStatement = "Get each " +
lineItem.ProductName + " for $" + decimal.Round(lineItem.DiscountAmount, 2,
MidpointRounding.AwayFromZero) + " less";
break;
case 2: // Offer Price
element.ProductPromotionStatement = (typeOfDiscount ==
PeriodicDiscountOfferType.MultipleBuy) ? "Buy atleast " + lineItem.MinimumQuantity + " " :
"Buy ";
element.ProductPromotionStatement = lineItem.ProductName + "(s) for
$" + decimal.Round(lineItem.OfferPrice, 2, MidpointRounding.AwayFromZero) + "each";
break;
case 3: // Offer Price Inclusive Of Tax
bool isDealPrice = ((from s in offerCollection where s.DiscountMethod
!= 3 select s).Count() == 0) ? true : false;
element.ProductPromotionStatement = "Get " + (isDealPrice ?
lineItem.DiscountName : lineItem.ProductName) +
" for $" + decimal.Round(lineItem.OfferPriceInclusiveOfTax, 2,
MidpointRounding.AwayFromZero) + "(Inclusive of Taxes)";
break;
}
returnObject.Add(element);
}
return returnObject;
}
/// <summary>
/// Consolidates and converts the Summarized Promotion Statement to an End-User
understandable format.
/// </summary>
/// <param name="offerCollection">Contains set of all Line Items for a particular
discount Offer.</param>
/// <param name="typeOfDiscount">Is it MultiBuy/ Mix-n-Match/ Discount/ Price
Adjustment.</param>
/// <returns>A collection of summarized promotions.</returns>
private static List<ChannelPromotionsSummarizedData>
Pass3GenerateConsolidatedPromotionStatement(IEnumerable<ChannelPromotionsSummarizedData>
offerCollection, PeriodicDiscountOfferType typeOfDiscount)
{
var returnObject = new List<ChannelPromotionsSummarizedData>();
var iterator = offerCollection.ToList();
string appendText = " when you buy a ";
string productStatement = String.Empty;
bool appendFlag = false;
for (int counter = 0; counter < offerCollection.Count(); counter++)
{
if
(string.IsNullOrEmpty(iterator.ElementAt(counter).ProductPromotionStatement))
{
appendFlag = true;
appendText += ((string.Compare(appendText, " when you buy a ",
StringComparison.OrdinalIgnoreCase) == 0) ? String.Empty : " and ") +
iterator.ElementAt(counter).ProductName;
}
productStatement =
(string.IsNullOrEmpty(iterator.ElementAt(counter).ProductPromotionStatement)) ?
productStatement : iterator.ElementAt(counter).ProductPromotionStatement;
}
foreach (var lineItem in offerCollection)
Module 3: Branding the Ecommerce Site
3 - 33
{
lineItem.ProductPromotionStatement = appendFlag ? productStatement +
appendText : lineItem.ProductPromotionStatement;
returnObject.Add(lineItem);
}
return returnObject;
}
}
}
Changing the CRT Configuration file
You cannot customize the workflow that is included with the CRT. However, you
can replace it with your own custom workflow or you can add workflows. The CRT
configuration file determines the workflow to load. If you add a new workflow
with the same name as a default workflow above the default workflow, the new
workflow replaces the default workflow.
To change the CRT configuration file
1. Open commerceRuntime.config in your solution.
Note: The location of this file varies based on your deployment. If you are
customizing the SharePoint starter store, you can find the file by using the Internet
Information Services (IIS) Manager. In IIS Manager, find the starter store under the
Sites node. Right-click the public starter store, and then click Explore.
2. Add a line for your new workflow to the list of assemblies.
<add source="assembly" value="ContosoWorkflow, Version=1.0.0.0,
Culture=neutral, PublicKeyToken=6598494e9dab8361,
processorArchitecture
Microsoft Dynamics for Retail in Ecommerce stores: Development and
Customization
3 - 34
Module Review
Test Your Knowledge
Test your knowledge with the following questions.
1. What is a Design Package in SharePoint 2013?
2. Which file type should be modified to change the content of the header and
footer of the Ecommerce site?
( ) Master Page
( ) Page Layout
( ) Cascading Style sheets
( ) JavaScript
( ) Display Templates
Module 3: Branding the Ecommerce Site
3 - 35
Test Your Knowledge Solutions
Module Review and Takeaways
1. What is a Design Package in SharePoint 2013?
MODEL ANSWER:
In SharePoint 2013, Design Manager can help web developers and designers
build and export the visual design of a SharePoint site collection as a package.
This package can easily be distributed to customers or other designated
groups for installation on their site collections. This new feature reduces the
complexity of transporting designs, and makes it easier for customers to
outsource the visual design of their sites.
2. Which file type should be modified to change the content of the header and
footer of the Ecommerce site?
(√) Master Page
( ) Page Layout
( ) Cascading Style sheets
( ) JavaScript
( ) Display Templates
4 - 1
MODULE 4: ECOMMERCE WEB PARTS
Module Overview
Microsoft Dynamics AX 2012 R3 Retail includes a sample online starter store. The
starter store is a site built by using the new site cross-site publishing model in
Microsoft SharePoint Server 2013.
You can change the functionality of the Ecommerce site by customizing the Web
Parts or the CRT Services, or both. In the starter Ecommerce site, you use two
types of Web parts to surface information or control behavior on the pages:
Content Search Web parts (CSWP) and Custom Web Parts. The CSWP uses the
Search index database to display information, whereas Custom Web Parts uses the
CRT Services to control behavior or display content.
Objectives
The objectives of this module are as follows:
Describe how to create a SharePoint WebPart.
Explain how to add a new AJAX Service to the Storefront.
Work with customizing the out of the box storefront WebParts.
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
4 - 2
Create a SharePoint WebPart
Customers usually want to customize the out-of–the-box SharePoint appearance
and behavior and provide custom functionality. In this lesson, we analyze creating
custom WebParts by using Visual Studio
Create a SharePoint WebPart
This topic provides a step-by-step approach to create a custom WebPart by using
Visual Studio
1. Log on to your development environment by using administrative
credentials.
2. Open Visual Studio > Create New Project by using the SharePoint
Empty Project template.
3. Add New Visual WebPart as shown in the ”Visual WebPart Creation
Wizard.” Name the visual WebPart “MyCoolVisualWebPart”.
FIGURE 4.1: VISUAL WEBPART CREATION WIZARD
4. Change the newly added WebPart user control mockup as shown in
the following figure.
Module 4: Ecommerce Web Parts
4 - 3
The user controls code behind file is updated automatically, as displayed in “User
Controls Code behind File” figure.
FIGURE 4.3: USER CONTROLS CODE BEHIND FILE
5. Update user controls code behind file to add label to the control.
FIGURE 4.4: ASCX CONTROL CODE BEHIND
6. Update the WebPart.group name in Elements.xml. In this example,
update the group name to “Dynamics eCommerce”. This is used
during deployment.
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
4 - 4
FIGURE 4.5: WEBPART GROUP NAME
Update the *.webpart file with a new title and description. This is used during
deployment to create a WebPart.
FIGURE 4.6: WEBPART TITLE AND DESCRIPTION
7. Build the project and deploy the WebPart in the SharePoint Site
collection. As soon as the WebPart is deployed, you should see the
WebPart in a list of available WebParts.
Browse to the SharePoint Site collection site, and then click Add a page under the
Site Settings icon as displayed in “SharePoint Add Page Setting” figure.
Module 4: Ecommerce Web Parts
4 - 5
FIGURE 4.7: SHAREPOINT ADD PAGE SETTING
8. Edit the newly created page and set Blank WebPart page as the
default page layout.
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
4 - 6
FIGURE 4.8: WEBPART PAGE LAYOUT
9. Move to the newly created page, and then click edit. Scroll to
WebPart zones, and then click Add a WebPart.
10. In the selection, you should see your new WebPart. Select it, and then
click Add.
Module 4: Ecommerce Web Parts
4 - 7
FIGURE 4.9: ADD WEBPART IN SHAREPOINT PAGE
You should see your WebPart in a page. See the “WebPart Layout in SharePoint
Page” figure.
FIGURE 4.10: WEBPART LAYOUT IN SHAREPOINT PAGE
Add a New AJAX Service to the Storefront
Creating a new AJAX Service requires the following steps:
1. Create an interface for your service. The interface should have the
ServiceContract attribute declaration. Define the methods that your
service will expose and mark them with the OperationContract
attribute. This is your service API.
2. Create the service. The service contains the methods that are called
from the JavaScript in your pages. This should be a lightweight
interface that does not contain business logic. It implements the
interface that you created in the previous step. The service method
calls a method on a controller and returns a response object. Services
are located in the SharePoint.Web.Services project’s ISAPI
subdirectory.
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
4 - 8
3. Create a controller. The controller contains implementation details
for creating, updating, reading, and deleting data to and from the
CRT or other data sources. The service method calls the controller and
returns a front-end object or collection instance. Controllers are
located in the SharePoint.Web.Services project’s ObjectModel
subdirectory.
4. Create a mapper (optional). A “mapper” converts an object from its
back-end representation to a front-end representation of the object.
They are used in controllers. It is best to create a new mapper as you
can use one of the existing mapper classes. Mappers are located in
the SharePoint.Web.Services project’s ObjectModel subdirectory.
5. Create a response object (optional). A response object
encapsulates the data that your service is returning to the page. It is
used in the service method to wrap the data that is returned from the
controller into a response that is consumed by the page. It is best to
create a new response object as you can use one of the existing
response classes. Response objects are located in the
SharePoint.Web.Services project’s ViewModel subdirectory.
Class Diagram
FIGURE 4.11: CLASS DIAGRAM
Getting Started
1. Download and install the Dynamics AX 2012 for Retail SDK.
2. Open the solution file, for example: C:\Users\<username>\My
Documents\Channels\SharePoint\Solution\RetailStoreFront.sln
Create a New AJAX Service and Get Customer Loyalty Card
Information
This topic provides a step-by-step approach to create an AJAX service.
Module 4: Ecommerce Web Parts
4 - 9
1. Create a Service Interface. A service interface defines the operations
that are available to your pages.
a. In the SharePoint.Web.Services project, right-click the project,
select Add, and then select New Item…. In the dialog box that is
displayed, select interface.
b. Enter the name of your new interface class. The recommendation
is to always prefix interface file names with an “I”. Name the
interface ILoyaltyService.cs.
c. To be available from clients, the interface requires the
ServiceContractAttribute. Add [ServiceContract] immediately
above the interface definition.
d. The interface contains one or more methods. Create a new
method definition named GetLoyaltyCard. It accepts a string
input parameter for the account number and returns a
LoyaltyCardResponse.
e. To be available from clients, the new method requires the
OperationContractAttribute. Add [OperationContract] to the
GetLoyaltyCard method.
Your service interface should resemble the ”Web Service Interface” figure.
FIGURE 4.12: WEB SERVICE INTERFACE
2. Create the Service. A service implements the interface and contains
the code that executes when your service methods are called from
the page.
a. In the SharePoint.Web.Services project, right-click the ISAPI folder
within the project, select Add, and then select New Item….
b. Select Text File in the dialog box.
c. Enter the name of your new service class. We recommend that
you use the same name as the interface without the prefix.
d. Name the interface LoyaltyService.svc. Define the service
definition by adding the following line to the top of the file:
<%@ ServiceHost Language="C#" Debug="true"
Service="Microsoft.Dynamics.Retail.SharePoint.Web.Services.Loya
ltyService, Microsoft.Dynamics.Retail.SP.Web.Services,
Version=6.2.0.0, Culture=neutral,
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
4 - 10
PublicKeyToken=31bf3856ad364e35"
Factory="Microsoft.SharePoint.Client.Services.MultipleBaseAddres
sWebServiceHostFactory,
Microsoft.SharePoint.Client.ServerRuntime, Version=14.0.0.0,
Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
Note: The PublicKeyToken=31bf3856ad364e35" that was given earlier is
based on the strong name file that you created. It can be extracted by using the
sn.exe tool. This setting should be changed accordingly.
e. Right-click the ISAPI folder within the project again, select Add,
and then select Class. Name your class LoyaltyService.svc.cs.
f. Add the
BasicHttpBindingServiceMetadataExchangeEndpointAttribute to
your class.
g. Add the AspNetCompatibilityRequirementsAttribute to your class.
h. Change the class declaration to implement ILoyaltyService.cs.
i. Implement the GetLoyaltyCard method with the same signature
that was defined for the interface. Do this by right-clicking the
ILoyaltyService text that was created in the previous step, and
select Implement Interface.
j. Add the WebInvokeAttribute to the method -
[WebInvoke(ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json, BodyStyle =
WebMessageBodyStyle.WrappedRequest)].
k. Do not change the implementation at this time. You must create
the supporting classes before you implement this.
Your code should resemble the “Web Service Method” figure.
FIGURE 4.13: WEB SERVICE METHOD
3. Create a ViewModel. A ViewModel object is the representation of
the business entity.
a. In the SharePoint.Web.Services project, right-click the ViewModel
folder within the project, select Add, and then select Class.
Module 4: Ecommerce Web Parts
4 - 11
b. Enter the name of your new view model class as Loyalty.cs.
c. Mark your new class with the SerializableAttribute and the
DataContractAttribute so that it is usable by the service,.
d. To store additional data that is not part of the data contract of
the class, implement the IExtensibleDataObject interface.
e. A CustomerLoyaltyCard from the CRT exposes several properties
to the UI. These properties include the following: RecordId (the
unique identifier), CardNumber, IssuedPoints, UsedPoints, and
ExpiredPoints. Properties that are available to the UI must have
the DataMemberAttribute. Create the following properties: long
RecordId, string CardNumber, decimal IssuedPoints, decimal
UsedPoints, and decimal ExpiredPoints.
The “Web Service Data Members” figure displays how the code should look.
FIGURE 4.14: WEB SERVICE DATA MEMBERS
4. Create a Mapper. A mapper transforms data from the CRT business
object to a front-end UI object, such as the ViewModel object that
you created in the previous step.
a. In the SharePoint.Web.Services project, right-click the
ObjectModel folder within the project, select Add, and then select
Class. Enter the name of your new mapper class as
LoyaltyMapper.cs.
b. Set the mapper class to static.
c. Add a new internal static method named ConvertToViewModel
that accepts the CRT object as input and returns an instance of
your ViewModel object.
d. Check whether the input parameter is null and either return null
or throw an ArgumentNullException. This depends on the
behavior that you want.
e. Write code that creates a new instance of your View Model class.
f. Assign values from properties of the CRT object to properties of
the ViewModel object.
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
4 - 12
The “View Model Class” figure displays how your code should look.
FIGURE 4.15: VIEW MODEL CLASS
5. Create a Controller. A controller handles the interaction between the
ViewModel and the service interface.
a. In the SharePoint.Web.Services project, right-click the
ObjectModel folder within the project, select Add, and then select
Class. Enter the name of your new controller class as
LoyaltyController.cs.
b. Set the controller class to static.
c. Create a static method GetLoyaltyCard. It should have a string
input parameter named accountNumber and should return the
ViewModel object that you created in the previous step.
d. The implementation of GetLoyaltyCard should create an instance
of the LoyaltyDataManager:
var manager =
LoyaltyDataManager.Create(Utilities.GetCommerceRuntime());
e. Code a call to the LoyaltyDataManager’s GetLoyaltyCardInfo
method. This returns a CRT CustomerLoyaltyCard object.
f. Using the Mapper class that you created in the previous step,
make a call to LoyaltyMapper.ConvertToViewModel, passing in
the CustomerLoyaltyCard object. The mapper method returns
your ViewModel LoyaltyCard object that you return as the result
of this method.
6. Create a Response object. A response object is what is returned to
the AJAX service caller. It encapsulates any data that you must have
on the client. It derives from the ServiceResponse class. By default, it
includes an error collection and an error redirect URL.
Module 4: Ecommerce Web Parts
4 - 13
a. In the SharePoint.Web.Services project, right-click the
ObjectModel folder within the project, select Add, and then select
Class. Enter the name of your new response class as
LoyaltyResponse.cs.
b. Your response class is part of the service contract. Add a
DataContractAttribute to the class.
c. Change the class definition to derive from the ServiceResponse
base class.
d. The class should return the data for the LoyaltyCard. Create a
property named LoyaltyCard with public get and set accessors.
This property returns the ViewModel LoyaltyCard class that you
created earlier in this tutorial. The property is also part of the
contract. Therefore, add a DataMemberAttribute to it.
7. Putting it all together: Now that you have the required classes
created for your service, it is time to return to the implementation of
the GetLoyaltyCard method in LoyaltyService.cs.
a. In the GetLoyaltyCard method, create an instance of the
LoyaltyResponse class. The method returns this object.
b. The response LoyaltyCard property is set by calling the
LoyaltyCardControllerGetLoyaltyCard method. You must be an
authorized to execute this call. Therefore, it should be contained
in a ServiceHelper.ExecuteForAuthorizedUser block.
c. Return the response object. to end creation of the AJAX service.
Customize Out-of-the-Box WebParts
The storefront solution provided with Dynamics Ax 2012 R3 includes many out-of-
the-box WebParts. You can customize these WebParts to change their appearance
and behavior or add functionality. Some WebParts that are provided with the
storefront solution include the following:
Add to cart
Checkout
Promotion code
Submit order
Mini shopping cart
Shopping cart
Address
Customer
Wish List
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
4 - 14
Create a SharePoint WebPart
This topic provides a step-by-step procedure to customize out-of-the-box
storefront WebParts by using Visual Studio.
1. Log on to your development environment by using administrative
credentials.
2. Open the Visual Studio solution file that is located at
\documents\Retail SDK\Online Channel\StoreFront\StoreFront.sln.
3. On the Solution Explorer window, browse to
Web\Sharepoint.Web.Webparts and expand it.
4. You can view a list of WebParts that are available in the storefront
solution:
5. Expand one of the WebParts, such as Login, and notice that the
WebPart includes a . WebPartfile, an ascx file, and an ascx.cs file.
6. The WebPart file contains the WebPart definition and is imported to
the WebPart gallery when it is installed in SharePoint.
7. Click the Login.ascx file to view the rendering logic for the WebPart.
8. Change the login validation message to “Please enter a valid email
id.” for the email id field.
To verify, build the storefront solution and deploy to the SharePoint farm.
Module 4: Ecommerce Web Parts
4 - 15
Module Review
Test Your Knowledge
Test your knowledge with the following questions.
1. What wizard can you use to create a new web part?
2. Which WebPart uses the Search index database to display information on the
Ecommerce store front?
( ) Master Page
( ) Search Page layouts
( ) Content Search Web parts
( ) JavaScript
3. Under which project can you find the out-of-the-box WebParts in the
storefront solution?
( ) Sharepoint.Web.Storefront
( ) Sharepoint.Web.Webparts
( ) Sharepoint.Webparts.Controls
( ) None of the above
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
4 - 16
Test Your Knowledge Solutions
Module Review and Takeaways
1. What wizard can you use to create a new web part?
MODEL ANSWER:
You can use the Visual Web Part creation wizard to create a new visual
WebPart.
2. Which WebPart uses the Search index database to display information on the
Ecommerce store front?
( ) Master Page
( ) Search Page layouts
(√) Content Search Web parts
( ) JavaScript
3. Under which project can you find the out-of-the-box WebParts in the
storefront solution?
( ) Sharepoint.Web.Storefront
(√) Sharepoint.Web.Webparts
( ) Sharepoint.Webparts.Controls
( ) None of the above
5 - 1
MODULE 5: SEARCH CONFIGURATION AND
CUSTOMIZATION
Module Overview
Microsoft Dynamics AX 2012 R3 Retail includes a sample online starter store. The
starter store is a site that is built by using the new site cross-site publishing model
in SharePoint 2013.
The cross-site publishing feature of SharePoint 2013 enables you to reuse content
across multiple site collections. It uses built-in search capabilities to enable
publishing scenarios and architectures. When you use cross-site publishing, you
use search technology to retrieve and show content. The search index is at the
center of search. The queries that are specified in the different Search Web Parts
on the publishing site are sent to the search index to retrieve relevant content and
show it in the Web Part.
Objectives
This module shows you how to configure, customize, and extend search in your
Ecommerce site.
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
5 - 2
Configure Refiners and Faceted Navigation
When content is crawled by the search engine, the metadata of the items that are
crawled is represented as crawled properties. To include crawled properties in the
search index, crawled properties have to be mapped to managed properties.
You can add refiners to a page to help users quickly browse to specific content.
Refiners are based on managed properties from the search index. To use managed
properties as refiners, the managed properties must be enabled as refiners, or
crawled properties must be mapped to managed properties that are enabled as
refiners.
“Faceted navigation” is browsing for content by filtering on refiners that are tied
to category pages. Faceted navigation enables you to specify different refiners for
category pages, even when the underlying page that is displaying the categories is
the same. When a catalog is crawled, SharePoint Server 2013 automatically creates
managed properties for all site columns that contain values.
Note: For information about category pages, see "Category pages and
catalog item pages" in Overview of cross-site publishing in SharePoint Server 2013
(http://technet.microsoft.com/en-us/library/jj635883.aspx).
You can apply faceted navigation only to publishing sites that use managed
navigation.
Lesson Objectives
Map a crawled property to a refinable managed property.
Enable a managed property as a refiner.
Configure refiners for faceted navigation.
Use JavaScript to display refiners in correct format.
Map a crawled property to a refinable managed property
in SharePoint site collection administration
By default, site collection administrators can configure refiners because the search
schema has many managed properties that are enabled as refiners. Before site
collection administrators can use these managed properties as refiners on their
web pages, they must map the appropriate crawled property to the managed
property that is enabled as a refiner. To make it easier to work with these
properties when doing additional refiner configuration in Term Store
Management, you can specify a user-friendly alias name for the managed
property.
Module 5: Search Configuration and Customization
5 - 3
The following table contains managed properties that are enabled as refiners by
default.
Managed property name Data type for mapping.
RefinableDate00 -
RefinableDate19
Values contain dates.
RefinableDecimal00 -
RefinableDecimal09
Values contain numbers with a maximum of three
decimals.
RefinableDouble00 -
RefinableDouble09
Values contain numbers with more than three
decimals.
RefinableInt00 -
RefinableInt49
Values are whole numbers.
RefinableString00 -
RefinableString99
Values are strings. This includes values that use the
data type Text, Person, or Group, Managed
Metadata, Choice and Yes/No.
For an overview of managed properties that are enabled as refiners by default, see
Managed properties that are enabled as refiners by default.
Note: This procedure is performed on the authoring site collection.
To map a crawled property to a refinable managed property
1. Verify that the user account that performs this procedure is a site
collection administrator on the authoring site collection.
2. On the authoring site collection, on the Settings menu, click Site
settings.
3. On the Site Settings page, in the Site Collection Administration
section, click Search Schema.
4. On the Managed Properties page, in the Managed property filter
box, type the name of a refinable managed property, such as,
RefinableString00, and then click the arrow.
5. In the Property Name column, click the refinable managed property
that you want to edit.
6. Specify an alias of the refinable managed property to use when you
configure refiners for faceted navigation. On the Edit Managed
Property page, type a user-friendly name in the Alias box.
Note: For properties that use the data type Managed Metadata, the alias
must consist of the type code, owstaxId, followed by the property name. For
example, for a property named Color that uses the Managed Metadata data type,
the alias for the refinable managed property must be owstaxIdColor.
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
5 - 4
7. In the Mappings to crawled properties section, click Add a Mapping.
8. In the Crawled property selection dialog box, find the crawled
property that you want to map to the refinable managed property in
the list, or search for it by typing the name of the crawled property in
the box, and then clicking Find.
Note: When you search for a crawled property, you may find two crawled
properties that represent the same content. For example, during a crawl a site
column of type Text named Color will discover two crawled properties: ows_Color
and ows_q_TEXT_Color. Crawled properties that begin with either ows_r<four letter
code>, ows_q<four letter code>, or ows_taxId are automatically-created crawled
properties. When you select a crawled property to map to a refinable managed
property, make sure that you do not map the automatically-created crawled
property. Instead, always map the crawled property that begins with ows_.
9. Click OK.
10. On the Edit Managed Property page, click OK.
Note: To configure refiners in Web Parts or in Term Store Management, you
must start a full crawl of the content source that contains the refinable managed
properties.
Enable Automatically-Created Managed Properties as Refiners in
SharePoint Central Administration
All automatically-created managed properties use the Text data type. To make
sure that the refiners are displayed in the correct format, you should enable only
an automatically-created managed property as a refiner. The refiner must be
based on a site column that uses the data type Text, Managed Metadata, or
Person or Group. For other data types, you must create a managed property, add
the type code to the property name, and enable the managed property as a
refiner.
To enable an automatically created managed property as a refiner
1. Verify that the user account that performs this procedure is an
administrator of the Search service application.
2. In Central Administration, in the Application Management section,
click Manage service applications.
3. On the Manage Service Applications page, click the Search service
application in which you want to enable the managed property as a
refiner.
4. On the Search Administration page, in the Quick Launch, under
Queries and Results, click Search Schema.
Module 5: Search Configuration and Customization
5 - 5
5. On the Managed Properties page, in the Managed property filter
box, type the name of the managed property that you want to enable
as a refiner, and then click the arrow.
6. In the Property Name column, click the managed property that you
want to edit.
7. On the Edit Managed Property page, in the Refinable section, select
either Yes – active or Yes – latent. If you select Yes - latent, you can
switch the refiner to active at a later time without doing a full crawl.
8. Click OK.
Note: To configure refiners in Web Parts or in Term Store Management, you
must complete a full crawl of the content source that contains the refinable
managed properties. For more information, see Configure search for cross-site
publishing.
To create a managed property, add type code to the name, and
enable a managed property as a refiner
1. Verify that the user account that performs this procedure is an
administrator of the Search service application.
2. In Central Administration, in the Application Management section,
click Manage service applications.
3. On the Manage Service Applications page, click the Search service
application in which you want to create a managed property.
4. On the Search Administration page, in the Quick Launch, under
Queries and Results, click Search Schema.
5. On the Managed Properties page, click New Managed Property.
On the New Managed Property page, in the Property name box, in the Name
and description section, type the name of the new managed property, followed by
the appropriate type code. For an overview of type codes, refer to the following
table.
Type codes
Site column
type
Type code Example of managed property name with
type code
Number OWSNMBR ManagedPropertyNameOWSNMBR
Currency OWSCURR ManagedPropertyNameOWSCURR
Date and Time OWSDATE ManagedPropertyNameOWSDATE
*Column creation not available through the user interface.
6. In the Type section, select the appropriate data type.
7. In the Main characteristics section, set the following selections (you
can also specify additional settings in this section):
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
5 - 6
o Queryable
o Refinable: Yes - active or Yes - latent
8. In the Mappings to crawled properties section, click Add a mapping.
9. In the Crawled property selection dialog box, find the crawled
property that you want to map to the managed property in the list.
You also can search for it by typing the name of the crawled property
in the box, and then clicking Find.
Note: When you search for a crawled property, you may find two crawled
properties that represent the same content. For example, during crawl a site column
of type Date and Time named Created will discover two crawled properties:
ows_Created and ows_q_DATE_Created. Crawled properties that begin with either
ows_r<four letter code>,ows_q<four letter code> or ows_taxId are automatically-
created crawled properties. When you select a crawled property to map to a
managed property, make sure that you do not map the automatically created
crawled property. Instead, always map the crawled property that begins with ows_.
10. Click OK.
Note: To configure refiners in Web Parts or in Term Store Management, you
must complete a full crawl of the content source that contains the refinable
managed properties.
Configure Refiners for Faceted Navigation
Before you begin the procedures in this section, verify the following:
A library or list is shared as a catalog on the authoring site.
The required managed properties are enabled as refiners.
A full crawl was completed for the content source that contains the
refinable managed properties.
Enable a term set for faceted navigation
To configure refiners for faceted navigation, you must first enable the relevant
term set for faceted navigation. This procedure is performed on the authoring site
collection.
To enable a term set for faceted navigation
1. Verify that the user account that performs this procedure is a member
of the Designers SharePoint group on the authoring site collection.
2. On the authoring site collection, on the Settings menu, click Site
settings.
Module 5: Search Configuration and Customization
5 - 7
3. On the Site Settings page, in the Site Administration section, click
Term store management.
4. In the TAXONOMY TERM STORE section, select the term set that you
want to enable for faceted navigation.
5. Click the INTENDED USE tab, and then select Use this Term Set for
Faceted Navigation.
6. Click Save.
Add refiners to a term set
When you configure refiners for faceted navigation, you can add refiners to all
terms in a term set or to specific terms in a term set. This procedure is performed
on the authoring site collection.
To add refiners to all terms in a term set
1. Verify that the user account that performs this procedure is a member
of the Designers SharePoint group on the authoring site collection.
2. On the authoring site collection, on the Settings menu, click Site
settings.
3. On the Site Settings page, in the Site Administration section, click
Term store management.
4. In the TAXONOMY TERM STORE section, click the term set that you
have enabled for faceted navigation.
5. Click the FACETED NAVIGATION tab, and then click Customize
refiners.
6. On the Refinement Configuration page, in the Available refiners
section, use the buttons to select which refiners should be added to
the term set, and to specify the order in which you want the refiners
to appear. If you have specified an alias for a refinable managed
property, this alias is displayed in the Configuration section.
7. In the Configuration for section, specify how you want each refiner to
appear.
8. Click OK to close the Refinement Configuration page, and then
click Save.
To add refiners to specific terms in a term set
1. Verify that the user account that performs this procedure is a member
of the Designers SharePoint group on the authoring site collection.
2. On the authoring site collection, on the Settings menu, click Site
settings.
3. On the Site Settings page, in the Site Administration section, click
Term store management.
4. In the TAXONOMY TERM STORE section, click the term set that you
have enabled for faceted navigation. Then click the term to which you
want to add term-specific refiners.
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
5 - 8
5. Click the FACETED NAVIGATION tab, and then click Stop
inheriting.
6. Click the FACETED NAVIGATION tab, and then click Customize
refiners.
7. On the Refinement Configuration page, in the Available refiners
section, use the buttons to select which refiners should be added to
the term set, and to specify the order in which you want the refiners
to appear. If you have specified an alias for a refinable managed
property, this alias is displayed in the Configuration section.
8. In the Configuration for section, specify how you want each refiner to
appear.
9. Click OK to close the Refinement Configuration page, and then
click Save.
Set intervals for refiner values
For refiners that contain numeric values, you can present the numeric values
within different intervals. For example, if you want users to refine based on price,
specify different price ranges. Do not display all available prices as separate
refiners. This procedure is performed in the authoring site collection.
To set ranges for refiner values
1. Add refiners to a term set as described in Add refiners to a term set
earlier in this t topic.
2. On the Refinement Configuration page, in the Selected refiners
section, click the refiner that you want to set ranges for.
3. In the Configuration for section, for Intervals, select Custom, and then
type the ranges in the Thresholds box.
4. Click OK to close the Refinement Configuration page, and then
click Save.
To display refiners on a page, you must add a Refinement Panel Web Part to the
page where you want the refiners to appear.
Add JavaScript to a Page to Display Refiners in the Correct
Format
To make sure that refiners that use the Number, Currency, Integer, and Date and
Time data types are displayed in the correct format, you can add JavaScript to the
page where the refiners are displayed. You can do this by adding a Content Editor
Web Part. Then you prevent this WebPart from displaying on the page.
Be aware that there are two methods that depend on whether you are using the
default display template: Filter_Default, or another display template in your
Refinement Web Part.
Module 5: Search Configuration and Customization
5 - 9
To add JavaScript to a page to display refiners in the correct format
when you are using the default display template
1. Verify that the user account that performs this procedure is a member
of the Designers SharePoint group on the publishing site collection.
2. Browse to the page where the refiners are displayed.
3. Click the Settings menu, and then click Edit page.
4. In a Web Part Zone, click Add a Web Part.
5. In the Categories list, click Media and Content.
6. In the Parts list, click Content Editor, and then click Add.
7. In the Web Part, click Click here to add new content, and type one
of the following two code strings:
# To ensure correct refiner formatting by using type
code:Srch.ValueInfo.overrideRenderingForProperty("<ManagedPropertyName>",
"Property<TypeCode>" );
# To ensure correct refiner formatting by using a managed properties that
is enabled as a refiner by default:
Srch.ValueInfo.overrideRenderingForProperty("<ManagedPropertyName>",
"<DefaultRefinableManagedProperty>");
Where:
o <ManagedPropertyName> is the name of the managed property
that is enabled as a refiner, such as ,CreatedOWSDATE.
o <TypeCode> is a seven-letter code that indicates the data type,
such as, OWSDATE.
o <DefaultRefinableManagedProperty> is the name of a managed
property that is enabled as a refiner by default, for example,
RefinableDate00. For an overview of managed properties that are
enabled as refiners by default, see Managed properties that are
enabled as refiners by default.
8. In the Web Part, click the Content Editor Web Part Menu arrow, and
then click Edit Web Part.
9. In the Web Part tool pane, expand the Layout section, and then select
Hidden.
10. Click OK.
To add JavaScript to a page to display refiners in the correct format
when you are not using the default display template
1. Verify that the user account that performs this procedure is a member
of the Designers SharePoint group on the publishing site collection.
2. Browse to the page where the refiners are displayed.
3. Click the Settings menu, and then click Edit page.
4. In a Web Part Zone, click Add a Web Part.
5. In the Categories list, click Media and Content.
6. In the Parts list, click Content Editor, and then click Add.
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
5 - 10
7. In the Web Part, click Click here to add new content, and then type
the following code strings:
# To ensure correct refiner formatting by using type code:
Srch.ValueInfo.overrideRefinementTemplateForProperty("<ManagedPro
pertyName>", "Property<TypeCode>",
"~sitecollection/<PathToDisplayTemplate>" );
# To ensure correct refiner formatting by using a managed
properties that is enabled as a refiner by default:
Srch.ValueInfo.overrideRefinementTemplateForProperty("<ManagedPro
pertyName>", "<DefaultRefinableManagedProperty>",
"~sitecollection/<PathToDisplayTemplate>" );
Where:
o <ManagedPropertyName> is the name of the managed property
that is enabled as a refiner, for such as, CreatedOWSDATE.
o <TypeCode> is a seven-letter code that indicates the data type,
for example OWSDATE.
o <DefaultRefinableManagedProperty> is the name of a managed
property that is enabled as a refiner by default, such as,
RefinableDate00. For an overview of managed properties that are
enabled as refiners by default, see Managed properties that are
enabled as refiners by default.
o <PathToDisplayTemplate> is the path of the display template
that you are using in the Refinement Web Part, such as
catalogs\masterpage\Display
Templates\Filters\MyDisplayTemplate.js.
8. In the Web Part, click the Content Editor Web Part Menu arrow, and
then click Edit Web Part.
9. In the Web Part tool pane, expand the Layout section, and then select
Hidden.
10. Click OK.
Manage Query Rules
You specify conditions and correlated actions in a query rule. When a query meets
the conditions in a query rule, the search system performs the actions that are
specified in the rule to improve the relevance of the search results, such as by
narrowing results or changing the order in which results are displayed. For
example, a query rule condition can be a term in a query that matches a particular
term in a SharePoint term set, or a query that is frequently performed on a
particular result source in a search system, such as videos. When the query rule
condition is satisfied, a correlated action can display a specific item at the top of
the search results.
Module 5: Search Configuration and Customization
5 - 11
You can configure query rules for one or more result sources, and you can specify
the time period during which the query rule is active.
Lesson Objectives
Create a new query rule.
Create and display a result block.
Change ranked search results.
Make a query rule inactive.
Rank query rules.
Create Query Rules at Different Levels in a SharePoint
Farm
You can create a query rule for a Search service application, a site collection, or a
site. The following table displays the permissions that are required to create a
query rule in each case, and where the query rule can be used.
When you create a
query rule at this
level
You must have this
permission
Use this query rule in
Search service
application
Search service
application
administrator
All site collections in web
applications that consume the
Search service application
Site collection Site collection
administrator
All sites in the site collection
Site Site owner The site
To add or edit a query rule, you must go to the Manage query rules page.
Depending on the level at which you are creating the query rule, use one of the
following procedures to go to the Manage query rules page.
To go to the Manage query rules page for a Search service application
11. Verify that the user account that performs this procedure is an
administrator for the Search service application.
12. In Central Administration, in the Application Management section,
click Manage service applications.
13. Click the Search service application to which you want to add query
rules.
14. On the Search Administration page for the Search service
application, in the Quick Launch, in the Queries and Results section,
click Query Rules.
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
5 - 12
To go to the Manage query rules page for a site collection
1. Verify that the user account that performs this procedure is a site
collection administrator.
2. On the Settings menu for the site collection, click Site Settings.
3. On the Site Settings page, in the Site Collection Administration
section, click Search Query Rules.
To go to the Manage query rules page for a site
1. Verify that the user account that performs this procedure is a member
of the Owners group for the site.
2. On the Settings menu for the site, click Site Settings.
3. On the Site Settings page, in the Site Administration section, click
Query Rules.
Create a Query Rule
To create a query rule:
1. On the Manage Query Rules page, in the Select a Result Source
menu, select a result source for the new query rule.
2. Click New Query Rule.
3. On the Add Query Rule page, in the General Information section, in
the Rule name field, type the name for the query rule.
4. Expand the Context section.
5. In the Context section, select one of the following options:
a. To apply the query rule to all result sources, select All sources.
b. To apply the query rule to one or more specific result sources,
select One of these sources. By default, the result source that
you specified in step 1 is selected.
c. To add a result source for the query rule, do the following: Click
Add Source. In the Add Source dialog box, select a result source,
and then click Save.
6. To restrict the query rule to categories, for example, a query rule
should fire only when a term from your managed navigation term set
is included in the query, click Show more conditions, and then
specify the following:
o To restrict the query rule to a category, click Add category. In
the Import from Taxonomy dialog box, select a term to include
it in a query that will cause the query rule to fire, and then click
Save.
o To restrict the query rule to a user segment, do the following:
i. Click Add User Segment.
ii. In the Add User Segment dialog box, in the Title field,
type the title for this rule.
Module 5: Search Configuration and Customization
5 - 13
iii. In the Import from taxonomy dialog box, select a term
that represents a user segment that will cause the query
rule to fire when it appears in a query.
iv. Click Save.
7. In the Query Conditions section, do one of the following:
o Select one of the conditions that is listed in the following table.
o Click Remove Condition to configure this query rule to fire for
every query that users type at the level at which you are creating
the rule, and then go to step 8.
For example, if you are creating this rule for a site collection, click Remove
Condition if you want this rule to fire for every query that user’s type in any
search box in the site collection.
Query
condition
Description Configuration Example
Query
Matches
Keyword
Exactly
Select this
option if you
want the
query rule to
fire when a
query exactly
matches a
word or
phrase that
you specify.
In the Query
exactly matches
one of these
phrases text box,
type one or more
phrases
separated by
semicolons.
You type "picture; pic" in
the Query contains one
of these phrases text box.
The query rule fires when a
user types "picture" or "pic"
in a search box. The rule
will not fire if a user types
"pictures" or "sunny
picture."
Query
Contains
Action Term
Select this
option if you
want the
query rule to
fire when a
query
contains a
term that
indicates
something
that the user
wants to do.
The term
must be at
the
beginning or
end of the
query.
Specify the
action term
that causes
the query
rule to fire by
doing one of
the following:
Select Action
term is one
of these
phrases, and
type one or
more
phrases.
Select Action
term is an
entry in this
dictionary,
and then
You type the word
"download" in the Action
term is one of these
phrases text box. When a
user types "download
Contoso Electronics
datasheet" in a search box,
the user is probably not
searching for a document
that contains the words
"download," "Contoso,"
"Electronics," and
"datasheet." Instead, the
user is probably trying to
download a Contoso
Electronics datasheet.
When a user types
"download Contoso
Electronics datasheet" in a
search box, the query rule
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
5 - 14
Query
condition
Description Configuration Example
click Import
from
taxonomy.
In the
Import from
taxonomy
dialog box,
select a term
from a term
set, and then
click Save.
fires, and only the words
"Contoso," "Electronics,"
and "datasheet" are passed
to the search index.
Query
Matches
Dictionary
Exactly
Select this
option if you
want the
query rule to
fire when the
query exactly
matches a
dictionary
entry.
From the Query
contains an
entry in this
dictionary menu,
select a
dictionary. To
specify a different
dictionary, click
Import from
taxonomy, and
then from the
Import from
taxonomy dialog
box, select a term
from a term set,
and then click
Save.
A word that a user types in
a search box matches an
entry in the preconfigured
People Names dictionary.
Query More
Common in
Source
Select this
option if you
want the
query rule to
fire if the
query was
frequently
issued by
users on a
different
result source
that you
specify.
In the Query is
more likely to
be used in this
source menu,
select a result
source.
In the Query is more
likely to be used in this
source menu, you select
Local Video Results. The
query rule fires if a user
types the word "training" in
a search box and that word
was frequently typed in a
search box in the Videos
vertical.
Result Type
Commonly
Select this
option if you
In the
Commonly
In the Commonly clicked
results match result type
Module 5: Search Configuration and Customization
5 - 15
Query
condition
Description Configuration Example
Clicked want the
query rule to
fire if other
users
frequently
clicked a
particular
result type
after they
typed the
same query.
clicked results
match result
type menu, select
a result type.
box, you select SharePoint
MicroBlog post. If users
frequently click a
microblog post in search
results, then in the Actions
section, you may want to
configure the most recent
microblog post as the first-
promoted result, and the
next most recent
microblog post as the
second-promoted result.
To add conditions, click Add Alternate Conditions.
Note: The rule fires when any condition is true.
8. In the Actions section, specify the action to take when the query rule
fires. Specify one of the following:
o To promote individual results so that they appear toward the top
of search results, click Add Promoted Result.. (In SharePoint
2010 Products this was called Best Bets). In the Add Promoted
Result dialog box, in the Title field, type the name that you want
to give this promoted result. In the URL field, type the URL of the
result that should be promoted. Render the URL as a banner
instead of as a hyperlink. Click Save.
o You can add several individual promoted results. When there is
more than one promoted result, you can specify the relative
ranking.
o To promote a group of search results, click Add Result Block. For
more information, see “Create and Display a Result Block” later in
this topic.
o To change ranked search results, click Change ranked results by
changing the query. For more information, see “Change Ranked
Search Results” later in this topic.
9. To make the query rule active during a particular time period, click
Publishing, and then specify the period.
Create and Display a Result Block
A “result block” is several search results that are displayed as a group. In the same
manner that you promote a specific result, you can promote a result block when a
specified query condition applies.
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
5 - 16
When you configure the query condition for a result block, you can use query
variables. “Query variables” are placeholders for values that you do not know
when you specify the query. However, when the query is run, this information is
known and you can use it when the system sends the query to the index.
Examples are {User.Name}, which represents the display name of the user who
typed the query, or {searchBoxQuery}. This represents the query that a user typed
in a search box. When you use Query Builder to configure the query, a list of
query variables is displayed. (See step 3 in the following procedure.)
To create a result block
1. In step 8 of the previous procedure, on the Add Query Rule page, in
the Actions section, click Add Result Block.
2. In the Block Title section, in the Title field, type a name for the result
block.
3. In the Query section, to specify the query, click Launch Query
Builder. In Query Builder, specify the following:
o On the BASIC tab, select options from the following lists to
define the query for the result block:
Select a query Select a result source to specify which content should be
searched.
Keyword filter You can use keyword filters to add query variables to your
query.
You can select predefined query variables from the drop-
down list, and then add them to the query by clicking Add
keyword filter.
Property filter You can use property filters to query the content of
managed properties that are set to queryable in the search
schema.
You can select managed properties from the Property
filter drop-down list. Click Add property filter to add the
filter to the query.
Note: For a list of available query variables, see Query variables in SharePoint
Server 2013 at http://technet.microsoft.com/en-us/library/jj683123.aspx.
On the SORTING tab, you can specify how search results within your
result block should be sorted.
o In the Sort by drop-down list:
To sort by managed properties that are set as sortable in
the search schema, select a managed property from the
Module 5: Search Configuration and Customization
5 - 17
list, and then select Descending or Ascending. To add
more sorting levels, click Add sort level.
To sort by relevance rank, select Rank, and then do the
following:
In the Ranking Model list, select which ranking model to
use for sorting search results (this selection is optional).
In the Dynamic ordering section, to specify additional
ranking by adding rules that change the order of search
results when certain conditions apply, click Add dynamic
ordering rule, and then specify conditional rules.
On the TEST tab, you can preview the query that is sent.
Query text Shows the final query that will be run by the Content Search
Web Part. It is based on the original query template where
dynamic variables are substituted with current values. Other
changes to the query may have to be made as part of query
rules.
Click Show more to display additional information.
Query
template
Shows the content of the query template that is applied to the
query.
Query
template
variables
Shows the query variables that will be applied to the query, and
the values of the variables that apply to the current page. You can
type other values to test the effect they will have on the query.
Click the Test Query button to preview the search results.
4. In the Query section, in the Configure Query box, in the Search this
Source drop-down list, select the result source to which this result
block should be applied.
5. In the Query section, in the Items drop-down list, select how many
results to show in the result block.
6. Expand the Settings section.
The result block will only display the number of search results that you specified in
the previous step. However, you can add a Show More link at the bottom of the
result block that displays all search results for the result block. To add a Show
More link, select "More" link goes to the following URL, and then type a URL.
You can use query variables in this URL, such as:
http://www.<site>/search/results.aspx?k={subjectTerms}.
7. Omit the Routing section.
8. Click OK.
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
5 - 18
Change Ranked Search Results
The ranking model calculates a ranking order of search results. You can change
this ranking by promoting or demoting items within the search results. For
example, for a query that contains "download toolbox," you can create a query
rule that recognizes the word "download" as an action term, and change the
ranked search results to promote a URL of a particular download site on your
intranet. You can also change the sorting order of the search results dynamically,
based on several variables such as file name extension or specific keywords.
Changing ranked search results by changing the query has the advantage of
results that are security-trimmed and refinable. In addition, the search results do
not appear if the document is no longer available.
To change ranked search results by changing the query
1. From step 8 of the procedure “Create a query rule,” on the Add
Query Rule page, in the Actions section, click Change ranked results
by changing the query.
2. In the Build Your Query dialog box, specify the following:
o On the BASIC tab, select options from the following table to
define the query for the result block.
Select a
query
Select a result source to specify which content should be
searched.
Keyword
filter
You can use keyword filters to add query variables to your
query.
You can select predefined query variables from the drop-down
list, and then add them to the query by clicking Add keyword
filter.
Property filter You can use property filters to query the content of managed
properties that are set to queryable in the search schema.
You can select managed properties from the Property filter
drop-down list. Click Add property filter to add the filter to the
query.
On the SORTING tab, you can specify how search results within your
result block should be sorted.
o In the Sort by drop-down list:
To sort by managed properties that are set as sortable in
the search schema, select a managed property from the
list, and then select Descending or Ascending. To add
more sorting levels, click Add sort level.
Module 5: Search Configuration and Customization
5 - 19
To sort by relevance rank, select Rank, and then do the
following:
In the Ranking Model list, select which ranking model to
use for sorting search results (this selection is optional).
In the Dynamic ordering section, to specify additional
ranking by adding rules that change the order of search
results when certain conditions apply, click Add dynamic
ordering rule, and then specify conditional rules.
On the TEST tab, you can preview the query that is sent.
Query text Shows the final query that is run by the Content Search Web
Part. It is based on the original query template where dynamic
variables are substituted with current values. Other changes to
the query may have to be made as part of query rules.
Click Show more to display additional information.
Query
template
Shows the content of the query template that is applied to the
query.
Query
template
variables
Shows the query variables that are applied to the query, and the
values of the variables that apply to the current page. You can
type other values to test the effect they have on the query. Click
the Test Query button to preview the search results.
Make a Query Rule Inactive
Query rules are created at the Search service application level. They are inherited
by site collections and sites that are in web applications that consume the Search
service application. Similarly, query rules that are created at the site collection
level are inherited by sites in the site collection. If you do not want a query rule to
apply to a site that inherits it, you can set the query rule as inactive for the site.
To make a query rule inactive on a site
1. Verify that the user account that performs this procedure is a member
of the Owners group for the site.
2. In the site collection, in the Settings menu, click Site Settings.
3. On the Site Settings page, in the Search section, click Query Rules.
4. On the Manage Query Rules page, on the Select a Result Source
menu, select the result source that contains the query rule that you
want to make inactive.
5. In the Name column, point to the query rule that you want to make
inactive, click the arrow that appears, and then click Make Inactive.
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
5 - 20
Rank Query Rules
When multiple query rules are active for a Search service application, a site
collection, or a site, more than one rule can fire for a query that is performed at
that level. By default, the rules do not fire in a prescribed order. You can control
the order in which the rules fire by adding the query rules that you create to
query groups. To do this, you select rules to add to a group, and then you specify
the order in which the rules in the group fire if they are triggered. You can also
prevent query rules that rank lowest in a group from firing even if they are
triggered.
To rank query rules for a site collection
1. Verify that the user account that performs this procedure is a site
collection administrator.
2. In the site collection, on the Settings menu, click Site Settings.
3. On the Site Settings page, in the Site Collection Administration
section, click Search Query Rules.
4. On the Manage Query Rules page, on the Select a Result Source
menu, select the result source that contains the query rules that you
want to group.
5. For each query rule that you created that you want to add to a group,
point to the rule and select the check box.
Note: “Defined For This Site Collection” contains query rules that you created
for this site collection.
6. Click Order Selected Rules.
7. In the Order Selected Rules dialog box, do one of the following, and
then click OK:
o Select Move rules to new group with this name, and then type
a name for the group.
o Select Move rules to existing group and select a group in the
drop-down list.
8. On the Manage Query Rules page, do the following:
a. To change the order in which a rule in a group fires if it is
triggered, change the numeric order of the rule.
b. To prevent query rules that are ranked lowest in the group from
firing, in the row for the group's query rule that should fire last, in
the Actions column, in the Continue/Stop drop-down list, select
Stop.
Module 5: Search Configuration and Customization
5 - 21
Module Review
Refiners and Faceted Navigation
1. When a catalog is crawled, SharePoint Server 2013 automatically
creates managed properties for all site columns that contain values.
These automatically-created managed properties use the Text data
type. Ensure that refiners use Number, Currency, Integer, and Date
and Time data types to display the refiners in the correct format.
2. Map a crawled property to a refinable managed property.
3. Configure refiners for faceted navigation by enabling a term set for
faceted navigation and by adding refiners to a term set.
4. Add JavaScript to a page to display refiners in the correct format. You
can use Content Editor Web Part on the page and add the JavaScript
to it.
Query Rules
1. You can create query rules at different levels in a SharePoint farm.
They inherit from highest level to lowest.
2. A result block is several search results that are displayed as a group.
3. A ranking model calculates a ranking order of search results.
4. A query rule can be made inactive at site level.
5. Query rules can be added to a group. You can control the order in
which query rules fire.
Best Practice: Plan for query rules during the Analysis and Design phase of
the project instead of during the build. Configuring query rules and fine-tuning
them takes time.
Test Your Knowledge
Test your knowledge with the following questions.
1. What is the difference between crawled property and managed property?
2. At what levels can you create Query Rules?
( ) Search Service Application only
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
5 - 22
( ) Site Collection level
( ) Site level
( ) All of the above
( ) None of the above
3. A result block is several search results that are displayed as a group.
( )True
( )False
Module 5: Search Configuration and Customization
5 - 23
Test Your Knowledge Solutions
Module Review and Takeaways
1. What is the difference between crawled property and managed property?
MODEL ANSWER:
Crawled properties must be mapped to a managed property.
2. At what levels can you create Query Rules?
( ) Search Service Application only
( ) Site Collection level
( ) Site level
(√) All of the above
( ) None of the above
3. A result block is several search results that are displayed as a group.
(√)True
( )False
6 - 1
MODULE 6: COMMERCE RUNTIME SERVICES
Module Overview
Microsoft Dynamics AX 2012 R3 Retail includes a sample Ecommerce site. The
Ecommerce site is built by using the cross-site publishing model in SharePoint
2013.
The Microsoft Dynamics AX commerce runtime (CRT) serves as the engine for the
Ecommerce site. It connects to a CRT database that stores business data for the
store.
Objectives
The objectives of this module are as follows:
Explain how to configure Commerce Runtime (CRT) for an
Ecommerce site.
Describe the available default services in CRT.
Present how to extend the CRT Services.
Review how to integrate a new Shipping Services in CRT.
As a prerequisite, refer to Module-1, “Ecommerce Technical Overview,” to
understand the architecture and design of CRT.
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
6 - 2
Commerce Runtime Extensibility
Microsoft Dynamics AX offers many services in the commerce runtime that
support the basic functionality of an online store. You can add your own services
or extend the services that are included in Microsoft Dynamics AX.
Integrate a Service into CRT
This topic describes how to create a new service and add it to the commerce run-
time configuration. To create a new service, you must create three different
objects: Request object, Response object and Service object. After you create the
service, you must change the Commerce Runtime configuration file. The following
steps document this process.
Create a Service
A service handles any number of service messages. A “service message “is the
combination of a service request and response. To create a service, you must
implement a request, a response, and a service.
The following steps show how to create a Request object:
1. Create a class that inherits from the ServiceRequest class.
Note: The ServiceRequest class encapsulates a service request that is sent to
services. It exposes information about the context and operation context. This
enables you to use logging and diagnostics functionality. It also exposes the
Validate method that enables you to confirm that the parameters that are passed in
are valid. It also exposes the ServiceRequest constructor that includes the
RequestContext object. The RequestContext object has information about the
current request that is being executed.
2. Implement the ServiceRequest constructor.
3. Implement any validation that you want to perform on the request.
The following steps show how to create a Response object:
1. Create an object that inherits from the ServiceResponse class.
2. Implement code to perform your preferred functionality. Typically,
this is a get or set operation.
The following steps show how to create a Service object:
1. Create an object that implements the IService interface.
2. Implement an execute method that takes a request object and returns
a class that is a service response.
Module 6: Commerce Runtime Services
6 - 3
3. Cast the request as a type that the service can handle. If the cast
succeeds, call a method to perform an action.
4. Return a response.
Change the Commerce Runtime Configuration File
Services are enumerated as types in the commerce runtime configuration file. The
commerce runtime configuration file controls which types to load. Services are
loaded in the order in which they are listed in the configuration file. All default
services are loaded automatically. However, if you add a new service above one of
the default services, the new service replaces the default service.
Note: You can also programmatically add a service to the catalog by using
the .NET API.
To change the commerce runtime configuration file:
1. Open commerceRuntime.config in your solution.
Note: The location of this file varies based on your deployment. If you are
customizing the SharePoint starter store, you can find the file by using the Internet
Information Services (IIS) Manager. In IIS Manager, find the starter store under the
Sites node. Right-click the public starter store, and then click Explore.
2. Add a line to include your new service. To load an entire assembly,
add a line like the following example from Walkthrough: Integrating a
new Shipping Service:
<add source="assembly" value="ContosoShippingCarrier,
Version=1.0.0.0, Culture=neutral,
PublicKeyToken=6598494e9dab8361, processorArchitecture=MSIL" />
To add a specific type, add a line like the following:
<add source="type" value="Fully_Qualified_Name_Of_Type,
AssemblyName"/>
Commerce Runtime Configuration
(CommerceRuntime.config)
Services are enumerated as types in the commerce run-time configuration file.
You can add types in the commerce run-time configuration file to control the
services that are loaded in the commerce runtime.
Services are loaded in the order in which they are listed in the configuration file.
All default services are loaded automatically. However, if you add a new service
above one of the default services, the new service replaces the default service.
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
6 - 4
To replace a service in the CRT, remove the type that represents that service from
the file, and then add the type that represents the service that you want to use.
You can either use fully-qualified assembly names to load assemblies from the
Global Assembly Cache, or you can use specific types from a directory source.
Example CommerceRuntime.Config file
<?xml version="1.0" encoding="utf-8"?>
<commerceRuntime>
<query defaultPageSize="250" maxPageSize="5000" />
<composition>
<!-- Please use fully qualified assembly names for ALL so we can
support loading from the Global Assembly Cache. -->
<add source="assembly"
value="Microsoft.Dynamics.Commerce.Runtime.Services, Version=6.2.0.0,
Culture=neutral, PublicKeyToken=31bf3856ad364e35,
processorArchitecture=MSIL" />
<add source="assembly"
value="Microsoft.Dynamics.Commerce.Runtime.Workflow, Version=6.2.0.0,
Culture=neutral, PublicKeyToken=31bf3856ad364e35,
processorArchitecture=MSIL" />
<!--
You can also compose specific types or from a directory source.
<add source="type"
value="Microsoft.Dynamics.Commerce.Runtime.Services.Pricing.Pricing,
Microsoft.Dynamics.Commerce.Runtime.Services"/>
<add source="type"
value="Microsoft.Dynamics.Commerce.Runtime.Services.Dimension.Dimension,
Microsoft.Dynamics.Commerce.Runtime.Services"/>
<add source="directory" value="%ProgramFiles%\Microsoft
Dynamics\6.0\"/>
-->
</composition>
</commerceRuntime>
Integrate a New Shipping Service
The commerce runtime (CRT) includes a shipping service to calculate shipping
costs and to determine shipping options for the current order. As with all services
in the CRT, you can use the default shipping service from Microsoft Dynamics AX
or you can use a third-party shipping service. This topic describes how to integrate
a new Contoso shipping service into the CRT.
Shipping functionality in the CRT consists of the shipping service and the shipping
carrier adapter service. You use the shipping service for any shipping-related
information. The shipping service calls into the shipping carrier adapter service if
additional real-time information from the actual shipping carrier, such as FedEx, is
required. See the following examples:
A retailer needs custom rates from the shipping carrier for each package
rather than a flat shipping rate.
A retailer wants to display the latest tracking information from the
Module 6: Commerce Runtime Services
6 - 5
shipping carrier.
A retailer wants to validate that a shipping address is valid for the
shipping carrier before an order is placed.
To integrate a new shipping service, do the following:
1. Create a shipping carrier class that inherits from the Service abstract class
and implements the IShippingCarrierService interface.
2. Create classes to encapsulate business logic for the shipping service.
3. Update the CommerceRuntime.config file to include the new shipping
service.
4. Configure the shipping adapter in Microsoft Dynamics AX.
Create a Shipping Carrier Class
The shipping carrier adapter service provides an entry point for a CRT entity to
communicate with an external shipping carrier. Both the shipping service and the
shipping carrier adapter service can be replaced independently of each other, as
long as the shipping service replacement implements IShippingService and the
shipping carrier replacement replaces IShippingCarrierService,. In this section you
create a class that inherits from the Service class and implements the
IShippingCarrierService interface.
To create a class project, do the following:
1. Create a new C# class library project in Visual Studio. For this example,
name it ContosoShippingCarrier.
2. Click PROJECT > ContosoShippingCarrier Properties…
3. Click Signing, and then select Sign the assembly.
4. In Choose a strong name key file, specify a key file.
5. In Solution Explorer, right-click ContosoShippingCarrier, and then click
Add Reference.
Add the following references:
o Microsoft.Dynamics.Commerce.Runtime ◦
o Microsoft.Dynamics.Commerce.Runtime.Services.Messages
o System.ComponentModel.DataAnnotations
o System.Runtime.Serialization
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
6 - 6
Note: The location of this file varies based on your deployment. If you are
customizing the SharePoint starter store, you can find the file by using the Internet
Information Services (IIS) Manager. In IIS Manager, find the starter store under the
Sites node. Right-click the public starter store, and then click Explore.
Open the C# class in your project and write logic for your shipping adapter.
Consider the following as you write your code:
Decorate the class by using the [Export(typeof(IService))] attribute.
Inherit from the Service class and implement the IShippingCarrierService
interface.
The ExecuteRequest(ServiceRequest) method determines the type of a
request and handles it accordingly.
If the carrier adapter requires a set of specific configuration values to
contact a web service, provide those adapter configuration values as part
of a parameter that is set inside the ServiceRequest object that is passed
into the shipping carrier.
The Name property serves as a unique identifier for the adapter binary.
For each delivery mode, the CRT determines which adapter for which to
create an instance based on this string value. This value must match one
of the rows in the RetailShipCarrierInterface table.
We recommend that you encapsulate into separate classes the logic of
each major task that is supported by the carrier, such as address
validation, rate calculation, and tracking information.
If the carrier expects the country codes and state codes in a format that is
different from what is used by the CRT, add a country region mapper.
The following code shows an example of a shipping carrier adapter:
Shipping Carrier code
namespace ContosoShippingCarrier
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.Composition;
using Microsoft.Dynamics.Commerce.Runtime;
using Microsoft.Dynamics.Commerce.Runtime.DataModel;
using Microsoft.Dynamics.Commerce.Runtime.Services;
using Microsoft.Dynamics.Commerce.Runtime.Services.Messages;
/// <summary>
/// Encapsulates code for the contoso shipping carrier adapter.
/// </summary>
[Export(typeof(IService))]
public sealed class ContosoShippingCarrierAdapter : Service,
IShippingCarrierService
{
Module 6: Commerce Runtime Services
6 - 7
/// <summary>
/// Enumerates a list of services that are supported by the
carrier.
/// </summary>
private enum WebServiceType
{
/// <summary>
/// Lists webservices that this adapter supports.
/// </summary>
AddressValidation = 1,
Tracking = 2,
Rating = 3
};
/// <summary>
/// Identifies an adapter binary.
/// </summary>
public string Name
{
get { return "Contoso"; }
}
/// <summary>
/// Executes the specified request.
/// </summary>
/// <typeparam name="TResponse">The type of the
response.</typeparam>
/// <param name="request">The request.</param>
/// <returns>The response.</returns>
protected override TResponse
ExecuteRequest<TResponse>(ServiceRequest request)
{
if (request == null)
{
throw new ArgumentNullException("request");
}
object response;
Type requestType = request.GetType();
if (requestType ==
typeof(GetShippingRateFromCarrierServiceRequest))
{
response =
GetShippingRate((GetShippingRateFromCarrierServiceRequest)request);
}
else if (requestType ==
typeof(GetTrackingInformationFromCarrierServiceRequest))
{
response =
GetTrackingDetails((GetTrackingInformationFromCarrierServiceRequest)reques
t);
}
else if (requestType ==
typeof(ValidateShippingAddressCarrierServiceRequest))
{
response =
ValidateShippingAddress((ValidateShippingAddressCarrierServiceRequest)requ
est);
}
else
{
throw new NotSupportedException(string.Format("Request
'{0}' is not supported.", request));
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
6 - 8
}
return (TResponse)response;
}
/// <summary>
/// Called for service-specific initialization.
/// </summary>
/// <param name="runtime">The runtime.</param>
public void Initialize(CommerceRuntime runtime)
{
// Any service initiliation code goes here.
// Example: Instantiation of data mapper, etc.
}
/// <summary>
/// Called for services-specific deinitialization.
/// </summary>
public void Uninitialize()
{
// Any service-specific deinitialization code goes here.
}
/// <summary>
/// Validates the shipping address.
/// </summary>
/// <param name="request">The request.</param>
/// <returns>The address validation response.</returns>
private static ValidateShippingAddressCarrierServiceResponse
ValidateShippingAddress(ValidateShippingAddressCarrierServiceRequest
request)
{
if (request.AddressToValidate == null)
{
throw new
ArgumentNullException("request.AddressToValidate");
}
if (request.AdapterConfig == null)
{
throw new ArgumentNullException("request.AdapterConfig");
}
IEnumerable<Address> suggestedAddresses = new
Collection<Address>();
bool isValid = false;
try
{
isValid =
AddressValidator.ValidateShippingAddress(request.AddressToValidate,
request.SuggestAddress, request.AdapterConfig, out suggestedAddresses);
}
catch (Exception ex)
{
ContosoErrorHandler(ex, WebServiceType.AddressValidation);
}
return new
ValidateShippingAddressCarrierServiceResponse(isValid,
suggestedAddresses);
}
/// <summary>
Module 6: Commerce Runtime Services
6 - 9
/// Gets the shipping rate.
/// </summary>
/// <param name="request">The request.</param>
/// <returns>The shipping rate response from the
carrier.</returns>
private static GetShippingRateFromCarrierServiceResponse
GetShippingRate(GetShippingRateFromCarrierServiceRequest request)
{
if (request.ShippingRateInfo == null)
{
throw new
ArgumentNullException("request.ShippingRateInfo");
}
if (request.AdapterConfig == null)
{
throw new ArgumentNullException("request.AdapterConfig");
}
decimal rates = 0;
try
{
rates =
RateCalculator.GetShippingRate(request.ShippingRateInfo,
request.AdapterConfig);
}
catch (Exception ex)
{
ContosoErrorHandler(ex, WebServiceType.Rating);
}
return new GetShippingRateFromCarrierServiceResponse(rates);
}
/// <summary>
/// Gets tracking details.
/// </summary>
/// <param name="request">The request.</param>
/// <returns>The tracking details response from carrier.</returns>
private static GetTrackingInformationFromCarrierServiceResponse
GetTrackingDetails(GetTrackingInformationFromCarrierServiceRequest
request)
{
if (request.AdapterConfig == null)
{
throw new ArgumentNullException("request.AdapterConfig");
}
if (request.TrackingNumbers == null)
{
throw new
ArgumentNullException("request.TrackingNumbers");
}
IEnumerable<TrackingInfo> trackingDetails = new
Collection<TrackingInfo>();
try
{
trackingDetails =
Tracker.GetTrackingDetails(request.AdapterConfig,
request.TrackingNumbers);
}
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
6 - 10
catch (Exception ex)
{
ContosoErrorHandler(ex, WebServiceType.Tracking);
}
return new
GetTrackingInformationFromCarrierServiceResponse(trackingDetails);
}
/// <summary>
/// Handles exceptions for all Contoso shipping adapter services.
/// </summary>
/// <param name="exception">The exception.</param>
/// <param name="serviceType">Type of the service that triggered
the exception.</param>
/// <exception cref="CommunicationException">To notify called of
any exception with customized message</exception>
private static void ContosoErrorHandler(Exception exception,
WebServiceType serviceType)
{
Type exceptionType = exception.GetType();
Exception translatedException = null;
if (exceptionType ==
typeof(System.Web.Services.Protocols.SoapException))
{
var ex = exception as
System.Web.Services.Protocols.SoapException;
translatedException = new
CommunicationException(CommunicationErrors.ExternalProviderError,
"Soap exception in Contoso
adapter." + exception.Message,
exception);
}
else
{
translatedException = new
CommunicationException(CommunicationErrors.ProviderCommunicationFailure,
"Unable to communicate with
Contoso." + exception.Message,
exception);
}
throw translatedException;
}
}
}
We recommend that you encapsulate business logic for address validation in a
separate class. The following code shows an example of an address validation class
for your shipping carrier adapter:
Address Validation code
namespace ContosoShippingCarrier
{
using System;
using System.Collections.Generic;
Module 6: Commerce Runtime Services
6 - 11
using Microsoft.Dynamics.Commerce.Runtime;
using Microsoft.Dynamics.Commerce.Runtime.DataModel;
/// <summary>
/// Static class to call into Contoso Address Validation WebService.
/// </summary>
internal static class AddressValidator
{
/// <summary>
/// Validates the shipping address.
/// </summary>
/// <param name="enteredAddress">The entered address.</param>
/// <param name="suggestAddress">A value indicating whether the
service should suggest addresses.</param>
/// <param name="adapterConfig">The adapter config.</param>
/// <param name="suggestedAddresses">The suggested
addresses.</param>
/// <returns>
/// Returns true if address was valid.
/// </returns>
public static bool ValidateShippingAddress(Address enteredAddress,
bool suggestAddress, ParameterSet adapterConfig, out IEnumerable<Address>
suggestedAddresses)
{
if (enteredAddress == null)
{
throw new ArgumentNullException("enteredAddress");
}
if (adapterConfig == null)
{
throw new ArgumentNullException("adapterConfig");
}
suggestedAddresses = null;
Boolean isValid = true;
// This is where a call to carrier web service would be made
to validate the address and get suggestions.
// Currently the code always returns true.
return isValid;
}
}
}
We recommend that you encapsulate business logic for rate calculation in a
separate class. The following code shows an example of a rate calculation class for
your shipping carrier adapter:
Rate Calculation code
namespace ContosoShippingCarrier
{
using System;
using Microsoft.Dynamics.Commerce.Runtime;
using Microsoft.Dynamics.Commerce.Runtime.DataModel;
/// <summary>
/// Static class to call into ContosoShipping Rate WebService.
/// </summary>
internal static class RateCalculator
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
6 - 12
{
/// <summary>
/// Gets the shipping rate.
/// </summary>
/// <param name="shippingRateInfo">The shipping rate info.</param>
/// <param name="adapterConfig">The adapter config.</param>
/// <returns>
/// Shipping Rate
/// </returns>
public static decimal GetShippingRate(ShippingRateInfo
shippingRateInfo, ParameterSet adapterConfig)
{
if (adapterConfig == null)
{
throw new ArgumentNullException("adapterConfig");
}
if (shippingRateInfo == null)
{
throw new ArgumentNullException("shippingRateInfo");
}
if (shippingRateInfo.ToAddress == null)
{
throw new
ArgumentNullException("shippingRateInfo.ToAddress");
}
if (shippingRateInfo.FromAddress == null)
{
throw new
ArgumentNullException("shippingRateInfo.FromAddress");
}
if (shippingRateInfo.GrossWeight <= 0)
{
throw new
ArgumentOutOfRangeException("shippingRateInfo.GrossWeight","Gross weight
cannot be zero or negative.");
}
decimal totalCharges = 0M;
// Call external service to get rate by using info in
ShippingRateInfo (FromAddress, GrossWeight, ToAddress).
// Our sample code returns a preset shipping charge
if (shippingRateInfo.GrossWeight < 10M)
{
decimal ChargePerUnitOfWeight = 2;
totalCharges = shippingRateInfo.GrossWeight *
ChargePerUnitOfWeight;
}
else
{
totalCharges = 20M;
}
return totalCharges;
}
}
Module 6: Commerce Runtime Services
6 - 13
}
We recommend that you encapsulate business logic for tracking information in a
separate class. The following code shows an example of a tracking information
class for your shipping carrier adapter:
Tracking information code
namespace ContosoShippingCarrier
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Microsoft.Dynamics.Commerce.Runtime;
using Microsoft.Dynamics.Commerce.Runtime.DataModel;
/// <summary>
/// Static class to call into ContosoShipping Track WebService.
/// </summary>
internal static class Tracker
{
/// <summary>
/// Message contents of response from webservice when a shipment's
information is not in their database.
/// </summary>
private const string ShipmentNotReceivedYet = "No information for
the following shipments has been received by our system yet";
/// <summary>
/// Gets the tracking details using tracking numbers specified
inside <see cref="TrackingInfo"/>.
/// Makes multiple calls to the webservice. One call per tracking
number.
/// </summary>
/// <param name="adapterConfig">The adapter configuration.</param>
/// <param name="trackingNumbers">The tracking numbers.</param>
/// <returns>Tracking details for all the tracking
numbers.</returns>
public static ReadOnlyCollection<TrackingInfo>
GetTrackingDetails(ParameterSet adapterConfig, IEnumerable<string>
trackingNumbers)
{
if (adapterConfig == null)
{
throw new ArgumentNullException("adapterConfig");
}
if (trackingNumbers == null)
{
throw new ArgumentNullException("trackingNumbers");
}
Collection<TrackingInfo> trackingDetails = new
Collection<TrackingInfo>();
// Call external web service to get tracking info.
foreach (string trackingNumber in trackingNumbers)
{
TrackingInfo trackingInfo = new TrackingInfo {
TrackingNumber = trackingNumber };
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
6 - 14
// Use web service response to set trackingInfo porperties
such as ShippedOnDate, DeliveredOnDate, DestinationAddress,
EstimatedDeliveryDate, OriginAddress,
// PackageWeight, PackagingType, ServiceType,
ShipmentProgress, ShippedOnDate, ShippingCharge, Status, TrackingNumber,
TrackingUrl.
trackingDetails.Add(trackingInfo);
}
return trackingDetails.AsReadOnly();
}
}
}
We recommend that you encapsulate all configuration keys required by the
carrier inside a separate class. These keys will be used to look up corresponding
values inside the adapter configuration parameter set that is passed in as part of
the ServiceRequest object. The following code shows an example of adapter
configuration fields code:
Adapter Configuration Fields code
namespace ContosoShippingCarrier
{
/// <summary>
/// Container of name of all the fields that are read from the adapter
configuration for ContosoShipping.
/// </summary>
internal static class AdapterConfigurationFields
{
/// <summary>
/// Name of field that contains the web service url in adapter
configuration.
/// </summary>
public const string TrackWebServiceUrl = "TrackWebServiceUrl";
/// <summary>
/// Name of field that contains the web service url in adapter
configuration.
/// </summary>
public const string RateWebServiceUrl = "RateWebServiceUrl";
/// <summary>
/// Adapter configuration field.
/// </summary>
public const string UserCredentialKey = "UserCredentialKey";
/// <summary>
/// Adapter configuration field.
/// </summary>
public const string UserCredentialPassword =
"UserCredentialPassword";
/// <summary>
/// Adapter configuration field.
/// </summary>
public const string AccountNumber = "AccountNumber";
/// <summary>
Module 6: Commerce Runtime Services
6 - 15
/// Adapter configuration field.
/// </summary>
public const string MeterNumber = "MeterNumber";
/// <summary>
/// Adapter configuration field.
/// </summary>
public const string DropOffType = "DropOffType";
/// <summary>
/// Adapter configuration field.
/// </summary>
public const string RateRequestType = "RateRequestType";
/// <summary>
/// Adapter configuration field.
/// </summary>
public const string ServiceType = "ServiceType";
/// <summary>
/// Adapter configuration field.
/// </summary>
public const string PackagingType = "PackagingType";
/// <summary>
/// Adapter configuration field.
/// </summary>
public const string WeightUnits = "WeightUnits";
/// <summary>
/// Adapter configuration field.
/// </summary>
public const string LinearUnits = "LinearUnits";
/// <summary>
/// Adapter configuration field.
/// </summary>
public const string CurrencyCode = "CurrencyCode";
}
}
Change the CommerceRuntime.config (CRT) Configuration File
The CRT configuration file contains an enumeration of services as types, and it
controls which types to load. By default, all types that are included with Microsoft
Dynamics AX are loaded. To replace a service in the CRT, remove the type that
represents that service from the file, and then add the type that represents the
service that you want to use.
Note: Types are loaded in the order in which they are listed in the
configuration file. Instead of removing a type to replace it with a customized type,
you can add your customized type above it in the file and it is used instead.
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
6 - 16
To change the CRT configuration file, do the following:
1. Open commerceRuntime.config in your solution.
2. Add a line to include your new service. such as the following:
<add source="assembly" value="ContosoShippingCarrier,
Version=1.0.0.0, Culture=neutral,
PublicKeyToken=6598494e9dab8361, processorArchitecture=MSIL" />
Note: The location of this file varies based on your deployment. If you are
customizing the SharePoint starter store, you can find the file by using the Internet
Information Services (IIS) Manager. In IIS Manager, find the starter store under the
Sites node. Right-click the public starter store, and then click Explore.
Configure the Shipping Adapter in Microsoft Dynamics AX
To configure the shipping adapter, do the following:
1. Create a shipping carrier account.
2. Create a unique identifier for the shipping adapter.
3. Map the shipping carrier account to the new shipping adapter.
4. Map the delivery mode to the new carrier ID.
5. Configure the Auto charge in Microsoft Dynamics AX 2012. For more
information about configuring auto charges, –click
http://technet.microsoft.com/en-us/library/aa571826.aspx.
Note: For information about calculating the charge, specify External in the
Category field in the Auto Charges section in Microsoft Dynamics AX 2012.
6. Run the jobs and synchronize the tables to update the delivery mode
mapping in the CRT database. The shipping carrier account is set up
in the Carrier company form.
Each external shipping adapter in the CRT is uniquely identified by the Name
property of the IShippingCarrierService interface that is implemented by each
shipping adapter. This information is reflected in Microsoft Dynamics AX in the
RetailShipCarrierInterface table. To register a new shipping adapter in Microsoft
Dynamics AX, add the name and description for the adapter in the
RetailShipCarrierInterface table by using the AddRetailShippingCarrier job later in
this topic. Use the Carrier IDs form to map the shipping carrier account to the new
shipping adapter.
Module 6: Commerce Runtime Services
6 - 17
For more information, see Carrier IDs form at http://technet.microsoft.com/EN-
US/library/hh209608.aspx. Set up shipping carriers at
http://technet.microsoft.com/EN-US/library/gg213688.aspx.
Use the Modes of delivery form to map the deliver mode to a carrier ID. For more
information, see Modes of delivery form at http://technet.microsoft.com/EN-
US/library/aa619881.aspx .Set up modes of delivery for online stores at
http://technet.microsoft.com/EN-US/library/jj728719.aspx.
To create the shipping carrier account in Microsoft Dynamics AX, do the following:
1. In Microsoft Dynamics AX, click Inventory and Warehouse
Management > Setup > Shipping Carrier > Carrier Company.
2. Click New.
3. Enter the carrier in the Carrier field, and then enter charges in the
General Charges fields.
4. Under Accounts, click Add.
5. Enter an Account Code, Carrier Account Number, and Currency for the
shipping carrier.
6. Click Configuration.
7. Specify any values that are required for the external carrier adapter in the
CRT, such as, the web service URL of the external shipping carrier, the
logon credentials for the web service, or units of measure.
For example, you can specify the web service URL of the external shipping carrier,
the logon credentials for the web service, or units of measure.
To create a unique identifier for the shipping adapter in Microsoft Dynamics AX,
do the following:
Add the name of the shipping adapter to the RetailShipCarrierInterface table by
using the following job:
static void AddRetailShippingCarrier(Args _args)
{
RetailShipCarrierInterfaceId carrierAdapterId = 'Contoso';
str carrierDescription = "Contoso Shipping Adapter";
RetailShipCarrierInterface loc_RetailShipCarrierInterface;
ttsBegin;
select forUpdate loc_RetailShipCarrierInterface where
loc_RetailShipCarrierInterface.CarrierAdapterId ==
carrierAdapterId;
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
6 - 18
if (loc_RetailShipCarrierInterface.RecId == 0)
{
loc_RetailShipCarrierInterface.CarrierAdapterId =
carrierAdapterId;
loc_RetailShipCarrierInterface.Description =
carrierDescription;
loc_RetailShipCarrierInterface.insert();
}
ttsCommit;
}
To map a shipping carrier account in Microsoft Dynamics AX to the new shipping
adapter in Microsoft Dynamics AX, do the following:
1. Click Inventory and Warehouse Management > Setup > Shipping
Carrier > Carrier IDs.
2. Click New.
3. Enter a unique carrier identifier in the Carrier ID field and a
description in the Carrier service description field, such as C01 for
Contoso.
4. Enter Contoso in the Carrier company field.
To map a delivery mode to a carrier ID, do the following:
1. Click Sales and Marketing > Setup > Distribution > Modes of
Delivery.
2. Specify a Mode of delivery or create a new one. For more
information, see “Set Up Modes of Delivery for Online Stores“.
3. Under Setup, select a Service.
4. Select the carrier ID that you specified in the previous procedure. This
populates the Carrier Company and Account Code fields.
Note: If multiple accounts are associated with a carrier company, select the
account code that has the associated adapter configuration.
Follow these steps to update the delivery mode mapping to the CRT database:
1. Click Retail > Periodic > Process delivery modes, and then click
OK.
2. Click Retail > Periodic > Data distribution > Create Actions.
Module 6: Commerce Runtime Services
6 - 19
3. Run the following jobs:
A-1120_OC
N-1120_OC
The jobs synchronize the following tables:
RetailShipCarrierAccountConfiguration
ShipCarrierCompanyAccounts
RetailShipCarrierInterface
ShipCarrierTable
DlvMode
Default CRT services
The following table highlights the most common services that you can use to
customize the Ecommerce store.
Service Description
AddressService Verifies addresses and gets location information such
as cities, counties, or states.
ChargeService Calculates auto-charges, price charges, and shipping
charges for a transaction.
CurrencyService Converts currencies based on exchange rates.
CustomerService Maintains customer information.
DimensionService Enables customers to find items in your store based
on criteria, such as category or color.
EmailService Sends email to customers based on an email template
that is defined in Microsoft Dynamics AX.
LoyaltyService Implements a program that rewards repeat
customers.
PaymentService Connects your online store to a payment service to
provide credit card authorization and to use
preconfigured payment processing. You can also
extend the payment service to add more third-party
payment processors. For more information about how
to use a third-party payment service, see “Create a
Payment Connector to Process Payments from a
Third-Party Provider.”
PricingService Obtains the price of an item in real time. The price is
adjusted based on the base price and any applicable
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
6 - 20
Service Description
discounts. Discounts can be customized for each
retailer.
ProductAvailabilityServi
ce
Calculates the quantities of products that are available
to sell.
RoundingService Rounds the tender amount that is based on the
tender type and store.
SalesOrderService Creates a sales order that is based on a customer
shopping cart.
ShippingService Calculates shipping costs and determines shipping
options for the current order. You can use shipping
data from Microsoft Dynamics AX or from a third-
party shipping service.
StoreLocatorService Generates a list of stores that is based on criteria, such
as nearness and product availability.
TaxService Calculates the sales tax for the current order. You can
use sales tax information from Microsoft Dynamics AX
or from a third-party sales tax service.
TotalingService Calculates the totals on the sales transactions and
sales lines.
Customize the Functionality of the Ecommerce Site
Microsoft Dynamics AX 2012 introduces a new suite of features that helps you
deploy, manage, and customize an online sales channel that is fully integrated
with Microsoft Dynamics AX. Ecommerce investments include a starter online
store that is built on Microsoft SharePoint Server 2013, developer tools, and
administrative and run-time components that integrate the online channel with
Microsoft Dynamics AX. By using this new suite of Ecommerce features, you can
centrally manage products, merchandising, and order fulfillment for all aspects of
your online sales channel directly in Microsoft Dynamics AX. The run-time
component enables you to deliver content and retail services in a scalable way.
The new starter online store speeds up the development of a highly customized
Ecommerce site. The starter online store includes the patterns and best practices
that are required to support production-ready deployments. This includes
powerful search-driven adaptive experiences that are offered by the SharePoint
Server 2013.
In this lesson, we discuss how to customize and extend the components that are
used in the Ecommerce site.
Module 6: Commerce Runtime Services
6 - 21
Lesson Objectives
Explain how to change the user interface behavior of the Ecommerce
site.
Describe how to change and extend the functionality of the
Commerce Runtime (CRT).
Present how to extend the Commerce Data Exchange: Real-Time
Service.
Preview how to customize or extend Search functionality.
Integrate a New Service in Commerce Runtime
Microsoft Dynamics AX retail services are scalable and extensible services that are
empowered through a combination of the commerce data exchange and the
commerce runtime.
The commerce runtime includes several services that represent particular areas of
functionality for your online store. If one of these services does not meet the
needs of your store, you can completely replace it with your own service and
continue to use the other services that are installed with the commerce runtime.
This topic describes how to create a new service and add it to the commerce
runtime configuration.
To create a new service, you must create three different objects: Request object,
Response object, and Service object. After you create the service, you must
change the Commerce Runtime configuration file. The following steps highlight
this process.
Create a Service
A service handles any number of service messages. A “service message” is the
combination of a service request and response. To create a service, you implement
a request, a response, and a service.
To create a Request object, do the following:
1. Create a class that inherits from the ServiceRequest class.
Note: The ServiceRequest class encapsulates a service request that is sent to
services. It exposes information about the context and operation context. This
enables you to use logging and diagnostics functionality. It also exposes the
Validate method that enables you to validate that the parameters that are passed
in are valid. It also exposes the ServiceRequest constructor that takes in the
RequestContext object. The RequestContext object has information about the
current request that is being executed.
2. Implement the ServiceRequest constructor.
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
6 - 22
3. Optionally implement any validation that you want to perform on the
request.
To create a Response object, do the following:
1. Create an object that inherits from the ServiceResponse class.
2. Implement code to perform your desired functionality. This is typically
a get or set operation.
To create a Service object, do the following:
1. Create an object that implements the IService interface.
2. Implement an execute method that takes a request object and returns
a class that is a service response.
3. Cast the request as a type that the service can handle. If the cast
succeeds, call a method to perform an action.
4. Return a response.
Change the Commerce Runtime Configuration File
Services are enumerated as types in the commerce runtime configuration file. The
commerce run-time configuration file controls which types to load. Services are
loaded in the order in which they are listed in the configuration file. All default
services are loaded automatically.. However, if you add a new service above one of
the default services, the new service replaces the default service.
Note: You can also programmatically add a service to the catalog using the
.NET API.
To change the commerce runtime config file, do the following:
1. Open commerceRuntime.config in your solution.
Note: The location of this file varies based on your deployment. If you are
customizing the SharePoint starter store, you can locate the file by using the
Internet Information Services (IIS) Manager. In IIS Manager, find the starter store
under the Sites node. Right-click the public starter store, and then click Explore.
2. Add a line to include your new service. To load a whole assembly, add
a line exactly like the following example from “Integrate a New
Shipping Service.”
<add source="assembly" value="ContosoShippingCarrier,
Version=1.0.0.0, Culture=neutral,
PublicKeyToken=6598494e9dab8361, processorArchitecture=MSIL" />
Module 6: Commerce Runtime Services
6 - 23
To add a specific type, add a line exactly like the following:
<add source="type" value="Fully_Qualified_Name_Of_Type,
AssemblyName"/>
Customize the Data in Commerce Entity
The CommerceEntity class is the base class of all entities in the commerce runtime
(CRT). The CommerceEntity class is a property bag of key value pairs of C#
properties. These properties provide string representations of fields from the
database so that you do not have to remember the names of columns in your
database when you write code. When you use commerce run-time APIs, you must
use commerce entities because the base class expects all parameters to be of type
CommerceEntity. But after you retrieve data from the database and return it from
the data manager, you can create regular C# objects that you can use in workflow
or services.
For any existing data type, if you add one or more new fields to a table in
Microsoft Dynamics AX, the commerce entity automatically includes those fields
as long as you change the stored procedure or view to return the additional field.
For example, you might want to verify the age of a customer for a particular
transaction. However, that information is not included in the customer object. To
enable the customer commerce entity to include the customer age automatically,
you can add a field in a Microsoft Dynamics AX table to store the customer age
and update the view in the commerce runtime to also return customer age.
Note: Adding customer age is an example that demonstrates this concept.
You also can access customer age through another way.
Update Properties in a Commerce Entity
To update the properties that are available in the commerce entity, you must do
the following:
1. Identify the field in Microsoft Dynamics AX that you want to expose in
the commerce entity. If the data that you want is not in an existing
table, you must create a new field on a new or existing table.
2. Change the stored procedure or view that specifies the data that is
passed from Microsoft Dynamics AX to the commerce entity.
3. Update the commerce entity to include the new field.
Note: If the field that you want to use already exists, go to ”To change the
view to include the new field.”
4. Add the new field in the CRT database.
5. Update the Synch service to pass the new field.
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
6 - 24
To change the view to include the new field, do the following:
1. Connect to your database server in SQL Server Management Studio.
2. Expand the Databases node, the node for your CRT database and the
Views node, and then find the view that corresponds to the data
entity you want to change.
3. Right-click the view, point to Script View as, point to ALTER To, and
then click New Query Editor Window.
4. Update the view to include the field that you created.
To update the commerce entity, do the following:
1. Open the commerce entity in Visual Studio.
2. Add a string variable to represent the property that you are adding,
for example, see the following:
private const string CustAge = “AGE”;
3. Add a method to cast the value from the field in Microsoft Dynamics
AX as a string and set it as the value for the property, for example, see
the following:
public string Age
{
get { return (string)this[CustAge]; }
set { this[CustAge] = value; }
}
Customize Workflows in Commerce Runtime
The commerce runtime includes workflow business logic that enforces rules for
your business. For example, after a customer places an order, you can use a
workflow to make sure that there is sufficient quantity available, validate the tax
calculation, check for credit approval, and then place the order. You can use the
workflows that are included in CRT or create your own.
A service encapsulates operations to perform one atomic task, whereas a workflow
performs a set of tasks. A workflow contains a set of steps that calls into one or
more services.
To create a workflow, do the following:
Exactly like services, workflows use the request and response pattern. The request
object inherits from the base commerce runtime Request class. The response
object inherits from the base commerce runtime Response class.
A workflow also has a request handler class that extends the
WorkflowRequestHandler<TRequest, TResponse> class. To create a workflow, you
create a request class and a response class, and then create a request handler class
that contains the business logic for your workflow. The following is an example
workflow for managing promotions.
Module 6: Commerce Runtime Services
6 - 25
To create a request, do the following:
Create a class that inherits from the base commerce runtime Request class, and
create any incoming parameters that you must have for your workflow. The
following example shows the GetPromotionsRequest class from the Promotions
workflow.
namespace Extensions.Promotions.Workflow
{
using Microsoft.Dynamics.Commerce.Runtime.Messages;
/// <summary>
/// Request Object for the PromotionsWorkFlowRequestHandler class.
/// </summary>
public class GetPromotionsRequest : Request
{
/// <summary>
/// Initializes a new instance of the <see cref="GetPromotionsRequest"/> class.
/// </summary>
public GetPromotionsRequest()
{
}
/// <summary>
/// Gets or sets the channel identifier.
/// </summary>
public long ChannelId { get; set; }
/// <summary>
/// Gets or sets the catalog identifier.
/// </summary>
public long CatalogId { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to get the summarized data set.
/// </summary>
public bool HasPromotionData { get; set; }
}
}
To create a response, do the following:
Create a class that inherits from the base commerce runtime Response class. The
following example displays the GetPromotionsResponse class from the
Promotions workflow.
namespace Extensions.Promotions.Workflow
{
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Extensions.Promotions.Data;
using Microsoft.Dynamics.Commerce.Runtime;
using Microsoft.Dynamics.Commerce.Runtime.Messages;
/// <summary>
/// Creates the response object for the Workflow.
/// </summary>
public class GetPromotionsResponse : Response
{
/// <summary>
/// Initializes a new instance of the <see cref="GetPromotionsResponse"/> class.
/// </summary>
/// <param name="promotions">The summerized promotions.</param>
public GetPromotionsResponse(IEnumerable<ChannelPromotionsSummarizedData> promotions)
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
6 - 26
{
this.SummarizedPromotions = promotions.AsReadOnly();
}
/// <summary>
/// Initializes a new instance of the <see cref="GetPromotionsResponse"/> class.
/// </summary>
/// <param name="promotions">The promotions.</param>
public GetPromotionsResponse(IEnumerable<PromotionDetails> promotions)
{
this.Promotions = promotions.AsReadOnly();
}
/// <summary>
/// Gets all the summarized channel promotions.
/// </summary>
public ReadOnlyCollection<ChannelPromotionsSummarizedData> SummarizedPromotions {
get; private set; }
/// <summary>
/// Gets non-summarized channel promotions.
/// </summary>
public ReadOnlyCollection<PromotionDetails> Promotions { get; private set; }
}
}
To create a request handler, do the following:
Create a class that inherits from the base commerce runtime
WorkflowRequestHandler<TRequest, TResponse> class. The following example
shows the GetPromotionsResponse class from the Promotions workflow.
namespace Extensions.Promotions.Workflow
{
using System;
using System.Collections.Generic;
using System.Linq;
using Extensions.Promotions.Data;
using Extensions.Promotions.Service;
using Microsoft.Dynamics.Commerce.Runtime.DataModel;
using Microsoft.Dynamics.Commerce.Runtime.Workflow;
using Microsoft.Dynamics.Commerce.Runtime.Workflow.Composition;
/// <summary>
/// Helper Class to call neccessary Services and perform Data Manipulation on it.
/// </summary>
[RequestHandlerMetadata(HandledRequestType = typeof(GetPromotionsRequest))]
internal class PromotionsWorkflowRequestHandlerRaw :
WorkflowRequestHandler<GetPromotionsRequest, GetPromotionsResponse>
{
/// <summary>
/// Executes the workflow to get the promotions.
/// </summary>
/// <param name="request">The request.</param>
/// <returns>The response.</returns>
protected override GetPromotionsResponse Process(GetPromotionsRequest request)
{
if (request == null)
{
throw new ArgumentNullException("request");
}
var serviceRequest = new GetPromotionsServiceRequest(this.Context);
IPromotions promotionsService = this.Context.Runtime.GetService<IPromotions>();
List<PromotionDetails> response = new List<PromotionDetails>();
Module 6: Commerce Runtime Services
6 - 27
List<ChannelPromotionsSummarizedData> summarizedResponse = new
List<ChannelPromotionsSummarizedData>();
serviceRequest.ChannelId = request.ChannelId;
serviceRequest.CatalogId = request.CatalogId;
foreach (PeriodicDiscountOfferType discount in
Enum.GetValues(typeof(PeriodicDiscountOfferType)))
{
serviceRequest.PromotionType = discount;
var serviceReply =
promotionsService.Execute<GetPromotionsServiceResponse>(serviceRequest).Promotions;
if (request.HasPromotionData)
{
summarizedResponse.AddRange(ConvertToSummarizedData(serviceReply,
discount));
}
else
{
response.AddRange(serviceReply);
}
}
if (request.HasPromotionData)
{
var summarizedResult = from s in summarizedResponse
orderby s.DiscountName
select s;
return new GetPromotionsResponse(summarizedResult);
}
else
{
var result = from s in response
orderby s.DiscountName
select s;
return new GetPromotionsResponse(result);
}
}
/// <summary>
/// Iterates through a list of promotions for:
/// 1. Generating a list of discount codes associated with an Item. This
generates duplicate records where the only difference is the discount codes.
/// 2. Removing above duplicates.
/// 3. Summarize the Promotion data into English Text for every unique record
being considered.
/// </summary>
/// <param name="promotionDetailsCollection">List containing promotion
details.</param>
/// <param name="typeOfDiscount">Discount Type associated with the list (eg.
MultiBuy/ MixNMatch, etc).</param>
/// <returns>A collection of summarized promotions.</returns>
private static List<ChannelPromotionsSummarizedData>
ConvertToSummarizedData(IEnumerable<PromotionDetails> promotionDetailsCollection,
PeriodicDiscountOfferType typeOfDiscount)
{
var returnObject = new List<ChannelPromotionsSummarizedData>();
var allDiscountOfferNames = promotionDetailsCollection
.Select(i => new { i.DiscountName })
.Distinct();
foreach (var currentOffer in allDiscountOfferNames)
{
var discountLineItems = from s in promotionDetailsCollection where
s.DiscountName == currentOffer.DiscountName orderby s.ItemId select s;
var lineItemsAfterPass1 = Pass1ConsolidateDiscountCodes(discountLineItems);
var lineItemsAfterPass2 =
Pass2GenerateSummarizedPromotionStatement(lineItemsAfterPass1, typeOfDiscount);
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
6 - 28
var lineItemsAfterPass3 =
Pass3GenerateConsolidatedPromotionStatement(lineItemsAfterPass2, typeOfDiscount);
returnObject.AddRange(lineItemsAfterPass3);
}
return returnObject;
}
/// <summary>
/// Consolidate all the discount codes available for a discount and then remove
redundant line items.
/// </summary>
/// <param name="offerCollection">Contains set of all Line Items for a particular
discount Offer.</param>
/// <returns>A collection of promotion details..</returns>
private static List<PromotionDetails>
Pass1ConsolidateDiscountCodes(IEnumerable<PromotionDetails> offerCollection)
{
var returnObject = new List<PromotionDetails>();
var element = new PromotionDetails();
var iterator = offerCollection.ToList();
for (int counter = 0; counter < offerCollection.Count(); counter++)
{
element = iterator.ElementAt(counter);
if (element.IsDiscountCodeRequired)
{
int index = 1;
while (counter + index < offerCollection.Count() &&
iterator.ElementAt(counter + index).ItemId == element.ItemId && iterator.ElementAt(counter +
index).IsDiscountCodeRequired == element.IsDiscountCodeRequired)
{
element.DiscountCode += ", " + iterator.ElementAt(counter +
index).DiscountCode;
index++;
}
counter += index;
}
returnObject.Add(element);
}
return returnObject;
}
/// <summary>
/// Generates a Summarized Promotion Statement for every line item, But it is still
not usable by the End-User.
/// </summary>
/// <param name="offerCollection">Contains set of all Line Items for a particular
discount Offer.</param>
/// <param name="typeOfDiscount">Is it MultiBuy/ Mix-n-Match/ Discount/ Price
Adjustment.</param>
/// <returns>A collection of summarized promotions.</returns>
private static List<ChannelPromotionsSummarizedData>
Pass2GenerateSummarizedPromotionStatement(IEnumerable<PromotionDetails> offerCollection,
PeriodicDiscountOfferType typeOfDiscount)
{
var returnObject = new List<ChannelPromotionsSummarizedData>();
ChannelPromotionsSummarizedData element;
foreach (var lineItem in offerCollection)
{
element = new ChannelPromotionsSummarizedData();
element.OfferId = lineItem.OfferId;
element.DiscountName = lineItem.DiscountName;
element.DiscountDescription = lineItem.DiscountDescription;
element.Disclaimer = lineItem.Disclaimer;
element.ProductName = lineItem.ProductName;
Module 6: Commerce Runtime Services
6 - 29
element.ProductOfferDescription = lineItem.ProductOfferDescription;
element.ProductImageLink = lineItem.ProductImageLink;
element.IsDiscountCodeRequired = lineItem.IsDiscountCodeRequired;
element.DiscountCodes = lineItem.DiscountCode;
switch (lineItem.DiscountMethod)
{
case 0: // Percentage Discount
if (lineItem.DiscountPercent == 0)
{
element.ProductPromotionStatement = String.Empty;
}
else if (lineItem.DiscountPercent == 100)
{
element.ProductPromotionStatement = "Get " + element.ProductName
+ " for free";
}
else
{
element.ProductPromotionStatement = (typeOfDiscount ==
PeriodicDiscountOfferType.MultipleBuy) ? "Buy atleast " +
Decimal.ToInt32(lineItem.MinimumQuantity) + " and " : String.Empty;
element.ProductPromotionStatement += "Get " +
decimal.ToInt32(lineItem.DiscountPercent) + "% Off on all " + lineItem.ProductName + "(s)";
}
break;
case 1: // Discount Amount
element.ProductPromotionStatement = "Get each " +
lineItem.ProductName + " for $" + decimal.Round(lineItem.DiscountAmount, 2,
MidpointRounding.AwayFromZero) + " less";
break;
case 2: // Offer Price
element.ProductPromotionStatement = (typeOfDiscount ==
PeriodicDiscountOfferType.MultipleBuy) ? "Buy atleast " + lineItem.MinimumQuantity + " " :
"Buy ";
element.ProductPromotionStatement = lineItem.ProductName + "(s) for
$" + decimal.Round(lineItem.OfferPrice, 2, MidpointRounding.AwayFromZero) + "each";
break;
case 3: // Offer Price Inclusive Of Tax
bool isDealPrice = ((from s in offerCollection where s.DiscountMethod
!= 3 select s).Count() == 0) ? true : false;
element.ProductPromotionStatement = "Get " + (isDealPrice ?
lineItem.DiscountName : lineItem.ProductName) +
" for $" + decimal.Round(lineItem.OfferPriceInclusiveOfTax, 2,
MidpointRounding.AwayFromZero) + "(Inclusive of Taxes)";
break;
}
returnObject.Add(element);
}
return returnObject;
}
/// <summary>
/// Consolidates and converts the Summarized Promotion Statement to an End-User
understandable format.
/// </summary>
/// <param name="offerCollection">Contains set of all Line Items for a particular
discount Offer.</param>
/// <param name="typeOfDiscount">Is it MultiBuy/ Mix-n-Match/ Discount/ Price
Adjustment.</param>
/// <returns>A collection of summarized promotions.</returns>
private static List<ChannelPromotionsSummarizedData>
Pass3GenerateConsolidatedPromotionStatement(IEnumerable<ChannelPromotionsSummarizedData>
offerCollection, PeriodicDiscountOfferType typeOfDiscount)
{
var returnObject = new List<ChannelPromotionsSummarizedData>();
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
6 - 30
var iterator = offerCollection.ToList();
string appendText = " when you buy a ";
string productStatement = String.Empty;
bool appendFlag = false;
for (int counter = 0; counter < offerCollection.Count(); counter++)
{
if
(string.IsNullOrEmpty(iterator.ElementAt(counter).ProductPromotionStatement))
{
appendFlag = true;
appendText += ((string.Compare(appendText, " when you buy a ",
StringComparison.OrdinalIgnoreCase) == 0) ? String.Empty : " and ") +
iterator.ElementAt(counter).ProductName;
}
productStatement =
(string.IsNullOrEmpty(iterator.ElementAt(counter).ProductPromotionStatement)) ?
productStatement : iterator.ElementAt(counter).ProductPromotionStatement;
}
foreach (var lineItem in offerCollection)
{
lineItem.ProductPromotionStatement = appendFlag ? productStatement +
appendText : lineItem.ProductPromotionStatement;
returnObject.Add(lineItem);
}
return returnObject;
}
}
}
You cannot customize a workflow that is included with the CRT. However, you can
replace it with your own custom workflow or you can add more workflows. The
CRT configuration file determines the workflow to load. If you add a new
workflow with the same name as a default workflow above the default workflow,
the new workflow replaces the default workflow.
To change the CRT configuration file, do the following:
1. Open commerceRuntime.config in your solution.
Note: The location of this file varies based on your deployment. If you are
customizing the SharePoint starter store, you can locate the file by using the
Internet Information Services (IIS) Manager. In IIS Manager, find the starter store
under the Sites node. Right-click the public starter store, and then click Explore.
2. Add a line for your new workflow to the list of assemblies, fSee the
following example.
<add source="assembly" value="ContosoWorkflow, Version=1.0.0.0,
Culture=neutral, PublicKeyToken=6598494e9dab8361,
processorArchitecture
Module 6: Commerce Runtime Services
6 - 31
Module Review
Test Your Knowledge
Test your knowledge with the following questions.
1. What are the basic steps to create a new Service and add it to the Commerce
Runtime?
2. Which CRT service should be customized to send email to customers based on
email templates that are defined in Microsoft Dynamics AX?
( ) PaymentService
( ) LoyaltyService
( ) AddressService
( ) EmailService
( ) SalesOrderService
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
6 - 32
Test Your Knowledge Solutions
Module Review and Takeaways
1. What are the basic steps to create a new Service and add it to the Commerce
Runtime?
MODEL ANSWER:
To create a new service, you must create three different objects: Request
object, Response object and Service object. After you create the service, you
must change the Commerce Runtime configuration file.
2. Which CRT service should be customized to send email to customers based on
email templates that are defined in Microsoft Dynamics AX?
( ) PaymentService
( ) LoyaltyService
( ) AddressService
(√) EmailService
( ) SalesOrderService
7 - 1
MODULE 7: TESTING, DEPLOYMENT AND
VERSIONING OF ECOMMERCE SITES
Module Overview
Microsoft Dynamics AX 2012 R3 includes an online starter store (Ecommerce) that
is built on Microsoft SharePoint Server 2012. You can create your own online store
by using some elements of the starter store, customizing some elements, and
adding your own elements.
This module helps you understand different ways to test the customization and
how you can deploy the customization across multiple environments, such as
development, test, production, and so on.
Objectives
The objectives are as follows:
Explain testing considerations.
Describe how to deploy custom code across environments.
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
7 - 2
Testing Considerations
This topic explains the different stages for testing a custom SharePoint application
Testing Overview
One of the primary design goals for any application is the ability to test the
application. The following diagram from the Acceptance Test Engineering
Guidance document displays the testing layers.
FIGURE 7.1: TESTING LAYERS
Each type of test has a distinct purpose. They are as follows:
Unit testing: Unit tests are written by developers and run under a unit testing
framework, such as Microsoft Visual Studio Team System or NUnit. Unit tests
isolate and verify discrete units of program logic. They isolate the logic by
replacing dependencies on the run-time environment, such as SharePoint, with
test-provided substitutes. Isolation enables unit tests to run quickly. Developers
can run unit tests frequently.
Integration testing: Integration tests differ from unit tests in that the code under
test is not isolated. Integration tests are written by developers or testers. They run
in a unit testing framework.
Acceptance testing: Acceptance tests consist of multiple steps that represent
realistic usage scenarios of the application as a whole. These tests verify that an
Module 7: Testing, Deployment and Versioning of Ecommerce Sites
7 - 3
application meets the needs of the intended users. Acceptance test scopes include
usability, functional correctness, and performance. In general, test engineers
create these tests.
Unit Testing with Mock Objects and Automating Unit
Testing for User Interface (UI) Testing
If the application references external components and those components are not
available for testing, you can perform unit testing by creating mock objects for the
external components. “Mock objects “are instances of test-provided classes that
simulate the behavior of external components. Mock objects isolate the
application code for testing. They create conditions that are otherwise difficult to
produce, such as a disk full exception.
Mock objects can be implemented in the following three ways for unit testing:
Mock views: You can use the Model-View-Presenter (MVP) pattern
to test the application that contains presenter classes that encapsulate
business logic. “Presenter classes” update the properties of view
interfaces that are provided by the top layer of the application. Unit
tests exercise the functionality of a presenter class in isolation by
providing a mock view implementation when you run the unit test.
Mock services: You can use the Service Locator pattern to test the
application-exposed services. Unit tests take advantage of this
architecture when testing the presenter layer by substituting test-
specific stub implementations that provide the inputs and outputs
that are required for the specific test scenario.
Tool-generated mock objects for system services: Mock views and
mock services are insufficient for testing the lowest layers of the
application. For example, components that are provided by
SharePoint are sealed classes that have internal constructors that do
not provide interfaces that allow for substitution. In this situation, you
must impersonate SharePoint classes in a special execution
environment.
Note: There are different tools that are available to support unit testing with
mock objects, such as a commercially available testing tool named Typemock
Isolator that is provided by Typemock. You must install this tool if you want to run
the unit tests.
Automate UI Test Methods for SharePoint
You can use Microsoft Visual Studio Team System Web test framework to
automate the SharePoint UI components. There are scenarios in the SharePoint
application where a developer wants to test the UI components before integration
testing. The developer can use the Web test framework to record the execution
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
7 - 4
steps. As soon as the steps are recorded, the recorded steps can run on any other
environment for testing the application.
The following are the basic steps for automating the UI test methods:
1. Create the scenario before you try to automate the test. The scenario
outlines the sequence of steps to complete the operation that you are
testing.
2. Record the Web test by following the steps in the scenario, and then
save the Web test.
3. Clean your test environment, and then run the coded test. If your test
passes, you can skip step 4.
4. Create an extraction rule to extract the globally unique identifiers
(GUIDs), and then replace the hard-coded GUIDs with the rule. If a
GUID must be extracted, you receive the exception "There is no
context parameter with the name …" when you run the recorded test.
There may be more than one GUID that must be extracted in a test.
5. Generate a coded test for the saved test.
6. Clean your test environment and run the coded test.
Integration Testing
Integration testing resembles unit testing in that tests start methods of application
classes in a unit testing framework. However, integration tests do not use mock
objects to substitute implementations for service dependencies. Instead,
integration tests rely on the application's services and components. The goal of
integration tests is to exercise the functionality of the application in its usual run-
time environment.
You usually perform integration testing in a separate environment called
Integration Environment. Developers working on their individual modules perform
unit testing in their development environment. As soon as the testing is successful,
they move the code to the Integration Environment. This is where integration
testing of different modules that may have been implemented by multiple
developers is performed to test the application.
Acceptance Testing (User Interface Testing)
A common form of acceptance testing consists of tests that exercise a user
scenario from the UI. These tests emulate the application keyboard and UI
interactions. A UI test for a browser-based application is known as a “Web test.”
Microsoft Visual Studio Team System includes automation for navigation that
enables you to create UI tests. There are different forms of testing that you can
perform as part of acceptance testing.
Module 7: Testing, Deployment and Versioning of Ecommerce Sites
7 - 5
Following are the different types of acceptance testing that can be performed:
Build verification testing: This is a regular check of application
functionality from the perspective of a user scenario of the
application under development.
Stress testing: This is a test of the application to handle a very high
volume of user scenarios that are executed at the same time. Stress
testing drives the system beyond expected maximum load in
production to see how it behaves.
Scale testing: This is a test of the application to determine whether
the application can handle the required number of users under
typical load conditions on the production hardware configuration.
SharePoint Deployment Architecture Guidance
This topic explains the deployment architecture for SharePoint 2013 and the many
ways that you can scale the SharePoint Farm for performance.
You can design Microsoft® SharePoint® 2013 topologies to optimize system
resources and to maximize performance for users.
Optimizing each tier
Front-end servers: Service applications, services, and components
that serve user requests directly are placed on front-end servers.
These servers are optimized for fast performance.
Batch-processing servers: Service applications, services, and
components that process background tasks are placed on a middle-
tier of servers that are referred to as “batch processing servers.” These
servers are optimized to maximize system resources. These servers
can tolerate larger loads because these tasks do not affect
performance as observed by users.
Database-servers: Guidance for deploying database servers remains
the same.
In a small farm, you can combine server roles on one or two servers. For example,
you can combine front-end services and batch-processing services on a single
server or on two or more servers to achieve redundancy.
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
7 - 6
FIGURE 7.2: SCALE GUIDANCE FOR EACH SERVER ROLE
FIGURE 7.3: SCALING TOPOLOGY TO SUPPORT LARGE FARM
Deployment
This topic describes different ways that a user can deploy a customization, such as
the following:
1. Map a network drive to the SharePoint 2013 Master Page Gallery to
add and edit Master Pages and Page Layouts.
2. Use a SharePoint solution package for customization deployment.
3. Deploy a Microsoft Dynamics AX Retail online store customization on
a single server.
Map a Network Drive to the SharePoint 2013 Master Page
Gallery to Add and Edit Master Pages and Page Layouts
This topic explains how to map a network drive to the Master Page Gallery so that
you can use Design Manager to upload design files in SharePoint Server 2013.
Design files can be a master page or a page layout.
Module 7: Testing, Deployment and Versioning of Ecommerce Sites
7 - 7
Note: For more information about mapping the SharePoint folder in a
development environment, refer to “Map a Network Drive to the SharePoint 2013
Files for Online Stores” in Module 2 “Development Environment Requirements.”
You can create a visual design for your website by using any web design tool or
HTML editor, and then use Design Manager to import the design into SharePoint.
To do this, you must make sure that the design tool stores its files in your site's
Master Page Gallery. This is where SharePoint expects to find the files. We
recommend that you map a network drive to the Master Page Gallery to make it
easier to save files in the correct location. To do this, you must first find the
location of the Master Page Gallery.
To find the location of the Master Page Gallery, do the following:
1. On the site for which you are creating a design, start Design Manager.
For example, on the Settings menu, select Design Manager.
Note: If your site is hosted in SharePoint Online, sign in to the site by using
your Office 365 credentials. Make sure that you select the Keep me signed in
check box.
2. In the numbered list, select Upload Design Files.
3. The Design Manager: Upload Design Files page contains the
location of the Master Page Gallery. The location typically ends in
/_catalogs/masterpage/. This is where you map a network drive.
4. Note the location of the Master Page Gallery, or copy it to the
Clipboard.
Additional Reading: How to map a network drive is explained in detail in
section “Map a Network Drive to the SharePoint 2013 Files for Online Stores” in
Module 2 “Development Environment Requirements.”
Use SharePoint Solution Package for Customization
Deployment
This article describes solution packages and the role that they play in deploying
authored and developed customizations in Microsoft SharePoint Server 2013. This
article explains the following topics:
Solution packages
Deploying site elements by using solution packages
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
7 - 8
Solution Packages
A “solution package” is a distribution package that delivers your custom
SharePoint Server 2013 development work to the Web servers or the application
servers in the server farm. Use solutions to package and deploy custom features,
site definitions, templates, layout pages, master pages, Web Parts, cascading style
sheets, and assemblies.
A “solution package” is a Cabinet (CAB) file that has a .wsp file name extension
and a manifest file. We recommend that you use Visual Studio 2012 Tools for
SharePoint 2013 to develop and package SharePoint solutions. You can also
create solution packages manually by using a tool such as Makecab.exe.
Components that can be packaged in a solution include the following:
.NET Framework assemblies, such as Web Part assemblies and event
receiver assemblies.
Deployment files, such as resource files, pages, master pages, or other
helper files.
Features that enable you to start and deactivate code in a website
and provide functionality that includes elements, such as custom lists,
libraries, fields, and content types.
New templates and site definitions.
Configurations that must be performed at the Web-server level, such
as deploying customizations to the Web.config files for the
registration of Web Parts. You can also change these configurations
with a Feature that is distributed with a Feature.
Web content, such as Web pages and images that are called by Web
pages. If you must deploy Web content in a disconnected
environment, you should use a content deployment package.
Deploy Site Elements by Using Solution Packages
This topic includes the following:
When to use solution packages
Deployment of farm solutions
When to use solution packages
A best practice to deploy customizations is to use solution packages as part of a
straightforward, safe, and consistent application lifecycle management process.
Solution packages make it simpler to change the features and functionality of the
websites after the sites are created.
Module 7: Testing, Deployment and Versioning of Ecommerce Sites
7 - 9
You can use solution packages to deploy new solutions and upgrade existing
solutions across the farm. You can package all SharePoint Server entities as one
file, add the file to the solution store, and deploy it to the front-end Web servers
in the farm. Use solution packages to synchronize a front-end Web server so that
its state is consistent with the state of other Web servers in the farm.
You can use solution packages to deploy authored site element customizations
from an integration farm to an authoring, pilot, or production farm. In SharePoint
Server, users can save a customized site as a template. This creates a solution
package with a .wsp file name extension that can be deployed on another farm.
You can use solution packages to deploy customizations between the following
environments:
From developer workstations to an integration farm or a software
configuration management system
From an integration farm and authoring client workstations to pilot or
production farms
Deployment of Farm Solutions
Farm solutions are deployed either locally or by using a timer service. You can
trigger both local and timer-based deployments either by using command-line
instructions or programmatically by using the object model.
Local deployment
In a local deployment, solution files are deployed only to the computer from
which the deployment operation was initiated. The solution is not marked as
"deployed" in the configuration database until the solution files are deployed to
all applicable servers in the server farm. Then solution features are installed, and
schema and definition files are committed to the configuration store.
Timer Service deployments
In deployments that use the timer service, the deployment creates a timer job.
This timer job is picked up by the timer service on each Web server in the server
farm. Manifest and feature manifests first are parsed to find assembly and _layouts
files. These files are copied to the appropriate locations. All other files that are
contained in a feature directory are copied to the feature directory.
After solution files are copied to the target computers, a configuration reset is
scheduled for all front-end Web servers. The reset then deploys the files and
restarts Internet Information Services (IIS). Solution features are then registered,
and schema and definition files are committed to the configuration store
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
7 - 10
Deploy a Microsoft Dynamics AX Retail Online Store
Customization on a Single Server
Storefront solution can customize the online store. Users can change the solution,
package it into a solution, and then deploy it by using a deployment script. This
topic describes how to build a package, change the deployment setting, and
deploy it.
To change the oob-topology.xml file, do the following:
1. Log on to the server that hosts Microsoft Dynamics AX retail online
store.
2. Locate the directory where the oob-topology and oob-settings files
are stored. By default, they are stored at this location: C:\Program
Files (x86)\Microsoft Dynamics AX\60\Retail Online Channel\tools.
3. Open the oob-topology.xml file in Notepad and make sure that the
highlighted settings are correct.
Note: For more information about how to deploy the online store on a single
server, refer to the MSDN article that is located at http://technet.microsoft.com/EN-
US/library/jj991927.aspx.
The ”Web Application Setting” image displays how to change the specific settings
in the .xml file to control deployment options.
FIGURE 7.4: WEB APPLICATION SETTING
Module 7: Testing, Deployment and Versioning of Ecommerce Sites
7 - 11
Settings for the Storefront Solution where you can specify the WSP location
FIGURE 7.5: STOREFRONT SOLUTION SETTING
Deploy-FarmSolutions.ps1
When you run this script, it usually performs the following actions on the server:
Deploys the new SharePoint solution package.
Starts features.
Executes post-deployment custom scripts (deploy mode).
These steps depend on the values that were set in the oob-topology.xml file.
When you re-execute, the scripts change the steps.
Execute Deploy-FarmSolutions.ps1
Follow these steps to execute this script.
1. On the server where you want to execute the script, open a command
prompt as an administrator.
2. Locate the directory where the oob-topology and oob-settings files
are stored. By default, they are stored at the following location:
C:\Program Files (x86)\Microsoft Dynamics AX\60\Retail Online
Channel\tools
3. Execute the following command:
powershell .\Deploy-FarmSolutions.ps1 oob-topology.xml oob-
settings.xml
When the system finishes the operation, you can verify the deployment.
Verify Deployment
If all deployment scripts are completed without errors, use this section to help
verify the online store deployment.
Note: For more information about how to configure the development
environment and to deploy the online store, refer to the MSDN article that is
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
7 - 12
located at http://technet.microsoft.com/EN-US/library/jj991927.aspx .
Verify that the Connector Service is running
After a successful deployment, the Dynamics AX Publishing Connector Service is
running in SharePoint Central Administration. At this point, the service displays
the error “No channel configuration could be found in the database.” This means
that the channel has not been configured in Microsoft Dynamics AX yet. You must
configure the channel in Microsoft Dynamics AX.
To verify that the Dynamics AX Publishing Connector service is running, do the
following:
1. In SharePoint Central Administration under System Settings, click
Manage services on server.
2. Verify that the Dynamics AX Publishing Connector service is running.
3. In SharePoint Central Administration, click Monitoring, and then click
Job Status.
4. Verify that you see jobs (SharePoint Timers jobs for the following web
applications) listed for the C1 Application for Retail Store Front –
Internal and the Out of box Store front – Public.
Verify that site collections exist and can be browsed
After a successful deployment, you can view the Retail online store web
applications and site collections in SharePoint Central Administration. If you
specified different URLs for your web applications, you must adjust the URLS by
doing the following:
1. In SharePoint Central Administration, click Application
Management, and then click View all site collections.
2. On the C1 Application for Retail Store Front – Internal web
application, copy the following URL:
http://ServerName:40001/sites/RetailProductCatalog
3. Paste the URL into a browser. Verify that the Welcome to your
product catalog site is displayed.
4. In SharePoint Central Administration, click the Web application drop-
down list, and then click Change web application.
5. Click Out of box Store front – Public web application.
6. In the URL section, verify that you see the following URLs:
o http:// ax2012r2a:40002/sites/RetailPublishingPortal
o http:// ax2012r2a:40002
7. Copy and paste each URL into a browser. Verify that you see the
Contoso electronic superstore website and the Contoso electronic
Module 7: Testing, Deployment and Versioning of Ecommerce Sites
7 - 13
superstore sign-in site. If the sign-in site displays a certificate warning,
click Continue to this web site. This warning appears if you used a
self-signed certificate.
Verify that you can create and sign-in with a new forms-based user account
You should be able to register a new user account and log on from the public
URL. To complete the sign-up process, verify SQL Server connectivity, SSL port
settings, and SSL certificate bindings, do the following:
1. Paste the public URL into a browser, and then press Enter. See the
following example:
http://ax2012r2a:40002/sites/RetailPublishingPortal
2. Click Register a new account.
3. Enter an email address and a strong password in the required fields,
and then click Create account.
4. Browse to the public portal site again
(http://ax2012r2a:40002/sites/RetailPublishingPortal).
5. Click Sign In, and then enter the information for the account that you
just created. The system logs you onto the Contoso electronics site as
a registered user.
Verify that you can browse the public URL
If you registered a domain, you should be able to surf the web address for your
site. For example, you should be able to browse
http://www.<your_domain>.com/sites/RetailPublishingPortal. If you have not yet
registered the domain, then you must create a host file entry and disable proxy
settings in your browser (if applicable) before you try to surf the web address.
Versioning and Code Maintenance
This topic explains the following concepts:
How to connect to TFS by using Visual Studio IDE
How to add Storefront solution in TFS
How to check in and check out a Storefront solution
How to label Storefront Solution code
How to Connect to TFS
This topic covers how to connect to TFS by using Visual Studio 2012 IDE. To
connect to TFS by using Visual Studio 2012 IDE, follow these steps:
1. Open Visual Studio 2012 IDE.
2. Click Team menu -> Connect to team Foundation Server….
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
7 - 14
3. A message is displayed. Click Servers. This displays a window.
4. Click Servers. A new window opens.
5. Click Add on the window. This enables the user to enter the following
TFS details to access the TFS instance:
6. TFS URL
7. Port Number
8. Protocol: http/https
9. When you have finished entering TFS details, click OK. This adds the
TFS instance in Visual Studio. Note: If Visual Studio displays the user
credential popup, make sure that you enter the credential that has
access to TFS.
10. The new TFS instance displays in the Team Project Collections section
on the left window. Projects are shown in the Team Project section on
the right window. Select the Team Project and click Connect. Visual
Studio now is connected to TFS.
How to Add a Storefront Solution in TFS
To add a Storefront solution in TFS, do the following:
1. Connect to TFS as described in “How to Connect to TFS.”
2. Open the Source Control Explorer window by browsing to View ->
Other Windows -> Source Control Explorer.
3. Select the TFS Instance from the left navigation of the Source
Control Explorer window. On the right side of the window, create a
folder named Storefront, and then copy the Storefront solution to the
new folder.
4. As soon as the Storefront solution is added to the new TFS folder,
right-click the Storefront folder, and then click Check In Pending
Changes to check in the Storefront solution files in TFS.
How to Check In and Check Out a Storefront Solution
TFS enables users to check in and check out individual files, a Visual Studio
project, or an entire solution. This helps users modify the files, projects, and
solutions based on the requirement. TFS enforces checkout to the file before the
user edits the file. Check-in is required to save the modified content back to TFS.
To perform the check-in and check-out operations on a Storefront solution, do
the following:
1. Open Storefront solution Visual Studio. You can view the Storefront
solution by using Solution Explorer > View menu-> Solution
Explorer.
Module 7: Testing, Deployment and Versioning of Ecommerce Sites
7 - 15
2. Right-click the Solution Storefront node that is available under
Solution Explorer, and then click Check out for Edit. This enables the
user to edit all projects that are available under Storefront solution.
3. As soon as a user is finished changing the files under Storefront
solution, the user can check the document back in TFS by right-
clicking the Storefront solution node, and then clicking Check-in. All
changed files are saved in TFS.
How to Label a Storefront Solution
TFS labeling enables users to label the code during development. If a team is
working on multiple application releases and they want to retrieve code for the
past releases, they can retrieve the code by using the TFS label. TFS internally
labels the file that uses the file version. When the user changes the file and checks
it back in TFS, a new file version is created.
If a Contoso team is working on an application and they have three releases
planned as a customer deliverable, they can have three code labels to identify the
code that is developed for the three releases. If the Contoso team finds a major
bug during Release 3 and they want to troubleshoot the changes since Release 2,
they can refer to the label to download the application code for both releases,
compare the source code, and then troubleshoot the issue.
To apply a TFS label, do the following:
1. Browse to Source Control Explorer (View -> Other Windows ->
Source Control Explorer).
2. Right-click the Storefront folder, and then click Advance - > Apply
Label.
3. Enter a label name, comment, and then click Create.
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
7 - 16
Module Review
Types of Testing
1. Unit Testing: This is testing that is performed by software developers
during the development phase. You can do unit testing manually or
by using automation scripts. This testing may involve mock objects for
testing.
2. Integration Testing: This type of testing is performed as soon as
different modules are integrated. This testing is done with the actual
object; no mock objects are used.
3. Acceptance Testing: This type of testing is usually performed on
staging or production environments to test the application against
customer requirements.
Deployment
1. You can deploy AX retail store UI customization by mapping the
Master Page gallery by using Windows Explorer.
Test Your Knowledge
Test your knowledge with the following questions.
1. Is Unit testing of an application is performed by a test professional?
2. What are the different types of testing performed during the application
development life cycle?
( ) Unit Testing
( ) Integration Testing
( ) Acceptance Testing
( ) All of the Above
( ) None
Module 7: Testing, Deployment and Versioning of Ecommerce Sites
7 - 17
3. Stress testing is part of unit testing.
( )True
( )False
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
7 - 18
Test Your Knowledge Solutions
Module Review and Takeaways
1. Is Unit testing of an application is performed by a test professional?
MODEL ANSWER:
No
2. What are the different types of testing performed during the application
development life cycle?
( ) Unit Testing
( ) Integration Testing
( ) Acceptance Testing
(√) All of the Above
( ) None
3. Stress testing is part of unit testing.
( )True
(√)False
8 - 1
MODULE 8: ECOMMERCE LABS
Module Overview
This module provides Labs for development and customization of the online
storefront i.e. Ecommerce site.
Objectives
Gain experience on the development and customization of the online
storefront.
Provides insight into the steps necessary to create an online storefront.
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
8 - 2
Lab A: Customize the Functionality of an Online Store
Exercise Scenario
When a user adds an item to a shopping cart, a user is presented with the
message “Adding item to cart”. This lab provides steps to change the message
that is displayed when an item is added to the shopping cart.
High Level Steps
1. Observe the message displayed when an item is added to the shopping
cart.
2. Access the JavaScript file.
3. Change the Storefont.js file.
4. Open the Home page.
5. Add Items to shopping card and view the display message.
Detailed Steps
1. Observe the message displayed when an item is added to the shopping
cart.
a. Open Internet Explorer and navigate to the Welcome page for
the starter store. Use the below URL for the Welcome page:
http:// ax2012r2a:40003/sites/RetailPublishingPortal
b. On the Navigation bar, hover mouse over Camera and in the
drop-down click on Digital Cameras
c. On the Product listing page of Digital Cameras, click on the first
product link, i.e. A. Datum Compact Digital Camera M200
Direct URL is -
http://ax2012r2a:40003/sites/RetailPublishingPortal/cameras/dig
ital-cameras/5637144652/5637145240
d. On the product detail page of A. Datum Compact Digital
Camera M200 click on the blue colored button – Add to Cart.
e. Observe the message “Adding Items to the Cart” which gets
displayed while adding items in the cart.
2. Access the JavaScript file
a. Navigate to the folders on the computer where the online
starter store is deployed.
b. Typically, files that contain JavaScript for the starter store pages
are found in a path that resembles the following:
C:\Program Files\Common Files\Microsoft Shared\Web Server
Extensions\15\TEMPLATE\LAYOUTS\Storefront\js
Module 8: Ecommerce Labs
8 - 3
c. Open the file Storefront.js. You can use Visual Studio or any
editor that you prefer.
3. Change the Storefont.js file.
a. Find the line that contains msaxServices.OnAddToCart. The
following example shows how to modify the code after line 170.
JS Add to cart function:
msaxServices.OnAddToCart(function ()
{
// msaxPopupOverlay.show('Updating shopping cart...');
alert('Adding to cart...');
});
4. Open the Home page.
a. Refresh the site by browsing to URL
http:// ax2012r2a:40003/sites/RetailPublishingPortal
5. Add Items to shopping card and view the display message.
a. Open Internet Explorer and navigate to the Welcome page for
the starter store. Use the below URL for the Welcome page:
http:// ax2012r2a:40003/sites/RetailPublishingPortal
b. On the Navigation bar, hover mouse over Camera and in the
drop-down click on Digital Cameras
c. On the Product listing page of Digital Cameras, click on the first
product link, i.e. A. Datum Compact Digital Camera M200
Direct URL is -
http://ax2012r2a:40003/sites/RetailPublishingPortal/cameras/dig
ital-cameras/5637144652/5637145240
d. On the product detail page of A. Datum Compact Digital
Camera M200 click on the blue colored button – Add to Cart
e. Click on Add to Cart link available on bottom right.
f. Observe the message Adding to cart… in the message window.
Click Ok to continue.
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
8 - 4
Lab B: Configure the Refiner on the Search Results
Page of the Ecommerce Site
Exercise Scenario
Company: Contoso Electronics
Contoso has recently added a new product line of High end Digital Cameras for
sale on their ecommerce site. Most of these products are targeted for professional
photographers. Contoso would like to help their users to filter the camera on the
Camera category page by Max ISO property. This property is available on all the
cameras and is managed within Dynamics AX 2012. This property is also
configured in AX as searchable and refinable. You have to configure SharePoint
search to enable this refiner on the Search Results page.
Task: Add a new refiner for a product category
High Level Steps
1. Navigate to Term Store.
2. Add the refiner.
3. Select the Display template.
4. Navigate to the home page to view the refiner.
Detailed Steps
1. Navigate to Term Store.
a. Open a web browser and navigate to the Product Catalog site
collection. Typically, the URL for the Products Catalog site
resembles the following:
http://ax2012r2a:40001/sites/RetailProductCatalog
b. Click on Manage Item Hierarchy in Term Store on the
home page of the Product Catalog site
c. On the left hand Navigation tree, under Managed Metadata
Service, select the Navigation Hierarchy under the Site
Collection – GUID > Product hierarchy
d. On the Navigation hierarchy, Select Product Hierarchy >
Electronics > Camera.
2. Add the refiner.
a. On the Term Store page, select the Faceted Navigation tab.
b. In the Refiners section, Click Customize refiners.
Module 8: Ecommerce Labs
8 - 5
c. From the Select available refiner from the select box, select
RetMaxISO.
3. Select the Display template
a. In display template drop-down list, select Retail Multi value
Refinement item.
b. Keep the other values unchanged.
c. Click Ok.
d. Click Save on the Faceted Navigation tab page.
e. A new refiner called Max ISO for camera is added.
4. Navigate to the home page to view the refiner.
a. Go to the home page of the publishing site.
http://ax2012r2a:40003/sites/RetailPublishingPortal/
b. In the navigation, select camera.
c. Observe the MAX ISO refinement section added on the
left navigation and the available check boxes for ISO
refiners.
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
8 - 6
Lab C: Change a Site Logo using MasterPage
Exercise Scenario
Company: Contoso Electronics
Contoso has recently decided to change the company logo and they want to
update their site logo with the updated one.
Task 1: Map a Network Drive to the SharePoint 2013 Master Page
Gallery
Detailed Steps
To find a location of the Master Page Gallery:
1. Open a web browser and navigate to the Retail Publishing site collection.
Typically, the URL for the Products Catalog site resembles the following:
http://ax2012r2a:40003/sites/ RetailPublishingPortal/
2. Go to Site Settings. Site setting URL is
http://ax2012r2a:40003/sites/
RetailPublishingPortal/_layouts/settings.aspx
3. Click the Design Manager link available under the Look and Feel
section.
4. In the numbered list available in left side of the screen, select Upload
Design Files.
5. The Design Manager: Upload Design Files page contains the location of
the Master Page Gallery. The location is
\\ax2012r2a@40003/sites/RetailPublishingPortal/_catalogs/masterpage/ .
This is the location to which you will map a network drive.
6. Open Windows Explorer (Windows Key + E). Click on Computer tab and
click on Map Network Drive button
7. Enter the Master Page Gallery location copied in the clipboard in Folder
textbox. Location is specified in Step 5.
Once the network folder is mapped, a user can browse to the UI components
such as master pages and css files uploaded under Master Page Gallery.
Task 2: Change the Site Logo in Storefront.master page
Detailed Steps
1. Open Storefront.master page from mapped master page gallery network
folder in visual studio.
2. Browse to the node <div class="msax-Main"> which contains the
Module 8: Ecommerce Labs
8 - 7
current site logo. Current site logo is set to logo_Contoso_main.png.
3. Change the image to logo_Contoso_main_original.png
4. Save the Storefront.master file.
5. Refresh the site and you should be able to see the updated site logo.
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
8 - 8
Lab D: Online Store Design Elements
Exercise Scenario
You have the out of the box online store up and running. Seasonally you want to
alter the basic look and feel of the online store. This scenario will walk through the
various design elements that can be controlled in an online store.
Task 1: Controlling the Desktop and Mobile Master Page
High Level Steps
1. Browse to the Publishing Portal.
2. View the site settings.
3. Edit the master page.
Detailed Steps
1. Browse to the Publishing Portal
a. All page editing functionality should be done using windows
authentication – port 40003 (for Contoso) and 50003 (for
Fabrikam). Browse to
http://ax2012r2a:40003/sites/retailpublishingportal
b. Select sign in from the top. The top navigation should indicate
that “System account” is signed in.
2. View the site settings.
a. Select the gear control on the right side.
b. Right click, and select Site Settings.
Module 8: Ecommerce Labs
8 - 9
3. Edit the master page.
a. Review the various areas on this page and select “Master
page” under “Look and Feel”.
b. Review the master page templates available for the default
master page. You can add new templates to become available
here. This can be used for seasonal display.
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
8 - 10
c. Select the Mobile master page drop down to review the pages
available for mobile. This controls the mobile master page.
d. Go back to the Site settings page.
e. Select device channels. See the user agent strings defined here.
Using other strings such as “iphone” or “android” defines the
other channels. The mobile device channel is defined under
device channels.
Task 2: Controlling Navigation and Refinements
High Level Steps
1. Browse to the Publishing Portal and navigate to Term Store Management.
2. View the site navigation settings.
3. View Custom Properties set from Microsoft Dynamics AX.
Detailed Steps
1. Browse to the Publishing Portal and navigate to Term Store Management.
a. Go to the site settings page for Fabrikam below-
http://ax2012r2a:50003/sites/RetailPublishingPortal/_layouts/15/settin
gs.aspx
b. Select Term store management under Site Administration .This
controls the terms store navigation for this publishing site. All
publishing site changes related to this site are done here.
2. View the site navigation settings.
a. Expand site navigation under 50002 and expand to select “Fashion
Accessories”. On the right hand side look at the tab called “Term
driven pages”.
b. Note how the “category landing page” specifies the actual landing
Module 8: Ecommerce Labs
8 - 11
page.
3. View Custom Properties set from AX
a. Select the custom properties. See the Nav_image property – This
defines the image shown on the category hover.
b. Expand the Fashion accessories and select Handbags.
c. Select the custom property and view the image value and
columnIndex and insideColumnIndex. This controls the image and
location of the image in the category landing page.
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
8 - 12
These values are set and controlled from AX. You can review this by
looking at the category attributes in the “Fashion navigation
hierarchy”.
Task 3: Managing Rich Content
Detailed Steps
1. View Image Hive.
a. Images are managed in the hive and can be located below.
b. Scan the images. The relative path is setup as references in the AX
product data.
Module 8: Ecommerce Labs
8 - 13
Lab E: Customize Search Results
Exercise Scenario
Search is very important for an online store. You are a Business manager and want
to improve the chances of showing Contoso tablets for all other competitor
brands. So you are looking to editorially control search to returns tablets from the
Contoso electronics store. In addition include a banner of Contoso tablets for the
search result.
At the end of this exercise, you should have a good understanding of how search
forms the basis of the Dynamics E-Commerce solution. You will get a better
understanding of editorial and business rules controlling search.
Task 1: Set up a Tablet Alias Query Rule with a Promoted Result
High Level Steps
1. Create a new Query rule.
2. Add a promoted result.
3. Add a result Block.
Detailed Steps
1. Create a new Query rule.
a. Go to:
http://ax2012r2a:40003/sites/RetailPublishingPortal/_layouts/15/settin
gs.aspx
b. Under “Site collection administration” select “Search Query Rules”.
c. In the drop down menu, Select a Result Source, select “Default”.
d. Select New Query Rule.
e. Provide the name “Tablet alias”.
f. Under Query conditions – Query Matches Keyword Exactly, specify
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
8 - 14
“ipad; kindle”
2. Add a promoted result.
a. Select Add promoted result
b. Provide the title “Cameras on Sale!”
c. Specify the following URL -
http://ax2012r2a:40002/sites/RetailPublishingPortal/PublishingImages
/contoso/banners/search_promo_tablets.png?width=396&height=150
d. Select the check box “Render the URL as a banner instead of as a
hyperlink” and close the prompt.
e. Select Save.
3. Add a result Block.
a. Select “Add result block”.
b. Specify “tablet” in Configure Query.
c. Select “Ok”.
Task 2: Include a Content Search Web Part with the Right Settings
High Level Steps
1. Add a Content Search Web-Part.
2. Setup web-part properties.
Detailed Steps
1. Add Content Search Web-Part
a. Go to: http://ax2012r2a:40003/sites/retailpublishingportal
b. Enter ipad in the search box
c. Select “sign in”
d. Select the gear icon on the right top side.
e. Select edit page.
f. Now Add a content search web part to the “Search gallery page”.
2. Setup web-part properties
a. In the Web Part, click the Content Search Web Part Menu arrow, and
then click Edit Web Part.
b. In the Web Part tool pane, in the Properties section, expand the
Module 8: Ecommerce Labs
8 - 15
Settings section.
c. In the Settings section within the Result Table list, select
SpecialTermResults.
d. Also set the control template to “List” and item template to “Best bet
item”.
e. Select “Change Query and select “Default” as the result source.
f. Save the page.
Task 3: Setup Image Rendition
High Level Steps
1. Create a new image rendition.
2. Specify the banner size.
Detailed Steps
1. Create new image rendition
a. Go to:
http://ax2012r2a:40003/sites/RetailPublishingPortal/_layouts/15/settin
gs.aspx
b. Select Image Renditions under “Look and Feel”
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
8 - 16
2. Specify the banner size.
a. Select new – specify a banner name.
b. Enter width = 396 and height = 150.
c. Click Save.
Task 4: Test the Scenario
Detailed Steps
1. Wait a couple minutes for the query rule to be picked up.
2. Go to: http://ax2012r2a:40002/sites/retailpublishingportal
3. Search for “ipad”.
4. View the banner and results from tablet.
Module 8: Ecommerce Labs
8 - 17
Lab F: Extending a Commerce Entity
Exercise Scenario
As the web developer on the project, you are extending the customer account to
enable a check box that the customer can use to specify whether they want to
opt-in for an Email to get more marketing information. The change is made in
both the “Account read only form” and “Edit Profile” page to read and change
email options.
At the end of this exercise, you should understand the various classes and
architecture of the online store to make further customizations. The architecture is
based on a standard model-view-controller pattern.
Task 1: Service Changes
High Level Steps
1. Add a custom property.
2. Edit Customer Mapper.
3. Update the Customer.js file.
4. Edit the CustomerDisplay.js.
Detailed Steps
1. Add a custom property.
a. Open Storefront.sln which is located at
c:\users\<user>\documents\Retail SDK\Online Channel\Storefront
b. Define a property for the new field. Open file
SharePoint.Web.Services. Folder ViewModel.
c. Edit file customer.cs and add the following:
///HOL Code
/// <summary>
/// Gets or sets the boolean value indicating whether the customer
has opted for email offers
/// </summary>
[DataMember]
public bool EmailOptIn { get; set; }
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
8 - 18
2. Edit Customer Mapper.
a. Open file Services/ObjectModel/CustomerMapper.cs.
b. Copy these lines:
bool emailOptIn = false; /// HOL Code
var emailOptInExtensionProperty = customer.ExtensionProperties.Where
(c => c.Key == "EMAILOPTIN").FirstOrDefault();
if (emailOptInExtensionProperty != null)
{
int intEmailOptIn =
(int)emailOptInExtensionProperty.Value.GetPropertyValue(); // HOL Code
emailOptIn = intEmailOptIn == 0 ? false : true;
}
c. Copy this line in the following location.
EmailOptIn = emailOptIn // HOL Code
Module 8: Ecommerce Labs
8 - 19
d. Copy this line to the method UpdateDataModel
dataModelCustomer["EMAILOPTIN"] =
Convert.ToInt64(customer.EmailOptIn); ///HOL Code
3. Update Customer.js file
a. Update file Customer.js. Add the following lines in “updateCustomer”
function.
// HOL Code
if ($view.find('.msax-EmailOptInCheckBox').is(':checked')) {
customer.EmailOptIn = true;
}
else {
customer.EmailOptIn = false;
}
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
8 - 20
4. Edit CustomerDisplay.js
a. Search for file CustomerDisplay.js in the solution explorer. Add this
code in function “Initialize”
// HOL Code
if (customer.EmailOptIn) {
$view.find('.msax-EmailOptInCheckBox').prop('checked', true);
}
else {
$view.find('.msax-EmailOptInCheckBox').prop('checked', false);
}
$view.find('.msax-EmailOptInCheckBox').attr("disabled", true);
Task 2: Controller Changes
High Level Steps
1. Add checkbox control.
2. Edit GetCustomerTemplate method.
3. Edit CustomerDisplay class.
Detailed Steps
1. Add checkbox control
Module 8: Ecommerce Labs
8 - 21
a. Search for file Customer.cs under SharePoint.Web.Controls/Customer.
b. Copy this code to RetailWebControl
private HtmlInputCheckBox emailOptIn; // HOL code
2. Edit GetCustomerTemplate method
a. Copy this code in function private HtmlTemplate
GetCustomerTemplate()
///HOL code
this.emailOptIn = ControlFactory.CreateCheckBox("msax-
EmailOptInCheckBox");
this.emailOptIn.AddAttribute(AXDataBindAttributes.Value,
"EmailOptIn");
HtmlLabel emailOptInLabel =
ControlFactory.CreateLabel(ControlResources.CustomerEmailOptI
n, null, this.emailOptIn);
HtmlFieldPanel emailOptInContainer =
ControlFactory.CreateFieldPanel(emailOptInLabel,
this.emailOptIn, "msax-CustomerEmailOptIn");
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
8 - 22
b. Paste this code as shown in the previous figure.
contactInfo.Controls.Add(emailOptInContainer);
3. Edit CustomerDisplay class
a. Search for file CustomerDisplay.cs.
b. Add this to the header:
using System.Web.UI.HtmlControls; /// HOL Code
c. In the method private HtmlTemplate GetCustomerTemplate() Paste
this code.
/// HOL code
HtmlLabel displayEmailOptInLabel =
ControlFactory.CreateLabel(ControlResources.CustomerEmailOptI
n, "msax-CustomerDisplayEmailOptInLabel");
HtmlInputCheckBox displayEmailOptIn =
ControlFactory.CreateCheckBox("msax-
CustomerDisplayEmailOptIn");
/// HOL Code
displayFieldSet.Controls.Add(displayEmailOptInLabel);
displayFieldSet.Controls.Add(displayEmailOptIn);
Module 8: Ecommerce Labs
8 - 23
Task 3: View Changes
High Level Steps
1. Edit ControlResources class.
2. Add resource string.
Detailed Steps
1. Edit ControlResources class
a. Search for file ControlResources.Designer.cs. Insert the string below.
/// <summary> HOL code
/// Looks up a localized string similar to Email for special offers:.
/// </summary>
internal static string CustomerEmailOptIn {
get {
return ResourceManager.GetString("CustomerEmailOptIn",
resourceCulture);
}
}
Microsoft Dynamics for Retail in Ecommerce Stores: Development and
Customization
8 - 24
2. Add resource string
a. Search for file ControlResources.resx in the controls folders.
b. Insert the required label like below.
Task 4: Build and Test the Solution
High Level Steps
1. Build the solution in Visual Studio.
2. Test the solution.
Detailed Steps
1. Build the solution in Visual Studio.
GAC altered dlls Microsoft.Dynamics.Retail.SP.Web.Controls.dll and
Microsoft.Dynamics.Retail.SP.Web.Services.dll.
a. Copy C:/Users/admin/Documents/Retail SDK/Online
Channel/StoreFront/Controls/obj/Debug/Microsoft.Dynamics.Retail.S
P.Web.Controls.dll
To
C:\Windows\Microsoft.NET\assembly\GAC_MSIL\Microsoft.Dynamics.
Retail.SP.Web.Controls\v4.0_1.0.0.0__cd39a5825b5ea86b
b. Copy C:/Users/admin/Documents/Retail SDK/Online
Channel/StoreFront/Services/obj/Debug/Microsoft.Dynamics.Retail.SP
.Web.Services.dll
To
C:\Windows\Microsoft.NET\assembly\GAC_MSIL\Microsoft.Dynamics.
Retail.SP.Web.Services\v4.0_1.0.0.0__cd39a5825b5ea86b
Module 8: Ecommerce Labs
8 - 25
c. Copy customer.js and customerdisplay.js to:
http://ax2012r2a:40003/sites/retailpublishingportal/Style
Library/Scripts/ViewModel
d. Run iis reset.
2. Test the solution.
a. Open Contoso home page from favorites.
b. Sign in and register a new user.
c. Go to the account page. View the Email option flag.
d. Select Edit profile and update the Email option flag.
e. Verify the update in the table by running the following SQL query:
select * from ax.retailcustpreference in db retailcustpreference.
Course 80640:
MICROSOFT DYNAMICS AX 2012 R3 FOR RETAIL IN
E-COMMERCE STORES: DEVELOPMENT AND
CUSTOMIZATION
This courseware is provided “as-is”. Information and views expressed in this courseware, including URL and
other Internet Web site references, may change without notice.
Unless otherwise noted, the examples depicted herein are provided for illustration only and are fictitious. No
real association or connection is intended or should be inferred.
This courseware does not provide you with any legal rights to any intellectual property in any Microsoft
product. Complying with all applicable copyright laws is the responsibility of the user. Without limiting the
rights under copyright, no part of this courseware may be reproduced, stored in or introduced into a retrieval
system, or transmitted in any form or by any means or for any purpose, without the express written
permission of Microsoft Corporation.
Copyright © 2012 Microsoft Corporation. All rights reserved.
Microsoft®, Microsoft Dynamics®, Microsoft® PowerPoint®, Microsoft® SQL Server® data management
software and Microsoft Dynamics® NAV are trademarks of the Microsoft group of companies. All other
trademarks are property of their respective owners.
MICROSOFT LICENSE TERMS
MICROSOFT INSTRUCTOR-LED COURSEWARE
These license terms are an agreement between Microsoft Corporation (or based on where you live, one of its
affiliates) and you. Please read them. They apply to your use of the content accompanying this agreement which
includes the media on which you received it, if any. These license terms also apply to Trainer Content and any updates and supplements for the Licensed Content unless other terms accompany those items. If so, those terms
apply.
BY ACCESSING, DOWNLOADING OR USING THE LICENSED CONTENT, YOU ACCEPT THESE TERMS. IF YOU DO NOT ACCEPT THEM, DO NOT ACCESS, DOWNLOAD OR USE THE LICENSED CONTENT.
If you comply with these license terms, you have the rights below for each license you acquire.
1. DEFINITIONS.
a. “Authorized Learning Center” means a Microsoft IT Academy Program Member, Microsoft Learning
Competency Member, or such other entity as Microsoft may designate from time to time.
b. “Authorized Training Session” means the instructor-led training class using Microsoft Instructor-Led Courseware conducted by a Trainer at or through an Authorized Learning Center.
c. “Classroom Device” means one (1) dedicated, secure computer that an Authorized Learning Center owns
or controls that is located at an Authorized Learning Center’s training facilities that meets or exceeds the
hardware level specified for the particular Microsoft Instructor-Led Courseware.
d. “End User” means an individual who is (i) duly enrolled in and attending an Authorized Training Session or Private Training Session, (ii) an employee of a MPN Member, or (iii) a Microsoft full-time employee.
e. “Licensed Content” means the content accompanying this agreement which may include the Microsoft Instructor-Led Courseware or Trainer Content.
f. “Microsoft Certified Trainer” or “MCT” means an individual who is (i) engaged to teach a training session
to End Users on behalf of an Authorized Learning Center or MPN Member, and (ii) currently certified as a
Microsoft Certified Trainer under the Microsoft Certification Program.
g. “Microsoft Instructor-Led Courseware” means the Microsoft-branded instructor-led training course that educates IT professionals and developers on Microsoft technologies. A Microsoft Instructor-Led
Courseware title may be branded as MOC, Microsoft Dynamics or Microsoft Business Group courseware.
h. “Microsoft IT Academy Program Member” means an active member of the Microsoft IT Academy
Program.
i. “Microsoft Learning Competency Member” means an active member of the Microsoft Partner Network program in good standing that currently holds the Learning Competency status.
j. “MOC” means the “Official Microsoft Learning Product” instructor-led courseware known as Microsoft Official Course that educates IT professionals and developers on Microsoft technologies.
k. “MPN Member” means an active silver or gold-level Microsoft Partner Network program member in good
standing.
l. “Personal Device” means one (1) personal computer, device, workstation or other digital electronic device
that you personally own or control that meets or exceeds the hardware level specified for the particular Microsoft Instructor-Led Courseware.
m. “Private Training Session” means the instructor-led training classes provided by MPN Members for
corporate customers to teach a predefined learning objective using Microsoft Instructor-Led Courseware.
These classes are not advertised or promoted to the general public and class attendance is restricted to individuals employed by or contracted by the corporate customer.
n. “Trainer” means (i) an academically accredited educator engaged by a Microsoft IT Academy Program
Member to teach an Authorized Training Session, and/or (ii) a MCT.
o. “Trainer Content” means the trainer version of the Microsoft Instructor-Led Courseware and additional
supplemental content designated solely for Trainers’ use to teach a training session using the Microsoft Instructor-Led Courseware. Trainer Content may include Microsoft PowerPoint presentations, trainer
preparation guide, train the trainer materials, Microsoft One Note packs, classroom setup guide and Pre-release course feedback form. To clarify, Trainer Content does not include any software, virtual hard
disks or virtual machines.
2. USE RIGHTS. The Licensed Content is licensed not sold. The Licensed Content is licensed on a one copy
per user basis, such that you must acquire a license for each individual that accesses or uses the Licensed Content.
2.1 Below are five separate sets of use rights. Only one set of rights apply to you.
a. If you are a Microsoft IT Academy Program Member: i. Each license acquired on behalf of yourself may only be used to review one (1) copy of the Microsoft
Instructor-Led Courseware in the form provided to you. If the Microsoft Instructor-Led Courseware is in digital format, you may install one (1) copy on up to three (3) Personal Devices. You may not
install the Microsoft Instructor-Led Courseware on a device you do not own or control.
ii. For each license you acquire on behalf of an End User or Trainer, you may either: 1. distribute one (1) hard copy version of the Microsoft Instructor-Led Courseware to one (1) End
User who is enrolled in the Authorized Training Session, and only immediately prior to the commencement of the Authorized Training Session that is the subject matter of the Microsoft
Instructor-Led Courseware being provided, or
2. provide one (1) End User with the unique redemption code and instructions on how they can access one (1) digital version of the Microsoft Instructor-Led Courseware, or
3. provide one (1) Trainer with the unique redemption code and instructions on how they can access one (1) Trainer Content,
provided you comply with the following: iii. you will only provide access to the Licensed Content to those individuals who have acquired a valid
license to the Licensed Content,
iv. you will ensure each End User attending an Authorized Training Session has their own valid licensed copy of the Microsoft Instructor-Led Courseware that is the subject of the Authorized Training
Session, v. you will ensure that each End User provided with the hard-copy version of the Microsoft Instructor-
Led Courseware will be presented with a copy of this agreement and each End User will agree that
their use of the Microsoft Instructor-Led Courseware will be subject to the terms in this agreement prior to providing them with the Microsoft Instructor-Led Courseware. Each individual will be required
to denote their acceptance of this agreement in a manner that is enforceable under local law prior to their accessing the Microsoft Instructor-Led Courseware,
vi. you will ensure that each Trainer teaching an Authorized Training Session has their own valid licensed copy of the Trainer Content that is the subject of the Authorized Training Session,
vii. you will only use qualified Trainers who have in-depth knowledge of and experience with the
Microsoft technology that is the subject of the Microsoft Instructor-Led Courseware being taught for all your Authorized Training Sessions,
viii. you will only deliver a maximum of 15 hours of training per week for each Authorized Training Session that uses a MOC title, and
ix. you acknowledge that Trainers that are not MCTs will not have access to all of the trainer resources
for the Microsoft Instructor-Led Courseware.
b. If you are a Microsoft Learning Competency Member: i. Each license acquired on behalf of yourself may only be used to review one (1) copy of the Microsoft
Instructor-Led Courseware in the form provided to you. If the Microsoft Instructor-Led Courseware is in digital format, you may install one (1) copy on up to three (3) Personal Devices. You may not
install the Microsoft Instructor-Led Courseware on a device you do not own or control.
ii. For each license you acquire on behalf of an End User or Trainer, you may either: 1. distribute one (1) hard copy version of the Microsoft Instructor-Led Courseware to one (1) End
User attending the Authorized Training Session and only immediately prior to the commencement of the Authorized Training Session that is the subject matter of the Microsoft
Instructor-Led Courseware provided, or
2. provide one (1) End User attending the Authorized Training Session with the unique redemption code and instructions on how they can access one (1) digital version of the Microsoft Instructor-
Led Courseware, or 3. you will provide one (1) Trainer with the unique redemption code and instructions on how they
can access one (1) Trainer Content, provided you comply with the following:
iii. you will only provide access to the Licensed Content to those individuals who have acquired a valid
license to the Licensed Content, iv. you will ensure that each End User attending an Authorized Training Session has their own valid
licensed copy of the Microsoft Instructor-Led Courseware that is the subject of the Authorized Training Session,
v. you will ensure that each End User provided with a hard-copy version of the Microsoft Instructor-Led
Courseware will be presented with a copy of this agreement and each End User will agree that their use of the Microsoft Instructor-Led Courseware will be subject to the terms in this agreement prior to
providing them with the Microsoft Instructor-Led Courseware. Each individual will be required to denote their acceptance of this agreement in a manner that is enforceable under local law prior to
their accessing the Microsoft Instructor-Led Courseware,
vi. you will ensure that each Trainer teaching an Authorized Training Session has their own valid licensed copy of the Trainer Content that is the subject of the Authorized Training Session,
vii. you will only use qualified Trainers who hold the applicable Microsoft Certification credential that is the subject of the Microsoft Instructor-Led Courseware being taught for your Authorized Training
Sessions, viii. you will only use qualified MCTs who also hold the applicable Microsoft Certification credential that is
the subject of the MOC title being taught for all your Authorized Training Sessions using MOC,
ix. you will only provide access to the Microsoft Instructor-Led Courseware to End Users, and x. you will only provide access to the Trainer Content to Trainers.
c. If you are a MPN Member:
i. Each license acquired on behalf of yourself may only be used to review one (1) copy of the Microsoft Instructor-Led Courseware in the form provided to you. If the Microsoft Instructor-Led Courseware is
in digital format, you may install one (1) copy on up to three (3) Personal Devices. You may not install the Microsoft Instructor-Led Courseware on a device you do not own or control.
ii. For each license you acquire on behalf of an End User or Trainer, you may either:
1. distribute one (1) hard copy version of the Microsoft Instructor-Led Courseware to one (1) End User attending the Private Training Session, and only immediately prior to the commencement
of the Private Training Session that is the subject matter of the Microsoft Instructor-Led Courseware being provided, or
2. provide one (1) End User who is attending the Private Training Session with the unique redemption code and instructions on how they can access one (1) digital version of the
Microsoft Instructor-Led Courseware, or
3. you will provide one (1) Trainer who is teaching the Private Training Session with the unique redemption code and instructions on how they can access one (1) Trainer Content,
provided you comply with the following: iii. you will only provide access to the Licensed Content to those individuals who have acquired a valid
license to the Licensed Content,
iv. you will ensure that each End User attending an Private Training Session has their own valid licensed copy of the Microsoft Instructor-Led Courseware that is the subject of the Private Training Session,
v. you will ensure that each End User provided with a hard copy version of the Microsoft Instructor-Led Courseware will be presented with a copy of this agreement and each End User will agree that their
use of the Microsoft Instructor-Led Courseware will be subject to the terms in this agreement prior to providing them with the Microsoft Instructor-Led Courseware. Each individual will be required to
denote their acceptance of this agreement in a manner that is enforceable under local law prior to
their accessing the Microsoft Instructor-Led Courseware, vi. you will ensure that each Trainer teaching an Private Training Session has their own valid licensed
copy of the Trainer Content that is the subject of the Private Training Session, vii. you will only use qualified Trainers who hold the applicable Microsoft Certification credential that is
the subject of the Microsoft Instructor-Led Courseware being taught for all your Private Training
Sessions, viii. you will only use qualified MCTs who hold the applicable Microsoft Certification credential that is the
subject of the MOC title being taught for all your Private Training Sessions using MOC, ix. you will only provide access to the Microsoft Instructor-Led Courseware to End Users, and
x. you will only provide access to the Trainer Content to Trainers.
d. If you are an End User:
For each license you acquire, you may use the Microsoft Instructor-Led Courseware solely for your personal training use. If the Microsoft Instructor-Led Courseware is in digital format, you may access the
Microsoft Instructor-Led Courseware online using the unique redemption code provided to you by the training provider and install and use one (1) copy of the Microsoft Instructor-Led Courseware on up to
three (3) Personal Devices. You may also print one (1) copy of the Microsoft Instructor-Led Courseware.
You may not install the Microsoft Instructor-Led Courseware on a device you do not own or control.
e. If you are a Trainer. i. For each license you acquire, you may install and use one (1) copy of the Trainer Content in the
form provided to you on one (1) Personal Device solely to prepare and deliver an Authorized
Training Session or Private Training Session, and install one (1) additional copy on another Personal Device as a backup copy, which may be used only to reinstall the Trainer Content. You may not
install or use a copy of the Trainer Content on a device you do not own or control. You may also print one (1) copy of the Trainer Content solely to prepare for and deliver an Authorized Training
Session or Private Training Session.
ii. You may customize the written portions of the Trainer Content that are logically associated with instruction of a training session in accordance with the most recent version of the MCT agreement.
If you elect to exercise the foregoing rights, you agree to comply with the following: (i) customizations may only be used for teaching Authorized Training Sessions and Private Training
Sessions, and (ii) all customizations will comply with this agreement. For clarity, any use of
“customize” refers only to changing the order of slides and content, and/or not using all the slides or content, it does not mean changing or modifying any slide or content.
2.2 Separation of Components. The Licensed Content is licensed as a single unit and you may not
separate their components and install them on different devices.
2.3 Redistribution of Licensed Content. Except as expressly provided in the use rights above, you may
not distribute any Licensed Content or any portion thereof (including any permitted modifications) to any third parties without the express written permission of Microsoft.
2.4 Third Party Programs and Services. The Licensed Content may contain third party programs or
services. These license terms will apply to your use of those third party programs or services, unless other
terms accompany those programs and services.
2.5 Additional Terms. Some Licensed Content may contain components with additional terms, conditions, and licenses regarding its use. Any non-conflicting terms in those conditions and licenses also
apply to your use of that respective component and supplements the terms described in this agreement.
3. LICENSED CONTENT BASED ON PRE-RELEASE TECHNOLOGY. If the Licensed Content’s subject
matter is based on a pre-release version of Microsoft technology (“Pre-release”), then in addition to the other provisions in this agreement, these terms also apply:
a. Pre-Release Licensed Content. This Licensed Content subject matter is on the Pre-release version of
the Microsoft technology. The technology may not work the way a final version of the technology will
and we may change the technology for the final version. We also may not release a final version. Licensed Content based on the final version of the technology may not contain the same information as
the Licensed Content based on the Pre-release version. Microsoft is under no obligation to provide you with any further content, including any Licensed Content based on the final version of the technology.
b. Feedback. If you agree to give feedback about the Licensed Content to Microsoft, either directly or through its third party designee, you give to Microsoft without charge, the right to use, share and
commercialize your feedback in any way and for any purpose. You also give to third parties, without charge, any patent rights needed for their products, technologies and services to use or interface with
any specific parts of a Microsoft software, Microsoft product, or service that includes the feedback. You will not give feedback that is subject to a license that requires Microsoft to license its software,
technologies, or products to third parties because we include your feedback in them. These rights
survive this agreement.
c. Pre-release Term. If you are an Microsoft IT Academy Program Member, Microsoft Learning Competency Member, MPN Member or Trainer, you will cease using all copies of the Licensed Content on
the Pre-release technology upon (i) the date which Microsoft informs you is the end date for using the
Licensed Content on the Pre-release technology, or (ii) sixty (60) days after the commercial release of the technology that is the subject of the Licensed Content, whichever is earliest (“Pre-release term”).
Upon expiration or termination of the Pre-release term, you will irretrievably delete and destroy all copies of the Licensed Content in your possession or under your control.
4. SCOPE OF LICENSE. The Licensed Content is licensed, not sold. This agreement only gives you some
rights to use the Licensed Content. Microsoft reserves all other rights. Unless applicable law gives you more rights despite this limitation, you may use the Licensed Content only as expressly permitted in this
agreement. In doing so, you must comply with any technical limitations in the Licensed Content that only allows you to use it in certain ways. Except as expressly permitted in this agreement, you may not:
access or allow any individual to access the Licensed Content if they have not acquired a valid license
for the Licensed Content,
alter, remove or obscure any copyright or other protective notices (including watermarks), branding
or identifications contained in the Licensed Content, modify or create a derivative work of any Licensed Content,
publicly display, or make the Licensed Content available for others to access or use,
copy, print, install, sell, publish, transmit, lend, adapt, reuse, link to or post, make available or
distribute the Licensed Content to any third party,
work around any technical limitations in the Licensed Content, or
reverse engineer, decompile, remove or otherwise thwart any protections or disassemble the
Licensed Content except and only to the extent that applicable law expressly permits, despite this limitation.
5. RESERVATION OF RIGHTS AND OWNERSHIP. Microsoft reserves all rights not expressly granted to
you in this agreement. The Licensed Content is protected by copyright and other intellectual property laws
and treaties. Microsoft or its suppliers own the title, copyright, and other intellectual property rights in the Licensed Content.
6. EXPORT RESTRICTIONS. The Licensed Content is subject to United States export laws and regulations.
You must comply with all domestic and international export laws and regulations that apply to the Licensed Content. These laws include restrictions on destinations, end users and end use. For additional information,
see www.microsoft.com/exporting.
7. SUPPORT SERVICES. Because the Licensed Content is “as is”, we may not provide support services for it.
8. TERMINATION. Without prejudice to any other rights, Microsoft may terminate this agreement if you fail
to comply with the terms and conditions of this agreement. Upon termination of this agreement for any
reason, you will immediately stop all use of and delete and destroy all copies of the Licensed Content in your possession or under your control.
9. LINKS TO THIRD PARTY SITES. You may link to third party sites through the use of the Licensed
Content. The third party sites are not under the control of Microsoft, and Microsoft is not responsible for
the contents of any third party sites, any links contained in third party sites, or any changes or updates to third party sites. Microsoft is not responsible for webcasting or any other form of transmission received
from any third party sites. Microsoft is providing these links to third party sites to you only as a convenience, and the inclusion of any link does not imply an endorsement by Microsoft of the third party
site.
10. ENTIRE AGREEMENT. This agreement, and any additional terms for the Trainer Content, updates and
supplements are the entire agreement for the Licensed Content, updates and supplements.
11. APPLICABLE LAW. a. United States. If you acquired the Licensed Content in the United States, Washington state law governs
the interpretation of this agreement and applies to claims for breach of it, regardless of conflict of laws
principles. The laws of the state where you live govern all other claims, including claims under state consumer protection laws, unfair competition laws, and in tort.
b. Outside the United States. If you acquired the Licensed Content in any other country, the laws of that
country apply.
12. LEGAL EFFECT. This agreement describes certain legal rights. You may have other rights under the laws of your country. You may also have rights with respect to the party from whom you acquired the Licensed
Content. This agreement does not change your rights under the laws of your country if the laws of your
country do not permit it to do so.
13. DISCLAIMER OF WARRANTY. THE LICENSED CONTENT IS LICENSED "AS-IS" AND "AS AVAILABLE." YOU BEAR THE RISK OF USING IT. MICROSOFT AND ITS RESPECTIVE
AFFILIATES GIVES NO EXPRESS WARRANTIES, GUARANTEES, OR CONDITIONS. YOU MAY HAVE ADDITIONAL CONSUMER RIGHTS UNDER YOUR LOCAL LAWS WHICH THIS AGREEMENT
CANNOT CHANGE. TO THE EXTENT PERMITTED UNDER YOUR LOCAL LAWS, MICROSOFT AND
ITS RESPECTIVE AFFILIATES EXCLUDES ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
14. LIMITATION ON AND EXCLUSION OF REMEDIES AND DAMAGES. YOU CAN RECOVER FROM
MICROSOFT, ITS RESPECTIVE AFFILIATES AND ITS SUPPLIERS ONLY DIRECT DAMAGES UP
TO US$5.00. YOU CANNOT RECOVER ANY OTHER DAMAGES, INCLUDING CONSEQUENTIAL, LOST PROFITS, SPECIAL, INDIRECT OR INCIDENTAL DAMAGES.
This limitation applies to
o anything related to the Licensed Content, services, content (including code) on third party Internet sites or third-party programs; and
o claims for breach of contract, breach of warranty, guarantee or condition, strict liability, negligence,
or other tort to the extent permitted by applicable law.
It also applies even if Microsoft knew or should have known about the possibility of the damages. The above limitation or exclusion may not apply to you because your country may not allow the exclusion or
limitation of incidental, consequential or other damages.
Please note: As this Licensed Content is distributed in Quebec, Canada, some of the clauses in this
agreement are provided below in French.
Remarque : Ce le contenu sous licence étant distribué au Québec, Canada, certaines des clauses
dans ce contrat sont fournies ci-dessous en français.
EXONÉRATION DE GARANTIE. Le contenu sous licence visé par une licence est offert « tel quel ». Toute utilisation de ce contenu sous licence est à votre seule risque et péril. Microsoft n’accorde aucune autre garantie
expresse. Vous pouvez bénéficier de droits additionnels en vertu du droit local sur la protection dues consommateurs, que ce contrat ne peut modifier. La ou elles sont permises par le droit locale, les garanties
implicites de qualité marchande, d’adéquation à un usage particulier et d’absence de contrefaçon sont exclues.
LIMITATION DES DOMMAGES-INTÉRÊTS ET EXCLUSION DE RESPONSABILITÉ POUR LES
DOMMAGES. Vous pouvez obtenir de Microsoft et de ses fournisseurs une indemnisation en cas de dommages directs uniquement à hauteur de 5,00 $ US. Vous ne pouvez prétendre à aucune indemnisation pour les autres
dommages, y compris les dommages spéciaux, indirects ou accessoires et pertes de bénéfices.
Cette limitation concerne: tout ce qui est relié au le contenu sous licence, aux services ou au contenu (y compris le code)
figurant sur des sites Internet tiers ou dans des programmes tiers; et.
les réclamations au titre de violation de contrat ou de garantie, ou au titre de responsabilité
stricte, de négligence ou d’une autre faute dans la limite autorisée par la loi en vigueur.
Elle s’applique également, même si Microsoft connaissait ou devrait connaître l’éventualité d’un tel dommage. Si
votre pays n’autorise pas l’exclusion ou la limitation de responsabilité pour les dommages indirects, accessoires ou de quelque nature que ce soit, il se peut que la limitation ou l’exclusion ci-dessus ne s’appliquera pas à votre
égard.
EFFET JURIDIQUE. Le présent contrat décrit certains droits juridiques. Vous pourriez avoir d’autres droits
prévus par les lois de votre pays. Le présent contrat ne modifie pas les droits que vous confèrent les lois de votre pays si celles-ci ne le permettent pas.
Revised September 2012