Пример #1
0
        public async Task <AnimalImage> UploadImage2([FromBody] AnimalImage animalImage)
        {
            try
            {
                var key = await _kv.GetKeyByName("WebSiteKey");

                CloudBlobClient    blobClient = BlobStorageAccount.CreateCloudBlobClient();
                CloudBlobContainer container  = blobClient.GetContainerReference(BlobStorageContainerName);
                await container.CreateIfNotExistsAsync();

                animalImage.Id        = Guid.NewGuid().ToString().ToLowerInvariant();
                animalImage.ImageName = animalImage.ImageName;
                animalImage.ImageBlob = $"{animalImage.Id}/{animalImage.ImageName}";

                // This call creates a local CloudBlobContainer object, but does not make a network call
                // to the Azure Storage Service. The container on the service that this object represents may
                // or may not exist at this point. If it does exist, the properties will not yet have been
                // popluated on this object.
                CloudBlockBlob blockblob = container.GetBlockBlobReference(animalImage.ImageBlob);
                animalImage.UploadBlobSASUrl = Utils.GenerateWriteSasUrl(blockblob);

                // upload data to Cosmos DB
                await CosmosDBClient.UpsertDocumentAsync(CosmosDBCollectionUri, animalImage);

                //return blob url for uploading image
                return(animalImage);
            }
            catch (Exception ex)
            {
                // TODO: need better exception handling
                Trace.TraceError(ex.ToString());
                throw;
            }
        }
        public async Task <IActionResult> Edit(int id, [Bind("UserId,AnimalId,ImageUrl,Id,CreatedOn,ModifiedOn")] AnimalImage animalImage)
        {
            if (id != animalImage.Id)
            {
                return(this.NotFound());
            }

            if (this.ModelState.IsValid)
            {
                try
                {
                    this.db.Update(animalImage);
                    await this.db.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!this.AnimalImageExists(animalImage.Id))
                    {
                        return(this.NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }

                return(this.RedirectToAction(nameof(this.Index)));
            }

            this.ViewData["AnimalId"] = new SelectList(this.db.Animals, "Id", "Id", animalImage.AnimalId);
            this.ViewData["UserId"]   = new SelectList(this.db.Users, "Id", "Id", animalImage.UserId);
            return(this.View(animalImage));
        }
        public ActionResult DeleteConfirmed(int id)
        {
            AnimalImage AnimalImage = db.AnimalImages.Find(id);
            //find all the mappings for this image
            var mappings = AnimalImage.AnimalImageMappings.Where(pim => pim.AnimalImageID == id);

            foreach (var mapping in mappings)
            {
                //find all mappings for any Animal containing this image
                var mappingsToUpdate = db.AnimalImageMappings.Where(pim => pim.AnimalID == mapping.AnimalID);
                //for each image in each Animal change its imagenumber to one lower if it is higher than the current image
                foreach (var mappingToUpdate in mappingsToUpdate)
                {
                    if (mappingToUpdate.ImageNumber > mapping.ImageNumber)
                    {
                        mappingToUpdate.ImageNumber--;
                    }
                }
            }

            System.IO.File.Delete(Request.MapPath(Constants.AnimalImagePath + AnimalImage.FileName));
            System.IO.File.Delete(Request.MapPath(Constants.AnimalThumbnailPath + AnimalImage.FileName));
            db.AnimalImages.Remove(AnimalImage);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
        public async Task CreateAnimalImageAsync(AddImagesInputModel input, string userId, int animalId)
        {
            foreach (var image in input.Images)
            {
                var extension = Path.GetExtension(image.FileName);

                if (!this.allowedExtensions.Any(x => extension.EndsWith(x)))
                {
                    throw new Exception($"Invalid image extension {extension}");
                }

                var imageUrl = await this.cloudinaryService.UploadAsync(this.cloudinary, image);

                var tempImage = new AnimalImage
                {
                    UserId   = userId,
                    AnimalId = animalId,
                    ImageUrl = imageUrl,
                };

                await this.animalImagesRepository.AddAsync(tempImage);
            }

            await this.animalImagesRepository.SaveChangesAsync();
        }
        public async Task <AnimalImage> CreateUpdateRecordByName([FromBody] AnimalImage image)
        {
            //DocumentCollection coll = await CosmosDBClient.CreateDocumentCollectionIfNotExistsAsync(new Uri(CosmosDBUrl),
            //    new DocumentCollection { Id = CosmosDBCollectionName },
            //    new RequestOptions { OfferThroughput = 10000 });

            FeedOptions queryOptions = new FeedOptions {
                MaxItemCount = -1, EnableCrossPartitionQuery = true
            };
            var ifexist = CosmosDBClient.CreateDocumentQuery <AnimalImage>(
                UriFactory.CreateDocumentCollectionUri(CosmosDBName, CosmosDBCollectionName), queryOptions).Where(u => u.ImageName == image.ImageName);
            //if (!ifexist.Any())
            //{
            //    return await UploadImage2(image);
            //}
            var result = new List <AnimalImage>(ifexist);

            if (result.Count == 0)
            {
                return(await UploadImage2(image));
            }
            else
            {
                result[0].Tag          = image.Tag;
                result[0].LocationName = image.LocationName;
                await CosmosDBClient.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(CosmosDBName, CosmosDBCollectionName, result[0].Id), result[0]);

                CloudBlobClient    blobClient = BlobStorageAccount.CreateCloudBlobClient();
                CloudBlobContainer container  = blobClient.GetContainerReference(BlobStorageContainerName);
                CloudBlockBlob     blockblob  = container.GetBlockBlobReference(result[0].ImageBlob);
                result[0].UploadBlobSASUrl = Utils.GenerateWriteSasUrl(blockblob);
                return(result[0]);
            }
        }
Пример #6
0
        async Task <AnimalImage> UploadImage(string imagePath)
        {
            try
            {
                var         client = new HttpClient();
                AnimalImage image  = new AnimalImage();
                image.ImageName  = Path.GetFileNameWithoutExtension(imagePath);
                image.FileFormat = Path.GetExtension(imagePath);

                // 1. Upload meta data to Cosmos DB
                string uploadUrl = "http://tncapi.azurewebsites.net/api/storage/Upload2";
                string imageJson = JsonConvert.SerializeObject(image);
                byte[] byteData  = Encoding.UTF8.GetBytes(imageJson);
                HttpResponseMessage response;

                using (var content = new ByteArrayContent(byteData))
                {
                    content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                    this.richTextBox1.Text      = ("Sending image info to Cosmos DataBase");
                    this.UploadingBar.Value    += 33;
                    response = await client.PostAsync(uploadUrl, content);

                    //response = client.PostAsync(uploadUrl, content).Result;
                }

                string responseStr = response.Content.ReadAsStringAsync().Result;
                Console.WriteLine(responseStr);
                AnimalImage imageResponse = JsonConvert.DeserializeObject <AnimalImage>(responseStr);

                // 2. uppload image self to blob storage
                byte[]         blobContent = File.ReadAllBytes(imagePath);
                CloudBlockBlob blob        = new CloudBlockBlob(new Uri(imageResponse.UploadBlobSASUrl));
                MemoryStream   msWrite     = new MemoryStream(blobContent);
                msWrite.Position = 0;

                using (msWrite)
                {
                    this.richTextBox1.Text = ("Uploading image data to Storage Colletion");
                    await blob.UploadFromStreamAsync(msWrite);

                    this.UploadingBar.Value += 33;
                }

                return(imageResponse);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                throw ex;
            }
        }
Пример #7
0
        private static void MetadataValidate(List <AnimalImage> animalImages, Func <AnimalImage, bool> validator, string message)
        {
            AnimalImage invalidImage = animalImages.FirstOrDefault(validator);

            if (invalidImage != null)
            {
                throw new TncException()
                      {
                          StatusCode   = HttpStatusCode.BadRequest,
                          ErrorCode    = ErrorCode.BadCSVMetadata,
                          ErrorMessage = "Message: " + message + " Image: " + JsonConvert.SerializeObject(invalidImage)
                      };
            }
        }
        public async Task <IActionResult> Create([Bind("UserId,AnimalId,ImageUrl,Id,CreatedOn,ModifiedOn")] AnimalImage animalImage)
        {
            if (this.ModelState.IsValid)
            {
                this.db.Add(animalImage);
                await this.db.SaveChangesAsync();

                return(this.RedirectToAction(nameof(this.Index)));
            }

            this.ViewData["AnimalId"] = new SelectList(this.db.Animals, "Id", "Id", animalImage.AnimalId);
            this.ViewData["UserId"]   = new SelectList(this.db.Users, "Id", "Id", animalImage.UserId);
            return(this.View(animalImage));
        }
Пример #9
0
        static async Task <AnimalImage> UploadImage(string imagePath)
        {
            try
            {
                var         client = new HttpClient();
                AnimalImage image  = new AnimalImage();
                image.ImageName  = Path.GetFileNameWithoutExtension(imagePath);
                image.FileFormat = Path.GetExtension(imagePath);

                Stopwatch watch = new Stopwatch();
                watch.Start();

                // 1. Upload meta data to Cosmos DB
                string uploadUrl = "http://tncapi.azurewebsites.net/api/storage/Upload2";
                string imageJson = JsonConvert.SerializeObject(image);
                byte[] byteData  = Encoding.UTF8.GetBytes(imageJson);
                HttpResponseMessage response;

                using (var content = new ByteArrayContent(byteData))
                {
                    content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                    response = await client.PostAsync(uploadUrl, content);
                }

                string responseStr = await response.Content.ReadAsStringAsync();

                Console.WriteLine(responseStr);
                AnimalImage imageResponse = JsonConvert.DeserializeObject <AnimalImage>(responseStr);
                Console.WriteLine("\nGet Uploading URL: " + watch.ElapsedMilliseconds);
                watch.Restart();

                // 2. uppload image self to blob storage
                byte[]         blobContent = File.ReadAllBytes(imagePath);
                CloudBlockBlob blob        = new CloudBlockBlob(new Uri(imageResponse.UploadBlobSASUrl));
                MemoryStream   msWrite     = new MemoryStream(blobContent);
                msWrite.Position = 0;
                using (msWrite)
                {
                    await blob.UploadFromStreamAsync(msWrite);
                }
                Console.WriteLine("\nImage uploaded: " + watch.ElapsedMilliseconds);

                return(imageResponse);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                throw ex;
            }
        }
Пример #10
0
        public async Task GetRandomPikachuImage()
        {
            var           client       = new RestClient($"https://some-random-api.ml/img/pikachu");
            var           request      = new RestRequest(Method.GET);
            IRestResponse response     = client.Execute(request);
            AnimalImage   animalimages = JsonConvert.DeserializeObject <AnimalImage>(response.Content);

            Console.WriteLine(response.Content);

            var builder = new EmbedBuilder()
                          .WithTitle("Pickachu")
                          .WithImageUrl($"{animalimages.link}")
                          .WithFooter("From Some Random API");

            var embed = builder.Build();
            await Context.Channel.SendMessageAsync(null, false, embed);
        }
Пример #11
0
        private async void BtnUpload_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                OpenFileDialog openFileDialog = new OpenFileDialog();
                openFileDialog.ShowDialog(); // Show the dialog.
//                                if (result == DialogResult.OK) // Test result.
//                                {
//                                }

                // 1. upload image
                string imagePath = openFileDialog.FileName;

                this.pictureBox1.Source = new BitmapImage(new Uri(imagePath, UriKind.RelativeOrAbsolute));

                AnimalImage image = await UploadImage(imagePath);

                //this.richTextBox1.Text = image.UploadBlobSASUrl;

                // 2. image classification
                string imageUrl = $"https://tncstorage4test.blob.core.windows.net/animalimages/{image.ImageBlob}";
                this.richTextBox1.Text = ("Waiting for prediction result...");
                var preResult = await MakePredictionRequestCNTK(imageUrl);

                this.UploadingBar.Value += 33;
                this.richTextBox1.Clear();
                List <String> items  = new List <String>();
                var           sorted = preResult.Predictions.OrderByDescending(f => f.Probability);
                foreach (var pre in sorted)
                {
                    // this.richTextBox1.Text += pre.Tag + ":  " + pre.Probability.ToString("P", CultureInfo.InvariantCulture) + "\n";
                    items.Add(pre.Tag + ":  " + Math.Round(pre.Probability * 100, 6) + "%\n");
                }
                this.ListV.ItemsSource = items;
                this.richTextBox1.Text = "Done Uploading";
            }
            catch (Exception ex)
            {
                //this.ListV.Items.Clear();
                //this.ListV.Items.Add(ex.ToString());
                throw ex;
            }
        }
