Custom Vision Predictiong a simple image: not found - microsoft-custom-vision

I am trying to get a very simple c# snippet on predicting an image, but get following error (there is very little on the internet around this subject):
Microsoft.Azure.CognitiveServices.Vision.CustomVision.Prediction.Models.CustomVisionErrorException HResult=0x80131500 Message=Operation returned an invalid status code 'NotFound'
var predictionClient = GetPredictionClient();
predictionClient.ClassifyImageUrl(Guid.Parse("5329678e-2a6b-46cf-ac11-fbd19ce89353"), "Iteration2", new ImageUrl("https://storageinfluencer.blob.core.windows.net/social-media-images/1e8bfef3-f070-44b9-9ae4-4b0d8a31316d.jpg"));
CustomVisionPredictionClient GetPredictionClient()
{
CustomVisionPredictionClient endpoint = new CustomVisionPredictionClient()
{
ApiKey = "xxx",
Endpoint = "https://northeurope.api.cognitive.microsoft.com/customvision/v3.0/Prediction/"
};
return endpoint;
}
I got a little closer by using fiddler. EndPoint should be https://northeurope.api.cognitive.microsoft.com only even if portal says copy the other as end point. However now I get:
{"code":"BadRequest","message":"Invalid project type for operation."}
I have following POST in fiddler:
https://northeurope.api.cognitive.microsoft.com/customvision/v3.0/prediction/xx-xx-xx-xx-xx/classify/iterations/Iteration2/url HTTP/1.1

I think I finally found why you got this 404, thanks to... Intelligent Kiosk demo being open-source!
See how they pass the endpoint value in their code, here:
private const string SouthCentralUsEndpoint = "https://southcentralus.api.cognitive.microsoft.com";
As you can see, the Endpoint field is the value of the root, not the Custom Vision Prediction API root
So change your
Endpoint = "https://northeurope.api.cognitive.microsoft.com/customvision/v3.0/Prediction/"
to:
Endpoint = "https://northeurope.api.cognitive.microsoft.com"
And it should be fine. I made a test with WestEurope and some CustomVision projects that I already had, it is working fine.

Related

Create team from group fails with exception

