Import Products throws Unhandled Exception in Category Mappings

Posted: January 08, 2019 at 8:02 PM Quote #217808
Nop Version: 4.0

When importing products from XLSX, the ImportManger class (ImportProductsFromXlsx function), will generate an unhandled exception if the category hierarchy does not match, but the last child category name does match.

For example, if my excel file contains this category entry: "Body >> Bumper >> Bumper Grilles"
However, the correct value should be: "Body Parts >> Bumper >> Bumper Grilles"

The code at line 1343 will throw an unhandled exception: Sequence contains no matching element

This is the current code:
var importedCategories = categoryNames.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(x => allCategories.ContainsKey(x.Trim()) ? allCategories[x.Trim()].Id : allCategories.Values.First(c => c.Name == x.Trim()).Id).ToList();

This happens because:

Will return false, then execute this condition:
allCategories.Values.First(c => c.Name == x.Trim()).Id
Which will fail, since the string will not be found, and throw a "Sequence contains no matching element" error.

We need to gracefully handle this error and report what the error is to the end user, in this case the fully qualified category path was not found the it the list of all allCategories.
This post/answer is useful
This post/answer is not useful

Please login or register
to vote for this post.

(click on this box to dismiss)
Posted: January 10, 2019 at 7:42 PM Quote #217887
I made some changes to the code to give a more meaningful error message, and also provide which record in the file is causing the error.  Possibly this can get incorporated into the next version?

Revised code:
var categoryNames = tempProperty.StringValue.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

//category mappings
var categories = isNew || !allProductsCategoryIds.ContainsKey(product.Id) ? new int[0] : allProductsCategoryIds[product.Id];
var importedCategories = categoryNames.Select(x =>
        allCategories.ContainsKey(x.Trim()) ? allCategories[x.Trim()].Id :
            allCategories.Values.Any(c => c.Name == x.Trim()) ? allCategories.Values.First(c => c.Name == x.Trim()).Id :
                throw new ArgumentException($"Categories do not contain a match for '{x.Trim()}'")
This post/answer is useful
This post/answer is not useful

Please login or register
to vote for this post.

(click on this box to dismiss)
Premium support services
  • Dedicated premium support services provided by core developers are intended for persons who run mission critical websites, work on projects with tight deadlines, or want to get dedicated support.
Professional services
  • Want to open a new store? Want to take your store to the next level? Need a custom extension? We can customize nopCommerce to fit your store perfectly. Request a quote to get started.