public async Task <IActionResult> DeleteImage(Guid imageId, CancellationToken cancellationToken) { _logger.LogInformation($"Deleting image: {imageId}"); Agent.Tracer.ActiveSpan?.SetTag("CUSTOM_KEY", "CUSTOM_VALUE"); await using var imagesCtx = new ImagesContext(); var image = await imagesCtx.ImagesData .FirstOrDefaultAsync(i => i.Id == imageId, cancellationToken).ConfigureAwait(false); if (image == null) { _logger.LogError($"Image: {imageId}, can't be found."); return(NotFound()); } imagesCtx.ImagesData.Remove(image); if (await imagesCtx.SaveChangesAsync(cancellationToken) == 0) { _logger.LogError($"Image: {imageId}, cannot be deleted."); return(Problem("The image can't be deleted.")); } _logger.LogInformation($"Image: {imageId}, has been deleted."); return(Ok()); }
public bool DataBaseContains(float[] image, ref int resNumb) { bool res = false; var hash = ((IStructuralEquatable)image).GetHashCode(EqualityComparer <float> .Default); using (var db = new ImagesContext()) { var q = from item in db.Images where item.FileHash == hash select item; var l = q.ToList(); foreach (var item in l) { item.AccessCount++; if (item.FileContent.Length == image.Length && item.FileContent.SequenceEqual(ImageToByteArray(imgDir[images.IndexOf(image)]))) { res = true; resNumb = item.Class; break; } } } return(res); }
public void CanCreateDBEntry() { var options = new DbContextOptionsBuilder <ImagesContext>() .UseInMemoryDatabase(databaseName: "testDb") .Options; var builder = new ConfigurationBuilder().AddEnvironmentVariables(); builder.AddUserSecrets <Startup>(); var configuration = builder.Build(); using (var context = new ImagesContext(options)) { var controller = new ImageController(context, configuration); //Act controller.Create(new Image() { URL = "test Url" }); Image testImage = context.Images. FirstOrDefaultAsync(test => test.URL == "test Url").Result; //Assert Assert.Equal("test Url", testImage.URL); } }
static void Main(string[] args) { using (var db = new ImagesContext()) { /* * Initialize ImagesContext DB object as db. Add the classifications model to the DB to * represent the database. Then save changes. */ // Enter database upload logic in here foreach (var item in db.Classifications) { Console.WriteLine(item.Id); Console.WriteLine(item.Annotator); Console.WriteLine(item.Label); Console.WriteLine(item.ImageBin); Console.WriteLine(item.X); Console.WriteLine(item.Y); Console.WriteLine(item.W); Console.WriteLine(item.H); } } Console.WriteLine("Press any key to exit..."); Console.ReadKey(); }
static void Main(string[] args) { using (var db = new ImagesContext()) { /* Initialize ImagesContext DB object as db. Add the classifications model to the DB to represent the database. Then save changes. */ // Enter database upload logic in here foreach (var item in db.Classifications) { Console.WriteLine(item.Id); Console.WriteLine(item.Annotator); Console.WriteLine(item.Label); Console.WriteLine(item.ImageBin); Console.WriteLine(item.X); Console.WriteLine(item.Y); Console.WriteLine(item.W); Console.WriteLine(item.H); } } Console.WriteLine("Press any key to exit..."); Console.ReadKey(); }
public ImageModelXunitTesting() { DbContextOptions <ImagesContext> options = new DbContextOptionsBuilder <ImagesContext>() .UseInMemoryDatabase(Guid.NewGuid().ToString()) .Options; _context = new ImagesContext(options); }
public async Task <IActionResult> Details(int id) { var images = await ImagesContext.GetImagesAsync(id); var viewModel = await DatabaseContext.GetAsync(id); ViewData["typeOfRealEstate"] = (Models.RealEstate.TypeOfRealEstate)viewModel.Typeofrealestate; ViewData["Area"] = viewModel.Area; ViewData["City"] = viewModel.City; ViewData["CreationDate"] = viewModel.Modificationdate; ViewData["Price"] = viewModel.Price; ViewData["Pricem2"] = Convert.ToInt32(viewModel.Price / viewModel.Area); ViewData["RoomsAmount"] = viewModel.Roomamount; return(View(images)); }
public async Task <IActionResult> GetImage(Guid imageId, CancellationToken cancellationToken) { _logger.LogInformation($"Getting image: {imageId}"); Agent.Tracer.ActiveSpan?.SetTag("CUSTOM_KEY", "CUSTOM_VALUE"); await using var imagesCtx = new ImagesContext(); var image = await imagesCtx.ImagesData .FirstOrDefaultAsync(i => i.Id == imageId, cancellationToken).ConfigureAwait(false); if (image == null) { _logger.LogError($"Image: {imageId}, can't be found."); return(NotFound()); } _logger.LogInformation($"Image: {imageId}, found with {image.ContentData.Length} bytes"); return(File(image.ContentData, image.ContentType)); }
public void ProcessFile(float[] image) { int resNumb = -1; if (DataBaseContains(image, ref resNumb)) { results.Enqueue(new Tuple <string, int>(imgDir[images.IndexOf(image)], resNumb)); return; } SessionOptions options = new SessionOptions(); options.SetSessionGraphOptimizationLevel(0); using (var session = new InferenceSession(modelPath)) { var inputMeta = session.InputMetadata; var container = new List <NamedOnnxValue>(); foreach (var name in inputMeta.Keys) { var tensor = new DenseTensor <float>(image, inputMeta[name].Dimensions); container.Add(NamedOnnxValue.CreateFromTensor <float>(name, tensor)); } foreach (var res in session.Run(container)) { var maxVal = res.AsTensor <float>().Max(); var prob = Softmax(res.AsTensor <float>().ToList <float>()); resNumb = res.AsTensor <float>().ToList <float>().IndexOf(maxVal); results.Enqueue(new Tuple <string, int>(imgDir[images.IndexOf(image)], resNumb)); var hash = ((IStructuralEquatable)image).GetHashCode(EqualityComparer <float> .Default); using (var db = new ImagesContext()) { db.Images.Add(new DataBase.Image() { Name = imgDir[images.IndexOf(image)], Class = resNumb, FileHash = hash, FileContent = ImageToByteArray(imgDir[images.IndexOf(image)]) }); db.SaveChanges(); } } } }
public async Task <IActionResult> PostImage(Guid restaurantId, CancellationToken cancellationToken) { _logger.LogInformation("[RestaurantId: {restaurantId}] Storing a new image", restaurantId); Agent.Tracer.ActiveSpan?.SetTag("CUSTOM_KEY", "CUSTOM_VALUE"); string contentType; Stream fileStream; if (Request.ContentType.StartsWith("image/")) { contentType = Request.ContentType; fileStream = Request.Body; } else { _logger.LogCritical("No images were found in the request. Invalid ContentType = " + Request.ContentType); return(BadRequest("No images were found in the request. Invalid ContentType = " + Request.ContentType)); } _logger.LogInformation("[RestaurantId: {restaurantId}] ContentType: {contentType}", restaurantId, contentType); await using var imagesCtx = new ImagesContext(); var bytesData = await Utils.GetBytesFromStreamAsync(fileStream, cancellationToken).ConfigureAwait(false); if (bytesData.Length == 0) { throw new Exception("Image data length must be greater than 0"); } var imgData = new ImagesEntity { RestaurantId = restaurantId, ContentType = contentType, ContentData = bytesData }; imagesCtx.ImagesData.Add(imgData); _logger.LogInformation("Writing image data to database..."); await imagesCtx.SaveChangesAsync(cancellationToken).ConfigureAwait(false); _logger.LogInformation("[RestaurantId: {restaurantId}] Images saved with Id: {Id}", restaurantId, imgData.Id); return(Ok(imgData.Id)); }
public void FailDBEntry() { var options = new DbContextOptionsBuilder <ImagesContext>() .UseInMemoryDatabase(databaseName: "testDb") .Options; var builder = new ConfigurationBuilder().AddEnvironmentVariables(); builder.AddUserSecrets <Startup>(); var configuration = builder.Build(); using (var context = new ImagesContext(options)) { var controller = new ImageController(context, configuration); //Assert Assert.IsType <BadRequestResult>(controller.Create(null)); } }
private void UpdateResults() { if (NumCombo.SelectedItem != null) { var q = from res in result where res.Item2 == (int)NumCombo.SelectedItem select res.Item1; sourceLB.OnNext(q.ToList()); } AmountText.Text = "Processed pictures amount: " + result.Count; int count; using (var db = new ImagesContext()) { count = db.Images.ToList().Count; } DBAmountText.Text = "Pictures in database amount: " + count; }
public async void AnalyticsControllerXunitGetText() { var options = new DbContextOptionsBuilder <ImagesContext>() .UseInMemoryDatabase(databaseName: "testDb") .Options; var builder = new ConfigurationBuilder().AddEnvironmentVariables(); builder.AddUserSecrets <Startup>(); var configuration = builder.Build(); using (var context = new ImagesContext(options)) { var controller = new AnalyticsController(configuration); //Act var results = controller.GetText("true"); //Assert Assert.IsNotType <Analytics>(results); } }
public void CanGenerateURLs(string query, int numResults) { var options = new DbContextOptionsBuilder <ImagesContext>() .UseInMemoryDatabase(databaseName: "testDb") .Options; var builder = new ConfigurationBuilder().AddEnvironmentVariables(); builder.AddUserSecrets <Startup>(); var configuration = builder.Build(); using (var context = new ImagesContext(options)) { var controller = new ImageController(context, configuration); //Act var results = controller.GetUrls(query, numResults); //Assert Assert.IsType <OkObjectResult>(results); } }
public async void CanReturnBingSearch() { var options = new DbContextOptionsBuilder <ImagesContext>() .UseInMemoryDatabase(databaseName: "testDb") .Options; var builder = new ConfigurationBuilder().AddEnvironmentVariables(); builder.AddUserSecrets <Startup>(); var configuration = builder.Build(); using (var context = new ImagesContext(options)) { var controller = new ImageController(context, configuration); //Act var results = await controller.BingSearch("cats"); //Assert Assert.IsAssignableFrom <IEnumerable>(results); } }
public void TestingCanAnalyze() { var options = new DbContextOptionsBuilder <ImagesContext>() .UseInMemoryDatabase(databaseName: "testDb") .Options; var builder = new ConfigurationBuilder().AddEnvironmentVariables(); builder.AddUserSecrets <Startup>(); var configuration = builder.Build(); using (var context = new ImagesContext(options)) { var controller = new AnalyticsController(configuration); //Act var results = controller.Analyze("hello from the past this is me"); //Assert Assert.IsType <Analytics>(results); } }
public async Task <IEnumerable <Guid> > GetRestaurantImages(Guid restaurantId) { _logger.LogInformation($"Getting all images for RestaurantId: {restaurantId}"); Agent.Tracer.ActiveSpan?.SetTag("CUSTOM_KEY", "CUSTOM_VALUE"); await using var ctx = ImagesContext.GetBalancedContext(); var ids = await ctx.ImagesData .Where(i => i.RestaurantId == restaurantId) .Select(i => i.Id) .ToListAsync().ConfigureAwait(false); if (ids.Count == 0) { _logger.LogWarning($"No images were found for restaurant: {restaurantId}"); } else { _logger.LogInformation($"Number of images found for {restaurantId}: {ids.Count}"); } return(ids); }
private void InitializeComponent() { AvaloniaXamlLoader.Load(this); ImagesCar = this.FindControl <Carousel>("ImagesCarousel"); ImgCombo = this.FindControl <ComboBox>("ImagesCombobox"); ClassButton = this.FindControl <Button>("ClassButton"); StopButton = this.FindControl <Button>("StopButton"); DBButton = this.FindControl <Button>("DBButton"); NumCombo = this.FindControl <ComboBox>("ClassesCombobox"); ImagesListBox = this.FindControl <ListBox>("ImagesListBox"); ProccText = this.FindControl <TextBlock>("ComputTextBlock"); AmountText = this.FindControl <TextBlock>("PictAmountTextBlock"); AmountText.Text = "Processed pictures amount: 0"; DBAmountText = this.FindControl <TextBlock>("DBAmountTextBlock"); int count; using (var db = new ImagesContext()) { count = db.Images.ToList().Count; } DBAmountText.Text = "Pictures in database amount: " + count; ClassButton.IsEnabled = false; }
public IActionResult UploadFile(IFormFile file) { if (file != null || file.Length != 0) { var number = Convert.ToInt32(HttpContext.Request.Form["realedit"]); NewImageFolder(number); var path = Path.Combine( Directory.GetCurrentDirectory(), "wwwroot\\Images" + "\\" + number, file.FileName); using (var stream = new FileStream(path, FileMode.Create)) { file.CopyTo(stream); } Domain.Image img = new Domain.Image(); img.RealEstateId = number; img.Nazwapliku = file.FileName; ImagesContext.AddToDatabase(img); } return(RedirectToAction("Index", "Home")); }
//constructor connecting to the database public ImageController(ImagesContext context, IConfiguration configuration) { _context = context; Configuration = configuration; }
public ImgService(ImagesContext context) { db = context; }
public MainWindow() { InitializeComponent(); var comboImgBinding = ImgCombo.Bind(ComboBox.ItemsProperty, sourcePath); var carousBinding = ImagesCar.Bind(Carousel.ItemsProperty, sourceImg); var comboClassBinding = NumCombo.Bind(ComboBox.ItemsProperty, sourceNum); var listBocBinding = ImagesListBox.Bind(ListBox.ItemsProperty, sourceLB); sourceNum.OnNext(new List <int> { 0, 1, 2, 3, 4, 5 }); ImgCombo.SelectionChanged += (s, e) => { sourceImg.OnNext(new List <Avalonia.Controls.Image> { Images[ImgCombo.SelectedIndex] }); }; NumCombo.SelectionChanged += (s, e) => { UpdateResults(); }; ClassButton.Click += (s, e) => { StopButton.IsEnabled = true; ProccText.IsVisible = true; NumCombo.IsEnabled = true; if (!isProcessing) { BeginSession(); } }; StopButton.Click += (s, e) => { if (myRec != null) { myRec.Stop(); } isProcessing = false; StopButton.IsEnabled = false; ProccText.IsVisible = false; }; DBButton.Click += (s, e) => { int count; using (var db = new ImagesContext()) { var imgs = db.Images.ToList(); foreach (var im in imgs) { db.Images.Remove(im); } db.SaveChanges(); count = db.Images.ToList().Count; } DBAmountText.Text = "Pictures in database amount: " + count; }; this.FindControl <Button>("ChooseDir").Click += async(s, e) => { var dialog = new OpenFolderDialog(); var res = await dialog.ShowAsync(GetWindow()); if (res != null) { imgDir = res.ToString(); UpdateImages(imgDir); ClassButton.IsEnabled = true; } }; }
public UserImageController(ImagesContext context) { _userImageContext = context ?? throw new ArgumentNullException(nameof(context)); ((DbContext)context).ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; }
// Constructor expects an instance of the context public ImagesService(ImagesContext context) { this.context = context; }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { var config = new ServerConfig(); Configuration.Bind(config); var newsContext = new NewsContext(config.MongoDB); var newsRepo = new NewsRepository(newsContext); var categoriesContext = new CategoriesContext(config.MongoDB); var categoriesRepo = new CategoriesRepository(categoriesContext); var imagesContext = new ImagesContext(config.MongoDB); var imagesRepo = new ImagesRepository(imagesContext); services.AddSingleton <INewsRepository>(newsRepo); services.AddSingleton <ICategoriesRepository>(categoriesRepo); services.AddSingleton <IImagesRepository>(imagesRepo); services.AddCors(options => { options.AddPolicy(SpecificOrigins, builder => { builder.WithOrigins("http://localhost", "http://localhost:3000").AllowAnyHeader().AllowAnyOrigin().AllowAnyMethod(); }); }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddElasticsearch(Configuration); services.AddMassTransit(x => { x.AddConsumer <MongoConsumer>(); x.AddConsumer <ElasticSearchConsumer>(); x.AddBus(provider => Bus.Factory.CreateUsingRabbitMq(cfg => { var host = cfg.Host(new Uri(RabbitMQConfig.RabbitMQUri), hst => { hst.Username(RabbitMQConfig.RabbitMQUserName); hst.Password(RabbitMQConfig.RabbitMQPassword); }); cfg.ReceiveEndpoint(host, "demiroren.news", ep => { ep.ConfigureConsumer <MongoConsumer>(provider); ep.ConfigureConsumer <ElasticSearchConsumer>(provider); }); })); }); services.AddSingleton <IHostedService, MassTransitConsoleHostedService>(); // swagger services.AddSwaggerGen(n => { n.SwaggerDoc("v1", new Info { Title = "News API", Version = "v1", Description = "News API using MongoDB & Elastic Search & RabbitMQ", }); }); }
public AlbumsService(ImagesContext context) { db = context; }