Get all messages from a queue in RabbitMQ in c# - c#

Given the queue name, i need all the messages in that queue in RabbitMQ.
I have got the number of messages in the queue in msgCount variable and the first message in strBody variable.
But i need all the messages in the given queue. Something that the RabbitMQ Management UI gives me in the browser when i click the Get Message(s) button
using (var conn = _connectionFactory.CreateConnection())
{
using (var channel = conn.CreateModel())
{
var queueName = "myqueuename";
var response = channel.QueueDeclarePassive(queueName);
var msgCount = response.MessageCount;
var consCount = response.ConsumerCount;
BasicGetResult result = channel.BasicGet(queueName, noAck);
if (result == null)
{
//No msgs available
}
else
{
IBasicProperties properties = result.BasicProperties;
byte[] body = result.Body;
string strBody = System.Text.Encoding.UTF8.GetString(body);
Console.WriteLine(strBody);
//channel.BasicAck(result.DeliveryTag, false);
}
}
}

Making a simple http request to the rabbitMQ server does the job.
Make a POST request to the following url:
string queuesUrl = Url + ":" + Port + "/api/queues/" + VirtualHost + "/" + queueName + "/get";
where Url is where your rabbitMQ is hosted
Send the following payload
{"count":5,"ackmode":"ack_requeue_true","encoding":"auto","truncate":50000}
Put -1 in count to get all the messages. Truncate is optional
RabbitMQ Management HTTP API :
https://rawcdn.githack.com/rabbitmq/rabbitmq-management/v3.8.0/priv/www/api/index.html

Related

Push: show all notifications in the notifications area

In my app, I insert the push notifications management. Now I'm testing only the Android area.
I sent the first test notifications with the FCM console. With this tool, if I send more than one notification, I see all of the in the notifications area of my phone (example: if I send 3 notifications with text "1", "2", and "3", I see all of them in the notification area).
Then, I tried to write some C# code to send these notifications from my server. I can now send the notifications from my code, but if I make the same test as above, I see only the last notification ("3") and not all of them.
I'm sure there is some parameter to be set, but I can't figure out which one is.
Do you know where have I to fix something? Below my C# code:
public string SendMessage()
{
string serverKey = "myserverkey";
try
{
var result = "-1";
var webAddr = "https://fcm.googleapis.com/fcm/send";
var regID = "myAndroidPhoneID";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Headers.Add("Authorization:key=" + serverKey);
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"to\": \"" + regID + "\",\"data\": {\"message\": \"1This is a Firebase Cloud Messaging Topic Message!\",},\"priority\":10}";
streamWriter.Write(json);
streamWriter.Flush();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
return result;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return "err";
}
}
I also tried to add in my json the parameter collapse_key, changing its value every notification, but I see always only the last.
Solved using this json instead of the posted one:
string json = "{\"to\": \"" + regID + "\",\"notification\": {\"title\": \"New deal\",\"body\": \"20% deal!\"},\"priority\":10}";
Summarized all the steps here: https://programmingistheway.wordpress.com/2017/07/19/devextremephonegap-how-to-manage-push-notifications-with-fcm/

Xamarin Android client post JSON to Node JS web service

I am having trouble with sending JSON data from my Android application written in C# using Xamarin Android (MvvmCross).
The function in Android application could run with no exception; however, my web service (written in Node JS using Express) seems not detecting the post request on its endpoint. Note that the other endpoints which use get (to send the data from web service to Android app) are working perfectly.
Below is my function to post my data to my web service
public async Task<int> insertSales(IEnumerable<Models.SalesTable> newsales)
{
/*ServerDatabaseApi.insertSalesEndpoint = "http://" + ipAddress + ":" + port +
"/insertsales";*/
WebRequest request = WebRequest.CreateHttp(ServerDatabaseApi.insertSalesEndpoint);
request.Method = "POST";
request.ContentType = "application/json";
try
{
using (var streamwriter = new StreamWriter(await request.GetRequestStreamAsync()))
{
string json = JsonConvert.SerializeObject(newsales, Formatting.Indented);
streamwriter.Write(json);
streamwriter.Flush();
}
return 1;
}
catch (WebException we)
{
return 0;
}
}
When running the function above, it is always succeed (return 1; always executes). I have also tried checking the JSON serialization and it is working perfectly fine.
Below also attached the endpoint code used to serve the data.
/*endpoint for inserting a new sales to sales table*/
app.post('/insertsales', function(appReq, appRes){
console.log("Insert sales; count : "+ appReq.body.length);
sql.connect(conn).then(function(){
console.log("Insert sales; count : "+ appReq.body.length);
for (var i = 0 ; i < appReq.body.length ; i++) {
new sql.Request()
.query("insert into SalesTable " +
"values ('"+appReq.body[i].DocumentNo+"','"+appReq.body[i].DateCreated+"','"+appReq.body[i].Location+"',"+
appReq.body[i].TotalDiscountAmount+","+appReq.body[i].Total+",'"+appReq.body[i].SalesmanId+"','"+
appReq.body[i].CustomerId+"',"+appReq.body[i].Latitude+","+appReq.body[i].Longitude+")")
.catch(function(err){
console.log(err);
});
}
}).catch(function(err){
console.log(err);
});
});
I tried to trace whether it reached the endpoint or not using console.log. However, it never executes.
Could you help me to spot where I went wrong? Thanks in advance.
There's nothing in your .NET code that actually sends the WebRequest. You create the request, write some JSON to it's stream, and flush it. Here's a simple way to make the network call (untested):
public async Task<int> InsertSales(IEnumerable<Models.SalesTable> newSales)
{
var ipAddress = "";// your IP address here
var port = ""; // your port here
var endpoint = $"http://{ipAddress}:{port}/insertsalesline";
var requestString = JsonConvert.SerializeObject(newSales);
var content = new StringContent(requestString, Encoding.UTF8, "application/json");
using (var client = new HttpClient())
{
var reponse = await client.PostAsync(endpoint, content);
if (reponse.IsSuccessStatusCode)
return 1;
else
return 0;
}
}

