How do you update a Cloud Property for an IoT Device in Azure IoT Hub using the SDKs? - azure-iot-hub

Is there a way to update a Cloud Property for an IoT Device in Azure IoT Hub?
The DTDL for the device Cloud Property is:
{
"#id": "dtmi:solutionModel:modelDefinition:rkkkbmsz:brcdv6wcme:DeviceSerialNumber",
"#type": [
"Property",
"Cloud",
"StringValue"
],
"displayName": {
"en": "Device Serial Number"
},
"name": "DeviceSerialNumber",
"schema": "string",
"minLength": 1,
"trimWhitespace": true
},
I am using the Azure IoT SDKs and C#.
deviceClient.UpdateReportedPropertiesAsync(reportedProperties, cancellationToken);
The property is showing up as "_unmodeleddata". The JSON is:
{
"_unmodeleddata": {
"DeviceSerialNumber": "dsn1i90NEW"
},
"_eventtype": "Property",
"_timestamp": "2022-08-14T23:13:45.966Z"
}

The Cloud Property declared in the DTDL model is visible only on the cloud facing side, in other words, there is no either any message exchange pattern between the device and IoT Hub or visibilities.
It based on the IoT Solution, where and how the Cloud Property is stored and managed. In the Azure IoT Hub the Cloud Property can be stored in the device twins such as the property tags.
In the Azure IoT Central, the Cloud Property is using own underlying storage (not the device twin tags) and the REST APIs for handling their values.
Note, that the IoT PnP Device should not send the Cloud Property to the IoT Hub, that's the reason why you are receiving _unmodeleddata for property DeviceSerialNumber

Related

Traverse of linked entities with API client exposed by spring-data-rest

With a generated client by openapi-generator (typescript-axios in my case), it is easy to request an entity that is exposed by spring-data-rest, let's say a Person entity with
const endpoint = PersonEntityControllerApiFactory(configuration);
endpoint.getItemResourcePersonGet('5000')
which gives me an object like
{
"id" : "5000",
"name" : "Mr. Anderson",
"_links" : {
"self": {
"href": "http://localhost:8888/api/persons/5000"
},
"addresses": {
"href": "http://localhost:8888/api/persons/5000/addresses"
}
}
}
Now, is there an easy way to request the addresses collection of that entity with the generated API client (typescript-axios in my case)?
One compicated way comes to my mind to solve this. It's possible to provide a spring data rest projection for Person which inlines ids or complete Address entities into Person. But that would take some extra effort and would be against the HAL / HATEOAS idea.
Another way could be to perform a request on the provided addresses link manually (e.g. by calling axios). But that would question the use of a generated API client in general.

Application Insights not logging SQL Dependencies queries

I'm using an App service hosted in Azure using Asp.Net Core & .Net5. I turned on SQL dependency tracking using below settings in appSettings.config. But I see SQL dependencies logged without SQL command Text. Is there any other settings to enable to see SQL commands in the log?
"ApplicationInsights": {
"InstrumentationKey": "my guid key",
"EnableDependencyTracking": true,
"DependencyTrackingOptions": {
"EnableSqlCommandTextInstrumentation": true
},
"sampling": {
"isEnabled": true,
"maxTelemetryItemsPerSecond": 5
}
},
Your settings in appSettings.config is for Azure Function, not ASP.NET Core applications.
For ASP.NET Core applications, It is now required to opt-in to SQL Text collection by using
services.ConfigureTelemetryModule<DependencyTrackingTelemetryModule>((module, o) => { module. EnableSqlCommandTextInstrumentation = true; });
For more details, you can refer official doc
Advanced SQL tracking to get full SQL Query

Azure AD extract role claim from acesses token and pass it on to the controller

