azure webjobs - 'It is not possible for an entity that requires sessions to create a non-sessionful message receiver - azure-webjobs

I am trying to trigger azure webjob using azure service bus queue which is FIFO. but following error is occured. is there way to fix it ?
It is not possible for an entity that requires sessions to create a
non-sessionful message receiver.
TrackingId:af15f75d-3d5f-423e-92c5-e22b222d25e6_G9_B1,
SystemTracker:testsbqueue:Queue:testsbqueuexxx
static void Main()
{
var serviceBusConfi = new ServiceBusConfiguration
{
ConnectionString= "Endpoint="",
};
var config = new JobHostConfiguration();
if (config.IsDevelopment)
{
config.UseDevelopmentSettings();
}
config.UseServiceBus(serviceBusConfi);
ServicePointManager.DefaultConnectionLimit = Int32.MaxValue;
var host = new JobHost(config);
// The following code ensures that the WebJob will be running continuously
host.RunAndBlock();
}
Function.cs
public class Functions
{
// This function will get triggered/executed when a new message is written
// on an Azure Queue called queue.
public static void ProcessQueueMessage([ServiceBusTrigger("testsbqueuexxx") ] string message, TextWriter log)
{
log.WriteLine($"[WebJobNotificationProcessor-]-{message}");
}
}

Related

Accessing AWS WebSocket using VertX HttpClient

I have created an API Gateway with a Web Socket on AWS. I would like to connect to it using the HttpClient provided by VertX. I am using the following code for the client verticle:
public class WebSocketClient extends AbstractVerticle {
// application address replaced by [address]
protected final String host = "[address].execute-api.us-east-1.amazonaws.com";
protected final String path = "/dev";
protected final int port = 80;
protected final String webSocketAddress = "wss://[address].execute-api.us-east-1.amazonaws.com/dev";
#Override
public void start() throws Exception {
startClient(this.vertx);
}
protected void startClient(Vertx vertx) {
HttpClient client = vertx.createHttpClient();
client.webSocket(port, host, path, asyncWebSocket -> {
if (asyncWebSocket.succeeded()) {
WebSocket socket = asyncWebSocket.result();
System.out.println("Successfully connected. Node closing.");
socket.close().onFailure(throwable -> {
throwable.printStackTrace();
});
} else {
asyncWebSocket.cause().printStackTrace();
}
});
}
}
The same code works when I am testing it with a VertX server running on the localhost, so I assume that it is a question of the correct WebSocketConnectionOptions.
When I try to connect to the AWS socket using the HttpClient verticle, I get a "connection refused" error. Connecting to it using wscat works without problems.
Thanks a lot for your help.
This question is dealing with basically the same problem. I will post the solution here just to document a straight-forward way to use AWS ApiGateway Websockets with VertX.
So, the goal is to implement a VertX WebClient connected to a deployed AWS Api WebSocket Gateway which can be reached under the WsUri "wss://[address].execute-api.us-east-1.amazonaws.com/dev" (you will have to replace [address] by the address of your ApiGateway Websocket).
Here the code to set up the WebClient, connect to the Websocket, print out a success message, and then disconnect again:
public class WebSocketClient extends AbstractVerticle {
protected final String webSocketUrl = "wss://[address].execute-api.us-east-1.amazonaws.com/dev"
protected final String host = "[address].execute-api.us-east-1.amazonaws.com";
protected final String path = "/dev";
protected final int sslPort = 443;
#Override
public void start() throws Exception {
startClient(this.vertx);
}
protected void startClient(Vertx vertx) {
HttpClient client = vertx
.createHttpClient(new
HttpClientOptions().setDefaultHost(host).setDefaultPort(sslPort).setSsl(true));
// connect to the web socket
client.webSocket(path, asyncWebSocket -> {
if (asyncWebSocket.succeeded()) {
// executed on a successful connection
WebSocket socket = asyncWebSocket.result(); // use this for further communication
System.out.println("Successfully connected. Closing the socket.");
// Closing the socket
socket.close().onFailure(throwable -> {
throwable.printStackTrace();
});
} else {
// executed if the connection attempt fails
asyncWebSocket.cause().printStackTrace();
}
});
}
You can use the following class to run the example:
public class PlayWebSocket {
public static void main(String[] args) throws URISyntaxException{
Vertx vertx = Vertx.vertx();
WebSocketClient clientVerticle = new WebSocketClient();
vertx.deployVerticle(clientVerticle);
}
}
On the Java side, this should print the message about the successful connection and the closing of the socket. On the AWS side, the $connect and the $disconnect methods of the ApiGateway should be called. You can check this in the logs of your handler function(s) using CloudWatch.

Should a triggered Webjob complete?

I have created a very simple WebJob with a TimerTrigger, for example;
static async Task Main()
{
var builder = new HostBuilder();
builder.ConfigureWebJobs(b =>
{
b.AddAzureStorageCoreServices();
b.AddTimers();
});
builder.ConfigureLogging((context, b) =>
{
b.AddConsole();
});
var host = builder.Build();
using (host)
{
await host.RunAsync();
}
}
}
public class Functions
{
public static void ProcessTimerMessage([TimerTrigger("*/30 * * * * *", RunOnStartup = true)] TimerInfo timerInfo, ILogger logger)
{
logger.LogInformation("I am here");
}
}
When I run this in Azure it never finishes. I was expecting this to complete on each run and then start again on the next trigger. Instead it never stops running:
The TimerTrigger for WebJobs runs as a singleton instance at startup and will run continuously, internally keeping track of the interval it runs at (based on the provide cron pattern). If any single invocation takes longer than the interval, then it will contiune processing the work it's doing and skip the overlapping invocation until the current work is complete.
You can read the details here:
https://github.com/Azure/azure-webjobs-sdk-extensions/wiki/TimerTrigger

How to running method webservice in background from android xamarin form

I want running this method UpdateStatus when he close app
It is my coding method UpdateStatus in android:
String id = "";
var id = Application.Current.Properties["Id"].ToString();
User user = new User(id);
user.Id = id;
user.Datetime = time;
var responseStatus = await api.UpdateStatus(new UpdateStatusQuery(user));
Could you help me ?
In the Android, When you close your applcation, based on my research, above code can not be run, because all of threads or services will be killed when applcation is killed.
If you want to run above code when application in the background, you can can use background service to achieve that, due to background execution limits in Android 8.0 or later, if you code need some time to execute, and you want code running stably, Foreground Services is a good choice.
In xamarin forms, you can use dependenceService in the OnSleep method of App.xaml.cs
OnSleep - called each time the application goes to the background.
You can create a interface.
IService.cs
public interface IService
{
void Start();
}
Then achieved DependentService to start a Foreground Service.
[assembly: Xamarin.Forms.Dependency(typeof(DependentService))]
namespace TabGuesture.Droid
{
[Service]
public class DependentService : Service, IService
{
public void Start()
{
var intent = new Intent(Android.App.Application.Context,
typeof(DependentService));
if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O)
{
Android.App.Application.Context.StartForegroundService(intent);
}
else
{
Android.App.Application.Context.StartService(intent);
}
}
public override IBinder OnBind(Intent intent)
{
return null;
}
public const int SERVICE_RUNNING_NOTIFICATION_ID = 10000;
public override StartCommandResult OnStartCommand(Intent intent,
StartCommandFlags flags, int startId)
{
// From shared code or in your PCL
CreateNotificationChannel();
string messageBody = "service starting";
var notification = new Notification.Builder(this, "10111")
.SetContentTitle(Resources.GetString(Resource.String.app_name))
.SetContentText(messageBody)
.SetSmallIcon(Resource.Drawable.main)
.SetOngoing(true)
.Build();
StartForeground(SERVICE_RUNNING_NOTIFICATION_ID, notification);
//==============================do you work=====================
String id = "";
var id = Application.Current.Properties["Id"].ToString();
User user = new User(id);
user.Id = id;
user.Datetime = time;
var responseStatus = await api.UpdateStatus(new UpdateStatusQuery(user));
return StartCommandResult.Sticky;
}
void CreateNotificationChannel()
{
if (Build.VERSION.SdkInt < BuildVersionCodes.O)
{
// Notification channels are new in API 26 (and not a part of the
// support library). There is no need to create a notification
// channel on older versions of Android.
return;
}
var channelName = Resources.GetString(Resource.String.channel_name);
var channelDescription = GetString(Resource.String.channel_description);
var channel = new NotificationChannel("10111", channelName, NotificationImportance.Default)
{
Description = channelDescription
};
var notificationManager = (NotificationManager)GetSystemService(NotificationService);
notificationManager.CreateNotificationChannel(channel);
}
}
}
Here is similar thread:
How to create service doing work at period time in Xamarin.Forms?

Can't connect to GRPC server which is deployed on AWS ECS