C# HttpClient; How to make safe async calls?

I have a site that exercises a third party API. This API will tell me the values of accounts for a user. The API has become unresponsive, and this has highlighted a flaw in my code. I am getting the exception "Thread was being aborted." in the try-catch trap around the call, and in EventViewer I can see the HttpException RequestTimedOut.
I am trying to use HttpClient, in a synchronous manner. This works fine when the API is responsive, but it is coming apart now that the API is very slow to respond.
I have an overview page that tries to gather all the account values for all users.
There are 3 types of users (CLIENT, LIAISON, MEMBER). The page makes three asynchronous Javascript calls for each type of account. The fact that there are three calls made is (most probably) a red-herring, but I am declaring it to be safe.
The server takes each call, gets the users for each call. So, for the CLIENT call, the system pulls up the all the CLIENT users, and serially steps through them. It makes an HTTP request per CLIENT user to get the account value.
Each call has a new HttpClient object created for it, wrapped in a using statement.
I strongly suspect that IIS is spotting the idle thread and shutting it down, which is fair enough.
How can I make the API call so that I return the thread to the pool until I get a response?
private static string getTotalAssets(string blockChainAddress, string identity)
{
var prefix = "getTotalAssets() - ";
string msg = "";
using (var handler = new HttpClientHandler { UseCookies = false, PreAuthenticate = true })
using (var client = new HttpClient(handler))
{
// Timeout
TimeSpan tsTimeout = new TimeSpan(0, 0, 0, _timeout);
client.Timeout = tsTimeout;
var message = new HttpRequestMessage(HttpMethod.Post, _urlSettleAPIGetTotalAssets);
// Accept Json
message.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(Constants.MIME_JSON));
// Form the content to send
string content = getTotalAssetsContent(blockChainAddress);
// Add to the message
message.Content = new StringContent(content);
// Make API Call
string sCallRef = "GET TOTAL ASSETS FOR [" + identity + "]";
Tuple<HttpResponseMessage, string> result = MakeAPICall(client, message, content, sCallRef);
if (result.Item1 == null)
return result.Item2; // Error during call
// Call returned
HttpResponseMessage response = result.Item1;
string responseString = result.Item2;
if (!response.IsSuccessStatusCode)
{
msg = "Response Status Code: " + response.StatusCode.ToString();
logger.Debug(prefix + msg);
return "Error [" + result.Item2 + "]; " + msg;
}
// Else, call returned 200-OK
logger.Debug(prefix + "Response:\r\n" + responseString + "\r\n");
return processGetTotalAssetsResponseString(responseString);
} // end of using...
}
public static Tuple<HttpResponseMessage, string> MakeAPICall(HttpClient client, HttpRequestMessage message, string content, string callRef)
{
var prefix = "MakeAPICall() - ";
string msg = "";
HttpResponseMessage responseMessage;
string responseString = "";
try
{
responseMessage = client.SendAsync(message).GetAwaiter().GetResult();
responseString = responseMessage.Content.ReadAsStringAsync().GetAwaiter().GetResult();
return new Tuple<HttpResponseMessage, string>(responseMessage, responseString);
}
catch (Exception ex)
{
msg = "Exception during call; \r\nBaseMessage:[" + ex.GetBaseException().Message + "]; \r\nMessage:[" + ex.Message + "]";
logger.Warn(prefix + msg);
return new Tuple<HttpResponseMessage, string>(null, msg);
}
} // end of MakeAPICall()

SendGrid email using MailHelper

