public void ChangeMemberMapTest()
        {
            var config = new CsvHelper.Configuration.CsvConfiguration(CultureInfo.InvariantCulture);
            var map    = config.AutoMap <A>();

            map.Map(m => m.B.C.P3).Index(3);
        }
        public void MultipleCharDelimiterWithBufferEndingInMiddleOfDelimiterTest()
        {
            var config = new CsvHelper.Configuration.CsvConfiguration(CultureInfo.InvariantCulture)
            {
                Delimiter  = "|~|",
                BufferSize = 16,
            };

            using (var stream = new MemoryStream())
                using (var reader = new StreamReader(stream))
                    using (var writer = new StreamWriter(stream))
                        using (var parser = new CsvParser(reader, config))
                        {
                            writer.WriteLine("12340000004321|~|2");
                            writer.Flush();
                            stream.Position = 0;

                            var hasRecords = parser.Read();
                            Assert.True(hasRecords);
                            Assert.Equal(2, parser.Count);
                            Assert.Equal("12340000004321", parser[0]);
                            Assert.Equal("2", parser[1]);

                            hasRecords = parser.Read();
                            Assert.False(hasRecords);
                        }
        }
示例#3
0
        public void ReadConvertWithIndexEndTest()
        {
            var config = new CsvHelper.Configuration.CsvConfiguration(CultureInfo.InvariantCulture)
            {
                HasHeaderRecord = false
            };
            var rowMock       = new Mock <IReaderRow>();
            var currentRecord = new[] { "1", "one", "1", "2", "3" };
            var context       = new ReadingContext(new StringReader(string.Empty), config, false)
            {
                Record = currentRecord
            };

            rowMock.Setup(m => m.Configuration).Returns(config);
            rowMock.Setup(m => m.Context).Returns(context);
            rowMock.Setup(m => m.GetField(It.IsAny <Type>(), It.IsAny <int>())).Returns <Type, int>((type, index) => Convert.ToInt32(currentRecord[index]));
            var data = new MemberMapData(typeof(Test).GetProperty("List"))
            {
                Index                = 2,
                IndexEnd             = 3,
                TypeConverterOptions = { CultureInfo = CultureInfo.CurrentCulture }
            };

            var converter  = new ArrayConverter();
            var enumerable = (int?[])converter.ConvertFromString("1", rowMock.Object, data);
            var list       = enumerable.ToList();

            Assert.AreEqual(2, list.Count);
            Assert.AreEqual(1, list[0]);
            Assert.AreEqual(2, list[1]);
        }
示例#4
0
        public void ConvertWithIndexEndTest()
        {
            var config = new CsvHelper.Configuration.CsvConfiguration(CultureInfo.InvariantCulture)
            {
                HasHeaderRecord = false
            };
            var rowMock       = new Mock <IReaderRow>();
            var headers       = new[] { "Id", "Name", "Prop1", "Prop2", "Prop3" };
            var currentRecord = new[] { "1", "One", "1", "2", "3" };
            var context       = new ReadingContext(new StringReader(string.Empty), config, false)
            {
                HeaderRecord = headers,
                Record       = currentRecord
            };

            rowMock.Setup(m => m.Configuration).Returns(config);
            rowMock.Setup(m => m.Context).Returns(context);
            rowMock.Setup(m => m.GetField(It.IsAny <Type>(), It.IsAny <int>())).Returns <Type, int>((type, index) => Convert.ToInt32(currentRecord[index]));
            var data = new MemberMapData(typeof(Test).GetProperty("Dictionary"))
            {
                Index    = 2,
                IndexEnd = 3
            };

            data.TypeConverterOptions.CultureInfo = CultureInfo.CurrentCulture;

            var converter  = new IDictionaryGenericConverter();
            var dictionary = (IDictionary)converter.ConvertFromString("1", rowMock.Object, data);

            Assert.AreEqual(2, dictionary.Count);
            Assert.AreEqual(1, dictionary["Prop1"]);
            Assert.AreEqual(2, dictionary["Prop2"]);
        }
