-
Notifications
You must be signed in to change notification settings - Fork 0
/
XmlFunctions.cs
376 lines (363 loc) · 10.6 KB
/
XmlFunctions.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
using System;
using System.Windows.Forms;
using System.Data;
using System.IO;
namespace DBTableMover
{
/// <summary>
/// methods for creating scripts from XML files
/// </summary>
public class XmlFunctions
{
public XmlFunctions()
{
}
DataSet xmlData = new DataSet();
string tableName = "";
string tableScript = "";
string valueScript = "";
/// <summary>
/// opens an XML file (xml or xsd) and reads the xml schema from the file. if it's XML it also reads the data.
/// </summary>
/// <param name="newFileName">name of the file to read from</param>
/// <returns>DataSet with the schema and/or data from the file</returns>
public DataSet OpenXmlToDataSet(string newFileName)
{
FileInfo file = new FileInfo(newFileName);
if (file.Extension.ToLower() == ".xml")
{
FileStream XMLFILE = new FileStream(newFileName, FileMode.Open, FileAccess.Read, FileShare.Read);
xmlData.ReadXml(XMLFILE);
XMLFILE.Close();
}
if (file.Extension.ToLower() == ".xsd")
{
FileStream XMLFILE = new FileStream(newFileName, FileMode.Open, FileAccess.Read, FileShare.Read);
xmlData.ReadXmlSchema(XMLFILE);
XMLFILE.Close();
}
return xmlData;
}
/// <summary>
/// creates an SQL Table Creation script for the passed in table name
/// </summary>
/// <param name="fileName"></param>
/// <param name="tableName"></param>
/// <returns></returns>
public string CreateTableScript(string fileName, string tableName)
{
this.tableScript = "";
try
{
// declare variables for specific items
string columnName = "";
string columnType = "";
int columnLen = 0;
string columnNull = "";
// start building script
this.xmlData = this.OpenXmlToDataSet(fileName);
this.tableName = tableName;
// insert drop and create scripts
tableScript = "if exists(select name from sysobjects where name='" + tableName + "' and type='U')\r\nBEGIN\r\ndrop table " + tableName + "\r\nEND\r\nGO\r\n\r\n";
tableScript += "create table [dbo].[" + tableName + "](\r\n";
// grab column values
int cols = 0;
foreach(DataColumn row in xmlData.Tables[tableName].Columns)
{
string columnOnly = "";
// there's more columns past the first then add this
if(cols >= 1)
columnOnly += ",\r\n";
columnName = row.ColumnName.ToString();
columnType = row.DataType.ToString();
columnLen = Convert.ToInt32(row.MaxLength.ToString());
if(row.AllowDBNull.ToString().ToUpper() == "TRUE")
columnNull = "NULL";
else
columnNull = "NOT NULL";
// create the script for column
columnOnly += "[" + columnName + "] ";
switch(columnType)
{
case "System.DateTime":
{
columnOnly += "[DateTime]";
break;
}
case "System.String":
{
columnOnly += "[nvarchar]";
if(row.MaxLength==-1)
columnOnly += "(MAX)";
else
columnOnly += "(" + row.MaxLength + ")";
break;
}
case "System.Boolean":
{
columnOnly += "[bit]";
break;
}
case "System.Int64":
{
columnOnly += "[int]";
break;
}
case "System.Int32":
{
columnOnly += "[int]";
break;
}
case "System.Int16":
{
columnOnly += "[int]";
break;
}
case "System.Decimal":
{
columnOnly += "[decimal]";
break;
}
case "System.Double":
{
columnOnly += "[double]";
break;
}
case "System.Single":
{
columnOnly += "[single]";
break;
}
case "System.Byte":
{
columnOnly += "[byte]";
break;
}
case "System.Byte[]":
{
columnOnly += "[byte[]]";
break;
}
case "System.Guid":
{ // don't want a value here, since the insert will auto add one.
// really shouldn't have this value anyway, since the keyrow should handle this.
break;
}
}
// if it's the identity set it as one
if(xmlData.Tables[tableName].Columns[row.ColumnName].AutoIncrement)
{
int seed = Convert.ToInt32(xmlData.Tables[tableName].Columns[row.ColumnName].AutoIncrementSeed);
int inc = Convert.ToInt32(xmlData.Tables[tableName].Columns[row.ColumnName].AutoIncrementStep);
columnOnly += " IDENTITY(" + seed + "," + inc + ")";
}
columnOnly += " " + columnNull;
// add one to the number of columns
cols++;
// add column text to script
tableScript += columnOnly;
}
// now add the primary key if there is one
string PrimaryKeyClause = CheckForPrimaryKey(tableName);
if(PrimaryKeyClause.Length > 0)
tableScript += PrimaryKeyClause;
// now close the script for the table
tableScript += "\r\n) ON [PRIMARY] \r\n GO \r\n";
}
catch(Exception x)
{
WriteLog(x.Message);
}
return tableScript;
}
/// <summary>
/// creates an insert script for each row in the selected table
/// </summary>
/// <param name="fileName">name of the XML file to write scripts for</param>
/// <param name="tableName">name of the selected table</param>
/// <returns></returns>
public string CreateValueScript(string fileName, string tableName)
{
this.valueScript = "";
try
{
// grab data
this.xmlData = this.OpenXmlToDataSet(fileName);
this.tableName = tableName;
///now start creating the script for the values
// check table for data
int rowCount = xmlData.Tables[tableName].Rows.Count;
if(rowCount==0)
{
MessageBox.Show("There is no data to script for.", "Empty Table...");
Exception x = new Exception("Empty Table");
throw(x);
}
// get table column name values
string columnNames = "";
DataRow columnRow = xmlData.Tables[tableName].Rows[0];
int c = 0;
foreach(DataColumn col in columnRow.Table.Columns)
{
if(col.AutoIncrement)
continue;
else
{
c++;
if(c==1)
columnNames += col.ColumnName.ToString();
else
columnNames += "," + col.ColumnName.ToString();
}
}
// now grab values and build SQL
foreach(DataRow row in xmlData.Tables[tableName].Rows)
{
int r = 0; // particular row column
valueScript += "INSERT INTO [dbo].[" + tableName + "] (" + columnNames + ") VALUES (";
int n = 0; // number of columns added to script
foreach(DataColumn col in row.Table.Columns)
{
if(col.AutoIncrement)
{
r++;
continue;
}
else
{
if(n>0)
valueScript += ",";
string colType = col.DataType.ToString();
// WriteLog("colType :" + colType);
// WriteLog("ToString : " + col.ToString());
// WriteLog(" \n");
if(Convert.IsDBNull(row[r]))
valueScript += "NULL";
else
{
switch(colType)
{
case "System.DateTime":
{
DateTime dbdate = Convert.ToDateTime(row[r]);
valueScript += "'" + dbdate.ToString("yyyyMMdd HH:mm:ss") + "'";
break;
}
case "System.String":
case "System.Boolean":
case "System.Object":
{
string tempValue = row[r].ToString();
tempValue = tempValue.Replace("'", "''");
valueScript += "'" + tempValue.Trim() + "'";
break;
}
case "System.Int64":
{
valueScript += Convert.ToInt64(row[r]);
break;
}
case "System.Int32":
{
valueScript += Convert.ToInt32(row[r]);
break;
}
case "System.Int16":
{
valueScript += Convert.ToInt16(row[r]);
break;
}
case "System.Decimal":
{
valueScript += Convert.ToDecimal(row[r]);
break;
}
case "System.Double":
{
valueScript += Convert.ToDouble(row[r]);
break;
}
case "System.Single":
{
valueScript += Convert.ToSingle(row[r]);
break;
}
case "System.Byte":
{
valueScript += "'" + Convert.ToByte(row[r]) + "'";
break;
}
case "System.Byte[]":
{
valueScript += "0x";
string stringValue = Convert.ToString(row[r]);
foreach(char b in stringValue)
{
valueScript += Convert.ToByte(b);
}
break;
}
case "System.Guid":
{ // don't want a value here, since the insert will auto add one.
// really shouldn't have this value anyway, since the keyrow should handle this.
break;
}
}
}
// add one to the count of values added to valueScript
n++;
}
// add one to the column count
r++;
}
valueScript += ")\r\n\r\nGO\r\n\r\n";
}
}
catch(Exception x)
{
WriteLog(x.Message);
}
return valueScript;
}
/// <summary>
/// checks to see if the current table has a primary key, if so, creates a script to include in the table definition
/// </summary>
/// <param name="tableName">name of the table to check for a primary key</param>
/// <returns>PK creation script</returns>
private string CheckForPrimaryKey(string tableName)
{
string returnString = "";
// number of rows
DataColumn[] keys = xmlData.Tables[tableName].PrimaryKey;
if(keys.GetLength(0) > 0)
{
returnString += ",\r\nCONSTRAINT [PK_" + tableName + "] PRIMARY KEY CLUSTERED\r\n(";
string columnNames = "";
int count = 0;
// now cycle through and check for "PRIMARY KEY"
foreach(DataColumn row in keys)
{
//WriteLog(row["constraint_type"].ToString() + " Value : " + Convert.ToInt32(row["constraint_type"].ToString().IndexOf("RIMARY KEY",0)));
if((count == 0 & keys.Length == 1) || (count == (keys.Length-1)))
columnNames += "[" + row.ColumnName + "]";
else
columnNames += "[" + row.ColumnName + "],";
count++;
}
returnString += columnNames + " ASC\r\n";
returnString += ") ON [PRIMARY]\r\n";
return returnString;
}
else
return "";
}
/// <summary>
/// write debug information to a textfile
/// </summary>
/// <param name="message">message to send to log</param>
private void WriteLog(string message)
{
ProjectMethods.WriteLog("XmlFunctions", message);
}
}
}