Пример #12
0
        static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine("TNCImagePredictionConsole.exe <Path_To_Local_Image>");
                Console.WriteLine(@"Example: TNCImagePredictionConsole.exe E:\Monkey.jpg");
            }

            // 1. upload image
            string      imagePath = args[0];
            AnimalImage image     = UploadImage(imagePath).Result;

            // 2. image classification
            string imageUrl = $"https://tncstorage4test.blob.core.windows.net/animalimages/{image.ImageBlob}";

            MakePredictionRequestCNTK(imageUrl);

            Console.ReadLine();
        }
Пример #13
0
        static void Main(string[] args)
        {
            //open DB
            using (var context = new WildscreenAnimalsAPI_dbEntities())
            {
                var animals         = context.Animals.ToList();//Get all animals
                var allAnimalImages = context.AnimalImages.ToList();

                foreach (var animal in animals)
                {
                    //Do a flickr search on the animal
                    var json         = SendRequest(string.Format(flickrSearchUrl, flickrKey, WebUtility.UrlEncode(animal.Name)));
                    var searchResult = JsonConvert.DeserializeObject <FlickrSearchResponse>(json);
                    //Loop through flikr images returned in the resuts and get image urls for them
                    if (searchResult.photos != null && searchResult.photos.photo.Count > 0)
                    {
                        foreach (var fPhoto in searchResult.photos.photo)
                        {
                            var photo = new AnimalImage()
                            {
                                Animal_Id    = animal.Id,
                                CreatedOn    = DateTime.Now,
                                Downvotes    = 0,
                                Upvotes      = 0,
                                SourceSystem = "Flickr",
                                ImageUrl     = string.Format(flickrImageUrl, fPhoto.farm, fPhoto.server, fPhoto.id, fPhoto.secret),
                                Name         = fPhoto.title
                            };
                            if (!allAnimalImages.Any(x => x.ImageUrl == photo.ImageUrl))
                            {
                                context.AnimalImages.Add(photo);
                            }
                        } //foreach
                    }     //if
                     //Create an image record
                }
                //Save
                context.SaveChanges();
            } //close db
        }
