Ejemplo n.º 1
0
 public JsonResult ProcessException(Exception ex, string message)
 {
     var errorResult = new JsonResult(message + ex.Message);
     Logger.LogError(category:"DivineBaseController", 
         message: message, 
         exception: ex, username:CurrentUser, 
         clientIp: DisplayUrl, 
         serverIp: Environment.MachineName );
     errorResult.StatusCode = (int)HttpStatusCode.BadRequest;
     return errorResult;
 }
        public async Task<IActionResult> Classifiers([FromBody]CreateClassifierViewModel viewModel)
        {
            if (viewModel == null)
            {
                return BadRequest("Missing view model");
            }

            // get zip file for each selected bundle
            ClassPositiveExamples[] positiveExamples = viewModel.Bundles
                .Where(m => !m.StartsWith("negative")).Select(m => new ClassPositiveExamples()
                {
                    ClassName = viewModel.Names[viewModel.Bundles.IndexOf(m)],
                    FileName = Path.Combine(_hostingEnvironment.WebRootPath, "images", "bundles", viewModel.Kind, m + ".zip")
                }).ToArray();
            var negativeBundle = viewModel.Bundles.FirstOrDefault(m => m.StartsWith("negative"));
            string negativeZipFile = null;
            if (negativeBundle != null)
            {
                negativeZipFile =
                    Path.Combine(_hostingEnvironment.WebRootPath, "images", "bundles", viewModel.Kind, negativeBundle + ".zip");
            }

            // call VisualRecognitionService and return the created classifier
            var result = new JsonResult(await _visualRecognitionService.CreateClassifierAsync(viewModel.Name, negativeZipFile, positiveExamples));

            // cleanup can happen after the result is returned to the front-end
            // disable the warning about this task continuing after the method ends
#pragma warning disable 4014
            Task.Run(() =>
            {
                // delete the classifier after 1 hour
                if (((Classifier)result?.Value)?.ClassifierId != null)
                {
                    var classifierId = ((Classifier)result.Value).ClassifierId;
                    Task.Factory.StartNew(() =>
                    {
                        Task.Delay(new TimeSpan(1, 0, 0)).ContinueWith(async (task) =>
                        {
                            await _visualRecognitionService
                                .DeleteClassifierAsync(classifierId);
                        });
                    });
                }
            });
#pragma warning restore 4014

            result.StatusCode = 200;
            return result;
        }
Ejemplo n.º 3
0
        public async Task ExecuteAsync_WritesJsonContent()
        {
            // Arrange
            var value = new { foo = "abcd" };
            var expected = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(value));

            var context = GetActionContext();

            var result = new JsonResult(value);

            // Act
            await result.ExecuteResultAsync(context);

            // Assert
            var written = GetWrittenBytes(context.HttpContext);
            Assert.Equal(expected, written);
            Assert.Equal("application/json; charset=utf-8", context.HttpContext.Response.ContentType);
        }
Ejemplo n.º 4
0
        private static void HandleException(ExceptionContext context)
        {
            //todo: logging

            if (!context.IsAjaxRequest())
            {
                return;
            }

            var data = new ApiError
            {
                Errors = new Dictionary<string, IEnumerable<string>>
                {
                    {"*", new[] {context.Exception.Message}}
                }
            };

            var jsonResult = new JsonResult(data) {StatusCode = (int) HttpStatusCode.InternalServerError};

            context.Result = jsonResult;
        }
        public static IActionResult Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log, ExecutionContext context,
            [Queue("report-generation", Connection = "AzureWebJobsStorage")] out string reportName)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");


            string name = req.Query["name"];



            string  requestBody = new StreamReader(req.Body).ReadToEnd();
            dynamic data        = JsonConvert.DeserializeObject(requestBody);

            reportName = name ?? data?.name;


            var res = new Microsoft.AspNetCore.Mvc.JsonResult(new { queued = reportName });

            return(res);
        }
Ejemplo n.º 6
0
 public JsonResult CustomContentType()
 {
     var result = new JsonResult(new { Message = "hello" });
     result.ContentType = "application/message+json";
     return result;
 }
        private async Task<JsonResult> ProcessUpload(IFormFile file)
        {
            Trace.TraceInformation("Process upload for {0}", file.ToString());

            var t = DateTime.UtcNow - new DateTime(1970, 1, 1);
            var epoch = (int)t.TotalSeconds;
            var sourceName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
            var filePath = Path.GetTempFileName();
            string url = null;

            // Save locally
            using (var stream = System.IO.File.OpenWrite(filePath))
            {
                await file.CopyToAsync(stream);
            }
            
            try
            {
                var resultPaths = ConvertFiles(filePath, sourceName);
            

                if (resultPaths != null && resultPaths.Any())
                {
                    foreach (var path in resultPaths)
                    {
                        Trace.TraceInformation("Moving to blob store: {0}", path);
                        var blobUri = await _storage.UploadFileToBlob(path, Path.GetFileName(path));

                        // Hack - Grab the destination URI for use later
                        if (blobUri.Contains(".dat"))
                        {
                            url = blobUri.Replace(".dat", string.Empty);
                        }
                    
                    }

                    // update project name if appropriate
                    string projectName = Path.GetFileNameWithoutExtension(sourceName);
                    var projects = _storage.GetProjectsForUser(GetEmailFromUser());

                    if (projects.Where(p => string.Equals(p.Name, projectName, StringComparison.OrdinalIgnoreCase)).Any())
                    {
                        int versionNumber = projects.Count(p => p.Name.Contains(projectName)) + 1;
                        projectName = string.Format("{0} (v{1})", projectName, versionNumber);
                    }
                    _storage.SaveFileToTables(projectName, url, GetEmailFromUser());
                }

            }
            catch (Exception ex)
            {
                var result = new JsonResult(new { error = "The server failed to process this file.  Please verify source data is compatible." });
                result.StatusCode = 500;
                return result;
            }

            return Json(new { thumbnail = "url" + ".jpg" });
        }