Calling Azure Function ( Queue Trigger) Doesnt work , but it does when i send i message from azure portal - debugging

Im working with a personal project with this details: net core 6 with c# web app and az functions.
I have a Queue Trigger (Az function) that shows a message and sends an email and I want to call it Queue from an Azure Function.
I'm using the right connection string and Queue name because If I send a message from the azure portal, I see the queue message, I'm able to debug it locally and I also receive an Email.
But when i make the call from my code ( another Az Function) , i see the Queue Message from the portal but i cannot debug it locally and i don't receive the email.
So obviously, it works from the portal but not locally ( or prod), something is wrong with my code.
I'm using this code to make the call from my code:
try
{
string conectionstring = "Myconnection";
QueueClient queue = new QueueClient(conectionstring, "myQueueName");
var rspqueue = await queue.SendMessageAsync("MyMessage");
}
catch (Exception ex)
{
throw;
}
This show 201 message and i see the message from the azure portal as i said.
Isn't SendMessageAsync supposed to call my Queue Trigger (Az function) ? Or im getting it wrong?
Regards
I tried to call a Queue Trigger (Az function) from another Az Function. I expect to know how to do that

Well, you are not calling the queue trigger but as the name suggest you are adding messages to the queue and the queue trigger is getting triggered .
Here I have a http trigger which is adding the message in the queue.
[FunctionName("Function1")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
string connectionString = "<Connection String>";
QueueClient queue = new QueueClient(connectionString, "testr");
string message = Convert.ToBase64String(Encoding.UTF8.GetBytes("Hello World "));
queue.SendMessage(message);
return new OkObjectResult("responseMessage");
}
My Queue trigger is like this
[FunctionName("Function1")]
public void Run([QueueTrigger("testr", Connection = "test")]string myQueueItem, ILogger log)
{
log.LogInformation($"C# Queue trigger function processed: {myQueueItem}");
}
Here I am encoding the string in the http trigger as I am importing a string in the queue trigger.
Queuetrigger output :

Related

Spring-Boot - using AWS SQS in a synchronic way

I have a pub/sub scenario, where I create and save to DB something in one service, publish it to a SNS topic, subscribe with SQS listener, and handle the message and save it to DB in another service. So far so good.
In one of the scenarios I create a user and subscribe it to a site. Then I send the new user to its topic, the user-site relation to another topic, and the subscribed service updates its own DB tables.
private void publishNewUserNotifications(UserEntity userEntity, List<SiteEntity> sitesToAssociateWithUser) {
iPublisherService.publishNewUserNotification(userEntity);
if (sitesToAssociateWithUser != null || !sitesToAssociateWithUser.isEmpty()) {
List<String> sitesIds = sitesToAssociateWithUser.stream().map(SiteEntity::getSiteId).collect(Collectors.toList());
iPublisherService.publishSitesToUserAssignment(userEntity.getId(), new ArrayList<>(), sitesIds);
}
}
The problem is that sometimes I have a thread race and handle the user-site relation before I created the user in the second service, get an empty result from DB when loading the User object, and fail to handle the user-site relation.
#Override
#Transactional
public void handle(UsersSitesListNotification message) {
UsersSitesNotification assigned = message.getAssigned();
List<UserEntity> userEntities = iUserRepository.findAllByUserIdIn(CollectionUtils.union(assigned.getUserIds()));
List<SiteEntity> siteEntities = iSiteRepository.findAllByIdIn(CollectionUtils.union(assigned.getSiteIds()));
List<UserSiteAssignmentEntity> assignedEntities = fromUsersSitesNotificationToUserSiteAssignmentEntities(assigned, userEntities, siteEntities);
Iterable<UserSiteAssignmentEntity> saved = iUserSiteAssignmentRepository.saveAll(assignedEntities);
}
Because of that, I consider using SQS in a synchronic way. The problem is that in order to use SQS I need to import the "spring-cloud-aws-messaging" package, and the SQS configuration inside it uses the Async client.
Is there a way to use SQS in a synchronic way? What should I change? How should I override the Async configuration that I need in the package/get some other package?
Any idea will help, tnx.

Ibm Wmq - Xms .Net - Read and delete message from Queue

Greetings of the day.
Please help on the below requirement:
Requirement:
We want to delete message from MQ only after it is processed successfully.
Use event based message detection technique and avoid loop
So, to achieve above:
I have created message listener and consumer class below:
{
sessionIn = connectionIn.CreateSession(false, AcknowledgeMode.ClientAcknowledge);
// Create message listener and assign it to consumer
messageListener = new MessageListener(OnMessageCallback);
consumerAsync.MessageListener = messageListener;
Console.WriteLine("Message Listener set. Starting the connection now.");
// Start the connection to receive messages.
connectionWMQ.Start();
}
Reading the message from the call back event and push the message into other system:
OnMessageCallback(Message) {
if (xmsMessage is IBytesMessage)
{
IBytesMessage bytesMessage = (IBytesMessage)xmsMessage;
byte[] arrayMessage = new byte[bytesMessage.BodyLength];
bytesMessage.ReadBytes(arrayMessage);
string message = System.Text.Encoding.Default.GetString(arrayMessage);
}
}
Once the message processed, external system will fire the below over ride method:
Response method override:
protected override Task OnResponse(ReponseMessage message)
{
 //Read the message and get the message id and correlation id.
//Delete the message from the queue.
//I am trying to do like this, but Its not working:
messageConsumerDelete = sessionDelete.CreateConsumer(destinationDelete, query);
if (messageConsumerDelete != null)
{
IMessage m = messageConsumerDelete.Receive(1000);
LogWrite("Receive Message=" + m);
m.Acknowledge();
}
}
Please suggest a best solution for this requirement.
I am trying to find a solution for this since weeks, but no breakthrough. 
Thanks,
Balaji