示例#5
0
        public void AutoMapWithExistingMapTest()
        {
            var config      = new CsvHelper.Configuration.CsvConfiguration(CultureInfo.InvariantCulture);
            var existingMap = new SimpleMap();

            config.Maps.Add(existingMap);
            var data = new
            {
                Simple = new Simple
                {
                    Id   = 1,
                    Name = "one"
                }
            };
            var map = config.AutoMap(data.GetType());

            Assert.IsNotNull(map);
            Assert.AreEqual(0, map.MemberMaps.Count);
            Assert.AreEqual(1, map.ReferenceMaps.Count);

            // Since Simple is a reference on the anonymous object, the type won't
            // be re-used. Types which are created from automapping aren't added
            // to the list of registered maps either.
            Assert.IsNotInstanceOfType(map.ReferenceMaps[0].Data.Mapping, typeof(SimpleMap));
        }
        public void RegisterClassInstanceTest()
        {
            var config = new CsvHelper.Configuration.CsvConfiguration(CultureInfo.InvariantCulture);

            Assert.IsNull(config.Maps[typeof(TestClass)]);
            config.RegisterClassMap(new TestClassMappings());
            Assert.IsNotNull(config.Maps[typeof(TestClass)]);
        }
        public void AddingMappingsWithInstanceMethodTest()
        {
            var config = new CsvHelper.Configuration.CsvConfiguration(CultureInfo.InvariantCulture);

            config.RegisterClassMap(new TestClassMappings());

            Assert.AreEqual(2, config.Maps[typeof(TestClass)].MemberMaps.Count);
        }
        /// <summary>
        /// Process the user request
        /// </summary>
        public override void ExecuteCmdlet()
        {
            base.ExecuteCmdlet();

            try
            {
                if (System.IO.File.Exists(this.MetaDataCsvFile))
                {
                    var CSVConfig = new CSVConfig.CsvConfiguration(CultureInfo.CurrentCulture)
                    {
                        Delimiter       = ",",
                        HasHeaderRecord = true
                    };
                    CSVConfig.RegisterClassMap <FileTagModelMap>();


                    using var fileInfo = System.IO.File.OpenText(this.MetaDataCsvFile);

                    var csv = new CsvReader(fileInfo, CSVConfig);

                    this.MetadataList.AddRange(csv.GetRecords <FileTagModel>());
                }
            }
            catch (System.IO.FileNotFoundException fex)
            {
                LogError(fex, "Failed to reach CSV file");
            }

            try
            {
                var onlineLibrary = Library.GetList(this.ClientContext.Web, ol => ol.RootFolder, ol => ol.Title, ol => ol.EnableVersioning);
                if (onlineLibrary.EnableVersioning)
                {
                    onlineLibrary.UpdateListVersioning(false, false, true);
                }

                // Parse Top Directory, enumerate files and upload them to root folder
                if (this.UploadFiles)
                {
                    UploadFileToSharePointFolder(onlineLibrary.RootFolder, this.DirectoryPath);
                }

                // Loop through all folders (recursive) that exist within the folder supplied by the operator
                var firstLevelFolders = System.IO.Directory.GetDirectories(this.DirectoryPath, "*", System.IO.SearchOption.TopDirectoryOnly);
                foreach (var folder in firstLevelFolders)
                {
                    var createdFolder = PopulateSharePointFolderWithFiles(onlineLibrary.RootFolder, this.DirectoryPath, folder);
                    if (!createdFolder)
                    {
                        LogDebugging("Folder {0} was not created successfully.", folder);
                    }
                }
            }
            catch (Exception ex)
            {
                LogError(ex, "Failed in SetDirectoryUpload {0} directory", DirectoryPath);
            }
        }
示例#9
0
        public void RegisterClassMapNonGenericTest()
        {
            var config  = new CsvHelper.Configuration.CsvConfiguration(CultureInfo.InvariantCulture);
            var context = new CsvContext(config);

            Assert.Null(context.Maps[typeof(TestClass)]);
            context.RegisterClassMap(typeof(TestClassMappings));
            Assert.NotNull(context.Maps[typeof(TestClass)]);
        }
