0

when I try to upload multiple entries to my CSV reader I get this error:

Exception Details: System.InvalidOperationException: Sequence contains no elements

on this line:

if (item.contactname != null) 
{ 
     ViewBag.name = item.contactname.First().ToString().ToUpper() + 
                    item.contactname.Substring(1);  
}

oddly when I only put one or two entries it seems to work its just a lot of entries, even manually one by one? what could be breaking this? I've checked the CSV through and the formatting seems fine.

This is the CSV

domain,contact,contactname,price,type,MJTopicsID,,,,,,,,,,,,,,,,,,
goodmenproject.com,brillianttransformations.md@gmail.com,Melissa Drake,60,0,15,,,,,,,,,,,,,,,,,,
oneworld365.org,admin@oneworld365.org,Paul,60,0,26,,,,,,,,,,,,,,,,,,
thefutureofthings.com/,kris@thefutureofthings.com,Kristijan,70,0,23,,,,,,,,,,,,,,,,,,
broowaha.com,editor@broowaha.com,,60,0,3,,,,,,,,,,,,,,,,,,
easytravelgroup.co.uk,emily@sussexseo.net,Emily,30,0,26,,,,,,,,,,,,,,,,,,
bbmlive.com,info@bbmlive.com,,30,0,8,,,,,,,,,,,,,,,,,,
fluxmagazine.com,editorial@fluxmagazine.com,Lee,30,0,8,,,,,,,,,,,,,,,,,,
irishdogs.ie,Peter.Banks@irishdogs.ie,Peter Banks,15,0,5,,,,,,,,,,,,,,,,,,
roberthorne.co.uk,emily@sussexseo.net,Emily,30,0,12,,,,,,,,,,,,,,,,,,
aspiringgentleman.com,info@aspiringgentleman.com,Jack,30,0,8,,,,,,,,,,,,,,,,,,
puretravel.com,julie@puretravel.com,Julie,22,0,26,,,,,,,,,,,,,,,,,,
domstechblog.com,dom@domstechblog.com,Dom,45,0,23,,,,,,,,,,,,,,,,,,
nerdly.co.uk,nerdly.co.uk@gmail.com,Phil,52,0,23,,,,,,,,,,,,,,,,,,
jcount.com,info@buzz2fone.com,Jony,35,0,3,,,,,,,,,,,,,,,,,,
marquetteturner.com/,simon@marquetteturner.com.au,Simon,20,0,12,,,,,,,,,,,,,,,,,,

This is my reader:

    [HttpPost]
    [ActionName("CreateBulk")]
    public ActionResult CreateBulkUpload(Identifier model)
    {
        var file = Request.Files["attachmentcsv"];
        using (var csv = new CsvReader(new StreamReader(file.InputStream), true))
        {
            csv.Configuration.HeaderValidated = null;
            csv.Configuration.MissingFieldFound = null;
            var records = csv.GetRecords<Identifier>().ToList();
            foreach (var item in records)
            {
                var strip = item.domain.Replace("https://www.", "").Replace("http://www.", "")
                   .Replace("https://", "").Replace("http://", "").Replace("www.", "");

                string[] URLtests =
                   {"http://www." + strip, "https://www." + strip, "https://" + strip, "http://" + strip};

                string[] Metric = MajesticFunctions.MajesticChecker(URLtests);

                if (!(from c in db.Identifiers
                      select c.domain).Contains(Metric[0]))
                {
                    if (item.contactname != null) { ViewBag.name = item.contactname.First().ToString().ToUpper() + item.contactname.Substring(1);  }
                    var userId = User.Identity.GetUserId();
                    var UserTableID = db.UserTables.Where(c => c.ApplicationUserId == userId).First().ID;

                    var identifier = new Identifier
                    {
                        domain = Metric[0],
                        contact = item.contact,
                        contactname = ViewBag.name,
                        price = item.price,
                        type = item.type,
                        TrustFlow = Int32.Parse(Metric[1]),
                        CitationFlow = Int32.Parse(Metric[2]),
                        RI = Int32.Parse(Metric[3]),
                        MJTopicsID = item.MJTopicsID,
                        UserTableID = UserTableID
                    };
                    ViewBag.identifier = identifier;
                    db.Identifiers.Add(identifier);
                    db.SaveChanges();
                }
                else { continue; }
            }
            return RedirectToAction("Index");
        }
    }

