CRM 2013-Azure Integration issue - azure

We are facing problem in CRM 2013-Azure Integration.
Below lines explains the CRM 2013 –Azure integration.
1.Plugin will read the data from CRM record and send the data to Azure Service Bus Queue.
2.Azure worker role will read the data from service bus queue and send it to WCF service which will insert/update the data in Azure DB.
When we call the send method to send the data to service bus queue we are getting “channel open did not complete within the specified timeout” error. Below is the code snippet of Azure Service Bus call.
Uri runtimeUri = ServiceBusEnvironment.CreateServiceUri(ConfigurationManager.AppSettings["schemaName"], ConfigurationManager.AppSettings["serviceNamespace"], string.Empty);
MessagingFactory mf = MessagingFactory.Create(runtimeUri,TokenProvider.CreateSharedAccessSignatureTokenProvider(ConfigurationManager.AppSettings["keyName"], ConfigurationManager.AppSettings["sharedAccessKey"]));
sendClient = mf.CreateQueueClient(ConfigurationManager.AppSettings["queuePath"]);
BrokeredMessage helloMessage = new BrokeredMessage(list of CRM data));
helloMessage.MessageId = Guid.NewGuid().ToString();
sendClient.Send(helloMessage);
But when we do the same operation from local(Outside CRM) it is working fine. Please suggest us some solution if you have any.

Related

Connect Device from Azure IoT Central to Azure Digital Twin

I have a device in Azure IoT central that has been receiving data. How can I send its telemetry data to its Azure Digital Twin so that they are connected?
You first need to pass the data from Azure IoT Central device to a cloud end point such as Service Bus or Event Hub. You can create an Azure Function and trigger it based on the end point you passed the data to. Within the Azure function you can create the code to push data to the Azure Digitial Twins.
Refer the following resources for data export
Export IoT data to Service Bus
Export IoT Hub data to Event Hubs
Once you have the data routed, use either of the following resources based on your clod end point to build Azure function
Run an Azure function when a Service Bus queue or topic message is created
Respond to events send to Event Hub event stream
Once you have the data flow into the Azure function, before you push the data to the Azure Digital Twin, ensure you have a Model created on the Azure digital twin representing you IoT device data.
If you haven't already done so, refer the Upload a model section to create a Data model for your Azure Digital Twin. Once you have the data model created, you can create Azure Digital Twin either from the Azure Digital Twin explorer or though the code Create Azure Digital Twin.
Once you have the Digital Twin created, you can then push data from your Azure function you created earlier. Here is the code I have tested through ServiceBus Queue trigger.
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Azure;
using Azure.Core.Pipeline;
using Azure.DigitalTwins.Core;
using Azure.Identity;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace RajIoTCentral.Function
{
public class RajIoTCentralServiceBusQueue
{
private static readonly HttpClient httpClient = new HttpClient();
private static string adtServiceUrl = "https://<yourdigitaltwinendpoint>.digitaltwins.azure.net";
[FunctionName("RajIoTCentralServiceBusQueue")]
public async Task RunAsync([ServiceBusTrigger("iotcentraldata", Connection = "RajIoTDataServiceBus_SERVICEBUS")] string myQueueItem, ILogger log)
{
log.LogInformation($"C# ServiceBus queue trigger function processed message: {myQueueItem}");
JObject deviceMessage = (JObject)JsonConvert.DeserializeObject(myQueueItem);
try
{
var temperature = deviceMessage["telemetry"]["temperature"];
var deviceId = "TemperatureSensor";
log.LogInformation($"Temperature is:{temperature.Value<double>()}");
var credentials = new DefaultAzureCredential();
DigitalTwinsClient client = new DigitalTwinsClient(
new Uri(adtServiceUrl), credentials, new DigitalTwinsClientOptions
{ Transport = new HttpClientTransport(httpClient) });
log.LogInformation($"ADT service client connection created.");
var updateTwinData = new JsonPatchDocument();
updateTwinData.AppendReplace("/Temperature", temperature.Value<double>());
await client.UpdateDigitalTwinAsync(deviceId, updateTwinData);
}
catch (Exception ex) { log.LogInformation("No temperature in the telemetry data"); }
}
}
}
In the above code, I am pushing the Temperature value I received from the Service Bus queue on to the Azure Digital Twin.
Please refer the following resources for more information on the above code and the approach
Ingest IoT Hub telemetry into Azure Digital Twins
Build out an end-to-end solution
A similar post has been addressed on the Microsoft Q&A forum in the past. Please refer the question here Unable to view result of pipeline which trasport a value from a sensor to digital twin