示例#10
0
        public void AddingMappingsWithNonGenericMethodTest()
        {
            var config  = new CsvHelper.Configuration.CsvConfiguration(CultureInfo.InvariantCulture);
            var context = new CsvContext(config);

            context.RegisterClassMap(typeof(TestClassMappings));

            Assert.Equal(2, context.Maps[typeof(TestClass)].MemberMaps.Count);
        }
示例#11
0
        public void AutoMapWithDefaultConstructor()
        {
            var      config = new CsvHelper.Configuration.CsvConfiguration(CultureInfo.InvariantCulture);
            ClassMap map    = config.AutoMap <SimpleReferenceHasNoDefaultConstructor>();

            Assert.AreEqual("Id", map.MemberMaps[0].Data.Names[0]);
            Assert.AreEqual("Name", map.ReferenceMaps[0].Data.Mapping.MemberMaps[0].Data.Names[0]);
            Assert.AreEqual("name", map.ReferenceMaps[0].Data.Mapping.ParameterMaps[0].Data.Name);
        }
        public void PropertyMapAccessTest()
        {
            var config = new CsvHelper.Configuration.CsvConfiguration(CultureInfo.InvariantCulture);

            config.RegisterClassMap <AMap>();
            config.Maps.Find <A>().Map(m => m.AId).Ignore();

            Assert.AreEqual(true, config.Maps[typeof(A)].MemberMaps[0].Data.Ignore);
        }
        public void MapMultipleTypesTest()
        {
            var config = new CsvHelper.Configuration.CsvConfiguration(CultureInfo.InvariantCulture);

            config.RegisterClassMap <AMap>();
            config.RegisterClassMap <BMap>();

            Assert.IsNotNull(config.Maps[typeof(A)]);
            Assert.IsNotNull(config.Maps[typeof(B)]);
        }
示例#14
0
            public APrivateMap()
            {
                var config = new CsvHelper.Configuration.CsvConfiguration(CultureInfo.InvariantCulture)
                {
                    IncludePrivateMembers = true,
                    MemberTypes           = MemberTypes.Fields
                };

                AutoMap(config);
            }
        public void UnregisterClassNonMapGenericTest()
        {
            var config = new CsvHelper.Configuration.CsvConfiguration(CultureInfo.InvariantCulture);

            Assert.IsNull(config.Maps[typeof(TestClass)]);
            config.RegisterClassMap(typeof(TestClassMappings));
            Assert.IsNotNull(config.Maps[typeof(TestClass)]);

            config.UnregisterClassMap(typeof(TestClassMappings));
            Assert.IsNull(config.Maps[typeof(TestClass)]);
        }
示例#16
0
        public void AutoMapEnumerableTest()
        {
            var config = new CsvHelper.Configuration.CsvConfiguration(CultureInfo.InvariantCulture);

            try
            {
                config.AutoMap(typeof(List <string>));
                Assert.Fail();
            }
            catch (ConfigurationException) { }
        }
示例#17
0
        public void AutoMapWithNoDefaultConstructor()
        {
            var config  = new CsvHelper.Configuration.CsvConfiguration(CultureInfo.InvariantCulture);
            var context = new CsvContext(config);
            var map     = context.AutoMap <SimpleHasNoDefaultConstructorReferenceHasNoDefaultConstructor>();

            Assert.Equal("Id", map.MemberMaps[0].Data.Names[0]);
            Assert.Equal("id", map.ParameterMaps[0].Data.Names[0]);
            Assert.Equal("name", map.ParameterMaps[1].ConstructorTypeMap.ParameterMaps[0].Data.Names[0]);
            Assert.Equal("Name", map.ReferenceMaps[0].Data.Mapping.MemberMaps[0].Data.Names[0]);
            Assert.Equal("name", map.ReferenceMaps[0].Data.Mapping.ParameterMaps[0].Data.Names[0]);
        }
