Face Detection in Azure - azure

I am trying to experiment with the Microsoft Azure Cognitive Services Face Detection. I am doing something wrong. I am trying to use the C# SDK for face detection. I am getting the error below. I have no idea how to even debug this or what the error message is telling me. Its almost like something I have set is not coming through, but I am just guessing.
Microsoft.Azure.CognitiveServices.Vision.Face.Models.APIErrorException
HResult=0x80131500
Message=Operation returned an invalid status code 'BadRequest'
Source=Microsoft.Azure.CognitiveServices.Vision.Face
StackTrace:
at Microsoft.Azure.CognitiveServices.Vision.Face.FaceOperations.<DetectWithUrlWithHttpMessagesAsync>d__9.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
at Microsoft.Azure.CognitiveServices.Vision.Face.FaceOperationsExtensions.<DetectWithUrlAsync>d__4.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at BWD.ASPNET.Core.Services.FaceDetection.<DoWork>d__5.MoveNext() in
My code for making this call is:
string faceEndpoint = "https://eastus.api.cognitive.microsoft.com";
FaceAttributeType[] faceAttributes =
{ FaceAttributeType.Age, FaceAttributeType.Gender, FaceAttributeType.Hair,
FaceAttributeType.Smile, FaceAttributeType.Gender, FaceAttributeType.Emotion, FaceAttributeType.FacialHair,
FaceAttributeType.Accessories };
FaceClient faceClient = new FaceClient( new ApiKeyServiceClientCredentials(connString), new System.Net.Http.DelegatingHandler[] { });
faceClient.Endpoint = faceEndpoint;
var ctx = new BWDContext();
var pics = await (from p in ctx.Picture where p.DateOfFacial == null select p).ToListAsync();
foreach(var pic in pics)
{
if(Uri.IsWellFormedUriString(pic.PicFileUrl, UriKind.Absolute))
{
IList<DetectedFace> faceList =
await faceClient.Face.DetectWithUrlAsync(pic.PicFileUrl, true, true, faceAttributes); // error occurs here
.....on and on .......
I also tried making a rest call with fiddler, which does work. On the fiddler call, I just do a post to this url: https://eastus.api.cognitive.microsoft.com/face/v1.0/detect?returnFaceId=true&returnFaceLandmarks=false&returnFaceAttributes=age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,noise
My header is:
User-Agent: Fiddler
Ocp-Apim-Subscription-Key: ....subscription key......
Content-Type: application/json
Host: eastus.api.cognitive.microsoft.com
Content-Length: 107
My post body is:
{ 'url': 'https://bwdpictures.blob.core.windows.net/bwdpictures/d916acdd-ab9f-429e-8b75-6d5f9206a9b4.jpg' }
I get a result back from the rest call in fiddler.
I'm sure that the problem is something with my code, but I have no idea what the issue is. If you have some suggestions, I would appreciate it.
TIA,
Wally

Bingo. The problem was that I had the Gender attribute in the face attributes twice. I just noticed it. When I took the second one out, the problem was solved. Sorry for the post.

Related

Azure storage CloudBlockBlob.PutBlockAsync() The value for one of the HTTP headers is not in the correct format.

I'm developing a web site with backend web api ASP.NET CORE 2.1 and frontend angular 6.
In this site I'm integrating upload of large files through web api with microsoft.azure.storage 9.3.2. I'm doing this chunking by blocks, and sending them from FE to an endpoint. Inside I do the following logic:
var container = CloudStorageAccount.Parse(key).CreateCloudBlobClient().GetContainerReference(containerName);
var result = await container.CreateIfNotExistsAsync();
if (result)
{
await container.SetPermissionsAsync(new BlobContainerPermissions
{
PublicAccess = BlobContainerPublicAccessType.Blob
});
}
BlockBlob = container.GetBlockBlobReference(blobName);
await fileUploadSession.BlockBlob.PutBlockAsync(block.BlockId, chunkStream, null);
And I have an exception here that says " The value for one of the HTTP headers is not in the correct format."
the stackTrace is:
at Microsoft.WindowsAzure.Storage.Core.Executor.Executor.d__4`1.MoveNext() in C:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\WindowsRuntime\Core\Executor\Executor.cs:line 316
--- 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 Microsoft.WindowsAzure.Storage.Blob.CloudBlockBlob.d__62.MoveNext() in C:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\WindowsRuntime\Blob\CloudBlockBlob.cs:line 1020
--- 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 vidiwin2Api.Controllers.VideosController.d__18.MoveNext() in D:\repos\vidiwin2api\vidiwin2Api\Controllers\VideosController.cs:line 469
The most amazing is that I had the same functionality in an older version, with BE web api on Framework 4.6 and microsoft.azure.storage 6.0.0, and this works!!
I have tested all kind of params in PutBlockAsync and allways the same exception.
Can anyone helps me please?
I had the same error because i forgot to reset the stream position to 0 before calling PutBlockAsync(). Try
chunkStream.Position = 0;
await fileUploadSession.BlockBlob.PutBlockAsync(block.BlockId, chunkStream, null);
Otherwise inspect the ExtendedErrorInformation property on the Exception. There you will find additional information about the wrong HTTP header.

An unhandled exception has occurred: Malformed URL in Release mode in .net core 2.0 app

I have a .net core 2.0 app which uses IdentityServer 4. it works perfectly in development mode. then I published it for production mode and tested. when I click a (that action has a method to generated accesstoken) link I got an error like below,
An unhandled exception has occurred: Malformed URL
then error occurs here in production(Release) mode:
var disco = await IdentityModel.Client.DiscoveryClient.GetAsync(_configuration.GetSection("Settings").GetSection("DiscoveryClient").Value);
above DiscoveryClient is http not https
here is the full description of the error ..
Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware[0]
An unhandled exception has occurred: Malformed URL
System.InvalidOperationException: Malformed URL
at IdentityModel.Client.DiscoveryClient.ParseUrl(String input)
at IdentityModel.Client.DiscoveryClient..ctor(String authority, HttpMessageHandler innerHandler)
at IdentityModel.Client.DiscoveryClient.<GetAsync>d__1.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.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
is this because 'https'. I have no idea what is happening.hope your help with this.
This is a pretty old post, but it still might help someone. I had this exact same issue, only that the URL that I was passing in was perfectly fine. The problem on my side was that the IdentityServer Authority URL was misconfigured, causing it to throw the same exception.
Here is code snippet from DiscoveryClient's ParseUrl showing when it throws that exception:
public static DiscoveryEndpoint ParseUrl(string input)
{
var success = Uri.TryCreate(input, UriKind.Absolute, out var uri);
if (success == false)
{
throw new InvalidOperationException("Malformed URL");
}
if (!DiscoveryEndpoint.IsValidScheme(uri))
{
throw new InvalidOperationException("Malformed URL");
}
Here is the code for DiscoveryEndpoint's IsValidScheme method:
public static bool IsValidScheme(Uri url)
{
if (string.Equals(url.Scheme, "http", StringComparison.OrdinalIgnoreCase) ||
string.Equals(url.Scheme, "https", StringComparison.OrdinalIgnoreCase))
{
return true;
}
return false;
}
Based on this the exception is not thrown because the url is using http.
Try calling
new Uri(_configuration.GetSection("Settings").GetSection("DiscoveryClient").Value, UriKind.Absolute)
before your call to 'IdentityModel.Client.DiscoveryClient.GetAsync' so that you can see what exception is thrown by the Uri constructor.

Sporadically receiving 502 bad gateway error with Spotify Web API

Sometimes, while calling the https://api.spotify.com/v1/me endpoint, I receive a 502 bad gateway error. This error occurs sporadically.
I would appreciate any help. Thanks!
Code:
PublicProfile profile = null;
var url = "https://api.spotify.com/v1/me";
using (var wc = new WebClient())
{
wc.Headers.Add("Authorization", TokenType + " " + AccessToken);
var response = wc.DownloadString(url);
profile = JsonConvert.DeserializeObject<PublicProfile>(response, settings);
}
I having the same issue. A majority of time when I make this request I get the 502: Bad Gateway response. Occasionally I will get an actual response. I am using Python and rauth library to make this request, this leads me to believe this is an error on Spotify's end and not ours.

RabbitMQ, EasyNetQ With NodeJS?

I'm trying to understand what's reasonable for integrating these technologies. How would I go about integrating NodeJS (currently using amqplib, but that could be changed) across RabbitMQ to EasyNetQ?
I have it sort of working, except EasyNetQ is expecting an object (I think) and Node/amqplib can only send strings.
C# code:
Bus.Subscribe<BusManifestHolla>(HollaID,
msg => {
Console.WriteLine("Received Manifest Holla ID {0}", msg.ManifestID.ToString());
Console.WriteLine("Responding with Manifest Yo ID {0}", YoID_1);
Bus.Publish(new BusManifestYo { ManifestID = msg.ManifestID, ServiceName = YoID_1 });
}
);
NodeJS code:
var b = new Buffer(JSON.stringify(new dto.BusManifestHolla(uuid.v4())));
ch.publish(Play.exchangeName, '#', b);
The result:
DEBUG: HandleBasicDeliver on consumer: a60b7760-e22f-4685-9f65-039bef19f58c, deliveryTag: 1
DEBUG: Recieved
RoutingKey: '#'
CorrelationId: ''
ConsumerTag: 'a60b7760-e22f-4685-9f65-039bef19f58c'
DeliveryTag: 1
Redelivered: False
ERROR: Exception thrown by subscription callback.
Exchange: 'RabbitMon.BusManifestHolla:RabbitMon'
Routing Key: '#'
Redelivered: 'False'
Message:
{"Guid":"a6cf174d-9b77-4558-bbda-efe9d8451dff"}
BasicProperties:
ContentType=NULL, ContentEncoding=NULL, Headers=[], DeliveryMode=0, Priority=0, CorrelationId=NULL, ReplyTo=NULL, Expiration=NULL, MessageId=NULL, Timestamp=0, Type=NULL, UserId=NULL, AppId=NULL, ClusterId=
Exception:
System.NullReferenceException: Object reference not set to an instance of an object.
at EasyNetQ.TypeNameSerializer.DeSerialize(String typeName)
at EasyNetQ.RabbitAdvancedBus.<>c__DisplayClass16.<Consume>b__15(Byte[] body, MessageProperties properties, MessageReceivedInfo messageRecievedInfo)
at EasyNetQ.Consumer.HandlerRunner.InvokeUserMessageHandler(ConsumerExecutionContext context)
Is there not a way to send an object across the bus? How do you integrate these two?
It's failing on the TypeNameSerializer.DeSerialize call. In your node code you'll need to populate BasicProperties.Type with the type that EasyNetQ should expect at the other end. This needs to be a fully qualified name including the assembly name. Just look at the name that EasyNetQ has given to your BusManifestHolla queue minus the HollaID value (and underscore).
Admittedly that error message isn't very helpful. It probably could be improved.

Cannot deserialize some tweets using NewtonSoft.Json

Hi All,
I am running a C# console app that is using the Twitter Stream API. My code is below
JToken json = JObject.Parse(ResponseStream.ReadLine());
For every +- 20 tweets, I get the following error "Error reading JObject from JsonReader".
I copied the json into JSONLint and it is valid, so I am perplexed to why this keeps happening. Has anyone else had this error?
Yes, and it just started happening recently. I believe it is either a bug with NewtonSoft.Json or a change in the twitter api causing it to send bad jsons. I did a packet capture and found the offending character by counting them, but I didn't see anything wrong. I think we will just have to wait for this bug to be fixed.
update
I downgraded Newtonsoft.Json.dll to 4.3.* and it works fine.
I found the issue. Sometimes the stream returns an empty string. Therefore parsing an empty string will throw an error. An example below on how I protected against it:
public static void ProccessTweet(object objMessage)
{
if(objMessage.ToString() != "")
{
var json = JObject.Parse(objMessage.ToString());
if (json["retweeted_status"] == null)
{
var message = ProcessNewTweet(json);
Db.Votes.Add(new FNBVote
{
Message = message,
Entry = Db.Entries.Find(message.Entry.EntryId)
});
return;
}
ProcessRetweet(json);
}
}

Resources