Example #1
0
        public ActionResult ExportDbData(bool isAutoQuery, string startTime, string endTime, int pageNumber,
                                         int pageSize)
        {
            var directory = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + "TempFiles");

            foreach (var info in directory.GetFileSystemInfos())
            {
                if (info.CreationTime < DateTime.Now.AddHours(-1))
                {
                    info.Delete();
                }
            }
            var helper = new CsvHelper();
            var dt     = ProjectDataDomainModel.Instance.GetDbDataForDataTable(isAutoQuery, startTime, endTime, pageNumber,
                                                                               pageSize);
            var temp = helper.ExportDataToCsv(dt);

            if (string.IsNullOrEmpty(temp))
            {
                Response.Write("无返回结果,请修改查询条件后重试!");
                return(new EmptyResult());
            }
            var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, temp);
            var fileName = Path.GetFileName(filePath);

            return(File(filePath, "application/octet-stream", fileName));
        }
Example #2
0
        public void ParseLog(string logFilePath)
        {
            lotInfo = lotInfo.ReadLotInfoFromLog(logFilePath);

            // we rewrite whole logs. no appending
            if (!CsvHelper.OutputAlreadyPresent(lotInfo.GetUniqueLotId(), outputFolderPath, ref outputFilePath))
            {
                var logFileName = Path.GetFileNameWithoutExtension(logFilePath);
                outputFilePath = Path.Combine(outputFolderPath, logFileName + ".csv");
            }
            else
            {
                //startingMeasurementIndex = int.Parse(CsvHelper.GetLastMeasurementIndex(outputFilePath));
            }

            CsvHelper.InitializeOutputFileContents(outputFilePath, lotInfo.MakeMeasurementFileHeader());

            var normalizedMeasurements = ReadAndNormalizeMeasurements(logFilePath, lotInfo.ZeroThreshold);

            RemoveFakeMeasurements(normalizedMeasurements);
            // normalizedMeasurementsFilePath = Path.Combine(outputFolderPath, logFileName + ".out");
            // SaveListToFile(normalizedMeasurements, normalizedMeasurementsFilePath); // Generic list save does not work

            var finalMeasurements = ExtractFinalMeasurements(normalizedMeasurements, lotInfo.Package.NetWeight);

            RemoveLastMeasurementIfNotInTolerance(finalMeasurements);
            AddPositionToEachMeasurement(finalMeasurements, startingMeasurementIndex);
            SaveListToFile(finalMeasurements, outputFilePath);
        }
Example #3
0
        void DoImport(string[] fileNames)
        {
            var list = new List <IEnumerable <Applicant> >();

            foreach (var fileName in fileNames)
            {
                try {
                    list.Add(CsvHelper.ImportCsvFile(fileName));
                } catch (Exception ex) {
                    Dispatcher.Invoke(() => MessageBox.Show(string.Format(_errorImportFile, fileName, ex), Title));
                }
            }

            var db = new ApplicantsDbContext();

            try {
                foreach (var l in list)
                {
                    foreach (var i in l)
                    {
                        db.Insert(i);
                    }
                }
            } catch (Exception ex) {
                Dispatcher.Invoke(() => MessageBox.Show(string.Format(_erorImport, ex), Title));
            }
        }
Example #4
0
            public void DoesNotModifyNormalCharatersTest1()
            {
                string str        = "no escaping here";
                string escapedStr = new CsvHelper().Escape(str);

                Assert.AreEqual(str, escapedStr);
            }
Example #5
0
        private void _getConfigInfo(string configPath)
        {
            _replaceInfos = new List <ReplaceInfo>();
            Dictionary <string, List <string> > configInfo = CsvHelper.AnalysisCsvByFile(configPath);

            foreach (List <string> values in configInfo.Values)
            {
                for (int i = 0; i < values.Count; i++)
                {
                    ReplaceInfo info = new ReplaceInfo();
                    info.SourceInfo = values[i];
                    _replaceInfos.Add(info);
                }
            }
            int temp = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(_replaceInfos.Count / 2.0f)));

            for (int i = 0; i < temp; i++)
            {
                ReplaceInfo info = new ReplaceInfo();
                info.SourceInfo  = _replaceInfos[i].SourceInfo;
                info.TargetInfo  = _replaceInfos[i + temp].SourceInfo;
                _replaceInfos[i] = info;
            }
            while (_replaceInfos.Count > temp)
            {
                _replaceInfos.RemoveAt(_replaceInfos.Count - 1);
            }
        }