示例#18
0
        public void AutoMapWithNestedHeaders()
        {
            var config = new CsvHelper.Configuration.CsvConfiguration(CultureInfo.InvariantCulture)
            {
                ReferenceHeaderPrefix = (type, name) => $"{name}."
            };
            var map = config.AutoMap <Nested>();

            Assert.AreEqual("Simple1.Id", map.ReferenceMaps[0].Data.Mapping.MemberMaps[0].Data.Names[0]);
            Assert.AreEqual("Simple1.Name", map.ReferenceMaps[0].Data.Mapping.MemberMaps[1].Data.Names[0]);
            Assert.AreEqual("Simple2.Id", map.ReferenceMaps[1].Data.Mapping.MemberMaps[0].Data.Names[0]);
            Assert.AreEqual("Simple2.Name", map.ReferenceMaps[1].Data.Mapping.MemberMaps[1].Data.Names[0]);
        }
        public void EnsureReaderAndParserConfigIsAreSameTest()
        {
            using (var stream = new MemoryStream())
                using (var reader = new StreamReader(stream))
                {
                    var csvReader = new CsvReader(reader, CultureInfo.InvariantCulture);

                    Assert.AreSame(csvReader.Configuration, csvReader.Parser.Configuration);

                    var config = new CsvHelper.Configuration.CsvConfiguration(CultureInfo.InvariantCulture);
                    var parser = new CsvParser(reader, config);
                    csvReader = new CsvReader(parser);

                    Assert.AreSame(csvReader.Configuration, csvReader.Parser.Configuration);
                }
        }
示例#20
0
        public static CsvHelper.Configuration.CsvConfiguration GetConfiguration()
        {
            var cfg = new CsvHelper.Configuration.CsvConfiguration();

            cfg.TrimFields              = true;
            cfg.TrimHeaders             = true;
            cfg.SkipEmptyRecords        = false;
            cfg.IgnoreBlankLines        = true;
            cfg.IgnoreReadingExceptions = false;
            cfg.ThrowOnBadData          = true;
            cfg.WillThrowOnMissingField = false;
            cfg.IgnoreHeaderWhiteSpace  = true;
            cfg.HasHeaderRecord         = true;
            cfg.IsHeaderCaseSensitive   = false;
            cfg.Quote = '"';
            return(cfg);
        }