I would like to know how do i extract the role claim from Azure ID accesses token ?
Ideally i would like to get the role claim in a string Variable in ASP.net Core 3.1 controller and then pass this on to my service layer which will do some kind of call to the backend db.
Any sample code would be of great help to me.
If you want to implement Azure AD auth based on app role, please refer to the following steps:
Define your Application Roles
a. In the blade for your application in Azure Portal, click Manifest.
b. Edit the manifest by locating the appRoles setting and adding your Application Roles. The role definitions are like the following json.
"appRoles": [
{
"allowedMemberTypes": [
"User"
],
"description": "User readers can read basic profiles of all users in the directory",
"displayName": "UserReaders",
"id": "a816142a-2e8e-46c4-9997-f984faccb625",
"isEnabled": true,
"lang": null,
"origin": "Application",
"value": "UserReaders"
},
{
"allowedMemberTypes": [
"User"
],
"description": "Directory viewers can view objects in the whole directory.",
"displayName": "DirectoryViewers",
"id": "72ff9f52-8011-49e0-a4f4-cc1bb26206fa",
"isEnabled": true,
"lang": null,
"origin": "Application",
"value": "DirectoryViewers"
}
],
c. Save the manifest.
assign app role to user or groups
Besides, please note that if you want to assign app role to group, you need to have Azure AD Premium license.
Code
a. Configure application to get role claim
please add following code in startup.cs
public void ConfigureServices(IServiceCollection services)
{
// This flag ensures that the ClaimsIdentity claims collection will be built from the claims in the token
JwtSecurityTokenHandler.DefaultMapInboundClaims = false;
// The following lines code instruct the asp.net core middleware to use the data in the "roles" claim in the Authorize attribute and User.IsInrole()
services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
{
// The claim in the Jwt token where App roles are available.
options.TokenValidationParameters.RoleClaimType = "roles";
});
}
b. get role claim
[Authorize(Roles = <your role>")] // In controllers
// or
User.IsInRole("<your role>"); // In methods
For more details, please refer to the document and the sample

How do I deregister device in MFP

I am sending push notification via an external script and capturing the response that is return from MobileFirst. The response is always 200 and a messageId is in the response JSON object
How can I simulate a error condition?
I used the MFP API to remove the subscription, removing the device from the device tab in the MFP console. However, I can still send and receive push notification for that deviceID .
Unsubscribing from the tag subscription (which you have subscribed in the code) does not clear all subscriptions. A default Push.ALL tag subscription stays in the DB. This is why you are able to still send notifications.
You can remove the device registration either using the SDK ( as mentioned by Gaurab) or use the REST API call to do this.
Details here: Push Device Registration Delete
I assume that you are using IBM MobileFirst v8.0.
You need to implement these API in client side to unregister the device or unsubscribe from tags.
Unregister the device from push notification service instance.
MFPPush.unregisterDevice(
function(successResponse) {
alert("Unregistered successfully");
},
function() {
alert("Failed to unregister");
}
);
Unsubscribe from tags.
var tags = ['sample-tag1','sample-tag2'];
MFPPush.unsubscribe(
tags,
function(tags) {
alert("Unsubscribed successfully");
},
function() {
alert("Failed to unsubscribe");
}
);

How to get mobile reistration ID using GSM Titanium?

I am developing android app in titanium,by button click event I have to get registration ID from GCM. how to do that I am new to titanium.
I followed this http://iamyellow.net/post/40100981563/gcm-appcelerator-titanium-module, but I am not able to understand how to implement?
Thanks in advance.
To implement push notification, you should use Ti.CloudPush module.
You can achieve GCM Push Notification in 6 easy steps
Setting up Google Cloud Messaging
Push Configuration in ACS Console
CloudPush Module Implementation
Retrieve Device Token
Cloud User Login
Subscribe a Channel
1. Setting Up GCM
To use GCM, you need to create a Google API project to obtain a Google API key and GCM sender ID. For instructions on creating and obtaining these items, see Android Developer: Getting Started with GCM and follow the directions in "Creating a Google API Project", "Enabling the GCM Service" and "Obtaining an API Key".
We will use our Project number as GCM Sender ID.
When creating a new server key, you are asked for a list of IP addresses to accept requests from. Do not enter any information in the textbox and click Create to accept all IP addresses.
2. Push Configuration in the ACS
Go to your apps, then go to My Apps -> Manage ACS -> DEVELOPMENT -> Settings/Android Push Configuration and enter your Google API key in the Google Cloud Messaging (GCM) API Key textbox and GCM sender ID in the Google Cloud Messaging (GCM) Sender ID textbox. (which we got from Step 1)
3. CloudPush Module Implementation
Add CloudPush module into your application.
To add CloudPush module, you need to add <module platform="android">ti.cloudpush</module> in your TiApp.xml. Then require the module in your javascript file using var CloudPush = require('ti.cloudpush');.
To use push notifications, in the tiapp.xml file, you need to specify push type to GCM.
To do this go to your tiapp.xml.
Add/edit the following lines
<property name="acs-push-type-development" type="string">gcm</property>
<property name="acs-push-type-production" type="string">gcm</property>
<property name="acs-push-type" type="string">gcm</property>
4. Retrieve Device Token
Call the retrieveDeviceToken method before setting the enabled property to true to enable the device to receive push notifications. You must call retrieveDeviceToken before any other CloudPush API call or else the device will not receive push notifications.
var CloudPush = require('ti.cloudpush');
var deviceToken = null;
CloudPush.retrieveDeviceToken({
success: function deviceTokenSuccess(e) {
Ti.API.info('Device Token: ' + e.deviceToken);
deviceToken = e.deviceToken;
},
error: function deviceTokenError(e) {
alert('Failed to register for push! ' + e.error);
}
});
5. Cloud User Login
Before subscribe for Push Notification, cloud user should logg in.
Cloud.Users.login({
login: username,
password: password
}, function (e) {
if (e.success) {
alert("login success");
} else {
alert('Error: ' + ((e.error && e.message) || JSON.stringify(e)));
}
});
6. Subscribe a Channel
You need to subscribe to a channel to get the pushnotification. Push notification will be sending to the particular channel and it will be reached to all users who subscribed to the channel.
if(deviceToken != null){
Cloud.PushNotifications.subscribe({
channel: 'yourchannelName',
device_token: deviceToken,
type: 'gcm' //here i am using gcm, it is recommended one
}, function (e) {
if (e.success) {
alert('Subscribed for Push Notification!');
} else {
alert('Subscribe error:' + ((e.error && e.message) || JSON.stringify(e)));
}
});
} else {
alert('You need to retrieve the device token first');
}
Now you can send push notification. To do this go to My Apps -> Manage ACS -> DEVELOPMENT -> Push Notifications, here you can see number of clients subscribed for push notification, channels etc. You can send the push notification from there.
UPDATE : Attention!!
GCM supports devices that run Android 2.2 and later
Google Play Store application should be installed in your device.
For pre-4.0 devices, the user is required to set up their Google account.
You're using an android device for testing, not emulator(Since you can't install Google Play in your emulator).
Google play service is running on your device.
The following links will help you:
Titanium.CloudPush
Android SDK Titanium
ACS Push Notification Using GCM