I have a GRPC server written on C#.
internal class Program
{
internal static void Main(string[] args)
{
using (var waitHandle = new AutoResetEvent(false))
{
void OnConsoleOnCancelKeyPress(object o, ConsoleCancelEventArgs e)
{
e.Cancel = true;
// ReSharper disable once AccessToDisposedClosure
waitHandle.Set();
}
Console.CancelKeyPress += OnConsoleOnCancelKeyPress;
var config = new AppConfig(new ConfigurationBuilder()
.AddJsonFile("appsettings.json", false)
.Build());
var containerBuilder = new ContainerBuilder();
containerBuilder.RegisterModule(new Module());
containerBuilder.RegisterModule(new Data.Module(config.Region, config.TablePrefix));
using (var container = containerBuilder.Build())
{
var buyRatesService = container.Resolve<BuyRatesService>();
var logger = container.Resolve<ILogger<Program>>();
var server = new Server
{
Services =
{
BuyRates.BindService(buyRatesService)
},
Ports = {new ServerPort("0.0.0.0", 50051, ServerCredentials.Insecure)}
};
try
{
server.Start();
logger.LogDebug("Service started");
waitHandle.WaitOne();
}
catch (Exception e)
{
logger.LogCritical("Application terminated unexpectedly. Exception {#exception}", e);
}
finally
{
server.ShutdownAsync().Wait();
Console.CancelKeyPress -= OnConsoleOnCancelKeyPress;
}
}
}
}
}
It works fine locally. I deploy it to ecs instance(Docker). The container port is 50051. ALB and Route 53 are used.
When I'm trying to connect to someroute54uri.net:50051 I get an error
Grpc.Core.RpcException: Status(StatusCode=Unavailable, Detail="Connect Failed").
In case when I'm trying to connect to someroute54uri.net, I get an error
Grpc.Core.RpcException: Status(StatusCode=Unavailable, Detail="Trying to connect an http1.x server").
Thanks!.
Please, let me know if additional information helps to solve the issue.

Unit Test for a Java Component accessing ActiveMq in Mule Flow

I have the below Java Class which retrieve messages from JMS queue. This class is invoked in a mule flow. Could you please advice on how I can write a Junit for this class? I have tried to create a standalone broker but I am having trouble
public Object getMessages(final MuleEventContext eventContext)
{
final String consumerID = eventContext.getMessage().getProperty("consumerID", PropertyScope.INVOCATION);
final String messageSelector = "ConsumerID = '" + consumerID + "'";
JmsConnector amqConnector = (JmsConnector) eventContext.getMuleContext().getRegistry().lookupConnector("Active_MQ");
ConnectionFactory factory = amqConnector.getConnectionFactory();
Connection connection = null;
List<String> listOfMessages = null;
try
{
connection = factory.createConnection();
//Consumer Settings
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Queue queue = session.createQueue(queuename");
MessageConsumer consumer = session.createConsumer(queue, messageSelector);
//Browser Settings
Session sessionBrowser = amqConnector.getSession( false, false );
Queue queueBrowser = sessionBrowser.createQueue( queuename );
QueueBrowser qBrowser = sessionBrowser.createBrowser( queueBrowser, messageSelector );
Enumeration<Message> enumeration = qBrowser.getEnumeration();
connection.start();
listOfMessages = new ArrayList<String>();
while (enumeration.hasMoreElements())
{
enumeration.nextElement();
Message message = consumer.receive();
TextMessage msg = (TextMessage) message;
listOfMessages.add(msg.getText());
}
//Close Browser Settings
qBrowser.close(); sessionBrowser.close();
//Close Consumer Settings
consumer.close(); session.close();
//Close Connection
connection.close();
}
catch ( Exception e )
{
throw new RuntimeException("Unable to retrieve messages from Queue "+ e);
}
}
You can create FunctionalTestCase, and then:
Test the class directly by calling the method, or
Test the whole scenario by calling the flow
public class MessageServiceTest extends FunctionalTestCase {
#Test
public void testJavaClass() throws Exception {
MuleEventContext eventContext = MuleTestUtils.getTestEventContext("", MessageExchangePattern.REQUEST_RESPONSE, muleContext);
MessageService messageService = new MessageService();
assertNotNull(messageService.getMessages(eventContext));
}
#Test
public void testFlow() throws Exception {
MuleEvent event = runFlow("messageserviceFlow");
MuleMessage message = event.getMessage();
assertNotNull(message);
assertNotNull(message.getPayload());
}
protected String getConfigResources() {
return "messageservice.xml";
}
}