Esempio n. 1
0
        /// <summary>
        /// Deletes the long-standing analyses from the database.
        /// </summary>
        /// <param name="serviceProvider">The application service provider.</param>
        /// <param name="token">The cancellation token for the task.</param>
        public async Task DeleteAnalysesAsync(IServiceProvider serviceProvider, CancellationToken token)
        {
            // Define the limit date.
            var limitDate = DateTime.Today - TimeSpan.FromDays(ApplicationDbContext.DaysBeforeDelete);
            // Define the IDs of the items to get.
            var itemIds = new List <string>();

            // Use a new scope.
            using (var scope = serviceProvider.CreateScope())
            {
                // Use a new context instance.
                using var context = scope.ServiceProvider.GetRequiredService <ApplicationDbContext>();
                // Get the IDs of the items to delete.
                itemIds = context.Analyses
                          .Where(item => item.Status == AnalysisStatus.Stopped || item.Status == AnalysisStatus.Completed || item.Status == AnalysisStatus.Error)
                          .Where(item => item.DateTimeEnded < limitDate)
                          .Select(item => item.Id)
                          .ToList();
            }
            // Define a new task.
            var task = new AnalysesTask
            {
                Items = itemIds
                        .Select(item => new AnalysisInputModel
                {
                    Id = item
                })
            };
            // Run the task.
            await task.DeleteAsync(serviceProvider, token);
        }
Esempio n. 2
0
        public async Task <IActionResult> OnPostAsync()
        {
            // Get the current user.
            var user = await _userManager.GetUserAsync(User);

            // Check if there isn't any ID provided.
            if (string.IsNullOrEmpty(Input.Id))
            {
                // Display a message.
                TempData["StatusMessage"] = "Error: No ID has been provided.";
                // Redirect to the index page.
                return(RedirectToPage("/Content/DatabaseTypes/Generic/Created/Analyses/Index"));
            }
            // Define the query.
            var query = _context.Analyses
                        .Where(item => item.AnalysisDatabases.Any(item1 => item1.Database.DatabaseType.Name == "Generic"))
                        .Where(item => item.IsPublic || item.AnalysisUsers.Any(item1 => item1.User == user))
                        .Where(item => item.Id == Input.Id);

            // Define the view.
            View = new ViewModel
            {
                IsUserAuthenticated = user != null,
                Analysis            = query
                                      .FirstOrDefault()
            };
            // Check if the item hasn't been found.
            if (View.Analysis == null)
            {
                // Display a message.
                TempData["StatusMessage"] = "Error: No analysis has been found with the provided ID, or you don't have access to it.";
                // Redirect to the index page.
                return(RedirectToPage("/Content/DatabaseTypes/Generic/Created/Analyses/Index"));
            }
            // Check if the reCaptcha is valid.
            if (!await _reCaptchaChecker.IsValid(Input.ReCaptchaToken))
            {
                // Add an error to the model.
                ModelState.AddModelError(string.Empty, "The reCaptcha verification failed.");
                // Return the page.
                return(Page());
            }
            // Check if the provided model isn't valid.
            if (!ModelState.IsValid)
            {
                // Add an error to the model.
                ModelState.AddModelError(string.Empty, "An error has been encountered. Please check again the input fields.");
                // Redisplay the page.
                return(Page());
            }
            // Check if the public availability isn't valid.
            if (!View.IsUserAuthenticated && !Input.IsPublic)
            {
                // Add an error to the model.
                ModelState.AddModelError(string.Empty, "You are not logged in, so the analysis must be set as public.");
                // Redisplay the page.
                return(Page());
            }
            // Define a new task.
            var task = new AnalysesTask
            {
                Items = new List <AnalysisInputModel>
                {
                    new AnalysisInputModel
                    {
                        Id          = Input.Id,
                        Name        = Input.Name,
                        Description = Input.Description,
                        IsPublic    = Input.IsPublic
                    }
                }
            };

            // Try to run the task.
            try
            {
                // Run the task.
                await task.EditAsync(_serviceProvider, CancellationToken.None);
            }
            catch (Exception exception)
            {
                // Add an error to the model.
                ModelState.AddModelError(string.Empty, exception.Message);
                // Redisplay the page.
                return(Page());
            }
            // Display a message.
            TempData["StatusMessage"] = "Success: 1 analysis updated successfully.";
            // Redirect to the index page.
            return(RedirectToPage("/Content/DatabaseTypes/Generic/Created/Analyses/Details/Index", new { id = View.Analysis.Id }));
        }
