public static async Task <HttpResponseMessage> GetDogsByBreed(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req,
            TraceWriter log)
        {
            sw.Restart();

            var queryValues = req.GetQueryNameValuePairs();

            // As a client, you would already have your userId when calling typically.
            string userId = queryValues.FirstOrDefault(p => p.Key == "UserId").Value;

            string breed = queryValues.FirstOrDefault(p => p.Key == "Breed").Value;

            string resourceToken = req.Headers?.GetValues("ResourceToken").FirstOrDefault();

            if (string.IsNullOrEmpty(resourceToken))
            {
                return(req.CreateErrorResponse(HttpStatusCode.Unauthorized, "ResourceToken is a required"));
            }

            // Set the resource token, to demonstrate usage from a 'Client'.
            repo.AuthKeyOrResourceToken(resourceToken);

            // Set the parition key, since our resource token is limited by partition key.  A client could just set this once initially.
            repo.PartitionKey(userId);

            var results = await repo.GetItemAsync <Dog>(p => p.Breed == breed);

            sw.Stop();


            log.Info($"Execution took: {sw.ElapsedMilliseconds}ms.");

            return(results == null
                ? req.CreateResponse(HttpStatusCode.BadRequest, "Unable to find document(s) with the given type.")
                : req.CreateResponse(HttpStatusCode.OK, results));
        }
        public static async Task <IActionResult> CognitivePipelineSyncProcessing(NewRequest <SmartDoc> newSmartDocRequest)
        {
            log.LogInformation($"***Starting Sync CognitivePipelineSyncProcessing***");

            IActionResult executionResult = null;

            if (newSmartDocRequest.Instructions.Contains(InstructionFlag.AnalyzeText.ToString()))
            {
                var stepName = InstructionFlag.AnalyzeText.ToString();
                log.LogInformation($"***Starting {stepName}***");
                string funcUri = GlobalSettings.GetKeyValue("FunctionBaseUrl") + "/NewCognitiveOCR";
                var    content = new StringContent(JsonConvert.SerializeObject(newSmartDocRequest), Encoding.UTF8, "application/json");
                try
                {
                    executionResult = await FunctionExecuter.CallFunction(funcUri, content);

                    if (executionResult is OkObjectResult)
                    {
                        //TODO: Update the request processing step
                        var    result                    = executionResult as OkObjectResult;
                        string updatedDocJson            = result.Value.ToString();
                        NewRequest <SmartDoc> updatedDoc = JsonConvert.DeserializeObject <NewRequest <SmartDoc> >(updatedDocJson);
                        newSmartDocRequest.RequestItem.CognitivePipelineActions.Add(updatedDoc.RequestItem.CognitivePipelineActions[0]);
                    }
                    else
                    {
                        //TODO: Better error information to be implemented
                        newSmartDocRequest.RequestItem.CognitivePipelineActions.Add(new ProcessingStep
                        {
                            LastUpdatedAt = DateTime.UtcNow,
                            Status        = SmartDocStatus.ProcessedUnsuccessfully.ToString(),
                            StepName      = stepName
                        });
                    }
                }
                catch (Exception ex)
                {
                    log.LogError($"***EXCEPTION*** in {stepName}: {ex.Message}, {ex.StackTrace}");
                    newSmartDocRequest.RequestItem.CognitivePipelineActions.Add(new ProcessingStep
                    {
                        LastUpdatedAt = DateTime.UtcNow,
                        Status        = SmartDocStatus.ProcessedUnsuccessfully.ToString(),
                        StepName      = InstructionFlag.AnalyzeText.ToString()
                    });
                }
            }

            if (newSmartDocRequest.Instructions.Contains(InstructionFlag.FaceAuthentication.ToString()))
            {
                var stepName = InstructionFlag.FaceAuthentication.ToString();
                log.LogInformation($"***Starting {stepName}***");
                CognitivePipeline.SharedModels.Models.User owner = await usersDbClient.GetItemAsync(newSmartDocRequest.OwnerId);

                string funcUri = GlobalSettings.GetKeyValue("FunctionBaseUrl") + $"/NewCognitiveFaceAuth/{owner.FacePersonId}";
                var    content = new StringContent(JsonConvert.SerializeObject(newSmartDocRequest), Encoding.UTF8, "application/json");
                try
                {
                    executionResult = await FunctionExecuter.CallFunction(funcUri, content);

                    if (executionResult is OkObjectResult)
                    {
                        //TODO: Update the request processing step
                        var    result                    = executionResult as OkObjectResult;
                        string updatedDocJson            = result.Value.ToString();
                        NewRequest <SmartDoc> updatedDoc = JsonConvert.DeserializeObject <NewRequest <SmartDoc> >(updatedDocJson);
                        newSmartDocRequest.RequestItem.CognitivePipelineActions.Add(updatedDoc.RequestItem.CognitivePipelineActions[0]);
                    }
                    else
                    {
                        //TODO: Better error information to be implemented
                        newSmartDocRequest.RequestItem.CognitivePipelineActions.Add(new ProcessingStep
                        {
                            LastUpdatedAt = DateTime.UtcNow,
                            Status        = SmartDocStatus.ProcessedUnsuccessfully.ToString(),
                            StepName      = stepName
                        });
                    }
                }
                catch (Exception ex)
                {
                    log.LogError($"***EXCEPTION*** in {stepName}: {ex.Message}, {ex.StackTrace}");
                    newSmartDocRequest.RequestItem.CognitivePipelineActions.Add(new ProcessingStep
                    {
                        LastUpdatedAt = DateTime.UtcNow,
                        Status        = SmartDocStatus.ProcessedUnsuccessfully.ToString(),
                        StepName      = stepName
                    });
                }
            }

            if (newSmartDocRequest.Instructions.Contains(InstructionFlag.ShelfCompliance.ToString()))
            {
                var stepName = InstructionFlag.ShelfCompliance.ToString();
                log.LogInformation($"***Starting {stepName}***");
                string funcUri = GlobalSettings.GetKeyValue("FunctionBaseUrl") + "/NewCognitiveShelfCompliance";
                var    content = new StringContent(JsonConvert.SerializeObject(newSmartDocRequest), Encoding.UTF8, "application/json");
                try
                {
                    executionResult = await FunctionExecuter.CallFunction(funcUri, content);

                    if (executionResult is OkObjectResult)
                    {
                        //TODO: Update the request processing step
                        var    result                    = executionResult as OkObjectResult;
                        string updatedDocJson            = result.Value.ToString();
                        NewRequest <SmartDoc> updatedDoc = JsonConvert.DeserializeObject <NewRequest <SmartDoc> >(updatedDocJson);
                        newSmartDocRequest.RequestItem.CognitivePipelineActions.Add(updatedDoc.RequestItem.CognitivePipelineActions[0]);
                    }
                    else
                    {
                        //TODO: Better error information to be implemented
                        newSmartDocRequest.RequestItem.CognitivePipelineActions.Add(new ProcessingStep
                        {
                            LastUpdatedAt = DateTime.UtcNow,
                            Status        = SmartDocStatus.ProcessedUnsuccessfully.ToString(),
                            StepName      = stepName
                        });
                    }
                }
                catch (Exception ex)
                {
                    log.LogError($"***EXCEPTION*** in {stepName}: {ex.Message}, {ex.StackTrace}");
                    newSmartDocRequest.RequestItem.CognitivePipelineActions.Add(new ProcessingStep
                    {
                        LastUpdatedAt = DateTime.UtcNow,
                        Status        = SmartDocStatus.ProcessedUnsuccessfully.ToString(),
                        StepName      = stepName
                    });
                }
            }

            if (newSmartDocRequest.Instructions.Contains(InstructionFlag.Thumbnail.ToString()))
            {
                var stepName = InstructionFlag.Thumbnail.ToString();
                log.LogInformation($"***Starting {stepName}***");

                //Currently the 2 Thumbnail sizes are loaded from Functions settings.
                var thumbnailConfig = GlobalSettings.GetKeyValue("CognitiveServices-Thumbnail-Config").Split(',');

                string funcUri = GlobalSettings.GetKeyValue("FunctionBaseUrl") + $"/NewCognitiveThumbnail/{thumbnailConfig[0]}/{thumbnailConfig[1]}/{thumbnailConfig[2]}/{thumbnailConfig[3]}";
                var    content = new StringContent(JsonConvert.SerializeObject(newSmartDocRequest), Encoding.UTF8, "application/json");
                try
                {
                    executionResult = await FunctionExecuter.CallFunction(funcUri, content);

                    if (executionResult is OkObjectResult)
                    {
                        //TODO: Update the request processing step
                        var    result                    = executionResult as OkObjectResult;
                        string updatedDocJson            = result.Value.ToString();
                        NewRequest <SmartDoc> updatedDoc = JsonConvert.DeserializeObject <NewRequest <SmartDoc> >(updatedDocJson);
                        newSmartDocRequest.RequestItem.CognitivePipelineActions.Add(updatedDoc.RequestItem.CognitivePipelineActions[0]);
                    }
                    else
                    {
                        //TODO: Better error information to be implemented
                        newSmartDocRequest.RequestItem.CognitivePipelineActions.Add(new ProcessingStep
                        {
                            LastUpdatedAt = DateTime.UtcNow,
                            Status        = SmartDocStatus.ProcessedUnsuccessfully.ToString(),
                            StepName      = stepName
                        });
                    }
                }
                catch (Exception ex)
                {
                    log.LogError($"***EXCEPTION*** in {stepName}: {ex.Message}, {ex.StackTrace}");
                    newSmartDocRequest.RequestItem.CognitivePipelineActions.Add(new ProcessingStep
                    {
                        LastUpdatedAt = DateTime.UtcNow,
                        Status        = SmartDocStatus.ProcessedUnsuccessfully.ToString(),
                        StepName      = stepName
                    });
                }
            }

            if (newSmartDocRequest.Instructions.Contains(InstructionFlag.AnalyzeImage.ToString()))
            {
                var stepName = InstructionFlag.AnalyzeImage.ToString();
                log.LogInformation($"***Starting {stepName}***");
                string funcUri = GlobalSettings.GetKeyValue("FunctionBaseUrl") + $"/NewCognitiveAnalyzeImage";
                var    content = new StringContent(JsonConvert.SerializeObject(newSmartDocRequest), Encoding.UTF8, "application/json");
                try
                {
                    executionResult = await FunctionExecuter.CallFunction(funcUri, content);

                    if (executionResult is OkObjectResult)
                    {
                        //TODO: Update the request processing step
                        var    result                    = executionResult as OkObjectResult;
                        string updatedDocJson            = result.Value.ToString();
                        NewRequest <SmartDoc> updatedDoc = JsonConvert.DeserializeObject <NewRequest <SmartDoc> >(updatedDocJson);
                        newSmartDocRequest.RequestItem.CognitivePipelineActions.Add(updatedDoc.RequestItem.CognitivePipelineActions[0]);
                    }
                    else
                    {
                        //TODO: Better error information to be implemented
                        newSmartDocRequest.RequestItem.CognitivePipelineActions.Add(new ProcessingStep
                        {
                            LastUpdatedAt = DateTime.UtcNow,
                            Status        = SmartDocStatus.ProcessedUnsuccessfully.ToString(),
                            StepName      = InstructionFlag.AnalyzeImage.ToString()
                        });
                    }
                }
                catch (Exception ex)
                {
                    log.LogError($"***EXCEPTION*** in {stepName}: {ex.Message}, {ex.StackTrace}");
                    newSmartDocRequest.RequestItem.CognitivePipelineActions.Add(new ProcessingStep
                    {
                        LastUpdatedAt = DateTime.UtcNow,
                        Status        = SmartDocStatus.ProcessedUnsuccessfully.ToString(),
                        StepName      = stepName
                    });
                }
            }

            //Validate cognitive processing and return relevant details
            log.LogInformation($"***Final Results Processing***");
            var processedResult = await CognitivePipelineResultProcessor.ProcessFinalResult(newSmartDocRequest, smartDocsDbClient, usersDbClient);

            if (!string.IsNullOrEmpty(processedResult))
            {
                return((ActionResult) new OkObjectResult(processedResult));
            }
            else
            {
                return((ActionResult) new BadRequestObjectResult(processedResult));
            }
        }