I created teams in Microsoft Teams (from groups as documented here) via the C# graph-api sdk without any problems - everything was working just fine.
But suddenly this is not working anymore. I will always get the following exception at the line return await graphServiceClient.Teams.Request().AddAsync(team);:
Message: Failed to execute Templates backend request
CreateTeamFromGroupWithTemplateRequest. Request Url:
https://teams.microsoft.com/fabric/emea/templates/api/groups/theGroupId/team,
Request Method: PUT,
And further:
Team Visibility can not be specified as it is inherited from the
group.
I know that the visibility property must not be set if creating the team from a group as it states in the Microsoft documentation:
The team that's created will always inherit from the group's display name, visibility, specialization, and members. Therefore, when making this call with the group#odata.bind property, the inclusion of team displayName, visibility, specialization, or members#odata.bind properties will return an error.
But the currently used code below shows that I am not setting any forbidden properties - and this code worked for the last few days, too:
private async Task<Team> CreateTeamFromGroup(string groupId)
{
var graphServiceClient = [...]
var groupResourceLink = $"https://graph.microsoft.com/v1.0/groups('{groupId}')";
var team = new Team
{
AdditionalData = new Dictionary<string, object>()
{
{ "template#odata.bind", "https://graph.microsoft.com/beta/teamsTemplates('standard')" },
{ "group#odata.bind", groupResourceLink }
},
Channels = new TeamChannelsCollectionPage
{
new Channel
{
DisplayName = "WhatEver"
}
}
};
return await graphServiceClient.Teams.Request().AddAsync(team);
}
Is anyone else experiencing this problem? Was there an API change? Was the teams backend changed? Anyone any ideas?
P.S.: I am using the latest NuGet-Package for Microsoft Graph - downgrading didn't help.
Update (with a not very satisfying work-around)
The error can be reproduced via the graph api explorer, too.
The POST command above issues a PUT command, that is described here. With this request, the team can be created.
The documentation and the graph api snippet for C# is out-dated, though. You have to add odatatype = null to the properties when using the sdk
Unfortunately it is not possible to add channels in the same step. If you specify the property 'channels' it will just be ignored.
Update (Detailed error message)
System.AggregateException: 'One or more errors occurred. (Code:
BadRequest Message: Failed to execute Templates backend request
CreateTeamFromGroupWithTemplateRequest. Request Url:
https://teams.microsoft.com/fabric/emea/templates/api/groups/theGroupId/team,
Request Method: PUT, Response Status Code: BadRequest,
ErrorMessage : {"errors":[{"message":"Team Visibility can not be
specified as it is inherited from the
group."}],"operationId":"639448e414ece64caee8f52839585bf7"} Inner
error: AdditionalData: date: 2020-11-24T10:21:22 request-id:
37a28cac-3ac5-4bd2-a061-daf44c442fac client-request-id:
37a28cac-3ac5-4bd2-a061-daf44c442fac ClientRequestId:
37a28cac-3ac5-4bd2-a061-daf44c442fac )'
Just tested this morning and I can say, that the "old way" by using the beta API to create a team with a template works again. Don't know, how many other ways exist to do these things, but here is our current request, that works now (again).
POST https://graph.microsoft.com/beta/teams
{
"displayName": "My Group Name",
"description": "Some description",
"template#odata.bind": "https://graph.microsoft.com/beta/teamsTemplates('educationClass')",
"owners#odata.bind": [
"https://graph.microsoft.com/beta/users('<someValidUserId>')"
]
}
I think this will be just an intermediate state and when the bugs are fixed, they will publish the new version again and this kind of creation will fail again, but if in this case the v1.0 documented way will work this wouldn't be a big problem. But being informed BEFORE there roll-out starts would be great.
This was a Microsoft issue/ bug and is currently being fixed as stated here.

Unable to update Table Row Values

I am attempting to update a table using a python library to iterate through the table rows.
I get this error: "Error Message: The API you are trying to use could not be found. It may be available in a newer version of Excel."
Adding rows succeeds, but any APIs on the rows endpoint doesn't work, I can't get range or update a row. I even tried going directly to requests to have more control over what gets passed. I tried both the v1.0 and beta endpoints as well.
https://learn.microsoft.com/en-us/graph/api/tablerow-update?view=graph-rest-1.0&tabs=http
Here is the URL Endpoint I am calling:
https://{redacted}/items/{file_id}/workbook/tables/Table1/rows/0
Any help is appreciated.
Update to add code (you have to have an existing authenticated requests session to run it in python):
data = {'values': [5, 6, 7]}
kwargs = {
'data': json.dumps(data),
'headers': {
'workbook-session-id': workbook.session.session_id,
'Content-type': 'application/json'}}
# Works
sharepoint = 'onevmw.sharepoint.com,***REDACTED***'
drive = '***REDACTED***'
item = '****REDACTED***'
base_url = f'https://graph.microsoft.com/v1.0//sites/{sharepoint}/drives/{drive}/items/{item}'
get_url = f"{base_url}/workbook/tables/{test_table.name}/rows"
session = office_connection.account.connection.get_session(load_token=True)
get_response: requests.Response = session.request(method='get', url=get_url)
print(get_response.text)
# Doesn't work
url = f"{base_url}/workbook/tables/{test_table.name}/rows/1"
response: requests.Response = session.request(method='patch', url=url, **kwargs)
print(response.text)
That's an issue. Unfortunately it not documented at the moment in the offical documentation.
I could make it work by changing the url from ".../rows/1" as ".../rows/itemAt(index=1)"
Posting the C# solution for others since the Msft Docs are incorrect and the actual solution is similar to #Amandeep's answer for javascript.
The docs (incorrectly) say:
...Tables["table_name"].Rows["row_num"].Request().UpdateAsync(); // incorrect!
Correct way:
...Tables["table_name"].Rows.ItemAt(123).Request().PatchAsync(wbRow); // correct!
Note the .ItemAt method takes an int, not a string.

Create managedDevice in Intune using Graph API

I am trying to create a managed device in Intune using the following Microsoft Graph but it keeps erroring out.
I also get an error when trying to update an existing device record.
I have the appropriate scopes and my account is an Intune admin. Any suggestions?
Here is the example error I receive when trying to update using PATCH
"error": {
"code": "InternalError",
"message": "An error has occurred - Operation ID (for customer support): 00000000-0000-0000-0000-000000000000 - Activity ID: 7d3aea54-282a-4911-99a5-af3d2422f81a - Url: https://fef.amsua0502.manage.microsoft.com/DeviceFE/StatelessDeviceFEService/managedDevices%28%278f312966-1c51-403b-9b3a-6cf52643fa70%27%29?api-version=5017-09-07 - CustomApiErrorPhrase: ",
"innerError": {
"request-id": "7d3aea54-282a-4911-99a5-af3d2422f81a",
"date": "2017-11-02T12:16:55"
}
}
They have changed the endpoint without updating the documentation..
Use: /deviceManagement/managedDevices
It's a beta so endpoints and (more frequently) required parameters in the json object chances..
I've figured out a lot of these changes by simply looking at posts from the developer mode in a browser.
The documentation is often behind the actual implementation.
And yea this worked. sorry for late response..
Edit2:
I don't have an example to create a managed device. But this is an example on how to create an empty device configuration:
$Endpoint = "https://graph.microsoft.com/beta"
## Win10
$Win10 = [pscustomobject]#{
'#odata.type' = "#microsoft.graph.windows10GeneralConfiguration"
'description' = "standard Windows 10 Device Restriction Configuration"
'displayName' = "Win10"
}
$Win10params = #{
ContentType = 'application/json'
Headers = $Header
Body = $Win10 | ConvertTo-Json -Compress
Method = 'POST'
URI = "$Endpoint/deviceManagement/deviceConfigurations"
}
Invoke-RestMethod #Win10params
But again. Take a look at the POST in the developer tab, and then start by trying out parameters from the top. If the documentation isn't updated with the least required parameters, you will have to go through it step by step..
They have changed the endpoint without updating the documentation..
Use: /deviceManagement/managedDevices

