PageRenderTime 80ms CodeModel.GetById 39ms RepoModel.GetById 1ms app.codeStats 1ms

/SQLExtendedProperties/Main.cs

#
C# | 3437 lines | 2928 code | 158 blank | 351 comment | 308 complexity | c3c114966b51d33a957567511e1dd4c1 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.ComponentModel;
  5. using System.Data;
  6. using System.Drawing;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Windows.Forms;
  10. using System.Data.SqlClient;
  11. using System.Configuration;
  12. using System.Threading;
  13. using System.Reflection;
  14. using System.Diagnostics;
  15. using System.IO;
  16. //SMO namespaces
  17. using Microsoft.SqlServer.Management.Common;
  18. using Microsoft.SqlServer.Management.Smo;
  19. using Smo = Microsoft.SqlServer.Management.Smo;
  20. using System.Xml.Linq;
  21. namespace Rhsoft.SqlServer.MetadataManager
  22. {
  23. public partial class Mainform : Form
  24. {
  25. #region Constants
  26. //Constants to label treenode metadata.
  27. const string NODETYPE_DB = "DB";
  28. const string NODETYPE_TABLE = "TBL";
  29. const string NODETYPE_COLUMN = "COL";
  30. const string NODETYPE_FK = "FK";
  31. const string NODETYPE_PROP = "PROP";
  32. const string NODETYPE_XPROP = "XPROP";
  33. const string NODETYPE_IX = "IX";
  34. //ORM Extended properties names
  35. const string ORM_CONNECTIONSTRING = "ORM_ConnectionStringName";
  36. const string ORM_CONTEXT_IMPORTS = "ORM_ContextImports";
  37. const string ORM_CONTEXT_NAME = "ORM_ContextName";
  38. const string ORM_CONTEXT_NAMESPACE = "ORM_ContextNamespace";
  39. const string ORM_ENTITY_IMPORTS = "ORM_EntityImports";
  40. const string ORM_ENTITY_NAMESPACE = "ORM_EntityNamespace";
  41. const string ORM_GENERATE_MULTIPLE_FILES = "ORM_GenerateMultipleClasses";
  42. const string ORM_INCLUDE_PREVENT_DEBUG = "ORM_IncludePreventingDebug";
  43. const string ORM_IS_SEALED = "ORM_IsSealed";
  44. const string ORM_IS_SERIALIZABLE = "ORM_IsSerializable";
  45. const string ORM_INCLUDE_CRUD_FUNCTIONS = "ORM_IncludeCRUDFunctions";
  46. const string ORM_OVERRIDE_CRUD_OPERATIONS = "ORM_OverrideCRUDOperations";
  47. const string ORM_ONLY_SELECTED = "ORM_OnlySelectedTables";
  48. const string ORM_SAVEPATH = "ORM_SavePath";
  49. //ORM Extended properties at table scope.
  50. const string ORM_CRUD_DELETE = "ORM_Crud_DeleteFunction";
  51. const string ORM_CRUD_INSERT = "ORM_Crud_InsertFunction";
  52. const string ORM_CRUD_UPDATE = "ORM_Crud_UpdateFunction";
  53. const string ORM_ENTITY_NAME = "ORM_EntityName";
  54. const string ORM_ENTITY_PLURALNAME = "ORM_EntityPluralName";
  55. const string ORM_ENTITY_IS_SEALED = "ORM_IsSealed";
  56. const string ORM_ENTITY_IS_SERIALIZED = "ORM_IsSerialized";
  57. #endregion
  58. #region Fields
  59. SqlConnection _conn; //Ado.NET Sql Connection.
  60. Server _serverObject; //Sql Server smo server object.
  61. ServerConnection _serverConn; //Smo server connection.
  62. Database _currentDatabase; //Store de current database object.
  63. Table _currentTable; //Store the current table object.
  64. Column _currentColumn; //Store the current column object.
  65. SqlSmoObject _currentObject; //Store a generic server object.
  66. string _currentObjectType = null;
  67. Smo.ExtendedPropertyCollection _currentPropertiesCollection = null;
  68. bool _serverConnected = false; //Current server state.
  69. string _currentServerConnectionString = null;
  70. //DbProperties fields.
  71. string _propertyOldName = null;
  72. #endregion
  73. #region Assembly Attribute Accessors
  74. public string AssemblyTitle
  75. {
  76. get
  77. {
  78. object[] attributes = Assembly.GetExecutingAssembly( ).GetCustomAttributes( typeof( AssemblyTitleAttribute ), false );
  79. if( attributes.Length > 0 )
  80. {
  81. AssemblyTitleAttribute titleAttribute = (AssemblyTitleAttribute)attributes[0];
  82. if( titleAttribute.Title != "" )
  83. {
  84. return titleAttribute.Title;
  85. }
  86. }
  87. return System.IO.Path.GetFileNameWithoutExtension( Assembly.GetExecutingAssembly( ).CodeBase );
  88. }
  89. }
  90. public string AssemblyVersion
  91. {
  92. get
  93. {
  94. return Assembly.GetExecutingAssembly( ).GetName( ).Version.ToString( );
  95. }
  96. }
  97. public string AssemblyDescription
  98. {
  99. get
  100. {
  101. object[] attributes = Assembly.GetExecutingAssembly( ).GetCustomAttributes( typeof( AssemblyDescriptionAttribute ), false );
  102. if( attributes.Length == 0 )
  103. {
  104. return "";
  105. }
  106. return ( (AssemblyDescriptionAttribute)attributes[0] ).Description;
  107. }
  108. }
  109. public string AssemblyProduct
  110. {
  111. get
  112. {
  113. object[] attributes = Assembly.GetExecutingAssembly( ).GetCustomAttributes( typeof( AssemblyProductAttribute ), false );
  114. if( attributes.Length == 0 )
  115. {
  116. return "";
  117. }
  118. return ( (AssemblyProductAttribute)attributes[0] ).Product;
  119. }
  120. }
  121. public string AssemblyCopyright
  122. {
  123. get
  124. {
  125. object[] attributes = Assembly.GetExecutingAssembly( ).GetCustomAttributes( typeof( AssemblyCopyrightAttribute ), false );
  126. if( attributes.Length == 0 )
  127. {
  128. return "";
  129. }
  130. return ( (AssemblyCopyrightAttribute)attributes[0] ).Copyright;
  131. }
  132. }
  133. public string AssemblyCompany
  134. {
  135. get
  136. {
  137. object[] attributes = Assembly.GetExecutingAssembly( ).GetCustomAttributes( typeof( AssemblyCompanyAttribute ), false );
  138. if( attributes.Length == 0 )
  139. {
  140. return "";
  141. }
  142. return ( (AssemblyCompanyAttribute)attributes[0] ).Company;
  143. }
  144. }
  145. #endregion
  146. #region Main
  147. public Mainform( )
  148. {
  149. InitializeComponent( );
  150. this.Text = string.Format( "{0} v{1}", AssemblyTitle, AssemblyVersion );
  151. LoadConfiguration( );
  152. DisableDatabaseControls( );
  153. PopulateServers( );
  154. }
  155. /// <summary>
  156. /// Load configuration values.
  157. /// </summary>
  158. private void LoadConfiguration( )
  159. {
  160. //ConfigValues.DescriptionLabel = ConfigurationManager.AppSettings["DescriptionLabel"].ToString( );
  161. //ConfigValues.SaveOnLostFocus = Convert.ToBoolean( ConfigurationManager.AppSettings["SaveOnLostFocus"] );
  162. ConfigValues.DescriptionLabel = Properties.Settings.Default.DescriptionPropertyName;
  163. ConfigValues.SaveOnLostFocus = Properties.Settings.Default.SaveOnLostFocus;
  164. ConfigValues.ViewSystemDatabases = Properties.Settings.Default.IncludeSystemDatabases;
  165. ConfigValues.ViewSystemTables = Properties.Settings.Default.IncludeSystemTables;
  166. ConfigValues.OverrideProperties = Properties.Settings.Default.OverrideProperties;
  167. }
  168. #endregion
  169. #region Helpers
  170. private string ParseValue( string value )
  171. {
  172. string ParsedValue = value;
  173. //Parse variables.
  174. if(_currentTable !=null)
  175. ParsedValue = ParseTableName( value, _currentTable.Name );
  176. if(_currentColumn != null)
  177. ParsedValue = ParseColumnName( value, _currentColumn.Name );
  178. return ParsedValue;
  179. }
  180. private string ParseTableName( string value, string maskValue )
  181. {
  182. string ParsedValue=string.Empty;
  183. //Parse variables.
  184. ParsedValue = value.Replace( "$TableName$", maskValue );
  185. return ParsedValue;
  186. }
  187. private string ParseDatabaseName( string value, string maskValue )
  188. {
  189. string ParsedValue = string.Empty;
  190. //Parse variables.
  191. ParsedValue = value.Replace( "$DatabaseName$", maskValue );
  192. return ParsedValue;
  193. }
  194. private string ParseColumnName( string value, string maskValue )
  195. {
  196. string ParsedValue = string.Empty;
  197. //Parse variables.
  198. ParsedValue = value.Replace( "$ColumnName$", maskValue );
  199. return ParsedValue;
  200. }
  201. private void ShowinfoMessage( string message )
  202. {
  203. MessageBox.Show( message, "Information message", MessageBoxButtons.OK, MessageBoxIcon.Information );
  204. }
  205. private DialogResult ShowConfirmationMessage( string message )
  206. {
  207. return MessageBox.Show( message, "Dialog confirmation", MessageBoxButtons.OKCancel, MessageBoxIcon.Question );
  208. }
  209. private void ShowAlertMessage( string message )
  210. {
  211. MessageBox.Show( message, "Alert", MessageBoxButtons.OK, MessageBoxIcon.Exclamation );
  212. }
  213. private void ShowErrorMessage( string message )
  214. {
  215. MessageBox.Show( message, "Error notification", MessageBoxButtons.OK, MessageBoxIcon.Error );
  216. }
  217. private void ShowWaitDialog( string message )
  218. {
  219. }
  220. #endregion
  221. #region User interface
  222. private void EnableDatabaseControls( )
  223. {
  224. DbTree.Enabled = true;
  225. DbList.Enabled = true;
  226. FieldDescription.Enabled = true;
  227. DbProperties.Enabled = true;
  228. bSaveDescription.Enabled = true;
  229. bAddProperty.Enabled = true;
  230. }
  231. private void DisableDatabaseControls( )
  232. {
  233. DbTree.Enabled = false;
  234. DbList.Enabled = false;
  235. FieldDescription.Enabled = false;
  236. DbProperties.Enabled = false;
  237. bSaveDescription.Enabled = false;
  238. bAddProperty.Enabled = false;
  239. }
  240. private void ClearDatabaseControls( )
  241. {
  242. DbTree.Nodes.Clear( );
  243. DbList.Items.Clear( ); DbList.Refresh( );
  244. DbProperties.Rows.Clear( );
  245. FieldDescription.Text = "";
  246. }
  247. private void EnableMenuItems( )
  248. {
  249. }
  250. private void DisableMenuItems( )
  251. {
  252. }
  253. #endregion
  254. #region Extended properties management
  255. /// <summary>
  256. /// Take current properties collection and fill the properties listview.
  257. /// </summary>
  258. /// <param name="propCol"></param>
  259. private void PopulateExtendedProperties( Smo.ExtendedPropertyCollection propCol )
  260. {
  261. try
  262. {
  263. //Set the current properties collection object which is used to add or remove properties.
  264. _currentPropertiesCollection = propCol;
  265. //Populate extended properties view.
  266. DbProperties.Rows.Clear( );
  267. foreach( ExtendedProperty item in propCol )
  268. {
  269. //Omit the property to store description and avoid delete or editing name.
  270. if( !( item.Name == ConfigValues.DescriptionLabel ) )
  271. DbProperties.Rows.Add( item.Name, item.Value.ToString( ) );
  272. }
  273. //Fill de description field.
  274. if( _currentPropertiesCollection[ConfigValues.DescriptionLabel] != null )
  275. {
  276. //Show in text field to edit.
  277. FieldDescription.Text = _currentPropertiesCollection[ConfigValues.DescriptionLabel].Value.ToString( );
  278. }
  279. }
  280. catch( InvalidOperationException ex ) { }
  281. catch( Exception ex ) { MessageBox.Show( ex.Message ); }
  282. }
  283. /// <summary>
  284. /// Update property value. Support variables:
  285. /// $TableName$, $ColumnName$ to custom values with tables or column names
  286. /// </summary>
  287. /// <param name="extendedPropertyName"></param>
  288. /// <param name="value"></param>
  289. private void SetExtendedProperty( string extendedPropertyName, string value )
  290. {
  291. //
  292. Smo.ExtendedPropertyCollection PropCol = _currentTable.ExtendedProperties;
  293. string ParsedValue = value;
  294. //Parse variables.
  295. ParsedValue = ParsedValue.Replace( "$TableName$", _currentTable.Name );
  296. ParsedValue = ParsedValue.Replace( "$ColumnName$", _currentColumn.Name );
  297. PropCol[extendedPropertyName].Value = ParsedValue;
  298. _currentTable.Alter( );
  299. }
  300. private void RemoveProperty( SqlSmoObject smoObject, string objectType, string name )
  301. {
  302. try
  303. {
  304. //Delete the property.
  305. _currentPropertiesCollection[name].Drop();
  306. //Repopulate the list view control with the current properties collection.
  307. PopulateExtendedProperties( _currentPropertiesCollection );
  308. }
  309. catch( Exception ex ) { MessageBox.Show( ex.Message ); }
  310. }
  311. private void AddSingleExtendedProperty( SqlSmoObject smoObject, string objectType )
  312. {
  313. //
  314. Smo.ExtendedPropertyCollection PropertiesCol = null;
  315. try
  316. {
  317. switch( objectType )
  318. {
  319. case NODETYPE_DB:
  320. Database Db = (Database)smoObject;
  321. PropertiesCol = Db.ExtendedProperties;
  322. PropertiesCol.Add( new ExtendedProperty( smoObject, string.Format( "NewProperty{0}", PropertiesCol.Count + 1 ), "DefaultValue" ) );
  323. Db.Alter( );
  324. break;
  325. case NODETYPE_TABLE:
  326. Table t = (Table)smoObject;
  327. PropertiesCol = t.ExtendedProperties;
  328. PropertiesCol.Add( new ExtendedProperty( smoObject, string.Format("NewProperty{0}", PropertiesCol.Count + 1), "DefaultValue" ) );
  329. t.Alter( );
  330. break;
  331. case NODETYPE_COLUMN:
  332. Column c = (Column)smoObject;
  333. PropertiesCol = c.ExtendedProperties;
  334. PropertiesCol.Add( new ExtendedProperty( smoObject, string.Format("NewProperty{0}", PropertiesCol.Count + 1), "DefaultValue" ) ) ;
  335. c.Alter( );
  336. break;
  337. default:
  338. break;
  339. }
  340. PopulateExtendedProperties( PropertiesCol );
  341. }
  342. catch( Exception ex ) { MessageBox.Show( ex.Message ); }
  343. }
  344. private void AddExtendedProperty( SqlSmoObject smoObject, string objectType, string name, string value )
  345. {
  346. //
  347. Smo.ExtendedPropertyCollection PropertiesCol = null;
  348. try
  349. {
  350. switch( objectType )
  351. {
  352. case NODETYPE_DB:
  353. Database db = (Database)smoObject;
  354. PropertiesCol = db.ExtendedProperties;
  355. if( PropertiesCol[name] != null )
  356. {
  357. //Drop first to override.
  358. if( Properties.Settings.Default.OverrideProperties )
  359. {
  360. PropertiesCol[name].Drop( );
  361. db.Alter( );
  362. PropertiesCol.Add( new ExtendedProperty( db, name, ParseDatabaseName( value, db.Name ) ) );
  363. db.Alter( );
  364. }
  365. }
  366. else
  367. {
  368. PropertiesCol.Add( new ExtendedProperty( db, name, ParseDatabaseName( value, db.Name ) ) );
  369. db.Alter( );
  370. }
  371. //Refresh current properties view.
  372. PropertiesCol = db.ExtendedProperties;
  373. PopulateExtendedProperties( PropertiesCol );
  374. break;
  375. case NODETYPE_TABLE:
  376. Table t = (Table)smoObject;
  377. PropertiesCol = t.ExtendedProperties;
  378. if( PropertiesCol[name] != null )
  379. {
  380. //Drop first to override.
  381. if( Properties.Settings.Default.OverrideProperties )
  382. {
  383. PropertiesCol[name].Drop( );
  384. t.Alter( );
  385. PropertiesCol.Add( new ExtendedProperty( t, name, ParseTableName( value, t.Name ) ) );
  386. t.Alter( );
  387. }
  388. }
  389. else
  390. {
  391. PropertiesCol.Add( new ExtendedProperty( t, name, ParseTableName( value, t.Name ) ) );
  392. t.Alter( );
  393. }
  394. //Refresh current properties view.
  395. PropertiesCol = t.ExtendedProperties;
  396. PopulateExtendedProperties( PropertiesCol );
  397. break;
  398. default:
  399. break;
  400. }
  401. }
  402. catch( Exception ex ) { ShowErrorMessage( ex.Message ); }
  403. finally { ProgressBar.Visible = false; }
  404. }
  405. private void AddExtendedPropertyAtScope( string objectType, string name, string value, Scope scope )
  406. {
  407. //If the scope is set to database scope.
  408. if( scope == Scope.DatabaseScope )
  409. {
  410. foreach( Table table in _currentDatabase.Tables )
  411. {
  412. AddExtendedProperty( table, NODETYPE_TABLE, name, value );
  413. }
  414. ShowinfoMessage( "Edit operation finished sucessfully." );
  415. //MessageBox.Show( "Edit operation finished sucessfully." );
  416. }
  417. //if the scope is set at scope to selected tables.
  418. if( scope == Scope.SelectedScope )
  419. {
  420. foreach( TreeNode node in DbTree.Nodes[0].Nodes.OfType<TreeNode>( ).Where( c => c.Checked ).ToList( ) )
  421. {
  422. Hashtable NodeTagValues = (Hashtable)node.Tag;
  423. Table TableByNode = _currentDatabase.Tables[NodeTagValues["Name"].ToString( ), NodeTagValues["Schema"].ToString( )];
  424. AddExtendedProperty( TableByNode, NODETYPE_TABLE, name, value );
  425. }
  426. ShowinfoMessage( "Edit operation finished sucessfully." );
  427. //MessageBox.Show( "Edit operation finished sucessfully." );
  428. }
  429. }
  430. /// <summary>
  431. /// Update property name and value, behavior set with IsName flag.
  432. /// </summary>
  433. /// <param name="smoObject"></param>
  434. /// <param name="objectType"></param>
  435. /// <param name="name"></param>
  436. /// <param name="value"></param>
  437. /// <param name="isName"></param>
  438. private void UpdateProperty( SqlSmoObject smoObject, string objectType, string name, string value, bool isName)
  439. {
  440. //
  441. Smo.ExtendedPropertyCollection PropertiesCol = null;
  442. try
  443. {
  444. switch( objectType )
  445. {
  446. case NODETYPE_DB:
  447. Database d = (Database)smoObject;
  448. PropertiesCol = d.ExtendedProperties;
  449. //Update name or value based in isName flag.
  450. if( isName )
  451. {
  452. //Recreate the property. parameter value is the new name.
  453. if( PropertiesCol[name] != null )
  454. {
  455. string _value = PropertiesCol[name].Value.ToString( );
  456. PropertiesCol[name].Drop( );
  457. PropertiesCol.Add( new ExtendedProperty( smoObject, value, _value ) );
  458. }
  459. }
  460. else
  461. {
  462. //Update property value.
  463. if( PropertiesCol[name] != null )
  464. {
  465. PropertiesCol[name].Value = this.ParseValue( value );
  466. }
  467. }
  468. d.Alter( );
  469. break;
  470. case NODETYPE_TABLE:
  471. Table t = (Table)smoObject;
  472. PropertiesCol = t.ExtendedProperties;
  473. //Update name or value based in isName flag.
  474. if( isName )
  475. {
  476. //Remove and add new property. parameter value is the new name.
  477. if( PropertiesCol[name] != null )
  478. {
  479. string _value = PropertiesCol[name].Value.ToString( );
  480. PropertiesCol[name].Drop( );
  481. PropertiesCol.Add( new ExtendedProperty( smoObject, value, _value ) );
  482. }
  483. }
  484. else
  485. {
  486. //Update property value.
  487. if( PropertiesCol[name] != null )
  488. {
  489. PropertiesCol[name].Value = this.ParseValue( value );
  490. }
  491. }
  492. t.Alter( );
  493. break;
  494. case NODETYPE_COLUMN:
  495. Column c = (Column)smoObject;
  496. PropertiesCol = c.ExtendedProperties;
  497. //Update name or value based in isName flag.
  498. if( isName )
  499. {
  500. //Remove and add new property. parameter value is the new name.
  501. if( PropertiesCol[name] != null )
  502. {
  503. string _value = PropertiesCol[name].Value.ToString( );
  504. PropertiesCol[name].Drop( );
  505. PropertiesCol.Add( new ExtendedProperty( smoObject, value, _value ) );
  506. }
  507. }
  508. else
  509. {
  510. //Update property value.
  511. PropertiesCol[name].Value = this.ParseValue( value );
  512. }
  513. c.Alter( );
  514. break;
  515. default:
  516. break;
  517. }
  518. PopulateExtendedProperties( PropertiesCol );
  519. }
  520. catch( Exception ex ) { ShowErrorMessage( ex.Message ); }
  521. }
  522. private void UpdatePropertyAtScope( string objectType, string name, string value, Scope scope, bool isName )
  523. {
  524. //If the scope is set to database scope.
  525. if( scope == Scope.DatabaseScope )
  526. {
  527. foreach( Table table in _currentDatabase.Tables )
  528. {
  529. UpdateProperty( table, NODETYPE_TABLE, name, value, isName );
  530. }
  531. ShowinfoMessage( "Edit operation finished sucessfully." );
  532. //MessageBox.Show( "Edit operation finished sucessfully." );
  533. }
  534. //if the scope is set at scope to selected tables.
  535. if( scope == Scope.SelectedScope )
  536. {
  537. foreach( TreeNode node in DbTree.Nodes[0].Nodes.OfType<TreeNode>().Where( c=>c.Checked ).ToList() )
  538. {
  539. Hashtable NodeTagValues = (Hashtable)node.Tag;
  540. Table TableByNode = _currentDatabase.Tables[NodeTagValues["Name"].ToString( ), NodeTagValues["Schema"].ToString( )];
  541. UpdateProperty( TableByNode, NODETYPE_TABLE, name, value, isName );
  542. }
  543. ShowinfoMessage( "Edit operation finished sucessfully." );
  544. //MessageBox.Show( "Edit operation finished sucessfully." );
  545. }
  546. }
  547. private void DeleteGlobalProperty( SqlSmoObject smoObject, string objectType, string name )
  548. {
  549. try
  550. {
  551. Smo.ExtendedPropertyCollection _propertiesCol = null;
  552. switch( objectType )
  553. {
  554. case NODETYPE_DB:
  555. Database DbObj = (Database)smoObject;
  556. //
  557. ProgressBar.Maximum = DbObj.Tables.Count; //ProgressBar
  558. ProgressBar.Value = 0;
  559. ProgressBar.Visible = true;
  560. foreach( Table table in DbObj.Tables )
  561. {
  562. _propertiesCol = table.ExtendedProperties;
  563. if( _propertiesCol[name] != null )
  564. {
  565. _propertiesCol[name].Drop( );
  566. table.Alter( );
  567. }
  568. ProgressBar.PerformStep( );
  569. }
  570. //Rebuild properties gridview.
  571. PopulateExtendedProperties( _currentTable.ExtendedProperties );
  572. break;
  573. case NODETYPE_TABLE:
  574. Table tableObj = (Table)smoObject;
  575. //
  576. ProgressBar.Maximum = tableObj.Columns.Count; //ProgressBar
  577. ProgressBar.Value = 0;
  578. ProgressBar.Visible = true;
  579. //
  580. foreach( Column column in tableObj.Columns )
  581. {
  582. _propertiesCol = column.ExtendedProperties;
  583. if( _propertiesCol[name] != null )
  584. {
  585. _propertiesCol[name].Drop( );
  586. column.Alter( );
  587. }
  588. ProgressBar.PerformStep( );
  589. }
  590. //Rebuild properties gridview.
  591. PopulateExtendedProperties( _currentColumn.ExtendedProperties );
  592. break;
  593. default:
  594. break;
  595. }
  596. }
  597. catch( Exception ex ) { MessageBox.Show( ex.Message ); }
  598. finally { ProgressBar.Visible = false; }
  599. }
  600. private void AddORMExtendedForeingKeyProperties( )
  601. {
  602. try
  603. {
  604. }
  605. catch( Exception ex ) { throw; }
  606. }
  607. private void AddORMExtendedProperties( Scope scope )
  608. {
  609. try
  610. {
  611. switch(scope)
  612. {
  613. case Scope.DatabaseScope:
  614. //Add ORM database properties.
  615. AddExtendedProperty( _currentDatabase, NODETYPE_DB, ORM_CONNECTIONSTRING, "" );
  616. AddExtendedProperty( _currentDatabase, NODETYPE_DB, ORM_CONTEXT_IMPORTS, "" );
  617. AddExtendedProperty( _currentDatabase, NODETYPE_DB, ORM_CONTEXT_NAME, "$DatabaseName$DataContext" );
  618. AddExtendedProperty( _currentDatabase, NODETYPE_DB, ORM_CONTEXT_NAMESPACE, "$DatabaseName$.Data" );
  619. AddExtendedProperty( _currentDatabase, NODETYPE_DB, ORM_ENTITY_IMPORTS, "" );
  620. AddExtendedProperty( _currentDatabase, NODETYPE_DB, ORM_ENTITY_NAMESPACE, "$DatabaseName$.Entities" );
  621. AddExtendedProperty( _currentDatabase, NODETYPE_DB, ORM_GENERATE_MULTIPLE_FILES, "true" );
  622. AddExtendedProperty( _currentDatabase, NODETYPE_DB, ORM_INCLUDE_PREVENT_DEBUG, "false" );
  623. AddExtendedProperty( _currentDatabase, NODETYPE_DB, ORM_IS_SEALED, "true" );
  624. AddExtendedProperty( _currentDatabase, NODETYPE_DB, ORM_IS_SERIALIZABLE, "true" );
  625. AddExtendedProperty( _currentDatabase, NODETYPE_DB, ORM_SAVEPATH, @"c:\temp" );
  626. AddExtendedProperty( _currentDatabase, NODETYPE_DB, ORM_INCLUDE_CRUD_FUNCTIONS, "false" );
  627. AddExtendedProperty( _currentDatabase, NODETYPE_DB, ORM_OVERRIDE_CRUD_OPERATIONS, "false" );
  628. _currentDatabase.Alter( );
  629. //
  630. foreach( Table table in _currentDatabase.Tables )
  631. {
  632. AddExtendedProperty( table, NODETYPE_TABLE, ORM_CRUD_DELETE, "" );
  633. AddExtendedProperty( table, NODETYPE_TABLE, ORM_CRUD_INSERT, "" );
  634. AddExtendedProperty( table, NODETYPE_TABLE, ORM_CRUD_UPDATE, "" );
  635. AddExtendedProperty( table, NODETYPE_TABLE, ORM_ENTITY_NAME, "$TableName$" );
  636. AddExtendedProperty( table, NODETYPE_TABLE, ORM_ENTITY_PLURALNAME, "$TableName$s" );
  637. AddExtendedProperty( table, NODETYPE_TABLE, ORM_ENTITY_IS_SEALED, "true" );
  638. AddExtendedProperty( table, NODETYPE_TABLE, ORM_ENTITY_IS_SERIALIZED, "true" );
  639. }
  640. break;
  641. default:
  642. break;
  643. }
  644. ShowConfirmationMessage( "Extended properties added successfully." );
  645. }
  646. catch( Exception ex ) { throw; }
  647. }
  648. #endregion
  649. #region Database Objects Managment
  650. private void PopulateServers( )
  651. {
  652. XElement XServers = XElement.Load( "Servers.xml" );
  653. foreach( var item in XServers.Elements( "Server" ) )
  654. {
  655. ServersList.Items.Add( item.Attribute( "Name" ).Value );
  656. }
  657. }
  658. /// <summary>
  659. /// Fill de database drop down control.
  660. /// </summary>
  661. private void PopulateDatabases( )
  662. {
  663. try
  664. {
  665. ProgressBar.Maximum = _serverObject.Databases.Count; //ProgressBar
  666. ProgressBar.Value = 0;
  667. ProgressBar.Visible = true;
  668. //Clear control.
  669. DbList.Items.Clear( );
  670. foreach( Database item in _serverObject.Databases )
  671. {
  672. //Fill control.
  673. if( item.IsSystemObject )
  674. {
  675. if( ConfigValues.ViewSystemDatabases ) DbList.Items.Add( item.Name );
  676. }
  677. else
  678. {
  679. DbList.Items.Add( item.Name );
  680. }
  681. ProgressBar.PerformStep( );
  682. //Thread.Sleep( 120 );
  683. }
  684. if( DbList.Items.Count > 0 )
  685. DbList.SelectedIndex = 1;
  686. }
  687. catch( Exception ex ) { MessageBox.Show( ex.Message ); }
  688. finally
  689. {
  690. ProgressBar.Visible = false;
  691. }
  692. }
  693. private void PopulateTables( bool refresh )
  694. {
  695. try
  696. {
  697. //---------------------------------
  698. string DatabaseName = DbList.Text;
  699. //This step is necesary to load database objects. Cant use directly in loop.
  700. _currentDatabase = _serverObject.Databases[DatabaseName];
  701. //Check if request refresh
  702. if( refresh )
  703. {
  704. _currentDatabase.Refresh( ); //Force refleshing database data.
  705. _currentDatabase.Tables.Refresh( ); //Force refreshing database tables (names not data).
  706. }
  707. ProgressBar.Maximum = _currentDatabase.Tables.Count; //ProgressBar
  708. ProgressBar.Value = 0;
  709. ProgressBar.Visible = true;
  710. //Configure treeview.
  711. DbTree.Nodes.Clear( );
  712. TreeNode DatabaseNode = DbTree.Nodes.Add( DatabaseName );
  713. DatabaseNode.ImageIndex = 1;
  714. DatabaseNode.SelectedImageIndex = 1;
  715. //Set object tag with values used to check the node type.
  716. Hashtable DatabaseTagValues = new Hashtable( );
  717. DatabaseTagValues.Add( "Type", NODETYPE_DB ); //Node type = database.
  718. DatabaseTagValues.Add( "Name", DatabaseName ); //Table name.
  719. DatabaseNode.Tag = DatabaseTagValues;
  720. //========================================
  721. // Add database tables nodes.
  722. //========================================
  723. Hashtable TableTagValues;
  724. foreach( Table table in _currentDatabase.Tables )
  725. {
  726. //Check if request refresh
  727. if( refresh )
  728. {
  729. table.Refresh( ); //Force refreshing only table data.
  730. table.Columns.Refresh( ); //Force refreshing table columns (names not properties).
  731. }
  732. //Check if it is a system table.
  733. if( table.IsSystemObject )
  734. {
  735. //If system tables allowed.
  736. if( ConfigValues.ViewSystemTables )
  737. {
  738. //Add node.
  739. TreeNode TableNode = DatabaseNode.Nodes.Add( table.Schema + "." + table.Name );
  740. TableNode.ImageIndex = 5;
  741. TableNode.SelectedImageIndex = 5;
  742. //Add virtually node to force show expand icon. It remove when populate columns.
  743. TableNode.Nodes.Add( " " );
  744. //Set object tag with values used to check the node values.
  745. TableTagValues = new Hashtable( );
  746. TableTagValues.Add( "Type", NODETYPE_TABLE ); //Node type = Table.
  747. TableTagValues.Add( "Schema", table.Schema ); //Schema name of table.
  748. TableTagValues.Add( "Name", table.Name ); //Table name.
  749. TableNode.Tag = TableTagValues;
  750. }
  751. }
  752. else
  753. {
  754. //Add node.
  755. TreeNode TableNode = DatabaseNode.Nodes.Add( table.Schema + "." + table.Name );
  756. TableNode.ImageIndex = 5;
  757. TableNode.SelectedImageIndex = 5;
  758. //Add virtually node to force show expand icon. It remove when populate columns.
  759. TableNode.Nodes.Add( " " );
  760. //Set object tag with values used to check the node values.
  761. TableTagValues = new Hashtable( );
  762. TableTagValues.Add( "Type", NODETYPE_TABLE ); //Node type = Table.
  763. TableTagValues.Add( "Schema", table.Schema ); //Schema name of table.
  764. TableTagValues.Add( "Name", table.Name ); //Table name.
  765. TableNode.Tag = TableTagValues;
  766. }
  767. //Thread.Sleep( 120 );
  768. ProgressBar.PerformStep( );
  769. }
  770. DatabaseNode.Expand( );
  771. }
  772. catch( Exception ex ) { MessageBox.Show( ex.Message ); }
  773. finally
  774. {
  775. ProgressBar.Visible = false;
  776. }
  777. }
  778. private void PopulateColumns( TreeNode tableNode, bool refresh )
  779. {
  780. try
  781. {
  782. tableNode.Nodes.Clear( );
  783. Hashtable TableTag = (Hashtable)tableNode.Tag;
  784. Table t = _currentDatabase.Tables[TableTag["Name"].ToString( ), TableTag["Schema"].ToString( )];
  785. foreach( Column column in t.Columns )
  786. {
  787. //Check if request refresh
  788. if( refresh )
  789. {
  790. column.Refresh( ); //Force refreshing column data.
  791. }
  792. //Add node, set tag value to nodetype "Column"
  793. TreeNode ColumnNode = tableNode.Nodes.Add( column.Name );
  794. ColumnNode.ToolTipText = column.DataType.ToString( );
  795. if( column.InPrimaryKey )
  796. {
  797. ColumnNode.ImageIndex = 3;
  798. ColumnNode.SelectedImageIndex = 3;
  799. }
  800. else
  801. {
  802. ColumnNode.ImageIndex = 0;
  803. ColumnNode.SelectedImageIndex = 0;
  804. }
  805. //Set the tag object.
  806. Hashtable ColumnTag = new Hashtable( ); //Tag object host a hashtable.
  807. ColumnTag.Add( "Type", NODETYPE_COLUMN ); //Node type Column.
  808. ColumnTag.Add( "Name", column.Name ); //Column name.
  809. ColumnNode.Tag = ColumnTag;
  810. }
  811. }
  812. catch( SqlException ex ) { MessageBox.Show( ex.Message ); }
  813. }
  814. #endregion
  815. #region LinqToSql Generator
  816. #region Helpers
  817. public Table GetReferencedTable( ForeignKey foreignKey )
  818. {
  819. return _currentDatabase.Tables[foreignKey.ReferencedTable, foreignKey.ReferencedTableSchema];
  820. }
  821. public string GetEntityName( Table table )
  822. {
  823. return table.ExtendedProperties["ORM_EntityName"].Value.ToString( );
  824. }
  825. public string GetEntityPluralName( Table table )
  826. {
  827. return table.ExtendedProperties["ORM_EntityPluralName"].Value.ToString( );
  828. }
  829. /// <summary>
  830. /// Return the reference name extended propertie of the column passed.
  831. /// </summary>
  832. /// <param name="column"></param>
  833. /// <returns></returns>
  834. public string GetColumnReferenceName( Column column )
  835. {
  836. if( column.ExtendedProperties["ORM_ReferenceName"] != null )
  837. {
  838. return column.ExtendedProperties["ORM_ReferenceName"].Value.ToString( );
  839. }
  840. else
  841. {
  842. return null;
  843. }
  844. }
  845. public string GetColumnReferencePluralName( Column column )
  846. {
  847. if( column.ExtendedProperties["ORM_ReferencePluralName"] != null )
  848. {
  849. return column.ExtendedProperties["ORM_ReferencePluralName"].Value.ToString( );
  850. }
  851. else
  852. {
  853. return null;
  854. }
  855. }
  856. public string GetParsedEnumColumnName( Column column )
  857. {
  858. return column.Name.Replace( "Enum", "" );
  859. }
  860. public string ParseForeignkeyName( string value )
  861. {
  862. return value.Replace( "FK_", "" );
  863. }
  864. public string ParseParameterName( string name )
  865. {
  866. return name.Replace( "@", "" );
  867. }
  868. /// <summary>
  869. /// Get the equivalent clr type of Sql data type.
  870. /// </summary>
  871. /// <param name="column"></param>
  872. /// <returns></returns>
  873. public string GetClrType( Column column )
  874. {
  875. string ClrType = string.Empty;
  876. if( column != null )
  877. {
  878. switch( column.DataType.SqlDataType.ToString( ).ToLower( ) )
  879. {
  880. case "xml":
  881. ClrType = "XElement";
  882. break;
  883. case "binary":
  884. case "varbinary":
  885. case "varbinarymax":
  886. case "image":
  887. ClrType = "System.Data.Linq.Binary";
  888. break;
  889. case "varchar":
  890. case "varcharmax":
  891. case "nvarchar":
  892. case "nvarcharmax":
  893. case "char":
  894. case "nchar":
  895. case "text":
  896. case "ntext":
  897. ClrType = "string";
  898. break;
  899. case "timestamp":
  900. ClrType = "byte[]";
  901. break;
  902. case "datetime":
  903. case "date":
  904. case "smalldatetime":
  905. ClrType = "System.DateTime";
  906. break;
  907. case "datetimeoffset":
  908. ClrType = "System.DateTimeOffset";
  909. break;
  910. case "decimal":
  911. case "money":
  912. case "smallmoney":
  913. case "numeric":
  914. ClrType = "decimal";
  915. break;
  916. case "float":
  917. case "real":
  918. ClrType = "double";
  919. break;
  920. case "bigint":
  921. ClrType = "long";
  922. break;
  923. case "int":
  924. ClrType = "int";
  925. break;
  926. case "smallint":
  927. ClrType = "short";
  928. break;
  929. case "tinyint":
  930. ClrType = "byte";
  931. break;
  932. case "bit":
  933. ClrType = "bool";
  934. break;
  935. case "uniqueidentifier":
  936. ClrType = "System.Guid";
  937. break;
  938. case "time":
  939. ClrType = "System.TimeSpan";
  940. break;
  941. default:
  942. ClrType = "System.Object";
  943. break;
  944. }
  945. }
  946. return ClrType;
  947. }
  948. /// <summary>
  949. /// Parse Sql data types to clr types.
  950. /// </summary>
  951. /// <param name="column"></param>
  952. /// <returns></returns>
  953. public string GetNullableClrType( Column column )
  954. {
  955. string ClrType = string.Empty;
  956. if( column != null )
  957. {
  958. switch( column.DataType.SqlDataType.ToString( ).ToLower( ) )
  959. {
  960. case "xml":
  961. ClrType = "XElement";
  962. break;
  963. case "binary":
  964. case "varbinary":
  965. case "varbinarymax":
  966. case "image":
  967. ClrType = "System.Data.Linq.Binary";
  968. break;
  969. case "varchar":
  970. case "varcharmax":
  971. case "nvarchar":
  972. case "nvarcharmax":
  973. case "char":
  974. case "nchar":
  975. case "text":
  976. case "ntext":
  977. ClrType = "string";
  978. break;
  979. case "timestamp":
  980. ClrType = "byte[]";
  981. break;
  982. case "datetime":
  983. case "date":
  984. case "smalldatetime":
  985. ClrType = "System.DateTime";
  986. break;
  987. case "datetimeoffset":
  988. ClrType = "System.DateTimeOffset";
  989. break;
  990. case "decimal":
  991. case "money":
  992. case "smallmoney":
  993. case "numeric":
  994. ClrType = "decimal";
  995. break;
  996. case "float":
  997. case "real":
  998. ClrType = "double";
  999. break;
  1000. case "bigint":
  1001. ClrType = "long";
  1002. break;
  1003. case "int":
  1004. ClrType = "int";
  1005. break;
  1006. case "smallint":
  1007. ClrType = "short";
  1008. break;
  1009. case "tinyint":
  1010. if( column.Name.Contains( "Enum" ) )
  1011. {
  1012. ClrType = column.Name.Replace("Enum","") + "Enum";
  1013. }
  1014. else
  1015. {
  1016. ClrType = "Byte";
  1017. }
  1018. break;
  1019. case "bit":
  1020. ClrType = "bool";
  1021. break;
  1022. case "uniqueidentifier":
  1023. ClrType = "System.Guid";
  1024. break;
  1025. case "time":
  1026. ClrType = "System.TimeSpan";
  1027. break;
  1028. default:
  1029. ClrType = "System.Object";
  1030. break;
  1031. }
  1032. if( ( !column.Nullable ) || ClrType == "string" || ClrType == "System.Object" || ClrType == "XElement" || ClrType == "System.Data.Linq.Binary" )
  1033. return ClrType;
  1034. else
  1035. //return "System.Nullable<" + systemType + ">";
  1036. return string.Format( "System.Nullable<{0}>", ClrType );
  1037. }
  1038. else
  1039. {
  1040. return null;
  1041. }
  1042. }
  1043. /// <summary>
  1044. /// Not used.
  1045. /// </summary>
  1046. /// <param name="column"></param>
  1047. /// <returns></returns>
  1048. public string GetDbTypeAttribute( Column column )
  1049. {
  1050. string columnDbType = column.DataType.ToString( );
  1051. //
  1052. if( column.DataType.ToString().Contains( "char" ) )
  1053. columnDbType += String.Format( "({0})", column.DataType.MaximumLength== -1 ? "MAX" : column.DataType.MaximumLength.ToString( ) );
  1054. //
  1055. if( !column.Nullable ) { columnDbType += " NOT NULL"; }
  1056. //
  1057. if( column.Identity)
  1058. {
  1059. columnDbType += " IDENTITY";
  1060. }
  1061. return columnDbType;
  1062. }
  1063. public string GetSimpleDbType( Column column )
  1064. {
  1065. string columnDbType = column.DataType.ToString( );
  1066. //
  1067. if( column.DataType.ToString( ).Contains( "char" ) )
  1068. columnDbType += String.Format( "({0})", column.DataType.MaximumLength == -1 ? "MAX" : column.DataType.MaximumLength.ToString( ) );
  1069. return columnDbType;
  1070. }
  1071. public string GetColumnKeyList(ForeignKeyColumnCollection keys )
  1072. {
  1073. List<string> list = new List<string>( );
  1074. foreach( Column column in keys )
  1075. list.Add( column.Name );
  1076. return String.Join( ", ", list.ToArray( ) );
  1077. }
  1078. public string Indent( string value, int level )
  1079. {
  1080. string Result = new String( ' ', level );
  1081. return string.Concat( Result, value );
  1082. }
  1083. #endregion
  1084. /// <summary>
  1085. /// Retrieve the ContextNamespace value.
  1086. /// </summary>
  1087. /// <returns></returns>
  1088. public string GetContextNamespace( )
  1089. {
  1090. if( _currentDatabase.ExtendedProperties[ORM_CONTEXT_NAMESPACE] != null )
  1091. {
  1092. return _currentDatabase.ExtendedProperties[ORM_CONTEXT_NAMESPACE].Value.ToString( );
  1093. }
  1094. else
  1095. {
  1096. //If not exist the database property uses general preference value.
  1097. return Properties.Settings.Default.LqGenContextNamespace;
  1098. }
  1099. }
  1100. /// <summary>
  1101. /// Retrieve the context name extended property value.
  1102. /// </summary>
  1103. /// <returns></returns>
  1104. public string GetContextName( )
  1105. {
  1106. if( _currentDatabase.ExtendedPr

Large files files are truncated, but you can click here to view the full file