Example #6
0
        private void _setConfigInfo(string configPath)
        {
            _dirInfoDic = new Dictionary <string, string>();
            Dictionary <string, List <string> > configInfo = CsvHelper.AnalysisCsvByFile(configPath);
            int           temp   = 0;
            List <string> keys   = new List <string>();
            List <string> values = new List <string>();

            foreach (List <string> tempList in configInfo.Values)
            {
                if (temp == 0)
                {
                    keys = tempList;
                }
                else if (temp == 1)
                {
                    values = tempList;
                }
                temp++;
            }
            for (int j = 0; j < keys.Count; j++)
            {
                _dirInfoDic.Add(keys[j], values[j]);
            }
        }
Example #7
0
        public void WriteReadCSV()
        {
            // Arrange
            var users = PrepareUsers(10);

            var csvHelper = new CsvHelper();

            csvHelper.Config.DateTimeFormat  = "yyyyMMdd HH:mm:ss";
            csvHelper.Config.Delimiter       = '\t';
            csvHelper.Config.HasHeaderRecord = true;


            // Act

            // write CSV
            string csvWriteResult = csvHelper.WriteRecords(users);

            // read CSV
            CsvReadResult <User> csvReaderResult = csvHelper.GetRecords <User>(csvWriteResult);


            // Assert
            csvReaderResult.Errors.Should().HaveCount(0);
            csvReaderResult.Records.Should().HaveCount(users.Count());

            csvReaderResult.Records.Should().BeEquivalentTo(users);
        }
Example #8
0
        public int TriageFlaws(GetTriageFlawsOptions options)
        {
            var allFlaws = new List <FlawType>();

            foreach (var buildid in options.BuildIds.Split(','))
            {
                var flaws = _veracodeRepository
                            .GetFlaws(buildid)
                            .OrderBy(x => x.issueid);

                foreach (var flaw in flaws)
                {
                    flaw.BuildId = buildid;
                }

                allFlaws.AddRange(flaws);
            }

            var output = new CsvHelper().ToCsv(allFlaws);

            if (options.Output.ToLower().Equals("csv"))
            {
                File.WriteAllText($"{options.Filename}.csv", output);
            }
            else
            {
                Console.WriteLine(output);
            }
            return(1);
        }
        static void Main(string[] args)
        {
            List <CsvDataRow> allData = CsvHelper.ProcessFile("sample.csv", out _, 1);

            allData.ForEach(row => Console.WriteLine(row.SourceLine));

            foreach (CsvDataRow item in allData)
            {
                Console.WriteLine($"{item.RowData.Count};");
                foreach (KeyValuePair <Column, string> cell in item.RowData)
                {
                    Console.WriteLine($"Value = {cell.Value}\t\t\tat column = {cell.Key}");
                }
            }

            Console.Clear();

            List <ClipboardLib.ClipboardDataRow> clipboardDataRows = ClipboardLib.ClipboardHelper.ProcessClipboardData(out _);

            clipboardDataRows.ForEach(row => Console.WriteLine(row.SourceText));

            foreach (var item in clipboardDataRows)
            {
                Console.WriteLine(item.RowData.Count);
                foreach (var cell in item.RowData)
                {
                    Console.WriteLine($"Value = {cell.Value}\t\t\tat column = {cell.Key}");
                }
            }
        }