Azure Event Hub - Can't understand Java flow

from Microsoft EventHub Java SDK examples (https://learn.microsoft.com/en-us/azure/event-hubs/event-hubs-java-get-started-send), these are the steps that needs to be taken to be able to consume messages from an Even-Hub via the java SDK :
1.Create a storage account
2.Create a new class called EventProcessorSample. Replace the placeholders with the values used when you created the event hub and storage account:
3.
String consumerGroupName = "$Default";
String namespaceName = "----NamespaceName----";
String eventHubName = "----EventHubName----";
String sasKeyName = "----SharedAccessSignatureKeyName----";
String sasKey = "----SharedAccessSignatureKey----";
String storageConnectionString = "----AzureStorageConnectionString----";
String storageContainerName = "----StorageContainerName----";
String hostNamePrefix = "----HostNamePrefix----";
ConnectionStringBuilder eventHubConnectionString = new ConnectionStringBuilder()
.setNamespaceName(namespaceName)
.setEventHubName(eventHubName)
.setSasKeyName(sasKeyName)
.setSasKey(sasKey);
There are several things i don't understand about this flow -
A. Why is a storage account required? Why does it needs to be created only when creating a consumer and not when creating the event hub itself?
B. What is 'hostNamePrefix' and why is it required?
C. More of a generalaztion of A, but i am failing to understand why is this flow so complicated and needs so much configuration. Event Hub is the default and only way of exporting metrics/monitoring data from Azure which is a pretty straightforward flow - Azure -> Event Hub -> Java Application. Am i missing a simpler way or a simpler client option?
All your questions are around consuming events from Event hub.
Why is a storage account required?
Read the event only once: Whenever your application will read event from event hub, you need to store the offset(identifier for the amount of event already read) value somewhere. The storing of this information is known as 'CheckPointing' and this information will be stored in Storage Account.
Read the events from starting everytime your app connects to it: In this case, your application will keep on reading the event from very beginning whenever it will start.
So, the storage account is required to store the offset value while consuming the events from event hub in case if you want to read event only once.
Why does it needs to be created only when creating a consumer and not
when creating the event hub itself?
As it depends upon the scenario, whether you want to read your events only once or every time your app starts and that's why storage account is not required while creating event hub.
What is 'hostNamePrefix' and why is it required?
As the name states 'hostNamePrefix', this is name for your host. The host means the application which is consuming the events. And it's a good practice to make use of GUID as a hostNamePrefix. HostNamePrefix is required by the event hub to manage the connection with the host. In case, if you have 32 partitions, and you have deployed 4 instances of your same application then 8 partition each will be assigned to your 4 different instances and that's where the host name helps the event hub to manage the information about the connection of the respective partitions to their host.
I will suggest you to read this article on event hub for clear picture of the event processor host.

Status change of Azure Service Bus

I have created a SB in the azure portal. By default the status is showing as Active. Let me have a scenario where i want to change the status of this SB, any idea on how to do that? Any pointers will be very helpful. We have 2 service bus and one needs to be active at a time. So how can we manage that?
By default the status is showing as Active. Let me have a scenario where i want to change the status of this SB, any idea on how to do that?
Service Bus works as a container or a namespace. The status of Azure Service Bus is internal used, we can't change it on Azure portal or using any API.
As #Sean Feldman said, we can only enable or disable the entities(queues or topics) in the Service Bus in the properties panel.
To disable all the queues and topics in a Service Bus, you could using following code.
string connectionString = "your connection string of service bus";
var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);
IEnumerable<QueueDescription> queueList = namespaceManager.GetQueues();
foreach (QueueDescription qd in queueList)
{
qd.Status = EntityStatus.Disabled;
namespaceManager.UpdateQueue(qd);
}
IEnumerable<TopicDescription> topicList = namespaceManager.GetTopics();
foreach (TopicDescription td in topicList)
{
td.Status = EntityStatus.Disabled;
namespaceManager.UpdateTopic(td);
}

