PageRenderTime 21ms CodeModel.GetById 47ms RepoModel.GetById 0ms app.codeStats 1ms

/Ixsd2Db/SchemaGeneration/Create_Alter.cs

#
C# | 618 lines | 506 code | 94 blank | 18 comment | 141 complexity | c917e2ce89734fc773360ad926fdc37e MD5 | raw file
  1. /***
  2. * Ixsd2db - Infopath XSD to DB table create tool
  3. * CODEPLEX
  4. * AUTHER: SHARON JOSEPH
  5. * LEAD: MAULIK SONI
  6. **/
  7. using System;
  8. using System.Collections.Generic;
  9. using System.ComponentModel;
  10. using System.Data;
  11. using System.Drawing;
  12. using System.Linq;
  13. using System.Text;
  14. using System.Windows.Forms;
  15. using System.IO;
  16. using System.Data.SqlClient;
  17. using System.Xml;
  18. using System.Xml.Schema;
  19. namespace WindowsFormsApplication1
  20. {
  21. public partial class Create_Alter : Form
  22. {
  23. string connectionString = " ";
  24. SqlConnection sqlCon;
  25. DataTable dt = new DataTable();
  26. DataColumn col1, col2, col3;
  27. public Create_Alter()
  28. {
  29. InitializeComponent();
  30. txtpassword.PasswordChar = '*';
  31. dataGridView1.DataSource = dt;
  32. col1 = new DataColumn();
  33. col1.ColumnName = "Table Name";
  34. dt.Columns.Add(col1);
  35. col2 = new DataColumn();
  36. col2.ColumnName = "Operation";
  37. dt.Columns.Add(col2);
  38. col3 = new DataColumn();
  39. col3.ColumnName = "Field Names";
  40. dt.Columns.Add(col3);
  41. dataGridView1.Visible = false;
  42. }
  43. private void btnCreateAlter_Click(object sender, EventArgs e)
  44. {
  45. try
  46. {
  47. if (txtFormTableName.Text == "" || txtFilePath.Text == "" || connectionString.Trim() == "")
  48. {
  49. string message = "Please enter required fields";
  50. string caption = "Missing Values";
  51. MessageBoxButtons buttons = MessageBoxButtons.OK;
  52. DialogResult result;
  53. result = MessageBox.Show(this, message, caption, buttons);
  54. }
  55. else
  56. {
  57. dataGridView1.Visible = true;
  58. string fpath1 = "";
  59. fpath1 = txtFilePath.Text;
  60. string[] elementname = new string[10000];//for storing column names
  61. string[] elementnull = new string[10000];//for storing null or not null values
  62. string[] elementtype = new string[10000];//for storing data types
  63. int i = 0;
  64. int name = 0, type = 0, nul = 0;
  65. try
  66. {
  67. XmlTextReader reader = new XmlTextReader(fpath1);
  68. while (reader.Read())
  69. {
  70. switch (reader.NodeType)
  71. {
  72. case XmlNodeType.Element: // The node is an element.
  73. if (reader.Name == "xsd:element")
  74. {
  75. while (reader.MoveToNextAttribute()) // Read the attributes.
  76. {
  77. if (reader.AttributeCount > 1)//the very first xsd:element has the form name and no other attributes
  78. {
  79. if (reader.Name == "ref" || reader.Name == "minoccurs")
  80. {
  81. name = 0;
  82. }
  83. if (reader.Name == "name")
  84. {
  85. elementname[i] = reader.Value;
  86. name = 1;
  87. }
  88. if (reader.Name == "type")
  89. {
  90. string xsd = "xsd:"; //the type is always stored with a xsd: in the xsd files, so strip the xsd: before storing the type in the columntype array
  91. int firstcharacter12 = reader.Value.IndexOf(xsd);
  92. firstcharacter12 = firstcharacter12 + xsd.Length;
  93. string fieldtype12 = reader.Value.Substring(firstcharacter12);
  94. elementtype[i] = fieldtype12;
  95. type = 1;
  96. }
  97. if (reader.Name == "nillable")
  98. {
  99. elementnull[i] = reader.Value;
  100. nul = 1;
  101. }
  102. }
  103. else
  104. {
  105. name = 0;
  106. }
  107. }
  108. if (name == 1 && type == 0)
  109. {
  110. elementtype[i] = "Varchar(500)";
  111. }
  112. if (name == 1 && nul == 0)
  113. {
  114. elementnull[i] = "false";
  115. }
  116. if (name != 0)
  117. {
  118. i++;
  119. }
  120. name = 0;
  121. nul = 0;
  122. type = 0;
  123. }
  124. break;
  125. }
  126. }
  127. }
  128. catch (Exception ex)
  129. {
  130. MessageBox.Show(ex.Message);
  131. }
  132. string table = "";
  133. string commandString = "";
  134. string[] tablename = txtFormTableName.Text.Split(' '); //get the form name from user to construct the table name and split them into individual words to remove spaces
  135. if (tablename.Length > 1)
  136. {
  137. for (int a = 0; a < tablename.Length; a++)
  138. {
  139. for (int b = 0; b < tablename[a].Length; b++) //check each character in each word for symbols that are not accepted by SQL
  140. {
  141. string c = tablename[a];
  142. if (c[b] != '-')
  143. {
  144. table += c[b];
  145. }
  146. }
  147. if (tablename.Length - 1 != a)
  148. {
  149. table += "_";
  150. }
  151. }
  152. }
  153. else
  154. {
  155. table = txtFormTableName.Text; //if the form name is already just a single word, use that as the table name
  156. }
  157. //once the xsd is read, check if the table needs to be created or altered
  158. string[] tablenames = new string[10000];
  159. int t = 0;
  160. SqlDataReader myReader = null;
  161. SqlCommand myCommand = new SqlCommand("Select TABLE_NAME from Information_Schema.Tables", sqlCon); //get all the table names from the information schema table
  162. myReader = myCommand.ExecuteReader();
  163. while (myReader.Read())
  164. {
  165. tablenames[t] = myReader["TABLE_NAME"].ToString();
  166. t++;
  167. }
  168. myReader.Close();
  169. int alter = 0;
  170. for (int v = 0; v < t; v++)
  171. {
  172. if (tablenames[v].Trim() == table.Trim()) //if table already exists then alter the table
  173. {
  174. //create = 0;
  175. alter = 1;
  176. break;
  177. }
  178. }
  179. if (alter == 1)
  180. {
  181. //code to alter the table
  182. SqlDataReader myReader1 = null;
  183. string myCom;
  184. myCom = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.Columns where TABLE_NAME ='"; //get all the column names for the selected table
  185. myCom += table;
  186. myCom += "'";
  187. SqlCommand myCommand1 = new SqlCommand(myCom, sqlCon);
  188. myReader1 = myCommand1.ExecuteReader();
  189. string[] colnames = new string[10000];
  190. int t1 = 0;
  191. while (myReader1.Read()) //reading already existing column names within the database
  192. {
  193. t1++;
  194. colnames[t1] = myReader1["COLUMN_NAME"].ToString();
  195. }
  196. myReader1.Close();
  197. int yes = 0;
  198. int ge = 0;
  199. int e1 = i;
  200. //check against the column names read from the xsd file
  201. if (t1 != e1) //if there is a change in the xsd file as compared to the database - to avoid errorneous submissions by the user
  202. {
  203. if (t1 < e1) //to add a field - if the elements in xsd file is more than the columns in the database
  204. {
  205. txtusername.Text = "";
  206. for (int pe = 0; pe < e1; pe++)//for every column name read from the xsd file
  207. {
  208. for (ge = 1; ge <= t1; ge++) //for every column name fetched from the database
  209. {
  210. if (colnames[ge] == elementname[pe]) //if there is match set yes to 1
  211. {
  212. yes = 1;
  213. break;
  214. }
  215. }
  216. if (yes == 0) //if yes was never set to 1 for this particular element, then add the column
  217. {
  218. //found a new column name
  219. commandString = "Alter Table ";
  220. commandString += table;
  221. commandString += " ";
  222. commandString += "ADD";
  223. commandString += " ";
  224. commandString += elementname[pe];
  225. commandString += " ";
  226. //mapping data types from XSD file to suitable SQL data types
  227. if (elementtype[pe] == "integer")
  228. {
  229. commandString += "INT";
  230. }
  231. if (elementtype[pe] == "dateTime")
  232. {
  233. commandString += "date";
  234. }
  235. if (elementtype[pe] == "string" || elementtype[pe] == "requiredString")
  236. {
  237. commandString += "VARCHAR(MAX)";
  238. }
  239. if (elementtype[pe] == "boolean")
  240. {
  241. commandString += "BIT";
  242. }
  243. if (elementtype[pe] == "double")
  244. {
  245. commandString += "float";
  246. }
  247. if (elementtype[pe] == "time")
  248. {
  249. commandString += "nvarchar(50)";
  250. }
  251. if (elementtype[pe] != "boolean" && elementtype[pe] != "time" && elementtype[pe] != "string" && elementtype[pe] != "integer" && elementtype[pe] != "requiredString" && elementtype[pe] != "double" && elementtype[pe] != "dateTime")
  252. {
  253. commandString += elementtype[pe];
  254. }
  255. commandString += " ";
  256. if (elementnull[pe] == "true")
  257. {
  258. commandString += " ";
  259. commandString += "NOT NULL";
  260. }
  261. else
  262. {
  263. commandString += "NULL";
  264. }
  265. DataRow myNewRow;
  266. myNewRow = dt.NewRow();
  267. myNewRow[col1] = table;
  268. myNewRow[col2] = "Column Addition";
  269. myNewRow[col3] = elementname[pe];
  270. dt.Rows.Add(myNewRow);
  271. SqlCommand sqlCmd = new SqlCommand(commandString, sqlCon);
  272. sqlCmd = new SqlCommand(commandString, sqlCon);
  273. sqlCmd.ExecuteNonQuery();
  274. }
  275. else
  276. {
  277. yes = 0;
  278. }
  279. }
  280. string message = "Table Altered successfully - Columns were added";
  281. string caption = "Alter Success";
  282. MessageBoxButtons buttons = MessageBoxButtons.OK;
  283. DialogResult result;
  284. result = MessageBox.Show(this, message, caption, buttons);
  285. }
  286. if (e1 < t1)//to delete a field - if the number of columns in database is more than the number of elements in the xsd file
  287. {
  288. int pe;
  289. for (pe = 1; pe <= t1; pe++) //for every column name read from the database
  290. {
  291. for (ge = 0; ge < e1; ge++) //for every element name fetched from the xsd file
  292. {
  293. if (colnames[pe] == elementname[ge]) //check if the column name exists in the xsd file
  294. {
  295. yes = 1;
  296. // break;
  297. }
  298. }
  299. if (yes == 0) //if column name does not exist in the xsd file, delete the column
  300. {
  301. commandString = "Alter Table ";
  302. commandString += table;
  303. commandString += " ";
  304. commandString += "DROP Column";
  305. commandString += " ";
  306. commandString += colnames[pe];
  307. try
  308. {
  309. DataRow myNewRow;
  310. myNewRow = dt.NewRow();
  311. myNewRow[col1] = table;
  312. myNewRow[col2] = "Column Deletion";
  313. myNewRow[col3] = colnames[pe];
  314. dt.Rows.Add(myNewRow);
  315. SqlCommand sqlCmd = new SqlCommand(commandString, sqlCon);
  316. sqlCmd = new SqlCommand(commandString, sqlCon);
  317. sqlCmd.ExecuteNonQuery();
  318. }
  319. catch (Exception ex)
  320. {
  321. MessageBox.Show(ex.Message);
  322. }
  323. }
  324. else
  325. {
  326. yes = 0;
  327. }
  328. }
  329. string message = "Table Altered successfully - Columns were deleted";
  330. string caption = "Alter Success";
  331. MessageBoxButtons buttons = MessageBoxButtons.OK;
  332. DialogResult result;
  333. result = MessageBox.Show(this, message, caption, buttons);
  334. }
  335. }
  336. else
  337. {
  338. string message = "There were no changes detected in the xsd file - Did you forget generating a new XSD source file after making changes to the Infopath form?";
  339. string caption = "Erroneous Submission";
  340. MessageBoxButtons buttons = MessageBoxButtons.YesNo;
  341. DialogResult result;
  342. result = MessageBox.Show(this, message, caption, buttons);
  343. if (result == DialogResult.Yes)
  344. {
  345. //this.Close();
  346. string message1 = "Please update the XSD file and try again.";
  347. string caption1 = "Erroneous Submission";
  348. MessageBoxButtons buttons1 = MessageBoxButtons.OK;
  349. DialogResult result1;
  350. result1 = MessageBox.Show(this, message1, caption1, buttons1);
  351. }
  352. if (result == DialogResult.No)
  353. {
  354. string message1 = "There were still no changes detected in the xsd file. Please check the path where the XSD file resides and try again.";
  355. string caption1 = "Erroneous Submission";
  356. MessageBoxButtons buttons1 = MessageBoxButtons.OK;
  357. DialogResult result1;
  358. result1 = MessageBox.Show(this, message1, caption1, buttons1);
  359. }
  360. }
  361. }
  362. else//if table does not exist, create the table
  363. {
  364. commandString += "CREATE TABLE ";
  365. commandString += table;
  366. commandString += "(";
  367. //type conversions
  368. int e1 = i;
  369. e1--;
  370. for (int g = 0; g <= e1; g++)
  371. {
  372. commandString += elementname[g];
  373. commandString += " ";
  374. if (elementtype[g] == "integer")
  375. {
  376. commandString += "INT";
  377. }
  378. if (elementtype[g] == "dateTime")
  379. {
  380. commandString += "date";
  381. }
  382. if (elementtype[g] == "string" || elementtype[g] == "requiredString")
  383. {
  384. commandString += "VARCHAR(500)";
  385. }
  386. if (elementtype[g] == "boolean")
  387. {
  388. commandString += "BIT";
  389. }
  390. if (elementtype[g] == "double")
  391. {
  392. commandString += "float";
  393. }
  394. if (elementtype[g] == "time")
  395. {
  396. commandString += "nvarchar(50)";
  397. }
  398. if (elementtype[g] != "boolean" && elementtype[g] != "time" && elementtype[g] != "string" && elementtype[g] != "integer" && elementtype[g] != "requiredString" && elementtype[g] != "double" && elementtype[g] != "dateTime")
  399. {
  400. commandString += elementtype[g];
  401. }
  402. if (elementnull[g] == "false")
  403. {
  404. commandString += " ";
  405. commandString += "NOT NULL";
  406. }
  407. if (e1 != g)
  408. {
  409. commandString += ",";
  410. }
  411. }
  412. commandString += ")";
  413. //execute the query
  414. DataRow myNewRow;
  415. myNewRow = dt.NewRow();
  416. myNewRow[col1] = table;
  417. myNewRow[col2] = "Table Creation";
  418. myNewRow[col3] = " ";
  419. dt.Rows.Add(myNewRow);
  420. SqlCommand sqlCmd = new SqlCommand(commandString, sqlCon);
  421. sqlCmd = new SqlCommand(commandString, sqlCon);
  422. sqlCmd.ExecuteNonQuery();
  423. //sqlCon.Close();
  424. string message = "Table created successfully";
  425. string caption = "Success";
  426. MessageBoxButtons buttons = MessageBoxButtons.OK;
  427. DialogResult result;
  428. result = MessageBox.Show(this, message, caption, buttons);
  429. // this.Close();
  430. }
  431. }
  432. }
  433. catch (Exception ex)
  434. {
  435. MessageBox.Show(ex.Message);
  436. }
  437. }
  438. private void btnBrowse_Click(object sender, EventArgs e)
  439. {
  440. try
  441. {
  442. openFileDialog1.InitialDirectory = @"C:\";
  443. openFileDialog1.Title = "Select a File";
  444. openFileDialog1.Filter = "XSD files (*.xsd)|*.xsd";
  445. openFileDialog1.FileName = "";
  446. openFileDialog1.ShowDialog();
  447. if (openFileDialog1.FileName != "")
  448. {
  449. txtFilePath.Text = openFileDialog1.FileName;
  450. }
  451. }
  452. catch (Exception ex)
  453. {
  454. MessageBox.Show(ex.Message);
  455. }
  456. }
  457. private void btnTestConnection_Click(object sender, EventArgs e)
  458. {
  459. try
  460. {
  461. connectionString = txtconnectionString.Text;
  462. if (connectionString.Trim() == "")
  463. {
  464. connectionString = "Data Source=" + txtdatasource.Text.Trim() + ";Initial Catalog=" + txtdbname.Text.Trim() + ";User ID=" + txtusername.Text.Trim() + ";Password=" + txtpassword.Text.Trim();
  465. if (txtdatasource.Text.Trim() == "" && txtusername.Text.Trim() == "" && txtpassword.Text.Trim() == "" && txtdbname.Text.Trim() == "")
  466. {
  467. string message = "You did not enter a Database Connection String.";
  468. string caption = "No Connection string specified";
  469. MessageBoxButtons buttons = MessageBoxButtons.OK;
  470. DialogResult result;
  471. result = MessageBox.Show(this, message, caption, buttons);
  472. connectionString = "";
  473. }
  474. else
  475. {
  476. try
  477. {
  478. sqlCon = new SqlConnection(connectionString);
  479. sqlCon.Open();
  480. string message = "Connection Success";
  481. string caption = "Successful Connection";
  482. MessageBoxButtons buttons = MessageBoxButtons.OK;
  483. DialogResult result;
  484. result = MessageBox.Show(this, message, caption, buttons);
  485. }
  486. catch (Exception e2)
  487. {
  488. string message = e2.Message;
  489. string caption = "Connection Failed";
  490. MessageBoxButtons buttons = MessageBoxButtons.OK;
  491. DialogResult result;
  492. result = MessageBox.Show(this, message, caption, buttons);
  493. }
  494. }
  495. }
  496. else
  497. {
  498. try
  499. {
  500. sqlCon = new SqlConnection(connectionString);
  501. sqlCon.Open();
  502. string message = "Connection Success";
  503. string caption = "Successful Connection";
  504. MessageBoxButtons buttons = MessageBoxButtons.OK;
  505. DialogResult result;
  506. result = MessageBox.Show(this, message, caption, buttons);
  507. }
  508. catch (Exception e2)
  509. {
  510. string message = e2.Message;
  511. string caption = "Connection Failed";
  512. MessageBoxButtons buttons = MessageBoxButtons.OK;
  513. DialogResult result;
  514. result = MessageBox.Show(this, message, caption, buttons);
  515. }
  516. }
  517. }
  518. catch (Exception ex)
  519. {
  520. MessageBox.Show(ex.Message);
  521. }
  522. }
  523. }
  524. }