MassTransit Consumer not getting called - azure

In the following sample program (using MassTransit, Azure ServiceBus), I am able to send messages to the queue, but my Receive Endpoint/Consumer does not seems to get the message. What am I doing wrong here? (Simple publish and a handler example given in this link(http://masstransit-project.com/MassTransit/quickstart.html) works fine!)
static async Task MainAsync(string[] args)
{
var bus = Bus.Factory.CreateUsingAzureServiceBus(cfg =>
{
var serviceUri = ServiceBusEnvironment.CreateServiceUri("sb", "{sb}", "{sb-name}");
var host = cfg.Host(serviceUri, h =>
{
h.OperationTimeout = TimeSpan.FromSeconds(5);
h.TokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(
"RootManageSharedAccessKey",
"{key}");
h.TransportType = TransportType.NetMessaging;
});
cfg.ReceiveEndpoint(host, "test_queue", ep =>
{
ep.Consumer<SayHelloCommandConsumer>();
});
});
bus.Start();
await SendAHello(bus);
Console.WriteLine("Press any key to exit");
Console.ReadKey();
bus.Stop();
}
private static async Task SendAHello(IBusControl bus)
{
var sendToUri = new Uri("queue-end-point-address");
var endPoint = await bus.GetSendEndpoint(sendToUri);
await endPoint.Send<ISayHello>( new
{
Message = "Hello there !"
});
}
}
public class SayHelloCommandConsumer : IConsumer<ISayHello>
{
public Task Consume(ConsumeContext<ISayHello> context)
{
var command = context.Message;
return Console.Out.WriteLineAsync($"Recieved a message {command}");
}
}
public interface ISayHello
{
string Message { get; set; }
}
}

The queue address looked suspect, and it seems like you've corrected it.

Related

The connection was inactive for more than the allowed 60000 milliseconds and is closed by container

I have an azure function that sends a message to the service bus queue. Since a recent deployment, I see an exception occurring frequently: The connection was inactive for more than the allowed 60000 milliseconds and is closed by container.
I looked into this GitHub post: https://github.com/Azure/azure-service-bus-java/issues/280 it says this is a warning. Is there a way to increase this timeout? Or any suggestions on how to resolve this? Here is my code:
namespace Repositories.ServiceBusQueue
{
public class MembershipServiceBusRepository : IMembershipServiceBusRepository
{
private readonly QueueClient _queueClient;
public MembershipServiceBusRepository(string serviceBusNamespacePrefix, string queueName)
{
var msiTokenProvider = TokenProvider.CreateManagedIdentityTokenProvider();
_queueClient = new QueueClient($"https://{serviceBusNamespacePrefix}.servicebus.windows.net", queueName, msiTokenProvider);
}
public async Task SendMembership(GroupMembership groupMembership, string sentFrom = "")
{
if (groupMembership.SyncJobPartitionKey == null) { throw new ArgumentNullException("SyncJobPartitionKey must be set."); }
if (groupMembership.SyncJobRowKey == null) { throw new ArgumentNullException("SyncJobRowKey must be set."); }
foreach (var message in groupMembership.Split().Select(x => new Message
{
Body = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(x)),
SessionId = groupMembership.RunId.ToString(),
ContentType = "application/json",
Label = sentFrom
}))
{
await _queueClient.SendAsync(message);
}
}
}
}
This could be due to deadlock in the thread pool, please check if you are calling an async method from a sync method.

Azure SignalR Service Connection string