Azure ioT and Event Hub?

I am trying to read the events that my device is sending. I am using azure npm lib to read the what i think is right.
Ok so first, under my Azure ioT Hub account for that service there is a tab call Messaging. There is something called "Event Hub-compatible name" and "Event Hub-compativle endpoint". Do i have to create a new Event hub with the name of "Event Hub-compatible name" or what? I am a bit confused :D
If not what is the connection string and topic and so on?
Here is how the code is now...
var azure = require('azure');
var serviceBusService = azure.createServiceBusService("Endpoint=XXXXXXXXXX.servicebus.windows.net/");
var isWaiting = false;
function waitForMessages(){
console.log("Checking Queue...");
isWaiting = true;
serviceBusService.receiveQueueMessage("messages","events",function (error, receivedMessage){
console.log(error);
console.log(receivedMessage);
isWaiting = false;
});
}
// Start messages listener
setInterval(function () {
if(!isWaiting){
waitForMessages();
}
}, 200);
The Event Hub-compatible name does not mean that you have to create a Event Hub with the same name.
IOT Hub provides an endpoint that is backward compatible with Event Hub API. I think the actual implementation is a little more complex, but you can think of IOT Hub as inheriting from or at least an implementation of Event Hubs. Use this Event Hub compatible name with any Event Hub SDKs or code examples as part of the connection string.
For explaining the concepts of Event Hub-compatible name & Event Hub-compatible endpoint, you can refer to the section How to read from Event Hubs-compatible endpoints of the offical doc Azure IoT Hub developer guide. You can use the Azure Service Bus SDK for .NET or the Event Hubs - Event Processor Host to read events from IoT Hub in C#.
Otherwise, there are two Azure IoT SDKs for NodeJS using connection string: Azure IoT Service SDK (API Reference) & Azure IoT Device SDK (API Reference).
The connection string that you can find it at the one policy of the tab Shared Access Policies in the All settings, please see the pic below from the doc Tutorial: Get started with Azure IoT Hub.
According to your needs for reading events from IoT Hub, you can follow these samples to code using Azure IoT SDKs for NodeJS.
Using Azure IoT Service SDK to list the deviceIds registed in your IoT Hub, please see the sample https://github.com/Azure/azure-iot-sdks/blob/master/node/service/samples/registry_sample.js.
Using Azure IoT Device SDK to monitor events from IoT Hub, please see the sample https://github.com/Azure/azure-iot-sdks/blob/master/node/device/samples/remote_monitoring.js.
Hope it helps. Any concern, please feel free to let me know.
You can use the Event Hubs SDK for Node.js to see events/messages sent by your device to your IoT Hub:
https://www.npmjs.com/package/azure-event-hubs
The client object of the event hubs SDK can accept an IoT Hub connection string, so you don't need to use the Event Hubs connection string.
If you're just trying to debug your device and want to verify that it's actually sending messages, you can use the tool called iothub-explorer provided with the Azure IoT Hub SDK:
https://github.com/Azure/azure-iot-sdks/tree/master/tools/iothub-explorer
Also a couple of clarifications regarding the previous answer: the Service SDK allows to send messages to devices, and to read the "feedback" message that the device sends, which is used to know if the device accepted or rejected the command message but contains no data. It doesn't help to read data events sent by the device.
Connect to the IoT Hub to receiving the data:
var protocol = 'amqps';
var eventHubHost = '{your event hub-compatible namespace}';
var sasName = 'iothubowner';
var sasKey = '{your iot hub key}';
var eventHubName = '{your event hub-compatible name}';
var numPartitions = 2;
Protocol
var protocol = 'amqps';
It is the Event Hub-compatible endpoint: sb://abcdefnamespace.servicebus.windows.net/
but without the sb:// and .service windows.net/
Like that: abcdefnamespace
var eventHubHost = '{your event hub-compatible namespace}';
Its so OK
var sasName = 'iothubowner';
Primary key, like this: 83wSUdsSdl6iFM4huqiLGFPVI27J2AlAkdCCNvQ==
var sasKey = '{your iot hub key}';
Name like this: iothub-ehub-testsss-12922-ds333s
var eventHubName = '{your event hub-compatible name}';
Its so OK
var numPartitions = 2;
Every Iot Hub instance comes with a built in endpoint that is compatible with Event Hubs. The Event Hub compatible endpoint you see in the Azure portal would be the connection string pointing to the Event Hub instance from where you can read all the messages sent to your Iot Hub instance.
You can use this connection string to the instantiate the EventHubConsumerClient class from the #azure/event-hubs library and read your messages.
In the event of a failover, it is said that this backing built-in endpoint would change. So, you would have to fetch the new connection string and restart the process. Another option is to use the sample code in the azure-iot-samples-node repo to get the Event Hub compatible connection string by passing in the Iot Hub connection string and then use the #azure/event-hubs library to read your messages. See more in Read from the built-in endpoint

Alerts for exceptions in an Azure worker role

Is there an easy way to send an alert or notification in the Azure Management portal if a worker role throws an exception or has an error?
I am using Azure 2.5
I have tracing and diagnostics all set up and can view the logs in the server explorer of Visual studio, but is there anyway to set an alert if for example and error message appears in the logs.
I know you can set up alerts for monitoring metrics in the Management portal is there an easy way to add metrics for errors and exceptions?
Or someway to get C# exception code to create notifications or alerts in the Azure Management portal?
I ended up using email alerts and Application insights to monitor my worker role in the Azure portal. I created an Application insight on the portal according to these instructions.
Using the Nuget package manager in Visual Studio I added the Application insights API, Application insights for website (even though my worker role is not a web app) and the Application insights trace listener.
I then created an Application insight instance by adding the following to the worker role.
private TelemetryClient tc = new TelemetryClient();
And then adding this to the onStart method.
tc.Context.InstrumentationKey = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXX";
You can find your insturmentation Key in the Azure Portal.
After running, or deploying my worker role I could then view all of my Trace.TraceInformation and TraceError statements in the Azure portal as well as add tc.TrackError and tc.TrackEvent statements to track errors and events.
TrackError worked perfectly for notifying me when an exception was thrown.
I use SendGrid for sending emails through Azure because it's free. Here is what I would do something like below:
try
{
//....
}
catch(Exception ex)
{
MailMessage mailMsg = new MailMessage() {
//Set your properties here
};
// Add the alternate body to the message.
mailMsg.AlternateViews.Add(
AlternateView.CreateAlternateViewFromString(Body
, new System.Net.Mime.ContentType("text/html")));
SmtpClient smtpClient = new SmtpClient(
ServerGlobalVariables.SmtpServerHost
, Convert.ToInt32(587));
System.Net.NetworkCredential credentials =
new System.Net.NetworkCredential(
ServerGlobalVariables.SmtpServerUserName
, ServerGlobalVariables.SmtpServerPassword);
smtpClient.Credentials = credentials;
smtpClient.Send(mailMsg);
}
Please note that I store my credits in a globalvariables class called ServerGlobalVariables. Also, I send my emails formatted as HTML, but you don't have to do that.

Resources