示例#21
0
    public void Write(Stream stream, DatabaseViewModel?database)
    {
        if (database is null)
        {
            return;
        }

        using var writer = new StringWriter();

        var configuration = new CSV.Configuration.CsvConfiguration(CultureInfo.CurrentCulture)
        {
            Delimiter = CultureInfo.CurrentCulture.TextInfo.ListSeparator
        };

        using (var csvWriter = new CSV.CsvWriter(writer, configuration))
        {
            // Columns

            csvWriter.WriteField(database.IdColumnName);
            foreach (var column in database.Columns)
            {
                csvWriter.WriteField(column.Name);
            }
            csvWriter.NextRecord();

            // Records

            foreach (var record in database.Records)
            {
                csvWriter.WriteField(record.Id);
                foreach (var value in record.Values)
                {
                    csvWriter.WriteField(value.Content);
                }
                csvWriter.NextRecord();
            }
        }

        var csv = writer.ToString();

        var fileSystem = _serviceProvider.GetService <IFileSystem>();

        fileSystem?.WriteUtf8Text(stream, csv);
    }
        /// <summary>
        /// Queries the reporting endpoint with the specified filters and interpolated classes
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="U"></typeparam>
        /// <param name="reportingFilters"></param>
        /// <param name="betaEndPoint"></param>
        /// <returns></returns>
        private ICollection <T> QueryBetaOrCSVMap <T, U>(QueryFilter reportingFilters, bool betaEndPoint = false)
            where T : JSONResult
            where U : CSVConfig.ClassMap
        {
            var successOrWillTry = false;
            var results          = new List <T>();

            if (betaEndPoint)
            {
                // Switch to JSON Output
                try
                {
                    reportingFilters.FormattedOutput = ReportUsageFormatEnum.JSON;

                    var activityresults = ResponseReader.RetrieveData <T>(reportingFilters);
                    results.AddRange(activityresults);
                    successOrWillTry = true;
                }
                catch (Exception ex)
                {
                    Logger.LogError(ex, $"Failed for JSON Format with message {ex.Message}");
                }
            }

            if (!successOrWillTry)
            {
                // Switch to CSV Output
                reportingFilters.FormattedOutput = ReportUsageFormatEnum.Default;
                reportingFilters.BetaEndPoint    = false;
                var CSVConfig = new CSVConfig.CsvConfiguration(CultureInfo.CurrentCulture)
                {
                    Delimiter       = ",",
                    HasHeaderRecord = true
                };
                CSVConfig.RegisterClassMap <U>();
                var resultscsv = new CSV.CsvReader(ResponseReader.RetrieveDataAsStream(reportingFilters), CSVConfig);
                results.AddRange(resultscsv.GetRecords <T>());
            }

            Logger.LogInformation($"Found {results.Count} while querying successOrWillTry:{successOrWillTry}");

            return(results);
        }
        public void AddGetRemoveTest()
        {
            var config        = new CsvHelper.Configuration.CsvConfiguration(CultureInfo.InvariantCulture);
            var customOptions = new TypeConverterOptions
            {
                Formats = new string[] { "custom" },
            };

            config.TypeConverterOptionsCache.AddOptions <string>(customOptions);
            var options = config.TypeConverterOptionsCache.GetOptions <string>();

            Assert.AreEqual(customOptions.Formats, options.Formats);

            config.TypeConverterOptionsCache.RemoveOptions <string>();

            options = config.TypeConverterOptionsCache.GetOptions <string>();

            Assert.AreNotEqual(customOptions.Formats, options.Formats);
        }
        public static void ResetConfiguration(CsvConfiguration csvConfiguration           = null,
                                              ManifestConfiguration manifestConfiguration = null, Assembly assembly = null)
        {
            Assembly = assembly;

            CsvConfiguration = csvConfiguration ?? new CsvConfiguration(new System.Globalization.CultureInfo("en-US"))
            {
                TrimOptions      = TrimOptions.Trim,
                IgnoreBlankLines = true
            };

            ManifestConfiguration = manifestConfiguration ?? new ManifestConfiguration
            {
                Delimiter          = ".",
                DelimiterFieldName = "{delimiter}",
                Extension          = "csv",
                ExtensionFieldName = "{extension}",
                ResourceFieldName  = "{resource}",
                Format             = "{delimiter}{resource}{delimiter}{extension}"
            };
        }
示例#25
0
    private static IEnumerable <string[]> ReadFields(Stream stream)
    {
        using var reader = new StreamReader(stream);

        var configuration = new CSV.Configuration.CsvConfiguration(CultureInfo.CurrentCulture)
        {
            Delimiter     = CultureInfo.CurrentCulture.TextInfo.ListSeparator,
            AllowComments = true,
            Comment       = '#'
        };

        using var csvParser = new CSV.CsvParser(reader, configuration);
        while (csvParser.Read())
        {
            var fields = csvParser.Record;
            if (fields is null)
            {
                break;
            }
            yield return(fields);
        }
    }