Google+ api with dart chrome app - 403 Daily Limit

I am trying to use the google_plus_v1_api + google_oauth2_client within a chrome packaged app.
Everythin works fine when i am using only the oauth2 lib:
chrome.identity.getAuthToken(new chrome.TokenDetails(interactive:true))
.then((token){
OAuth2 auth = new SimpleOAuth2(token);
var request = new HttpRequest();
request.onLoad.listen((d){print(request.response);
request.open('GET', 'https://www.googleapis.com/plus/v1/people/me');
auth.authenticate(request).then((request) => request.send());
});
But i can't make google+ lib works:
chrome.identity.getAuthToken(new chrome.TokenDetails(interactive:true))
.then((token){
OAuth2 auth = new SimpleOAuth2(token);
Plus plus = new Plus(auth);
plus.people.get('me').then((d)=>print(d));
});
Return this exception:
GET https://www.googleapis.com/plus/v1/people/me 403 (Forbidden)
Exception: APIRequestException: 403 Daily Limit for Unauthenticated
Use Exceeded. Continued use requires signup.
Am i missing something? How am i supposed to use google+ api lib?
I just saw your answer, but wanted to point out I had the same problem and solved it by setting the makeAuthRequests property of the Plus client to true:
final plusclient.Plus plus = new plusclient.Plus(auth)
..makeAuthRequests = true;
Seems like a more straightfoward solution, since the auth object already contains the token. I would've expected makeAuthRequests to be automatically set to true when constructing a Plus client with an OAuth2 object, but apparently it's not (probably an oversight).
Sorry, i figured out that this line was missing thanks to this tutorial :
plus.oauth_token = auth.token.data;
My google_plus_v1_api query is now working.
Sorry for the inconvenience.

QuickBooks Online querying with filter returns 401 everytime

I've had success creating objects with POST and Content-Type application/xml
I've also had success querying using Content-Type application/x-www-form-urlencoded with a blank request body which returns all of the object type depending on which URI I specify.
I can also get the same to work with something like PageNum=1&ResultsPerPage=1 in the request body and I have figured out how to incorporate that into the signature so I get a valid response.
However no matter how I format it, I cannot get anything other than a 401 response when I try to use a filter (something basic like Filter=FAMILYNAME :EQUALS: Doe). I've read over the OAuth Core 1.0 Revision A specifications on how all parameter names and values are escaped using the [RFC3986] percent-encoding. However I feel like I'm missing a step or formatting incorrectly. I've seen inconsistent information in my searching through Intuit's forums on what exactly is the proper format.
Any help on this would be greatly appreciated. I've been struggling with this for a good week now.
The response I get when trying to use a filter is:
HTTP Status 401 - message=Exception authenticating OAuth; errorCode=003200; statusCode=401
----Update----
I'm am seeing the same error when I try to use filters with the New IPP Developer Tools - IPP API Explorer. I'm using the IDS V2 QBO API Explorer. I'm able to use that tool to do a retrieve all Post and the response shows all of my customers, but when I try to use a filter I get :
Server Error
401 - Unauthorized: Access is denied due to invalid credentials.
You do not have permission to view this directory or page using the credentials that you supplied.
Any Ideas? If I'm getting the same error from the API Explorer tool, it makes me think the problem is something else entirely.
----Final Update----
I have finally had success with filters and I believe I have figure out what my problem was. I was always suspicious that I was able to get queries with pagination like "PageNum=1&ResultsPerPage=1" to work, but could not get something like "Filter=FAMILYNAME :EQUALS: Doe". I suspected there problem was with the white space in the filter format. What threw me off tracking this down earlier was that I could not get the filters to work in the IDS V2 QBO API Explorer. That made me suspect there was something else going on. I decided to ignore the API Explorer all together and focus on why I could get it to work the one way but no the other.
I believe my problem came down to improper encoding of the Filter's value in the signature. That explains the 401 invalid signature errors I was getting.
"Filter=Name :EQUALS: Doe" becomes "Filter=Name%20%3AEQUALS%20%3ADoe" after normalization.
Percent-Encoding that should give "Filter%3DName%2520%253AEQUALS%2520%253ADoe".
In essence you have to "double" encode the blank space and the colons, but not the equal sign. I tried many permutations of doing the encoding, but believe my mistake was that I was either not "double" encoding, or when I was double encoding I was including the '=' sign. Either way breaks your signature. Thanks for everyone's input.
I believe my problem came down to improper encoding of the Filter's value in the signature. That explains the 401 invalid signature errors I was getting.
I used an online tool to take me through the steps in properly signing an Oauth request. While going through those steps I realized my problem was with the steps where you normalize the request parameters and then percent-encode them. I was including the '=' of the filter in the normalization step, which breaks your signature. The tool I used can be found at:
http://hueniverse.com/2008/10/beginners-guide-to-oauth-part-iv-signing-requests/
Thanks for everyone's input.
Do you get a 401 with the same request in the API Explorer?
http://ippblog.intuit.com/blog/2013/01/new-ipp-developer-tool-api-explorer.html
Also, are you using the static base URL or retrieving it at runtime?
https://ipp.developer.intuit.com/0010_Intuit_Partner_Platform/0050_Data_Services/0400_QuickBooks_Online/0100_Calling_Data_Services/0010_Getting_the_Base_URL
If you are using the static base URL, try switching to the runtime base URL to see if you still get the error.
peterl answered one of my questions on here that may also answer yours. I had been trying to put the Filters in the body when they should have gone into the header. Here was peterl's code sample for getting all unpaid invoices (open balance greater than 0.00) for a particular customer.
http://pastebin.com/raw.php?i=7VUB6whp
public List<Intuit.Ipp.Data.Qbo.Invoice> GetQboUnpaidInvoices(DataServices dataServices, int startPage, int resultsPerPage, IdType CustomerId)
{
StringBuilder requestXML = new StringBuilder();
StringBuilder responseXML = new StringBuilder();
var requestBody = String.Format("PageNum={0}&ResultsPerPage={1}&Filter=OpenBalance :GreaterThan: 0.00 :AND: CustomerId :EQUALS: {2}", startPage, resultsPerPage, CustomerId.Value);
HttpWebRequest httpWebRequest = WebRequest.Create(dataServices.ServiceContext.BaseUrl + "invoices/v2/" + dataServices.ServiceContext.RealmId) as HttpWebRequest;
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.Headers.Add("Authorization", GetDevDefinedOAuthHeader(httpWebRequest, requestBody));
requestXML.Append(requestBody);
UTF8Encoding encoding = new UTF8Encoding();
byte[] content = encoding.GetBytes(requestXML.ToString());
using (var stream = httpWebRequest.GetRequestStream())
{
stream.Write(content, 0, content.Length);
}
HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;
using (Stream data = httpWebResponse.GetResponseStream())
{
Intuit.Ipp.Data.Qbo.SearchResults searchResults = (Intuit.Ipp.Data.Qbo.SearchResults)dataServices.ServiceContext.Serializer.Deserialize<Intuit.Ipp.Data.Qbo.SearchResults>(new StreamReader(data).ReadToEnd());
return ((Intuit.Ipp.Data.Qbo.Invoices)searchResults.CdmCollections).Invoice.ToList();
}
}
protected string GetDevDefinedOAuthHeader(HttpWebRequest webRequest, string requestBody)
{
OAuthConsumerContext consumerContext = new OAuthConsumerContext
{
ConsumerKey = consumerKey,
ConsumerSecret = consumerSecret,
SignatureMethod = SignatureMethod.HmacSha1,
UseHeaderForOAuthParameters = true
};
consumerContext.UseHeaderForOAuthParameters = true;
//URIs not used - we already have Oauth tokens
OAuthSession oSession = new OAuthSession(consumerContext, "https://www.example.com",
"https://www.example.com",
"https://www.example.com");
oSession.AccessToken = new TokenBase
{
Token = accessToken,
ConsumerKey = consumerKey,
TokenSecret = accessTokenSecret
};
IConsumerRequest consumerRequest = oSession.Request();
consumerRequest = ConsumerRequestExtensions.ForMethod(consumerRequest, webRequest.Method);
consumerRequest = ConsumerRequestExtensions.ForUri(consumerRequest, webRequest.RequestUri);
if (webRequest.Headers.Count > 0)
{
ConsumerRequestExtensions.AlterContext(consumerRequest, context => context.Headers = webRequest.Headers);
if (webRequest.Headers[HttpRequestHeader.ContentType] == "application/x-www-form-urlencoded")
{
Dictionary<string, string> formParameters = new Dictionary<string, string>();
foreach (string formParameter in requestBody.Split('&'))
{
formParameters.Add(formParameter.Split('=')[0], formParameter.Split('=')[1]);
}
consumerRequest = consumerRequest.WithFormParameters(formParameters);
}
}
consumerRequest = consumerRequest.SignWithToken();
return consumerRequest.Context.GenerateOAuthParametersForHeader();
}
You can also see my original Question Here on StackOverflow: Query for All Invoices With Open Balances using QuickBooks Online (QBO) Intuit Partner Platform (IPP) DevKit.

Resources