/
Program.cs
385 lines (333 loc) · 14.7 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using CsvHelper;
using System.Dynamic;
using Microsoft.SqlServer.Management.Smo;
using System.Data.SqlClient;
using System.Configuration;
namespace CsvToSqlUtility
{
class Program
{
static void Main( string[] args )
{
// Get Source Folder
string sourceFolder = ConfigurationManager.AppSettings["SourceFolder"];
if ( string.IsNullOrWhiteSpace(sourceFolder)) throw new Exception( "Missing Source Folder Application Setting" );
var dir = new DirectoryInfo( sourceFolder );
if ( dir == null ) throw new Exception( "Invalid Source Folder Directory" );
var files = dir.GetFiles( "*.csv" );
if ( !files.Any() ) throw new Exception( "There are not any *.csv files in the source folder" );
// Get Database
var configConnectionString = ConfigurationManager.ConnectionStrings["DbContext"];
if ( configConnectionString == null ) throw new Exception( "Missing Connection String" );
string connectionString = configConnectionString.ConnectionString;
if ( string.IsNullOrWhiteSpace( connectionString ) ) throw new Exception( "Invalid Connection String" );
var sqlConn = new SqlConnection( connectionString );
if ( sqlConn == null ) throw new Exception( "Invalid Connection String" );
var serverCon = new Microsoft.SqlServer.Management.Common.ServerConnection( sqlConn );
Server server = new Server( serverCon );
var db = server.Databases[sqlConn.Database];
if ( db == null ) throw new Exception( "Invalid Database Name in Connection String" );
string dbTablePrefix = ConfigurationManager.AppSettings["DbTablePrefix"];
if ( string.IsNullOrWhiteSpace( dbTablePrefix ) ) dbTablePrefix = "_csv_";
Console.Write( $"Starting Import [{DateTime.Now.ToShortTimeString()}]" );
// Process Files
foreach ( var file in files )
{
Console.WriteLine();
Console.Write( string.Format( "Processing {0}...", file.Name ) );
// Read all the records
var records = GetRecords( file.FullName );
// Determine the best field types
var fields = GetFields( records );
// Create the table
string tableName = dbTablePrefix + Path.GetFileNameWithoutExtension( file.FullName );
CreateTable( db, tableName, fields );
// Import records
InsertRecords( connectionString, tableName, fields, records );
}
Console.WriteLine();
Console.Write( $"Finished Import [{DateTime.Now.ToShortTimeString()}]" );
Console.ReadLine();
}
private static List<dynamic> GetRecords( string filePath )
{
if ( File.Exists( filePath ) )
{
using ( var s = File.OpenText( filePath ) )
{
var config = new CsvHelper.Configuration.Configuration();
config.BadDataFound = null;
var reader = new CsvReader( s, config );
reader.Configuration.HasHeaderRecord = true;
var records = reader.GetRecords<dynamic>().ToList();
return records;
}
}
return null;
}
private static List<CsvFieldInfo> GetFields( List<dynamic> records )
{
var fields = new List<CsvFieldInfo>();
if ( records != null && records.Any() )
{
ExpandoObject obj = records[0];
foreach ( var p in obj )
{
fields.Add( new CsvFieldInfo { Name = p.Key } );
}
foreach ( dynamic record in records )
{
foreach ( var p in record )
{
var fieldInfo = fields.FirstOrDefault( f => f.Name == p.Key );
if ( fieldInfo != null )
{
string value = p.Value.ToString().Trim();
if ( value != null && value != string.Empty )
{
int len = value.Length;
fieldInfo.MaxLength = len > fieldInfo.MaxLength ? len : fieldInfo.MaxLength;
// Check to see if data can be parsed
if ( fieldInfo.IsDateTime )
{
DateTime datetime;
if ( !DateTime.TryParse( value, out datetime ) )
{
fieldInfo.IsDateTime = false;
}
}
if ( fieldInfo.IsBool )
{
bool boolValue;
if ( !bool.TryParse( value, out boolValue ) )
{
fieldInfo.IsBool = false;
}
}
if ( fieldInfo.IsInteger )
{
int number;
if ( !int.TryParse( value, out number ) )
{
fieldInfo.IsInteger = false;
}
}
if ( !fieldInfo.IsInteger && fieldInfo.IsDecimal )
{
decimal number;
if ( !decimal.TryParse( value, out number ) )
{
fieldInfo.IsDecimal = false;
}
}
}
}
}
}
foreach ( var field in fields )
{
var l = field.MaxLength;
field.MaxLength = 50 - ( l % 50 ) + l;
}
}
return fields;
}
private static void CreateTable( Database database, string tableName, List<CsvFieldInfo> fields )
{
var tbl = new Table( database, tableName );
foreach ( var fieldInfo in fields )
{
var dataType = fieldInfo.MaxLength >= 2000 ? DataType.VarCharMax : DataType.VarChar( fieldInfo.MaxLength );
if ( fieldInfo.IsDecimal )
{
dataType = DataType.Decimal( 2, 18 );
}
if ( fieldInfo.IsInteger )
{
dataType = DataType.Int;
}
if ( fieldInfo.IsDateTime )
{
dataType = DataType.DateTime;
}
if ( fieldInfo.IsBool )
{
dataType = DataType.Bit;
}
var col = new Column( tbl, fieldInfo.Name, dataType );
tbl.Columns.Add( col );
}
tbl.Create();
}
private static void InsertRecords( string connectionString, string tableName, List<CsvFieldInfo> fields, List<dynamic> records )
{
var insertPrefix = new StringBuilder();
foreach ( var field in fields )
{
if ( insertPrefix.Length == 0 )
{
insertPrefix.AppendFormat( "INSERT INTO [{0}] ( [{1}]", tableName, field.Name );
}
else
{
insertPrefix.AppendFormat( ", [{0}]", field.Name );
}
}
insertPrefix.AppendFormat( " ){0} VALUES ", Environment.NewLine );
using ( SqlConnection connection = new SqlConnection( connectionString ) )
{
connection.Open();
int iRec = 0;
string msg = string.Empty;
int msgLen = 0;
var insertRows = new StringBuilder();
foreach ( var record in records )
{
if ( insertRows.Length > 0 )
{
insertRows.Append( "," + Environment.NewLine );
}
var insertFields = new StringBuilder();
foreach ( var p in record )
{
var fieldInfo = fields.FirstOrDefault( f => f.Name == p.Key );
if ( fieldInfo != null )
{
string value = p.Value.ToString().Trim();
if ( insertFields.Length > 0 )
{
insertFields.Append( ", " );
}
if ( fieldInfo.IsBool )
{
if ( value == null || value == "" )
{
value = "NULL";
}
else
{
if ( bool.TryParse( value, out bool selected ) )
{
value = selected ? "1" : "0";
}
else
{
value = "NULL";
}
}
}
else if ( fieldInfo.IsDateTime )
{
if ( value == null || value == "" )
{
value = "NULL";
}
else
{
if ( DateTime.TryParse( value, out DateTime selected ) )
{
value = "'" + selected.ToString() + "'";
}
else
{
value = "NULL";
}
}
}
else if ( fieldInfo.IsInteger )
{
if ( value == null || value == "" )
{
value = "NULL";
}
else
{
if ( !int.TryParse( value, out int selected ) )
{
value = "NULL";
}
}
}
else if ( fieldInfo.IsDecimal )
{
if ( value == null || value == "" )
{
value = "NULL";
}
else
{
if ( decimal.TryParse( value, out decimal selected ) )
{
value = selected.ToString();
}
else
{
value = "NULL";
}
}
}
else
{
if ( value == null )
{
value = "";
}
value = "'" + value.Replace( "'", "''" ) + "'";
}
insertFields.Append( value );
}
}
insertRows.AppendFormat( "( {0} )", insertFields.ToString() );
iRec++;
if ( iRec % 100 == 0 )
{
if ( msgLen > 0 )
{
var bs = new String( '\b', msgLen );
Console.Write( bs );
}
msg = $"{iRec:N0} of {records.Count:N0}";
msgLen = msg.Length;
Console.Write( msg );
using ( SqlCommand querySaveStaff = new SqlCommand( insertPrefix.ToString() + insertRows.ToString(), connection ) )
{
querySaveStaff.ExecuteNonQuery();
}
insertRows = new StringBuilder();
}
}
if ( msgLen > 0 )
{
var bs = new String( '\b', msgLen );
Console.Write( bs );
}
msg = $"{iRec:N0} of {records.Count:N0}";
msgLen = msg.Length;
Console.Write( msg );
if ( insertRows.Length > 0 )
{
using ( SqlCommand querySaveStaff = new SqlCommand( insertPrefix.ToString() + insertRows.ToString(), connection ) )
{
querySaveStaff.ExecuteNonQuery();
}
}
connection.Close();
}
}
private class CsvFieldInfo
{
public string Name { get; set; }
public int MaxLength { get; set; } = 0;
public bool IsDateTime { get; set; } = true;
public bool IsInteger { get; set; } = true;
public bool IsDecimal { get; set; } = true;
public bool IsBool { get; set; } = true;
}
}
}