Пример #14
0
        /// <summary>
        /// This method will help get the UI set up for a new game and will
        /// work with other classes to reset variables for a new game.
        /// </summary>
        public void SetGameUp()
        {
            try
            {
                //Setting game variables
                newGame.GameType            = User.UsersLatestChoice;
                newGame.NumProblemsAnswered = 0;
                newGame.Score = 0;
                newGame.SetUpProblem();

                cancelled = false;

                //Clearing Displays
                FeedbackLabel.Content          = "";
                ProblemAnswerTextBox.IsEnabled = true;
                ProblemNumberLabel.Content     = "";
                ProblemAnswerTextBox.Text      = "";
                CurrentProblemLabel.Content    = "";
                operandDisplay = newGame.LeftOperand.ToString() + newGame.currOperator + newGame.RightOperand.ToString();
                CurrentProblemLabel.Content = operandDisplay;
                Keyboard.Focus(ProblemAnswerTextBox);
                Feedback2Label.Content = "";
                AnimalImage.SetValue(System.Windows.Controls.Image.SourceProperty, null);

                //Reseting Answers
                User.SetArrayToFalse();

                //Reseting timer
                startTime        = DateTime.Now;
                myTimer.Interval = new TimeSpan(0, 0, 1);
                myTimer.Start();
            }
            catch (Exception ex)
            {
                throw new Exception(MethodInfo.GetCurrentMethod().DeclaringType.Name + "." +
                                    MethodInfo.GetCurrentMethod().Name + "." + ex.Message);
            }
        }
