public IActionResult CreateWithFileWindows(NewConfigurationFileViewModel model)
        {
            // Check file type
            string fileExtension = Path.GetExtension(model.ProductFile.FileName);

            if (fileExtension != ".csv")
            {
                ViewBag.CsvError = "Only .CSV filetype accepted, please try again.";
                return(View(model));
            }

            List <WindowsProduct> productList = new List <WindowsProduct>();

            using (var reader = new StreamReader(model.ProductFile.OpenReadStream()))
            {
                // Check the correct data is present
                var headerLine = reader.ReadLine();
                reader.ReadLine();
                string nextProductLine;
                if (headerLine == "#TYPE Selected.System.Management.Automation.PSCustomObject")
                {
                    // While there is another line
                    while ((nextProductLine = reader.ReadLine()) != null)
                    {
                        // Cleanse and split the line
                        nextProductLine = nextProductLine.Replace("\\", "");
                        nextProductLine = nextProductLine.Replace("\"", "");
                        nextProductLine = nextProductLine.Replace("(", "");
                        nextProductLine = nextProductLine.Replace(")", "");
                        nextProductLine = nextProductLine.Replace("-bit", "");
                        nextProductLine = nextProductLine.ToLower();
                        var values = nextProductLine.Split(',');

                        // Create newWindowsProduct object only if the DisplayName is not empty
                        if (values[0] != "")
                        {
                            var newWindowsProduct = new WindowsProduct()
                            {
                                DisplayName    = values[0],
                                DisplayVersion = values[1]
                            };

                            productList.Add(newWindowsProduct);
                        }
                    }
                }
                else
                {
                    //TODO return error because it's not the right content
                }
            }

            // Attempt matching
            var cveList = _context.Products.ToList();

            // foreach import product
            foreach (var currImportProduct in productList)
            {
                var matches = new List <MatchedProduct>();
                // Split into words
                var displayNameSplit = currImportProduct.DisplayName.Split(" ");
                var matchedList      = new List <MatchedProduct>();

                foreach (var currDatabaseProduct in cveList)
                {
                    var wordMatchCount = 0;
                    foreach (var currWord in displayNameSplit)
                    {
                        if (currDatabaseProduct.Concatenated.Contains(currWord))
                        {
                            wordMatchCount++;
                        }
                    }

                    var newMatchedProduct = new MatchedProduct()
                    {
                        ImportProduct   = currImportProduct.DisplayName,
                        DatabaseProduct = currDatabaseProduct.Concatenated,
                        Score           = wordMatchCount
                    };

                    matchedList.Add(newMatchedProduct);

                    matchedList = matchedList.OrderBy(ml => ml.Score).ToList();
                }
                System.Diagnostics.Debug.WriteLine("STOP");
            }

            return(null);
        }
        public IActionResult CreateWithFile(NewConfigurationFileViewModel model)
        {
            // Check file type
            string fileExtension = Path.GetExtension(model.ProductFile.FileName);

            if (fileExtension != ".csv")
            {
                ViewBag.CsvError = "Only .CSV filetype accepted, please try again.";
                return(View(model));
            }

            // Determine template being used and get all the products only if the format is correct
            var productList = new List <string>();

            using (var reader = new StreamReader(model.ProductFile.OpenReadStream()))
            {
                var    headerLine = reader.ReadLine();
                string nextProductLine;
                if (headerLine == "Concatenated CPE Names Below")
                {
                    while ((nextProductLine = reader.ReadLine()) != null)
                    {
                        productList.Add(nextProductLine);
                    }
                }
                else if (headerLine == "Type,Vendor,Product Name,Version,Update,Edition,Language")
                {
                    while ((nextProductLine = reader.ReadLine()) != null)
                    {
                        List <string> productPartList = nextProductLine.Split(',').ToList();
                        StringBuilder builder         = new StringBuilder();
                        builder.Append("cpe:2.3:");
                        foreach (var productPart in productPartList)
                        {
                            if (String.IsNullOrEmpty(productPart) || productPart == "*")
                            {
                                builder.Append("*:");
                            }
                            else
                            {
                                builder.Append(productPart + ":");
                            }
                        }
                        builder.Append("*:*:*:*");
                        productList.Add(builder.ToString());
                    }
                }
                else
                {
                    ViewBag.CsvError = "Incorrect Template format, please download the correct template and try again.";
                    return(View(model));
                }
            }

            // Create a new configuration based off user input
            Configuration newConfiguration = new Configuration
            {
                AspNetUserID          = _userManager.GetUserId(User),
                ConfigurationName     = model.ConfigurationName,
                Notes                 = model.Notes,
                DateAdded             = DateTime.Now,
                UserCveConfigurations = new List <UserCveConfiguration>()
            };

            if (newConfiguration == null)
            {
                Exception e = new ArgumentNullException();
                TempData["Param"] = "userCveConfigurationToUpdate save changes";
                TempData["Error"] = e.Message;
                throw e;
            }

            List <string> successList = new List <string>();
            List <string> failedList  = new List <string>();

            // Foreach product add it to a new ProductConfiguration and add that to the newConfiguration
            foreach (var productItem in productList)
            {
                Product existingProduct = _context.Products
                                          .Where(p => p.Concatenated == productItem)
                                          .Include(p => p.CveConfigurations)
                                          .FirstOrDefault();

                // If the product exists
                if (existingProduct != null)
                {
                    // Add CveConfiguration to UserCveConfiguration for customisable notes etc.
                    Status unresolvedStatus = _context.Status
                                              .Where(s => s.StatusName == "Unresolved")
                                              .FirstOrDefault();
                    foreach (var CveConfigurationItem in existingProduct.CveConfigurations)
                    {
                        UserCveConfiguration newUserCveConfiguration = new UserCveConfiguration
                        {
                            ProductID = existingProduct.ProductID,
                            CveID     = CveConfigurationItem.CveID,
                            StatusID  = unresolvedStatus.StatusID,
                            Notes     = "No user defined notes.",
                            DateAdded = DateTime.Now,
                            New       = 'N'.ToString()
                        };

                        newConfiguration.UserCveConfigurations.Add(newUserCveConfiguration);
                    }
                    successList.Add(productItem);
                }
                else
                {
                    failedList.Add(productItem);
                }
            }

            // Save the new configuration if there any successful products
            if (successList.Any())
            {
                try
                {
                    _context.Configurations.Add(newConfiguration);
                    _context.SaveChanges();
                }
                catch (Exception e)
                {
                    TempData["Param"] = "newConfiguration save changes";
                    TempData["Error"] = e.Message;
                    throw e;
                }
            }

            // Determine success and add result to ViewBag
            if (productList == null)
            {
                ViewBag.CsvError = "The CSV file does not contain any products or is invalid, please check and upload again.";
                return(View(model));
            }

            if (!failedList.Any())
            {
                ViewBag.UploadStatus = "success";
            }
            else if (failedList.Any() && successList.Any())
            {
                ViewBag.UploadStatus = "partial";
            }
            else if (!successList.Any())
            {
                ViewBag.UploadStatus = "failed";
            }

            ViewBag.SuccessList = successList;
            ViewBag.FailedList  = failedList;

            return(View(model));
        }