Trying to create a POC for azure signalr service. I found the github samples, which appeared to have some solid examples. I chose this one. Basically, my problem is that when I run the code locally, works like a champ with the localhost url, but when I try to run using an Azure SignalR Service using a url that I copied from azure portal keys which is in this format: Endpoint=<service_endpoint>;AccessKey=<access_key>;, I get an error stating that "Invalid URI: The URI scheme is not valid.". How do I transform the url from what I copy from keys and use it to connect to a signalr service?
class Program
{
private const string DefaultHubEndpoint = "Endpoint=http://someFakesrsname.service.signlar.net;AccsssKey=thisseemslikeagoodaccesskeytouseformyquestion";//"http://localhost:5000/ManagementSampleHub";
private const string Target = "Target";
private const string DefaultUser = "User";
static void Main(string[] args)
{
var app = new CommandLineApplication();
app.FullName = "Azure SignalR Management Sample: SignalR Client Tool";
app.HelpOption("--help");
var hubEndpointOption = app.Option("-h|--hubEndpoint", $"Set hub endpoint. Default value: {DefaultHubEndpoint}", CommandOptionType.SingleValue, true);
var userIdOption = app.Option("-u|--userIdList", "Set user ID list", CommandOptionType.MultipleValue, true);
app.OnExecute(async () =>
{
var hubEndpoint = hubEndpointOption.Value() ?? DefaultHubEndpoint;
var userIds = userIdOption.Values != null && userIdOption.Values.Count > 0 ? userIdOption.Values : new List<string>() { "User" };
Console.WriteLine("hubEndpoint: " + hubEndpoint);
Console.WriteLine("DefaultHubEndpoint: " + DefaultHubEndpoint);
foreach (var userId in userIds)
{
Console.WriteLine("UserId: " + userId);
}
var connections = (from userId in userIds
select CreateHubConnection(hubEndpoint, userId)).ToList();
await Task.WhenAll(from conn in connections
select conn.StartAsync());
Console.WriteLine($"{connections.Count} Client(s) started...");
Console.ReadLine();
await Task.WhenAll(from conn in connections
select conn.StopAsync());
return 0;
});
app.Execute(args);
}
static HubConnection CreateHubConnection(string hubEndpoint, string userId)
{
var url = hubEndpoint.TrimEnd('/') + $"?user={userId}";
var connection = new HubConnectionBuilder().WithUrl(url).Build();
connection.On(Target, (string message) =>
{
Console.WriteLine($"{userId}: gets message from service: '{message}'");
});
connection.Closed += async ex =>
{
Console.WriteLine(ex);
Environment.Exit(1);
};
return connection;
}
}
enter code here

integration payload router issues

i am trying to configure payload router to route messages to either rabbitmq,ibmq and kafka MOM's. payload will have to be routed to more than one MOM in some cases, here is the code
#ServiceActivator(inputChannel = "routerChannel", outputChannel = "outputChannel")
public PayloadTypeRouter router(Log message) {
PayloadTypeRouter router = new PayloadTypeRouter();
for (Platform platform : new MessageConfig().getConfig(message.getClientKey())) {
System.out.println("platform type=" + platform.getRouter());
if (platform.getRouter().equals(BridgeType.Bridge.rabbitmq.toString())) {
router.setChannelMapping(String.class.getName(), "rabbitChannel");
} else if (platform.getRouter().equals(BridgeType.Bridge.ibmmq.toString())) {
router.setChannelMapping(String.class.getName(), "ibmmqChannel");
} else if (platform.getRouter().equals(BridgeType.Bridge.kafka.toString())) {
router.setChannelMapping(String.class.getName(), "kafkaChannel");
}
}
return router;
}
earlier i had below code which was working fine(sending to individual MOM but not to two at same time)
#Router(inputChannel = "routerChannel")
public String route(Log message) {
log.info("message in the router='{}'", message.getClientKey());
for (Platform platform : new MessageConfig().getConfig(message.getClientKey())) {
System.out.println("platform type=" + platform.getRouter());
if (platform.getRouter().equals(BridgeType.Bridge.rabbitmq.toString())) {
return "rabbitChannel";
} else if (platform.getRouter().equals(BridgeType.Bridge.ibmmq.toString())) {
return "ibmmqChannel";
} else if (platform.getRouter().equals(BridgeType.Bridge.kafka.toString())) {
return "kafkaChannel";
}
}
return "errorChannel";
}
not sure what i am doing wrong , appreciate any help here
PayloadTypeRouter and MethodInvokingRouter only support one destination.
Use a RecipientListRouter with Recipients with MessageSelectors if you want to route to multiple destinations.
Actually, I was wrong; you can simply return List<String> from your second example.

DNX (rc1-final): IHttpConnectionFeature not found