Warning publishing Azure service bus queue trigger can't find named value in local.settings.json

I have a Azure service bus queue trigger function and when I created it it asked me 3 fields, access rights, connection and queue name.
I put in listen for the access rights. For the connection I used the the 'primary connection' name given in the 'RootManageSharedAccessKey' in the service bus I created.
It looks something like this
Endpoint=sb://yogaband2017.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=JG0gwJ90bkbGl1BU=
and I created a queue in my service bus called yogaband and that is what I used for the queue name as the third parameter.
My function looks like this
public static class PostEventEmails
{
[FunctionName("PostEventEmails")]
public static void Run([ServiceBusTrigger("yogaband2017", AccessRights.Listen, Connection = "Endpoint=sb://yogaband2017.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=gkbGl1BU=")]string myQueueItem, TraceWriter log)
{
log.Info($"C# ServiceBus queue trigger function processed message: {myQueueItem}");
}
}
When I publish the function I get this warning
.nuget\packages\microsoft.net.sdk.functions\1.0.2\build\netstandard1.0\Microsoft.NET.Sdk.Functions.Build.targets(31,5): warning : Function [PostEventEmails]: cannot find value named 'Endpoint=sb://yogaband2017.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=0bkbGl1BU=' in local.settings.json that matches 'connection' property set on 'serviceBusTrigger' [C:\Users\Source\Workspaces\YogaBand2017\YogaBand2017\PostEventEmails\PostEventEmails.csproj]
and in my site I can pass the queue a message and I see the message in the queue in my Azure portal, but the function isn't picking up the message and processing it. So I still see '1 message' in the active message count in the queue. I assume it would be 0 after the function picks it up and processes it and I would see the log trace in the window? But I don't so I think the connection isn't correct or I didn't configure something correctly but I don't know what!
Here is what I put into the local.settings.json file
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "Endpoint=sb://yogaband2017.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=bGl1BU=",
"AzureWebJobsDashboard": ""}}
FYI - here is how I send the mesage to the queue in c#
var queueClient = QueueClient.Create("yogaband2017");
BrokeredMessage message = new BrokeredMessage("some test message");
message.MessageId = newEvent.YogaSpaceEventId.ToString();
queueClient.Send(message);
and in my web.config file I added this
<add key="Microsoft.ServiceBus.ConnectionString" value="Endpoint=sb://yogaband2017.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=0gwJ90bkbGl1BU="/>
Connection property of ServiceBusTrigger should be set to a setting name, not connection string itself:
[ServiceBusTrigger("yogaband2017", AccessRights.Listen, Connection = "MyConn")]
You then define a setting with this name in local.settings.json for local development environment:
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "... azure storage connection string ...",
"MyConn": "... service bus connection string ..."
}
}
and in App Settings for Azure deployment.
Note that AzureWebJobsStorage is NOT service bus connection.

spring websocket notification

Ok here i'm , i'm right now following the guides on spring site but i'm having problem on how to deliver a notification to only one user using WebSocket, i'm following this guide https://spring.io/guides/gs/messaging-stomp-websocket/ .
What I want is: i have 2 users, both of them subscribe to process1... User1 need to let the server process his pass...now i want that the server will deliver the notification only to User1...
#Controller
public class ProcessController {
#MessageMapping("/ProcessOwner/approve/{pass}")
#SendTo("")
public String notifica(#DestinationVariable String pass)throws Exception{
return "ok"+pass;
}
}
Now what should i write in the #SendTo field to deliver the answer only to user1 ? if ill write /Process/process1 both user1 and user2 will receive the message....
You ca use the sufix. It's send to every unique client.
When you subscribe in the js code:
client.connect('guest', 'guest', function(frame) {
var suffix = frame.headers['queue-suffix'];
client.subscribe("/queue/error" + suffix, function(msg) {
// handle error
});
client.subscribe("/queue/position-updates" + suffix, function(msg) {
// handle position update
});
});
On the server side you can use #ReplyToUser or the message template
String user = "fabrice";
String queue = "/queue/position-updates";
this.messagingTemplate.convertAndSendToUser(user, queue, position);
See more here: http://assets.spring.io/wp/WebSocketBlogPost.html (section: Sending Messages To a Single User)

Getting the Queue name from within the MDB

I have 2 Websphere application Server(WAS) applications, one sending a message and the other reading and processing it . I need the queue name to be known in the reading application for my downstream processing.
I am trying to get the queue name (in the reading application) by using the following code . But however I get NullPointerException since the getJMSDestination is returning null.
Queue queue = (Queue)message.getJMSDestination();
logger.info("Queue ID: "+queue.getQueueName());
Note that the queue name is set via the destination object in the sending application.
Is there any other parameters that I am missing to set in the sending application ?
The message should have the destination stored in its JMSDestination property, you can try fetch that instead of using getJMSDestination()
I've using Spring with ActiveMQ, and this appears to work for me:
public void processMessage( Message msg )
{
// Get the queue name from the supplied Message.
String sourceQueueName = "UNKNOWN";
try
{
ActiveMQDestination sourceQueue = (ActiveMQDestination) msg.getJMSDestination();
sourceQueueName = sourceQueue.getPhysicalName();
}
catch ( JMSException e )
{
LOGGER.error( "Cannot get JMSDestination from Message: " + msg, e );
}
....
Does WAS have a Queue object you can cast to that exposes similar methods?

Resources