Sales Effectiveness in Dynamics CRM with Azure IoT and Machine Learning - Part 1

Sales Effectiveness in Dynamics CRM with Azure IoT and Machine Learning

How can an organisation optimise its sales channels and product targeting by building a 365-degree view of its customers in Dynamics CRM? The answer, and topic of this article, is with the help of Azure IoT and Machine Learning services!


Sales Effectiveness

The use case described in this article is the identification of common patterns of actions by consumers, classification based on criteria like age, gender, location, etc., and promotion of best-fit products. To achieve this objective, wearable and mobile devices are used and connected to the Azure IoT Hub for collecting information about location, commuting patterns and weather condition. All this information is then scored and evaluated in Azure Machine Learning to predict the best matching products. Data about sales conversion and customer loyalty is also captured and analysed with Power BI.

CRM Integration Flow with Azure IoT and Machine Learning


The products on sales are active cosmetics. The objective is to optimise stock availability in street distributors according to predicted demand. This is done by creating a full profile of customer’s actions and classifying them according to different criteria, or features:

·         Age

·         Gender

·         Skin Type

·         Season

·         Weather Condition

This information, collected by the Azure IoT platform and stored in the CRM system, provides the analysis dataset for applying a “demand prediction” Machine Learning algorithm that determines:

·         Churn Rate, or measure of customer attrition, defined as the number of customers who discontinue a product during a specified time period, divided by the total number of customers over the same time period.

·         Appetency, a word with the same root as “appetite”, which indeed defines the appetite, or desire of a customer to buy a specific product.

·         Upselling, the likelihood to sell a similar product to others that have been bought in the past, in response to determined conditions.


Azure IoT Suite

Let’s start digging into the implementation details of the technology components of this solution, based on the Microsoft’s Azure stack. Microsoft’s offering for Internet-of-Thing solutions consists of several resources, of which the Azure IoT Suite represents the most comprehensive, as it aggregates multiple components into a single package ready for use. At time of writing, the Azure IoT Suite offers the possibility to create two types of solutions:

·         Predictive Maintenance: Anticipate maintenance needs and avoid unscheduled downtime by connecting and monitoring devices for predictive maintenance.

·         Remote Monitoring: Connect and monitor devices to analyse untapped data and improve business outcomes by automating processes.

This solution is based on the “Remote Monitoring” type for streaming data from connected devices in use by customers. A typical dashboard of the Azure IoT Suite contains elements of:

·         Visualisation of devices over a geography (Bing Map).

·         Telemetry History (line diagram showing real-time data streams).

·         Gauges for reporting average measures.

·         Alarm History for reporting violations of defines rules (exceeding of set metrics as measured by the connected devices).

Azure IoT Suite Dashboard


Several technology components work together in the Azure IoT Suite and are brought together in Azure under the same Resource Group, namely aptly after the Azure IoT Suite solution itself. Components include:

·         IoT Hub: The pulsing heart of the IoT Suite, providing a device registry and bi-directional communication.

·         Storage: Typically, in the form of a NoSQL database like DocumentDB, for storing data and alert history.

·         Event Hub: A highly scalable data streaming platform capable of ingesting millions of events per second.

·         App Service: Works in combination with Power BI to display data in the dashboard.

·         Stream Analytics: Provides in-motion data analysis, processes incoming telemetry, and detects events.

A full description of the components of the Azure IoT Suite preconfigured solutions is available on Microsoft Web Site.

Azure resources for the IoT Suite


Azure IoT Hub

The Azure IoT Hub is an Azure service that enables secure and reliable bi-directional communications between your application back end and millions of devices. It allows the application back end to receive telemetry at scale from your devices, route that data to a stream event processor, receive file uploads from devices, and also to send cloud-to-device commands to specific devices. In addition, IoT Hub includes a device identity registry used to provision devices, their security credentials, and their rights to connect to the hub. The device identity registry, thus enforces:

·         Block of unsolicited network information: Only registered devices can communicate with the IoT Hub.

·         Bi-directional secured communication: Device specific queues are maintained for all commands, to guarantee delivery, especially in conditions of low-power usage. When a device enters into stand-by mode to reduce power consumption and preserve battery life, an “awake” signal is sent by the IoT Hub to alert the device that a new measure is required, at specified intervals of time.

Connecting a device to the IoT Hub, programmatically, is relatively simple when using the .NET framework and the device runs Windows 10 IoT Core operating system. The solution in Visual Studio requires the following packages to enable the communication between the device and the IoT Hub. These packages have a lot of dependencies, though, so expect to see a longer list of packages installed automatically by NuGet Package Manager.

NuGet Packages for connecting a device to the Azure IoT Hub


The ThermostatManager class in the code sample below connects a pseudo-thermostat device to the Azure IoT Hub via the RegistryManager factory, and adds the device identified by its unique ID. Access to the IoT Hub is identified by a connection string in the form of:

HostName={AzureIoTHub-Hostname}; SharedAccessKeyName={AccessPolicyName}; SharedAccessKey={AccessPrimaryKey}

These three elements can be conveniently stored in the application configuration file, and be used for building the connection string in the expected format.


    <add key="AzureIoTHub-HostName" value="{hostname}"/>

    <add key="AzureIoTHub-AccessPolicyName" value="iothubowner"/>

    <add key="AzureIoTHub-AccessPrimaryKey" value="{primary-key}"/>


Connection String elements to Azure IoT Hub


The access policy defines the level of permissions granted to an application / device that connects to the hub. “iothubowner” is the most privileged access, able to maintain the device registry and establish communication from and to the connected devices. Other policies have less permissions and are more suitable for cloud-to-device communication only (service) or device-to-cloud direction (device). Choose your access policy depending on the activities your application is expected to perform. Each access policy has a primary and secondary key for authentication in Azure IoT Hub.

Access Policy to Azure IoT Hub


Once added to the IoT Hub, a key is assigned to the device in the hub’s registry. Each registered device is identified by an instance of the Device class in the Microsoft.Azure.Devices namespace. Given the device ID and access key, a client instance (DeviceClient class) should be used for further communication between the device and the hub.

using Microsoft.Azure.Devices;

using Microsoft.Azure.Devices.Common.Exceptions;