示例#26
0
 /// <summary>
 /// Creates a new CSV writer using the given <see cref="TextWriter"/>.
 /// </summary>
 /// <param name="writer">The <see cref="StreamWriter"/> use to write the CSV file.</param>
 /// <param name="configuration">The configuration.</param>
 /// <param name="leaveOpen">true to leave the writer open after the CsvWriter object is disposed, otherwise false.</param>
 public CsvWriter(TextWriter writer, Configuration.CsvConfiguration configuration, bool leaveOpen) : this(new CsvSerializer(writer, configuration, leaveOpen))
 {
 }
        public ActionResult Upload(HttpPostedFileWrapper file)
        {
            if (file == null)
            {
                var model = new ClientsIndexModel();
                ViewBag.ImportApprovalStatusError = "Please select a file.";
                return(View("Index", model));
            }
            var id = Guid.NewGuid();

            string fileName = System.IO.Path.Combine(System.IO.Path.GetTempPath(), id.ToString());

            var csvConf = new CsvHelper.Configuration.CsvConfiguration()
            {
                IsStrictMode     = false,
                IsCaseSensitive  = false,
                SkipEmptyRecords = true
            };

            csvConf.ClassMapping <ApprovalStatusCsvMap>();



            using (var csvReader = new CsvHelper.CsvReader(new System.IO.StreamReader(file.InputStream), csvConf))
            {
                var updatedAt = DateTime.Now;
                var updatedBy = this.Permissions.User.Id;

                var csvChunkSize = 10000;
                var recordIndex  = 1;

                Dictionary <int, int> fsas = new Dictionary <int, int>();

                using (var db = new ccEntities())
                {
                    db.Imports.AddObject(new CC.Data.Import()
                    {
                        Id        = id,
                        StartedAt = DateTime.Now,
                        UserId    = this.Permissions.User.Id
                    });
                    db.SaveChanges();

                    var q = (from fs in db.FundStatuses
                             join a in db.ApprovalStatuses on fs.ApprovalStatusName equals a.Name
                             select new
                    {
                        fsid = fs.Id,
                        asid = a.Id
                    }
                             );
                    foreach (var intem in q)
                    {
                        fsas.Add(intem.fsid, intem.asid);
                    }
                }



                foreach (var csvChunk in csvReader.GetRecords <ImportClient>().Split(csvChunkSize))
                {
                    string connectionString = System.Data.SqlClient.ConnectionStringHelper.GetProviderConnectionString();

                    using (var sqlBulk = new System.Data.SqlClient.SqlBulkCopy(connectionString, SqlBulkCopyOptions.KeepNulls))
                    {
                        foreach (var record in csvChunk)
                        {
                            record.RowIndex = recordIndex++;
                            record.ImportId = id;
                            if (record.FundStatusId.HasValue && fsas.ContainsKey(record.FundStatusId.Value))
                            {
                                record.ApprovalStatusId = fsas[record.FundStatusId.Value];
                            }
                            record.UpdatedAt   = updatedAt;
                            record.UpdatedById = updatedBy;
                        }

                        var dataTable = csvChunk.ToDataTable();
                        var q         = dataTable.Columns.OfType <System.Data.DataColumn>().Where(f => f.DataType == typeof(Int32)).Select(f => new
                        {
                            c      = f.ColumnName,
                            values = dataTable.Rows.OfType <System.Data.DataRow>().Select((r, i) => r[f.ColumnName])
                        });

                        sqlBulk.DestinationTableName = "ImportClients";
                        sqlBulk.NotifyAfter          = 1000;
                        sqlBulk.ColumnMappings.Add("ClientId", "ClientId");
                        sqlBulk.ColumnMappings.Add("FundStatusId", "FundStatusId");
                        sqlBulk.ColumnMappings.Add("RowIndex", "RowIndex");
                        sqlBulk.ColumnMappings.Add("ImportId", "ImportId");
                        sqlBulk.ColumnMappings.Add("UpdatedAt", "UpdatedAt");
                        sqlBulk.ColumnMappings.Add("UpdatedById", "UpdatedById");

                        sqlBulk.SqlRowsCopied += (s, e) =>
                        {
                            System.Diagnostics.Debug.Write(e.RowsCopied);
                        };

                        sqlBulk.WriteToServer(dataTable);
                    }
                }
            }

            return(RedirectToAction("Preview", new { id = id }));
        }