Пример #15
0
        private async void button1_Click(object sender, EventArgs e)
        {
            try
            {
                DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
                if (result == DialogResult.OK)                      // Test result.
                {
                }

                // 1. upload image
                string imagePath = openFileDialog1.FileName;
                this.pictureBox1.ImageLocation = openFileDialog1.FileName;

                AnimalImage image = await UploadImage(imagePath);

                //this.richTextBox1.Text = image.UploadBlobSASUrl;

                // 2. image classification
                string imageUrl = $"https://tncstorage4test.blob.core.windows.net/animalimages/{image.ImageBlob}";
                this.richTextBox1.Text = ("Waiting for prediction result...");
                var preResult = await MakePredictionRequestCNTK(imageUrl);

                this.richTextBox1.Clear();
                var sorted = preResult.Predictions.OrderByDescending(f => f.Probability);
                foreach (var pre in sorted)
                {
                    // this.richTextBox1.Text += pre.Tag + ":  " + pre.Probability.ToString("P", CultureInfo.InvariantCulture) + "\n";

                    this.richTextBox1.Text += pre.Tag + ":  " + pre.Probability + "\n";
                }
            }
            catch (Exception ex)
            {
                this.richTextBox1.Text = ex.ToString();
            }
        }
Пример #16
0
        public async Task <AnimalImage> Post([FromBody] AnimalImage animalImage)
        {
            CloudBlobClient    blobClient = this.AppConfiguration.BlobStorageAccount.CreateCloudBlobClient();
            CloudBlobContainer container  = blobClient.GetContainerReference(this.AppConfiguration.AnimalImageContainer);

            // Create a new container, if it does not exist
            container.CreateIfNotExists();

            // TODO: validate input
            animalImage.Id         = Guid.NewGuid().ToString().ToLowerInvariant();
            animalImage.ImageName  = animalImage.ImageName.ToLowerInvariant();
            animalImage.FileFormat = animalImage.FileFormat.ToLowerInvariant();
            animalImage.ImageBlob  = animalImage.Id + "/" + animalImage.ImageName +
                                     "." + animalImage.FileFormat;
            CloudBlockBlob blockblob = container.GetBlockBlobReference(animalImage.ImageBlob);

            await this.AppConfiguration.CosmosDBClient.UpsertDocumentAsync(
                this.AppConfiguration.AnimalImageCollectionUri,
                animalImage);

            animalImage.UploadBlobSASUrl = Utils.GenerateWriteSasUrl(blockblob);

            return(animalImage);
        }