I am using SendGrid mailhelper (as part of C# SDK) to send email. I need to send to multiple users, and hence I am using Personalization.
I get an error : Bad Request
This is my code:
static async Task Execute(string sub, string body, List<Recipient> recipients)
{
string apiKey = Environment.GetEnvironmentVariable("SendGrid_ApiKey", EnvironmentVariableTarget.User);
dynamic sg = new SendGridAPIClient(apiKey);
SendGrid.Helpers.Mail.Email from = new SendGrid.Helpers.Mail.Email("test1#gmail.com");
string subject = sub;
Personalization personalization = new Personalization();
SendGrid.Helpers.Mail.Email emails = new SendGrid.Helpers.Mail.Email();
var i = 0;
foreach (var recp in recipients)
{
emails.Address = recp.Email;
emails.Name = recp.FirstName + " " + recp.LastName;
personalization.AddTo(emails);
i++;
}
SendGrid.Helpers.Mail.Email to = new SendGrid.Helpers.Mail.Email("test1#gmail.com");
Content content = new Content("text/plain", body);
Mail mail = new Mail(from, subject, to, content);
mail.AddPersonalization(personalization);
dynamic response = await sg.client.mail.send.post(requestBody: mail.Get());
}
I appreciate if someone could advise me what am I doing incorrect.
Sendgrid API responds with bad request when there are more than 1 email address that is the same in the Personalization object. Make sure all the emails are unique

How to read the body of the message in the mail retrieve from gmail by using pop3 in c #?

This is code:
protected void Button9_Click(object sender, EventArgs e)
{
try
{
// create an instance of TcpClient
TcpClient tcpclient = new TcpClient();
// HOST NAME POP SERVER and gmail uses port number 995 for POP
tcpclient.Connect("pop.gmail.com", 995);
// This is Secure Stream // opened the connection between client and POP Server
System.Net.Security.SslStream sslstream = new SslStream(tcpclient.GetStream());
// authenticate as client
sslstream.AuthenticateAsClient("pop.gmail.com");
//bool flag = sslstream.IsAuthenticated; // check flag
// Asssigned the writer to stream
System.IO.StreamWriter sw = new StreamWriter(sslstream);
// Assigned reader to stream
System.IO.StreamReader reader = new StreamReader(sslstream);
// refer POP rfc command, there very few around 6-9 command
sw.WriteLine("USER your_gmail_user_name#gmail.com");
// sent to server
sw.Flush(); sw.WriteLine("PASS your_gmail_password");
sw.Flush();
// RETR 1 will retrive your first email. it will read content of your first email
sw.WriteLine("RETR 1");
sw.Flush();
// close the connection
sw.WriteLine("Quit ");
sw.Flush(); string str = string.Empty;
string strTemp = string.Empty;
while ((strTemp = reader.ReadLine()) != null)
{
// find the . character in line
if (strTemp == ".")
{
break;
}
if (strTemp.IndexOf("-ERR") != -1)
{
break;
}
str += strTemp;
}
textbox1.text = str;
textbox1.text += "<BR>" + "Congratulation.. ....!!! You read your first gmail email ";
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
The message body is a bunch of what appears to be random characters. I know it's not just a bunch of random characters but some code that needs to be parsed and converted. How can I read content in "message body"?
I know i'm not directly replying to your answer but reading email is a really complex task and I think you can achieve this better and faster with an external library instead of implementing it by yourself.
There are many good implementation, i usually use OpenPop.NET which works fine and is opensource.
https://sourceforge.net/projects/hpop/
You can find many example on internet because it is really popular.
http://hpop.sourceforge.net/examples.php
you can get all mail easly:
using(Pop3Client client = new Pop3Client())
{
// Connect to the server
client.Connect("pop.gmail.com", 995, true);
// Authenticate ourselves towards the server
client.Authenticate("username#gmail.com", "password", AuthenticationMethod.UsernameAndPassword);
// Get the number of messages in the inbox
int messageCount = client.GetMessageCount();
// We want to download all messages
List<Message> allMessages = new List<Message>(messageCount);
// Messages are numbered in the interval: [1, messageCount]
// Ergo: message numbers are 1-based.
// Most servers give the latest message the highest number
for (int i = messageCount; i > 0; i--)
{
allMessages.Add(client.GetMessage(i));
}
}
you can get the full raw message
var mailbody = ASCIIEncoding.ASCII.GetString(message.RawMessage);
or if it is an utf8 encoded email:
var encodedStringAsBytes = System.Convert.FromBase64String(message.RawMessage);
var rawMessage =System.Text.Encoding.UTF8.GetString(encodedStringAsBytes);
Instead if you want only the mail body you have to dig into the mail structure:
http://hpop.sourceforge.net/documentation/OpenPop~OpenPop.Mime.MessagePart.html
I know it is not an easy task but as I stated above emails are complex objects.

Categories

Resources