TriggeredFunctionData null when entering Webjob SDK function - rabbitmq

I am trying to use a rabbitMQ extension to webjob SDK (https://github.com/Sarmaad/WebJobs.Extensions.RabbitMQ) to have it trigger when something is put on the queue.
The triggering works fine, but the content is never passed into my function.
I downloaded the source for the extension so i could debug inside it and I see that the content of the queue is delivered successfully and the extension repackages it into a TriggeredFunctionData object. The object is then passed to my function through the Webjob executor.
However as I step into my function this object is null.
Listener method from extension lib:
_consumer.Received += (sender, args) =>
{
var triggerValue = new RabbitQueueTriggerValue {MessageBytes = args.Body};
if (args.BasicProperties != null)
{
triggerValue.MessageId = args.BasicProperties.MessageId;
triggerValue.ApplicationId = args.BasicProperties.AppId;
triggerValue.ContentType = args.BasicProperties.ContentType;
triggerValue.CorrelationId = args.BasicProperties.CorrelationId;
triggerValue.Headers = args.BasicProperties.Headers;
}
var result = _executor.TryExecuteAsync(new TriggeredFunctionData{TriggerValue = triggerValue}, CancellationToken.None).Result;
When debugging I can see that Triggervalue contains my message data.
My function being executed:
public static async Task ProcessRabbitMqTopicStatusMessage([RabbitQueueTrigger("tempq")]
[RabbitQueueBinder("myexchange", "myroutingkey", "myerrorq",autoDelete:true,durable:true, execlusive:false)]
TriggeredFunctionData message,
TextWriter logger)
{
if (message != null)
{
}
}
This method is triggered successfully, but message is always null.
Any suggestions?

Your user function shouldn't bind directly to TriggeredFunctionData. That's an intermediate object used by the triggering infrastructure which gets converted to final destination objects to match your function's signature.
The binding author (in this case, RabbitMQ at the GitHub site you linked to) is what defines the possible objects that it can bind to.
From http://www.sarmaad.com/2016/11/azure-webjobs-and-rabbitmq/, here was an example of their usage:
public void IntegrateApprovedProductToMarketPlace(
[RabbitQueueBinder("product", "product.approved", "error")]
[RabbitQueueTrigger("integration-product-approved")]
ProductApproved message, TextWriter log)
{
[handle message here]
}

Related

.NET Core service startup configuration

I've been assigned to upscale a project built by a former coworker. I'm not a .NET Core specialist, I understand most of it as is similar to any other language, but I'm having trouble understanding the Fluent configuration made at startup.
At the Startup.cs, there is this function declared:
public void Configure(IApplicationBuilder app)
At some point, there is an initialzation of a service that listens for something. I can manage that from the already initialized class/service, but I'd like to understand what is this:
app.UseRawRequestRequestBodyHandler(options => options
.Handlers
.AddRange(new[] {
new RawRequestHandler
{
ContentType = NotificationSubscriber.ContentType,
StartSegments = NotificationSubscriber.StartSegments,
Response = "[OK]",
Endpoint = new Uri(_configManager.Client.BaseAddress, "v1/payments").ToString(),
ModifyRequestBodyAsyncFunc = async (handler, context, bodyContent) =>
{
using (var scope = app.ApplicationServices.CreateScope())
{
var subscriber = scope.ServiceProvider
.GetRequiredService<INotificationSubscriber>();
await subscriber.QueueAndAkcknowledgeAsync(handler, context, bodyContent);
}
return bodyContent;
}
},
I'm having special trobule with the ModifyRequestBodyAsyncFunc function, that is declared (in the interface) like this:
public Func<RawRequestHandler, HttpContext, string, Task<string>> ModifyRequestBodyAsyncFunc { set; get; }
Also, I don't get how or where are initialized handler, context and bodyContent (RawRequestHandler handler, HttpContext context, string bodyContent as declared in the NotificationSubscriber class). I pressume these are loaded by Dependency Injection, but It would be different for other DI implementations I've seen.
Any help would be appreciated; also, I take reading recommendations.
Thank you very much!
I'm having special trobule with the ModifyRequestBodyAsyncFunc function
This is a special C# type, called a delegate. The delegate in question is a function that accepts RawRequestHeader, HttpContext, string and returns a Task<string>, which tells us that it's asynchronous.
Next, this is a syntax to create an anonymous async function and assign it to the delegate property:
/* SomeProp */ = async (handler, context, bodyContent) =>
{
// ...
return bodyContent;
}
Also, I don't get how or where are initialized handler, context and bodyContent
The .UseRawRequestRequestBodyHandler(...) registers a middleware which is basically a piece of code which runs for every request. So, somewhere inside that middleware, there is code that has access to said parameters and probably passes them like that:
// the params are not necessarily named exactly like this, only the types must match
string content = await rawRequestHeader.ModifyRequestBodyAsyncFunc(handler, context, bodyContent);
Notice the await keyword (we must await asynchronous functions) and also the fact that the delegate is invoked just like a normal method.

Azure service bus Message deserialize broken in core conversion

So, I've created a new Azure Functions project v3 and am porting over a subset of functions from v1 that was running on 4.6.2, while retiring the rest as obsolete. Unfortunately in the change from BrokeredMessage to Message due to changing from Microsoft.ServiceBus.Messaging to Microsoft.Azure.ServiceBus the following deserialization method is now failing with:
There was an error deserializing the object of type stream. The input source is not correctly formatted.
The problem is right there in the error, but Im not sure what the correct new approach is, its a bit unclear.
Serialize
public static Message CreateBrokeredMessage(object messageObject)
{
var message = new Message(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(messageObject)))
{
ContentType = "application/json",
Label = messageObject.GetType().Name
};
return message;
}
Deserialize
public static T ParseBrokeredMessage<T>(Message msg)
{
var body = msg.GetBody<Stream>();
var jsonContent = new StreamReader(body, true).ReadToEnd();
T updateMessage = JsonConvert.DeserializeObject<T>(jsonContent);
return updateMessage;
}
Object
var fileuploadmessage = new PlanFileUploadMessage()
{
PlanId = file.Plan_Id.Value,
UploadedAt = uploadTimeStamp,
UploadedBy = uploadUser,
FileHash = uploadedFileName,
FileName = file.Name,
BusinessUnitName = businessUnitName,
UploadedFileId = uploadedFile.Id
};
```
Message.GetBody<T>() is an extension method for messages sent using the legacy Service Bus SDK (WindowsAzure.ServiceBus package) where BrokeredMessage was populated with anything other than Stream. If your sender sends an array of bytes as you've showed, you should access it using Message.Body property.
In case your message is sent as a BrokeredMessage, the receiving code will need to select either of the methods based on some information to indicate how the message was originally sent.

Why does WCF ignore my TokenProvider?

I have a BizTalk WCF-Custom receive location to which I have added a custom behavior:
public class SasTokenProviderEndpointBehavior : BehaviorExtensionElement, IEndpointBehavior
{
public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
{
var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(sharedAccessSecretName, sharedAccessKey);
bindingParameters.Add(new TransportClientEndpointBehavior { TokenProvider = tokenProvider });
}
}
}
parameter setup code omitted for brevity
This is adapted from a sample found at https://code.msdn.microsoft.com/How-to-integrate-BizTalk-07fada58#content - this author is widely respected in the BizTalk community and code of this kind has been in use for some years. All I am doing is adapting the method he uses, that is proven to work, to substitute a different TokenProvider.
I can see through debugging that this code runs and the TransportClientEndpointBehavior with correct parameters is added to the channel. However when the BizTalk receive location polls Service Bus, I see the following in the event log:
The adapter "WCF-Custom" raised an error message. Details "System.UnauthorizedAccessException: 40102: Missing authorization token, Resource:sb://[namespace].servicebus.windows.net/[queue]. TrackingId:452c2534-d3e6-400f-874f-09be324e9e11_G27, SystemTracker:[namespace].servicebus.windows.net:[queue], Timestamp:12/1/2016 11:38:56 AM ---> System.ServiceModel.FaultException: 40102: Missing authorization token, Resource:sb://[namespace].servicebus.windows.net/[queue]. TrackingId:452c2534-d3e6-400f-874f-09be324e9e11_G27, SystemTracker:[namespace].servicebus.windows.net:[queue], Timestamp:12/1/2016 11:38:56 AM
I cannot see any reason that the Azure Service Bus endpoint would return this error message except that because the token provider is not being used. Why would the channel ignore the TokenProvider and what do I have to do to pass the token correctly?
edit:
I have inspected the raw WCF message traffic for the port in question as well as one using the SB-Messaging adapter, which works as expected. The difference is that the SB-Messaging adapter's messages contain a SOAP header like:
<Authorization xmlns="http://schemas.microsoft.com/servicebus/2010/08/protocol/">SharedAccessSignature sr=[really long encoded string]</Authorization> and my custom binding port's messages do not. So it is true that the problem is a missing Authorization SOAP header; but the question persists - why isn't the channel adding this header?
edit #2:
I have decompiled Microsoft.ServiceBus.dll and I believe I've found the class that actually creates the WCF messsage, Microsoft.ServiceBus.Messaging.Sbmp.SbmpMessageCreator. It has this method:
private Message CreateWcfMessageInternal(string action, object body, bool includeToken, string parentLinkId, RetryPolicy policy, TrackingContext trackingContext, RequestInfo requestInfo)
{
Message message = Message.CreateMessage(this.messageVersion, action, body);
MessageHeaders headers = message.Headers;
headers.To = this.logicalAddress;
string sufficientClaims = this.GetSufficientClaims();
if (this.linkInfo != null)
{
if (!string.IsNullOrEmpty(this.linkInfo.TransferDestinationEntityAddress))
{
SecurityToken authorizationToken = this.GetAuthorizationToken(this.linkInfo.TransferDestinationEntityAddress, sufficientClaims);
if (authorizationToken != null)
{
SimpleWebSecurityToken webSecurityToken = (SimpleWebSecurityToken) authorizationToken;
if (webSecurityToken != null)
this.linkInfo.TransferDestinationAuthorizationToken = webSecurityToken.Token;
}
}
this.linkInfo.AddTo(headers);
}
if (includeToken)
{
ServiceBusAuthorizationHeader authorizationHeader = this.GetAuthorizationHeader(sufficientClaims);
if (authorizationHeader != null)
headers.Add((MessageHeader) authorizationHeader);
}
if (this.messagingFactory.FaultInjectionInfo != null)
this.messagingFactory.FaultInjectionInfo.AddToHeader(message);
if (!string.IsNullOrWhiteSpace(parentLinkId))
message.Properties["ParentLinkId"] = (object) parentLinkId;
if (trackingContext != null)
TrackingIdHeader.TryAddOrUpdate(headers, trackingContext.TrackingId);
MessageExtensionMethods.AddHeaderIfNotNull<RequestInfo>(message, "RequestInfo", "http://schemas.microsoft.com/netservices/2011/06/servicebus", requestInfo);
return message;
}
So thinking about it logically, there are two reasons the Authorization header would be missing:
includeToken is false (Why would this be so?)
GetAuthorizationHeader() returns null (Why?)
edit #3:
I have compiled and run the example code and this works. The only significant difference between my code and his is that mine includes a line which calls out to Azure Key Vault:
var kv = new KeyVaultClient(this.GetAccessToken);
var key = kv.GetSecretAsync(this.KeyVaultUri.AbsoluteUri, this.SharedAccessSecretName).Result;
var sharedAccessKey = key.Value;
var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(
this.SharedAccessSecretName,
sharedAccessKey);
bindingParameters.Add(new TransportClientEndpointBehavior { TokenProvider = tokenProvider });
This is an asynchronous method that returns a Task. Can it be that blocking on the result of this Task somehow doesn't do what would be expected in certain situations, and this is messing up the configuration of the WCF channel somehow? As I said, I am certain this code runs and assigns the TokenProvider. I am now merely not certain when it runs.
D'OH!
I had neglected to realise that the very old version of Microsoft.ServiceBus.dll we still have in the solution for interop with the (equally old) on premises version of Service Bus (Service Bus for Windows Server) was the one referenced by my project. For whatever reason this version just doesn't do what it's supposed to, and doesn't give any indication that it's bypassing the intended behaviour. Updating to have the current NuGet package for Service Bus fixes the problem.

Genesys Platform : Get Call Details From Sip Server

I want to get Call Details from Genesys Platform SIP Server.
And Genesys Platform has Platform SDK for .NET .
Anybod has a SIMPLE sample code which shows how to get call details using Platform SDK for .NET [ C# ] from SIP Server?
Extra Notes:
Call Details : especially i wanted to get AgentId for a given call
and
From Sip Server : I am not sure if Sip Server is the best candiate to
take call details. So open to other suggestions/ alternatives
You can build a class that monitor DN actions. Also you watch specific DN or all DN depending what you had to done. If its all about the call, this is the best way to this.
Firstly, you must define a TServerProtocol, then you must connect via host,port and client info.
var endpoint = new Endpoint(host, port, config);
//Endpoint backupEndpoint = new Endpoint("", 0, config);
protocol = new TServerProtocol(endpoint)
{
ClientName = clientName
};
//Sync. way;
protocol.Open();
//Async way;
protocol.BeginOpen();
I always use async way to do this. I got my reason thou :) You can detect when connection open with event that provided by SDK.
protocol.Opened += new EventHandler(OnProtocolOpened);
protocol.Closed += new EventHandler(OnProtocolClosed);
protocol.Received += new EventHandler(OnMessageReceived);
protocol.Error += new EventHandler(OnProtocolError);
Here there is OnMessageReceived event. This event where the magic happens. You can track all of your call events and DN actions. If you go genesys support site. You'll gonna find a SDK reference manual. On that manual quiet easy to understand there lot of information about references and usage.
So in your case, you want agentid for a call. So you need EventEstablished to do this. You can use this in your recieve event;
var message = ((MessageEventArgs)e).Message;
// your event-handling code goes here
switch (message.Id)
{
case EventEstablished.MessageId:
var eventEstablished = message as EventEstablished;
var AgentID = eventEstablished.AgentID;
break;
}
You can lot of this with this usage. Like dialing, holding on a call inbound or outbound even you can detect internal calls and reporting that genesys platform don't.
I hope this is clear enough.
If you have access to routing strategy and you can edit it. You can add some code to strategy to send the details you need to some web server (for example) or to DB. We do such kind of stuff in our strategy. After successful routing block as a post routing strategy sends values of RTargetPlaceSelected and RTargetAgentSelected.
Try this:
>
Genesyslab.Platform.Contacts.Protocols.ContactServer.Requests.JirayuGetInteractionContent
JirayuGetInteractionContent =
Genesyslab.Platform.Contacts.Protocols.ContactServer.Requests.JirayuGetInteractionContent.Create();
JirayuGetInteractionContent.InteractionId = "004N4aEB63TK000P";
Genesyslab.Platform.Commons.Protocols.IMessage respondingEventY =
contactserverProtocol.Request(JirayuGetInteractionContent);
Genesyslab.Platform.Commons.Collections.KeyValueCollection keyValueCollection =
((Genesyslab.Platform.Contacts.Protocols.ContactServer.Events.EventGetInteractionContent)respondingEventY).InteractionAttributes.AllAttributes;
We are getting AgentID and Place as follows,
Step-1:
Create a Custome Command Class and Add Chain of command In ExtensionSampleModule class as follows,
class LogOnCommand : IElementOfCommand
{
readonly IObjectContainer container;
ILogger log;
ICommandManager commandManager;
public bool Execute(IDictionary<string, object> parameters, IProgressUpdater progress)
{
if (Application.Current.Dispatcher != null && !Application.Current.Dispatcher.CheckAccess())
{
object result = Application.Current.Dispatcher.Invoke(DispatcherPriority.Send, new ExecuteDelegate(Execute), parameters, progress);
return (bool)result;
}
else
{
// Get the parameter
IAgent agent = parameters["EnterpriseAgent"] as IAgent;
IIdentity workMode = parameters["WorkMode"] as IIdentity;
IAgent agentManager = container.Resolve<IAgent>();
Genesyslab.Desktop.Modules.Core.Model.Agents.IPlace place = agentManager.Place;
if (place != null)
{
string Place = place.PlaceName;
}
else
log.Debug("Place object is null");
CfgPerson person = agentManager.ConfPerson;
if (person != null)
{
string AgentID = person.UserName;
log.DebugFormat("Place: {0} ", AgentID);
}
else
log.Debug("AgentID object is null");
}
}
}
// In ExtensionSampleModule
readonly ICommandManager commandManager;
commandManager.InsertCommandToChainOfCommandAfter("MediaVoiceLogOn", "LogOn", new
List<CommandActivator>() { new CommandActivator()
{ CommandType = typeof(LogOnCommand), Name = "OnEventLogOn" } });
enter code here
IInteractionVoice interaction = (IInteractionVoice)e.Value;
switch (interaction.EntrepriseLastInteractionEvent.Id)
{
case EventEstablished.MessageId:
var eventEstablished = interaction.EntrepriseLastInteractionEvent as EventEstablished;
var genesysCallUuid = eventEstablished.CallUuid;
var genesysAgentid = eventEstablished.AgentID;
.
.
.
.
break;
}

wcf callback + save session not operationcontext

I'm new to stackoverflow however I use it everyday. Today I need you because I dont get this info anywhere.
My question is:
I want to make a service with callback to clients but I dont want to callback in the function they call in the service. (something like subscriber/publisher)
I want to save the callback instance.
Then I want a service calling a function in my service that will trigger the callbacks(like this: callbacks.PrintMessage("Message"));)
Saving the callback instance in a static list in a static class.
When calling the callback.function() Im getting this error: "you are using Disposed object"
because Im getting the instance with this: OperationContext.Current.GetCallbackChannel<"callback interface">
What can I do to save that callback instances?
Thanks a lot.
Pedro
CODE:
//FUNCTION IN MY SERVICE
public void Subscribe()
{
var callback = OperationContext.Current.GetCallbackChannel<IMonitoringWebServiceCallback>();
callbacks.Add(callback);
callback = OperationContext.Current.GetCallbackChannel<IMonitoringWebServiceCallback>();
AlarmCallbackSingleton.Instance.AddCallback(callback);
//callback.PrintString("String"); //HERE IT WORKS! BUT I DONT WANT CALL HERE!
alarmInfoHandler = new AlarmInfoEventHandler(AlarmInfoHandler);
NewAlarmInfo += alarmInfoHandler;
}
//FUNCTION IN THE SAME SERVICE CALLED BY OTHER CLIENT
public void PublishAlarm(string alarm)
{
AlarmInfoEventArgs e = new AlarmInfoEventArgs();
e.Alarm = alarm;
NewAlarmInfo(this, e);
}
public void AlarmInfoHandler(object sender, AlarmInfoEventArgs e)
{
List<IMonitoringWebServiceCallback> callbacks = AlarmCallbackSingleton.Instance.GetCallbacks();
//EVERYONE THAT SUBSCRIBED SHOULD EXECUTE THIS (HERE I GET THE DISPOSED ERROR)
callbacks.ForEach(x => x.ShowString("String!"));
}
Ok. I got it! The answer to this question is as simple as this:
When you subscribe to the service you need to save somewhere(List etc..) the OperationContext and not the callback object.
Then when the PublishAlarm is called by another client the event is triggered and you need to get OperationContext of all clients that subscribe.
I saved that objetcs in a static List(singleton class) just for the example.
Then:
public void AlarmInfoHandler(object sender, AlarmInfoEventArgs e)
{
var operation = AlarmCallbackSingleton.Instance.operationContext
var callback = operation.GetCallbackChannel<IMonitoringWebServiceCallback>();
callback.ShowAlarm(); //function you want to call
}
Hope this can help!