Using the latest rc1-final version of ASP.NET 5, I'm attempting to find the remote IP address inside an Azure API App controller method.
When running the code, 'context' is this.HttpContext, inside the controller method.
But feature is coming back null, since the feature doesn't exist.
IHttpConnectionFeature feature = context.Features.Get<IHttpConnectionFeature>();
Does anything have to be enabled in the configuration to have this feature be available?
Thanks,
Kirk
I had the same problem.
The following code works for me:
public async Task<IActionResult> Index()
{
if (!UserID.HasValue)
{
UpdateRemoteIp(HttpContext);
var remoteIpAddress = HttpContext.Features.Get<IHttpConnectionFeature>()?.RemoteIpAddress.ToString();
if (remoteIpAddress == null)
{
throw new Exception("Cannot determine client IP");
}
await _userService.LoginAnonymous(remoteIpAddress);
string url = UriHelper.GetDisplayUrl(Request);
return Redirect(url);
}
PrepareViewModel();
return View("Index", ViewModel);
}
private static void UpdateRemoteIp(HttpContext httpContext)
{
var xForwardedForHeaderValue = httpContext.Request.Headers.GetCommaSeparatedValues(XForwardedForHeaderName);
if (xForwardedForHeaderValue != null && xForwardedForHeaderValue.Length > 0)
{
IPAddress ipFromHeader;
int? port;
if (IPAddressWithPortParser.TryParse(xForwardedForHeaderValue[0], out ipFromHeader, out port))
{
var connection = httpContext.Connection;
var remoteIPString = connection.RemoteIpAddress?.ToString();
if (!string.IsNullOrEmpty(remoteIPString))
{
httpContext.Request.Headers[XOriginalIPName] = remoteIPString;
}
if (port.HasValue)
{
if (connection.RemotePort != 0)
{
httpContext.Request.Headers[XOriginalPortName] = connection.RemotePort.ToString(CultureInfo.InvariantCulture);
}
connection.RemotePort = port.Value;
}
connection.RemoteIpAddress = ipFromHeader;
}
}
}
Hope it helps you

how to check if device is registered for windows phone push notification

I am using notification hub to register my windows phone device for push notification service.Once if I register my device and again if I register my device for push notification I am getting two notifications means a single device is registering for two time.Can anyone please tell me how to prevent a user to register for more than once.
My code is as:
public static async Task SetupPushNotifications()
{
await RegisterWithNotificationHub();
}
private static HttpNotificationChannel CreateHttpNotificationChannel(string channelName)
{
var httpChannel = HttpNotificationChannel.Find(channelName);
#endregion
return httpChannel;
}
private static async Task RegisterWithNotificationHub()
{
try
{
// requesting a channel from MPNS
App.NotificationChannel = CreateHttpNotificationChannel("");
App.ClientHub = new NotificationHub(
"",""
);
var storedTagsForUser = await GetRegistrationsTagsFromBackEnd();
await RegisterTemplateNotificationWithNotificationHub(storedTagsForUser);
}
catch (Exception exc)
{
Debug.WriteLine(exc);
}
}
private static async Task RegisterTemplateNotificationWithNotificationHub(IEnumerable<string> tags)
{
var toastMessageTemplate =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<wp:Notification xmlns:wp=\"WPNotification\">" +
"<wp:Toast>" +
"<wp:Text1>$(oppTitleValue)</wp:Text1>" +
"<wp:Text2>$(myToastMessage)</wp:Text2>" +
"<wp:Param>$(pageToOpen)</wp:Param>" +
"</wp:Toast>" +
"</wp:Notification>";
try
{
await App.ClientHub.RegisterTemplateAsync(
App.NotificationChannel.ChannelUri.AbsoluteUri,
xmlTemplate: toastMessageTemplate,
templateName: TemplateRegistrationName,
tags: tags);
}
catch (Exception exc)
{
Debug.WriteLine("Error registering template notification with notification hubs: " + exc);
}
}
You can check if the channel already exists by calling HttpNotificationChannel.Find(channelName). It will return null if it doesn't.
So you would only want to create a channel if it doesnt't already exist. For example
private void RegisterPushChannel()
{
HttpNotificationChannel currentChannel = HttpNotificationChannel.Find("MyPushChannel");
if (currentChannel == null)
{
currentChannel = new HttpNotificationChannel("MyPushChannel");
currentChannel.Open();
currentChannel.BindToShellTile();
currentChannel.BindToShellToast();
}
}

Resources