Error while writing to an Azure Worker role Input Endpoint - azure

I'm trying to create an azure application which can recieve messages on a TCP port. I have configured an input endpoint shown below :
Endpoint Name:GPRSEndpoint
Type:Input
Protocol:TCP
Port:10000
My azure worker role code looks like this:-
TcpListener listener = new TcpListener(RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["GPRSEndpoint"].IPEndpoint);
listener.ExclusiveAddressUse = false;
listener.Start();
while (true)
{
Thread.Sleep(100);
if (listener.Pending())
{
Trace.WriteLine("Incoming Request", "Information");
TcpClient c = listener.AcceptTcpClient(); //waiting for client to connect
Stream s = c.GetStream();
StreamReader sr = new StreamReader(s);
string text = sr.ReadLine();
if (text != null && text.Length > 0)
{
Trace.WriteLine("Saving GPRS Packets into Storage Table", "Information");
//Saving GPRS Packets into Storage Table
Site site = new Site();
site.GPRSPacket = text;
var insertOperation = TableOperation.Insert(site);
siteTable.Execute(insertOperation);
}
c.Close();
}
Trace.TraceInformation("Working", "Information");
}
}
And finally my client program looks like this:-
TcpClient c = new TcpClient();
Console.WriteLine("\nConnecting to Azure...");
IPAddress AzureWorkeraddress = IPAddress.Parse("168.63.239.54");
//String AzureWorkeraddress = "http://clienttcpcloud.cloudapp.net/";
//IPAddress AzureWorkeraddress = IPAddress.Parse("65.52.184.129");
c.Connect(AzureWorkeraddress, 10000); //Azure Worker Role's INPUT TCP Endpoint 168.63.239.54 or (http://clienttcpcloud.cloudapp.net/)
Console.WriteLine("\n<<<<<<<<<<<<<<<<<<Server Connected>>>>>>>>>>>>>>>>>>\n");
Console.WriteLine("Sending to Azure...");
Stream s = c.GetStream();
StreamWriter sw = new StreamWriter(s);
sw.WriteLine(text);
sw.Flush();
Console.WriteLine("\n\nGPRS Packet Sent!!!");
s.Close();
c.Close();
I've tried changing the port number to several values, but it still fails to respond. The error that i get is:-
**A Connection failed because the connecting party did not properly respond after a period of time, or the established connection failed, because connected host failed to respond 168.63.239.54:10000**
I really don't know what the problem is.....

There is a sample application at http://blog.maartenballiauw.be/post/2010/01/17/Creating-an-external-facing-Azure-Worker-Role-endpoint.aspx. Have you tried that and compared what it is doing to what you are doing?

Related

Validate the connection string of Microsoft Azure Service Bus

I have a Microsoft Azure Service Bus connection string that I want to validate if it is a valid one. I want to validate the topics and subscriptions as well if they exist. If the connection string, topics, and subscriptions are invalid then we can take appropriate actions.
The sample connection string can be like - TransportType=AmqpWebSockets;Endpoint=sb://myservicebus.servicebus.windows.net/;SharedAccessKeyName=sendkey;SharedAccessKey=MQHnx3voLhH/xVgoamX3KijzkZ0qb7U6oHTolj7LM9H=;
I tried ServiceBusClient but it is not having such support. Is there a way we can validate the connection string and topics/subscriptions?
The client will validate that the connection string and entity names are well-formed, but there is no dedicated operation for testing its ability to communicate with Service Bus.
Connections and links are established lazily when the first network operation that requires them is invoked. There are two approaches that occur to me which would trigger network resource creation without being intrusive.
Create a message batch
In order to ensure that the batch size does not exceed the limits for a given resource, the ServiceBusSender must query the queue/topic. In the case where the client is misconfigured, it will throw.
// In a real scenario, you would want to create these as
// singletons and reuse them for the lifetime of the application.
await using var client = new ServiceBusClient("<< Connection String>>");
await using var sender = client.CreateSender("<< Queue/Topic >>");
var valid = true;
try
{
using var batch = await sender.CreateMessageBatchAsync().ConfigureAwait(false);
}
catch (Exception ex)
when (ex is ServiceBusException
|| ex is IOException
|| ex is SocketException)
{
valid = false;
}
Peek a message
Peeking a message will not cause the message to be locked or otherwise impact receiving it.
await using var client = new ServiceBusClient("<< Connection String>>");
await using var receiver = client.CreateReceiver("<< Queue/Subscription >>");
var valid = true;
try
{
_ = await receiver.PeekMessageAsync().ConfigureAwait(false);
}
catch (Exception ex)
when (ex is ServiceBusException
|| ex is IOException
|| ex is SocketException)
{
valid = false;
}
Interactions with each queue, topic, and subscription make use of a dedicated AMQP link, so each would need to be tested individually if you'd like to ensure that the name matches a known Service Bus entity.

ActiveMQ message consume from queue take more in Linux environment