public class ThermostatManager


    public ThermostatManager(string hostName, string accessPolicyName, string accessPrimaryKey)


        this.hostName = hostName;


        string connectionString = $"HostName={hostName};SharedAccessKeyName={accessPolicyName};SharedAccessKey={accessPrimaryKey}";

        registry = RegistryManager.CreateFromConnectionString(connectionString);



    public async Task AddDeviceAsync(Thermostat thermostat)


        // Add the device to the IoT Hub

        Device device;



            device = await registry.AddDeviceAsync(new Device(thermostat.Id));


        catch (DeviceAlreadyExistsException)


            device = await registry.GetDeviceAsync(thermostat.Id);



        // Creates a device client for communication with the IoT Hub

        DeviceClient client = DeviceClient.Create(this.hostName,

            new DeviceAuthenticationWithRegistrySymmetricKey(






Registering a device into the Azure IoT Hub


Once the device is registered in the hub, it can start streaming data using the client object.

private async void SendMessagesAsync(Thermostat sender, EventArgs e)


    var telemetryDataPoint = new


        deviceId = sender.Id,

        temperature = e.Measure



    var messageString = JsonConvert.SerializeObject(telemetryDataPoint);

    var message = new Message(Encoding.ASCII.GetBytes(messageString));


    await deviceClient.SendEventAsync(message);


Sending a message to the IoT Hub


The full code is available on CodePlex for free download. It also provides a simulation of two thermostat devices connected to the Azure IoT Hub and streaming data every second in parallel. The first device runs for 10 seconds, and the second one for 15 seconds. Communication is interrupted with a cancellation token. When the execution of a data reading from the device is cancelled, an ReadCanceled event is raised.


public void Run()


    Parallel.ForEach(deviceList, async (item) =>


        CancellationTokenSource cts = item.RunForMilliseconds < 0 ? null : new CancellationTokenSource(item.RunForMilliseconds);

        await RunThermostatAsync(item.Thermostat, cts);




private async Task RunThermostatAsync(Thermostat thermostat, CancellationTokenSource cts)




        while (true)


            await thermostat.ReadTemperatureAsync(cts != null ? cts.Token : CancellationToken.None);



    catch (OperationCanceledException)






public delegate void ReadCanceledEventHandler(Thermostat sender, EventArgs e);


public event ReadCanceledEventHandler ReadCanceled;


protected virtual void OnReadCanceled(Thermostat sender)


    ReadCanceled?.Invoke(sender, EventArgs.Empty);


Parallel running and cancellation handling of device readings


The simulation runs as a Windows Console application, with the following output. Temperatures are simulated and generated randomly, and sent to the IoT Hub every second until the cancellation period occurs.

Messages sent to the IoT Hub from the connected devices


In the Azure Portal, it is possible to see metrics about the number of connected devices and messages exchanged.

IoT Hub Metrics



This part 1 of the article introduced the use case for generating more effective sales in Dynamics CRM, as a result of optimisation of stock availability of products. This is obtained by identifying customer usage patterns, combining the technology of mobile and wearable devices connected to Azure IoT Hub for collecting information.

In the second part of the article, focus is on the implementation of a demand estimation experiment in Azure Machine Learning, which analyses the data collected in the IoT Hub and scores, i.e. predicts, future demand. Based on the estimated demand, according to a number of conditions identified in the input dataset, churn rate, appetency and upselling are optimised for the products in stock.




Jonathan clerk
On 15 Mar 2019 at 00:00
Thanks for sharing it in the blogosphere. We really appreciate contribution in Sales era. IOT and ML are quite good for sales calculation and Customer Engagement:
 Source Code

Project Name: AzureIoT

 Related Content
A flexible Default Value for your DateTime properties
When creating an MVC application with Entity Framework, it is possible to set default values for most properties in a model using the DefaultValue attribute. However, no much flexibility is offered for a DateTime property. This article presents a custom validation attribute for DateTime types that accepts different formats for defining the default value of the property.
Adding a Secured Geo-located Audit Trail
How I built a social sharing component for my own web site and added a secured geo-located audit trail. Step by step, let’s analyse technologies and source code for developing this component.
Adding Social Sharing to a Web Site
How I built a social sharing component for my own web site and added a secured geo-located audit trail. Step by step, let’s analyse technologies and source code for developing this component.
Best practices for mobile form design in SharePoint
Build effective SharePoint forms with Nintex that are accessible anywhere, at any time, and on any device. You built the workflows, you built the forms, now make them mobile.
Bring your “A” game to ESPC16
With just over 3 weeks to go to Europe's largest gathering of SharePoint & Office 365 professionals, take a look at these tips that will help you get the most out of ESPC16…
Building an MVC application for SharePoint
Learn how to write code to perform basic operations with the SharePoint 2013 .NET Framework client-side object model (CSOM), and build an ASP.NET MVC application that retrieves information from a SharePoint server.
What are the synergies and differences of the roles of a Chief Information Officer and a Chief Technology Officer? An open conversation about two roles with one mission…
Coded UI test automation of MVC applications with Visual Studio
Whether you are a software developer, tester, administrator or analyst, this article can help you master different types of UI testing of an MVC application, by using Visual Studio for creating coded UI test suites that can be automated for continuous execution.
Converting GIS spatial coordinates
Different formats and standards exist for describing geographical coordinates in GIS systems and applications. This article explains how to convert between the most used formats, presenting a working library written in C#.
Creating mobile accessible forms in SharePoint
With the release of the Nintex Mobile apps, SharePoint users can now optimise their experience across popular mobile devices and platforms.
Define your Performance Testing strategy with Visual Studio
Performance Testing is an essential part of software testing, with the specific goal of determining how a system performs in terms of responsiveness and stability under a particular workload. In this series of posts we’ll define and execute a good strategy for testing performance of an application using Visual Studio.
Disserting about colliding GUIDs and the Big Bang Theory
Can you generate two identical GUIDs? Would the world end if two GUIDs collide? How long does it take to generate a duplicate GUID and would we be still here when the result is found?
GIS Location Services in Dynamics CRM
A design paper about implementing GIS-based services for a local Council in Dynamics CRM, structuring address data, and delivering location services in the form of WebAPI endpoints via an Enterprise Service Bus.
Group or Team?
All teams are groups but not all groups are teams. What defines a group and what a team? When do we need one over the other one?
How to Give Constructive Feedback
Learning to give and receive constructive feedback is an essential part of learning, growing, improving and achieving our goals.
Mirroring an iPad on your laptop
Have you ever wanted to see your iPhone or iPad on a larger screen? Play games, watch movies, demo apps or present to your computer from your iPhone or iPad. Reflector mirrors iOS devices on big screens wirelessly using iOS built-in AirPlay mirroring.
Mobilize your SharePoint workflows
Build workflow applications in SharePoint that can be accessed on mobile devices using the Nintex solution for business process mobilization.
Natural String Sorting
Have you ever desired to have in your code a way to order a sequence of strings in the same way as Windows does for files whose name contains a mix of letters and numbers? Natural string sorting is not natively supported in .NET but can be easily implemented by specialising a string comparer and adding a few extensions to the enumerable string collection.
Scaling Applications with Azure Redis and Machine Learning - Part 1
This article presents design best practices and code examples for implementing the Azure Redis Cache and tuning the performance of ASP.NET MVC applications, optimising cache hit ratio and reducing “miss rate” with smart algorithms processed by Machine Learning.
Software Development Management in 11 steps
What it takes to be a great Software Development Manager? I have been building software for the last 15 years and have collected a few stories and experiences to share. Some I have used as questions when interviewing candidates. In 11 points, this is my story to date.
SOLID SharePoint apps with MVC
Practical code examples of ASP.NET MVC applications that connect to a SharePoint Server and comply with the SOLID principles.
The art of outsourcing projects
Outsourcing may look financially attractive, but working with companies in far-off lands introduces challenges that, if not considered properly, can drive any project to failure. Let’s explore some common pitfalls when working with offshore partners and a common-sense approach to work around them.
The value of hashtags
Customers expect a modern approach to advertising. Digital advertising can leverage evolving technology to provide just-in-time, just-at-the-right-place promotions.
We don't need no Yoda's syntax
There is an urban myth in the programmers’ community that the so called “Yoda’s syntax” performs better when checking an object for nullity. Let's demystify it...