Example #10
0
    private void AddList(GameDataSet dataSet, GameDataType dataType, string csvString)
    {
        List <string[]> csvDataList = CsvHelper.FormatCsvToStringArrayList(csvString);

        switch (dataType)
        {
        case GameDataType.USER_ITEM:
            foreach (string[] data in csvDataList)
            {
                if (data == csvDataList[0])
                {
                    continue;
                }
                dataSet.UserItemList.Add(new UserItem(int.Parse(data[0]), int.Parse(data[1]), Convert.ToBoolean(data[2])));
            }
            break;

        case GameDataType.USER_PARAMETER:
            foreach (string[] data in csvDataList)
            {
                if (data == csvDataList[0])
                {
                    continue;
                }
                dataSet.UserParameterList.Add(new UserParameter(int.Parse(data[0]), int.Parse(data[1]), data[2]));
            }
            break;

        default:
            break;
        }
    }
        public void UT_Dt2Csv_V1()
        {
            DataTable dt       = CreateTestDataTable();
            string    filePath = Path.Combine("D:/", dt.TableName + ".csv");

            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }
            try
            {
                bool result = CsvHelper.Dt2Csv(dt, filePath);
                if (!result)
                {
                    Assert.Fail("DataTable对象转换为CSV文件失败");
                }
                else
                {
                    Assert.IsTrue(File.Exists(filePath));
                }
            }
            catch (Exception ex)
            {
                Assert.Fail(ex.Message);
            }
        }
Example #12
0
        public void CalculatePricesTest()
        {
            Dictionary <string, Dictionary <string, JOffer> > pdfRates = new Rates().GetRates(sf, out site);
            string brokerName = "JIG";
            //  for (int i = 0; i < Classes.Count(); i++)
            {
                PricingHelper ph = new PricingHelper();

                List <JOffer> categoryOffers = new PricingHelper().GetMiniRatesList(pdfRates, "EconomyA");
                List <JOffer> higherOffers   = new PricingHelper().GetMiniRatesList(pdfRates, "CompactM");
                List <float>  fuseRates      = new CsvHelper("314141").GetFuseRates(brokerName);

                PricingClass[] classes   = new PricingClass[5];
                PricingHelper  hp        = new PricingHelper(new PricingModel(), classes);
                List <float>   priceList = hp.CalculatePrices(categoryOffers, higherOffers, fuseRates, brokerName);

                Console.WriteLine("-----------------");

                for (int i = 0; i < priceList.Count; i++)
                {
                    JOffer tempOffer = categoryOffers.Count > i?categoryOffers.ElementAt(i) : null;

                    float price = tempOffer != null?tempOffer.GetMinPrice() : 0;

                    float gmPrice = tempOffer != null?tempOffer.GetMinGmPrice() : 0;

                    Console.WriteLine(i + " price " + price + " gmprice " + gmPrice + " fuse: " + fuseRates.ElementAt(i) + " new price: " + priceList.ElementAt(i));
                }
                Console.WriteLine("-----------------");
                Console.ReadLine();
            }
        }
        private static void InstantiateBinding()
        {
            if (Selection.activeObject != null)
            {
                var path = AssetDatabase.GetAssetPath(Selection.activeObject);
                if (!string.IsNullOrEmpty(path))
                {
                    var table       = CsvHelper.ReadCSV(path, System.Text.Encoding.GetEncoding("gb2312"));
                    var bindingInfo = table.LoadPrefabBindingInfo();
                    if (bindingInfo != null)
                    {
                        CreateBindingTemplate(bindingInfo);
                        return;
                    }
                }
            }

            var filePath = EditorUtility.OpenFilePanel("选择绑定配制文档", prefer_ConfigPath.Value, "csv");

            if (!string.IsNullOrEmpty(filePath))
            {
                prefer_ConfigPath.Value = System.IO.Path.GetDirectoryName(filePath);
                var table = CsvHelper.ReadCSV(filePath, System.Text.Encoding.GetEncoding("gb2312"));
                if (table != null)
                {
                    var bindingInfo = table.LoadPrefabBindingInfo();
                    if (bindingInfo != null)
                    {
                        CreateBindingTemplate(bindingInfo);
                    }
                }
            }
        }
        private void ExportConfigClick()
        {
            if (uiInfo == null)
            {
                return;
            }

            var configPath = SaveConfigFilePath();

            if (!string.IsNullOrEmpty(configPath))
            {
                var table = uiInfo.UIInfoToTable();
                trySave : try
                {
                    CsvHelper.SaveCSV(table, configPath, System.Text.Encoding.GetEncoding("gb2312"));
                    DialogHelper.OpenFolderAndSelectFile(configPath);
                }
                catch (Exception e)
                {
                    var retry = DialogHelper.ShowDialog("保存失败", e.Message + "\n重试请按确认!", true);
                    if (retry)
                    {
                        goto trySave;
                    }
                }
            }
        }