Esempio n. 3
0
        public async Task <IActionResult> OnPostAsync()
        {
            // Get the current user.
            var user = await _userManager.GetUserAsync(User);

            // Check if there isn't any algorithm provided.
            if (Input.Algorithm == null)
            {
                // Display a message.
                TempData["StatusMessage"] = "Error: An algorithm is required for creating an analysis.";
                // Redirect to the index page.
                return(RedirectToPage("/Content/DatabaseTypes/Generic/Created/Analyses/Index"));
            }
            // Try to get the algorithm.
            try
            {
                // Get the algorithm.
                _ = EnumerationExtensions.GetEnumerationValue <AnalysisAlgorithm>(Input.Algorithm);
            }
            catch (Exception)
            {
                // Display a message.
                TempData["StatusMessage"] = "Error: The provided algorithm is not valid.";
                // Redirect to the index page.
                return(RedirectToPage("/Content/DatabaseTypes/Generic/Created/Analyses/Index"));
            }
            // Define the view.
            View = new ViewModel
            {
                IsUserAuthenticated = user != null,
                Algorithm           = Input.Algorithm,
                SampleItems         = _context.Samples
                                      .Where(item => item.SampleDatabases.Any(item1 => item1.Database.DatabaseType.Name == "Generic"))
                                      .Select(item => new SampleItemModel
                {
                    Id          = item.Id,
                    Name        = item.Name,
                    Description = item.Description
                })
            };
            // Check if the reCaptcha is valid.
            if (!await _reCaptchaChecker.IsValid(Input.ReCaptchaToken))
            {
                // Add an error to the model.
                ModelState.AddModelError(string.Empty, "The reCaptcha verification failed.");
                // Return the page.
                return(Page());
            }
            // Check if the provided model isn't valid.
            if (!ModelState.IsValid)
            {
                // Add an error to the model.
                ModelState.AddModelError(string.Empty, "An error has been encountered. Please check again the input fields.");
                // Redisplay the page.
                return(Page());
            }
            // Check if the public availability isn't valid.
            if (!View.IsUserAuthenticated && !Input.IsPublic)
            {
                // Add an error to the model.
                ModelState.AddModelError(string.Empty, "You are not logged in, so the analysis must be set as public.");
                // Redisplay the page.
                return(Page());
            }
            // Try to deserialize the network data.
            if (!Input.NetworkData.TryDeserializeJsonObject <IEnumerable <string> >(out var networkIds) || networkIds == null)
            {
                // Add an error to the model.
                ModelState.AddModelError(string.Empty, "The provided network data could not be deserialized.");
                // Redisplay the page.
                return(Page());
            }
            // Check if there weren't any network IDs provided.
            if (!networkIds.Any())
            {
                // Add an error to the model.
                ModelState.AddModelError(string.Empty, "At least one network ID must be specified.");
                // Redisplay the page.
                return(Page());
            }
            // Try to get the networks with the provided IDs.
            var networks = _context.Networks
                           .Where(item => item.IsPublic || item.NetworkUsers.Any(item1 => item1.User == user))
                           .Where(item => item.NetworkDatabases.Any(item1 => item1.Database.DatabaseType.Name == "Generic"))
                           .Where(item => item.NetworkDatabases.Any(item1 => item1.Database.IsPublic || item1.Database.DatabaseUsers.Any(item2 => item2.User == user)))
                           .Where(item => networkIds.Contains(item.Id));

            // Check if there weren't any networks found.
            if (!networks.Any())
            {
                // Add an error to the model.
                ModelState.AddModelError(string.Empty, "No networks could be found with the provided IDs.");
                // Redisplay the page.
                return(Page());
            }
            // Try to deserialize the seed data.
            if (!Input.SourceNodeData.TryDeserializeJsonObject <IEnumerable <string> >(out var sourceItems) || sourceItems == null)
            {
                // Add an error to the model.
                ModelState.AddModelError(string.Empty, "The provided source data could not be deserialized.");
                // Redisplay the page.
                return(Page());
            }
            // Try to deserialize the target data.
            if (!Input.TargetNodeData.TryDeserializeJsonObject <IEnumerable <string> >(out var targetItems) || targetItems == null)
            {
                // Add an error to the model.
                ModelState.AddModelError(string.Empty, "The provided target data could not be deserialized.");
                // Redisplay the page.
                return(Page());
            }
            // Check if there wasn't any target data found.
            if (!targetItems.Any())
            {
                // Add an error to the model.
                ModelState.AddModelError(string.Empty, "No target data has been provided.");
                // Redisplay the page.
                return(Page());
            }
            // Define the generation data.
            var data = JsonSerializer.Serialize(sourceItems
                                                .Select(item => new AnalysisNodeInputModel
            {
                Node = new NodeInputModel
                {
                    Id = item
                },
                Type = "Source"
            })
                                                .Concat(targetItems
                                                        .Select(item => new AnalysisNodeInputModel
            {
                Node = new NodeInputModel
                {
                    Id = item
                },
                Type = "Target"
            })));
            // Define a new task.
            var task = new AnalysesTask
            {
                Scheme    = HttpContext.Request.Scheme,
                HostValue = HttpContext.Request.Host.Value,
                Items     = new List <AnalysisInputModel>
                {
                    new AnalysisInputModel
                    {
                        Name              = Input.Name,
                        Description       = Input.Description,
                        IsPublic          = Input.IsPublic,
                        Data              = data,
                        MaximumIterations = Input.MaximumIterations,
                        MaximumIterationsWithoutImprovement = Input.MaximumIterationsWithoutImprovement,
                        Algorithm  = Input.Algorithm,
                        Parameters = Input.Algorithm == AnalysisAlgorithm.Greedy.ToString() ? JsonSerializer.Serialize(Input.GreedyAlgorithmParameters) :
                                     Input.Algorithm == AnalysisAlgorithm.Genetic.ToString() ? JsonSerializer.Serialize(Input.GeneticAlgorithmParameters) :
                                     null,
                        AnalysisUsers = View.IsUserAuthenticated ?
                                        new List <AnalysisUserInputModel>
                        {
                            new AnalysisUserInputModel
                            {
                                User = new UserInputModel
                                {
                                    Id = user.Id
                                }
                            }
                        } :
                        new List <AnalysisUserInputModel>(),
                        AnalysisNetworks = networks
                                           .Select(item => item.Id)
                                           .Select(item => new AnalysisNetworkInputModel
                        {
                            Network = new NetworkInputModel
                            {
                                Id = item
                            }
                        })
                    }
                }
            };
            // Define the IDs of the created items.
            var ids = Enumerable.Empty <string>();

            // Try to run the task.
            try
            {
                // Run the task.
                ids = await task.CreateAsync(_serviceProvider, CancellationToken.None);
            }
            catch (Exception exception)
            {
                // Add an error to the model.
                ModelState.AddModelError(string.Empty, exception.Message);
                // Redisplay the page.
                return(Page());
            }
            // Check if there wasn't any ID returned.
            if (ids != null && ids.Any())
            {
                // Display a message.
                TempData["StatusMessage"] = $"Success: 1 generic analysis with the algorithm \"{Input.Algorithm}\" defined successfully with the ID \"{ids.First()}\" and scheduled for generation.";
                // Redirect to the index page.
                return(RedirectToPage("/Content/DatabaseTypes/Generic/Created/Analyses/Details/Index", new { id = ids.First() }));
            }
            // Display a message.
            TempData["StatusMessage"] = $"Success: 1 generic analysis with the algorithm \"{Input.Algorithm}\" defined successfully and scheduled for generation.";
            // Redirect to the index page.
            return(RedirectToPage("/Content/DatabaseTypes/Generic/Created/Analyses/Index"));
        }