示例#28
0
    void OnGUI()
    {
        GUI.skin.box.wordWrap = true;

        //Window size
        Rect winRect  = new Rect((Screen.width - Screen.width * windowRatio) / 2, (Screen.height - Screen.height * windowRatio) / 2, Screen.width * windowRatio, Screen.height * windowRatio);
        Rect smallWin = new Rect((Screen.width - Screen.width * (windowRatio / 2)) / 2, (Screen.height - Screen.height * (windowRatio / 2)) / 2, winRect.width / 2, winRect.height / 2);

        //Content of the main menu
        if (showMenu)
        {
            GUI.Box(winRect, "Picross");

            //Play button to start puzzles
            if (GUI.Button(new Rect(winRect.x + winRect.width - 170, winRect.y + winRect.height - 60, 150, 40), "Play"))
            {
                showMenu = false;
                gridManager.NewPuzzle();
            }
        }

        //Content of the win screen
        if (showPuzWin)
        {
            GUI.Box(winRect, "Puzzle Complete! \n" + "Time: " + gridManager.timer.ToString());

            //Next puzzle button
            if (GUI.Button(new Rect(winRect.x + winRect.width - 170, winRect.y + winRect.height - 60, 150, 40), "Next Puzzle"))
            {
                showPuzWin = false;
                gridManager.NewPuzzle();
                resultsSaved = false;
            }

            //Results button
            if (GUI.Button(new Rect(winRect.x + 20, winRect.y + winRect.height - 60, 150, 40), "Results"))
            {
                //Close this screen, open final screen
                showPuzWin = false;
                showFin    = true;
            }
        }

        //Content of the loss screen
        if (showPuzLoss)
        {
            GUI.Box(winRect, "Puzzle Failed.");

            //Next puzzle button
            if (GUI.Button(new Rect(winRect.x + winRect.width - 170, winRect.y + winRect.height - 60, 150, 40), "Next Puzzle"))
            {
                showPuzLoss = false;
                gridManager.NewPuzzle();
                resultsSaved = false;
            }

            //Results button
            if (GUI.Button(new Rect(winRect.x + 20, winRect.y + winRect.height - 60, 150, 40), "Results"))
            {
                showPuzLoss = false;
                showFin     = true;
            }
        }

        //Final window, lists number of wins, losses and average time to both.
        if (showFin)
        {
            GUI.Box(winRect, "Results \n" + "Puzzles completed: " + gridManager.wins.ToString() + "\nPuzzles failed: " + gridManager.losses.ToString() + " \nAverage Time: " + gridManager.timeAvg + " \nATTF: " + gridManager.attf);

            if (GUI.Button(new Rect(winRect.x + winRect.width - 170, winRect.y + winRect.height - 60, 150, 40), "Save"))
            {
                //Create the data record
                var results = new List <ResultsRecord>
                {
                    new ResultsRecord {
                        PuzzlesCompleted = gridManager.wins, PuzzlesFailed = gridManager.losses, AverageTime = gridManager.timeAvg, ATTF = gridManager.attf
                    }
                };

                // the file name should be Picross_results.csv in the program file
                string path = ".\\Picross_results.csv";

                try
                {
                    //If the file doesn't exist
                    if (!File.Exists(path))
                    {
                        //Create the file
                        using (var writer = new StreamWriter(path))
                            using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
                            {
                                csv.WriteRecords(results);
                            }
                        message = AppDomain.CurrentDomain.BaseDirectory + path;
                    }
                    //If the file does exist
                    else
                    {
                        //Append the re cord to the existing file
                        var csvConfig = new CsvHelper.Configuration.CsvConfiguration(CultureInfo.InvariantCulture)
                        {
                            HasHeaderRecord = false
                        };

                        using (var stream = File.Open(path, FileMode.Append))
                            using (var writer = new StreamWriter(stream))
                                using (var csv = new CsvWriter(writer, csvConfig)) { csv.WriteRecords(results); }
                        message = AppDomain.CurrentDomain.BaseDirectory + path;
                    }

                    resultsSaved = true;
                    showSave     = true;
                }
                catch (Exception e)
                {
                    message   = e.Message;
                    showDebug = true;
                }
            }
            if (GUI.Button(new Rect(winRect.x + 20, winRect.y + winRect.height - 60, 150, 40), "Quit"))
            {
                //resultsSaved is always false until saving is implemented
                if (!resultsSaved)
                {
                    showSmall = true;
                }
                else
                {
                    //For debugging/developing purposes, check if how its running and close that
#if UNITY_EDITOR
                    if (UnityEditor.EditorApplication.isPlaying)
                    {
                        UnityEditor.EditorApplication.ExitPlaymode();
                    }
                    else
                    {
                        Application.Quit();
                    }
#else
                    Application.Quit();
#endif
                }
            }
        }

        //Show small is for confirming quitting the application without saving results.
        if (showSmall)
        {
            GUI.Box(smallWin, "Results have not been saved, Quit anyway?");
            if (GUI.Button(new Rect(smallWin.x + 10, smallWin.y + smallWin.height - 30, 70, 20), "Yes"))
            {
                //For debugging/developing purposes, check if how its running and close that
#if UNITY_EDITOR
                if (UnityEditor.EditorApplication.isPlaying)
                {
                    UnityEditor.EditorApplication.ExitPlaymode();
                }
                else
                {
                    Application.Quit();
                }
#else
                Application.Quit();
#endif
            }
            if (GUI.Button(new Rect(smallWin.x + smallWin.width - 80, smallWin.y + smallWin.height - 30, 70, 20), "No"))
            {
                showSmall = false;
            }
        }

        //Show results save confirmation window
        if (showSave)
        {
            GUI.Box(smallWin, "Results saved at " + message);
            if (GUI.Button(new Rect(smallWin.x + (smallWin.width / 2), smallWin.y + smallWin.height - 30, 70, 20), "Ok"))
            {
                showSave = false;
            }
        }

        if (showDebug)
        {
            GUI.Box(smallWin, message);
            if (GUI.Button(new Rect(smallWin.x + (smallWin.width / 2), smallWin.y + smallWin.height - 30, 70, 20), "Ok"))
            {
                showSave = false;
            }
        }
    }
