Пример #1
0
        public List <JobRequest> GetCallList(string filepath)
        {
            List <JobRequest> jobList = new List <JobRequest>();

            try
            {
                XLWorkbook   workbook  = new XLWorkbook(filepath);
                IXLWorksheet worksheet = workbook.Worksheet(1);
                IXLRows      rows      = worksheet.RowsUsed();
                foreach (IXLRow r in rows)
                {
                    if (r.RowNumber() == 1)
                    {
                        continue;
                    }

                    JobRequest job = new JobRequest();
                    foreach (IXLCell cell in r.CellsUsed())
                    {
                        FillJobRequestInfo(cell, ref job);
                    }
                    jobList.Add(job);
                }
                if (jobList.Count <= 0)
                {
                    throw new Exception("JobRequestInfo List Count is 0");
                }
                workbook.Dispose();
                return(jobList);
            }
            catch (Exception)
            {
                throw;
            }
        }
Пример #2
0
        private int GetIndexEmptyRow(IXLWorksheet worksheet, IXLRows rowUsed, IXLColumns colUsed, int workingRow, int workingCol)
        {
            int countEmptyCell = 0;
            int countCell      = 0;

            foreach (var col in colUsed)
            {
                if (col.ColumnNumber() > 1 && col.ColumnNumber() > workingCol)
                {
                    if (common.GetValue(worksheet, workingRow, col.ColumnNumber()) == "")
                    {
                        countEmptyCell++;
                    }
                    else
                    {
                        return(-1);
                    }
                    countCell++;
                }
            }

            if (countEmptyCell == countCell)
            {
                return(workingRow);
            }

            return(-1);
        }
