Computer Vision API–Testing SRK Photo

Computer Vision API provides ready algorithms for processing images – It can classify a picture as object, animal etc.  It can also validate it with Celebrities – all through the machine learning infrastructure of Azure under the hood.

image

Azure Service

For testing this you need to create the Computer Vision service from Azure > Marketplace.

image

Choose the S1 tier as most of the capabilities are residing there.

image

Console Application in C#

Create a Console Application in C# and add the following Nuget package.

image

SRK

As a test I am going to upload above SRK picture & let the Computer Vision API identify him.

Output

The API is successfully identifying SRK! Smile

image

The Code

using Microsoft.Azure.CognitiveServices.Vision.ComputerVision;
using Microsoft.Azure.CognitiveServices.Vision.ComputerVision.Models;
using Microsoft.Rest;
using System;
using System.IO;
using System.Net.Http;

namespace ComputerVisionAPI
{
     class Program
     {
         static void Main(string[] args)
         {
             var features = new VisualFeatureTypes[] { VisualFeatureTypes.Tags, VisualFeatureTypes.Description };

            ComputerVisionClient computerVisionClient = new ComputerVisionClient(
                 new ApiKeyServiceClientCredentials(“YOUR KEY”),
                 new DelegatingHandler[] { }
                 )
             {
                 Endpoint = https://URL.cognitiveservices.azure.com/
             };

            using (var fs = new FileStream(@”C:\temp\ShahrukhKhan.png”, FileMode.Open))
             {
                 ImageAnalysis result = computerVisionClient.AnalyzeImageInStreamAsync(fs, features).Result;

                Console.WriteLine(“TAGS >> “);
                 foreach (string tag in result.Description.Tags)
                     Console.Write($” {tag} “);

                Console.WriteLine(Environment.NewLine + Environment.NewLine + “CAPTION >>”);
                 foreach (ImageCaption caption in result.Description.Captions)
                     Console.WriteLine($”{caption.Text} – Confidence: {caption.Confidence} “);

            }
         }
     }
}

References

https://azure.microsoft.com/en-us/services/cognitive-services/computer-vision/#product-overview

How to Install a PFX Certificate through Code?

IIS

Go to IIS > Server Certificates > Export Certificate

C#

Install Certificate to Current User.

X509Certificate2 certificate = new X509Certificate2(“C:\\Certificates\\IISExported.pfx”, “Password”);
X509Store xstore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
xstore.Open(OpenFlags.ReadWrite);
xstore.Add(certificate);
xstore.Close();

Testing C#

Try getting the Certificate back.

X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
X509Certificate2Collection col = store.Certificates.Find(X509FindType.FindByThumbprint, certificate.Thumbprint, false);
if (col == null || col.Count == 0)
{
     Console.WriteLine(“ERROR: Certificate not found with thumbprint”);
}
else
     Console.WriteLine(“Found: ” + col[0].FriendlyName);

Azure Key Vault & Access from C#

Azure Key Vault & Access from C#

In this article we can explore how to create an Azure Key Vault & Access from C#.

Azure Key Vault

Azure Key Vault allows to keep encrypted secured strings. Eg: Connection Strings, Passwords etc.

Create Azure Key Vault

Open Azure Portal & Create a new Key Vault as shown below.

image

Go the Secrets blade and create a new Secret with name as key1 and value as value1

image

Create App Registration

We need to create an App Registration for our Console Application. This will enable to Authenticate our Console Application using the Credentials.

Go to Azure Portal > Azure Active Directory > App Registrations. Create new App Registration as below.

image

Create new client secret too.

image

Now copy the Client ID and Client Secret which you need in the next steps.

Authorize Console Application

We need to Authorize the Console Application to the Key Vault. Without this step you will get Forbidden error.

Go to Key Vault > Access Policies blade

image

Click Add Access Policy and select our Console Application as Principal.

image

image

Now onwards any application authenticated through Client Credentials of the Console App Registration will be considered as Principal – which is the Security Identity for the application.

Create Project

Create a new console application in Visual Studio. Add references to following:

· Microsoft.Azure.KeyVault

· Microsoft.IdentityModel.Clients.ActiveDirectory

Replace the code with following.

using Microsoft.Azure.KeyVault;

using Microsoft.IdentityModel.Clients.ActiveDirectory;

using System;

using System.Threading.Tasks;

namespace KeyVault

{

class Program

{

static void Main(string[] args)

{

Console.WriteLine($”Secret Value from Vault is: {GetVaultValue()}”);

Console.ReadKey(false);

}

static string GetVaultValue()

{

KeyVaultClient client = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(GetToken));

var vaultAddress = “https://your-key-vault.vault.azure.net”;

var secretName = “key1”;

var secret = client.GetSecretAsync(vaultAddress, secretName).GetAwaiter().GetResult();

return secret.Value;

}

static async Task<string> GetToken(string authority, string resource, string scope)

{

var clientId = “YOUR CLIENT ID”;

var clientSecret = “YOUR CLIENT SECRET”;

ClientCredential credential = new ClientCredential(clientId, clientSecret);

var context = new AuthenticationContext(authority, TokenCache.DefaultShared);

var result = await context.AcquireTokenAsync(resource, credential);

return result.AccessToken;

}

}

}

On running the application, you will get the following output.

image

Summary

In this article we have explored how to create an Azure Key Vault & Access from C#.