Example #15
0
        public void DataTableImportExportTest()
        {
            var dt = new DataTable();

            dt.Columns.AddRange(new[]
            {
                new DataColumn("Name"),
                new DataColumn("Age"),
                new DataColumn("Desc"),
            });
            for (var i = 0; i < 10; i++)
            {
                var row = dt.NewRow();
                row.ItemArray = new object[] { $"Test_{i}", i + 10, $"Desc_{i}" };
                dt.Rows.Add(row);
            }
            //
            var csvBytes     = dt.ToCsvBytes();
            var importedData = CsvHelper.ToDataTable(csvBytes);

            Assert.NotNull(importedData);
            Assert.Equal(dt.Rows.Count, importedData.Rows.Count);
            for (var i = 0; i < dt.Rows.Count; i++)
            {
                Assert.Equal(dt.Rows[i].ItemArray.Length, importedData.Rows[i].ItemArray.Length);
                for (var j = 0; j < dt.Rows[i].ItemArray.Length; j++)
                {
                    Assert.Equal(dt.Rows[i].ItemArray[j], importedData.Rows[i].ItemArray[j]);
                }
            }
        }
Example #16
0
        public static void SetClipboardData(List <string[]> data)
        {
            if (data is null || data.Count == 0)
            {
                return;
            }

            var sb1 = new StringBuilder();
            var sb2 = new StringBuilder();

            foreach (var row in data)
            {
                sb1.Append(CsvHelper.FormatForCsv(CultureInfo.CurrentCulture.TextInfo.ListSeparator, row));
                sb1.Append(Environment.NewLine);

                sb2.Append(CsvHelper.FormatForCsv("\t", row));
                sb2.Append(Environment.NewLine);
            }
            string clipboardData1 = sb1.ToString();
            string clipboardData2 = sb2.ToString();

            Clipboard.Clear();
            if (!String.IsNullOrEmpty(clipboardData1))
            {
                Clipboard.SetData(DataFormats.CommaSeparatedValue, clipboardData1);
            }
            if (!String.IsNullOrEmpty(clipboardData2))
            {
                Clipboard.SetData(DataFormats.Text, clipboardData2);
            }
        }
Example #17
0
        private List <string> GetImgDirList(string imgDirPath, string configPath)
        {
            string        errorInfo = "未找到目录如下:\n";
            List <string> result    = new List <string>();
            Dictionary <string, List <string> > configInfo = CsvHelper.AnalysisCsvByFile(configPath);
            List <string> infoList = new List <string>();

            foreach (List <string> valueTemp in configInfo.Values)
            {
                for (int i = 0; i < valueTemp.Count; i++)
                {
                    infoList.Add(valueTemp[i]);
                }
            }
            for (int i = 0; i < infoList.Count; i++)
            {
                string dirPath = Path.Combine(imgDirPath, infoList[i]);
                if (Directory.Exists(dirPath))
                {
                    result.Add(dirPath);
                }
                else
                {
                    errorInfo += dirPath + "\n";
                }
            }
            File.WriteAllText(statisticalPath, errorInfo, Encoding.UTF8);
            return(result);
        }
Example #18
0
        public void SaveData(Stream stream, FormatTypeEnum formatType)
        {
            var upload = new UploadFile();

            upload.UploadDate   = DateTime.Now;
            upload.FormatType   = formatType;
            upload.Transactions = new List <Transaction>();

            if (formatType == FormatTypeEnum.CSV)
            {
                StreamReader reader = new StreamReader(stream);

                while (!reader.EndOfStream)
                {
                    upload.Transactions.Add(CsvHelper.FromCsv(reader.ReadLine()));
                }
            }
            else
            {
                upload.Transactions.AddRange(XmlHelper.FromXml(stream));
            }

            try
            {
                db.SaveData(upload);
            }
            catch (Exception ex)
            {
                throw new Exception("Error save", ex);
            }
        }