Пример #3
0
        private void FillCallInfoList(IXLRows rows, ref CallInfoList listInfo)
        {
            try
            {
                foreach (IXLRow r in rows)
                {
                    if (r.RowNumber() == 1)
                    {
                        continue;
                    }

                    CallInfoSymptom symptom = new CallInfoSymptom();
                    CallInfoTime    time    = new CallInfoTime();
                    foreach (IXLCell cell in r.CellsUsed())
                    {
                        MatchCallInfoListName(cell, ref listInfo, ref symptom, ref time);
                    }
                    listInfo.SymptomInfo.Add(symptom);
                    listInfo.TimeInfo.Add(time);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
Пример #4
0
        private async Task <List <int> > GetTeamRowsAsync(IXLWorksheet worksheet, string columnName, ExcelCell groupByNameCell)
        {
            List <int> teamRows = new List <int>();
            IXLRows    col      = await Task.Run(() => worksheet.RowsUsed());

            foreach (IXLRow row in col)
            {
                int columnNumber = XLHelper.GetColumnNumberFromLetter(groupByNameCell.Column);

                if (!int.TryParse(await Task.Run(() => Regex.Replace(row.Cell(columnNumber).Address.ToString(), "[^0-9.]", "")), out int currentRowAddress))
                {
                    throw new InvalidCastException("Unable to parse row int from cell address resturned from Excel");
                }


                if (row.Cell(columnNumber).Value.ToString().Trim() == columnName)
                {
                    if (_log.IsDebugEnabled)
                    {
                        _log.Debug($"ExcelReader.GetTeamRowsAsync - Adding { currentRowAddress } to the teamRows list");
                    }
                    teamRows.Add(currentRowAddress);
                }
            }
            return(teamRows);
        }
Пример #5
0
 /// <summary>
 /// <see cref="AdvCommandXLRows"/>のコンストラクタです。
 /// </summary>
 /// <param name="xlRows">基となる<see cref="IXLRows"/>です。</param>
 public AdvCommandXLRows(IXLRows xlRows)
 {
     this.advCommandXLRows = new List <AdvCommandXLRow>();
     foreach (IXLRow xlRow in xlRows)
     {
         this.advCommandXLRows.Add(new AdvCommandXLRow(xlRow));
     }
 }
Пример #6
0
        static void FoldRows(IXLRows rows)
        {
            rows.Style.Fill.BackgroundColor = XLColor.FromArgb(45, 45, 45);
            IXLRow last = null;

            rows.ForEach(x => last              = x);
            last.Style.Border.BottomBorder      = XLBorderStyleValues.Thin;
            last.Style.Border.BottomBorderColor = XLColor.DarkGray;
            rows.Group(1, true);
        }
        internal void ParseDataTypeRange()
        {
            IXLWorksheet dataTypeSheet = Workbook.Worksheets.Worksheet("DataTypes");
            IXLRows      rows          = dataTypeSheet.RowsUsed();
            bool         firstRow      = true;

            foreach (IXLRow row in rows)
            {
                if (firstRow)
                {
                    firstRow = false;
                    continue;
                }
                IXLCell typeNameCell  = row.Cell("A");
                IXLCell nameSpaceCell = row.Cell("B");
                IXLCell idCell        = row.Cell("C");
                string  key           = typeNameCell.GetString();
                if (string.IsNullOrWhiteSpace(key))
                {
                    Logger.Error($"Empty type name in row {row.RowNumber()}");
                    continue;
                }
                byte nsByte;
                try
                {
                    nsByte = nameSpaceCell.GetValue <byte>();
                }
                catch (FormatException exception)
                {
                    Logger.Error($"Unable to parse Namespace of DataType {key} | {nameSpaceCell.GetString()} | {idCell.GetString()}", exception);
                    continue;
                }
                byte idByte;
                try
                {
                    idByte = idCell.GetValue <byte>();
                }
                catch (FormatException exception)
                {
                    Logger.Error($"Unable to parse ID of DataType {key} | {nameSpaceCell.GetString()} | {idCell.GetString()}", exception);
                    continue;
                }
                NodeID dataTypeID = new NodeID
                {
                    Namespace = nsByte,
                    Value     = idByte
                };
                if (CommonConfig.KnownDataTypes.ContainsKey(key))
                {
                    Logger.Warn($"DataType with name '{key}' already exists. Value will be overwritten from row {row.RowNumber()}");
                }
                CommonConfig.KnownDataTypes[key] = dataTypeID;
            }
        }
Пример #8
0
 private void CopyRows(IXLRows newRows)
 {
     foreach (var newRow in newRows)
     {
         var internalRow = Worksheet.Internals.RowsCollection[newRow.RowNumber()];
         internalRow._height = Height;
         internalRow.SetStyle(Style);
         internalRow._collapsed    = Collapsed;
         internalRow._isHidden     = IsHidden;
         internalRow._outlineLevel = OutlineLevel;
     }
 }
Пример #9
0
        /// <summary>
        ///         ''' TODO AGGIUNGERE PARAMETRO ROUNDING OPPURE CELLFORMAT
        ///         ''' </summary>
        ///         ''' <param name="sheetName"></param>
        ///         ''' <param name="labelCell"></param>
        ///         ''' <param name="labelCellValue"></param>
        ///         ''' <param name="excludeHeaders"></param>
        ///         ''' <returns></returns>
        public ExcelHelper AddRowTotal(string sheetName, string labelCell = "A", string labelCellValue = "TOT.", bool excludeHeaders = true)
        {
            IXLRange range = this.GetRangeUsed(sheetName);

            if (range == null)
            {
                //SD.Log("range not found in " + sheetName, SD.LogLevel.Error);
                return(this);
            }
            int       rowsNumber    = range.RowCount();
            IXLCell   lastCellUsed  = range.LastCellUsed();
            IXLColumn lastColUsed   = lastCellUsed.WorksheetColumn();
            IXLRow    lastRowUsed   = lastCellUsed.WorksheetRow();
            string    lastColLetter = lastColUsed.ColumnLetter();
            int       lastRowNumber = lastRowUsed.RowNumber();
            IXLRows   rows          = lastRowUsed.InsertRowsBelow(1);
            //IXLRow newRow = rows.Last();
            var    ws     = this._workbook.Worksheets.Worksheet(sheetName);
            IXLRow newRow = ws.LastRowUsed().RowBelow();

            if (labelCell.Trim() != "")
            {
                newRow.Cell(labelCell).Value           = labelCellValue;
                newRow.Cell(labelCell).Style.Font.Bold = true;
            }
            var      firstTotalCellAddress = newRow.FirstCell().CellRight().Address;
            var      lastTotalCellAddress  = newRow.Cell(lastColLetter).Address;
            IXLRange rangeTotal            = this.GetRangeUsed(sheetName, firstTotalCellAddress, lastTotalCellAddress);
            //int i = rangeTotal.Cells().Count() + 1;
            int i = rangeTotal.ColumnCount() + 1;
            int firstDataRowIndex = 0;

            // escludo la riga delle intestazioni
            if (excludeHeaders)
            {
                firstDataRowIndex = 2;
            }

            for (int k = 1; k <= i; k++)
            {
                XLDataType colDataType = newRow.Cell(k).CellAbove(1).DataType;
                if (colDataType == XLDataType.Number)
                {
                    string colLetter = newRow.Cell(k).Address.ColumnLetter;
                    string formula   = "=SUM(" + colLetter + firstDataRowIndex.ToString() + ":" + colLetter + rowsNumber.ToString() + ")";
                    this.AddFormula(sheetName, newRow.Cell(k).Address, formula);
                }
            }
            newRow.AsRange().RangeUsed().Style.Border.TopBorder = XLBorderStyleValues.Thick;
            return(this);
        }
Пример #10
0
        public async Task <List <string> > GetNamesAsync(string excelPath, ExcelCell groupByNameCell)
        {
            List <string> managerNames = new List <string>();

            if (_log.IsDebugEnabled)
            {
                _log.Debug($"ExcelReader.GetNamesAsync - Creating a new file stream to extract names from source Excel at { excelPath }");
            }
            using (FileStream fs = new FileStream(excelPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                XLWorkbook excel          = new XLWorkbook(fs);
                int        workSheetCount = excel.Worksheets.Count;

                if (_log.IsDebugEnabled)
                {
                    _log.Debug($"ExcelReader.GetNamesAsync - workSheetCount = { workSheetCount }");
                }

                IXLWorksheet worksheet = await Task.Run(() => excel.Worksheet(workSheetCount));

                if (_log.IsDebugEnabled)
                {
                    _log.Debug($"Created Worksheet");
                }

                string nameColumnHeader = worksheet.Row(groupByNameCell.Row)
                                          .Cell(XLHelper.GetColumnNumberFromLetter(groupByNameCell.Column)).Value.ToString();

                if (_log.IsDebugEnabled)
                {
                    _log.Debug($"ExcelReader.GetNamesAsync - nameColumnHeader = { nameColumnHeader }");
                }

                IXLRows rows = await Task.Run(() => worksheet.RowsUsed());

                foreach (IXLRow row in rows)
                {
                    string cellValue = row.Cell(XLHelper.GetColumnNumberFromLetter(groupByNameCell.Column)).Value.ToString().Trim();
                    if (!(string.IsNullOrEmpty(cellValue) || cellValue == nameColumnHeader))
                    {
                        if (_log.IsDebugEnabled)
                        {
                            _log.Debug($"ExcelReader.GetManagerNamesAsync - Adding { cellValue } to manager list");
                        }
                        managerNames.Add(cellValue);
                    }
                }
            }
            return(await Task.Run(() => managerNames.Distinct().ToList()));
        }
Пример #11
0
        public CallInfoList GetCallList(string excelPath)
        {
            CallInfoList listInfo = new CallInfoList();

            try
            {
                using (XLWorkbook workbook = new XLWorkbook(excelPath))
                {
                    using (IXLWorksheet sheet = workbook.Worksheet(1))
                    {
                        using (IXLRows rows = sheet.RowsUsed())
                        {
                            FillCallInfoList(rows, ref listInfo);
                        }
                    }
                }
                return(listInfo);
            }
            catch (Exception)
            {
                throw;
            }
        }
        internal CommonConfig ReadCommon()
        {
            if (Workbook == null)
            {
                return(null);
            }
            IXLWorksheet commonSheet = Workbook.Worksheets.Worksheet("Common");

            if (commonSheet == null)
            {
                Logger.Error("Unable to find \"Common\" sheet.");
                return(null);
            }
            IXLRows rows = commonSheet.RowsUsed();

            CommonConfig.MetaConfig.ConfigurationVersion = new ConfigurationVersion();
            DateTime now  = DateTime.UtcNow;
            TimeSpan time = now - ConfigurationVersion.Base;
            uint     defaultConfigVersion = (uint)time.TotalSeconds;

            foreach (IXLRow row in rows)
            {
                IXLCell cell      = row.Cell("A");
                IXLCell valueCell = row.Cell("B");
                Logger.Debug($"Cell value: {cell.Value}");
                switch (cell.Value)
                {
                case "Publisher ID":
                    CommonConfig.PublisherID = valueCell.GetString();
                    break;

                case "DataSetWriterId":
                    ushort id;
                    try
                    {
                        id = valueCell.GetValue <ushort>();
                    }
                    catch (FormatException exception)
                    {
                        Logger.Error($"Unable to parse DataSetWriterID: '{valueCell.GetString()}'");
                        Logger.Debug("FormatException:", exception);
                        break;
                    }
                    CommonConfig.DataSetWriterID = id;
                    break;

                case "MetaData - Name":
                    CommonConfig.MetaConfig.MetaDataName = valueCell.GetString();
                    break;

                case "MetaData - Description":
                    CommonConfig.MetaConfig.MetaDataDescription = valueCell.GetString();
                    break;

                case "ConfigurationVersion - Major":
                    uint major;
                    try
                    {
                        major = valueCell.GetValue <uint>();
                    }
                    catch (FormatException exception)
                    {
                        Logger.Info($"Unable to parse ConfigurationVersion - Major: '{valueCell.GetString()}', using default value {defaultConfigVersion}");
                        major = defaultConfigVersion;
                        Logger.Debug("FormatException:", exception);
                    }
                    CommonConfig.MetaConfig.ConfigurationVersion.Major = major;
                    break;

                case "ConfigurationVersion - Minor":
                    uint minor;
                    try
                    {
                        minor = valueCell.GetValue <uint>();
                    }
                    catch (FormatException exception)
                    {
                        Logger.Info($"Unable to parse ConfigurationVersion - Minor: '{valueCell.GetString()}', using default value {defaultConfigVersion}");
                        minor = defaultConfigVersion;
                        Logger.Debug("FormatException:", exception);
                    }
                    CommonConfig.MetaConfig.ConfigurationVersion.Minor = minor;
                    break;
                }
            }
            return(CommonConfig);
        }
        internal void ParseEnumSheet()
        {
            IXLWorksheet dataTypeSheet = Workbook.Worksheets.Worksheet("Enums");
            IXLRows      rows          = dataTypeSheet.RowsUsed();
            bool         firstRow      = true;

            foreach (IXLRow row in rows)
            {
                if (firstRow)
                {
                    firstRow = false;
                    continue;
                }
                IXLCell dataTypeCell      = row.Cell("A");
                IXLCell qualifiedNameCell = row.Cell("B");

                //IXLCell enumDescriptionDataTypeCell = row.Cell("C");
                IXLCell   valueCell       = row.Cell("C");
                IXLCell   displayNameCell = row.Cell("D");
                IXLCell   descriptionCell = row.Cell("E");
                IXLCell   valueNameCell   = row.Cell("F");
                EnumEntry entry           = new EnumEntry();
                if (!TryGetNodeID(dataTypeCell.GetString(), out NodeID tempID, CommonConfig))
                {
                    continue;
                }
                entry.DataType      = tempID;
                entry.QualifiedName = qualifiedNameCell.GetString();
                int intValue;
                try
                {
                    intValue = valueCell.GetValue <int>();
                }
                catch (FormatException exception)
                {
                    Logger.Error($"Unable to parse integer value for enum '{valueCell.GetString()}' in row {row.RowNumber()}", exception);
                    continue;
                }
                entry.Value       = intValue;
                entry.DisplayName = displayNameCell.GetString();
                entry.Description = descriptionCell.GetString();
                entry.ValueName   = valueNameCell.GetString();
                EnumDescription enumDescription;
                if (CommonConfig.EnumDescriptions.ContainsKey(entry.DataType))
                {
                    enumDescription = CommonConfig.EnumDescriptions[entry.DataType];
                }
                else
                {
                    enumDescription = new EnumDescription
                    {
                        Name       = new QualifiedName(entry.QualifiedName),
                        DataTypeID = entry.DataType,
                        Fields     = new List <EnumField>()
                    };
                    CommonConfig.EnumDescriptions.Add(entry.DataType, enumDescription);
                }
                EnumField enumField = new EnumField
                {
                    Value       = entry.Value,
                    Name        = new String(entry.ValueName),
                    Description = new LocalizedText(),
                    DisplayName = new LocalizedText()
                };
                if (!string.IsNullOrEmpty(entry.DisplayName))
                {
                    enumField.DisplayName.Locale = new String("en-US");
                    enumField.DisplayName.Text   = new String(entry.DisplayName);
                }
                if (!string.IsNullOrEmpty(entry.Description))
                {
                    enumField.Description.Locale = new String("en-US");
                    enumField.Description.Text   = new String(entry.Description);
                }

                // TODO: Add check for duplicates
                enumDescription.Fields.Add(enumField);
            }
        }
Пример #14
0
        public List <DeltaEntry> Read(string Name, bool isGrouped = false)
        {
            List <DeltaEntry> deltaEntries = new List <DeltaEntry>();

            if (CommonConfig == null || Workbook == null)
            {
                return(deltaEntries);
            }
            IXLWorksheet keySheet = Workbook.Worksheets.Worksheet(Name);
            IXLRows      rows     = keySheet.RowsUsed();
            bool         firstRow = true;

            foreach (IXLRow row in rows)
            {
                if (firstRow)
                {
                    firstRow = false;
                    continue;
                }
                DeltaEntry entry = new DeltaEntry();

                // Index
                IXLCell indexCell = row.Cell("A");
                if (string.IsNullOrWhiteSpace(indexCell.GetString()))
                {
                    Logger.Error($"Empty index cell in row {row.RowNumber()}");
                    continue;
                }
                ushort index = ushort.MinValue;
                try
                {
                    index = indexCell.GetValue <ushort>();
                }
                catch (FormatException e)
                {
                    Logger.Error($"Unable to parse index '{indexCell.GetString()}' as ushort in row {row.RowNumber()}", e);
                    continue;
                }
                entry.Index = index;

                //Grouped Delta Entry
                if (isGrouped)
                {
                    entry.DataType = KeyEntries.First()
                                     .DataType;
                }
                else
                {
                    // Map DataType from KeyList
                    if (KeyEntries == null || KeyEntries.Count == 0)
                    {
                        Logger.Error("Cannot parse value of DeltaEntry, because KeyEntries are not available.");
                        continue;
                    }
                    if (KeyEntries.Count < entry.Index)
                    {
                        Logger.Error($"Cannot parse value of DeltaEntry, because index [{entry.Index}] of Delta Entry is not available in KeyEntries List (count is {KeyEntries.Count})."
                                     );
                        continue;
                    }
                    KeyEntry keyEntry = KeyEntries[entry.Index];
                    entry.DataType = keyEntry.DataType;
                }

                // Orcat
                IXLCell orcatCell = row.Cell("B");
                if (ParseOrcat(row, orcatCell, out byte?orcatValue) && orcatValue.HasValue)
                {
                    entry.Orcat = orcatValue.Value;
                }

                // Quality
                IXLCell qualityCell = row.Cell("C");
                if (ParseQuality(row, qualityCell, out ushort?qualityValue) && qualityValue.HasValue)
                {
                    entry.Quality = qualityValue.Value;
                }

                // Timestamp
                IXLCell timeStampCell = row.Cell("D");
                if (ParseTimeStamp(row, timeStampCell, out long?timeStampValue) && timeStampValue.HasValue)
                {
                    entry.TimeStamp = timeStampValue.Value;
                }

                // Value
                IXLCell valueCell  = row.Cell("E");
                IXLCell value2Cell = row.Cell("F");
                IEntry  baseEntry  = entry;
                if (!TryParse(valueCell, value2Cell, ref baseEntry))
                {
                    continue;
                }

                //Name
                if (isGrouped)
                {
                    IXLCell cellName = row.Cell("F");
                    if (!string.IsNullOrWhiteSpace(cellName.GetString()))
                    {
                        try
                        {
                            entry.Name = cellName.GetValue <string>();
                        }
                        catch (FormatException exception)
                        {
                            Logger.Error($"Unable to parse '{qualityCell.GetString()}' in row {row.RowNumber()} as UInt16", exception);
                        }
                    }
                }
                deltaEntries.Add(entry);
            }
            return(deltaEntries);
        }
Пример #15
0
        public List <KeyEntry> Read(string Name)
        {
            List <KeyEntry> keyEntries = new List <KeyEntry>();

            if (CommonConfig == null || Workbook == null)
            {
                return(keyEntries);
            }
            IXLWorksheet keySheet = Workbook.Worksheets.Worksheet(Name);
            IXLRows      rows     = keySheet.RowsUsed();
            bool         firstRow = true;

            foreach (IXLRow row in rows)
            {
                if (firstRow)
                {
                    firstRow = false;
                    continue;
                }
                KeyEntry entry = new KeyEntry();

                // Index
                IXLCell indexCell = row.Cell("A");
                if (string.IsNullOrWhiteSpace(indexCell.GetString()))
                {
                    Logger.Error($"Empty index cell in row {row.RowNumber()}");
                    continue;
                }
                ushort index = ushort.MinValue;
                try
                {
                    index = indexCell.GetValue <ushort>();
                }
                catch (FormatException e)
                {
                    Logger.Error($"Unable to parse index '{indexCell.GetString()}' as int in row {row.RowNumber()}", e);
                    continue;
                }
                entry.Index = index;

                // Name
                IXLCell nameCell = row.Cell("B");
                if (string.IsNullOrWhiteSpace(nameCell.GetString()))
                {
                    Logger.Error($"Name is empty in row {row.RowNumber()}");
                    continue;
                }
                entry.Name = nameCell.GetString();

                // Description
                IXLCell descriptionCell = row.Cell("C");
                if (string.IsNullOrWhiteSpace(descriptionCell.GetString()))
                {
                    Logger.Info($"Description is empty in row {row.RowNumber()}");
                }
                entry.Description = descriptionCell.GetString();

                // DataType
                IXLCell dataTypeCell = row.Cell("D");
                if (ReadConfiguration.TryGetNodeID(dataTypeCell.GetString(), out NodeID tempID, CommonConfig))
                {
                    entry.DataType = tempID;
                }
        public List <HistoricoKilometrajeDTO> ImportarDatosInterface(UploadedFileDTO file, string usuario)
        {
            List <HistoricoKilometrajeDTO> listaResultado = new List <HistoricoKilometrajeDTO>();
            List <T_Ihmn>     datosAgregar = new List <T_Ihmn>();
            DB_MAPRI_Entities context      = null;

            int      columnasDetectadas   = 0;
            int      filaInicio           = 0;
            DateTime?fechaCreacionArchivo = null;
            bool     esFilaFecha          = false;

            try
            {
                XLWorkbook archivoXLSX = GetWoorkbook(file.Data);

                IXLRows nonEmptyDataRows = archivoXLSX.Worksheet("Report").RowsUsed();

                foreach (IXLRow dataRow in nonEmptyDataRows)
                {
                    if (columnasDetectadas == listaColumnasGuardar.Count)
                    {
                        break;
                    }

                    IXLCells cellsUsed = dataRow.CellsUsed();

                    foreach (IXLCell cellItem in cellsUsed)
                    {
                        if (columnasDetectadas == listaColumnasGuardar.Count)
                        {
                            break;
                        }

                        string valorCelda = cellItem.GetValue <string>().Trim();

                        if (valorCelda == "Created")
                        {
                            esFilaFecha = true;
                            continue;
                        }
                        if (esFilaFecha && fechaCreacionArchivo == null)
                        {
                            double baseDate = cellItem.GetValue <double>();
                            fechaCreacionArchivo = DateTime.FromOADate(baseDate);
                        }

                        int    rowNumber    = cellItem.Address.RowNumber;
                        int    columnNumber = cellItem.Address.ColumnNumber;
                        string value        = cellItem.Value.ToString().Trim();

                        if (listaColumnasGuardar.ContainsKey(value))
                        {
                            if (listaColumnasGuardar[value] == 0)
                            {
                                listaColumnasGuardar[value] = columnNumber;
                                if (filaInicio == 0)
                                {
                                    filaInicio = rowNumber + 1;
                                }
                                columnasDetectadas++;
                            }
                        }
                    }
                }

                var dataRows = archivoXLSX.Worksheet("Report").RowsUsed().Where(r => r.RowNumber() >= filaInicio);

                Parallel.ForEach(dataRows, new ParallelOptions {
                    MaxDegreeOfParallelism = 10
                }, e => AgregarHistoricoKilometrajeDTO(e, fechaCreacionArchivo, ref listaResultado));

                datosAgregar.AddRange(
                    listaResultado.AsParallel().Select(
                        e => new T_Ihmn()
                {
                    VIN          = e.VIN,
                    Fecha        = e.Fecha,
                    Kilometros   = e.Kilometros,
                    Horas        = e.Horas,
                    Minutos      = e.Minutos,
                    CreationUser = usuario,
                    Accion       = "Alta",
                    CreationDate = DateTime.Now
                })
                    );

                context = new DB_MAPRI_Entities();

                context.T_Ihmn.AddRange(datosAgregar);
                int saved = context.SaveChanges();

                listaResultado.Clear();

                listaResultado.AddRange(
                    datosAgregar.AsParallel().Select(
                        e => new HistoricoKilometrajeDTO()
                {
                    Id         = e.Id,
                    VIN        = e.VIN,
                    Fecha      = e.Fecha,
                    Kilometros = e.Kilometros,
                    Horas      = e.Horas,
                    Minutos    = e.Minutos
                })
                    );
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                context?.Dispose();
            }


            return(listaResultado);
        }
Пример #17
0
 private void CopyRows(IXLRows newRows)
 {
     foreach (var newRow in newRows)
     {
         var internalRow = Worksheet.Internals.RowsCollection[newRow.RowNumber()];
         internalRow._height = Height;
         internalRow.SetStyle(Style);
         internalRow._collapsed = Collapsed;
         internalRow._isHidden = IsHidden;
         internalRow._outlineLevel = OutlineLevel;
     }
 }
Пример #18
0
        /// <summary>
        /// The upload batch of users.
        /// </summary>
        /// <param name="company">
        /// The company.
        /// </param>
        /// <param name="fileStream">
        /// The file stream.
        /// </param>
        /// <param name="type">
        /// The type.
        /// </param>
        /// <param name="failed">
        /// The failed.
        /// </param>
        /// <param name="error">
        /// The error.
        /// </param>
        /// <param name="sendActivation">
        /// The send Activation.
        /// </param>
        /// <param name="notifyViaRTMP">
        /// The notify via RTMP.
        /// </param>
        /// <returns>
        /// The <see cref="IEnumerable{User}"/>.
        /// </returns>
        public IEnumerable <User> UploadBatchOfUsers(
            Company company,
            Stream fileStream,
            string type,
            out List <string> failed,
            out string error,
            Action <User> sendActivation = null,
            // ReSharper disable once InconsistentNaming
            bool notifyViaRTMP = true)
        {
            var result = new List <User>();

            failed = new List <string>();
            error  = null;
            try
            {
                var          bookToRead = new XLWorkbook(fileStream);
                IXLWorksheet sheet      = bookToRead.Worksheets.FirstOrDefault();
                if (sheet != null)
                {
                    var     license           = company.Licenses.FirstOrDefault();
                    var     currentUsersCount = this.GetCountForCompany(company.Id).Value;
                    IXLRows rows = sheet.RowsUsed();
                    foreach (IXLRow row in rows)
                    {
                        IXLCell nameCell          = row.FirstCellUsed();
                        string  nameValue         = nameCell.With(x => x.Value.ToString());
                        IXLCell familyNameCell    = nameCell.With(x => x.CellRight());
                        string  familyNameValue   = familyNameCell.With(x => x.Value.ToString());
                        IXLCell emailCell         = familyNameCell.With(x => x.CellRight());
                        string  emailValue        = emailCell.With(x => x.Value.ToString());
                        IXLCell passwordCell      = emailCell.With(x => x.CellRight());
                        string  passwordCellValue = passwordCell.With(x => x.Value.ToString());
                        if (!string.IsNullOrWhiteSpace(emailValue) && emailValidator.Match(emailValue).Success)
                        {
                            if (this.GetOneByEmail(emailValue).Value != null)
                            {
                                failed.Add(string.Format("{0}{1}{2}{3}", nameValue, familyNameValue, emailValue, ": Email exist"));
                                continue;
                            }

                            if (license != null && license.TotalLicensesCount < currentUsersCount + result.Count + 1)
                            {
                                error = "Max users amount is reached";
                                return(result);
                            }

                            try
                            {
                                var instance = new User
                                {
                                    Email        = emailValue,
                                    FirstName    = nameValue,
                                    LastName     = familyNameValue,
                                    Company      = company,
                                    DateCreated  = DateTime.Now,
                                    DateModified = DateTime.Now,
                                    Status       = UserStatus.Inactive,
                                    Language     =
                                        this.languageModel.GetOneById(
                                            this.GetLanguageIdBatchImport(emailCell)).Value,
                                    TimeZone =
                                        this.timeZoneModel.GetOneById(
                                            this.GetTimeZoneIdForBatchImport(emailCell)).Value,
                                    UserRole =
                                        this.userRoleModel.GetOneById((int)UserRoleEnum.User)
                                        .Value,
                                    CreatedBy  = company.PrimaryContact,
                                    ModifiedBy = null
                                };
                                if (string.IsNullOrWhiteSpace(passwordCellValue))
                                {
                                    instance.SetPassword(Password.CreateAlphaNumericRandomPassword(8));
                                    if (sendActivation != null)
                                    {
                                        sendActivation(instance);
                                    }
                                }
                                else
                                {
                                    instance.Status = UserStatus.Active;
                                    instance.SetPassword(passwordCellValue);
                                }

                                this.RegisterSave(instance, true);
                                //if (notifyViaRTMP)
                                //{
                                //    IoC.Resolve<RealTimeNotificationModel>()
                                //        .NotifyClientsAboutChangesInTable<User>(
                                //            NotificationType.Update,
                                //            instance.Company.Id,
                                //            instance.Id);
                                //}

                                result.Add(instance);
                            }
                            catch (Exception ex)
                            {
                                failed.Add(
                                    string.Format(
                                        "{0}{1}{2}{3}",
                                        nameValue,
                                        familyNameValue,
                                        emailValue,
                                        ": Creation error + " + ex.With(x => x.Message)));
                            }
                        }
                        else
                        {
                            failed.Add(
                                string.Format("{0}{1}{2}{3}", nameValue, familyNameValue, emailValue, ": Invalid email"));
                        }
                    }
                }
                else
                {
                    error = "Wrong excel file";
                }
            }
            catch (Exception ex)
            {
                error = ex.ToString();
            }

            return(result);
        }