Stack Trace:

[InvalidOperationException: Sequence contains no elements]
System.Linq.Enumerable.First(IEnumerable`1 source) +301
Linkofy.Controllers.IdentifiersController.CreateBulkUpload(Identifier model) in C:\Users\liam\Documents\Visual Studio 2017\Linkofy4\Linkofy\Controllers\IdentifiersController.cs:229
lambda_method(Closure , ControllerBase , Object[] ) +104
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +157
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
 System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +22
 System.Web.Mvc.Async.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult) +29
 System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32
       System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +50
   System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +228
   System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +10
  System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
 System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34
 System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +26
 System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +100
 System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
 System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
 System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +13
 System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
 System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
 System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +36
 System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +12
 System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +22
 System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
 System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
 System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
 System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +21
 System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
 System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
 System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9748493
 System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +48
 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +159
Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
Lucie
  • 131
  • 1
  • 9
  • Is `item.contactname` empty in that case? – rene Feb 13 '18 at 12:47
  • That's a lot of code. Please try to reduce this to a [mcve], and post the full stack trace rather than just the message. (I strongly suspect, as rene does, that `item.contactname` is empty, so `First()` is throwing the exception. But you should do the diagnostic work to find out *why* it's empty, which will first involve reducing this to a much smaller piece of code and data.) – Jon Skeet Feb 13 '18 at 12:47
  • @rene I suspected this but I thought missingfieldfound=null would bypass this? – Lucie Feb 13 '18 at 12:50
  • @JonSkeet sorry I shall remove the model, I didn't know if it was necessary – Lucie Feb 13 '18 at 12:50
  • If you attach the debugger it is easy enough to diagnose if what you think bypasses it, really works that way. It is not null for sure because that woud have triggered a null reference exception. Callig First() on an empty string triggers your error: https://ideone.com/aM5x8A – rene Feb 13 '18 at 12:57
  • It's not a matter of removing the model - it's a matter of simplifying both the code and the data until you can present *complete* but *simple* code that reproduces the problem. As just one example, is `CitationFlow` necessary to reproduce the problem? I doubt it. So remove that from both the model and your data. Repeat until you have the *absolute bare minimum* required to reproduce the problem, and then provide that in a *complete* example we can run for ourselves. Usually, in the course of finding that minimal example, you'll find the answer for yourself. – Jon Skeet Feb 13 '18 at 12:59
  • @rene you're right! I moved it out of the object declaration and put it into a string and tried declaring it and got the error on that line, I've posted the line above, though its still giving the same error, shall I say if string is longer than 2 for example or is there a better way? – Lucie Feb 13 '18 at 13:07
  • No, just implement the method explained [here](https://stackoverflow.com/a/4405876/578411) and feed it `item.Contactname`. Instead of throwing an exception, return a value, for example an empty string – rene Feb 13 '18 at 13:09
  • @mjwills yeah that was my next port of call :) worked perfectly thanks ! – Lucie Feb 13 '18 at 13:24
  • @rene ended up going with this if (item.contName != null && item.contName.Length > 0) { seemed to work perfectly, saves creating another method :) thanks for identifying the issue though, I never realised that calling first if the string was empty would return an exception! – Lucie Feb 13 '18 at 13:30

1 Answers1

0

This worked in the end bypassed the calling of first when the variable was empty:

(item.contName != null && item.contName.Length > 0) 
Lucie
  • 131
  • 1
  • 9