I'm trying to delete a blob snapshot - I don't want to delete anything other than the snapshot for which I have the reference.
await snapshotBlob.DeleteAsync(DeleteSnapshotsOption.None,
acc,
new BlobRequestOptions(),
new OperationContext());
I've tried different DeleteSnapshotsOption but the exception tells me that only DeleteSnapshotsOption.None can be used when deleting a snapshot.
The AccessCondition (acc) has only the LeaseID set.
I don't have BlobRequestOptions or OperationContext preferences; I've also tried passing null for those two properties but it makes no difference.
The method call throws "The remote server returned an error: (400) Bad Request."
Stack trace:
Microsoft.WindowsAzure.Storage.StorageException at
Microsoft.WindowsAzure.Storage.Core.Executor.Executor.EndExecuteAsync[T](IAsyncResult
result) at
Microsoft.WindowsAzure.Storage.Blob.CloudBlob.EndDelete(IAsyncResult
asyncResult) at
Microsoft.WindowsAzure.Storage.Core.Util.AsyncExtensions.<>c__DisplayClass4.b__3(IAsyncResult
ar)
--- 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.ConfiguredTaskAwaitable.ConfiguredTaskAwaiter.GetResult()
at StorageHooks.StorageBackup.d__0.MoveNext() in [line in my
code]
Can anyone explain what's wrong with the way I'm calling the method?
Also, in case it has an influence, I'm calling this method in an Azure Function. Furthermore, the code is copying existing blobs into another container, and the code works for creating a snapshot, creating the new blob, uploading to the other container, copying metadata, obtaining a lease... The only part which fails is deleting the snapshot.
I tried your code and traced the request/response through Fiddler. When I specified the lease id in the access condition, I got the 400 error. When I looked up the details, this is what the error message told me:
<?xml version="1.0" encoding="utf-8"?>
<Error>
<Code>InvalidQueryParameterValue</Code>
<Message>
Value for one of the query parameters specified in the request URI is invalid.
RequestId:cb8bcb1d-001e-004a-4811-991d8e000000
Time:2018-01-29T15:00:02.6030417Z
</Message>
<QueryParameterName>snapshot</QueryParameterName>
<QueryParameterValue>2018-01-29T14:55:27.3537780Z</QueryParameterValue>
<Reason>Leases are not allowed with snapshots.</Reason>
</Error>
Please try your request by removing the access condition from your request. When I did that, the request went just fine. So your code would be:
await snapshotBlob.DeleteAsync(DeleteSnapshotsOption.None)
Related
I have an issue with getting embed token. I've done all 5 steps which is described in this link (5 steps to push data into a dataset) and everything works perfectly: datasets are created, tables are created and filled in with data without any problems.
I have a task to embed a datasets (not reports) to web page.
I found this page (Power BI Embeded Sample) which shows how embed report/dataset/dashboard/tile will look like. And on this page there is an embed token.
I googled a little and found this page (Generate Embed Token Example) which describes the looks oh HTTP POST requests. I did the part for datasets. Here is my code example:
private static void generateEmbedToken()
{
// TokenCredentials Initializes a new instance of the
// Microsoft.Rest.TokenCredentials class with
// the given 'Bearer' token.
var credentials = new TokenCredentials(token);
// Initialize PowerBIClient with credentials
var powerBIclient = new Microsoft.PowerBI.Api.V2.PowerBIClient(credentials)
{
// BaseUri is the api endpoint, default is https://api.powerbi.com
BaseUri = new Uri("https://api.powerbi.com")
};
try
{
// Create body where accessLevel = View, datasetId = "" by default
var requestParameters = new GenerateTokenRequest(TokenAccessLevel.Create, datasetId, true);
// Generate EmbedToken This function sends the POST message
//with all parameters and returns the token
EmbedToken token = powerBIclient.Reports.GenerateTokenForCreate(requestParameters);
embedToken = token.Token;
}
catch (Exception exc)
{
Console.WriteLine(exc.ToString());
}
}
and I got next error:
Microsoft.Rest.HttpOperationException: Operation returned an invalid status code 'NotFound'
at Microsoft.PowerBI.Api.V2.Reports.<GenerateTokenForCreateWithHttpMessagesAsync>d__8.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.PowerBI.Api.V2.ReportsExtensions.<GenerateTokenForCreateAsync>d__7.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.PowerBI.Api.V2.ReportsExtensions.GenerateTokenForCreate(IReports operations, GenerateTokenRequest requestParameters)
at PushDataApp.Program.generateEmbedToken() in C:\Users\PC\Documents\Visual Studio 2017\Projects\PushDataApp\PushDataApp\Program.cs:line 388
here is line 388:
EmbedToken token = powerBIclient.Reports.GenerateTokenForCreate(requestParameters);
I don't know why it's happening.
I took this code from here (Generate Embed Token Example), but I did some changes for my purposes (because I need dataset and not report).
I'll appreciate any help.
I have come across a similar error when attempting to embed using Power BI. I recommend using a tool like Fiddler to intercept the communication between your application and Power BI and finding out the error code that is actually being returned.
The following article from Telerik shows how to intercept traffic using Fiddler: Capturing Traffic from .NET Services with Fiddler
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?
I'm using the WebClient class. I've had some luck with the OpenReadTaskAsync method with a GET, but right now, I want to call a POST, or PUT REST method. I figured that I should use UploadStringTaskAsync. But, when I call this method on a working REST service, I get this error:
System.Net.WebException: An exception occurred during a WebClient request. ---> System.NotSupportedException: Specified method is not supported on this request.
at System.Net.Browser.BrowserHttpWebRequest.set_Method(String value)
at System.Net.WebClient.GetWebRequest(Uri address)
at System.Net.WebClient.UploadStringAsync(Uri address, String method, String data, Object userToken)
--- End of inner exception stack trace ---
at Microsoft.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at Microsoft.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccess(Task task)
at Microsoft.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at CF.RESTClientDotNet.Silverlight.Sample.MainPage.d__3.MoveNext()
This is the code
var webClient = new WebClient();
var returnValue = await webClient.UploadStringTaskAsync(uri.AbsoluteUri, "POST", bodyString);
I ended up completely redesigning my library. There are samples here:
https://bitbucket.org/MelbourneDeveloper/restclient-.net/src/master/
NuGet: Install-Package RESTClient.NET
I am working on a Windows Runtime Component which makes API calls. Until earlier today I used the HttpClient and related models from System.Net but switched over to Windows.Web instead to leverage the WinRT streams.
Aside from changing the using statements, swapping HttpContent to IHttpContent and using the WindowsRuntimeExtensions to change my IInputStream to Stream for JSON.NET, I didn't have to do anything special. However suddenly 3 out of my 16 tests fail whereas previously everything worked.
All 3 (integration) tests validate that I receive an error response when logging in with invalid credentials. There are other tests that include logging in as well (but with valid credentials) and they work just fine. The given error message is of type AggregateException and has as message
System.AggregateException: One or more errors occurred. ---> System.Exception: Element not found.
A dialog cannot be displayed because the parent window handle has not been set.
The exception contains HRESULT values. The outerexception has value -2146233088 which corresponds to 0x80131500 while the innerexception has -2147023728 which corresponds to 0x80070490. Neither of those are a known error code on the MSDN page.
Following investigation:
0x80131500 corresponds to COR_E_EXCEPTION
0x80070490 corresponds to ERROR_NOT_FOUND
Stacktrace:
Result StackTrace:
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at xx.Models.Requests.GetRequest.<ExecuteRequestAsync>d__0.MoveNext() in c:\Users\jeroen\Github\Windows-app\xx\xx\Models\Requests\Request.cs:line 17
--- 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 xx.ApiDispatcher.<ExecuteAsync>d__0`2.MoveNext() in c:\Users\jeroen\Github\Windows-app\xx\xx\ApiDispatcher.cs:line 40
--- End of inner exception stack trace ---
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
at System.Threading.Tasks.Task`1.get_Result()
at xx.ApiDispatcher.Execute[TCallResult,TResponseObject](ApiCall`2 call) in c:\Users\jeroen\Github\Windows-app\xx\xx\ApiDispatcher.cs:line 22
Originally my question was worded somewhat differently because the actual problem seemed to be hidden. I have found out that the GET request by the HttpClient returns back to the caller instead of awaiting the result of the call (and executing the rest of the method).
In my project, executing the line var data = await myHttpClient.GetAsync(url); will return to the calling method with a non-constructed object and subsequent lines that come after the GetAsync() call are simply not executed.
Adding .ConfigureAwait(false) to stop it from going back did not make a difference.
The AggregateException is thrown when a user tries to login with invalid credentials. For some reason the HttpClient decides to throw an exception then without giving me a return value I could use. The problem here is that it does not tell me what kind of exception: catching COMException, TaskCanceledException, AggregateException and Exception only trigger the latter.
I have also found out that asynchronous integration tests do not work well with the multithreaded MSTest environment, so that explains several other failed tests that I had (but worked just fine individually)
I also, finally, have an example that demonstrates the problem (but I can't provide a webservice that takes basic auth)!
[TestMethod]
public void TestMethod3()
{
Assert.IsTrue(new Test().Do().AsTask().Result);
}
public sealed class Test
{
public IAsyncOperation<bool> Do()
{
return DoSomething().AsAsyncOperation();
}
private async Task<bool> DoSomething()
{
var client = new HttpClient();
var info = "jeroen.vannevel#something.com:nopass";
var token = Convert.ToBase64String(Encoding.UTF8.GetBytes(info));
client.DefaultRequestHeaders.Authorization = new HttpCredentialsHeaderValue("Basic", token);
var data = await client.GetAsync(new Uri("https://mytestdomain/v2/apikey?format=Json"));
return true;
}
}
Executing this code with a valid password will return true while an invalid password will throw an AggregateException.
Right now I am working around the problem by catching a general Exception around the call to GetAsync() but this is very rudimentary and I'd like to know why this incomplete exception is thrown in the first place.
After reconstructing your example and playing around, I figured out what happens.
var data = await client.GetAsync(new Uri("https://mytestdomain/v2/apikey?format=Json"));
The GetAsync method invokes the HTTP request with invalid credentials. What happens is that the returned request tries to look for a window where you can enter the correct credentials, but doesn't find one. Hence it throws an Element Not Found while searching for that window.
This can be fixed by creating a HttpBaseProtocolFilter and setting the AllowUI property to false and then passing it to the HttpClient:
private async Task<bool> DoSomething()
{
var httpBaseFilter = new HttpBaseProtocolFilter
{
AllowUI = false
};
var client = new HttpClient(httpBaseFilter);
var info = "jeroen.vannevel#something.com:nopass";
var token = Convert.ToBase64String(Encoding.UTF8.GetBytes(info));
client.DefaultRequestHeaders.Authorization = new HttpCredentialsHeaderValue("Basic", token);
var data = await client.GetAsync(new Uri("https://mytestdomain/v2/apikey?format=Json"));
return true;
}
Setting AllowUI on HttpBaseProtocolFilter to false will stop this error.
If however you do want a dialog box to display, allowing the user to enter credentials, then the web request needs to be started on the UI thread.
I think the problem is that the exception is actually thrown by your call to EnsureSuccessStatusCode.
Did you try adding HttpResponseMessage class EnsureSuccessStatusCode() method and check.
http://msdn.microsoft.com/en-us/library/system.net.http.httpresponsemessage.ensuresuccessstatuscode.aspx
After this line:
var data = await client.GetAsync(new Uri("https://mytestdomain/v2/apikey?format=Json"));
date.EnsureSuccessStatusCode();
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.