Azure Message Bus, Unable to complete a message - message-queue

My project is a UWP application. I follow the guideline of this link. URL: https://github.com/Azure/azure-service-bus/tree/master/samples/DotNet/Microsoft.Azure.ServiceBus/BasicSessionSendReceiveUsingQueueClient. Then I got a problem. The Message does not complete when I call 'session.CompleteAsync'. Message is still in queue until it runs out of its maximum delivery count.
private async Task ProcessSessionMessagesAsync(IMessageSession session, Message message, CancellationToken token)
{
var sessionId = session.SessionId;
var sequenceNumber = message.SystemProperties.SequenceNumber;
var messageId = message.MessageId;
var messageBody = Encoding.UTF8.GetString(message.Body);
await session.CompleteAsync(message.SystemProperties.LockToken);
}

Related

Post JSON Object RestSharp v107

I have to post this json data:
JSON.stringify(dataRest) is:
{"Ds_MerchantParameters":"eyJEU19NRVJDSEFOVF9BTU9VTlQiOiI3Myw4NCIsIkRTX01FUkNIQU5UX0NVUlJFTkNZIjoiOTc4IiwiRFNfTUVSQ0hBTlRfTUVSQ0hBTlRDT0RFIjoiMzUyNDM0NDM1IiwiRFNfTUVSQ0hBTlRfT1JERVIiOiIwMDAwMDAwMDA3NjUiLCJEU19NRVJDSEFOVF9JRE9QRVIiOiIxODExNzViOTBjNDM2ZDNlZDQ3ODg4OWEyMjdjNjI2Yjc0MDBiOTEyIiwiRFNfTUVSQ0hBTlRfVEVSTUlOQUwiOiIxIiwiRFNfTUVSQ0hBTlRfVFJBTlNBQ1RJT05UWVBFIjoiMCJ9","Ds_Signature":"X5IoP/ssIy+8gBFbD9znLoz4dFOH/mWRjMCaE/8kq65XJJVLywT05wVXE4Fqbbo6","Ds_SignatureVersion":"HMAC_SHA256_V1"}
To this endpoint https://sis-t.redsys.es:25443/sis/rest/trataPeticionREST
Using RestSharp (v107) (or httpclient).
I post above data to my api LaunchRequest via ajax:
$.ajax({
method: 'POST',
url: localhost + 'api/Redsys/LaunchRequest',
contentType: 'application/json',
data: JSON.stringify(dataRest)
}).done(function (response) {
console.log(response);
}).fail(function (error) {
console.error(error.status + '\n' + error.responseText);
});
This is the api that receive the above data and launch request to the endpoint:
[HttpPost("LaunchRequest")]
public async Task<string> LaunchRequest(DataRest dataRest)
{
string strDataRest = JsonConvert.SerializeObject(dataRest);
var client = new RestClient("https://sis-t.redsys.es:25443/");
var request = new RestRequest("sis/rest/trataPeticionREST", Method.Post);
request.RequestFormat = DataFormat.Json;
request.AddBody(strDataRest);
var response = await client.ExecuteAsync(request);
if (response.IsSuccessful)
{
return response.Content;
}
else
{
return response.ErrorMessage;
}
}
What is wrong?
Allways receive this message:
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. (sis-t.redsys.es:25443)
Thank you in advance for your help.
I think one of my mistakes is serialize dataRest.
LaunchRequest should be like this:
[HttpPost("LaunchRequest")]
public async Task<string> LaunchRequest(DataRest dataRest)
{
var client = new RestClient("https://sis-t.redsys.es:25443/");
var request = new RestRequest("sis/rest/trataPeticionREST", Method.Post);
request.RequestFormat = DataFormat.Json;
request.AddBody(dataRest);
var response = await client.ExecuteAsync(request);
if (response.IsSuccessful)
{
return response.Content;
}
else
{
return response.ErrorMessage;
}
}
I don't know if the steps I follow in LaunchRequest are correct, but anyway I always get this error message:
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. (sis-t.redsys.es:25443)
Thank you very much again for the help you can give me.
Your issue is most probably not related to RestSharp as it looks like a connection issue between the host running your API, and the external API host.
From the other issues, I am not sure why you deserialize the object just to serialize it back. You can just do this:
var request = new RestRequest("sis/rest/trataPeticionREST", Method.Post);
request.AddJsonBody(dataRest);
You also need to avoid creating the client for each request. Create a single client instance in the controller's constructor.
It's all described in the documentation by the way.