示例#29
0
        public void EndBufferTest()
        {
            var config = new CsvHelper.Configuration.CsvConfiguration
            {
                BufferSize = 12
            };
            using( var stream = new MemoryStream() )
            using( var writer = new StreamWriter( stream ) )
            using( var reader = new StreamReader( stream ) )
            using( var parser = new CsvParser( reader, config ) )
            {
                writer.Write( "111,222,333\r\naaa,bbb,ccc\r\n" );
                writer.Flush();
                stream.Position = 0;

                // BufferSize is set to 12 to force a buffer read after the first \r
                var row = parser.Read();

                Assert.IsNotNull( row );
                Assert.AreEqual( "111", row[0] );
                Assert.AreEqual( "222", row[1] );
                Assert.AreEqual( "333", row[2] );

                row = parser.Read();

                Assert.IsNotNull( row );
                Assert.AreEqual( "aaa", row[0] );
                Assert.AreEqual( "bbb", row[1] );
                Assert.AreEqual( "ccc", row[2] );
            }
        }
示例#30
0
 /// <summary>
 /// Creates a new serializer using the given <see cref="TextWriter"/>
 /// and <see cref="CsvHelper.Configuration.CsvConfiguration"/>.
 /// </summary>
 /// <param name="writer">The <see cref="TextWriter"/> to write the CSV file data to.</param>
 /// <param name="configuration">The configuration.</param>
 public CsvSerializer(TextWriter writer, Configuration.CsvConfiguration configuration) : this(writer, configuration, false)
 {
 }
示例#31
0
 /// <summary>
 /// Creates a new serializer using the given <see cref="TextWriter"/>
 /// and <see cref="CsvHelper.Configuration.CsvConfiguration"/>.
 /// </summary>
 /// <param name="writer">The <see cref="TextWriter"/> to write the CSV file data to.</param>
 /// <param name="configuration">The configuration.</param>
 /// <param name="leaveOpen">true to leave the reader open after the CsvReader object is disposed, otherwise false.</param>
 public CsvSerializer(TextWriter writer, Configuration.CsvConfiguration configuration, bool leaveOpen)
 {
     context = new WritingContext(writer, configuration, leaveOpen);
 }