Example #19
0
        public void GuessNewlineTest()
        {
            // Create a test file with LF Only
            var fileName = Path.Combine(m_ApplicationDirectory, "TestFileLF.txt");

            using (var file = new StreamWriter(File.Open(fileName, FileMode.CreateNew), System.Text.Encoding.GetEncoding(65001)))
            {
                string[] lines = { "ID\tTitle\t\"Object ID\"",
                                   "12367890\t5 Overview\tc41f21c8-d2cc-472b-8cd9-707ddd8d24fe",
                                   "3ICC\t10/14/2010\t0e413ed0-3086-47b6-90f3-836a24f7cb2e",
                                   "3SOF\t3 Overview\taff9ed00-016e-4202-a3df-27a3ce443e80",
                                   "3T1SA\t3 Phase 1\t\"8d527a23-2777-4754-a73d-029f67abe715\"",
                                   "3T22A\t3 Phase 2\tf9a99add-4cc2-4e41-a29f-a01f5b3b61b2",
                                   "3T25C\t3 Phase 2\tab416221-9f79-484e-a7c9-bc9a375a6147",
                                   "7S721A\t7 راز\t2b9d291f-ce76-4947-ae7b-fec3531d1766",
                                   "#Hello\t7th Heaven\t1d5b894b-95e6-4026-9ffe-64197e79c3d1" };
                foreach (string line in lines)
                {
                    // If the line doesn't contain the word 'Second', write the line to the file.
                    if (!line.Contains("Second"))
                    {
                        file.Write(line);
                        file.Write('\n');
                    }
                }
            }

            var Test = new CsvFile(Path.Combine(m_ApplicationDirectory, fileName))
            {
                CodePageId = 65001
            };

            Test.FileFormat.FieldQualifier = "\"";
            Assert.AreEqual("LF", CsvHelper.GuessNewline(Test));
        }
Example #20
0
 public void GuessStartRow()
 {
     Assert.AreEqual(0, CsvHelper.GuessStartRow(new CsvFile
     {
         FileName = Path.Combine(m_ApplicationDirectory, "BasicCSV.txt")
     }), "BasicCSV.txt");
 }
Example #21
0
        public void GuessCodePage()
        {
            var setting = new CsvFile
            {
                FileName = Path.Combine(m_ApplicationDirectory, "BasicCSV.txt")
            };

            CsvHelper.GuessCodePage(setting);
            Assert.AreEqual(1200, setting.CodePageId);

            var setting2 = new CsvFile
            {
                FileName = Path.Combine(m_ApplicationDirectory, "UnicodeUTF16BE.txt")
            };

            CsvHelper.GuessCodePage(setting2);
            Assert.AreEqual(1201, setting2.CodePageId);

            var setting3 = new CsvFile
            {
                FileName = Path.Combine(m_ApplicationDirectory, "Test.csv")
            };

            CsvHelper.GuessCodePage(setting3);
            Assert.AreEqual(65001, setting3.CodePageId);
        }
        public virtual void Write(string fileName)
        {
            ReadReportParams();
            ProcessReport();
            var reportTable = GetReportTable();

            if (IsEmpty(reportTable))
            {
                throw new Exception(@"В результате подготовки отчета получился пустой набор данных
1. если это отчет по заказам, то возможно за выбранный период нет заказов или же данные за выбранный период не были импортированы (нужно проверить таблицу ordersold)
2. если это отчет по динамике цен, то возможно не были подготовлены данные, нужно проверить, заполнены ли соответствующие таблицы данными
3. если это отчет по предложениям, то нужно проверить настройки отчета возможно в них ошибка. Так, например:
а) для отчета, формируемом по базовым ценам, нужно убедиться, что ценовая колонка, настроенная в системе, как базовая присутствует в прайс-листе поставщика");
            }

            var writer = GetWriter(Format);

            if (writer != null)
            {
                // Новый механизм, выносим часть для выгрузки в файл в отдельный класс
                var settings = GetSettings();
                writer.WriteReportToFile(_dsReport, fileName, settings);
                Warnings.AddRange(writer.Warnings);
                return;
            }

            if (Format == ReportFormats.DBF)
            {
                if (!DbfSupported)
                {
                    throw new ReportException("Подотчет не может готовиться в формате DBF.");
                }
                // Формируем DBF
                fileName = Path.Combine(Path.GetDirectoryName(fileName), ReportCaption + ".dbf");
                ProfileHelper.Next("DataTableToDbf");
                DataTableToDbf(reportTable, fileName);
            }
            else if (Format == ReportFormats.CSV)
            {
                if (!DbfSupported)
                {
                    throw new ReportException("Подотчет не может готовиться в формате CSV.");
                }
                //Формируем CSV
                ProfileHelper.Next("CsvHelper.Save");
                fileName = Path.Combine(Path.GetDirectoryName(fileName), ReportCaption + ".csv");
                CsvHelper.Save(reportTable, fileName);
            }
            else
            {
                // Формируем Excel
                ProfileHelper.Next("DataTableToExcel");
                DataTableToExcel(reportTable, fileName);
                if (File.Exists(fileName))
                {
                    ProfileHelper.Next("FormatExcel");
                    FormatExcel(fileName);
                }
            }
        }
