web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Microsoft Dynamics CRM (Archived)

Can I Write  a Custom Plugin to send Data to Azure Service Bus Topic

(1) ShareShare
ReportReport
Posted on by 67

Can I Write  a Custom Plugin to send Data to Azure Service Bus Topic, Where I Can see the OOB plugins like contact, account were there in internet.

My Question; 

How I Can Register a custom plugin under Service endpoint created for Service bus

The same example for OOB Plugin Has registered to send data to Azure Service Bus

http://sachinkumar.strikingly.com/blog/registering-service-endpoint-for-azure-service-bus-topic-in-microsoft

I have written Custom Code but I am Confused how to register my custom plugin under Service endpoint??? Can Any one help on this

The code is below

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xrm.Sdk;
using System.IO;
using System.Xml;
using System.Runtime.Serialization;
using Microsoft.ServiceBus.Messaging;
using Newtonsoft.Json;
using System.Security;


namespace AccWildcatToSAPH2SFLCValuesTransfer
{
public class SAPH2SFLCValuesTransfer : IPlugin
{
Entity location = null;
Entity currentValues = null;
string flc = string.Empty;
//decimal higestH2S = 0;
string l_s_error_log = string.Empty;
string l_s_flc = string.Empty;
decimal l_s_higestH2S = 0m;

public void Execute(IServiceProvider serviceProvider)
{
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = factory.CreateOrganizationService(context.UserId);
ITracingService tracing = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

if (context.Depth > 1)
{
tracing.Trace("Depth is more than one ");
return;
}
if (context.PrimaryEntityName == "hss05_wellsite" && (context.MessageName == "Update"))
{
if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
{
location = (Entity)context.InputParameters["Target"];
currentValues = service.Retrieve(context.PrimaryEntityName, context.PrimaryEntityId, new Microsoft.Xrm.Sdk.Query.ColumnSet("hss05_functionallocationcode","hss05_highesth2sreadingatlocation"));

if (location.Attributes.Contains("hss05_highesth2sreadingatlocation"))
{
if(currentValues.Attributes.Contains("hss05_functionallocationcode") && currentValues.Attributes["hss05_functionallocationcode"]!= null)
{
l_s_flc = location.GetAttributeValue<string>("hss05_functionallocationcode");
}

if(currentValues.Attributes.Contains("hss05_highesth2sreadingatlocation") && currentValues.Attributes["hss05_highesth2sreadingatlocation"]!= null)
{
l_s_higestH2S = location.GetAttributeValue<decimal>("hss05_highesth2sreadingatlocation");
}

var messageData = new
{
flc = l_s_flc,
higestH2S = l_s_higestH2S
};
string connectionString = "Endpoint=sb://notificationdetailqa.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=vicGNY8RwUWWtdaWi5U779/RmI+ino1mlRavPCECjBI=";
string senderTopicName = "notificationcreation";



//string connectionString = GetConfigDataString(_pluginConfiguration, "connectionString");
//string senderTopicName = GetConfigDataString(_pluginConfiguration, "senderTopicName");

var client = TopicClient.CreateFromConnectionString(connectionString, senderTopicName);
Stream stream = GenerateStreamFromString((JsonConvert.SerializeObject(new { NotificationDetails = messageData })));
Console.WriteLine(stream);
var xmlmessage = new BrokeredMessage(stream);
client.Send(xmlmessage);
throw new InvalidPluginExecutionException("Succesfully Executed");
//location["hss05_notificationstatusflag"] = "3 : Notification Details Sent to SAP";

}
}

}
}

public static string GetConfigDataString(XmlDocument doc, string label)
{
return GetValueNode(doc, label);
}
private static string GetValueNode(XmlDocument doc, string key)
{
XmlNode node = doc.SelectSingleNode(String.Format("Settings/setting[@name='{0}']", key));
if (node != null)
{
return node.SelectSingleNode("value").InnerText;
}
return string.Empty;
}


public void WriteLog(string strLog)
{
StreamWriter log;
FileStream fileStream = null;
DirectoryInfo logDirInfo = null;
FileInfo logFileInfo;

string logFilePath = "D:\\Wildcat_SAP_log\\";
logFilePath = logFilePath + "Log-" + System.DateTime.Today.ToString("MM-dd-yyyy") + "." + "txt";
logFileInfo = new FileInfo(logFilePath);
logDirInfo = new DirectoryInfo(logFileInfo.DirectoryName);
if (!logDirInfo.Exists) logDirInfo.Create();
if (!logFileInfo.Exists)
{
fileStream = logFileInfo.Create();
}
else
{
fileStream = new FileStream(logFilePath, FileMode.Append);
}
log = new StreamWriter(fileStream);
log.WriteLine(strLog);
log.Close();
}

private static Stream GenerateStreamFromString(string s)
{
MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
writer.Write(s);
writer.Flush();
stream.Position = 0;
return stream;

}


}
}

*This post is locked for comments

