public async Task <OperationReturnModel <CustomInventoryImportModel> > CustomInventory()
        {
            OperationReturnModel <CustomInventoryImportModel> ret = new OperationReturnModel <CustomInventoryImportModel>();

            try
            {
                if (!Request.Content.IsMimeMultipartContent())
                {
                    throw new InvalidOperationException();
                }

                var provider = new MultipartMemoryStreamProvider();
                await Request.Content.ReadAsMultipartAsync(provider);

                CustomInventoryImportFileModel fileModel = new CustomInventoryImportFileModel();

                foreach (var content in provider.Contents)
                {
                    var file      = content;
                    var paramName = file.Headers.ContentDisposition.Name.Trim('\"');
                    var buffer    = await file.ReadAsByteArrayAsync();

                    var stream = new MemoryStream(buffer);

                    using (var s = new StreamReader(stream))
                    {
                        switch (paramName)
                        {
                        case "file":
                            stream.CopyTo(fileModel.Stream);
                            fileModel.FileName = file.Headers.ContentDisposition.FileName.Trim('\"');
                            stream.Seek(0, SeekOrigin.Begin);
                            fileModel.Contents = s.ReadToEnd();
                            break;

                        case "options":
                            // Figure out what to do here
                            fileModel = Newtonsoft.Json.JsonConvert.
                                        DeserializeObject <CustomInventoryImportFileModel>(s.ReadToEnd());
                            break;
                        }
                    }
                }

                //if (string.IsNullOrEmpty(fileModel.Contents))
                //    return new ListImportModel() { Success = false, ErrorMessage = "Invalid request" };

                ret.SuccessResponse = importLogic.ImportCustomInventory
                                          (this.AuthenticatedUser, this.SelectedUserContext, fileModel);
                ret.IsSuccess = true;
            }
            catch (Exception ex)
            {
                ret.IsSuccess    = false;
                ret.ErrorMessage = ex.Message;
                _log.WriteErrorLog("Import Custom Inventory", ex);
            }
            return(ret);
        }
        public CustomInventoryImportModel ImportCustomInventory
            (UserProfile user, UserSelectedContext catalogInfo, CustomInventoryImportFileModel file)
        {
            try {
                CustomInventoryImportModel importReturn = new CustomInventoryImportModel();

                List <CustomInventoryItem> items = parseListDelimited(file, CSV_DELIMITER, user, catalogInfo);

                _customInventoryRepo.SaveRange(items);
                importReturn.Success = true;

                return(importReturn);
            } catch (Exception ex) {
                eventLogRepository.WriteErrorLog
                    (string.Format("Custom Inventory Import Error for Customer {0}", catalogInfo.CustomerId), ex);
                SendErrorEmail(file, ex);

                return(new CustomInventoryImportModel {
                    Success = false,
                    ErrorMessage = "An error has occurred while processing the import file"
                });
            }
        }
        private void SendErrorEmail(CustomInventoryImportFileModel file, Exception ex)
        {
            try {
                string errorMessage = string.Format
                                          ("File Import error.\n\nImport Options:\nSelected Format: {0}\nSkip First Line: {1}\nFile Name:{2}",
                                          file.FileFormat,
                                          file.IgnoreFirstLine,
                                          file.FileName);

                ContentType ct     = null;
                Attachment  attach = null;

                switch (file.FileFormat)
                {
                case FileFormat.Excel:
                    file.Stream.Seek(0, SeekOrigin.Begin);
                    ct     = new ContentType("application/msexcel");
                    attach = new Attachment(file.Stream, ct);
                    attach.ContentDisposition.FileName = file.FileName;
                    break;

                default:
                    ct = new ContentType(MediaTypeNames.Text.Plain);
                    byte[]       stringBytes = Encoding.UTF8.GetBytes(file.Contents);
                    MemoryStream memStream   = new MemoryStream();
                    memStream.Write(stringBytes, 0, stringBytes.Length);
                    memStream.Seek(0, SeekOrigin.Begin);
                    attach = new Attachment(memStream, ct);
                    attach.ContentDisposition.FileName = file.FileName;
                    break;
                }

                ExceptionEmail.Send(ex, errorMessage, "File Import Error", attach);
            } catch (Exception emailEx) {
                eventLogRepository.WriteErrorLog("Error sending Import failure email", emailEx);
            }
        }
        private List <CustomInventoryItem> parseListDelimited
            (CustomInventoryImportFileModel file, char delimiter, UserProfile user, UserSelectedContext catalogInfo)
        {
            List <CustomInventoryItem> returnValue = new List <CustomInventoryItem>();

            string[] rows = file.Contents.Split(new[] {
                Environment.NewLine,
                "\n"
            }, StringSplitOptions.None);

            int itemNumberColumn   = 0;
            int nameColumn         = -1;
            int brandColumn        = -1;
            int supplierColumn     = -1;
            int packColumn         = -1;
            int sizeColumn         = -1;
            int eachColumn         = -1;
            int casePriceColumn    = -1;
            int packagePriceColumn = -1;
            int labelColumn        = -1;

            List <string> header = rows.Take(1)
                                   .Select(i => i.Split(delimiter)
                                           .ToList())
                                   .FirstOrDefault();

            if (header != null)
            {
                int colCount = 0;
                foreach (string col in header)
                {
                    string replaced = col.Replace("\"", string.Empty);
                    if (replaced.Equals("itemid", StringComparison.CurrentCultureIgnoreCase))
                    {
                        itemNumberColumn = colCount;
                    }
                    else if (replaced.Equals("name", StringComparison.CurrentCultureIgnoreCase))
                    {
                        nameColumn = colCount;
                    }
                    else if (replaced.Equals("brand", StringComparison.CurrentCultureIgnoreCase))
                    {
                        brandColumn = colCount;
                    }
                    else if (replaced.Equals("supplier", StringComparison.CurrentCultureIgnoreCase))
                    {
                        supplierColumn = colCount;
                    }
                    else if (replaced.Equals("pack", StringComparison.CurrentCultureIgnoreCase))
                    {
                        packColumn = colCount;
                    }
                    else if (replaced.Equals("size", StringComparison.CurrentCultureIgnoreCase))
                    {
                        sizeColumn = colCount;
                    }
                    else if (replaced.Equals("each(t or f)", StringComparison.CurrentCultureIgnoreCase))
                    {
                        eachColumn = colCount;
                    }
                    else if (replaced.Equals("caseprice", StringComparison.CurrentCultureIgnoreCase))
                    {
                        casePriceColumn = colCount;
                    }
                    else if (replaced.Equals("packageprice", StringComparison.CurrentCultureIgnoreCase))
                    {
                        packagePriceColumn = colCount;
                    }
                    else if (replaced.Equals("label", StringComparison.CurrentCultureIgnoreCase))
                    {
                        labelColumn = colCount;
                    }
                    colCount++;
                }
            }
            else
            {
                throw new ApplicationException("Problem with header row. Template should be used.");
            }

            IEnumerable <string> data = rows.Skip(1);

            if (data == null)
            {
                throw new ApplicationException("Need to include custom inventory items to add.");
            }
            try {
                returnValue = data
                              .Where(line => !string.IsNullOrWhiteSpace(line))
                              .Select(i => i.Split(delimiter))
                              .Select(l => new CustomInventoryItem {
                    CustomerNumber = catalogInfo.CustomerId,
                    BranchId       = catalogInfo.BranchId,
                    ItemNumber     = l[itemNumberColumn].Replace("\"", string.Empty),
                    Name           = l[nameColumn].Replace("\"", string.Empty),
                    Brand          = l[brandColumn].Replace("\"", string.Empty),
                    Label          = l[labelColumn].Replace("\"", string.Empty),
                    Supplier       = l[supplierColumn].Replace("\"", string.Empty),
                    Pack           = l[packColumn].Replace("\"", string.Empty),
                    Size           = l[sizeColumn].Replace("\"", string.Empty),
                    Each           = l[eachColumn].Replace("\"", string.Empty)
                                     .Equals
                                         ("t", StringComparison.CurrentCultureIgnoreCase) ? true : false,
                    CasePrice = l[casePriceColumn].Replace("\"", string.Empty)
                                .Length > 0 ?
                                decimal.Parse(l[casePriceColumn].Replace("\"", string.Empty)) : 0,
                    PackagePrice = l[packagePriceColumn].Replace("\"", string.Empty)
                                   .Length > 0 ?
                                   decimal.Parse(l[packagePriceColumn].Replace("\"", string.Empty)) : 0
                })
                              .Where(x => !string.IsNullOrEmpty(x.ItemNumber))
                              .ToList();
            } catch (Exception ex) {
                throw new ApplicationException(ex.InnerException.Message);
            }

            return(returnValue);
        }