I'm building a web application that connects to a Predix Timeseries instance to ingest data through a websocket. When I attempt to create the socket, I get this exception:
System.Net.WebSockets.WebSocketException: 'Unable to connect to the
remote server'
I'm using this code to create my websocket, with my error being thrown on the ConnectAsync call:
public async Task openWebSocket()
{
_socket = new ClientWebSocket();
_socket.Options.SetRequestHeader(headerName: "predix-zone-id", headerValue: PREDIX_ZONE_ID_HERE);
_socket.Options.SetRequestHeader(headerName: "authorization", headerValue: "Bearer " + AUTH_TOKEN_HERE);
_socket.Options.SetRequestHeader(headerName: "content-type", headerValue: "application/json");
CancellationToken token = new CancellationToken();
var uri = new Uri(uriString: "wss://gateway-predix-data-services.run.aws-usw02-pr.ice.predix.io/v1/stream/messages");
await _socket.ConnectAsync(uri: uri, cancellationToken: token);
}
and here is my exception's stack trace:
System.Net.WebSockets.WebSocketException occurred
HResult=0x80004005
Message=Unable to connect to the remote server
Source=<Cannot evaluate the exception source>
StackTrace:
at System.Net.WebSockets.WebSocketHandle.<ConnectAsyncCore>d__20.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Net.WebSockets.ClientWebSocket.<ConnectAsyncCore>d__16.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
at PROJECTNAME.Services.TimeseriesService.<openWebSocket>d__6.MoveNext() in %PROJECTLOCATION%\Services\%SERVICENAME%.cs:line 34
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
at PROJECTNAME.Services.TimeseriesService.<Initialize>d__5.MoveNext() in %PROJECTLOCATION%\Services\%SERVICENAME%.cs:line 21
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
at PROJECTNAME.Program.<Initialize>d__1.MoveNext() in %PROJECTLOCATION%\Program.cs:line 52
Inner Exception 1:
WebSocketException: Unable to connect to the remote server
The inner exception stack track has little more information, but noting the ThrowOnInvalidConnectState() that might be useful:
at System.Net.WebSockets.WinHttpWebSocket.ThrowOnInvalidConnectState()
at System.Net.WebSockets.WinHttpWebSocket.<ConnectAsync>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Net.WebSockets.WebSocketHandle.<ConnectAsyncCore>d__20.MoveNext()
I'm not sure what else to try - lots of other posts on SO at least have some useful information in the inner exception.
I've also attempted to use Fiddler. I can see message for other services, including my auth token retrieval from UAA, but nothing from this service.
Am I missing some configuration steps somewhere? Any help or guidance would be appreciated.
I figured out the issue. The three required headers for the Predix Timeseries are:
Predix-Zone-Id: zone_id_here
Authorization: Bearer auth_token_here
Origin: "https:// hostname_here
My problem is that I tried the Origin header, but the Predix VCAP_APPLCIATION environmental variable for the application_uris doesn't include the "https://". Once I added it manually ("https://" + uri) it worked fine.
I haven't done this in C#, but "Unable to connect" sounds like it could be a network issue. Can you open a websocket to another server? Maybe this one?
https://www.websocket.org/echo.html
Could be a proxy server issue? Can you try from a different network?
Related
I'm working on a messaging extension and am trying to get the email address of the user who is using the app.
This app is being used internally and I'm using the email address to query Active Directory for the user's username.
When attempting to use the GetConversationMembersAsync method I receive a 403 (Forbidden) exception.
I am running this through IIS Express in Visual Studio 2017.
[BotAuthentication, TenantFilter]
public class MessagesController : ApiController
{
static string AppID = ConfigurationManager.AppSettings["MicrosoftAppId"];
static string AppPassword = ConfigurationManager.AppSettings["MicrosoftAppPassword"];
[HttpPost]
public async Task<HttpResponseMessage> Post([FromBody] Activity activity)
{
using (var connector = new ConnectorClient(new Uri(activity.ServiceUrl)))
{
var members = await connector.Conversations.GetConversationMembersAsync(activity.Conversation.Id);
System.UnauthorizedAccessException
HResult=0x80070005
Message=Authorization for Microsoft App ID XXX failed with status code Forbidden and reason phrase 'Forbidden'
Source=Microsoft.Bot.Connector
StackTrace:
at Microsoft.Bot.Connector.JwtTokenRefresher.d__2.MoveNext()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Net.Http.HttpClient.d__58.MoveNext()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
at Microsoft.Bot.Connector.Conversations.d__10.MoveNext()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Bot.Connector.ConversationsExtensions.d__11.MoveNext()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at NewApp.Controllers.MessagesController.d__2.MoveNext() in C:\Users\xxxx\source\repos\NewApp\NewApp\Controllers\MessagesController.cs:line 25
Inner Exception 1:
HttpRequestException: Response status code does not indicate success: 403 (Forbidden).
I found a similar issue here: Authorization for Microsoft App ID xxx failed with status code Forbidden and reason phrase 'Forbidden'. But that is not specifically for Microsoft Teams. connector-> Credentials->OAuthScope is showing "api.botframework.com/.default" but I believe that is correct for Teams.
My MicrosoftAppId and MicrosoftAppPassword are correct. If I comment out [BotAuthentication, TenantFilter] I get a 401 Unauthorized exception. If I comment out the line with GetConversationMembersAsync the app works.
I'm following the instructions here to attempt to get this context info: https://learn.microsoft.com/en-us/microsoftteams/platform/concepts/bots/bots-context.
I know this is an old question, but I had the same issue and found the solution, in case it helps someone. You need to be sure and add MicrosoftAppCredentials.TrustServiceUrl(serviceURL);, as follows:
using (var connector = new ConnectorClient(new Uri(activity.ServiceUrl)))
{
// the line below is the new required item
MicrosoftAppCredentials.TrustServiceUrl(serviceURL);
var members = await connector.Conversations.GetConversationMembersAsync(activity.Conversation.Id);
...
We are using microsoft graph api for calendar and mail item processing. we pick the items from the office 365 account,process the item then we mark it as read and after that we delete that item so that it will not be processed again.
In the mark item as read process, we have below method
MarkReadMail()
{
var response = graphClient.Me.Messages[itemID].Request().Select("IsRead").GetAsync();
var msg = response.Result;
msg.IsRead = true;
graphClient.Me.Messages[itemID].Request().Select("IsRead").UpdateAsync(msg);
}
MarkReadMail() is working fine with office 365 business essential account but on the client side they have used office 365 enterprise account, it gives the below error:
Message: Exception occured in method MarkReadMail :Code: ErrorAccessDenied
Message: Access is denied. Check credentials and try again.
Inner error
Stack Trace: at Microsoft.Graph.HttpProvider.<SendAsync>d__19.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Graph.BaseRequest.<SendRequestAsync>d__36.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Graph.BaseRequest.<SendAsync>d__32`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Graph.MessageRequest.<UpdateAsync>d__8.MoveNext()
Although, we have provided Mail.ReadWrite permission under delegated permissions on both the account.
Please suggest.
You cannot POST the object you received from the GET as it includes read-only properties (i.e. id). You need to POST a new object with just the properties you wish to update:
graphClient
.Me
.Messages["itemID"]
.Request()
.UpdateAsync(new Message(){ IsRead = true });
I'm trying to return a 304 Not Modified status code in my ASP.Net Core application when a file is accessed via my middleware.
I try setting the HTTP Status Code and sending the response back like so:
context.Response.StatusCode = 304;
await context.Response.WriteAsync("Not Modified");
But I get this exception:
System.InvalidOperationException occurred HResult=-2146233079
Message=Write to non-body 304 response.
Source=Microsoft.AspNetCore.Server.Kestrel StackTrace:
at Microsoft.AspNetCore.Server.Kestrel.Internal.Http.Frame.HandleNonBodyResponseWrite()
at Microsoft.AspNetCore.Server.Kestrel.Internal.Http.Frame.d__183.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task)
at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
at Adapt.REST.ServeStaticFilesMiddleware.d__8.MoveNext() in
C:\AdaptSource\Xivic\Adapt.Services\ServeStaticFilesMiddleware.cs:line
113 InnerException:
So obviously I can't use WriteAsync or SendFileAsync because they both send a response that contains a body.
How do I send a 304 back to the client without a body?
Simply doing nothing after setting the status code causes the intended functionality.
context.Response.StatusCode = 304;
return;
As traffic to our Azure website has increased, we've been seeing an increasing number of "A task was canceled" errors. A typical trace might look like this:
Fatal web api error: Controller: CustomerUserEventsController;
Url: http://app.payboard.com/api/organizations/9ddf55d1-e0c1-4a8f-9327-eef38682e090/addcustomeruserevent?callback=jQuery210035782216349616647_1398442710964&cookieId=05be2755-dc0d-414d-b0d2-ea1986a929c3&customerId=&customerName=&customerUserId=&customerUserFirstName=&customerUserLastName=&eventName=hr-index-GET&_=1398442710965;
Error: A task was canceled. ( at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Controllers.ExceptionFilterResult.<ExecuteAsync>d__0.MoveNext())
We used to maybe get one a day; it's been increasing gradually, so that now we're getting a couple dozen.
You'll notice that there's only framework code in the stack trace - none of our code is in there at all. So I'm a bit at a loss for how to troubleshoot it. Any suggestions on how to approach tracking these down?
See the answer here:
ASP.NET Web API OperationCanceledException when browser cancels the request
And the WebAPI bug here:
http://aspnetwebstack.codeplex.com/workitem/1797
Basically, it's expected when an HTTP request is canceled, for instance, if the user closes the page that initiated the request. To keep it from showing up in your logs, basically, you just need to create a custom message handler that suppresses the error:
/// <summary>
/// See https://stackoverflow.com/questions/22157596/asp-net-web-api-operationcanceledexception-when-browser-cancels-the-request
/// </summary>
public class CancelledTaskBugWorkaroundMessageHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var response = await base.SendAsync(request, cancellationToken);
// Try to suppress response content when the cancellation token has fired; ASP.NET will log to the Application event log if there's content in this case.
if (cancellationToken.IsCancellationRequested)
{
return new HttpResponseMessage(HttpStatusCode.InternalServerError);
}
return response;
}
}
Had the exact same problem. In my case the solution was to change the authority (an https URL) from https://login.windows.net/... to https://login.microsoftonline.com/... as it could not be reached anymore. I am not publishing the full authority as it is a specific one for our organisation. Theoretically the first one is more direct, so I used that based on advise from a Microsoft specialist. But if it cannot be reached then there is a problem. Will need to go figure out nw why it is unreachable.
Hope this will be a lead to resolve your issues.
Regards,
Coen.
I followed the Live Authentication tutorial on the Azure Mobile Services page (http://www.windowsazure.com/en-us/develop/mobile/tutorials/single-sign-on-windows-8-dotnet/)
and when I run this line of code
LiveLoginResult result = await liveIDClient.LoginAsync(new[] { "wl.basic" });
I get a "NullReferenceException" no matter what I do. I tried changing "wl.basic" to "wl.signin" and that didn't work either.
I am signed into my Microsoft Account, I get the pop-up to allow it to login, the app is associated to my dev account, and I have added the client key and secret to my azure account.
Thanks a ton for the help everyone! It's driving me crazy. Here's the full code if it helps. It doesn't get passed the line stated above and I posted on MSDN as well, just thought StackOverflow would be more helpful.
private LiveConnectSession session;
private async System.Threading.Tasks.Task Authenticate()
{
LiveAuthClient liveIDClient = new LiveAuthClient("https://mobileserviceexample.azure-mobile.net/");
while (session == null)
{
// TODO: Added for testing of multiple microsoft accounts. Only works on non-connected accounts
if (liveIDClient.CanLogout)
{ liveIDClient.Logout(); }
LiveLoginResult result = await liveIDClient.LoginAsync(new[] { "wl.basic" });
if (result.Status == LiveConnectSessionStatus.Connected)
{}
Exception:
System.NullReferenceException was unhandled by user code
HResult=-2147467261
Message=Object reference not set to an instance of an object.
Source=Microsoft.Live
StackTrace:
at Microsoft.Live.ResourceHelper.GetString(String name)
at Microsoft.Live.TailoredAuthClient.<AuthenticateAsync>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at Microsoft.Live.LiveAuthClient.<ExecuteAuthTaskAsync>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at CommunistTutsApp.HomePage.<Authenticate>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
at CommunistTutsApp.HomePage.<OnNavigatedTo>d__f.MoveNext()
I had the same issue- "Object Reference not set to the instance of an object" when calling LoginAsync.
Make sure you have entered the Redirect URL in the Live Connect setup- see Step 4 of the attached link-
https://www.windowsazure.com/en-us/develop/mobile/how-to-guides/register-for-microsoft-authentication/
Thank you!