I have the same question (0)
  • Suggested answer
    Kalpavruksh D365 CoE Profile Picture
    2,545 on at
    Hi,
    IServiceEndpointNotificationService is use for invoking the service endpoint.
     
     6675.MicrosoftTeams_2D00_image-_2800_8_2900_.png
  • manojmashetty Profile Picture
    67 on at

    I tried but I am getting the below Message

    <Message>Could not load file or assembly 'Microsoft.ServiceBus, Version=2.7.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.</Message>

    3660.Capture.JPG

    My Code is below

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using Microsoft.Xrm.Sdk;
    using System.IO;
    using System.Xml;
    using System.Runtime.Serialization;
    using Microsoft.ServiceBus.Messaging;
    using Newtonsoft.Json;
    using System.Security;


    namespace AccWildcatToSAPH2SFLCValuesTransfer
    {
    public class SAPH2SFLCValuesTransfer : IPlugin
    {
    Entity location = null;
    Entity currentValues = null;
    string flc = string.Empty;
    //decimal higestH2S = 0;
    string l_s_error_log = string.Empty;
    string l_s_flc = string.Empty;
    decimal l_s_higestH2S = 0m;

    public void Execute(IServiceProvider serviceProvider)
    {
    IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
    IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
    IOrganizationService service = factory.CreateOrganizationService(context.UserId);
    ITracingService tracing = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
    IServiceEndpointNotificationService cloudservice = (IServiceEndpointNotificationService)serviceProvider.GetService(typeof(IServiceEndpointNotificationService));

    if (context.Depth > 1)
    {
    tracing.Trace("Depth is more than one ");
    return;
    }
    if (context.PrimaryEntityName == "hss05_wellsite" && (context.MessageName == "Update"))
    {
    if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
    {
    Guid serviceEndpointId = new Guid("4c808e0a-f798-e911-8332-e6a7fe5887f7");
    location = (Entity)context.InputParameters["Target"];
    string response = cloudservice.Execute(new EntityReference("serviceendpoint", serviceEndpointId), context);

    currentValues = service.Retrieve(context.PrimaryEntityName, context.PrimaryEntityId, new Microsoft.Xrm.Sdk.Query.ColumnSet("hss05_functionallocationcode", "hss05_highesth2sreadingatlocation"));

    if (location.Attributes.Contains("hss05_highesth2sreadingatlocation"))
    {
    if (currentValues.Attributes.Contains("hss05_functionallocationcode") && currentValues.Attributes["hss05_functionallocationcode"] != null)
    {
    l_s_flc = location.GetAttributeValue<string>("hss05_functionallocationcode");
    }

    if (currentValues.Attributes.Contains("hss05_highesth2sreadingatlocation") && currentValues.Attributes["hss05_highesth2sreadingatlocation"] != null)
    {
    l_s_higestH2S = location.GetAttributeValue<decimal>("hss05_highesth2sreadingatlocation");
    }

    var messageData = new
    {
    flc = l_s_flc,
    higestH2S = l_s_higestH2S
    };
    string connectionString = "Endpoint=sb://notificationdetailqa.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=vicGNY8RwUWWtdaWi5U779/RmI+ino1mlRavPCECjBI=";
    string senderTopicName = "notificationcreation";

    //string connectionString = GetConfigDataString(_pluginConfiguration, "connectionString");
    //string senderTopicName = GetConfigDataString(_pluginConfiguration, "senderTopicName");


    var client = TopicClient.CreateFromConnectionString(connectionString, senderTopicName);
    Stream stream = GenerateStreamFromString((JsonConvert.SerializeObject(new { NotificationDetails = messageData })));
    Console.WriteLine(stream);
    var xmlmessage = new BrokeredMessage(stream);
    client.Send(xmlmessage);
    throw new InvalidPluginExecutionException("Succesfully Executed");
    //location["hss05_notificationstatusflag"] = "3 : Notification Details Sent to SAP";

    }
    }

    }
    }

    public static string GetConfigDataString(XmlDocument doc, string label)
    {
    return GetValueNode(doc, label);
    }
    private static string GetValueNode(XmlDocument doc, string key)
    {
    XmlNode node = doc.SelectSingleNode(String.Format("Settings/setting[@name='{0}']", key));
    if (node != null)
    {
    return node.SelectSingleNode("value").InnerText;
    }
    return string.Empty;
    }


    public void WriteLog(string strLog)
    {
    StreamWriter log;
    FileStream fileStream = null;
    DirectoryInfo logDirInfo = null;
    FileInfo logFileInfo;

    string logFilePath = "D:\\Wildcat_SAP_log\\";
    logFilePath = logFilePath + "Log-" + System.DateTime.Today.ToString("MM-dd-yyyy") + "." + "txt";
    logFileInfo = new FileInfo(logFilePath);
    logDirInfo = new DirectoryInfo(logFileInfo.DirectoryName);
    if (!logDirInfo.Exists) logDirInfo.Create();
    if (!logFileInfo.Exists)
    {
    fileStream = logFileInfo.Create();
    }
    else
    {
    fileStream = new FileStream(logFilePath, FileMode.Append);
    }
    log = new StreamWriter(fileStream);
    log.WriteLine(strLog);
    log.Close();
    }

    private static Stream GenerateStreamFromString(string s)
    {
    MemoryStream stream = new MemoryStream();
    StreamWriter writer = new StreamWriter(stream);
    writer.Write(s);
    writer.Flush();
    stream.Position = 0;
    return stream;

    }


    }
    }

    Why I am trying to debug Even it is not going to Execute Method and throwing  <Message>Could not load file or assembly 'Microsoft.ServiceBus, Version=2.7.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.</Message>

    Could you please let me know why I a m getting this error and Where should load I Load Microsoft.Servicebus assembly other than in the bin folder?

  • chikhaleankush Profile Picture
    547 on at

    I tried and works for me. I can see context as message in my service bus queue. I wan to achieve slightly different, rather than context I wish to send custom message let's say json object. Can I do that using serviceendpoint.execute method?

  • Zafar.Khan Profile Picture
    10 on at

    Did you find the Solution for this. I am also looking for the same

  • BP-27061936-0 Profile Picture
    3 on at
    @chikhaleankush  Did you ever find a way to send something other than the IPluginExecutionContext?  I would like to send my own "custom" JSON message.

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > 🔒一 Microsoft Dynamics CRM (Archived)

#1
SA-08121319-0 Profile Picture

SA-08121319-0 4

#1
Calum MacFarlane Profile Picture

Calum MacFarlane 4

#3
Alex Fun Wei Jie Profile Picture

Alex Fun Wei Jie 2

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans