├── LICENSE ├── README.md ├── .gitignore └── CsvSerializer.cs /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Antonio Leonardo de Abreu Freire 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # C# CSV Serializer 2 | 3 | This C# class giving a simplest way with performance serializer functionalities to manipulate CSV strings; several test cases were executed in order to treat the particularities of a sequence of CSV characters; in this publication, is considered stable, it is implemented in productive environments with large scale of data generated or consumed in CSV daily. 4 | 5 | Specifications: This 'CsvSerializer' class enjoy best pratices of Design Patterns result in a powerful CSV serialization and deserialization functionality, giving to Developer other data sctructure options like [DataTable](https://docs.microsoft.com/en-us/dotnet/api/system.data.datatable) object or a custom C# Plain Old CLR Object (Entity class) with capacity to define column name and order exihbition. 6 | Both methods 'Serialize' and 'Deserialize' contains on important argument named "csvSeparator" to gives flexible generation of CSV. 7 | 8 | Bellow are examples of using the 'CsvSerializer': 9 | 10 | ## 1) Serialize 11 | 12 | #### 1.1) Using a POCO (Plain Old CLR Objects) class, with native .NET [DataMemberAtribute](https://docs.microsoft.com/en-us/dotnet/api/system.runtime.serialization.datamemberattribute) (attribute is not mandatory): 13 | ```cs 14 | public class ExampleModel 15 | { 16 | [DataMember(Name = "My Property 1", Order = 4)] 17 | public string MyProperty1 { get; set; } 18 | 19 | [DataMember(Name = "My Property 2", Order = 1)] 20 | public string MyProperty2 { get; set; } 21 | 22 | [DataMember(Name = "Any Property", Order = 3)] 23 | public string AnyProperty { get; set; } 24 | 25 | [DataMember(Name = "Property comments change order", Order = 6)] 26 | public string PropertyWithChangeOrder { get; set; } 27 | 28 | [DataMember(Name = "Some Property", Order = 2)] 29 | public string SomeProperty { get; set; } 30 | 31 | [DataMember(Name = "Capacity Property", Order = 5)] 32 | public string CapacityProperty { get; set; } 33 | } 34 | ``` 35 | 36 | #### 1.2) Create a collection based on Entity class above: 37 | ```cs 38 | List list = new List(); 39 | 40 | list.Add(new ExampleModel() 41 | { 42 | AnyProperty = "any 1", 43 | CapacityProperty = "20", 44 | MyProperty1 = "my 1", 45 | MyProperty2 = "my 2", 46 | PropertyWithChangeOrder = "Comments to change and or texts...", 47 | SomeProperty = "some 1" 48 | }); 49 | list.Add(new ExampleModel() 50 | { 51 | AnyProperty = "any yna", 52 | CapacityProperty = "45", 53 | MyProperty1 = "11 my", 54 | MyProperty2 = "22 my", 55 | PropertyWithChangeOrder = "Another comment to change contents!", 56 | SomeProperty = "2 some 1" 57 | }); 58 | list.Add(new ExampleModel() 59 | { 60 | AnyProperty = @"\/any yna\/", 61 | CapacityProperty = "57", 62 | MyProperty1 = "1my1", 63 | MyProperty2 = "2my2", 64 | PropertyWithChangeOrder = "Texts with comments to rich all tests", 65 | SomeProperty = "some3" 66 | }); 67 | ``` 68 | 69 | #### 1.3) Execute Serialize method, and *Voilà*! 70 | ```cs 71 | string csvSerialized = CsvSerializer.Serialize(';', list); 72 | ``` 73 | 74 | #### 1.4) This is the result of the string bulk: 75 | ```csv 76 | My Property 2;Some Property;Any Property;My Property 1;Capacity Property;Property comments change order; 77 | 78 | my 2;some 1;any 1;my 1;20;Comments to change and or texts...; 79 | 80 | 22 my;2 some 1;any yna;11 my;45;Another comment to change contents!; 81 | 82 | 2my2;some3;\/any yna\/;1my1;57;Texts with comments to rich all tests; 83 | ``` 84 | 85 | #### 1.5) Pear attention: if you want to save '*.csv*' file, remeber to use Encoding UTF8, according [CSV specifications](https://en.wikipedia.org/wiki/Comma-separated_values): 86 | ```cs 87 | File.WriteAllText(@"\\path\to\save\file.csv", csvSerialized, Encoding.UTF8); 88 | ``` 89 | ---------------------------- 90 | 91 | ## 2) Deserialize 92 | 93 | #### 2.1) The developer may consume any '*.csv*' file by sugestted instruction: 94 | ```cs 95 | string csvToDeserialize = File.ReadAllText(@"\\path\to\read\file.csv"); 96 | ``` 97 | 98 | #### 2.2) And, if dont know the data column arrange, may populate a DataTable objet: 99 | ```cs 100 | DataTable dtDeserialized = CsvSerializer.Deserialize(';', csvToDeserialize); 101 | ``` 102 | 103 | #### 2.2) Or populate a collection of Entity class (like array or list): 104 | ```cs 105 | ExampleModel[] arrayCollection = CsvSerializer.Deserialize(';', csvToDeserialize).ToArray(); 106 | List listCollection = CsvSerializer.Deserialize(';', csvToDeserialize).ToList(); 107 | ``` 108 | ---------------------- 109 | ## License 110 | 111 | [View MIT license](https://github.com/antonio-leonardo/CsvSerializer/blob/master/LICENSE) 112 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Build results 17 | [Dd]ebug/ 18 | [Dd]ebugPublic/ 19 | [Rr]elease/ 20 | [Rr]eleases/ 21 | x64/ 22 | x86/ 23 | [Aa][Rr][Mm]/ 24 | [Aa][Rr][Mm]64/ 25 | bld/ 26 | [Bb]in/ 27 | [Oo]bj/ 28 | [Ll]og/ 29 | 30 | # Visual Studio 2015/2017 cache/options directory 31 | .vs/ 32 | # Uncomment if you have tasks that create the project's static files in wwwroot 33 | #wwwroot/ 34 | 35 | # Visual Studio 2017 auto generated files 36 | Generated\ Files/ 37 | 38 | # MSTest test Results 39 | [Tt]est[Rr]esult*/ 40 | [Bb]uild[Ll]og.* 41 | 42 | # NUNIT 43 | *.VisualState.xml 44 | TestResult.xml 45 | 46 | # Build Results of an ATL Project 47 | [Dd]ebugPS/ 48 | [Rr]eleasePS/ 49 | dlldata.c 50 | 51 | # Benchmark Results 52 | BenchmarkDotNet.Artifacts/ 53 | 54 | # .NET Core 55 | project.lock.json 56 | project.fragment.lock.json 57 | artifacts/ 58 | 59 | # StyleCop 60 | StyleCopReport.xml 61 | 62 | # Files built by Visual Studio 63 | *_i.c 64 | *_p.c 65 | *_h.h 66 | *.ilk 67 | *.meta 68 | *.obj 69 | *.iobj 70 | *.pch 71 | *.pdb 72 | *.ipdb 73 | *.pgc 74 | *.pgd 75 | *.rsp 76 | *.sbr 77 | *.tlb 78 | *.tli 79 | *.tlh 80 | *.tmp 81 | *.tmp_proj 82 | *_wpftmp.csproj 83 | *.log 84 | *.vspscc 85 | *.vssscc 86 | .builds 87 | *.pidb 88 | *.svclog 89 | *.scc 90 | 91 | # Chutzpah Test files 92 | _Chutzpah* 93 | 94 | # Visual C++ cache files 95 | ipch/ 96 | *.aps 97 | *.ncb 98 | *.opendb 99 | *.opensdf 100 | *.sdf 101 | *.cachefile 102 | *.VC.db 103 | *.VC.VC.opendb 104 | 105 | # Visual Studio profiler 106 | *.psess 107 | *.vsp 108 | *.vspx 109 | *.sap 110 | 111 | # Visual Studio Trace Files 112 | *.e2e 113 | 114 | # TFS 2012 Local Workspace 115 | $tf/ 116 | 117 | # Guidance Automation Toolkit 118 | *.gpState 119 | 120 | # ReSharper is a .NET coding add-in 121 | _ReSharper*/ 122 | *.[Rr]e[Ss]harper 123 | *.DotSettings.user 124 | 125 | # JustCode is a .NET coding add-in 126 | .JustCode 127 | 128 | # TeamCity is a build add-in 129 | _TeamCity* 130 | 131 | # DotCover is a Code Coverage Tool 132 | *.dotCover 133 | 134 | # AxoCover is a Code Coverage Tool 135 | .axoCover/* 136 | !.axoCover/settings.json 137 | 138 | # Visual Studio code coverage results 139 | *.coverage 140 | *.coveragexml 141 | 142 | # NCrunch 143 | _NCrunch_* 144 | .*crunch*.local.xml 145 | nCrunchTemp_* 146 | 147 | # MightyMoose 148 | *.mm.* 149 | AutoTest.Net/ 150 | 151 | # Web workbench (sass) 152 | .sass-cache/ 153 | 154 | # Installshield output folder 155 | [Ee]xpress/ 156 | 157 | # DocProject is a documentation generator add-in 158 | DocProject/buildhelp/ 159 | DocProject/Help/*.HxT 160 | DocProject/Help/*.HxC 161 | DocProject/Help/*.hhc 162 | DocProject/Help/*.hhk 163 | DocProject/Help/*.hhp 164 | DocProject/Help/Html2 165 | DocProject/Help/html 166 | 167 | # Click-Once directory 168 | publish/ 169 | 170 | # Publish Web Output 171 | *.[Pp]ublish.xml 172 | *.azurePubxml 173 | # Note: Comment the next line if you want to checkin your web deploy settings, 174 | # but database connection strings (with potential passwords) will be unencrypted 175 | *.pubxml 176 | *.publishproj 177 | 178 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 179 | # checkin your Azure Web App publish settings, but sensitive information contained 180 | # in these scripts will be unencrypted 181 | PublishScripts/ 182 | 183 | # NuGet Packages 184 | *.nupkg 185 | # The packages folder can be ignored because of Package Restore 186 | **/[Pp]ackages/* 187 | # except build/, which is used as an MSBuild target. 188 | !**/[Pp]ackages/build/ 189 | # Uncomment if necessary however generally it will be regenerated when needed 190 | #!**/[Pp]ackages/repositories.config 191 | # NuGet v3's project.json files produces more ignorable files 192 | *.nuget.props 193 | *.nuget.targets 194 | 195 | # Microsoft Azure Build Output 196 | csx/ 197 | *.build.csdef 198 | 199 | # Microsoft Azure Emulator 200 | ecf/ 201 | rcf/ 202 | 203 | # Windows Store app package directories and files 204 | AppPackages/ 205 | BundleArtifacts/ 206 | Package.StoreAssociation.xml 207 | _pkginfo.txt 208 | *.appx 209 | 210 | # Visual Studio cache files 211 | # files ending in .cache can be ignored 212 | *.[Cc]ache 213 | # but keep track of directories ending in .cache 214 | !?*.[Cc]ache/ 215 | 216 | # Others 217 | ClientBin/ 218 | ~$* 219 | *~ 220 | *.dbmdl 221 | *.dbproj.schemaview 222 | *.jfm 223 | *.pfx 224 | *.publishsettings 225 | orleans.codegen.cs 226 | 227 | # Including strong name files can present a security risk 228 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 229 | #*.snk 230 | 231 | # Since there are multiple workflows, uncomment next line to ignore bower_components 232 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 233 | #bower_components/ 234 | 235 | # RIA/Silverlight projects 236 | Generated_Code/ 237 | 238 | # Backup & report files from converting an old project file 239 | # to a newer Visual Studio version. Backup files are not needed, 240 | # because we have git ;-) 241 | _UpgradeReport_Files/ 242 | Backup*/ 243 | UpgradeLog*.XML 244 | UpgradeLog*.htm 245 | ServiceFabricBackup/ 246 | *.rptproj.bak 247 | 248 | # SQL Server files 249 | *.mdf 250 | *.ldf 251 | *.ndf 252 | 253 | # Business Intelligence projects 254 | *.rdl.data 255 | *.bim.layout 256 | *.bim_*.settings 257 | *.rptproj.rsuser 258 | *- Backup*.rdl 259 | 260 | # Microsoft Fakes 261 | FakesAssemblies/ 262 | 263 | # GhostDoc plugin setting file 264 | *.GhostDoc.xml 265 | 266 | # Node.js Tools for Visual Studio 267 | .ntvs_analysis.dat 268 | node_modules/ 269 | 270 | # Visual Studio 6 build log 271 | *.plg 272 | 273 | # Visual Studio 6 workspace options file 274 | *.opt 275 | 276 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 277 | *.vbw 278 | 279 | # Visual Studio LightSwitch build output 280 | **/*.HTMLClient/GeneratedArtifacts 281 | **/*.DesktopClient/GeneratedArtifacts 282 | **/*.DesktopClient/ModelManifest.xml 283 | **/*.Server/GeneratedArtifacts 284 | **/*.Server/ModelManifest.xml 285 | _Pvt_Extensions 286 | 287 | # Paket dependency manager 288 | .paket/paket.exe 289 | paket-files/ 290 | 291 | # FAKE - F# Make 292 | .fake/ 293 | 294 | # JetBrains Rider 295 | .idea/ 296 | *.sln.iml 297 | 298 | # CodeRush personal settings 299 | .cr/personal 300 | 301 | # Python Tools for Visual Studio (PTVS) 302 | __pycache__/ 303 | *.pyc 304 | 305 | # Cake - Uncomment if you are using it 306 | # tools/** 307 | # !tools/packages.config 308 | 309 | # Tabs Studio 310 | *.tss 311 | 312 | # Telerik's JustMock configuration file 313 | *.jmconfig 314 | 315 | # BizTalk build output 316 | *.btp.cs 317 | *.btm.cs 318 | *.odx.cs 319 | *.xsd.cs 320 | 321 | # OpenCover UI analysis results 322 | OpenCover/ 323 | 324 | # Azure Stream Analytics local run output 325 | ASALocalRun/ 326 | 327 | # MSBuild Binary and Structured Log 328 | *.binlog 329 | 330 | # NVidia Nsight GPU debugger configuration file 331 | *.nvuser 332 | 333 | # MFractors (Xamarin productivity tool) working folder 334 | .mfractor/ 335 | 336 | # Local History for Visual Studio 337 | .localhistory/ 338 | 339 | # BeatPulse healthcheck temp database 340 | healthchecksdb -------------------------------------------------------------------------------- /CsvSerializer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Text; 3 | using System.Linq; 4 | using System.Data; 5 | using System.Reflection; 6 | using System.Collections.Generic; 7 | using System.Runtime.Serialization; 8 | 9 | namespace CsvSerialization 10 | { 11 | /// 12 | /// Abstract class that share all Serializations execution, 13 | /// only Serialize and Deserialize 14 | /// 15 | /// Maybe POCO class or any object that provides collections 16 | public abstract class CsvSerializerAbstraction 17 | where TEntity : class 18 | { 19 | /// 20 | /// 21 | /// 22 | protected internal readonly char _csvSeparator; 23 | 24 | /// 25 | /// 26 | /// 27 | protected internal static string CsvSeparator { get; private set; } 28 | 29 | /// 30 | /// / 31 | /// 32 | /// 33 | public CsvSerializerAbstraction(char csvSeparator) 34 | { 35 | this._csvSeparator = csvSeparator; 36 | CsvSeparator = this._csvSeparator.ToString(); 37 | } 38 | 39 | /// 40 | /// Abstraction of method to Serialize routine 41 | /// 42 | /// 43 | /// 44 | protected abstract string CustomSerialize(params TEntity[] collection); 45 | 46 | /// 47 | /// Abstraction to Deserialize csv string format 48 | /// 49 | /// 50 | /// 51 | protected abstract IEnumerable CustomDeserialize(string csvString); 52 | } 53 | 54 | /// 55 | /// Concrete partial class with DataRow class implementation 56 | /// 57 | public sealed partial class CsvSerializer : CsvSerializerAbstraction 58 | { 59 | /// 60 | /// This class only be instanciable like a private behavior 61 | /// 62 | private CsvSerializer(char csvSeparator) : base(csvSeparator) 63 | { 64 | } 65 | 66 | #region ' Serialize ' 67 | 68 | /// 69 | /// Public method to return the result of string serialized in CSV format 70 | /// 71 | /// Datatable with data array to be serialized 72 | /// System.String 73 | public static string Serialize(char csvSeparator, DataTable collection) 74 | { 75 | StringBuilder sbColumns = new StringBuilder(); 76 | 77 | for (int i = 0; i < collection.Columns.Count; i++) 78 | { 79 | if (i == collection.Columns.Count - 1) 80 | { 81 | sbColumns.AppendLine(collection.Columns[i].ColumnName + csvSeparator); 82 | } 83 | else 84 | { 85 | sbColumns.Append(collection.Columns[i].ColumnName).Append(csvSeparator); 86 | } 87 | } 88 | return sbColumns.ToString() + (new CsvSerializer(csvSeparator)).CustomSerialize(collection.Rows.Cast().ToArray()); 89 | } 90 | 91 | /// 92 | /// Overriden method with all instructions to perform serialization from DataTable 93 | /// 94 | /// Array of DataRows 95 | /// System.String 96 | protected override string CustomSerialize(params DataRow[] collection) 97 | { 98 | StringBuilder sbRows = new StringBuilder(); 99 | DataColumnCollection columns = collection.FirstOrDefault().Table.Columns; 100 | for (int i = 0; i < collection.Length; i++) 101 | { 102 | for (int j = 0; j < columns.Count; j++) 103 | { 104 | string data = null; 105 | if (columns[j].DataType == typeof(string)) 106 | { 107 | data = collection[i][columns[j]].ToString().Replace("\r", "").Replace("\n", "").Replace(CsvSeparator, " "); 108 | } 109 | if (j == columns.Count - 1) 110 | { 111 | if (!string.IsNullOrWhiteSpace(data)) 112 | { 113 | sbRows.AppendLine(data + CsvSeparator); 114 | } 115 | else 116 | { 117 | sbRows.AppendLine((collection[i][columns[j]]) + CsvSeparator); 118 | } 119 | } 120 | else 121 | { 122 | if (!string.IsNullOrWhiteSpace(data)) 123 | { 124 | sbRows.Append(data).Append(CsvSeparator); 125 | } 126 | else 127 | { 128 | sbRows.Append((collection[i][columns[j]])).Append(CsvSeparator); 129 | } 130 | } 131 | } 132 | } 133 | return sbRows.ToString(); 134 | } 135 | 136 | #endregion 137 | 138 | #region ' Deserialize ' 139 | 140 | /// 141 | /// Public method to return a DataTable from string CSV 142 | /// 143 | /// 144 | /// System.Data.DataTable 145 | public static DataTable Deserialize(char csvSeparator, string csvString) 146 | { 147 | return (new CsvSerializer(csvSeparator)).CustomDeserialize(csvString).ToArray().CopyToDataTable(); 148 | } 149 | 150 | /// 151 | /// Overriden method to execute performance deserialization from string CSV 152 | /// 153 | /// 154 | /// 155 | protected override IEnumerable CustomDeserialize(string csvString) 156 | { 157 | DataTable dt = new DataTable(); 158 | string[] csvLines = csvString.Split('\n'); 159 | string[] columnsName = csvLines[0].Split(base._csvSeparator); 160 | for (int i = 0; i < columnsName.Length - 1; i++) 161 | { 162 | dt.Columns.Add(columnsName[i]); 163 | } 164 | return this.GetArrayOfDataTableRows(dt, csvLines); 165 | } 166 | 167 | /// 168 | /// Private method to make iteration on data rows of string, by yield looping 169 | /// 170 | /// Defined parent scope DataTable 171 | /// Array that represents rows of CSV file 172 | /// 173 | private IEnumerable GetArrayOfDataTableRows(DataTable dt, params string[] csvLines) 174 | { 175 | DataRow dr = null; 176 | for (int i = 0; i < csvLines.Length - 1; i++) 177 | { 178 | if (i > 0) 179 | { 180 | dr = dt.NewRow(); 181 | string[] columnsName = csvLines[0].Split(base._csvSeparator); 182 | string[] columnsValue = csvLines[i].Split(base._csvSeparator); 183 | for (int j = 0; j < columnsValue.Length - 1; j++) 184 | { 185 | dr[columnsName[j]] = columnsValue[j]; 186 | } 187 | yield return dr; 188 | } 189 | } 190 | } 191 | 192 | #endregion 193 | 194 | } 195 | 196 | /// 197 | /// Concrete partial class with Generic class definition 198 | /// 199 | public sealed partial class CsvSerializer : CsvSerializerAbstraction 200 | where TEntity : class 201 | { 202 | /// 203 | /// 204 | /// 205 | private CsvSerializer(char csvSeparator) : base(csvSeparator) 206 | { 207 | } 208 | 209 | #region ' Serialize ' 210 | 211 | /// 212 | /// Public method to return the result of string serialized in CSV format 213 | /// 214 | /// Generic that represents the entity collection 215 | /// Datatable with data array to be serialized 216 | /// System.String 217 | public static string Serialize(char csvSeparator, List collection) 218 | { 219 | return Serialize(csvSeparator, collection.ToArray()); 220 | } 221 | 222 | /// 223 | /// Overloaded method with all instructions to perform serialization from DataTable 224 | /// 225 | /// Array of DataRows 226 | /// System.String 227 | public static string Serialize(char csvSeparator, params TEntity[] collection) 228 | { 229 | return (new CsvSerializer(csvSeparator)).CustomSerialize(collection); 230 | } 231 | 232 | /// 233 | /// Overriden method with all instructions to perform serialization from DataTable 234 | /// 235 | /// Array of Generic definition 236 | /// System.String 237 | protected override string CustomSerialize(params TEntity[] collection) 238 | { 239 | StringBuilder sbColumns = new StringBuilder(); 240 | StringBuilder sbRows = new StringBuilder(); 241 | 242 | KeyValuePair[] pairs = typeof(TEntity).GetElementsResult().ToArray(); 243 | 244 | this.MountCsvColumns(ref sbColumns, pairs); 245 | 246 | for (int j = 0; j < collection.Length; j++) 247 | { 248 | this.MountCsvRows(ref sbRows, collection[j], pairs); 249 | } 250 | return sbColumns.ToString() + sbRows.ToString(); 251 | } 252 | 253 | /// 254 | /// This method mounts all CSV columns based on CSV specifications 255 | /// 256 | /// Defined Generic 257 | /// StringBUilder with correctly string concats 258 | /// Tuple that represents parity of the entity property with this respective Attribute 259 | private void MountCsvColumns(ref StringBuilder sbColumns, params KeyValuePair[] pairs) 260 | { 261 | for (int i = 0; i < pairs.Length; i++) 262 | { 263 | if (i == pairs.Length - 1) 264 | { 265 | sbColumns.AppendLine(pairs[i].Value.Name + CsvSeparator); 266 | } 267 | else 268 | { 269 | sbColumns.Append(pairs[i].Value.Name).Append(CsvSeparator); 270 | } 271 | } 272 | } 273 | 274 | /// 275 | /// This method mounts all CSV rows based on CSV specifications 276 | /// 277 | /// Defined Generic 278 | /// StringBUilder with correctly string concats 279 | /// The generic object represents a CSV line row 280 | /// Parity that represents property and attribute 281 | private void MountCsvRows(ref StringBuilder sbRows, TEntity obj, params KeyValuePair[] pairs) 282 | { 283 | for (int i = 0; i < pairs.Length; i++) 284 | { 285 | string result = (null != obj.GetType().GetProperty(pairs[i].Key.Name).GetValue(obj, null)) ? 286 | Convert.ChangeType(obj.GetType().GetProperty(pairs[i].Key.Name).GetValue(obj, null), Type.GetTypeCode(pairs[i].Key.PropertyType)).ToString() : string.Empty; 287 | result = result.Replace("\r", "").Replace("\n", "").Replace(CsvSeparator, " "); 288 | if (i == pairs.Length - 1) 289 | { 290 | 291 | sbRows.AppendLine(result + CsvSeparator); 292 | } 293 | else 294 | { 295 | sbRows.Append(result).Append(CsvSeparator); 296 | } 297 | } 298 | } 299 | 300 | /// 301 | /// Validator to check if contais a property on array of collected properties 302 | /// 303 | /// class property 304 | /// properties without error 305 | /// System.Boolean 306 | private bool ContainsPropertyInPropsWithoutExclude(PropertyInfo property, List propsWithoutError) 307 | { 308 | bool result = false; 309 | foreach (PropertyInfo prop in propsWithoutError) 310 | { 311 | if (prop.Name == property.Name) 312 | { 313 | result = true; 314 | } 315 | } 316 | return result; 317 | } 318 | 319 | /// 320 | /// Mount exception phrase and corresponding error columns 321 | /// 322 | /// Ordered collection of attributes 323 | /// Array of properties 324 | /// System.String 325 | private string MountInnerExcetionMessage(List ordered, params PropertyInfo[] properties) 326 | { 327 | StringBuilder sb = new StringBuilder(); 328 | sb.AppendLine("Listing properties without the 'DataMemberAttribute' attribute:"); 329 | List propsWithoutError = new List(); 330 | 331 | foreach (DataMemberAttribute item in ordered) 332 | { 333 | for (int i = 0; i < properties.Length; i++) 334 | { 335 | DataMemberAttribute att = properties[i].GetCustomAttribute(typeof(DataMemberAttribute)) as DataMemberAttribute; 336 | if (null != att && item.Name == att.Name) 337 | { 338 | propsWithoutError.Add(properties[i]); 339 | } 340 | } 341 | } 342 | 343 | for (int j = 0; j < properties.Length; j++) 344 | { 345 | if (!ContainsPropertyInPropsWithoutExclude(properties[j], propsWithoutError)) 346 | { 347 | sb.AppendLine(" '" + properties[j] + "' "); 348 | } 349 | } 350 | return sb.ToString(); 351 | } 352 | 353 | #endregion 354 | 355 | #region ' Deserialize ' 356 | 357 | /// 358 | /// Public method to give collection result from Deserialization 359 | /// 360 | /// string with read CSV 361 | /// Collection of Generic 362 | public static IEnumerable Deserialize(char csvSeparator, string csvString) 363 | { 364 | return (new CsvSerializer(csvSeparator)).CustomDeserialize(csvString); 365 | } 366 | 367 | /// 368 | /// Overriden method to implements analisys throwing all generic type properties 369 | /// 370 | /// Defined generic 371 | /// Csv on string format 372 | /// Collection of Generic 373 | protected override IEnumerable CustomDeserialize(string csvString) 374 | { 375 | string[] arrayLinesCsv = csvString.Split('\n'); 376 | string[] columnsName = arrayLinesCsv[0].Split(base._csvSeparator); 377 | Type tp = typeof(TEntity); 378 | PropertyInfo[] props = tp.GetProperties(); 379 | for (int i = 1; i < arrayLinesCsv.Length - 1; i++) 380 | { 381 | object instance = Activator.CreateInstance(tp); 382 | string[] columnsValue = arrayLinesCsv[i].Split(base._csvSeparator); 383 | for (int j = 0; j < columnsValue.Length - 1; j++) 384 | { 385 | PropertyInfo prop = null; 386 | for (int x = 0; x < props.Length; x++) 387 | { 388 | DataMemberAttribute att = props[x].GetCustomAttribute(typeof(DataMemberAttribute)) as DataMemberAttribute; 389 | if ((null != att && att.Name == columnsName[j]) || columnsName[j] == props[x].Name) 390 | { 391 | prop = props[x]; 392 | } 393 | if (null != prop) 394 | { 395 | prop.SetValue(instance, Convert.ChangeType(columnsValue[j], Type.GetTypeCode(prop.PropertyType)), null); 396 | } 397 | } 398 | } 399 | yield return (instance as TEntity); 400 | } 401 | } 402 | 403 | #endregion 404 | 405 | } 406 | } --------------------------------------------------------------------------------