Cognitive Services Exception in Xamarin App - c#

Hi I am using Microsoft Cognitive Services and it's giving me an exception for some unknown reason. This is the way I declared FaceServiceRestClient:
var faceServiceClient = new FaceServiceRestClient("MY_KEY");
when I run above code it throws an exception by saying "Your Subscription key is invalid". I checked 3-4 times Key is correct, I also regenerated key and used it still exception is there.
Now, I added second parameter, thats URL so not my declaration is as follows:
var faceServiceClient = new FaceServiceRestClient("MY_KEY", "https://australiaeast.api.cognitive.microsoft.com/face/v1.0" );
For above statement I get an exception as "Java.Lang.IllegalStateException: Target host must not be null, or set in parameters. scheme=null, host=null, path=MY_KEY/detect"
This is how I am calling detect method (If you want to see)
Com.Microsoft.Projectoxford.Face.Contract.Face[] result = faceServiceClient.Detect(#params[0], true, false, null);
I do not understand exactly where to look at or which declaration is correct. & BTW this is Xamarin application and I used Xamarin.Microsoft.Cognitive.Face package. If you want to anything else in my code please Comment I will share code snippet.
Can anyone please help?
Thank you

"Java.Lang.IllegalStateException: Target host must not be null, or set in parameters. scheme=null, host=null, path=MY_KEY/detect"
That package wraps the Android/Java API and that API is different then the other platforms. In the case of FaceServiceRestClient, the Azure Face Endpoint is the first param, and your Face API key is the second.
Note: They did not even name the parameters in the binding library so you will see param names such as p0 p1 throughout the C# API :-( I ended up using Rekognition to work around the throughput limitations of Cognitive services, but that is a different story)
I stripped down a camera/photo tagger that I wrote to get you started.
Example:
await Task.Run(() =>
{
var faceServiceClient = new FaceServiceRestClient(faceEndpoint, faceAPIKey);
using (var imageFileStream = camera.SingleImageStream)
{
var faceAttributes = new FaceServiceClientFaceAttributeType[] { FaceServiceClientFaceAttributeType.Gender, FaceServiceClientFaceAttributeType.Age, FaceServiceClientFaceAttributeType.Smile, FaceServiceClientFaceAttributeType.Glasses, FaceServiceClientFaceAttributeType.FacialHair };
var faces = faceServiceClient.Detect(imageFileStream, true, false, faceAttributes);
foreach (var face in faces)
{
Log.Debug(TAG, $"{face.FaceRectangle.Left}:{face.FaceRectangle.Top}:{face.FaceRectangle.Width}:{face.FaceRectangle.Height}");
DrawFaceRect(face.FaceRectangle);
TagPhoto(face.FaceAttributes);
}
}
});

Related

How to find a type by FQN in a solution?

I am writing a Rider/ReSharper nav-from-here plugin which is supposed to determine a target type based on a symbol I am standing on using some simple rules, and finally, navigate to it.
The first part is okay, I have managed to form the FQN needed, but I am struggling with the navigation. I found this StackOverflow post, and thought I might try this approach. So I have been trying to use TypeFactory.CreateTypeByCLRName for like two hours to create an IDeclaredType instance to be able to get the IDeclaredElement using GetTypeElement() and eventually get its declarations. But the API seems to have changed and no matter what I do I cannot get my code to work.
Here is what I've got so far:
// does not work with Modules.GetModules(), either
foreach (var psiModule in solution.GetPsiServices().Modules.GetSourceModules())
{
var type = TypeFactory.CreateTypeByCLRName("MyNamespace.MyClassName", psiModule);
var typeElement = type.GetTypeElement();
if (typeElement != null)
{
MessageBox.ShowInfo(psiModule.Name); // to make sure sth is happening
break;
}
}
The weird part is, I actually see a message box - but only when the tab with MyClassName.cs is active. When it is in focus, everything is fine. When it's not or the file is closed, the class does not get resolved, type.IsResolved is false.
What am I doing wrong?
To do this, you should have a IPsiModule instance from the context where you plan to use the type you're looking for. You can get it from some syntax node you're working with via .GetPsiModule() method or via many other ways (like dataContext.GetData(PsiDataConstants.SOURCE_FILE)?.GetPsiModule().
void FindTypes(string fullTypeName, IPsiModule psiModule)
{
// access the symbol cache where all the solution types are stored
var symbolCache = psiModule.GetPsiServices().Symbols;
// get a view on that cache from specific IPsiModule, include all referenced assemblies
var symbolScope = symbolCache.GetSymbolScope(psiModule, withReferences: true, caseSensitive: true);
// or use this to search through all of the solution types
// var symbolScope = symbolCache.GetSymbolScope(LibrarySymbolScope.FULL, caseSensitive: true);
// request all the type symbols with the specified full type name
foreach (var typeElement in symbolScope.GetTypeElementsByCLRName(fullTypeName))
{
// ...
}
}

Access Denied status getting custom service's characteristics with GetCharacteristicsAsync

I'm attempting to get the characteristics of a custom BLE service. I have a NETStandard class library, making use of NETCore build 17134 for Bluetooth communication. This library is then used in a WPF application (.NET Framework 4.7.1.) I'm able to connect to my BLE peripheral, as well as read the generic service that includes Hardware Revision, etc. However, when it then goes to get the characteristics of my custom service, the status reads AccessDenied and the array of characteristics is empty. Any help would be greatly appreciated.
The same code works when it's purely UWP. However, I have no way to set Bluetooth permissions in the desktop app as I can in UWP. I've attempted running as administrator and performing the workaround using an AppID/registry entry. It didn't seem to work, but perhaps I simply did something wrong.
Is this a known issue? I've read there's been some regression since the original Creator's Update (15xxx) but the threads all seem about a year old.
protected async override Task<IList<ICharacteristic>> GetCharacteristicsNativeAsync()
{
var accessRequestResponse = await _nativeService.RequestAccessAsync();
// Returns Allowed
if (accessRequestResponse != Windows.Devices.Enumeration.DeviceAccessStatus.Allowed)
{
throw new Exception("Access to service " + _nativeService.Uuid.ToString() + " was disallowed w/ response: " + accessRequestResponse);
}
var allCharacteristics = await _nativeService.GetCharacteristicsAsync(Windows.Devices.Bluetooth.BluetoothCacheMode.Uncached);
// Status: AccessDenied
var status = allCharacteristics.Status;
// No error
var err = allCharacteristics.ProtocolError;
var nativeChars = allCharacteristics.Characteristics;
var charList = new List<ICharacteristic>();
foreach (var nativeChar in nativeChars)
{
var characteristic = new Characteristic(nativeChar, this);
charList.Add(characteristic);
}
return charList;
}
Any help would be greatly appreciated!

Xamarin says "Allow Multiple Bind To Same Port only allowed on Windows". What do I do?

I'm trying to use SocketLite.PCL with my iOS/Android solution in Xamarin,
but I get the message Allow Multiple Bind To Same Port only allowed on Windows when running it.
What does it mean and how do I fix it?
EDIT:
Example code I'm using can be found here: https://github.com/1iveowl/SocketLite.PCL
I put the following code inside rotected async override void OnStart(){} of the app:
var udpReceived = new UdpSocketReceiver();
await udpReceived.StartListeningAsync(4992, allowMultipleBindToSamePort: true);
var udpMessageSubscriber = udpReceived.ObservableMessages.Subscribe(
msg =>
{
System.Console.WriteLine($"Remote adrres: {msg.RemoteAddress}");
System.Console.WriteLine($"Remote port: {msg.RemotePort}");
var str = System.Text.Encoding.UTF8.GetString(msg.ByteData);
System.Console.WriteLine($"Messsage: {str}");
},
ex =>
{
// Exceptions received here
}
);
EDIT 2:
Ok, so setting allowMultipleBindToSamePort to false stopped that error.
Now I get the error Address already in use.
However I am still curious as to what allowMultipleBindToSamePort is used for.
As you can see in the new documentation:
IMPORTANT: Please notice that the parameter allowMultipleBindToSamePort will only work on Windows. On other platforms it should be set to false
About However I am still curious as to what allowMultipleBindToSamePort is used for.
There is a good and complete explanation on this post, you can read more in the following stackoverflow post

getContentResolver() is not defined

I want to create small app to parse sms. I use Visual Studio with Xamarin.
I found these peace of code and want to adapt is for my need.
But getContentResolver() method is not defined. I know, that it needs application context, but i don't understand how to get it.
Could someone give me an example please?
// Create Sent box URI
Uri sentURI = Uri.parse("content://sms/sent");
// List required columns
String[] reqCols = new String[] { "_id", "address", "body" };
// Get Content Resolver object, which will deal with Content Provider
ContentResolver cr = getContentResolver();
// Fetch Sent SMS Message from Built-in Content Provider
Cursor c = cr.query(sentURI, reqCols, null, null, null);
In Java world, you'll see methods like getContentResolver and setContentResolver. In Xamarin and C# those two will be combined to one property called ContentResolver. The latter part of your code should be like this:
// Fetch Sent SMS Message from Built-in Content Provider
Cursor c = ContentResolver.Query(sentURI, reqCols, null, null, null);
When porting Java code to C# (Xamarin), you can usually get basic stuff to work by capitalizing method names. With that logic, you should also modify the first line to this:
Uri sentURI = Uri.Parse("content://sms/sent");
However, this is a very simplified example. Knowing both Java and C# and how to use both the Android and Xamarin documentation will take you quite far.

How do I look up a Corba service with C# and IIOP.NET?

I am writing a C# client for a Corba server and I am using IIOP.NET, going by the example on the following page: http://iiop-net.sourceforge.net/rmiAdderDNClient.html
I have gotten this far without errors:
// Register channel
IiopClientChannel channel = new IiopClientChannel();
ChannelServices.RegisterChannel(channel, false);
// Access COS naming context
CorbaInit init = CorbaInit.GetInit();
NamingContext context = init.GetNameService(host, port);
The variable "host" is a string with the computer name of the server and "port" is an int representing the port number. The values for these are currently used by other systems to connect to the server so I can confirm that they are correct.
However, trying to connect to the trader service yields an exception in runtime. Here is the code I use to do that:
// Looking up VB Trader
NameComponent[] names = new NameComponent[] { new NameComponent("TraderInterface") };
object obj = context.resolve(names);
And here is the error message I'm getting:
"CORBA system exception : omg.org.CORBA.INV_OBJREF, completed: Completed_No minor: 10102."
This seems to suggest an invalid object reference, but what does that mean? Is the string I am passing to the resolve method incorrectly formatted? I have tried many different names for this service as used in other systems, but I always get the same error, which makes me wonder whether I am even interpreting it correctly.
Incidentally, in my desperation, I have also attempted to obtain an object reference from the IOR, but this again throws a different exception (namely omg.org.CORBA.ORB_package.InvalidName).
OrbServices orb = OrbServices.GetSingleton();
object obj = orb.resolve_initial_references(traderIOR);
Any advice is welcome.
I was never able to reach my server with any of the above methods, however the following code is what finally got the communication working:
Hashtable props = new Hashtable();
props[IiopChannel.BIDIR_KEY] = true;
props[IiopServerChannel.PORT_KEY] = port;
// register corba services
IiopChannel channel = new IiopChannel(props);
ChannelServices.RegisterChannel(channel, false);
MyInterface obj = (MyInterface)RemotingServices.Connect(typeof(MyInterface), ior);
I'm not entirely sure why I had to use this (seemingly) unconventional way. Perhaps it is due to the lack of a naming service running on the server. Whatever the cause, I hope this helps somebody out there.

Categories