I'm creating a sample .net core solution in local and IIS larger message consuming in a queue within a second but I'm deployed in Linux server to could take more time to consume a message in a queue. I don't know how to resolve it kindly help me. Below I attached my sample code here.
string topic = "QueueTest";
QueueConnectionFactory.OptimizeAcknowledge = true;
QueueConnectionFactory.AlwaysSyncSend = false;
using (IConnection connection = QueueConnectionFactory.CreateConnection("admin", "admin"))
{
connection.Start();
Apache.NMS.ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge);
using (IDestination dest = session.GetQueue(topic))
using (IMessageConsumer consumer = session.CreateConsumer(dest))
{
// TimeSpan span4 = TimeSpan.FromSeconds(3);
IMessage msg = consumer.Receive();
if (msg != null)
{
ITextMessage message = msg as ITextMessage;
string data = message.Text;
}
}
}
Check for receiveBufferSize and sendBufferSize and you can add this to your connection url :
?transport.receiveBufferSize=65536&transport.sendBufferSize=16384

C# as sender and python as receiver in Azure event hub

I have an IoT device that is connected to Azure event hub. I'm trying to make this device communicate with azure databricks and azure event hub is placed in between as a middleware. The problem is that after we are able to send messages via ".NET framework", it is never shown in messages received in "python" command line (we should do that as we work separately for each part)
I followed the guidelines .NET framework as sender and python as receiver, and this doesn't work.
I am seeing that there are spikes in the request and message graphs under event hub stream instances, but it just never shows in the receiver
==================================UPDATE==================================
Just deleted the eventhub and recreated and it seems work.
However, messages are received in the form of long strings something like this below:
Received: 662a2a44-4414-4cb5-a9e9-a08d12a417e0
Received: b68ef8f8-305f-4726-84e4-f35b76de30c5
Received: e94dfb73-972c-47b4-baef-1ab41b06be28
Received: 8eda384d-f79d-4cdf-9db3-fe5c2156553b
Received: d154283f-a8c2-4a4c-a7d5-e8d8129b568d
Received: 3e3e190e-f883-416c-a5be-b8cd8547d152
Received: e218c63b-85b3-4f4f-8f04-cb5ffc6d8921
Received: 0adec5ad-e351-4151-ba56-01093e0f383d
Received 8 messages in 0.05406975746154785 seconds
This happens when I read the messages in format below:
print("Received: {}".format(event_data.body_as_str(encoding='UTF-8')))
I just give it a try, and I can repro your issue. And here are something you need to check.
1.In you sender(in c#), you should make sure your message to send is correct. Like below:
static void SendingRandomMessages()
{
var eventHubClient = EventHubClient.CreateFromConnectionString(connectionString, eventHubName);
int i = 0;
while (true)
{
try
{
// make sure the message is correct.
var message = i+":"+Guid.NewGuid().ToString()+":"+DateTime.Now;
Console.WriteLine("{0} > Sending message: {1}", DateTime.Now, message);
var myeventdata = new EventData(Encoding.UTF8.GetBytes(message));
eventHubClient.Send(myeventdata);
i++;
//eventHubClient.Send(new EventData(Encoding.UTF8.GetBytes(message)));
}
catch (Exception exception)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("{0} > Exception: {1}", DateTime.Now, exception.Message);
Console.ResetColor();
}
Thread.Sleep(2000);
}
}
2.There seems some delay for the receiver(in python), so I execute the python receiver about 3 times, and I can see the expected output. The screenshot as below:
Update 1022: as we discussed in the comment, there is a solution for fixing just receiving even / odd number event data.
In you sender(in c#), use the code below, which sends event data to partition 0:
static void SendingRandomMessages()
{
var eventHubClient = EventHubClient.CreateFromConnectionString(connectionString, eventHubName);
var myclient = eventHubClient.CreatePartitionedSender("0");
int i = 30;
while (true)
{
var message = i + ":" + Guid.NewGuid().ToString() + ":" + DateTime.Now;
Console.WriteLine("{0} > Sending message: {1}", DateTime.Now, message);
var myeventdata = new EventData(Encoding.UTF8.GetBytes(message));
myclient.Send(myeventdata);
i++;
Thread.Sleep(2000);
}
}
then in your receiver(in python), specify the partition to 0(use this PARTITION = "0"), then you can get all the event data.

Azure service bus message delivery count is not increasing or is reset when topic subscription disabling/enabling

I have the following workflow:
Service bus receives messages.
Azure function triggers and tries to deliver this messages via HTTP to some service.
If delivery failed - function throws exception (custom) and disables topic subscription via code below:
The other function in parallel pings special health check endpoint of the service, and if it gets 200 - it tries to enable subscription and make the flow work again.
The steps could be reproduced N times, cause health check will return 200, thus the delivery url of point 2 - 4xx code.
After the next attempt to enable subscription and deliver the message, I expect that delivery count will be increased and in the end (after 10 deliveries attempt) it will get to dead-letter.
Actual - it equals 1.
I assume, that it may reset when I call CreateOrUpdate with status changed.
If yes - what is the other way to manage subscription status instead of Microsoft.Azure.Management package so that the messages delivery count will not be reset?
UPDATE: Function code
public static class ESBTESTSubscriptionTrigger
{
private static readonly HttpClient Client = new HttpClient();
private static IDatabase redisCache;
[FunctionName("ESBTESTSubscriptionTrigger")]
[Singleton]
public static async Task Run([ServiceBusTrigger("Notifications", "ESBTEST", AccessRights.Listen, Connection = "NotificationsBusConnectionString")]BrokeredMessage serviceBusMessage, TraceWriter log, [Inject]IKeyVaultSecretsManager keyVaultSecretsManager)
{
var logicAppUrl = await keyVaultSecretsManager.GetSecretAsync("NotificationsLogicAppUrl");
if (redisCache == null)
{
redisCache = RedisCacheConnectionManager.GetRedisCacheConnection(
keyVaultSecretsManager.GetSecretAsync("RedisCacheConnectionString").GetAwaiter().GetResult());
}
if (string.IsNullOrWhiteSpace(logicAppUrl))
{
log.Error("Logic App URL should be provided in Application settings of function App.");
throw new ParameterIsMissingException("Logic App URL should be provided in Application settings of function App.");
}
var applicaitonId = serviceBusMessage.Properties["applicationId"].ToString();
var eventName = serviceBusMessage.Properties.ContainsKey("Event-Name") ? serviceBusMessage.Properties["Event-Name"].ToString() : string.Empty;
if (string.IsNullOrWhiteSpace(applicaitonId))
{
log.Error("ApplicationId should be present in service bus message properties.");
throw new ParameterIsMissingException("Application id is missing in service bus message.");
}
Stream stream = serviceBusMessage.GetBody<Stream>();
StreamReader reader = new StreamReader(stream);
string s = reader.ReadToEnd();
var content = new StringContent(s, Encoding.UTF8, "application/json");
content.Headers.Add("ApplicationId", applicaitonId);
HttpResponseMessage response;
try
{
response = await Client.PostAsync(logicAppUrl, content);
}
catch (HttpRequestException e)
{
log.Error($"Logic App responded with {e.Message}");
throw new LogicAppBadRequestException($"Logic App responded with {e.Message}", e);
}
if (!response.IsSuccessStatusCode)
{
log.Error($"Logic App responded with {response.StatusCode}");
var serviceBusSubscriptionsSwitcherUrl = await keyVaultSecretsManager.GetSecretAsync("ServiceBusTopicSubscriptionSwitcherUri");
var sbSubscriptionSwitcherResponse = await Client.SendAsync(
new HttpRequestMessage(HttpMethod.Post, serviceBusSubscriptionsSwitcherUrl)
{
Content =
new
StringContent(
$"{{\"Action\":\"Disable\",\"SubscriptionName\":\"{applicaitonId}\"}}",
Encoding.UTF8,
"application/json")
});
if (sbSubscriptionSwitcherResponse.IsSuccessStatusCode == false)
{
throw new FunctionNotAvailableException($"ServiceBusTopicSubscriptionSwitcher responded with {sbSubscriptionSwitcherResponse.StatusCode}");
}
throw new LogicAppBadRequestException($"Logic App responded with {response.StatusCode}");
}
if (!string.IsNullOrWhiteSpace(eventName))
{
redisCache.KeyDelete($"{applicaitonId}{eventName}DeliveryErrorEmailSent");
}
}
}

How make a multi client server using Bluetooth API in j2me?

I am planning to implement a server using Bluetooth API using J2ME. I want multiple clients to be able to connect to it at the same time but I could not find much on the NET.
UUID uuid = new UUID("1101", false);
String SurveyAnswer="";
//Create the service url
String connectionString = "btspp://localhost:" + uuid + ";name=xyz";
//open server url
StreamConnectionNotifier streamConnNotifier = (StreamConnectionNotifier) Connector.open(connectionString);
//Wait for client connection
System.out.println("\nServer Started. Waiting for clients to connect...");
while(true){
StreamConnection connection = streamConnNotifier.acceptAndOpen();
}
How do I modify these codes in order for it to work as a multi client server?
That's a standard problem. When the StreamConnection connection = streamConnNotifier.acceptAndOpen(); returns you have to spawn a Thread which uses the connection. The main Thread then reenters the accept and waits for next connection.
UUID uuid = new UUID("1101", false); String SurveyAnswer="";
//Create the service url
String connectionString = "btspp://localhost:" + uuid + ";name=xyz";
//open server url
StreamConnectionNotifier streamConnNotifier = (StreamConnectionNotifier)
Connector.open(connectionString);
//Wait for client connection
System.out.println("\nServer Started. Waiting for clients to connect...");
while(true){
StreamConnection connection = streamConnNotifier.acceptAndOpen();
System.out.println("Client connected starting communication");
new CommunicationThread(connection).start();
}
In the class CommunicationThreads run method you can then get the streams and communicate.

Resources