Labs Exercises - AZ-220
Labs Exercises - AZ-220
com/MicrosoftLearning/AZ-220-Microsoft-Azure-IoT-
Developer/tree/master/Instructions/Labs
Lab no.1
Lab Scenario
You work for a gourmet cheese company named Contoso. The company's Chief Technology Officer
has evaluated the business opportunity for implementing IoT and has concluded that Contoso can
realize significant benefits by implementing an IoT solution. Contoso has selected the Microsoft Azure
IoT tools based on their evaluations.
As one of the individuals assigned to the project, you need to become familiar with the Azure tools.
In This Lab
In this lab, you will become familiar with the Azure portal and you will setup a Resource Group. The
lab includes the following exercises:
Lab Instructions
Before you begin working with the Azure IoT services, it's good to be familiar with how Azure itself
works.
Although Azure commonly referred to as a 'cloud', it is actually a web portal that is designed to make
Azure resources accessible from a single web site. All of Azure is accessible through the Azure portal.
1. In the lab virtual machine environment, open a Microsoft Edge browser window, and then
navigate to the Azure portal using the following Web address:
+++http://portal.azure.com+++
NOTE: Whenever you see the green "T" symbol, for example +++enter this text+++, you can
click the associated text and the information will be typed into the current field within the
virtual machine environment.
2. When prompted to Sign in using Azure account credentials, enter the credentials that you are
using for this course.
When you log into Azure you will arrive at the Azure portal. The Azure portal provides you
with a customizable UI that you can use to access your Azure resources.
3. In the upper left corner of the portal window, to open the Azure portal menu, click the
hamburger menu icon.
At the top of the portal menu, you should see a section containing four menu options:
o The Create a resource button opens a page displaying the services available
through the Azure Marketplace, many of which provide free options. Notice that
services are grouped by technology, including "Internet of Things", and that a search
box is provided.
o The Dashboard button opens a page displaying your default (or most recently used)
dashboard. You will be creating a dashboard later in this lab.
The bottom section of the portal menu is a FAVORITES section that can be customized to
show your favorite, or most commonly used, resources. Later in this lab, you will learn how to
customize this default list of common services to make it a list of your own favorites.
The Home page provides a customized view of recently used resources and services, as well
as other helpful links.
Azure Monitor is a tool that can help you to manage your Azure resources. You will be using
Azure Monitor later in this course when you have implemented the services that comprize
your IoT solution.
6. On the left side navigation menu, to display a map of data center regions, click Service
Health.
This map shows the current status of regions associated with your subscription(s). A green
circle is used to indicate that services are running normally at that region.
With any cloud vendor (Azure, AWS, Google Cloud, etc.), services will go down from time to
time. If you see a blue 'i' next to a region on the Service Health map, it means the region is
experiencing a problem with one or more services. Azure mitigates these issues by running
multiple copies of your application in different regions (a practice referred to as Geo-
redundancy). If a region experiences an issue with a particular service, those requests will roll
over to another region to fulfill the request. This is one of the big advantages of hosting apps
in the Azure cloud. Azure deals with the issues, so you don't have to.
7. In the upper-left corner of your Azure portal, to navigate back to your home page, click Home.
You can also use the portal menu to perform some simple navigation. You will have a chance
to try out some options for portal navigation shortly.
The All services page provides you with a few different viewing options and access to all of
the PaaS, IaaS, and SaaS services that Azure offers. The first time that you open the All
services page, you will see the Overview page. This view is accessible from the left side
menu.
This view displays all of the services organized into groups corresponding to each Category.
The Search box at the top can be very helpful.
The list of services is now limited to the services directly related to an IoT solution.
Service/Resource pages on the Azure portal are sometimes referred to as blades. When you
opened the Service Health page a couple of steps back, you opened a Service Health blade.
The Azure portal uses blades as a kind of navigation pattern, opening new blades to the right
as you drill deeper and deeper into a service. This gives you a form of breadcrumb navigation
as you navigate horizontally, and Azure provides a File Explorer style path at the top of the
blade that is clickable. For example: Home > Monitor > Service Health. But not every page is
a blade. You will get used to it pretty quickly.
A dialog box should be displayed. In the top-right corner, notice the "star" shape. When the
star shape is filled-in, the service is selected as a favorite. Favorites will appear on the list of
your favorite services on the left navigation menu of the portal window. This makes it easier to
access the services that you use most often. You can customize your favorites list by
selecting the services that you use most.
5. In the top-right corner of the IoT Hub dialog, to add IoT Hub to the list of your favorite
services, click the star shaped icon.
The star should now appear filled. If the star is shown as an outline, click the star icon again.
Tip: When you add a new item to your list of favorites, it is placed at the bottom of the
favorites list on the Azure portal menu. You can rearrange your favorites into the order that
you want by using a drag-and-drop operation.
6. Use the same process to add the following services to your favorites: Azure IoT Hub Device
Provisioning Services, Logic Apps, and Stream Analytics jobs.
Note: You can remove a service from the list of your favorite services by clicking the star of a
selected service.
o Subscriptions
o Resource groups
The favorites that you've added are enough to get you started, but you can use the Internet of
Things category to add additional favorites to the portal menu if you want.
In addition to the hamburger menu icon on the far left of this toolbar, there several tool items
that you will find helpful.
First, notice that you have a Search resources tool that can be used to quickly find a particular
resource.
To the right of the search tool are several buttons that provide access to common tools. You
can hover the mouse pointer over a button to display the button name.
On the far right is a button for your account information, providing you with access to things
like your account password and billing information.
3. Take a moment to scan the contents of the I have unexpected charges. How do I
understand them? page.
If you are using a paid Azure subscription and you are responsible for billing (you are the
Account Administrator), you can set up cost alerts to help manage your billing.
On the Azure portal, dashboards are used to present a customized view of your resources.
Information is displayed through the use of tiles which can be arranged and sized to help you organize
your resources in useful ways. You can create many different dashboards that provide different views
and serve different purposes.
Each tile that you place on your dashboard exposes one or more of your resources. In addition to tiles
that expose the data of an individual resource, you can create a tile for something called a resource
group.
A resource group is a logical group that contains related resources for a project or application. The
resource group can include all the resources for the solution, or only those resources that you want to
manage as a group. You decide how you want to allocate resources to resource groups based on
what makes the most sense for your organization. Generally, add resources that share the same
lifecycle to the same resource group so you can easily deploy, update, and delete them as a group.
create a custom dashboard that you can use during this course
create a Resource Group and add a Resource Group tile to your dashboard
Task 1: Create a Dashboard
1. If you closed the Azure portal browser window, open the Microsoft Edge browser, and then
navigate to the Azure portal:
+++http://portal.azure.com+++
When prompted to Sign in using Azure account credentials, enter the Azure credentials that
you are using for this course.
You can create a custom dashboard to organize and access your Azure resources for a
project. In this case, you will create a custom dashboard for this course.
In the upcoming steps you will be adding a tile to your dashboard manually. Another option
would be to use drag-and-drop operations to add tiles from the Tile gallery to the space
provided.
Task 2: Create a Resource Group and add a Resource Group tile to your Dashboard
This blade displays all of the resource groups that you have created using your Azure
subscription(s). If you are just getting started with Azure, you probably don't have any
resource groups yet.
Notice that the resource group is associated with a Subscription and a Region. Consider the
following:
4. In the Subscription dropdown, select the Azure subscription that you are using for this
course.
The name of the resource group must be unique within your subscription. A green check
mark will appear if the name that you enter has not already been used and confirms to
resource group naming rules.
Tip: The Azure documentation describes all Azure naming rules and restrictions.
6. In the Region dropdown, select a region that is near you.
You should check with your instructor as well, as not all regions offer all services.
You need to provide a location for the resource group because the resource group stores
metadata about the resources and acts as the default location for where new resources in the
resource group will be created. For compliance reasons, you may want to specify where that
metadata is stored. In general, it is recommended that you specify a location where most of
your resources will reside. Using the same location can simplify the template used to manage
your resources.
You should see a message informing you that the settings for your resource group have been
validated successfully.
9. On the top menu of the Resource groups blade, to see your new resource group,
click Refresh
You will learn more about managing your resources as you continue through this course.
10. In the list of named resource groups, click the box to the left of the rg-az220 resource group
that your just created.
Note: You don't want to open the resource group in a new blade, you just want to select it
(check mark on the left).
11. On the right side of the screen, click the ellipsis (...) corresponding to your resource group,
and then click Pin to dashboard.
12. Ensure that the dashboard you created is selected and then select Pin.
Your dashboard should now contain an empty Resources tile, but don't worry, you will fill it up
soon enough.
Lab no.2
Lab Scenario
You are an Azure IoT Developer working for Contoso, a company that crafts and distributes gourmet
cheeses.
You have been tasked with exploring Azure and the Azure IoT services that you will using to develop
Contoso's IoT solution. You have already become familiar with the Azure portal and created a
resource group for your project. Now you need to begin investigating the Azure IoT services.
In This Lab
In this lab, you will create and examine an Azure IoT Hub and an IoT Hub Device Provisioning
Service. The lab includes the following exercises:
Explore Globally Unique Resource Naming Requirements
Create an IoT Hub using the Azure portal
Examine features of the IoT Hub service
Create a Device Provisioning Service and link it to your IoT Hub
Examine features of the Device Provisioning Service
Lab Instructions
In labs 2-19 of this course, you will be creating and configuring the Azure resources that are used to
develop your IoT solution. To ensure consistency across the labs and to help in tidying up resources
when you are finished with them, suggested resource names will be provided within the lab
instructions. As much as possible, the suggested resource names will follow the naming guidelines
recommended here: Recommended naming and tagging conventions. However, many of the
resources that you will create during this course expose services that can be consumed across the
web, which means that they must have globally unique names. To ensure that these resources satisfy
the globally unique requirement, you will be adding a unique identifier to the end of the resource
names when needed.
In this exercise, you will create your unique ID and review some examples that help to illustrate how
you will use your unique ID during labs 2-19 of this course.
1. Construct your unique ID by using your lower-case initials and the current date in the
following pattern:
2. YourInitialsYYMMDD
The first part of your unique ID will be your initials in lower-case. The second part will be the
last two digits of the current year, the current numeric month, and the current numeric day.
Here are some examples:
gwb200123
bho200504
cah201216
dm200911
Within the lab instructions, you will see {your-id} listed as part of the suggested resource
name whenever you need to enter your unique ID. The {your-id} portion of the suggested
resource name is a placeholder. You will replace the entire placeholder string (including
the {}) with your unique value.
3. Make a note of your unique ID now and then use the same value through the entire
course.
Note: Don't change the date portion of your unique ID each day. Use the same unique ID
each day of the course.
Many of the resources that you create during the labs in this course will have publicly-addressable
(although secured) endpoints and therefore must be globally unique. Examples of resources that
require globally unique names include IoT Hubs, Device Provisioning Services, and Azure Storage
Accounts.
As noted above, when you create these types of resources, you will be provided with a resource
name that follows suggested guidelines and you will be instructed to include your unique ID as part of
the resource name. To help clarify when you need to enter your unique ID, the suggested resource
name will include a placeholder value for your unique ID. You will be instructed to replace the
placeholder value, {your-id}, with your unique ID.
iot-az220-training- iot-az220-training-
IoT Hub
{your-id} cah191216
dps-az220-training- dps-az220-training-
Device Provisioning Service
{your-id} cah191216
2. Review the following example for applying your unique ID within a Bash script:
In some of the labs later in this course, you will be instructed to apply your unique ID value
within a Bash script. The Bash script file, which is provided for you, might include code that is
similar to the following:
#!/bin/bash
YourID="{your-id}"
RGName="rg-az220"
IoTHubName="iot-az220-training-$YourID"
In the code above, if the value of your unique ID is cah191216, then the line
containing YourID="{your-id}" should be updated to YourID="cah191216".
Note: Notice that you do not change the $YourID value on the final code line. If it isn't {your-
id} then don't replace it.
3. Review the following example for applying your unique ID within C# code:
In some of the labs later in this course, you will be instructed to apply your unique ID value
within C# source files. The C# source code, which will be provided to you, might include a
code section that looks similar to the following:
4. Notice that not all resource names require you to apply your unique ID.
As you may have already considered, the Resource Group that you created in the previous
lab did not include your unique ID value.
Some resources, like the Resource Group, must have a unique name within your
subscription, but the name does not need to be globally unique. Therefore, each student
taking this course can use the resource group name: rg-az220. Of course this is only true if
each student uses their own subscription, but that should be the case.
The Azure IoT Hub is a fully managed service that enables reliable and secure bidirectional
communications between IoT devices and Azure. The Azure IoT Hub service provides the following:
There are several methods that you can use to create an IoT Hub. For example, you can create an
IoT Hub resource using the Azure portal, or you can create an IoT Hub (and other resources)
programmatically. During this course you will be investigating various methods that can be used to
create and manage Azure resources, including Azure CLI and Bash scripts.
In this exercise, you will use the Azure portal to create and configure your IoT Hub.
1. In the lab virtual machine environment, open a Microsoft Edge browser window, and then
navigate to the Azure portal using the following Web address:
+++http://portal.azure.com+++
NOTE: Whenever you see the green "T" symbol, for example +++enter this text+++, you can
click the associated text and the information will be typed into the current field within the
virtual machine environment.
2. When prompted to Sign in using Azure account credentials, enter the Azure credentials that
you are using for this course.
If you have more than one Azure account, be sure that you are logged in with the account that
is tied to the subscription that you will be using for this course.
3. Notice that the AZ-220 dashboard that you created in the previous lab has been loaded.
The New blade that opens is a front-end to the Azure Marketplace, which is a collection of all
the resources you can create in Azure. The marketplace contains resources from both
Microsoft and the community.
The Marketplace blade will open to display the available services matching your search
criteria.
Note: Marketplace services provided by private contributors may include a cost that is not
covered by a Microsoft Azure Pass or other Microsoft Azure free credit offerings. You will be
using Microsoft provided resources during the labs in this course.
Note: A Create action is shown at the bottom of the IoT Hub search result - that will navigate
directly to the IoT Hub creation view. In normal use you may chose to click this - for the
purpose of the tutorial, click anywhere in the main body of the IoT Hub search result.
There is no need to explore these links now, but it's worth noting that they are available.
The Documentation link, for example, takes you to the root page for IoT Hub resources and
documentation. You can use this page to review the most up-to-date Azure IoT Hub
documentation and explore additional resources that are outside the scope of this course.
You will be referred to the docs.microsoft.com site throughout this course for additional
reading on specific topics.
If you opened one of the links, close it now and use your browser to navigate back to the
Azure portal tab.
Tip: In the future, there are two other ways to get to the Create experience of any Azure
resource type:
i. If you have the service in your Favorites, you can click the service to navigate to the
list of instances, then click the + Add button at the top.
ii. You can search for the service name in the Search box at the top of the portal to get
to the list of instances, then click the + Add button at the top.
The following steps walk you through the settings required to create your IoT Hub, explaining
each of the fields as you fill them in.
The Basics tab that is selected initially contains uninitialized fields that you are required to fill
in, but there are settings on other tabs that you will need to be familiar with as well.
3. To the right of Resource group, open the dropdown, and then click rg-az220
This is the resource group that you created in the previous lab. You will be grouping the
resources that you create for this course together in the same resource group. It is best
practice to group related resources in this way, and will help you to clean up your resources
when you no longer need them.
4. To the right of IoT hub name, enter a globally unique name for your IoT Hub as follows:
For example: iot-az220-training-cah191216
The name of your IoT Hub must be globally unique because it is a publicly accessible
resource that you must be able to access from any of your IP enabled IoT devices.
Consider the following when you specify a unique name for your new IoT Hub:
i. The value that you apply to IoT hub name must be unique across all of Azure. This is
true because the value assigned to the name will be used in the IoT Hub's connection
string. Since Azure enables you to connect devices from anywhere in the world to
your hub, it makes sense that all Azure IoT hubs must be accessible from the Internet
using the connection string and that connection strings must therefore be unique. You
will explore connection strings later in this lab.
ii. The value that you assign to IoT hub name cannot be changed once your resource
has been created. If you do need to change the name, you'll need to create a new IoT
Hub with the desired name, re-register your devices from the original hub and register
them with the new one, and delete your old IoT Hub.
Note: Azure will ensure that the name you enter is unique. If the name that you enter is not
unique, Azure will display a message below the name field as a warning. If you see the
warning message, you should update your unique ID. Try appending your unique ID with '00',
or '01', or '02, 'etc. as necessary to achieve a globally unique name.
Note: Some resource names do not allow extended characters like the dash (-) or underscore
(_), so stick with numeric digits when updating your unique ID.
5. To the right of Region, open the drop-down list and select the same region that you selected
for your resource group.
Note: One of the upcoming labs will use Event Grid. To support this future lab, you need to
select a Region that supports Event Grid. For the current list of regions that support Event
Grid, see the following link: Products available by region
As you saw previously, Azure is supported by a series of datacenters that are placed in
regions all around the world. When you create something in Azure, you deploy it to one of
these datacenter locations.
Note: When picking a region to host your resources, keep in mind that picking a region close
to your end users will decrease load/response times. In a production environment, if you are
on the other side of the world from your end users, you should not be picking the region
nearest you.
Take a minute to review the fields and other information presented on this tab.
7. To the right of Pricing and scale tier, ensure that S1: Standard tier is selected.
Azure IoT Hub provides several tier options depending on how many features you require and
how many messages you need to send within your solution per day. The S1 tier that you are
using in this course allows a total of 400,000 messages per unit per day and provides the all
of the services that are required in this training. You won't actually need 400,000 messages
per unit per day, but you will be using features provided by the Standard tier, such as Cloud-
to-device commands, Device management, and IoT Edge. IoT Hub also offers a Free tier that
is meant for testing and evaluation. It has the same capabilities as the Standard tier, but
limited messaging allowances. It is important to note that you cannot upgrade from the Free
tier to either Basic or Standard. The Free tier allows 500 devices to be connected to the IoT
hub and up to 8,000 messages per day. Each Azure subscription can create one IoT Hub in
the Free tier.
Note: The S1 - Standard tier has a cost of $25.00 USD per month per unit. You will be
specifying 1 unit. For details about the other tier options, see Choosing the right IoT Hub tier
for your solution.
As mentioned above, the pricing tier that you choose establishes the number of messages
that your hub can process per unit per day. To increase the number of messages that your
hub can process without moving to a higher pricing tier, you can increase the number of units.
For example, if you want your IoT hub to support ingress of up to 800,000 messages per day,
you could specify two S1 tier units. For this course you will be using just 1 unit.
Azure Defender for IoT is a unified security solution for identifying IoT/OT devices,
vulnerabilities, and threats. It enables you to secure your entire IoT/OT environment, whether
you need to protect existing IoT/OT devices or build security into new IoT innovations.
TIP: Azure Defender for IoT was formerly known as Azure Security Center and you may
still see places in Azure, and in this content, where the name has not yet been updated.
Azure Defender for IoT is on by default because security is important to your IoT solution. You
will be exploring Azure Defender for IoT in Lab 19 of this course. Disabling it for now ensures
that the Lab 19 instructions work as expected.
Currently, you can enable Azure Defender at the subscription level, through the Azure portal.
Azure Defender is free for the first 30 days. Any usage beyond 30 days will be automatically
charged as per the pricing information detailed here.
10. Review the table that summarizes the current settings and costs.
The number of partitions relates the device-to-cloud messages to the number of simultaneous
readers of these messages. Most IoT hubs will only need four partitions, which is the default
value. For this course you will create your IoT Hub using the default number of partitions.
12. Within the Transport Layer Security (TLS) section, ensure the Minimum TLS Version is set
to 1.0.
IoT Hub uses Transport Layer Security (TLS) to secure connections from IoT devices and
services. Two versions of the TLS protocol are currently supported, namely versions 1.0 and
1.2.
[!Important] The Minimum TLS Version property cannot be changed once your IoT Hub
resource is created. It is therefore essential that you properly test and validate that all your
IoT devices and services are compatible with TLS 1.2 and the recommended ciphers in
advance. You can learn more about IoT Hub and TLS below:
14. At the bottom of the blade, to finalize the creation of your IoT Hub, click Create.
Deployment can take a minute or more to complete. You can open the Azure portal
Notification pane to monitor progress.
15. Notice that after a couple of minutes you receive a notification stating that your IoT Hub was
successfully deployed to your rg-az220 resource group.
You should see that your resource group tile lists your new IoT Hub.
As you have already learned, IoT Hub is a managed service, hosted in the cloud, that acts as a
central message hub for bi-directional communication between your Azure IoT services and your
connected devices.
IoT Hub's capabilities help you build scalable, full-featured IoT solutions such as managing industrial
equipment used in manufacturing, tracking valuable assets in healthcare, monitoring office building
usage, and many more scenarios. IoT Hub monitoring helps you maintain the health of your solution
by tracking events such as device creation, device failures, and device connections.
In this exercise, you will examine some of the features that IoT Hub provides.
1. If you closed your Azure portal window, open a Microsoft Edge browser window, and then
navigate to the Azure portal:
+++http://portal.azure.com+++
If you have more than one Azure account, be sure that you are logged in with the account that
is tied to the subscription that you will be using for this course.
When you first open your IoT Hub blade, the Overview information will be displayed. As you
can see, the area at the top of this blade provides some essential information about your IoT
Hub service, such as datacenter location and subscription. But this blade also includes tiles
that provide information about how you are using your hub and recent activities. Let's take a
look at these tiles before exploring further.
4. At the bottom-left of your IoT Hub blade, notice the IoT Hub Usage tile.
Note: The tiles positions are based upon the width of the browser window, so the layout may
be a little different than described.
This tile provides a quick overview of what is connected to your hub and message count. As
you add devices and start sending messages, this tile will provide nice "at-a-glance"
information.
5. To the right of the IoT Hub Usage tile, notice the Number of messages used tile and
the Device to cloud messages tile.
The Device to cloud messages tile provides a quick view of the incoming messages from
your devices over time. You will be registering a device and sending messages to your hub
during a module in the next module, so you will begin to see information on these tiles pretty
soon.
The Number of messages used tile can help you to keep track of the total number of
messages used.
1. On the IoT Hub blade, take a minute to scan the left-side menu options.
As you would expect, these menu options are used to open panes that provide access to
properties and features of your IoT Hub. For example, some panes provides access to
devices that are connected to your hub.
This pane can be used to add, modify, and delete devices registered to your hub. You will get
pretty familiar with this pane by the end of this course.
As the name implies, this pane gives you access to a log that can be used to review activities
and diagnose issues. You can also define queries that help with routine tasks. Very handy.
IoT Hub exposes "endpoints" that enable external connections. Essentially, an endpoint is
anything connected to or communicating with your IoT Hub. You should see that your hub
already has two endpoints defined:
o Events
o Cloud to device messaging
The IoT Hub message routing feature enables you to route incoming device-to-cloud
messages to service endpoints such as Azure Storage containers, Event Hubs, and Service
Bus queues. You can also create routing rules to perform query-based routes.
Note: This lab exercise is only intended to be an introduction to the IoT Hub service and get
you more comfortable with the UI, so don't worry if you feel a bit overwhelmed at this point.
You will be configuring and managing your IoT Hub, devices, and their communications as
this course continues.
The Azure IoT Hub Device Provisioning Service is a helper service for IoT Hub that enables zero-
touch, just-in-time provisioning to the right IoT hub without requiring human intervention. The Device
Provisioning Service provides the following:
Zero-touch provisioning to a single IoT solution without hardcoding IoT Hub connection
information at the factory (initial setup)
Load balancing devices across multiple hubs
Connecting devices to their owner's IoT solution based on sales transaction data
(multitenancy)
Connecting devices to a particular IoT solution depending on use-case (solution isolation)
Connecting a device to the IoT hub with the lowest latency (geo-sharding)
Reprovisioning based on a change in the device
Rolling the keys used by the device to connect to IoT Hub (when not using X.509 certificates
to connect)
There are several methods that you can use to create an instance of the IoT Hub Device Provisioning
Service. For example, you can use the Azure portal, which is what you will do in ths task. But you can
also create a DPS instance using Azure CLI or an Azure Resource Manager Template.
Task 1: Use the Azure portal to create a resource (Device Provisioning Service)
1. If you closed your Azure portal window, open a Microsoft Edge browser window, and then
navigate to the Azure portal:
+++http://portal.azure.com+++
If you have more than one Azure account, be sure that you are logged in with the account that
is tied to the subscription that you will be using for this course.
As you saw previously, the New blade provides you with the capability to search the Azure
Marketplace for services.
Again, there is no need to explore this documentation now, but is is good to know that it is
available. The IoT Hub Device Provisioning Service Documentation page is the root page for
DPS. You can use this page to explore current documentation and find tutorials and other
resources that will help you to explore activities that are outside the scope of this course. You
will be referred to the docs.microsoft.com site throughout this course for additional reading on
specific topics.
If you opened one of the links, close it now and use your browser to navigate back to the
Azure portal tab.
Next, you need to specify information about the Hub and your subscription. The following
steps walk you through the settings, explaining each of the fields as you fill them in.
2. Under Subscription, ensure that the subscription you are using for this course is selected.
You will be grouping the resources that you create for this course together in the same
resource group. It's a best practice to group related resources in this way, and will help you to
clean up your resources when you no longer need them.
4. Under Name, enter a globally unique name for your IoT Hub Device Provisioning Service as
follows:
For example: dps-az220-training-cah191216
5. Under Region, open the drop-down list and select the same region that you selected for your
resource group.
Note: When picking a datacenter to host your resources, keep in mind that picking a
datacenter close to your end users will decrease load/response times. If you are on the other
side of the world from your end users, you should not be picking the datacenter nearest you.
6. At the bottom of the blade, click Review + Create. Once validation passes, click Create.
Deployment can take a minute or more to complete. You can open the Azure portal
Notification pane to monitor progress.
7. Notice that after a couple of minutes you receive a notification stating that your IoT Hub
Device Provisioning Service instance was successfully deployed to your rg-az220 resource
group.
You should see that your resource group tile lists your new IoT Hub Device Provisioning
Service.
You should see both your IoT Hub and DPS resources listed - (you may need to hit Refresh if
the resources were only recently created)
You will use the Add link to IoT hub blade to provide the information required to link your
Device Provisioning service instance to an IoT hub.
This is the IoT Hub that you created in the previous exercise.
The iothubowner credentials provide the permissions needed to establish the link with the
specified IoT hub.
You should now see the selected hub listed on the Linked IoT hubs pane. You might need to
click Refresh to show Linked IoT hubs.
The IoT Hub Device Provisioning Service is a helper service for IoT Hub that enables zero-touch, just-
in-time provisioning to the right IoT hub without requiring human intervention, enabling customers to
provision millions of devices in a secure and scalable manner.
1. If you closed your Azure portal window, open a Microsoft Edge browser window, and then
navigate to the Azure portal:
+++http://portal.azure.com+++
If you have more than one Azure account, be sure that you are logged in with the account that
is tied to the subscription that you will be using for this course.
When you first open your Device Provisioning Service instance, it will display the Overview
information. As you can see, the area at the top of the blade provides some essential
information about your DPS instance, such as status, datacenter location and subscription.
This blade also provides the Quick Links section, which provide access to:
When time permits, you can come back and explore these links.
Task 2: View features of Device Provisioning Service using the navigation menu
As you might expect, these options open panes that provide access to activity logs, properties
and feature of the DPS instance.
As the name implies, this pane gives you access to a log that can be used to review activities
and diagnose issues. You can also define queries that help with routine tasks. Very handy.
This pane lists the steps to start using the Iot Hub Device Provisioning Service, links to
documentation and shortcuts to other blades for configuring DPS.
This pane provides management of access policies, lists the existing policies and the
associated permissions.
Here you can see the linked IoT Hub from earlier. The Device Provisioning Service can only
provision devices to IoT hubs that have been linked to it. Linking an IoT hub to an instance of
the Device Provisioning service gives the service read/write permissions to the IoT hub's
device registry; with the link, a Device Provisioning service can register a device ID and set
the initial configuration in the device twin. Linked IoT hubs may be in any Azure region. You
may link hubs in other subscriptions to your provisioning service.
Here you can manage the X.509 certificates that can be used to secure your Azure IoT hub
using the X.509 Certificate Authentication. You will investigate X.509 certificates in a later lab.
Here you can manage the enrollment groups and individual enrollments.
Enrollment groups can be used for a large number of devices that share a desired initial
configuration, or for devices all going to the same tenant. An enrollment group is a group of
devices that share a specific attestation mechanism. Enrollment groups support both X.509
as well as symmetric. All devices in the X.509 enrollment group present X.509 certificates that
have been signed by the same root or intermediate Certificate Authority (CA). Each device in
the symmetric key enrollment group present SAS tokens derived from the group symmetric
key. The enrollment group name and certificate name must be alphanumeric, lowercase, and
may contain hyphens.
An individual enrollment is an entry for a single device that may register. Individual
enrollments may use either X.509 leaf certificates or SAS tokens (from a physical or virtual
TPM) as attestation mechanisms. The registration ID in an individual enrollment is
alphanumeric, lowercase, and may contain hyphens. Individual enrollments may have the
desired IoT hub device ID specified.
Note: This lab exercise is only intended to be an introduction to the IoT Hub Device
Provisioning Service and get you more comfortable with the UI, so don't worry if you feel a bit
overwhelmed at this point. You will be covering DPS in much more detail as the course
continues.
Lab no.3
Lab Scenario
As one of the developers at Contoso, you know that setting up your development environment is an
important step before starting to build your Azure IoT solution. You also know that Microsoft and other
companies provide a number of tools that can be used to develop and support your IoT solutions, and
that some decisions should be made about which tools your team will use.
You decide to prepare a development environment that the team can use to work on your IoT
solution. The environment will need to support your work in Azure and on your local PC. After some
discussion, your team has made the following high-level decisions about the dev environment:
Operating System: Windows 10 will be used as the OS. Windows is used by most of your
team, so it was a logical choice. You make a note to the team that Azure services support
other operating systems (such as Mac OS and Linux), and that Microsoft provides supporting
documentation for the members of your team who choose one of these alternatives.
General Coding Tools: Visual Studio Code and Azure CLI will be used as the primary coding
tools. Both of these tools support extensions for IoT that leverage the Azure IoT SDKs.
IoT Edge Tools: Docker Desktop Community and Python will be used to support custom IoT
Edge module development (along with Visual Studio Code).
Python 3.9
node.js (latest)
IMPORTANT: A virtual machine has been created for this course that provides a majority of the tools
specified above. The instructions below support using the prepared VM or setting up the development
environment locally using your PC.
In This Lab
In this lab, you will configure your development environment. The lab includes the following exercises:
Lab Instructions
IMPORTANT: For students who are using the hosted virtual machine environment to complete the
labs in this course, Exercise 1 is the only Exercise that you need to complete. All of the other
Exercises in this lab are for students who are setting up a dev environment on their local PC. If you
will be setting up a dev environment on your local PC, skip to ahead to Exercise 2 and then complete
all of the remaining Exercises.
The Visual Studio Code and Azure CLI tools (already installed on the virtual machine) both support an
Azure IoT extension that helps developers to create their solutions more efficiently. These extensions
leverage the Azure IoT SDKs and will often reduce development time while ensuring security
provisions. You will also be adding a C# extension for Visual Studio Code.
You can hover the mouse pointer over the buttons to display the button titles. The Extensions
button is sixth from the top.
3. In the Visual Studio Code Extension manager, search for and then install the following
Extensions:
1. Open a new command-line / terminal window, to install the Azure IoT CLI extensions.
2. At the command prompt, to install the Azure CLI extension for IoT, enter the following
command:
3. At the command prompt, to install the Azure CLI extension for Time Series Insights, enter the
following command:
Many of the labs will require the use of the Azure CLI IoT extensions via the Azure Cloud Shell. The
following steps ensure the extension is installed and running the latest version.
1. Open Web browser window on your virtual machine, and then navigate to the Azure cloud
shell at the following address:
+++https://shell.azure.com/+++
2. When prompted, login with the Azure subscription you are using for this course.
3. If you are prompted about setting up storage for Cloud Shell, accept the defaults.
The dropdown in the top-left corner of the Azure Cloud Shell page is used to select the
environment. Verify that the selected dropdown value is Bash.
5. At the command prompt, to install the Azure CLI extension for IoT, enter the following
command:
Note: If the extension is already installed, you can ensure you are running the latest version
by entering the following command:
6. At the command prompt, to install the Azure CLI extension for Time Series Insights, enter the
following command:
You should verify that the development environment has been set up successfully. Once this is
complete, you will be ready to start building your IoT solutions.
2. Validate the Azure CLI installation by running the following command that will output the
version information for the currently installed version of the Azure CLI.
3. az --version
The az --version command will output the version information for Azure CLI that you have
installed (the azure-cli version number). This command also outputs the version number for
all the Azure CLI modules installed, including the IoT extension. You should see output similar
to the following:
azure-cli 2.21.0
core 2.21.0
telemetry 1.0.6
Extensions:
azure-iot 0.10.10
timeseriesinsights 0.2.1
4. Validate the .NET Core 3.x SDK installation by running the following command that will
output the version number for the currently installed version of the .NET Core SDK.
5. dotnet --version
The dotnet --version command will output the version of the .NET Core SDK that is currently
installed.
NOTE: If you are using the LOD virtual machine environment to complete the labs in this course, your
dev environment is configured and you are ready to move on to the next lab.
IMPORTANT: Exercise 2 and all of the remaining Exercises in this lab are for students who
are NOT using the LOD virtual machine that was created for this course. Students who need to
configure their local PC as their dev environment can use Exercises 2-5 to help them install tools and
configure the dev environment on their local PC.
.NET Core is a cross-platform version of .NET for building websites, services, and console apps.
1. To open the .NET Core download page, open a new browser tab, and then navigate to the
following page:
2. https://dotnet.microsoft.com/download
3. On the .NET download page, under .NET Core, click Download .NET Core SDK.
The .NET Core SDK is used to build .NET Core apps. You will be using it to build/edit code
files during the labs in this course.
4. On the popup menu, click Run, and then follow the on-screen instructions to complete the
installation.
The installation should take less than a minute to complete. The following components will be
installed:
Visual Studio Code is a lightweight but powerful source code editor which runs on your desktop and is
available for Windows, macOS and Linux. It comes with built-in support for JavaScript, TypeScript and
Node.js and has a rich ecosystem of extensions for other languages (such as C++, C#, Java, Python,
PHP, Go) and run times (such as .NET and Unity).
1. To open the Visual Studio Code download page, open a new browser tab, and then navigate
to the following page:
2. https://code.visualstudio.com/Download
Instructions for installing Visual Studio Code on Mac OS X and Linux can be found on the
Visual Studio Code set up guide here. This page also includes more detailed instructions and
tips for the Windows installation.
When you start the download, two things will happen: a popup dialog opens and some getting
started guidance will be displayed.
4. On the popup dialog, to begin the set up process, click Run and then follow the on-screen
instructions.
If you choose to Save the installer to your Downloads folder, you you can complete the
installation by opening the folder and then double-clicking the VSCodeSetup executable.
By default, Visual Studio Code is installed in the "C:\Program Files (x86)\Microsoft VS Code"
folder location (for a 64-bit machine). The set up process should only take about a minute.
Note: .NET Framework 4.5 is required for Visual Studio Code when installing on Windows. If
you are using Windows 7, please ensure .NET Framework 4.5 is installed.
For detailed instructions on installing Visual Studio Code, see the Microsoft Visual Studio
Code Installation Instruction guide here: https://code.visualstudio.com/Docs/editor/setup
1. To open the Azure CLI tools download page, open a new browser tab, and then navigate to
the following page:
2. https://docs.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest
You should be installing the latest version of the Azure CLI tools. The current version of Azure
CLI (as of February 2022) is version 2.33, but be aware that new versions are released
monthly, so the latest version is likely to have changed.
3. On the Install Azure CLI page, select the install option for your OS (such as Install on
Windows), and then follow the on-screen instructions to install the Azure CLI tool.
You will be given detailed instructions for using the Azure CLI tools during the labs in this
course, but if you want more information now, see Get started with Azure CLI
You will be using Python 3.9 in support of IoT Edge and Docker.
1. To open the Python.org downloads page, open a new browser tab, and then navigate to the
following page:
2. https://www.python.org/downloads/
3. On the Python download page, select the installer file that is appropriate for your Operating
System.
6. Click Install Now.
7. When the "Setup was successful" page appears, click Disable path length limit.
You will be using Docker Desktop Community (latest stable version) during a lab that covers creating
and deploying custom IoT Edge modules.
1. To open the Docker Desktop for Windows download page, open a new browser tab, and then
navigate to the following page:
2. https://docs.docker.com/docker-for-windows/install/
The left-side navigation menu provides access to installations for additional operating
systems.
You can use Windows Settings to open the Windows Features dialog, and use that to verify
that Hyper-V and Containers are enabled.
4. Click Docker Desktop for Windows, and then follow the on-screen instructions to open and
run the downloaded installation file.
It can take a little while for the installation dialog for Docker Desktop to appear.
Docker Desktop does not start automatically after installation. To start Docker Desktop,
search for Docker, and select Docker Desktop in the search results. When the whale icon in
the status bar stays steady, Docker Desktop is up-and-running, and is accessible from any
terminal window.
Some sample web applications are run locally using node.js. The following steps ensure node.js is
installed and running the latest version:
1. To open the Node.js download page, open a new browser tab, and then navigate to the
following page:
2. https://nodejs.org/en/#home-downloadhead
3. Download the latest LTS (Long Term Support) version - 14.16.0 at the time of writing.
Multiple packages will be downloaded and installed. This will take some time.
9. Once the installation has completed, open a new command shell and enter the following
command:
node --version
The Visual Studio Code and Azure CLI tools both support an Azure IoT extension that helps
developers to create their solutions more efficiently. These extensions leverage the Azure IoT SDKs
and will often reduce development time while ensuring security provisions. You will also be adding a
C# extension for Visual Studio Code.
Task 1: Install Visual Studio Code Extensions on the local PC
You can hover the mouse pointer over the buttons to display the button titles. The Extensions
button is sixth from the top.
3. In the Visual Studio Code Extension manager, search for and then install the following
Extensions:
1. Open a new command-line / terminal window, to install the Azure IoT CLI extensions.
2. At the command prompt, to install the Azure CLI extension for IoT, enter the following
command:
3. At the command prompt, to install the Azure CLI extension for Time Series Insights, enter the
following command:
Many of the labs will require the use of the Azure CLI IoT extensions via the Azure Cloud Shell. The
following steps ensure the extension is installed and running the latest version.
1. In your Web browser, navigate to the Azure cloud shell at the following address:
2. When prompted, login with the Azure subscription you are using for this course.
3. If you are prompted about setting up storage for Cloud Shell, accept the defaults.
The dropdown in the top-left corner of the Azure Cloud Shell page is used to select the
environment. Verify that the selected dropdown value is Bash.
5. At the command prompt, to install the Azure CLI extension for IoT, enter the following
command:
az extension add --name azure-iot
Note: If the extension is already installed, you can ensure you are running the latest version
by entering the following command:
6. At the command prompt, to install the Azure CLI extension for Time Series Insights, enter the
following command:
You should verify that the development environment has been set up successfully.
2. Validate the Azure CLI installation by running the following command that will output the
version information for the currently installed version of the Azure CLI.
3. az --version
The az --version command will output the version information for Azure CLI that you have
installed (the azure-cli version number). This command also outputs the version number for
all the Azure CLI modules installed, including the IoT extension. You should see output similar
to the following:
azure-cli 2.21.0
core 2.21.0
telemetry 1.0.6
Extensions:
azure-iot 0.10.10
timeseriesinsights 0.2.1
4. Validate the .NET Core 3.x SDK installation by running the following command that will
output the version number for the currently installed version of the .NET Core SDK.
5. dotnet --version
The dotnet --version command will output the version of the .NET Core SDK that is currently
installed.
Exercise 4: Set Up Course Lab Files and Alternative Tools on the Local PC
A number of the labs in this course rely on pre-built resources, such as a code project that can be
used as a starting point for the lab activity. These lab resources are provided in a GitHub project that
you should download to your local PC dev environment.
In addition to the resources that directly support the course labs (the resources contained in the
GitHub project), there are some optional tools that you may choose to install because they support
learning opportunities outside of this course. One example is PowerShell, which you may see
referenced within Microsoft tutorials and other resources.
The instructions below lead you through the configuration of both these resource types.
Important: By default, Windows has a maximum file path length of 260. As the file paths
within the ZIP are already long, avoid extracting the archive within nested folders with a large
file path. For example, the default path prompted to extract the zip could be similar to c:\
users\[username]\downloads\AZ-220-Microsoft-Azure-IoT-Developer-master - it is
recommended that you shorten this as much as possible, to perhaps c:\az220
Note: The lab activities in this course do NOT include using PowerShell, however, you may see
sample code in reference documents that use PowerShell. If you want to run PowerShell code, you
can use the following instructions to complete the installation steps.
Azure PowerShell is a set of cmdlets for managing Azure resources directly from the PowerShell
command line. Azure PowerShell is designed to make it easy to learn and get started with, but
provides powerful features for automation. Written in .NET Standard, Azure PowerShell works with
PowerShell 5.1 on Windows, and PowerShell 6.x and higher on all platforms.
Warning: You can't have both the AzureRM and Az modules installed for PowerShell 5.1 for Windows
at the same time. If you need to keep AzureRM available on your system, install the Az module for
PowerShell Core 6.x or later. To do this, install PowerShell Core 6.x or later and then follow these
instructions in a PowerShell Core terminal.
1. Decide if you wish to install the Azure PowerShell module for just the current user
(recommended approach) or for all users.
2. Launch the PowerShell terminal of your choice - if you are installing for all users you must
launch an elevated PowerShell session either by either selecting run as administrator or
with the sudo command on macOS or Linux.
3. To only install for the current user, enter the following command:
5. Untrusted repository
6.
7. You are installing the modules from an untrusted repository. If you trust this repository,
change
8. its InstallationPolicy value by running the Set-PSRepository cmdlet.
9.
10. Are you sure you want to install the modules from 'PSGallery'?
11. [Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "N"):
The Az module is a rollup module for the Azure PowerShell cmdlets. Installing it downloads all
of the available Azure Resource Manager modules, and makes their cmdlets available for
use.
Note: If the Az module is already installed, you can update to the latest version using:
Update-Module -Name Az
Many different types of resources will be created during this course, some of which may not have
been registered for use in the current subscription. While some resources are registered automatically
during the first use, others must be registered before they can be used, otherwise errors will be
reported.
The Azure CLI provides a number of commands to help manage resource providers. In this task, you
will ensure that the resource providers required for this course are registered.
1. Using a browser, open the Azure Cloud Shell and login with the Azure subscription you are
using for this course.
2. To view a list of the current state of the resource providers, enter the following command:
3. To see return a list of the namespaces that contains the string Event, run the following
command:
4. To register the resources required for this course, execute the following commands:
8. To view the updated status of the resources, execute the following commands:
You can see the registration status and register a resource provider namespace through the portal. In
this task, you will familiarize yourself with the UI.
4. From the list of subscriptions, select the subscription you want to use for registering the
resource provider.
5. For your subscription, select Resource providers.
6. Look at the list of resource providers, resources can be be registered or unregistered by
clicking the appropriate action.
7. To filter the listed resources, in the search textbox, enter insights.
Notice that the list is filtered as search criteria is entered. The search is also case-insensitive.
Lab no. 4
Tips
1. In the code they say to provide a connectionString, but what they really mean is this Primary
Connection String. I have no idea why they made the one from Outputs to be copied.
3. All the code from Program.cs is in the AllFiles file (what you download).
4. Finally, you need to do some installations in PowerShell and the name of the IoT Hub is
without a domain.
Lab Scenario
Contoso is known for producing high quality cheeses. Due to the company's rapid growth in both
popularity and sales, they want to take steps to ensure that their cheeses stay at the same high level
of quality that their customers expect.
In the past, temperature and humidity data was collected by factory floor workers during each work
shift. The company is concerned that the factory expansions will require increased monitoring as the
new facilities come online and that a manual process for collecting data won't scale.
Contoso has decided to launch an automated system that uses IoT devices to monitor temperature
and humidity. The rate at which telemetry data is communicated will be adjustable to help ensure that
their manufacturing process is under control as batches of cheese proceed through environmentally
sensitive processes.
To evaluate this asset monitoring solution prior to full scale implementation, you will be connecting an
IoT device (that includes temperature and humidity sensors) to IoT Hub.
Note: For the purposes of this lab, you will be creating a .NET Core console application that simulates
the physical IoT device and sensors. Your simulated device will implement the IoT Device SDK and it
will connect to IoT Hub just like a physical device would. Your simulated device will also communicate
telemetry values using the same SDK resources used by a physical device, but the sensor readings
will be generated values rather than real values read from temperature and humidity sensors.
The following resources will be created:
In This Lab
In this lab, you will begin by reviewing the lab prerequisites and you will run a script if needed to
ensure that your Azure subscription includes the required resources. You will then use the Azure
portal to register a device ID with Azure IoT Hub and develop the corresponding simulated device app
in Visual Studio Code. You will then insert the connection string (created by IoT Hub when you
registered the device) into your simulated device code and run the app to test the connection and
verify that telemetry is reaching IoT Hub as intended. The lab includes the following exercises:
Lab Instructions
This lab assumes that the following Azure resources are available:
1. In the virtual machine environment, open a Microsoft Edge browser window, and then
navigate to the following Web address:
2. https://portal.azure.com/#create/Microsoft.Template/uri/https%3A%2F
%2Fraw.githubusercontent.com%2FMicrosoftLearning%2FAZ-220-Microsoft-Azure-IoT-
Developer%2Fmaster%2FAllfiles%2FARM%2Flab04.json
NOTE: Whenever you see the green "T" symbol, for example +++enter this text+++, you can
click the associated text and the information will be typed into the current field within the
virtual machine environment.
3. If prompted to log in to the Azure portal, enter the Azure credentials that you are using for this
course.
NOTE: If the rg-az220 group already exists, the Region field is set to the region used by the
resource group and is read-only.
11. Once the deployment has completed, in the left navigation area, to review any output values
from the template, click Outputs.
i. connectionString
Exercise 2: Create an Azure IoT Hub Device ID using the Azure portal
During this course you will be using IoT Hub's capabilities to help you build a scalable, full-featured
IoT solution for Contoso, but in this lab you are focused on using IoT Hub to establish reliable and
secure bidirectional communications between IoT Hub and your IoT device(s).
In this exercise, you will open your IoT Hub in the Azure portal, add a new IoT device to the device
registry, and then get a copy of the Connection String that IoT Hub created for your device (which you
will use in your device code later in the lab).
Task 1: Create the Device
In the virtual machine environment, open a browser window and navigate to: ++
+https://portal.azure.com+++
If you have more than one Azure account, be sure that you are logged in with the account that
is tied to the subscription that you will be using for this course.
4. On the left-side menu of your IoT Hub blade, under Device management, click Devices.
The device identity (Device ID) is used for device authentication and access control.
It is helpful to establish some form of naming convention for your device identities. There are
several reasons for this, including that the device ID is the value IoT Hub uses represent a
device. Having a device ID that succinctly and informatively differentiates one device from
another is therefor helpful.
Notice that there are three types of authentication available. In this lab you will leverage the
simplest of the three, Symmetric key. X.509 Certificates and their use for authentication will
be covered in later labs.
You could choose the Disable option here during the initial creation of a device if you were
creating the device entry ahead of rollout. You could also choose to set this value to Disable
at some future time if you wished to retain the device record, but prevent the associated
device from connecting to the IoT Hub.
IoT devices may be parented by other devices such as IoT Edge devices. You will get a
chance to implement a Parent-Child device relationship later in the course.
TIP: You may need to refresh manually - click the Refresh button on the page, rather than
refreshing the browser
In order for a device to connect to an IoT Hub, it needs to establish a connection. In this lab, you will
use a connection string to connect your device directly to the IoT Hub (this for of authentication is
often referred to as symmetric key authentication). When using Symmetric key authentication, there
are two connection strings available - one that utilizes the Primary key, the other that uses the
Secondary key. As noted above, the Primary and Secondary keys are only generated once the device
record is saved. Therefore, to obtain one of the connection strings, you must first save the record (as
you did in the task above) and then re-open the device record (which is what you are about to do).
In addition to the device properties, notice that the device detail blade provides access to a
number of device related functions (such as Direct Method and Device Twin) along the top of
the blade.
3. Notice that the key and connection string values are now populated.
The values are obfuscated by default, but you can click the "eye" icon on the right of each
field to toggle between showing and hiding the values.
You can hover your mouse pointer over the button icons to display their names; the Copy
button is on the far right.
Note: You will need to use the Primary Connection String value later in the lab, so you may
want to save it to an accessible location (perhaps by pasting the value into a text editor such
as NotePad).
HostName={IoTHubName}.azure-devices.net;DeviceId=sensor-th-
0001;SharedAccessKey={SharedAccessKey}
The Azure IoT Device SDKs enable you to build apps that run on your IoT devices using the device
client. Tools in the SDK will help you to establish secure connections as well as packaging messages
and implementing communication with your IoT hub. The device SDK will also help you to receive
messages, job, method, or device twin updates from your IoT hub.
In this exercise, you will create a simulated device application using Visual Studio Code and the Azure
IoT Device SDKs. You will connect your device to Azure IoT Hub using the Device ID and Shared
Access Key (Primary Connection String) that you created in the previous exercise. You will then test
your secured device connection and communication to ensure that IoT Hub is receiving the simulated
temperature and humidity values from your device as expected.
Note: You will be writing your simulated device code using the C# programming language, but don't
worry if you are more accustomed to another programming language or if your programming skills are
a bit rusty, the instructions will be easy to follow. The important thing is for you to recognize how the
IoT Device SDK is implemented in code (which is also explained in detail).
2. Navigate to the folder location where you want to create your simulated device application.
The root folder location is not critical, but something easy to find with a short folder path amy
be helpful.
3. At the command prompt, to create a directory named "CaveDevice" and change the current
directory to that directory, enter the following commands:
4. mkdir CaveDevice
cd CaveDevice
This command creates a Program.cs file in your folder, along with a project file.
6. To install the Azure IoT Device SDK and code libraries required for your simulated device
app, enter the following commands:
You will build and test your simulated device app in the next task.
7. To ensure all of the application dependencies are downloaded, enter the following command
dotnet restore
The EXPLORER pane of Visual Studio Code should now list two C# project files:
o CaveDevice.csproj
o Program.cs
Note: If you see a message Required assets to build and debug are missing from
CaveDevice. Add them?, you may click Yes to proceed.
CaveDevice.csproj
Program.cs
In this task, you will use Visual Studio Code to review the contents and purpose of the two application
files.
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Azure.Devices.Client" Version="1.*" />
</ItemGroup>
</Project>
Note: The package version numbers in your file may differ from those shown above, that's
okay.
The project file (.csproj) is an XML document that specifies the type of project that you are
working on. In this case, the project is an Sdk style project.
As you can see, the project definition contains two sections - a PropertyGroup and
an ItemGroup.
The PropertyGroup defines the type of output that building this project will produce. In this
case you will be building an executable file that targets .NET Core 3.1.
The ItemGroup specifies any external libraries that are required for the application. These
particular references are for NuGet packages, and each package reference specifies the
package name and the version. The dotnet add package commands (that you entered in the
steps above) added these references to the project file and the dotnet restore command
ensured that all of the dependencies were downloaded.
Tip: You can learn more about NuGet here.
3. In the EXPLORER pane, click Program.cs.
The Program.cs file should now be opened in the code editor pane.
using System;
namespace CaveDevice
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
This program simply writes "Hello World!" to the command line window. Even though there
isn't much code here, there are still some things worth noting:
o The using area - the source file lists the namespaces that the code is using (this is
typically done at the top of the file as it is here). In this example, the code specifies
that it is using System. This means that when your code uses a component that's
contained within the System namespace, you don't have to explicitly list the
word System within that code line. For example, in the code above,
the Console class is used to write "Hello World!". The Console class is part of
the System namespace, but you didn't have to include the word System when you
used Console. The benefit of this becomes more apparent when you consider that
some namespaces are nested quite deeply (five or more levels is common). Once
again referring to the code above, if you didn't specify using System;, you would have
to write the console line as:
System.Console.WriteLine("Hello World!");
o The namespace area - this specifies that the classes contained with the { } that follow
the namespace are part of that namespace. So, similar to how Console is part of
the System namespace, in the example above, the Program class is part of
the CaveDevice namespace, and its full name is CaveDevice.Program.
o The class area - this defines the contents of the Program class. You can have more
than one class within a single source file
Note: Developers will typically separate classes into their own source file (a single class per
source file), especially in larger projects. However, in the labs for this course, you will be
including multiple classes per file. This will help to simplify the lab instructions and does not
imply best practice.
This will open the integrated Terminal at the bottom of the Visual Studio Code window. You
will be using the Terminal window to compile and run your console application.
6. In the Terminal pane, ensure that the current directory path is set to the CaveDevice folder.
The Terminal command prompt includes the current directory path. The commands that you
enter are run at the current location, so be sure that you are located in the CaveDevice folder.
8. dotnet run
Although this Hello World app demonstrates some basic concepts, it is clearly not a simulated
device. In the next task you will replace this code with the code for your simulated device.
In this task, you will use Visual Studio Code to enter the code that leverages the Azure IoT Device
SDK to connect to your IoT Hub resource.
In the EXPLORER pane, click Program.cs.
In the code editor pane, to create the basic structure of your simulated device application,
enter the following code:
Important: If you are intending to paste the code into a learning environment such as LODS,
there are a few things to be aware of:
o The Type text -> Type clipboard text buffer is limited, so it may truncate the code
that is copied - double check your work and add any missing characters.
o As the Type clipboard text simulates typing, the default settings in Visual Studio
Code will automatically indent code and insert closing braces - ), } and ] - resulting in
duplicate characters and incorrect indentation. These actions can be turned off with
the following settings:
Editor: Auto Closing Brackets
Editor: Auto Indent
o The source can be reformatted at any time by using F1 and entering Format
Document or by pressing SHIFT + ALT + F
To specify the namespaces that the application code will be using, enter the following code:
using System;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure.Devices.Client;
using Newtonsoft.Json;
Notice that as well as specifying System, you are also declaring other namespaces that the
code will be using, such as System.Text for encoding strings, System.Threading.Tasks for
asynchronous tasks, and the namespaces for the two packages you added earlier.
Tip: When inserting code, the code layout may not be ideal. You can have Visual Studio
Code format the document for you by right-clicking in the code editor pane and then
clicking Format Document. You can achieve the same result by opening the Task pane
(press F1) and typing Format Document and then pressing Enter. And on Windows, the
shortcut for this task is SHIFT+ALT+F.
Locate the // INSERT variables below here comment.
To specify the variables that the program is using, enter the following code:
// Contains methods that a device can use to send messages to and receive from an IoT Hub.
private static DeviceClient deviceClient;
// The device connection string to authenticate the device with your IoT hub.
// Note: in real-world applications you would not "hard-code" the connection string
// It could be stored within an environment variable, passed in via the command-line or
// stored securely within a TPM module.
private readonly static string connectionString = "{Your device connection string here}";
Take a moment to review the code (and code comments) that you just entered.
The connectionString variable will contain the connection string for the device we created
earlier. This value is used by the DeviceClient to connect to the IoT Hub. You will specify the
value of connectionStrin in the next step.
Important: You will see examples in this and other labs throughout this course where
connection strings, passwords and other configuration information is hard-coded into the
application. This is done solely to simplify the labs and is not a recommended practice. As
much as possible, security issues like this will be addressed as they come up in the labs.
Security topics (and other important considerations) will be addressed during the instructor
presentation and in your Student Handbook content in a manner that supports the overall flow
of the course. The two may not always align perfectly. As a result, you may be exposed to
topics in the labs that are not covered in detail until later in the course.
As noted within the code comments, connection strings and similar configuration values
should be supplied via alternative means such as environment variables, command-line
parameters or, better still, stored in secured hardware such as Trusted Platform Modules
(TPM).
In the code that you just entered, update the value for connectionString using the Primary
Connection String that you copied from IoT Hub.
To construct the Main method of your simulated device application, enter the following code:
The Main method is the first part of your application that runs once your app is started.
Take a minute to review the code (and code comments) that you just entered.
Take a minute to review the code (and code comments) that you just entered.
o You then start an infinite loop - while(true) {} will repeat until the user hits CTRL+C.
o Within the loop, the first thing you do is read the temperature and humidity from your
sensor and use those values to create a message string - you will add the code
for CreateMessageString in a moment as well.
o Then you create the actual message that will be sent to IoT Hub. You do this by
creating an instance of the Message class from the Azure IoT Device SDK - the data
structure that represents the message that is used for interacting with Iot Hub (IoT
Hub expects a specific message format). The constructor that you use for
the Message class requires that the message string be encoded as a byte array.
o Next, you augment the message with additional properties - here, for example, you
set the temperatureAlert property to true if the currentTemperature is greater than
30, otherwise false.
o Finally, you write the message string to the local console window to show that
telemetry has been sent to IoT Hub, and then wait for 1000 milliseconds (1 second)
before repeating the loop.
This method creates an anonymous object with the temperature and humidity properties and
assigns it to telemetryDataPoint.
/// <summary>
/// This class represents a sensor
/// real-world sensors would contain code to initialize
/// the device or devices and maintain internal state
/// a real-world example can be found here: https://bit.ly/IoT-BME280
/// </summary>
internal class EnvironmentSensor
{
// Initial telemetry values
double minTemperature = 20;
double minHumidity = 60;
Random rand = new Random();
internal EnvironmentSensor()
{
// device initialization could occur here
}
internal double ReadTemperature()
{
return minTemperature + rand.NextDouble() * 15;
}
internal double ReadHumidity()
{
return minHumidity + rand.NextDouble() * 20;
}
}
This is a very simple class that uses random numbers to return values that represent
temperature and humidity. In reality, it is often much more complex to interact with sensors,
especially if you have to communicate with them at a low-level and derive the measurement
value (rather than getting a direct reading in the appropriate units).
Information: You can view a more representative example of the code that interacts with a
simple temperature, humidity and pressure sensor here.
On the File menu, click Save.
Verify that the selected terminal shell is the windows command prompt.
2. In the Terminal view, at the command prompt, enter the following command:
3. dotnet run
This command will build and run the Simulated Device application. Be sure the terminal
location is set to the directory with the CaveDevice.cs file.
Note: If the command outputs a Malformed Token or other error message, then make sure
the Primary Connection String value is configured correctly as the value of
the connectionString variable.
If you receive additional error messages, you can verify that you constructed your code
correctly by referring to completed solution code that is available for reference in
the Final folder for this lab. This Final folder is included with the lab resources files that you
downloaded when setting up your development environment in lab 3. The folder path is:
o Allfiles
Labs
LAB_AK_04-connect-iot-device-to-azure
Final
4. Observe the message string output displayed in the Terminal.
Once the Simulated Device application is running, it will be sending event messages to the
Azure IoT Hub that include temperature and humidity values, and displaying message string
output in the console.
In this task, you will use the Azure CLI to verify telemetry sent by the simulated device is being
received by Azure IoT Hub.
1. In a browser window, use the following Web address to navigate to the Azure Cloud Shell:
+++https://shell.azure.com/+++
If prompted, login with the Azure subscription you are using for this course.
2. In the Azure Cloud Shell, to monitor the event messages that are being received by your IoT
hub, enter the following command:
Be sure to replace the {IoTHubName} placeholder with the name of your Azure IoT Hub.
Note: If you receive a message stating "Dependency update required for IoT extension
version" when running the Azure CLI command, then press y to accept the update and
press Enter. This will allow the command to continue as expected.
The monitor-events command (within the az iot hub Azure CLI module) offers the capability to
monitor device telemetry and other message types sent to an Azure IoT Hub. This can be a
very useful tool during code development, and the convenience of the command-line interface
is also nice.
The --device-id parameter is optional and allows you to monitor the events from a single
device. If the parameter is omitted, the command will monitor all events sent to the specified
Azure IoT Hub.
4. Notice that the az iot hub monitor-events Azure CLI command outputs a JSON representation
of the events that are arriving at your specified Azure IoT Hub.
This command enables you to monitor the events being sent to IoT hub. You are also
verifying that the device is able to connect to and communicate with the your IoT hub.
You should see messages displayed that are similar to the following:
5. Once you have verified that IoT hub is receiving the telemetry, press Ctrl-C in the Azure
Cloud Shell and Visual Studio Code windows.
Ctrl-C is used to stop the running apps. Always remember to shut down unneeded apps and
jobs.
Lab no