Example #23
0
        public void ExportDictionaries(string processId, PrcSettingsElastic settings, List <string> tagIdList, CancellationToken token, string hostUrl)
        {
            try
            {
                var service = serviceQuery.Get(settings.ServiceId);

                var dataSet     = GlobalStore.DataSets.Get(settings.DataSetName).DataSet;
                var allDicCount = tagIdList.Count;
                /*ZIP time*/
                allDicCount += (allDicCount / 10);
                var progress = new Progress(allDicCount);

                var dictionariesPath = string.Format("{0}/{1}", _dictionaryRootPath, settings.ServiceId);

                var tempDirectoryPath = string.Format("{0}/{1}", siteConfig.Directory.Temp, processId);
                System.IO.Directory.CreateDirectory(tempDirectoryPath);

                foreach (var tagId in tagIdList)
                {
                    if (token.IsCancellationRequested)
                    {
                        processHandler.Cancelled(processId);
                        return;
                    }
                    var filePath    = $"{dictionariesPath}/{DictionaryProtoBuf.GetFileName(tagId)}";
                    var dicProtoBuf = BaseProtoBuf.DeSerialize <DictionaryProtoBuf>(filePath);

                    var csvPath = $"{tempDirectoryPath}/{tagId}.csv";
                    if (dicProtoBuf.Dictionary != null)
                    {
                        CsvHelper.CreateCsv(csvPath, dicProtoBuf.Dictionary.Select(d => new List <string> {
                            d.Key, d.Value.ToString()
                        }).ToList());
                    }
                    else
                    {
                        CsvHelper.CreateCsv(csvPath, new List <List <string> >());
                    }

                    progress.Step();
                    processHandler.Changed(processId, progress.Percent.Round(2));
                }
                /*time to ZIP the results*/
                var zipFileName   = string.Format("{0}.zip", processId);
                var dirToZipPath  = string.Format("{0}/{1}", siteConfig.Directory.Temp, processId);
                var resultZipPath = string.Format("{0}/{1}", siteConfig.Directory.User, zipFileName);
                ZipHelper.CompressFolder(dirToZipPath, resultZipPath);

                var zipUrl = string.Format("{0}{1}/{2}", hostUrl, Common.Constants.FilesPath, zipFileName);

                processHandler.Finished(processId,
                                        string.Format("{0}\n{1}",
                                                      string.Format(ServiceResources.SuccessfullyExportedDictionariesFrom_0_Service_1, ServiceTypeEnum.Prc, service.Name),
                                                      string.Format(ServiceResources.ExportFileCanBeDownloadFromHere_0, zipUrl)));
            }
            catch (Exception ex)
            {
                processHandler.Interrupted(processId, ex);
            }
        }
        public static T ReadTable <T>(string name, Stream s, int ni, int ti, int vi, int ki)
            where T : class, ICsvDataTableReader, new()
        {
            DataTable dt = CsvHelper.csv2dt(name, s, ni, ti, vi);

            return(ParseDataTable <T>(dt, ki));
        }
            public override string SaveLine()
            {
                StringBuilder sb = new StringBuilder();

                sb.Append(string.Join(",",
                                      ShipID,
                                      CsvHelper.EscapeCsvCell(ShipName),
                                      HPMin,
                                      HPMax,
                                      FirepowerMin,
                                      FirepowerMax,
                                      TorpedoMin,
                                      TorpedoMax,
                                      AAMin,
                                      AAMax,
                                      ArmorMin,
                                      ArmorMax,
                                      ASW.MinimumEstMin,
                                      ASW.MinimumEstMax,
                                      ASW.Maximum,
                                      Evasion.MinimumEstMin,
                                      Evasion.MinimumEstMax,
                                      Evasion.Maximum,
                                      LOS.MinimumEstMin,
                                      LOS.MinimumEstMax,
                                      LOS.Maximum,
                                      LuckMin,
                                      LuckMax,
                                      Range));

                if (DefaultSlot == null)
                {
                    sb.Append(",null,null,null,null,null");
                }
                else
                {
                    sb.Append(",").Append(string.Join(",", DefaultSlot));
                }

                if (Aircraft == null)
                {
                    sb.Append(",null,null,null,null,null");
                }
                else
                {
                    sb.Append(",").Append(string.Join(",", Aircraft));
                }

                sb.Append(",").Append(string.Join(",",
                                                  CsvHelper.EscapeCsvCell(MessageGet),
                                                  CsvHelper.EscapeCsvCell(MessageAlbum),
                                                  CsvHelper.EscapeCsvCell(ResourceName),
                                                  ResourceGraphicVersion ?? "null",
                                                  ResourceVoiceVersion ?? "null",
                                                  ResourcePortVoiceVersion ?? "null",
                                                  OriginalCostumeShipID
                                                  ));

                return(sb.ToString());
            }
