Esempio n. 1
0
            public string GetData(T item)
            {
                string result;

                object data = func(item);

                if (data == null)
                {
                    result = string.Empty;
                }
                else
                {
                    result = data.ToString();
                }

                if (excelSanitizer.IsThreat(result))
                {
                    string message = string.Format(
                        "A potentially dangerous string was identified and sanitised when writing CSV data. The value was \"{0}\".",
                        result);
                    Trace.TraceWarning(message);
                    result = excelSanitizer.Sanitize(result);
                }

                if (formatAsText)
                {
                    // Assuming the CSV file will be opened in Excel, write the value as a formula. E.g. ="The value".
                    // Any double quotes already present in the string are escaped with double double-quotes.
                    result = string.Format("=\"{0}\"", result.Replace("\"", "\"\""));
                }

                return(result);
            }
Esempio n. 2
0
        public void CsvWriter_WithExcelSanitizer_SanitizesValues()
        {
            // Arrange
            IExcelSanitizer sanitizer = A.Fake <IExcelSanitizer>();

            A.CallTo(() => sanitizer.IsThreat("Bad String")).Returns(true);
            A.CallTo(() => sanitizer.Sanitize("Bad String")).Returns("Sanitized Bad String");

            CsvWriter <string> writer = new CsvWriter <string>(sanitizer);

            writer.DefineColumn("Column 1", x => x);

            List <string> data = new List <string>()
            {
                "Good String", "Bad String"
            };

            // Act
            string csv = writer.Write(data);

            // Assert
            string expectedValue =
                "Column 1" + Environment.NewLine +
                "Good String" + Environment.NewLine +
                "Sanitized Bad String" + Environment.NewLine;

            Assert.Equal(expectedValue, csv);
        }