GetStringAsync method not responding

I'm trying to get some custom columns values (longitude,latitude) from ASPNetUsers Table from the DB , When I send a Get request throw browser I get a 200 ok with the requested json .. but when I try to use GetStringAsync to deserialize the response in my xamarin app I don't get any response .
In AccountController class
// POST api/Account/GetUserPostion
[Route("GetUserPostion")]
public LocationDataToPostAsync GetUserPostion()
{
var store = new UserStore<ApplicationUser>(new ApplicationDbContext());
var manager = new ApplicationUserManager(store);
LocationDataToPostAsync locationData = new LocationDataToPostAsync();
var model = manager.FindById(User.Identity.GetUserId());
locationData.UserId = User.Identity.GetUserId();
if (model.Longitude != null) locationData.Longitude = (double) model.Longitude;
if (model.Latitude != null) locationData.Latitude = (double) model.Latitude;
return locationData;
}
In ApiService class in xamarin forms app
public async Task<LocationDataToPostAsync> GetUserLocationAsync(string accessToken)
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var json = await client.GetStringAsync("http://10.0.2.2:45455/api/Account/GetUserPostion");
var location = JsonConvert.DeserializeObject<LocationDataToPostAsync>(json);
return location;
}
It is unclear from your code if the Task is awaited or you are calling .Result or .GetAwaiter().GetResult() on the Task. However, as we found out in the comments adding .ConfigureAwait(false) fixed your issue.
This indicates that the code cannot return to the context it came from, so adding .ConfigureAwait(false) the code doesn't return to the context.
In your case the context is probably the UI thread and when it tries to return the UI thread is blocked.
The most likely scenario why the UI Thread is block is because you called your Task in a wrong manner. If you call it with .Result on the UI thread you are synchronously blocking the UI thread, hence anything that tries to return to the UI thread, will deadlock, since you are blocking that.
The easy fix here is to just add .ConfigureAwait(false) in your code. The better solution would be not to block the UI thread by awaiting the Task.

exchange api push notification response

I am using exchange managed API and using push notification.
I am using below code
Uri uri = new Uri("http://domain.io/MyPage.aspx");
PushSubscription ps = service.SubscribeToPushNotifications(folder, uri, 1, "", EventType.Created, EventType.Modified, EventType.Deleted);
Now i get a hit on domain.io/MyPage.aspx when i change a event from calendar.
But now how i process that response ?
There is limited value in request header.
how could i know that which calendar, which service this request come.
Here is my answer. Using API Call is more simple.
public HttpResponseMessage ExchangeCalendar()
{
string itemId = string.Empty;
string subscriptionId = string.Empty;
string pushResponse = "OK";
string RESPONSE_OK = string.Empty;
HttpContent requestContent = Request.Content;
string eventData = requestContent.ReadAsStringAsync().Result;
XmlDocument doc = new XmlDocument();
doc.LoadXml(eventData);
subscriptionId = GetNodeValue(doc.GetElementsByTagName("t:SubscriptionId"));
itemId = GetNodeValue(doc.GetElementsByTagName("t:ItemId"));
calendarId = GetNodeValue(doc.GetElementsByTagName("t:FolderId"));
RESPONSE_OK = "<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope\"><soap:Body><SendNotificationResult xmlns=\"http://schemas.microsoft.com/exchange/services/2006/messages\"><SubscriptionStatus>" + pushResponse + "</SubscriptionStatus></SendNotificationResult></soap:Body></soap:Envelope>";
return new HttpResponseMessage()
{
Content = new StringContent(RESPONSE_OK, Encoding.UTF8, "text/xml")
};
}
In very basic terms, after the SubscribeToPushNotifications call returns the PushSubscription there will be a subscription id that links the folder you subscribed to. Any notifications for that folder will contain the subscription id and the ItemId, as well as the type of notification, New, Changed, Moved, etc. You will need to maintain some kind of mapping of subscription id-to-folder, and then call EWS via GetItem to find the item in question.

My Windows Phone app Get empty response (404 Not Found) Scond time, work's great first time;And always work fine if without SSL