Example #26
0
 // Token: 0x060009E2 RID: 2530 RVA: 0x0003CEF1 File Offset: 0x0003B0F1
 public static void Init()
 {
     LocalisationSystem.csvFile = Resources.Load <TextAsset>("localisation");
     CsvHelper.Init(',');
     LocalisationSystem.table  = CsvHelper.Create(LocalisationSystem.csvFile.name, LocalisationSystem.csvFile.text, true, true);
     LocalisationSystem.isInit = true;
 }
Example #27
0
        //TODO: Figure out how to externalise the dependencies for Nutrient and Food Factory
        public Food Create(string lineCSV, string headerCSV, string unitsCSV)
        {
            var fields = CsvHelper.SplitCSV(lineCSV);
            var header = CsvHelper.SplitCSV(headerCSV);
            var units  = CsvHelper.SplitCSV(unitsCSV);

            if (fields.Length != header.Length || fields.Length != units.Length)
            {
                throw new ArgumentOutOfRangeException($"Input arguments have different field lengths. " +
                                                      $"lineCSV: {fields.Length}, headerCSV: {header.Length}, unitCSV: {units.Length}");
            }

            var publicFoodKey  = fields[0];
            var classification = fields[1];
            var description    = fields[2];

            //TODO: we could initialise the dictionary once then just clone it and populate the values for each line.
            var nutrients = new Dictionary <Nutrient, Value>();

            for (int i = 3; i < fields.Length; i++)
            {
                var value = fields[i];

                var nutrient = NutrientFactory.Default.Lookup(header[i]);
                if (nutrient != Nutrient.Null)
                {
                    Console.WriteLine($"Adding Nutrient {nutrient} to the dictionary with index {i} with unit value of {units[i]}");
                    nutrients[nutrient] = Food.IsEmpty(value, UnitFactory.Default.Lookup(units[i]));
                }
            }

            return(new Food(publicFoodKey, classification, description, nutrients));
        }
