private static async Task <bool> UpsertFaceListAndCheckIfContainsFaceAsync()
        {
            try
            {
                faceServiceClient = new FaceServiceClient(Configuration["FaceAPIKey"], "https://eastus.api.cognitive.microsoft.com/face/v1.0");
                var faceListId = Guid.Parse(Configuration["FaceListId"]).ToString();
                var faceLists  = await faceServiceClient.ListFaceListsAsync();

                var faceList = faceLists.FirstOrDefault(_ => _.FaceListId == FaceListId.ToString());

                if (faceList == null)
                {
                    await faceServiceClient.CreateFaceListAsync(faceListId, "GeekBurgerFaces", null);

                    return(false);
                }

                var faceListJustCreated = await faceServiceClient.GetFaceListAsync(faceListId);

                return(faceListJustCreated.PersistedFaces.Any());
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #2
0
        public async Task <bool> UpsertFaceListAndCheckIfContainsFaceAsync()
        {
            try
            {
                var faceListIdIn = faceListId.ToString();
                var faceLists    = await _faceServiceClient.ListFaceListsAsync();

                var faceList = faceLists.FirstOrDefault(_ => _.FaceListId == faceListIdIn);

                if (faceList == null)
                {
                    await _faceServiceClient.CreateFaceListAsync(faceListIdIn, "GeekBurgerFaces", null);

                    return(false);
                }

                var faceListJustCreated = await _faceServiceClient.GetFaceListAsync(faceListIdIn);

                return(faceListJustCreated.PersistedFaces.Any());
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
        public async Task <dynamic> GetCandidateFiles()
        {
            string message           = string.Empty;
            var    faceServiceClient = new FaceServiceClient(ServiceKey);

            FacesCollection.Clear();
            DirectoryInfo dir = new DirectoryInfo(Path.Combine(Server.MapPath(directory)));

            FileInfo[] files = null;
            files = dir.GetFiles().OrderBy(p => p.CreationTime).ToArray();

            if (files.Count() > 0)
            {
                _faceListName = Guid.NewGuid().ToString();
                await faceServiceClient.CreateFaceListAsync(_faceListName, _faceListName, "face list for sample");

                foreach (var item in files)
                {
                    var imgPath = Server.MapPath(directory) + '\\' + item.Name as string;
                    try
                    {
                        using (var fStream = System.IO.File.OpenRead(imgPath))
                        {
                            var faces = await faceServiceClient.AddFaceToFaceListAsync(_faceListName, fStream);

                            FacesCollection.Add(new vmFace
                            {
                                ImagePath = imgPath,
                                FileName  = item.Name,
                                FilePath  = directory + '\\' + item.Name,
                                FaceId    = Convert.ToString(faces.PersistedFaceId)
                            });
                        }
                    }
                    catch (FaceAPIException fe)
                    {
                        //do exception work
                        message = fe.ToString();
                    }
                }
            }
            else
            {
                message = "No files to Detect!! Please Upload Files";
            }
            return(new JsonResult
            {
                Data = new
                {
                    Message = message,
                    FacesCollection = FacesCollection
                },
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            });
        }
Example #4
0
        public async Task RegisterFaceAsync(string faceId, ImageRequest request)
        {
            var client = new FaceServiceClient(subscriptionKey: Secrets.CongnitiveServiceFaceApiKey, apiRoot: Consts.CognitiveServiceFaceApiEndPoint);

            try
            {
                await client.GetFaceListAsync(faceId);
            }
            catch (FaceAPIException)
            {
                // not found
                await client.CreateFaceListAsync(faceListId : faceId, name : faceId);
            }

            await client.AddFaceToFaceListAsync(faceListId : faceId, imageStream : new MemoryStream(request.Image));
        }
        private async Task <bool> UpsertFaceListAndCheckIfContainsFaceAsync()
        {
            var faceLists = await _faceServiceClient.ListFaceListsAsync();

            var faceList = faceLists.FirstOrDefault(_ => _.FaceListId == _faceListId);

            if (faceList == null)
            {
                await _faceServiceClient.CreateFaceListAsync(_faceListId, "geekburger-users-face", null);

                return(false);
            }

            var faceListJustCreated = await _faceServiceClient.GetFaceListAsync(_faceListId);

            return(faceListJustCreated.PersistedFaces.Any());
        }
Example #6
0
        private static async Task <bool> UpsertFaceListAndCheckIfContainsFaceAsync()
        {
            var faceListId = FaceListId.ToString();
            var faceLists  = await faceServiceClient.ListFaceListsAsync();

            var faceList = faceLists.FirstOrDefault(_ => _.FaceListId == FaceListId.ToString());

            if (faceList == null)
            {
                await faceServiceClient.CreateFaceListAsync(faceListId, "GeekBurgerFaces", null);

                return(false);
            }

            var faceListJustCreated = await faceServiceClient.GetFaceListAsync(faceListId);

            return(faceListJustCreated.PersistedFaces.Any());
        }
Example #7
0
        /// <summary>
        ///
        /// <remarks>
        /// facelistId:为空时,自动创建Guid
        /// </remarks>
        /// </summary>
        /// <param name="serviceKey">服务key</param>
        /// <param name="facelistId">容器Id</param>
        public FaceApiHelper(string serviceKey, string facelistId = "")
        {
            ServiceKey = serviceKey;
            if (string.IsNullOrEmpty(facelistId))
            {
                facelistId = Guid.NewGuid().ToString();
            }
            FaceListId        = facelistId;
            faceServiceClient = new FaceServiceClient(ServiceKey);
            //判定是否已经存在
            FaceList isExist = GetFaceListInfoById(FaceListId).Result;

            if (isExist == null)
            {
                var task = faceServiceClient.CreateFaceListAsync(FaceListId, FaceListId, FaceListId);
                task.Wait();
            }
        }
Example #8
0
        /// <summary>
        /// Function to create new face list
        /// </summary>
        /// <param name="obj"></param>
        private async void CreateFaceListAsync(object obj)
        {
            try
            {
                if (!_faceListExists)
                {
                    await _faceServiceClient.CreateFaceListAsync(FaceListName.ToLower(), FaceListName, string.Empty);

                    await DoesFaceListExistAsync();
                }
            }
            catch (FaceAPIException ex)
            {
                Debug.WriteLine($"Failed to create face list - {ex.ErrorMessage}");
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }
Example #9
0
        private async Task <Face[]> UploadAndFindFaceAttributes(MediaFile file)
        {
            try
            {
                var faceListName = Guid.NewGuid().ToString();
                await faceServiceClient.CreateFaceListAsync(faceListName, faceListName, "face list for sample");

                var faces = await faceServiceClient.DetectAsync(file.GetStream());

                foreach (var f in faces)
                {
                    //var result = await faceServiceClient.FindSimilarAsync(f.FaceId, faces, 10);
                }


                return(faces);
            }
            catch (Exception)
            {
            }

            return(null);
        }
Example #10
0
 public async Task CreateFaceListAsync(string faceListId, string name, string userData)
 {
     await RunTaskWithAutoRetryOnQuotaLimitExceededError(() => faceClient.CreateFaceListAsync(faceListId, name, userData));
 }
        /// <summary>
        /// Pick image folder and detect all faces in these images
        /// </summary>
        /// <param name="sender">Event sender</param>
        /// <param name="e">Event arguments</param>
        private async void FolderPicker_Click(object sender, RoutedEventArgs e)
        {
            // Show folder picker
            System.Windows.Forms.FolderBrowserDialog dlg = new System.Windows.Forms.FolderBrowserDialog();
            var result = dlg.ShowDialog();

            bool forceContinue = false;

            if (result == System.Windows.Forms.DialogResult.OK)
            {
                // Enumerate all ".jpg" files in the folder, call detect
                List<Task> tasks = new List<Task>();

                FacesCollection.Clear();
                TargetFaces.Clear();
                FindSimilarCollection.Clear();
                SelectedFile = null;

                // Set the suggestion count is intent to minimum the data preparetion step only,
                // it's not corresponding to service side constraint
                const int SuggestionCount = 10;
                int processCount = 0;

                MainWindow.Log("Request: Preparing, detecting faces in chosen folder.");

                MainWindow mainWindow = Window.GetWindow(this) as MainWindow;
                string subscriptionKey = mainWindow._scenariosControl.SubscriptionKey;

                var faceServiceClient = new FaceServiceClient(subscriptionKey);

                _faceListName = Guid.NewGuid().ToString();
                await faceServiceClient.CreateFaceListAsync(_faceListName, _faceListName, "face list for sample");

                foreach (var img in Directory.EnumerateFiles(dlg.SelectedPath, "*.jpg", SearchOption.AllDirectories))
                {
                    tasks.Add(Task.Factory.StartNew(
                        async (obj) =>
                        {
                            var imgPath = obj as string;

                            // Call detection
                            using (var fStream = File.OpenRead(imgPath))
                            {
                                try
                                {
                                    var faces = await faceServiceClient.AddFaceToFaceListAsync(_faceListName, fStream);
                                    return new Tuple<string, ClientContract.AddPersistedFaceResult>(imgPath, faces);
                                }
                                catch (FaceAPIException)
                                {
                                    // Here we simply ignore all detection failure in this sample
                                    // You may handle these exceptions by check the Error.Error.Code and Error.Message property for ClientException object
                                    return new Tuple<string, ClientContract.AddPersistedFaceResult>(imgPath, null);
                                }
                            }
                        },
                        img).Unwrap().ContinueWith((detectTask) =>
                        {
                            var res = detectTask.Result;
                            if (res.Item2 == null)
                            {
                                return;
                            }

                            // Update detected faces on UI
                            this.Dispatcher.Invoke(
                                new Action<ObservableCollection<Face>, string, ClientContract.AddPersistedFaceResult>(UIHelper.UpdateFace),
                                FacesCollection,
                                res.Item1,
                                res.Item2);
                        }));
                    processCount++;

                    if (processCount >= SuggestionCount && !forceContinue)
                    {
                        var continueProcess = System.Windows.Forms.MessageBox.Show("The images loaded have reached the recommended count, may take long time if proceed. Would you like to continue to load images?", "Warning", System.Windows.Forms.MessageBoxButtons.YesNo);
                        if (continueProcess == System.Windows.Forms.DialogResult.Yes)
                        {
                            forceContinue = true;
                        }
                        else
                        {
                            break;
                        }
                    }
                }

                await Task.WhenAll(tasks);

                MainWindow.Log("Response: Success. Total {0} faces are detected.", FacesCollection.Count);
            }
        }
        public async Task <string> FindSimilarImages()
        {
            //Creation of facelist and sending all the images(the images to which we are going to do match) to the facelist

            _faceListName = Guid.NewGuid().ToString();                            // Generating a unique group-id for the entire images
            var faceServiceClients = new FaceServiceClient(subscriptionKeyValue); //calling the Face API using subscription key

            try
            {
                await faceServiceClients.CreateFaceListAsync(_faceListName, _faceListName, "face_Images"); //Calling the API service'CreateFaceListAsync' to create a facelist with id/name as  _faceListName.
            }

            catch (FaceAPIException ex)
            {
                Errormsg = ex.ErrorMessage;
                return(RedirectToAction("Error", "Home", new { Errormsg = Errormsg }).ToString());
            }

            DirectoryInfo DirInfo = new DirectoryInfo(@"C:\Image");

            Dictionary <string, string> DictionaryListofPersistanceIDAndImagePath = new Dictionary <string, string>();//Dictionary entry for storing the persistance id returned for each image from the Face API service

            try
            {
                foreach (var file in DirInfo.GetFiles("*.jpg"))
                {
                    string     imgPath = @"C:\Image\" + file.ToString();
                    FileStream fStream = new FileStream(imgPath, FileMode.Open, FileAccess.Read);
                    var        faces   = await faceServiceClients.AddFaceToFaceListAsync(_faceListName, fStream); //Adding of each image content to the created facelist in the Face API using the service 'AddFaceToFaceListAsync'

                    DictionaryListofPersistanceIDAndImagePath.Add(faces.PersistedFaceId.ToString(), imgPath);     //Storing the PersistedFaceId of the image returned by the Face API service and image path in dictionary
                }
            }
            //End
            catch (FaceAPIException ex)
            {
                ViewData["ExceptionMsg"] = ex.ErrorMessage;
            }


            // Sending  and matching the captured image with the images contained in the facelist

            //  string CapturedImgName = Server.MapPath("~/Image/CapturedImg.jpg");
            string CapturedImgName = Server.MapPath("~/test.jpg");

            string[] MatchedImgpath; //int MatchedImgcount = 0;

            using (var fileStream = System.IO.File.OpenRead(CapturedImgName))
            {
                var faceServiceClient = new FaceServiceClient(subscriptionKeyValue);
                var faces             = await faceServiceClient.DetectAsync(fileStream); //Calling the Face API 'DetectAsync' to detect the captured image by sending the content of the captured image

                // After call it will return a faceid to the captured image
                foreach (var f in faces)
                {
                    var       faceId = f.FaceId;           //Retrive the face id of the captured image
                    const int requestCandidatesCount = 20; // The number of the more confidece images to be rturned.Most matched image have more confidence value.
                                                           //confidence value is assigned by the Face API service based on the match.
                    try
                    {
                        var result = await faceServiceClient.FindSimilarAsync(faceId, _faceListName, requestCandidatesCount); // Matching the captured image with images by sending  faceId and _faceListName to the Face API 'FindSimilarAsync'

                        //The variable result contains the matched image's PersistedFaceId
                        MatchedImgpath = new string[requestCandidatesCount];                                                                    //Declare an array with size 'requestCandidatesCount' to store the matched images path
                                                                                                                                                // int MatchedImgcount = 0;
                        foreach (var fr in result)                                                                                              //Loop through the PersistedFaceId of matched faces
                        {
                            if (fr.Confidence >= 0.8)                                                                                           //To check whether the confidence value of the matched image is >=0.8
                            {
                                if (DictionaryListofPersistanceIDAndImagePath.ContainsKey(fr.PersistedFaceId.ToString()))                       //To check whether the Persistance id is present in the dictionary
                                                                                                                                                //if present retrive the curresponding image-path of that PersistedFaceId.
                                {
                                    MatchedImgpath[MatchedImgcount] = DictionaryListofPersistanceIDAndImagePath[fr.PersistedFaceId.ToString()]; //Store the image-path in an array.This array contains all the matched image path which have confidence-value >=0.8
                                    MatchedImgcount = MatchedImgcount + 1;
                                }
                            }
                        }
                    }

                    catch (FaceAPIException ex)
                    {
                        ViewData["ExceptionMsg"] = ex.ErrorMessage;
                    }
                }
            }
            if (MatchedImgcount != 0)
            {
                return("found");
            }
            else
            {
                return("notfound");
            }
            //End
        }
Example #13
0
        /// <summary>
        /// Pick image folder and detect all faces in these images
        /// </summary>
        /// <param name="sender">Event sender</param>
        /// <param name="e">Event arguments</param>
        private async void FolderPicker_Click(object sender, RoutedEventArgs e)
        {
            // Show folder picker
            System.Windows.Forms.FolderBrowserDialog dlg = new System.Windows.Forms.FolderBrowserDialog();
            var result = dlg.ShowDialog();

            bool forceContinue = false;

            if (result == System.Windows.Forms.DialogResult.OK)
            {
                // Enumerate all ".jpg" files in the folder, call detect
                List <Task> tasks = new List <Task>();

                FacesCollection.Clear();
                TargetFaces.Clear();
                FindSimilarCollection.Clear();
                SelectedFile = null;

                // Set the suggestion count is intent to minimum the data preparetion step only,
                // it's not corresponding to service side constraint
                const int SuggestionCount = 10;
                int       processCount    = 0;

                MainWindow.Log("Request: Preparing, detecting faces in chosen folder.");

                MainWindow mainWindow      = Window.GetWindow(this) as MainWindow;
                string     subscriptionKey = mainWindow._scenariosControl.SubscriptionKey;

                var faceServiceClient = new FaceServiceClient(subscriptionKey);

                _faceListName = Guid.NewGuid().ToString();
                await faceServiceClient.CreateFaceListAsync(_faceListName, _faceListName, "face list for sample");

                foreach (var img in Directory.EnumerateFiles(dlg.SelectedPath, "*.jpg", SearchOption.AllDirectories))
                {
                    tasks.Add(Task.Factory.StartNew(
                                  async(obj) =>
                    {
                        var imgPath = obj as string;

                        // Call detection
                        using (var fStream = File.OpenRead(imgPath))
                        {
                            try
                            {
                                var faces = await faceServiceClient.AddFaceToFaceListAsync(_faceListName, fStream);
                                return(new Tuple <string, ClientContract.AddPersistedFaceResult>(imgPath, faces));
                            }
                            catch (FaceAPIException)
                            {
                                // Here we simply ignore all detection failure in this sample
                                // You may handle these exceptions by check the Error.Error.Code and Error.Message property for ClientException object
                                return(new Tuple <string, ClientContract.AddPersistedFaceResult>(imgPath, null));
                            }
                        }
                    },
                                  img).Unwrap().ContinueWith((detectTask) =>
                    {
                        var res = detectTask.Result;
                        if (res.Item2 == null)
                        {
                            return;
                        }

                        // Update detected faces on UI
                        this.Dispatcher.Invoke(
                            new Action <ObservableCollection <Face>, string, ClientContract.AddPersistedFaceResult>(UIHelper.UpdateFace),
                            FacesCollection,
                            res.Item1,
                            res.Item2);
                    }));
                    processCount++;

                    if (processCount >= SuggestionCount && !forceContinue)
                    {
                        var continueProcess = System.Windows.Forms.MessageBox.Show("The images loaded have reached the recommended count, may take long time if proceed. Would you like to continue to load images?", "Warning", System.Windows.Forms.MessageBoxButtons.YesNo);
                        if (continueProcess == System.Windows.Forms.DialogResult.Yes)
                        {
                            forceContinue = true;
                        }
                        else
                        {
                            break;
                        }
                    }
                }

                await Task.WhenAll(tasks);

                MainWindow.Log("Response: Success. Total {0} faces are detected.", FacesCollection.Count);
            }
        }
Example #14
0
        /// <summary>
        /// Pick image folder and detect all faces in these images
        /// </summary>
        /// <param name="sender">Event sender</param>
        /// <param name="e">Event arguments</param>
        private async void FolderPicker_Click(object sender, RoutedEventArgs e)
        {
            bool groupExists = false;

            MainWindow mainWindow      = Window.GetWindow(this) as MainWindow;
            string     subscriptionKey = mainWindow._scenariosControl.SubscriptionKey;

            var faceServiceClient = new FaceServiceClient(subscriptionKey);

            try
            {
                MainWindow.Log("Request: Face List {0} will be used to build a person database. Checking whether the face list exists.", _faceListName);

                await faceServiceClient.GetFaceListAsync(_faceListName);

                groupExists = true;
                MainWindow.Log("Response: Face List {0} exists.", _faceListName);
            }
            catch (FaceAPIException ex)
            {
                if (ex.ErrorCode != "FaceListNotFound")
                {
                    MainWindow.Log("Response: {0}. {1}", ex.ErrorCode, ex.ErrorMessage);
                    return;
                }
                else
                {
                    MainWindow.Log("Response: Face List {0} did not exist previously.", _faceListName);
                }
            }

            if (groupExists)
            {
                var cleanFaceList = System.Windows.MessageBox.Show(string.Format("Requires a clean up for face list \"{0}\" before setting up a new face list. Click OK to proceed, face list \"{0}\" will be cleared.", _faceListName), "Warning", MessageBoxButton.OKCancel);
                if (cleanFaceList == MessageBoxResult.OK)
                {
                    await faceServiceClient.DeleteFaceListAsync(_faceListName);
                }
                else
                {
                    return;
                }
            }

            OpenFaceButton.IsEnabled = false;
            // Show folder picker
            System.Windows.Forms.FolderBrowserDialog dlg = new System.Windows.Forms.FolderBrowserDialog();
            var result = dlg.ShowDialog();

            bool forceContinue = false;


            if (result == System.Windows.Forms.DialogResult.OK)
            {
                // Enumerate all ".jpg" files in the folder, call detect
                List <Task> tasks = new List <Task>();

                FacesCollection.Clear();
                TargetFaces.Clear();
                FindSimilarMatchPersonCollection.Clear();
                FindSimilarMatchFaceCollection.Clear();
                SelectedFile = null;

                // Set the suggestion count is intent to minimum the data preparation step only,
                // it's not corresponding to service side constraint
                const int SuggestionCount = 10;
                int       processCount    = 0;

                MainWindow.Log("Request: Preparing, detecting faces in chosen folder.");

                await faceServiceClient.CreateFaceListAsync(_faceListName, _faceListName, "face list for sample");

                var imageList =
                    new ConcurrentBag <string>(
                        Directory.EnumerateFiles(dlg.SelectedPath, "*.*", SearchOption.AllDirectories)
                        .Where(s => s.EndsWith(".jpg") || s.EndsWith(".png") || s.EndsWith(".bmp") || s.EndsWith(".gif")));

                string img;
                int    invalidImageCount = 0;
                while (imageList.TryTake(out img))
                {
                    tasks.Add(Task.Factory.StartNew(
                                  async(obj) =>
                    {
                        var imgPath = obj as string;
                        // Call detection
                        using (var fStream = File.OpenRead(imgPath))
                        {
                            try
                            {
                                var faces =
                                    await faceServiceClient.AddFaceToFaceListAsync(_faceListName, fStream);
                                return(new Tuple <string, ClientContract.AddPersistedFaceResult>(imgPath, faces));
                            }
                            catch (FaceAPIException ex)
                            {
                                // if operation conflict, retry.
                                if (ex.ErrorCode.Equals("ConcurrentOperationConflict"))
                                {
                                    imageList.Add(imgPath);
                                    return(null);
                                }
                                // if operation cause rate limit exceed, retry.
                                else if (ex.ErrorCode.Equals("RateLimitExceeded"))
                                {
                                    imageList.Add(imgPath);
                                    return(null);
                                }
                                else if (ex.ErrorMessage.Contains("more than 1 face in the image."))
                                {
                                    Interlocked.Increment(ref invalidImageCount);
                                }
                                // Here we simply ignore all detection failure in this sample
                                // You may handle these exceptions by check the Error.Error.Code and Error.Message property for ClientException object
                                return(new Tuple <string, ClientContract.AddPersistedFaceResult>(imgPath, null));
                            }
                        }
                    },
                                  img).Unwrap().ContinueWith((detectTask) =>
                    {
                        var res = detectTask?.Result;
                        if (res?.Item2 == null)
                        {
                            return;
                        }

                        // Update detected faces on UI
                        this.Dispatcher.Invoke(
                            new Action
                            <ObservableCollection <Face>, string, ClientContract.AddPersistedFaceResult>(
                                UIHelper.UpdateFace),
                            FacesCollection,
                            res.Item1,
                            res.Item2);
                    }));

                    processCount++;

                    if (processCount >= SuggestionCount && !forceContinue)
                    {
                        var continueProcess =
                            System.Windows.Forms.MessageBox.Show(
                                "The images loaded have reached the recommended count, may take long time if proceed. Would you like to continue to load images?",
                                "Warning", System.Windows.Forms.MessageBoxButtons.YesNo);
                        if (continueProcess == System.Windows.Forms.DialogResult.Yes)
                        {
                            forceContinue = true;
                        }
                        else
                        {
                            break;
                        }
                    }

                    if (tasks.Count >= _maxConcurrentProcesses || imageList.IsEmpty)
                    {
                        await Task.WhenAll(tasks);

                        tasks.Clear();
                    }
                }
                if (invalidImageCount > 0)
                {
                    MainWindow.Log("Warning: more or less than one face is detected in {0} images, can not add to face list.", invalidImageCount);
                }
                MainWindow.Log("Response: Success. Total {0} faces are detected.", FacesCollection.Count);
            }
            GC.Collect();
            OpenFaceButton.IsEnabled = true;
        }
Example #15
0
 private async Task<string> CreateFaceListAsync(FaceServiceClient faceServiceClient)
 {
     var faceListId = _faceListNameRoot + Guid.NewGuid();
     await faceServiceClient.CreateFaceListAsync(faceListId, faceListId, null);
     return faceListId;
 }
Example #16
0
        async Task <AiResult> MakeRequest(string imageToCheck)
        {
            AiResult res = new AiResult();
            // imageToCheck = "https://www.liberationnews.org/wp-content/uploads/2015/07/donaldtrump61815.jpg";

            EmotionServiceClient emotionServiceClient = new EmotionServiceClient(emotionKey);

            Emotion[] imageEmotion = await emotionServiceClient.RecognizeAsync(imageToCheck);

            Console.WriteLine("Feeling: " + imageEmotion[0].Scores.ToRankedList().First().Key);
            Console.WriteLine("Top score: " + imageEmotion[0].Scores.ToRankedList().First().Value);

            res.Emotion = string.Format("Unknwn ({0:P2})", 0);
            float bestScore = 0;

            foreach (var em in imageEmotion[0].Scores.ToRankedList())
            {
                if (em.Value > bestScore)
                {
                    bestScore   = em.Value;
                    res.Emotion = res.Emotion = string.Format("{0} ({1:P2})", em.Key, em.Value);
                }
            }

            FaceServiceClient faceServiceClient = new FaceServiceClient(faceKey);
            FaceList          trumpList         = null;

            try
            {
                trumpList = await faceServiceClient.GetFaceListAsync(faceList);
            }
            catch (FaceAPIException apiExp)
            {
                if (apiExp.ErrorCode == "FaceListNotFound")
                {
                    await faceServiceClient.CreateFaceListAsync(faceList, faceList, "A collection of trumps");

                    trumpList = await faceServiceClient.GetFaceListAsync(faceList);
                }
                else
                {
                    throw apiExp;
                }
            }
            if (trumpList.PersistedFaces.Count() < 5)
            {
                await faceServiceClient.AddFaceToFaceListAsync(faceList, "https://www.liberationnews.org/wp-content/uploads/2015/07/donaldtrump61815.jpg");

                await faceServiceClient.AddFaceToFaceListAsync(faceList, "http://thefederalist.com/wp-content/uploads/2016/02/trumpie.jpg");

                await faceServiceClient.AddFaceToFaceListAsync(faceList, "http://www.redstate.com/uploads/2016/02/donald-trump-is-still-soaring-in-iowa-but-there-are-now-some-clear-warning-signs.jpg");

                await faceServiceClient.AddFaceToFaceListAsync(faceList, "http://i.huffpost.com/gen/3706868/images/o-DONALD-TRUMP-FUNNY-facebook.jpg");

                await faceServiceClient.AddFaceToFaceListAsync(faceList, "http://media.salon.com/2015/04/donald_trump_thumbsup.jpg");

                trumpList = await faceServiceClient.GetFaceListAsync(faceList);
            }

            Face[] faceToCompare = await faceServiceClient.DetectAsync(imageToCheck);

            SimilarPersistedFace[] faces = await faceServiceClient.FindSimilarAsync(faceToCompare[0].FaceId, faceList, FindSimilarMatchMode.matchFace);

            res.TrumpMatch = String.Format("{0:P2}", 0);
            if (faces.Count() == 0)
            {
                Console.WriteLine("Sorry, nothing compares to you");
            }
            else
            {
                double totalConfidence = 0;
                foreach (SimilarPersistedFace matching in faces)
                {
                    totalConfidence += matching.Confidence;
                }
                double averageConfidence = totalConfidence / faces.Count();
                res.TrumpMatch = String.Format("{0:P2}", averageConfidence);
                Console.WriteLine("Trump comparison: " + res.TrumpMatch);
            }
            return(res);
        }