Пример #17
0
        /// <summary>
        /// Works with the Game game class to check the user's answer and see if
        /// it was right. It will handle showing user correct/incorrect information
        /// and will display an animal if correct.
        /// </summary>
        private void CheckAnswer()
        {
            try
            {
                switch (newGame.GameType)
                {
                case "Addition":
                    if (newGame.AddNumberPair(ProblemAnswerTextBox.Text))
                    {
                        FeedbackLabel.Foreground = new SolidColorBrush(Colors.Green);
                        FeedbackLabel.Content    = "Correct!";
                        correct.Play();
                        GetAnimal();
                        User.WhichCorrect[newGame.NumProblemsAnswered - 1] = true;
                    }
                    else
                    {
                        FeedbackLabel.Foreground = new SolidColorBrush(Colors.Red);
                        FeedbackLabel.Content    = "Incorrect.";
                        incorrect.Play();
                        Feedback2Label.Content = "";
                        AnimalImage.SetValue(System.Windows.Controls.Image.SourceProperty, null);
                    }
                    break;

                case "Subtraction":
                    if (newGame.SubtractNumberPair(ProblemAnswerTextBox.Text))
                    {
                        FeedbackLabel.Foreground = new SolidColorBrush(Colors.Green);
                        FeedbackLabel.Content    = "Correct!";
                        correct.Play();
                        GetAnimal();
                        User.WhichCorrect[newGame.NumProblemsAnswered - 1] = true;
                    }
                    else
                    {
                        FeedbackLabel.Foreground = new SolidColorBrush(Colors.Red);
                        FeedbackLabel.Content    = "Incorrect.";
                        incorrect.Play();
                        Feedback2Label.Content = "";
                        AnimalImage.SetValue(System.Windows.Controls.Image.SourceProperty, null);
                    }
                    break;

                case "Multiplication":
                    if (newGame.MultiplyNumberPair(ProblemAnswerTextBox.Text))
                    {
                        FeedbackLabel.Foreground = new SolidColorBrush(Colors.Green);
                        FeedbackLabel.Content    = "Correct!";
                        correct.Play();
                        GetAnimal();
                        User.WhichCorrect[newGame.NumProblemsAnswered - 1] = true;
                    }
                    else
                    {
                        FeedbackLabel.Foreground = new SolidColorBrush(Colors.Red);
                        FeedbackLabel.Content    = "Incorrect.";
                        incorrect.Play();
                        Feedback2Label.Content = "";
                        AnimalImage.SetValue(System.Windows.Controls.Image.SourceProperty, null);
                    }
                    break;

                case "Division":
                    if (newGame.DivideNumberPair(ProblemAnswerTextBox.Text))
                    {
                        FeedbackLabel.Foreground = new SolidColorBrush(Colors.Green);
                        FeedbackLabel.Content    = "Correct!";
                        correct.Play();
                        GetAnimal();
                        User.WhichCorrect[newGame.NumProblemsAnswered - 1] = true;
                    }
                    else
                    {
                        FeedbackLabel.Foreground = new SolidColorBrush(Colors.Red);
                        FeedbackLabel.Content    = "Incorrect.";
                        incorrect.Play();
                        Feedback2Label.Content = "";
                        AnimalImage.SetValue(System.Windows.Controls.Image.SourceProperty, null);
                    }
                    break;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(MethodInfo.GetCurrentMethod().DeclaringType.Name + "." +
                                    MethodInfo.GetCurrentMethod().Name + "." + ex.Message);
            }
        }
        public ActionResult Delete(int id)
        {
            AnimalImage AnimalImage = db.AnimalImages.Find(id);

            return(View(AnimalImage));
        }
        public ActionResult Upload(HttpPostedFileBase[] files)
        {
            bool   allValid     = true;
            string inValidFiles = "";

            //check the user has entered a file
            if (files[0] != null)
            {
                //if the user has entered less than ten files
                if (files.Length <= 10)
                {
                    //check they are all valid
                    foreach (var file in files)
                    {
                        if (!ValidateFile(file))
                        {
                            allValid      = false;
                            inValidFiles += ", " + file.FileName;
                        }
                    }
                    //if they are all valid then try to save them to disk
                    if (allValid)
                    {
                        foreach (var file in files)
                        {
                            try
                            {
                                SaveFileToDisk(file);
                            }
                            catch (Exception)
                            {
                                ModelState.AddModelError("FileName", "Sorry an error occurred saving the files to disk, please try again");
                            }
                        }
                    }
                    //else add an error listing out the invalid files
                    else
                    {
                        ModelState.AddModelError("FileName", "All files must be gif, png, jpeg or jpg  and less than 2MB in size. The following files" + inValidFiles +
                                                 " are not valid");
                    }
                }
                //the user has entered more than 10 files
                else
                {
                    ModelState.AddModelError("FileName", "Please only upload up to ten files at a time");
                }
            }
            else
            {
                //if the user has not entered a file return an error message
                ModelState.AddModelError("FileName", "Please choose a file");
            }

            if (ModelState.IsValid)
            {
                bool   duplicates     = false;
                bool   otherDbError   = false;
                string duplicateFiles = "";
                foreach (var file in files)
                {
                    //try and save each file
                    var AnimalToAdd = new AnimalImage {
                        FileName = file.FileName
                    };
                    try
                    {
                        db.AnimalImages.Add(AnimalToAdd);
                        db.SaveChanges();
                    }
                    //if there is an exception check if it is caused by a duplicate file
                    catch (DbUpdateException ex)
                    {
                        SqlException innerException = ex.InnerException.InnerException as SqlException;
                        if (innerException != null && innerException.Number == 2601)
                        {
                            duplicateFiles += ", " + file.FileName;
                            duplicates      = true;
                            db.Entry(AnimalToAdd).State = EntityState.Detached;
                        }
                        else
                        {
                            otherDbError = true;
                        }
                    }
                }
                //add a list of duplicate files to the error message
                if (duplicates)
                {
                    ModelState.AddModelError("FileName", "All files uploaded except the files" + duplicateFiles + ", which already exist in the system." +
                                             " Please delete them and try again if you wish to re-add them");
                    return(View());
                }
                else if (otherDbError)
                {
                    ModelState.AddModelError("FileName", "Sorry an error has occurred saving to the database, please try again");
                    return(View());
                }
                return(RedirectToAction("Index"));
            }
            return(View());
        }
Пример #20
0
        public async Task UploadOneAnimalImage()
        {
            // upload request
            string content = "";
            HttpResponseMessage response = null;
            var animal = new AnimalImage
            {
                Tag        = "my first image",
                LocationId = "Golden Mokey Area",
                ImageName  = "image0001",
                FileFormat = "JPG"
            };

            AnimalImage animalReturned = null;

            try
            {
                var stringContent  = JsonConvert.SerializeObject(animal);
                var requestContent = new StringContent(stringContent, Encoding.UTF8, "application/json");

                response = await client.PostAsync("api/animalimages", requestContent);

                if (response.IsSuccessStatusCode)
                {
                    content = await response.Content.ReadAsStringAsync();
                }
                Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
                animalReturned = JsonConvert.DeserializeObject <AnimalImage>(content);
                Assert.IsNotNull(animalReturned.ImageBlob);
                Assert.IsNotNull(animalReturned.UploadBlobSASUrl);
                Assert.IsNotNull(animalReturned.Id);
            }
            catch (Exception e)
            {
                LogInfo(e.Message);
                throw;
            }
            finally
            {
                LogInfo($"received response status {response.StatusCode}, response content: {content}");
            }

            // now can use the provided UploadBlobSASUrl to upload image
            string         blobContent = "This is how I upload an image";
            CloudBlockBlob blob        = new CloudBlockBlob(new Uri(animalReturned.UploadBlobSASUrl));

            // Create operation: Upload a blob with the specified name to the container.
            // If the blob does not exist, it will be created. If it does exist, it will be overwritten.
            try
            {
                MemoryStream msWrite = new MemoryStream(Encoding.UTF8.GetBytes(blobContent));
                msWrite.Position = 0;
                using (msWrite)
                {
                    await blob.UploadFromStreamAsync(msWrite);
                }

                LogInfo($"Create operation succeeded for SAS {animalReturned.UploadBlobSASUrl}\n");
            }
            catch (StorageException e)
            {
                LogInfo($"Create operation failed for SAS {animalReturned.UploadBlobSASUrl} : {e.ToString()}\n");
                throw;
            }

            // Get
            response = await client.GetAsync($"api/animalimages/{animalReturned.Id}");

            if (response.IsSuccessStatusCode)
            {
                content = await response.Content.ReadAsStringAsync();

                LogInfo($"received response status {response.StatusCode}, response content: {content}");
            }

            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
            animalReturned = JsonConvert.DeserializeObject <AnimalImage>(content);
            Assert.IsNotNull(animalReturned.ImageBlob);
            Assert.IsNotNull(animalReturned.DownloadBlobSASUrl);
            Assert.IsNotNull(animalReturned.Id);
            Assert.AreEqual(animal.Tag, animalReturned.Tag);
            Assert.AreEqual(animal.LocationId, animalReturned.LocationId);
            Assert.AreEqual(animal.ImageName, animalReturned.ImageName);
            Assert.AreNotEqual(animal.FileFormat, animalReturned.FileFormat);
            Assert.AreEqual(animal.FileFormat.ToLowerInvariant(), animalReturned.FileFormat);
        }
Пример #21
0
        public void TestCsvMetadataParsing()
        {
            List <AnimalImage> expectedValues = new List <AnimalImage>(new[]
            {
                new AnimalImage
                {
                    OriginalFileId         = "L-TJH15-V08A-0001",
                    OriginalImageId        = "IMAG0001",
                    FileFormat             = "JPG",
                    OriginalFolderId       = "L-TJH15-V08A",
                    CameraId               = "T0330",
                    LocationId             = "L-TJH15-V08A",
                    CameraInstallationDate = new DateTime(2017, 12, 01),
                    ShootingTime           = "19:00",
                    WorkingDays            = 1,
                    Category               = "工作人员",
                    IndependentProbeFirst  = "1",
                    Notes = "设置相机"
                },
                new AnimalImage
                {
                    OriginalFileId   = "L-TJH15-V08A-0002",
                    OriginalImageId  = "IMAG0002",
                    FileFormat       = "JPG",
                    OriginalFolderId = "L-TJH15-V08A",
                    CameraId         = "T0330",
                    LocationId       = "L-TJH15-V08A",
                    ShootingTime     = "19:00",
                    WorkingDays      = 1,
                    Category         = "工作人员"
                },
                new AnimalImage
                {
                    OriginalFileId   = "L-TJH15-V08A-0003",
                    OriginalImageId  = "IMAG0003",
                    FileFormat       = "JPG",
                    OriginalFolderId = "L-TJH15-V08A",
                    CameraId         = "T0330",
                    LocationId       = "L-TJH15-V08A",
                    ShootingTime     = "19:00",
                    WorkingDays      = 1,
                    Category         = "工作人员"
                },
                new AnimalImage
                {
                    OriginalFileId   = "L-TJH15-V08A-0004",
                    OriginalImageId  = "IMAG0004",
                    FileFormat       = "AVI",
                    OriginalFolderId = "L-TJH15-V08A",
                    CameraId         = "T0330",
                    LocationId       = "L-TJH15-V08A",
                    ShootingTime     = "19:00",
                    WorkingDays      = 1,
                    Category         = "工作人员"
                },
                new AnimalImage
                {
                    OriginalFileId        = "L-TJH15-V08A-0005",
                    OriginalImageId       = "IMAG0025",
                    FileFormat            = "JPG",
                    OriginalFolderId      = "L-TJH15-V08A",
                    CameraId              = "T0330",
                    LocationId            = "L-TJH15-V08A",
                    ShootingTime          = "2:12",
                    WorkingDays           = 2,
                    Category              = "兽类",
                    SpecicesName          = "猪獾",
                    AnimalQuantity        = 1,
                    IndependentProbeFirst = "1"
                }
            });

            List <AnimalImage> parsedData = AnimalImage.ReadFromCsv(ValidCsvMetadata);

            Assert.AreEqual(expectedValues.Count, parsedData.Count);

            for (int i = 0; i < expectedValues.Count; i++)
            {
                Assert.AreEqual(expectedValues[i].OriginalFileId, parsedData[i].OriginalFileId, $"Line {i}, field 'OriginalFileId'");
                Assert.AreEqual(expectedValues[i].OriginalImageId, parsedData[i].OriginalImageId, $"Line {i}, field 'OriginalImageId'");
                Assert.AreEqual(expectedValues[i].FileFormat, parsedData[i].FileFormat, $"Line {i}, field 'FileFormat'");
                Assert.AreEqual(expectedValues[i].OriginalFolderId, parsedData[i].OriginalFolderId, $"Line {i}, field 'OriginalFolderId'");
                Assert.AreEqual(expectedValues[i].CameraId, parsedData[i].CameraId, $"Line {i}, field 'CameraId'");
                Assert.AreEqual(expectedValues[i].LocationId, parsedData[i].LocationId, $"Line {i}, field 'LocationId'");
                Assert.AreEqual(expectedValues[i].CameraInstallationDate, parsedData[i].CameraInstallationDate, $"Line {i}, field 'CameraInstallationDate'");
                Assert.AreEqual(expectedValues[i].ShootingTime, parsedData[i].ShootingTime, $"Line {i}, field 'ShootingTime'");
                Assert.AreEqual(expectedValues[i].WorkingDays, parsedData[i].WorkingDays, $"Line {i}, field 'WorkingDays'");
                Assert.AreEqual(expectedValues[i].Category, parsedData[i].Category, $"Line {i}, field 'Category'");
                Assert.AreEqual(expectedValues[i].SpecicesName, parsedData[i].SpecicesName, $"Line {i}, field 'SpecicesName'");
                Assert.AreEqual(expectedValues[i].AnimalQuantity, parsedData[i].AnimalQuantity, $"Line {i}, field 'AnimalQuantity'");
                Assert.AreEqual(expectedValues[i].Sex, parsedData[i].Sex, $"Line {i}, field 'Sex'");
                Assert.AreEqual(expectedValues[i].IndependentProbeFirst, parsedData[i].IndependentProbeFirst, $"Line {i}, field 'IndependentProbeFirst'");
                Assert.AreEqual(expectedValues[i].Notes, parsedData[i].Notes, $"Line {i}, field 'Notes'");
            }
        }
Пример #22
0
        public async Task <IHttpActionResult> UploadImageBatchAsync([FromBody] UploadBatchRequest value)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(value.BatchTag))
                {
                    throw new TncException()
                          {
                              StatusCode   = HttpStatusCode.BadRequest,
                              ErrorCode    = ErrorCode.ProperyCannotBeEmpty,
                              ErrorMessage = string.Format(ErrorMessages.PropertyCannotBeEmpty, "BatchTag")
                          };
                }

                if (string.IsNullOrWhiteSpace(value.CSVMetadata))
                {
                    throw new TncException()
                          {
                              StatusCode   = HttpStatusCode.BadRequest,
                              ErrorCode    = ErrorCode.ProperyCannotBeEmpty,
                              ErrorMessage = string.Format(ErrorMessages.PropertyCannotBeEmpty, "CSVMetadata")
                          };
                }

                List <AnimalImage> animalImages;
                try
                {
                    animalImages = AnimalImage.ReadFromCsv(value.CSVMetadata);
                }
                catch (Exception ex)
                {
                    throw new TncException()
                          {
                              StatusCode   = HttpStatusCode.BadRequest,
                              ErrorCode    = ErrorCode.BadCSVMetadata,
                              ErrorMessage = ex.Message
                          };
                }

                MetadataValidate(animalImages, a => string.IsNullOrWhiteSpace(a.OriginalFileId), "OriginalFileId is not present");
                MetadataValidate(animalImages, a => string.IsNullOrWhiteSpace(a.OriginalFolderId), "OriginalFolderId is not present");
                MetadataValidate(animalImages, a => string.IsNullOrWhiteSpace(a.OriginalImageId), "OriginalImageId is not present");
                MetadataValidate(animalImages, a => string.IsNullOrWhiteSpace(a.FileFormat), "FileFormat is not present");

                var operation = new OperationResult
                {
                    CreationTime = DateTime.UtcNow,
                    Id           = Guid.NewGuid().ToString(),
                    Status       = new OperationStatus {
                        Code = OperationStage.New
                    }
                };

                await this.AppConfiguration.CosmosDBClient.UpsertDocumentAsync(
                    this.AppConfiguration.OperationResultCollectionUri,
                    operation);

                Uri        originalUri = this.Request.RequestUri;
                UriBuilder uriBuilder  = new UriBuilder(originalUri.Scheme, originalUri.Host, originalUri.Port, $"/api/operationresults/{operation.Id}");

                this.Request.Properties[Constants.CustomResponseHeaders] = new Dictionary <string, string>()
                {
                    { Constants.LocationHeader, uriBuilder.Uri.AbsoluteUri },
                    { Constants.RetryAfterHeader, Constants.RetryIntervalInSeconds.ToString() }
                };

                return(this.Accepted());
            }
            catch (TncException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new TncException
                      {
                          ErrorCode    = "UnexpectedException",
                          ErrorMessage = ex.ToString()
                      };
            }
        }