Example #28
0
        public static List <List <string?> > ParseClipboardData()
        {
            IDataObject dataObj = Clipboard.GetDataObject();

            if (dataObj is null)
            {
                return(new List <List <string?> >());
            }

            object clipboardData = dataObj.GetData(DataFormats.CommaSeparatedValue);

            if (clipboardData is not null)
            {
                string clipboardDataString = GetClipboardDataString(clipboardData);
                return(CsvHelper.ParseCsv(CultureInfo.CurrentCulture.TextInfo.ListSeparator, clipboardDataString));
            }
            clipboardData = dataObj.GetData(DataFormats.Text);
            if (clipboardData is not null)
            {
                string clipboardDataString = GetClipboardDataString(clipboardData);
                return(CsvHelper.ParseCsv("\t", clipboardDataString));
            }

            return(new List <List <string?> >());
        }
        private static void AnalysisBinding()
        {
            if (Selection.activeTransform != null)
            {
                var bindingInfo = DecompressionBindingInfo(Selection.activeTransform);

                var table = bindingInfo.CreateTable();

                if (table != null)
                {
                    if (string.IsNullOrEmpty(prefer_ConfigPath.Value))
                    {
                        prefer_ConfigPath.Value = Application.dataPath;
                    }
                    var filePath = EditorUtility.SaveFilePanel("另存为配制文档", prefer_ConfigPath.Value, table.name, "csv");
                    if (!string.IsNullOrEmpty(filePath))
                    {
                        var dir = System.IO.Path.GetDirectoryName(filePath);
                        prefer_ConfigPath.Value = dir;
                        CsvHelper.SaveCSV(table, filePath, System.Text.Encoding.GetEncoding("gb2312"));
                        AssetDatabase.Refresh();
                    }
                }
            }
        }
Example #30
0
        public int PolicySummary(PolicySummaryOptions options)
        {
            var summaries = new List <ScanSummary>();

            foreach (var buildid in options.BuildIds.Split(','))
            {
                var severities = _veracodeRepository.GetSeverity(buildid);
                foreach (var severity in severities)
                {
                    var summary = severity.category.Select(c => new ScanSummary
                    {
                        Category = c.categoryname,
                        BuildId  = buildid,
                        Severity = SeverityLabel(severity.level),
                        Count    = c.cwe.Sum(cwe => cwe.staticflaws.Count())
                    });
                    summaries.AddRange(summary);
                }
            }

            var output = new CsvHelper().ToCsv(summaries);

            if (options.Output.ToLower().Equals("csv"))
            {
                File.WriteAllText($"{options.Filename}.csv", output);
            }
            else
            {
                Console.WriteLine(output);
            }
            return(1);
        }
Example #31
0
        public void DisposeWhenUsingWriteOnlyStream()
        {
            var writeOnlyStream = new WriteOnlyStream();

            using( var csvHelper = new CsvHelper( writeOnlyStream ) )
            {
                csvHelper.Writer.WriteField( "test" );
            }
        }
Example #32
0
        public void DisposeWhenUsingReadOnlyStream()
        {
            var data = Encoding.Default.GetBytes( "one,two,three" );
            var memoryStream = new MemoryStream( data, false );

            using( var csvHelper = new CsvHelper( memoryStream ) )
            {
                csvHelper.Reader.Read();
            }
        }
Example #33
0
        public void WriteUsingWriteOnlyStreamTest()
        {
            var writeOnlyStream = new WriteOnlyStream();

            var csvHelper = new CsvHelper( writeOnlyStream );
            csvHelper.Writer.WriteField( "test" );

            try
            {
                csvHelper.Reader.Read();
                Assert.Fail( "Accessing the reader did not throw and exception." );
            }
            catch( CsvReaderException ) {}
        }
Example #34
0
        public void ReadUsingReadOnlyStreamTest()
        {
            var data = Encoding.Default.GetBytes( "one,two,three" );
            var memoryStream = new MemoryStream( data, false );

            var csvHelper = new CsvHelper( memoryStream );
            csvHelper.Reader.Read();

            try
            {
                csvHelper.Writer.WriteField( "test" );
                Assert.Fail( "Accessing the writer did not throw an exception." );
            }
            catch( CsvWriterException )
            {
            }
        }