I am building my first windowsPhone 8.1 application ,the role of my application is to create connection with server to get information from it, so I am writing the code to do this process by sending json-rpc request to server to get some information ,I am successful to get it in first time but when I send the second request I am receiving an empty response with 404 error (page not found).
But when I call the service without https (http only) it works fine regardless how many time I call it !
public async Task<string> GetDataFromServer(string urlToCall, string JSONData,string RR)
{
string UserName = “XXXXXXX”
string Password = "XXX";
using ( var handler = new HttpClientHandler())
{
handler.Credentials = new NetworkCredential(UserName, Password);
HttpClient client = new HttpClient(handler);
HttpResponseMessage response = null;
try
{
response = await client.PostAsync(urlToCall, new StringContent(JSONData.ToString(), Encoding.UTF8, " application/json"));
string res = response.Content.ReadAsStringAsync().Result;
Windows.UI.Popups.MessageDialog g = new Windows.UI.Popups.MessageDialog(res);
await g.ShowAsync();
return res;
}
catch (Exception ex)
{
Windows.UI.Popups.MessageDialog g = new Windows.UI.Popups.MessageDialog("Error is : " + ex.Message);
g.ShowAsync();
return "Error";
}
finally
{
response.Dispose();
client.CancelPendingRequests();
client.Dispose();
handler.Dispose();
}
}
}
Again, when call the URL of service (start with https) on first time I got response with seeked data, but second time I receive an empty response with 404 error (page not found) !!
Any help please
Please try to use this solution.
public async Task<string> SendJSONData3(string urlToCall, string JSONData)
{
string UserName = "XXXXXXXXX";
string Password = "XXXXXXXXX";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(urlToCall);
httpWebRequest.Credentials = new NetworkCredential(UserName, Password);
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(await httpWebRequest.GetRequestStreamAsync()))
{
string json = JSONData;
streamWriter.Write(json);
streamWriter.Flush();
}
var httpResponse = (HttpWebResponse)await httpWebRequest.GetResponseAsync();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
return result;
}
}
A couple of ideas:
Do not use the .Result property. Just use await instead to avoid deadlocks.
Remove the additional space in front of the media type parameter " application/json"
Enable logging on the webserver and see if the second request arrives on the server.
Get a network trace, for example with Wireshark or Fiddler.
Try puting WebRequest.RegisterPrefix("https://", WebRequestCreator.ClientHttp); in your initialization code, as proposed in this answer.

No ServiceStack WebServiceException.ResponseStatus on csv format request

When unit testing, I want to check csv formatted results, so I have the following code in my test.
MyDtoReq request = new MyDtoReq();
// ... assign some properties
string url = request.ToUrl("GET");
HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(url);
httpReq.Accept = "text/csv";
csv = new StreamReader(httpReq.GetResponse().GetResponseStream()).ReadToEnd();
That works fine, if the request succeeds. But when it fails, it raises a System.Net.WebException that doesn't have the expected WebServiceException.ResponseStatus details. NUnit reports the exception as follows:
Test Name: TestReq
Test FullName: [...].TestReq
Test Source: c:\Users\[...]\UnitTestProject1\ServiceTests.cs : line 261
Test Outcome: Failed
Test Duration: 0:00:27.104
Result Message: System.Net.WebException : The remote server returned an error: (400) Bad Request.
Result StackTrace: at [...].TestReq() in c:\Users\[...]\UnitTestProject1\ServiceTests.cs:line 287
Turns out that this is by design, as most clients requesting csv format are not able to parse a ResponseStatus. In order to see the actual error, I would re-submit the request with format=html in the browser - a frustrating waste of time.
Here's how to get the actual error message from failing csv format requests:
// Declared in test setup
public const string Host = "http://localhost:1337";
private const string BaseUri = Host + "/";
[Test]
public void TestMyDtoReqCsvFormat()
{
MyDtoReq request = new MyDtoReq();
request.startDate = "20130919";
request.endDate = "20130930";
request.source = "Token";
try
{
string requestUrl = request.ToUrl("GET");
HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(requestUrl);
httpReq.Accept = "text/csv";
var csv = new StreamReader(httpReq.GetResponse().GetResponseStream()).ReadToEnd();
// assert some facts about the contents of csv
}
catch (Exception)
{
try {
JsonServiceClient client = new JsonServiceClient(BaseUri);
MyDtoReqResponse response = client.Get(request);
// do something if re-request succeeds (i.e. was a transient error)
}
catch (WebServiceException webEx)
{
var message = webEx.ResponseStatus.ErrorCode +
" " + webEx.ResponseStatus.Message.Trim() +
" " + webEx.ResponseStatus.StackTrace.Trim();
throw new WebException(message,webEx);
}
catch (Exception otherEx) {
System.Diagnostics.Debug.WriteLine(otherEx.Message);
throw new Exception(otherEx.Message, otherEx);
}
}
}