PageRenderTime 73ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/SQLExtendedProperties/Main.cs

#
C# | 3437 lines | 2928 code | 158 blank | 351 comment | 308 complexity | c3c114966b51d33a957567511e1dd4c1 MD5 | raw 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.ExtendedProperties[ORM_CONTEXT_NAME] != null )
  1107. {
  1108. return _currentDatabase.ExtendedProperties[ORM_CONTEXT_NAME].Value.ToString( );
  1109. }
  1110. else
  1111. {
  1112. //If not exist the database property uses general preference value.
  1113. return Properties.Settings.Default.LqGenContextName;
  1114. }
  1115. }
  1116. /// <summary>
  1117. ///
  1118. /// </summary>
  1119. /// <returns></returns>
  1120. public string GetEntityNamespace( )
  1121. {
  1122. if( _currentDatabase.ExtendedProperties[ORM_ENTITY_NAMESPACE] != null )
  1123. {
  1124. return _currentDatabase.ExtendedProperties[ORM_ENTITY_NAMESPACE].Value.ToString( );
  1125. }
  1126. else
  1127. {
  1128. //If not exist the database property uses general preference value.
  1129. return Properties.Settings.Default.LqGenEntityNamespace;
  1130. }
  1131. }
  1132. /// <summary>
  1133. ///
  1134. /// </summary>
  1135. /// <returns></returns>
  1136. public string GetSavePath( )
  1137. {
  1138. if( _currentDatabase.ExtendedProperties[ORM_SAVEPATH] != null )
  1139. {
  1140. return _currentDatabase.ExtendedProperties[ORM_SAVEPATH].Value.ToString( );
  1141. }
  1142. else
  1143. {
  1144. //If not exist the database property uses general preference value.
  1145. return Properties.Settings.Default.LqGenSavePath;
  1146. }
  1147. }
  1148. public string GetContextImports( )
  1149. {
  1150. if( _currentDatabase.ExtendedProperties[ORM_CONTEXT_IMPORTS] != null )
  1151. {
  1152. return _currentDatabase.ExtendedProperties[ORM_CONTEXT_IMPORTS].Value.ToString( );
  1153. }
  1154. else
  1155. {
  1156. return string.Empty;
  1157. }
  1158. }
  1159. public string GetEntityImports( )
  1160. {
  1161. return _currentDatabase.ExtendedProperties["ORM_EntityImports"].Value.ToString( );
  1162. }
  1163. public string GetBaseClassProperty( )
  1164. {
  1165. if( _currentDatabase.ExtendedProperties["ORM_BaseClass"].Value != null )
  1166. {
  1167. return _currentDatabase.ExtendedProperties["ORM_BaseClass"].Value.ToString( ) + ", ";
  1168. }
  1169. else
  1170. {
  1171. return string.Empty;
  1172. }
  1173. }
  1174. public bool GetGenerateMultipleClassesOption( )
  1175. {
  1176. if( _currentDatabase.ExtendedProperties["ORM_GenerateMultipleClasses"] != null )
  1177. {
  1178. return Convert.ToBoolean( _currentDatabase.ExtendedProperties["ORM_GenerateMultipleClasses"].Value );
  1179. }
  1180. else
  1181. {
  1182. //If not exist the database property uses general preference value.
  1183. return Properties.Settings.Default.LqGenGenerateMultipleClasses;
  1184. }
  1185. }
  1186. public bool GetOnlySelectedTablesOption( )
  1187. {
  1188. if( _currentDatabase.ExtendedProperties["ORM_OnlySelectedTables"] != null )
  1189. {
  1190. return Convert.ToBoolean( _currentDatabase.ExtendedProperties["ORM_OnlySelectedTables"].Value );
  1191. }
  1192. else
  1193. {
  1194. //If not exist the database property uses general preference value.
  1195. return Properties.Settings.Default.LqGenOnlySelectedTables;
  1196. }
  1197. }
  1198. public bool GetIsSealedOption( )
  1199. {
  1200. if( _currentDatabase.ExtendedProperties["ORM_IsSealed"] != null )
  1201. {
  1202. //if serializable option is set at database level
  1203. if( Convert.ToBoolean( _currentDatabase.ExtendedProperties["ORM_IsSealed"].Value ) )
  1204. {
  1205. //At database level is true.
  1206. return true;
  1207. }
  1208. else
  1209. {
  1210. //At database level is false.
  1211. return false;
  1212. }
  1213. }
  1214. else
  1215. {
  1216. //If IsSealed set as setting.
  1217. if( Properties.Settings.Default.LqGenIsSealed )
  1218. {
  1219. return true;
  1220. }
  1221. else
  1222. {
  1223. return false;
  1224. }
  1225. }
  1226. }
  1227. public bool GetIsSealedOption( Table table )
  1228. {
  1229. if( table.ExtendedProperties["ORM_IsSealed"] != null )
  1230. {
  1231. //if serializable option is set at entity level
  1232. if( Convert.ToBoolean( table.ExtendedProperties["ORM_IsSealed"].Value ) )
  1233. {
  1234. //at table level is true.
  1235. return true;
  1236. }
  1237. else
  1238. {
  1239. //At table level is false.
  1240. return false;
  1241. }
  1242. }
  1243. //IsSeale does not exist at table level.
  1244. else
  1245. {
  1246. if( _currentDatabase.ExtendedProperties["ORM_IsSealed"] != null )
  1247. {
  1248. //if serializable option is set at database level
  1249. if( Convert.ToBoolean( _currentDatabase.ExtendedProperties["ORM_IsSealed"].Value ) )
  1250. {
  1251. //At database level is true.
  1252. return true;
  1253. }
  1254. else
  1255. {
  1256. //At database level is false.
  1257. return false;
  1258. }
  1259. }
  1260. else
  1261. {
  1262. //If IsSealed set as setting.
  1263. if( Properties.Settings.Default.LqGenIsSealed )
  1264. {
  1265. return true;
  1266. }
  1267. else
  1268. {
  1269. return false;
  1270. }
  1271. }
  1272. }
  1273. }
  1274. public bool GetIsSerializableOption( )
  1275. {
  1276. //Check if exist at database level.
  1277. if( _currentDatabase.ExtendedProperties["ORM_IsSerializable"] != null )
  1278. {
  1279. //if serializable option is set at database level
  1280. if( Convert.ToBoolean( _currentDatabase.ExtendedProperties["ORM_IsSerializable"].Value ) )
  1281. {
  1282. return true;
  1283. }
  1284. else
  1285. {
  1286. //at database level is false.
  1287. return false;
  1288. }
  1289. }
  1290. else
  1291. {
  1292. //If serialiableis set as setting.
  1293. if( Properties.Settings.Default.LqGenIsSerializable )
  1294. {
  1295. //finally at setting is true.
  1296. return true;
  1297. }
  1298. else
  1299. {
  1300. //finally at setting is false.
  1301. return false;
  1302. }
  1303. }
  1304. }
  1305. public bool GetIncludeCRUDFunctionsOption( )
  1306. {
  1307. //Check if exist at database level.
  1308. if( _currentDatabase.ExtendedProperties["ORM_IncludeCRUDFunctions"] != null )
  1309. {
  1310. //if serializable option is set at database level
  1311. if( Convert.ToBoolean( _currentDatabase.ExtendedProperties["ORM_IncludeCRUDFunctions"].Value ) )
  1312. {
  1313. return true;
  1314. }
  1315. else
  1316. {
  1317. //at database level is false.
  1318. return false;
  1319. }
  1320. }
  1321. else
  1322. {
  1323. //If serialiableis set as setting.
  1324. if( Properties.Settings.Default.LqGenIncludeCRUD)
  1325. {
  1326. //finally at setting is true.
  1327. return true;
  1328. }
  1329. else
  1330. {
  1331. //finally at setting is false.
  1332. return false;
  1333. }
  1334. }
  1335. }
  1336. public bool GetOverrideCRUDOperationsOption( )
  1337. {
  1338. //Check if exist at database level.
  1339. if( _currentDatabase.ExtendedProperties["ORM_OverrideCRUDOperations"] != null )
  1340. {
  1341. //if serializable option is set at database level
  1342. if( Convert.ToBoolean( _currentDatabase.ExtendedProperties["ORM_OverrideCRUDOperations"].Value ) )
  1343. {
  1344. return true;
  1345. }
  1346. else
  1347. {
  1348. //at database level is false.
  1349. return false;
  1350. }
  1351. }
  1352. else
  1353. {
  1354. //If serialiableis set as setting.
  1355. if( Properties.Settings.Default.LqGenOverriteCRUD)
  1356. {
  1357. //finally at setting is true.
  1358. return true;
  1359. }
  1360. else
  1361. {
  1362. //finally at setting is false.
  1363. return false;
  1364. }
  1365. }
  1366. }
  1367. public string ParseHelpEntityDescription( string value )
  1368. {
  1369. throw new NotImplementedException( );
  1370. }
  1371. public string GetTableDescription( Table table )
  1372. {
  1373. return table.ExtendedProperties[Properties.Settings.Default.DescriptionPropertyName].Value.ToString( );
  1374. }
  1375. public string GetConnectionAccessCode( )
  1376. {
  1377. return _currentDatabase.ExtendedProperties["ORM_ConnectionStringName"].Value.ToString( );
  1378. }
  1379. /// <summary>
  1380. /// Get the seriablizable option from table, database or setting.
  1381. /// </summary>
  1382. /// <param name="table"></param>
  1383. /// <returns></returns>
  1384. public bool GetIsSerializableOption( Table table )
  1385. {
  1386. if( table.ExtendedProperties["ORM_IsSerializable"] != null )
  1387. {
  1388. //if serializable option is set at entity level
  1389. if( Convert.ToBoolean( table.ExtendedProperties["ORM_IsSerializable"].Value ) )
  1390. {
  1391. return true;
  1392. }
  1393. //Is false;
  1394. else
  1395. {
  1396. //at table level is false.
  1397. return false;
  1398. }
  1399. }
  1400. //IsSealed not exist at table level.
  1401. else
  1402. {
  1403. //Check if exist at database level.
  1404. if( _currentDatabase.ExtendedProperties["ORM_IsSerializable"] != null )
  1405. {
  1406. //if serializable option is set at database level
  1407. if( Convert.ToBoolean( _currentDatabase.ExtendedProperties["ORM_IsSerializable"].Value ) )
  1408. {
  1409. return true;
  1410. }
  1411. else
  1412. {
  1413. //at database level is false.
  1414. return false;
  1415. }
  1416. }
  1417. else
  1418. {
  1419. //If serialiableis set as setting.
  1420. if( Properties.Settings.Default.LqGenIsSerializable )
  1421. {
  1422. //finally at setting is true.
  1423. return true;
  1424. }
  1425. else
  1426. {
  1427. //finally at setting is false.
  1428. return false;
  1429. }
  1430. }
  1431. }
  1432. }
  1433. public bool GetPreventingDebugOption( )
  1434. {
  1435. if( _currentDatabase.ExtendedProperties["ORM_IncludePreventingDebug"] != null )
  1436. {
  1437. return Convert.ToBoolean( _currentDatabase.ExtendedProperties["ORM_IncludePreventingDebug"].Value );
  1438. }
  1439. else
  1440. {
  1441. //If not exist the database property uses general preference value.
  1442. return Properties.Settings.Default.LqGenPreventDebug;
  1443. }
  1444. }
  1445. public string GetAttributePrimaryKey( Column column )
  1446. {
  1447. if( column.Identity )
  1448. {
  1449. return ", AutoSync=AutoSync.OnInsert, IsDbGenerated=true, DbType=\"Int NOT NULL IDENTITY\"";
  1450. }
  1451. if( column.RowGuidCol )
  1452. {
  1453. return ", AutoSync=AutoSync.OnInsert, IsDbGenerated=true, DbType=\"uniqueidentifier not null\"";
  1454. }
  1455. return string.Empty;
  1456. }
  1457. public Dictionary<Table, List<ForeignKey>> GetReverseForeignKeys( )
  1458. {
  1459. //Build a dictionary to store referenced keys by foreignKeys to coding EntityRefs.
  1460. Dictionary<Table, List<ForeignKey>> _reverseForeignKeys = new Dictionary<Table, List<ForeignKey>>( );
  1461. //Is necesary iterate through entire database to locate relationships.
  1462. foreach( Table table in _currentDatabase.Tables )
  1463. {
  1464. foreach( ForeignKey ForeignKey in table.ForeignKeys )
  1465. {
  1466. //Get the reference table.
  1467. Table _referencedTable = _currentDatabase.Tables[ForeignKey.ReferencedTable, ForeignKey.ReferencedTableSchema];
  1468. //
  1469. if( _reverseForeignKeys.ContainsKey( _referencedTable ) )
  1470. {
  1471. _reverseForeignKeys[_referencedTable].Add( ForeignKey );
  1472. }
  1473. else
  1474. {
  1475. List<ForeignKey> _foreignkeys = new List<ForeignKey>( );
  1476. _foreignkeys.Add( ForeignKey );
  1477. _reverseForeignKeys.Add( _referencedTable, _foreignkeys );
  1478. }
  1479. }
  1480. }
  1481. return _reverseForeignKeys;
  1482. }
  1483. public string GetDatacontextClassCode( List<Table> tables )
  1484. {
  1485. try
  1486. {
  1487. StringBuilder Output = new StringBuilder( );
  1488. Output.AppendLine( GetContextImports( ) );
  1489. Output.AppendLine( );
  1490. Output.AppendLine( string.Format( "namespace {0}", GetContextNamespace( ) ) );
  1491. Output.AppendLine( "{" );
  1492. Output.AppendLine( Indent( string.Format( "[DatabaseAttribute(Name=\"{0}\")]", _currentDatabase.Name ), 2 ) );
  1493. Output.AppendLine( Indent( string.Format( "public {0} partial class {1} : DataContext", GetIsSealedOption( ) ? "sealed" : "", GetContextName( ) ), 2 ) );
  1494. Output.AppendLine( Indent( "{", 2 ) );
  1495. Output.AppendLine( Indent( "private static MappingSource mappingSource = new AttributeMappingSource( );", 4 ) );
  1496. #region Ctors
  1497. //Ctors
  1498. Output.AppendLine( Indent( "#region Constructors", 4 ) );
  1499. //Ctor1
  1500. if( GetPreventingDebugOption( ) )
  1501. Output.AppendLine( Indent( "[System.Diagnostics.DebuggerNonUserCodeAttribute()]", 4 ) );
  1502. Output.AppendLine( Indent( string.Format( "public {0}() : base( {1}, mappingSource)", GetContextName( ), GetConnectionAccessCode( ) ), 4 ) );
  1503. Output.AppendLine( Indent( "{", 4 ) );
  1504. Output.AppendLine( Indent( "OnCreated( );", 6 ) );
  1505. Output.AppendLine( Indent( "}", 4 ) );
  1506. //Ctor2
  1507. if( GetPreventingDebugOption( ) )
  1508. Output.AppendLine( Indent( "[System.Diagnostics.DebuggerNonUserCodeAttribute()]", 4 ) );
  1509. Output.AppendLine( Indent( string.Format( "public {0}( string connection ) : base( connection, mappingSource )", GetContextName( ) ), 4 ) );
  1510. Output.AppendLine( Indent( "{", 4 ) );
  1511. Output.AppendLine( Indent( "OnCreated( );", 6 ) );
  1512. Output.AppendLine( Indent( "}", 4 ) );
  1513. //Ctor3
  1514. if( GetPreventingDebugOption( ) )
  1515. Output.AppendLine( Indent( "[System.Diagnostics.DebuggerNonUserCodeAttribute()]", 4 ) );
  1516. Output.AppendLine( Indent( string.Format( "public {0}( string connection, MappingSource mappingSource) : base( connection, mappingSource )", GetContextName( ) ), 4 ) );
  1517. Output.AppendLine( Indent( "{", 4 ) );
  1518. Output.AppendLine( Indent( "OnCreated( );", 6 ) );
  1519. Output.AppendLine( Indent( "}", 4 ) );
  1520. //Ctor4
  1521. if( GetPreventingDebugOption( ) )
  1522. Output.AppendLine( Indent( "[System.Diagnostics.DebuggerNonUserCodeAttribute()]", 4 ) );
  1523. Output.AppendLine( Indent( string.Format( "public {0}( IDbConnection connection ) : base( connection, mappingSource )", GetContextName( ) ), 4 ) );
  1524. Output.AppendLine( Indent( "{", 4 ) );
  1525. Output.AppendLine( Indent( "OnCreated( );", 6 ) );
  1526. Output.AppendLine( Indent( "}", 4 ) );
  1527. //Ctor5
  1528. if( GetPreventingDebugOption( ) )
  1529. Output.AppendLine( Indent( "[System.Diagnostics.DebuggerNonUserCodeAttribute()]", 4 ) );
  1530. Output.AppendLine( Indent( string.Format( "public {0}( IDbConnection connection, MappingSource mappingSource) : base( connection, mappingSource )", GetContextName( ) ), 4 ) );
  1531. Output.AppendLine( Indent( "{", 4 ) );
  1532. Output.AppendLine( Indent( "OnCreated( );", 6 ) );
  1533. Output.AppendLine( Indent( "}", 4 ) );
  1534. Output.AppendLine( Indent( "#endregion", 4 ) );
  1535. #endregion
  1536. #region Extend
  1537. //Extensibility
  1538. Output.AppendLine( Indent( "#region Extensibility", 4 ) );
  1539. Output.AppendLine( Indent( "partial void OnCreated();", 4 ) );
  1540. Output.AppendLine( Indent( "#endregion", 4 ) );
  1541. #endregion
  1542. #region Tables
  1543. //Tables
  1544. Output.AppendLine( Indent( "#region Tables", 4 ) );
  1545. foreach( Table table in tables )
  1546. {
  1547. Output.AppendLine( Indent( "///", 4 ) );
  1548. Output.AppendLine( Indent( string.Format( "///Table {0}", table.Name ), 4 ) );
  1549. Output.AppendLine( Indent( "///", 4 ) );
  1550. Output.AppendLine( Indent( string.Format( "public Table<{0}> {1}", GetEntityName( table ), GetEntityPluralName( table ) ), 4 ) );
  1551. Output.AppendLine( Indent( "{", 4 ) );
  1552. Output.AppendLine( Indent( "get", 6 ) );
  1553. Output.AppendLine( Indent( "{", 6 ) );
  1554. Output.AppendLine( Indent( string.Format( "return this.GetTable<{0}>();", GetEntityName( table ) ), 8 ) );
  1555. Output.AppendLine( Indent( "}", 6 ) );
  1556. Output.AppendLine( Indent( "}", 4 ) );
  1557. }
  1558. Output.AppendLine( Indent( "#endregion", 4 ) );
  1559. #endregion
  1560. #region Functions
  1561. //Functions
  1562. Output.AppendLine( Indent( "#region Functions", 4 ) );
  1563. if( GetIncludeCRUDFunctionsOption( ) )
  1564. {
  1565. foreach( Table table in tables )
  1566. {
  1567. Output.AppendLine( Indent( "#region " + table.Name, 6 ) );
  1568. #region InsertFunction
  1569. Output.AppendLine( Indent( "//Insert", 6 ) );
  1570. //if exist a Crud insert defined.
  1571. if( table.ExtendedProperties[ORM_CRUD_INSERT] != null )
  1572. {
  1573. string FunctionName = table.ExtendedProperties[ORM_CRUD_INSERT].Value.ToString( );
  1574. //If exist a stored procedures to mapping.
  1575. if( _currentDatabase.StoredProcedures.OfType<StoredProcedure>( ).Where( c => c.Name == FunctionName ).Count( ) > 0 )
  1576. {
  1577. //Get stored procedure input parameters.
  1578. StoredProcedureParameterCollection Parameters = _currentDatabase.StoredProcedures
  1579. .OfType<StoredProcedure>( )
  1580. .Where( c => c.Name == FunctionName )
  1581. .Single( ).Parameters;
  1582. int i = 1;
  1583. //If must override runtime insert
  1584. if( GetOverrideCRUDOperationsOption( ) )
  1585. {
  1586. Output.AppendLine( Indent( string.Format( "private void Insert{0}({0} obj)", GetEntityName( table ) ), 6 ) );
  1587. Output.AppendLine( Indent( "{", 6 ) );
  1588. Output.AppendLine( Indent( string.Format( "this.Crear{0}(", GetEntityName( table ) ), 10 ) );
  1589. foreach( Parameter parameter in Parameters )
  1590. {
  1591. Output.AppendLine( Indent( string.Format( "({0}) obj.{1}{2}", GetNullableClrType( table.Columns[parameter.Name.Replace( "@", "" )] ), parameter.Name.Replace( "@", "" ), Parameters.Count > i ? "," : ");" ), 14 ) );
  1592. i++;
  1593. }
  1594. //
  1595. Output.AppendLine( Indent( "}", 6 ) );
  1596. }
  1597. else
  1598. {
  1599. Output.AppendLine( Indent( string.Format( "partial void Insert{0}({0} instance);", GetEntityName( table ) ), 6 ) );
  1600. }
  1601. Output.AppendLine( Indent( string.Format( "[Function(Name=\"{0}.{1}\")]", table.Schema, FunctionName ), 6 ) );
  1602. Output.AppendLine( Indent( string.Format( "public ISingleResult<{0}> Crear{0}(", GetEntityName( table ) ), 6 ) );
  1603. i = 1;
  1604. foreach( Parameter parameter in Parameters )
  1605. {
  1606. Output.AppendLine( Indent( string.Format( "[Parameter(Name=\"{0}\", DbType=\"{1}\")] {2} {0}{3}", ParseParameterName( parameter.Name ), GetSimpleDbType( table.Columns[ParseParameterName( parameter.Name )] ), GetNullableClrType( table.Columns[ParseParameterName( parameter.Name )] ), Parameters.Count > i ? "," : ")" ), 14 ) );
  1607. i++;
  1608. }
  1609. Output.AppendLine( Indent( "{", 6 ) );
  1610. Output.AppendLine( Indent( "IExecuteResult result = ExecuteMethodCall(this, (MethodInfo) MethodInfo.GetCurrentMethod(),", 8 ) );
  1611. i = 1;
  1612. foreach( Parameter parameter in Parameters )
  1613. {
  1614. Output.AppendLine( Indent( string.Format( "{0}{1}", ParseParameterName( parameter.Name ), Parameters.Count > i ? "," : ");" ), 14 ) );
  1615. i++;
  1616. }
  1617. Output.AppendLine( Indent( string.Format( "return (ISingleResult<{0}>) result.ReturnValue;", GetEntityName( table ) ), 8 ) );
  1618. Output.AppendLine( Indent( "}", 6 ) );
  1619. }
  1620. else
  1621. {
  1622. Output.AppendLine( Indent( string.Format( "partial void Insert{0}({0} instance);", GetEntityName( table ) ), 6 ) );
  1623. }
  1624. }
  1625. else
  1626. {
  1627. Output.AppendLine( Indent( string.Format( "partial void Insert{0}({0} instance);", GetEntityName( table ) ), 6 ) );
  1628. }
  1629. #endregion
  1630. #region UpdateFunction
  1631. Output.AppendLine( Indent( "//Update", 6 ) );
  1632. //if exist Crud update extended property.
  1633. if( table.ExtendedProperties[ORM_CRUD_UPDATE] != null )
  1634. {
  1635. string FunctionName = table.ExtendedProperties[ORM_CRUD_UPDATE].Value.ToString( );
  1636. //If exist a stored procedures to mapping.
  1637. if( _currentDatabase.StoredProcedures.OfType<StoredProcedure>( ).Where( c => c.Name == FunctionName ).Count( ) > 0 )
  1638. {
  1639. //Get stored procedure input parameters.
  1640. StoredProcedureParameterCollection Parameters = _currentDatabase.StoredProcedures.OfType<StoredProcedure>( ).Where( c => c.Name == FunctionName ).Single( ).Parameters;
  1641. int i = 1;
  1642. //If must override runtime update
  1643. if( GetOverrideCRUDOperationsOption( ) )
  1644. {
  1645. Output.AppendLine( Indent( string.Format( "private void Update{0}({0} obj)", GetEntityName( table ) ), 6 ) );
  1646. Output.AppendLine( Indent( "{", 6 ) );
  1647. Output.AppendLine( Indent( string.Format( "this.Actualizar{0}(", GetEntityName( table ) ), 10 ) );
  1648. foreach( Parameter parameter in Parameters )
  1649. {
  1650. Output.AppendLine( Indent( string.Format( "({0}) obj.{1}{2}", GetNullableClrType( table.Columns[parameter.Name.Replace( "@", "" )] ), parameter.Name.Replace( "@", "" ), Parameters.Count > i ? "," : ");" ), 14 ) );
  1651. i++;
  1652. }
  1653. //
  1654. Output.AppendLine( Indent( "}", 6 ) );
  1655. }else
  1656. {
  1657. Output.AppendLine( Indent( string.Format( "partial void Update{0}({0} instance);", GetEntityName( table ) ), 6 ) );
  1658. }
  1659. Output.AppendLine( Indent( string.Format( "[Function(Name=\"{0}.{1}\")]", table.Schema, FunctionName ), 6 ) );
  1660. Output.AppendLine( Indent( string.Format( "public int? Actualizar{0}(", GetEntityName( table ) ), 6 ) );
  1661. i = 1;
  1662. foreach( Parameter parameter in Parameters )
  1663. {
  1664. Output.AppendLine( Indent( string.Format( "[Parameter(Name=\"{0}\", DbType=\"{1}\")] {2} {0}{3}", ParseParameterName( parameter.Name ), GetSimpleDbType( table.Columns[ParseParameterName( parameter.Name )] ), GetNullableClrType( table.Columns[ParseParameterName( parameter.Name )] ), Parameters.Count > i ? "," : ")" ), 14 ) );
  1665. i++;
  1666. }
  1667. Output.AppendLine( Indent( "{", 6 ) );
  1668. Output.AppendLine( Indent( "IExecuteResult result = ExecuteMethodCall(this, (MethodInfo) MethodInfo.GetCurrentMethod(),", 8 ) );
  1669. i = 1;
  1670. foreach( Parameter parameter in Parameters )
  1671. {
  1672. Output.AppendLine( Indent( string.Format( "{0}{1}", ParseParameterName( parameter.Name ), Parameters.Count > i ? "," : ");" ), 14 ) );
  1673. i++;
  1674. }
  1675. Output.AppendLine( Indent( string.Format( "return (int?) result.ReturnValue;", GetEntityName( table ) ), 8 ) );
  1676. Output.AppendLine( Indent( "}", 6 ) );
  1677. }
  1678. else
  1679. {
  1680. Output.AppendLine( Indent( string.Format( "partial void Update{0}({0} instance);", GetEntityName( table ) ), 6 ) );
  1681. }
  1682. }
  1683. else
  1684. {
  1685. Output.AppendLine( Indent( string.Format( "partial void Update{0}({0} instance);", GetEntityName( table ) ), 6 ) );
  1686. }
  1687. #endregion
  1688. #region DeleteFunction
  1689. Output.AppendLine( Indent( "//Delete", 6 ) );
  1690. if( table.ExtendedProperties[ORM_CRUD_DELETE] != null )
  1691. {
  1692. string FunctionName = table.ExtendedProperties[ORM_CRUD_DELETE].Value.ToString( );
  1693. //If exist a stored procedures to mapping.
  1694. if( _currentDatabase.StoredProcedures.OfType<StoredProcedure>( ).Where( c => c.Name == FunctionName ).Count( ) > 0 )
  1695. {
  1696. //Get stored procedure input parameters.
  1697. StoredProcedureParameterCollection Parameters = _currentDatabase.StoredProcedures.OfType<StoredProcedure>( ).Where( c => c.Name == FunctionName ).Single( ).Parameters;
  1698. int i = 1;
  1699. //If must override runtime delete
  1700. if( GetOverrideCRUDOperationsOption( ) )
  1701. {
  1702. Output.AppendLine( Indent( string.Format( "private void Delete{0}({0} obj)", GetEntityName( table ) ), 6 ) );
  1703. Output.AppendLine( Indent( "{", 6 ) );
  1704. Output.AppendLine( Indent( string.Format( "this.Eliminar{0}(", GetEntityName( table ) ), 10 ) );
  1705. foreach( Parameter parameter in Parameters )
  1706. {
  1707. Output.AppendLine( Indent( string.Format( "({0}) obj.{1}{2}", GetNullableClrType( table.Columns[parameter.Name.Replace( "@", "" )] ), parameter.Name.Replace( "@", "" ), Parameters.Count > i ? "," : ");" ), 14 ) );
  1708. i++;
  1709. }
  1710. //
  1711. Output.AppendLine( Indent( "}", 6 ) );
  1712. }else
  1713. {
  1714. Output.AppendLine( Indent( string.Format( "partial void Delete{0}({0} instance);", GetEntityName( table ) ), 6 ) );
  1715. }
  1716. Output.AppendLine( Indent( string.Format( "[Function(Name=\"{0}.{1}\")]", table.Schema, FunctionName ), 6 ) );
  1717. Output.AppendLine( Indent( string.Format( "public int? Eliminar{0}(", GetEntityName( table ) ), 6 ) );
  1718. i = 1;
  1719. foreach( Parameter parameter in Parameters )
  1720. {
  1721. Output.AppendLine( Indent( string.Format( "[Parameter(Name=\"{0}\", DbType=\"{1}\")] {2} {0}{3}", ParseParameterName( parameter.Name ), GetSimpleDbType( table.Columns[ParseParameterName( parameter.Name )] ), GetNullableClrType( table.Columns[ParseParameterName( parameter.Name )] ), Parameters.Count > i ? "," : ")" ), 14 ) );
  1722. i++;
  1723. }
  1724. Output.AppendLine( Indent( "{", 6 ) );
  1725. Output.AppendLine( Indent( "IExecuteResult result = ExecuteMethodCall(this, (MethodInfo) MethodInfo.GetCurrentMethod(),", 8 ) );
  1726. i = 1;
  1727. foreach( Parameter parameter in Parameters )
  1728. {
  1729. Output.AppendLine( Indent( string.Format( "{0}{1}", ParseParameterName( parameter.Name ), Parameters.Count > i ? "," : ");" ), 14 ) );
  1730. i++;
  1731. }
  1732. Output.AppendLine( Indent( string.Format( "return (int?) result.ReturnValue;", GetEntityName( table ) ), 8 ) );
  1733. Output.AppendLine( Indent( "}", 6 ) );
  1734. }
  1735. else
  1736. {
  1737. Output.AppendLine( Indent( string.Format( "partial void Delete{0}({0} instance);", GetEntityName( table ) ), 6 ) );
  1738. }
  1739. }
  1740. else
  1741. {
  1742. Output.AppendLine( Indent( string.Format( "partial void Delete{0}({0} instance);", GetEntityName( table ) ), 6 ) );
  1743. }
  1744. #endregion
  1745. Output.AppendLine( Indent( "#endregion", 6 ) );
  1746. }
  1747. }
  1748. else
  1749. {
  1750. foreach( Table table in tables )
  1751. {
  1752. Output.AppendLine( Indent( "#region " + table.Name, 6 ) );
  1753. Output.AppendLine( Indent( string.Format( "partial void Insert{0}( {0} instance );", GetEntityName( table ) ), 6 ) );
  1754. Output.AppendLine( Indent( string.Format( "partial void Update{0}( {0} instance );", GetEntityName( table ) ), 6 ) );
  1755. Output.AppendLine( Indent( string.Format( "partial void Delete{0}( {0} instance );", GetEntityName( table ) ), 6 ) );
  1756. Output.AppendLine( Indent( "#endregion", 6 ) );
  1757. }
  1758. }
  1759. Output.AppendLine( Indent( "#endregion", 4 ) );
  1760. #endregion
  1761. //
  1762. Output.AppendLine( Indent( "}", 2 ) );
  1763. Output.AppendLine( "}" );
  1764. return Output.ToString( );
  1765. }
  1766. catch( Exception ex ) { throw; }
  1767. }
  1768. public string GetEntityClassCode( Table table, List<Table> tables )
  1769. {
  1770. //Initializations
  1771. Dictionary<Table, List<ForeignKey>> _reverseForeignKeys = GetReverseForeignKeys( );
  1772. //
  1773. StringBuilder Output = new StringBuilder( );
  1774. Output.AppendLine( GetEntityImports() );
  1775. Output.AppendLine( );
  1776. Output.AppendLine( string.Format( "namespace {0}", GetEntityNamespace( ) ) );
  1777. Output.AppendLine( "{" );
  1778. Output.AppendLine( Indent( "///<Summary>", 2 ) );
  1779. Output.AppendLine( Indent( string.Format( "///{0}", ""), 2 ) );
  1780. Output.AppendLine( Indent( "///</Summary>", 2 ) );
  1781. Output.AppendLine( Indent( string.Format( "[Table(Name=\"{0}.{1}\")]", table.Schema, table.Name ), 2 ) );
  1782. if( GetIsSerializableOption( table ) )
  1783. {
  1784. Output.AppendLine( Indent( string.Format( "[DataContract()][KnownType(typeof({0}))]", GetEntityName( table ) ), 2 ) );
  1785. }
  1786. if( GetIsSealedOption( table ) )
  1787. {
  1788. Output.AppendLine( Indent( string.Format( "public sealed partial class {0} :{1} INotifyPropertyChanging, INotifyPropertyChanged", GetEntityName( table ), GetBaseClassProperty() ), 2 ) );
  1789. }
  1790. else
  1791. {
  1792. Output.AppendLine( Indent( string.Format( "public partial class {0} :{1} INotifyPropertyChanging, INotifyPropertyChanged", GetEntityName( table ), GetBaseClassProperty( ) ), 2 ) );
  1793. }
  1794. Output.AppendLine( Indent( "{", 2 ) );
  1795. //Variables used in ab above code.
  1796. int DataMemberCounter = 1;
  1797. int Counter = 1;
  1798. string Temp = string.Empty;
  1799. string EntityPluralName = string.Empty;
  1800. string EntityName = string.Empty;
  1801. string EntityRefEntityName = string.Empty;
  1802. string EntityRefEntityPluralName = string.Empty;
  1803. string EntityRefGenName = string.Empty;
  1804. string EntityGenSimpleName = string.Empty;
  1805. string EntityGenName = string.Empty;
  1806. //*****Fields*********
  1807. #region Fields
  1808. Output.AppendLine( Indent( "#region Fields", 6 ) );
  1809. foreach( Column column in table.Columns)
  1810. {
  1811. Output.AppendLine( Indent( string.Format( "private {0} _{1};", GetNullableClrType( column ), column.Name ), 6 ) );
  1812. }
  1813. //EntityRef fields Inicialization
  1814. Counter = 1;
  1815. Temp = string.Empty;
  1816. //
  1817. if( table.ForeignKeys.Count > 0 )
  1818. {
  1819. foreach( ForeignKey foreignKey in table.ForeignKeys )
  1820. {
  1821. EntityRefEntityName = GetEntityName( GetReferencedTable( foreignKey ) );
  1822. EntityRefGenName = EntityRefEntityName;
  1823. //Obtain the referenced primarykey reference name.
  1824. string ReferenceKeyEntityName = GetColumnReferenceName( foreignKey.Parent.Columns[foreignKey.Columns[0].Name] );
  1825. //If exist use it but generate alternative name.
  1826. if( ReferenceKeyEntityName != null )
  1827. {
  1828. EntityRefGenName = ReferenceKeyEntityName;
  1829. }
  1830. else
  1831. {
  1832. //To avoid duplicate foreignKeys reference. Append counter.
  1833. if( !( string.IsNullOrEmpty( Temp ) ) )
  1834. {
  1835. if( Temp == EntityRefGenName )
  1836. {
  1837. EntityRefGenName = EntityRefEntityName + Counter;
  1838. Counter++;
  1839. Temp = EntityRefGenName;
  1840. }
  1841. else
  1842. {
  1843. EntityRefGenName = EntityRefEntityName;
  1844. Temp = EntityRefGenName;
  1845. }
  1846. }
  1847. else
  1848. {
  1849. EntityRefGenName = EntityRefEntityName;
  1850. Temp = EntityRefGenName;
  1851. }
  1852. }
  1853. Output.AppendLine( Indent( string.Format( "private EntityRef<{0}> _{1};", EntityRefEntityName, EntityRefGenName ), 6 ) );
  1854. }
  1855. }
  1856. //EntitySet fields Inizialization
  1857. Counter = 1;
  1858. Temp = string.Empty;
  1859. //
  1860. if( _reverseForeignKeys.ContainsKey( table ) )
  1861. {
  1862. foreach( ForeignKey foreignKey in _reverseForeignKeys[table] )
  1863. {
  1864. EntityPluralName = GetEntityPluralName( foreignKey.Parent );
  1865. EntityName = GetEntityName( foreignKey.Parent );
  1866. EntityGenName = EntityPluralName;
  1867. //Obtain the referenced primarykey reference name.
  1868. string ColumnReferencePluralName = GetColumnReferencePluralName( foreignKey.Parent.Columns[foreignKey.Columns[0].Name] );
  1869. //Is exist use it but generate alternative name.
  1870. if( ColumnReferencePluralName != null )
  1871. {
  1872. EntityGenName = ColumnReferencePluralName;
  1873. }
  1874. else
  1875. {
  1876. //To avoid duplicate.
  1877. if( !( string.IsNullOrEmpty( Temp ) ) )
  1878. {
  1879. if( Temp == EntityGenName )
  1880. {
  1881. EntityGenName = EntityPluralName + Counter;
  1882. Counter++;
  1883. Temp = EntityGenName;
  1884. }
  1885. else
  1886. {
  1887. EntityGenName = EntityPluralName;
  1888. Temp = EntityGenName;
  1889. }
  1890. }
  1891. else
  1892. {
  1893. EntityGenName = EntityPluralName;
  1894. Temp = EntityGenName;
  1895. }
  1896. }
  1897. Output.AppendLine( Indent( string.Format( "private EntitySet<{0}> _{1};", EntityName, EntityGenName ), 6 ) );
  1898. }
  1899. }
  1900. Output.AppendLine( Indent( "private bool serializing;", 6 ) );
  1901. Output.AppendLine( Indent( "#endregion", 6 ) );
  1902. #endregion
  1903. #region Ctors
  1904. Output.AppendLine( Indent( "#region Ctors", 6 ) );
  1905. if( GetPreventingDebugOption( ) )
  1906. Output.AppendLine( Indent( "[System.Diagnostics.DebuggerNonUserCodeAttribute()]", 6 ) );
  1907. Output.AppendLine( Indent( string.Format( "public {0}()", GetEntityName( table ) ), 6 ) );
  1908. Output.AppendLine( Indent( "{", 6 ) );
  1909. Output.AppendLine( Indent( "this.Initialize();", 8 ) );
  1910. Output.AppendLine( Indent( "}", 6 ) );
  1911. Output.AppendLine( Indent( "private void Initialize()", 6 ) );
  1912. Output.AppendLine( Indent( "{", 6 ) );
  1913. //Ctor EntitySet Inizialization.
  1914. Counter = 1;
  1915. Temp = string.Empty;
  1916. //
  1917. if( _reverseForeignKeys.ContainsKey( table ) )
  1918. {
  1919. foreach( ForeignKey foreignKey in _reverseForeignKeys[table] )
  1920. {
  1921. EntityPluralName = GetEntityPluralName( foreignKey.Parent );
  1922. EntityName = GetEntityName( foreignKey.Parent );
  1923. EntityGenName = EntityPluralName;
  1924. string ColumnReferencePluralName = GetColumnReferencePluralName( foreignKey.Parent.Columns[foreignKey.Columns[0].Name] );
  1925. //Is exist use it but generate alternative name.
  1926. if( ColumnReferencePluralName != null )
  1927. {
  1928. EntityGenName = ColumnReferencePluralName;
  1929. }
  1930. else
  1931. {
  1932. //To avoid duplicate.
  1933. if( !( string.IsNullOrEmpty( Temp ) ) )
  1934. {
  1935. if( Temp == EntityGenName )
  1936. {
  1937. EntityGenName = EntityPluralName + Counter;
  1938. Counter++;
  1939. Temp = EntityGenName;
  1940. }
  1941. else
  1942. {
  1943. EntityGenName = EntityPluralName;
  1944. Temp = EntityGenName;
  1945. }
  1946. }
  1947. else
  1948. {
  1949. EntityGenName = EntityPluralName;
  1950. Temp = EntityGenName;
  1951. }
  1952. }
  1953. Output.AppendLine( Indent( string.Format( "this._{0} = new EntitySet<{1}>(", EntityGenName, EntityName ), 8 ) );
  1954. Output.AppendLine( Indent( string.Format( "new Action<{0}>(this.attach_{1}),", EntityName, EntityGenName ), 14 ) );
  1955. Output.AppendLine( Indent( string.Format( "new Action<{0}>(this.detach_{1}));", EntityName, EntityGenName ), 14 ) );
  1956. }
  1957. }
  1958. //Ctor EntityRef inizialization.
  1959. Counter = 1;
  1960. Temp = string.Empty;
  1961. //
  1962. if( table.ForeignKeys.Count > 0 )
  1963. {
  1964. foreach( ForeignKey foreignKey in table.ForeignKeys )
  1965. {
  1966. EntityRefEntityName = GetEntityName( GetReferencedTable( foreignKey ) );
  1967. EntityRefGenName = EntityRefEntityName;
  1968. //Obtain the referenced primarykey reference name.
  1969. string ReferenceKeyEntityName = GetColumnReferenceName( foreignKey.Parent.Columns[foreignKey.Columns[0].Name] );
  1970. //If exist use it but generate alternative name.
  1971. if( ReferenceKeyEntityName != null )
  1972. {
  1973. EntityRefGenName = ReferenceKeyEntityName;
  1974. }
  1975. else
  1976. {
  1977. //To avoid duplicate foreignKeys reference. Append counter.
  1978. if( !( string.IsNullOrEmpty( Temp ) ) )
  1979. {
  1980. if( Temp == EntityRefGenName )
  1981. {
  1982. EntityRefGenName = EntityRefEntityName + Counter;
  1983. Counter++;
  1984. Temp = EntityRefGenName;
  1985. }
  1986. else
  1987. {
  1988. EntityRefGenName = EntityRefEntityName;
  1989. Temp = EntityRefGenName;
  1990. }
  1991. }
  1992. else
  1993. {
  1994. EntityRefGenName = EntityRefEntityName;
  1995. Temp = EntityRefGenName;
  1996. }
  1997. }
  1998. Output.AppendLine( Indent( string.Format( "this._{1} = default( EntityRef<{0}>);", EntityRefEntityName, EntityRefGenName ), 8) );
  1999. }
  2000. }
  2001. Output.AppendLine( Indent( "OnCreated( );", 8 ) );
  2002. Output.AppendLine( Indent( "}", 6 ) );
  2003. Output.AppendLine( Indent( "#endregion", 6 ) );
  2004. #endregion
  2005. #region Columns
  2006. Output.AppendLine( Indent( "#region Columns", 6 ) );
  2007. //Column inizialization.
  2008. Counter = 1;
  2009. //
  2010. foreach( Column column in table.Columns )
  2011. {
  2012. Output.AppendLine( Indent( string.Format( "[Column(Storage=\"_{0}\", Name=\"{0}\" {1}{2}{3})]", column.Name, GetAttributePrimaryKey(column), column.InPrimaryKey ? ", IsPrimaryKey=true":"", column.Nullable ? "":", CanBeNull=false" ), 6 ) );
  2013. if( GetIsSerializableOption( table ) )
  2014. {
  2015. Output.AppendLine( Indent( string.Format( "[DataMember(Order={0})]", DataMemberCounter ), 6 ) );
  2016. }
  2017. Output.AppendLine( Indent( string.Format( "public {0} {1}", GetNullableClrType( column ), column.Name ), 6 ) );
  2018. Output.AppendLine( Indent( "{", 6 ) );
  2019. Output.AppendLine( Indent( "get", 8 ) );
  2020. Output.AppendLine( Indent( "{", 8 ) );
  2021. Output.AppendLine( Indent( string.Format( "return this._{0};", column.Name ), 10 ) );
  2022. Output.AppendLine( Indent( "}", 8 ) );
  2023. Output.AppendLine( Indent( "set", 8 ) );
  2024. Output.AppendLine( Indent( "{", 8 ) );
  2025. Output.AppendLine( Indent( string.Format( "if (this._{0} != value)", column.Name ), 10 ) );
  2026. Output.AppendLine( Indent( "{", 10 ) );
  2027. Output.AppendLine( Indent( string.Format( "this.On{0}Changing(value);", column.Name ), 12 ) );
  2028. Output.AppendLine( Indent( "this.OnPropertyChanging();", 12 ) );
  2029. Output.AppendLine( Indent( string.Format( "this._{0} = value;", column.Name ), 12 ) );
  2030. Output.AppendLine( Indent( string.Format( "this.OnPropertyChanged(\"{0}\");", column.Name ), 12 ) );
  2031. Output.AppendLine( Indent( string.Format( "this.On{0}Changed();", column.Name ), 12 ) );
  2032. Output.AppendLine( Indent( "}", 10 ) );
  2033. Output.AppendLine( Indent( "}", 8) );
  2034. Output.AppendLine( Indent( "}", 6) );
  2035. //
  2036. Counter++;
  2037. DataMemberCounter++;
  2038. }
  2039. Output.AppendLine( Indent( "#endregion", 6 ) );
  2040. #endregion
  2041. #region EntityRef Associations
  2042. Output.AppendLine( Indent( "#region EntityRef Associations", 6 ) );
  2043. //Association entityRef inizialization.
  2044. Counter = 1;
  2045. Temp = string.Empty;
  2046. //
  2047. foreach( ForeignKey foreignkey in table.ForeignKeys )
  2048. {
  2049. EntityName = GetEntityName(table);
  2050. EntityPluralName = GetEntityPluralName(table);
  2051. EntityRefEntityName = GetEntityName( GetReferencedTable( foreignkey ) );
  2052. EntityRefEntityPluralName = GetEntityPluralName( GetReferencedTable( foreignkey ) );
  2053. EntityRefGenName = EntityRefEntityName;
  2054. //Obtain the referenced primarykey reference name.
  2055. string ReferenceKeyEntityName = GetColumnReferenceName( foreignkey.Parent.Columns[foreignkey.Columns[0].Name] );
  2056. string ReferenceKeyPluralName = GetColumnReferencePluralName( foreignkey.Parent.Columns[foreignkey.Columns[0].Name] );
  2057. //If exist use it but generate alternative name.
  2058. if( ReferenceKeyEntityName != null )
  2059. {
  2060. //Take properties column values.
  2061. EntityRefGenName = ReferenceKeyEntityName;
  2062. EntityRefEntityPluralName = ReferenceKeyPluralName;
  2063. }
  2064. else
  2065. {
  2066. EntityRefEntityPluralName = GetEntityPluralName( table );
  2067. //Generate names.
  2068. if( !( string.IsNullOrEmpty( Temp ) ) )
  2069. {
  2070. //if _temp3 = next foreignkey plural name.
  2071. if( Temp == EntityRefGenName )
  2072. {
  2073. EntityRefGenName = GetEntityName( GetReferencedTable( foreignkey ) ) + Counter;
  2074. Counter++;
  2075. Temp = EntityRefGenName;
  2076. }
  2077. else
  2078. {
  2079. EntityRefGenName = GetEntityName( GetReferencedTable( foreignkey ) );
  2080. Temp = EntityRefGenName;
  2081. }
  2082. }
  2083. else
  2084. {
  2085. EntityRefGenName = GetEntityName( GetReferencedTable( foreignkey ) );
  2086. Temp = EntityRefGenName;
  2087. }
  2088. }
  2089. //Get the foreingKey column name.
  2090. string ThisKey = foreignkey.Columns[0].Name;
  2091. //Get the column name of primary key referenced by this foreignkey.
  2092. string OtherKey = GetReferencedTable( foreignkey ).Columns.OfType<Column>( ).Where( c => c.InPrimaryKey == true ).First( ).Name;
  2093. //
  2094. Output.AppendLine( Indent( string.Format( "[Association(Name=\"{0}\", Storage=\"_{1}\", ThisKey=\"{2}\", OtherKey=\"{3}\", {4})]", ParseForeignkeyName( foreignkey.Name ), EntityRefGenName, ThisKey, OtherKey, "IsForeignKey=true" ), 6 ) );
  2095. Output.AppendLine( Indent( string.Format( "public {0} {1}", EntityRefEntityName, EntityRefGenName ), 6 ) );
  2096. Output.AppendLine( Indent( "{", 6 ) );
  2097. Output.AppendLine( Indent( "get", 8 ) );
  2098. Output.AppendLine( Indent( "{", 8 ) );
  2099. Output.AppendLine( Indent( string.Format( "return this._{0}.Entity;", EntityRefGenName ), 10 ) );
  2100. Output.AppendLine( Indent( "}", 8) );
  2101. Output.AppendLine( Indent( "set", 8 ) );
  2102. Output.AppendLine( Indent( "{", 8 ) );
  2103. Output.AppendLine( Indent( string.Format( "{0} previousValue = this._{1}.Entity;", EntityRefEntityName, EntityRefGenName ), 10 ) );
  2104. Output.AppendLine( Indent( string.Format( "if ((previousValue != value) || (this._{0}.HasLoadedOrAssignedValue == false))", EntityRefGenName ), 10 ) );
  2105. Output.AppendLine( Indent( "{", 10 ) );
  2106. Output.AppendLine( Indent( "this.OnPropertyChanging();", 12 ) );
  2107. Output.AppendLine( Indent( "if ((previousValue != null))", 12 ) );
  2108. Output.AppendLine( Indent( "{", 12 ) );
  2109. Output.AppendLine( Indent( string.Format( "this._{0}.Entity = null;", EntityRefGenName ), 14 ) );
  2110. Output.AppendLine( Indent( string.Format( "previousValue.{0}.Remove(this);", EntityRefEntityPluralName ), 14 ) );
  2111. Output.AppendLine( Indent( "}", 12 ) );
  2112. Output.AppendLine( Indent( string.Format( "this._{0}.Entity = value;", EntityRefGenName ), 12 ) );
  2113. Output.AppendLine( Indent( "if ((value != null))", 12 ) );
  2114. Output.AppendLine( Indent( "{", 12 ) );
  2115. Output.AppendLine( Indent( string.Format( "value.{0}.Add(this);", EntityRefEntityPluralName ), 14 ) );
  2116. Output.AppendLine( Indent( string.Format( "this.{0} = value.{1};", ThisKey, OtherKey ), 14 ) );
  2117. Output.AppendLine( Indent( "}else{", 12 ) );
  2118. Output.AppendLine( Indent( string.Format( "this.{0} = default({1});", ThisKey, GetNullableClrType( table.Columns[ThisKey] ) ), 14 ) );
  2119. Output.AppendLine( Indent( "}", 12 ) );
  2120. Output.AppendLine( Indent( string.Format( "this.OnPropertyChanged(\"{0}\");", EntityRefGenName ), 12 ) );
  2121. Output.AppendLine( Indent( "}", 10 ) );
  2122. Output.AppendLine( Indent( "}", 8 ) );
  2123. Output.AppendLine( Indent( "}", 6 ) );
  2124. //Incremente member order.
  2125. DataMemberCounter++;
  2126. }
  2127. Output.AppendLine( Indent( "#endregion", 6 ) );
  2128. #endregion
  2129. #region EntitySet Associations
  2130. Output.AppendLine( Indent( "#region EntitySet Associations", 6 ) );
  2131. //Association entitySet inizialization.
  2132. Counter = 1;
  2133. Temp = string.Empty;
  2134. //
  2135. if( _reverseForeignKeys.ContainsKey( table ) )
  2136. {
  2137. foreach( ForeignKey foreignKey in _reverseForeignKeys[table] )
  2138. {
  2139. EntityPluralName = GetEntityPluralName( foreignKey.Parent );
  2140. EntityName = GetEntityName( foreignKey.Parent );
  2141. EntityGenName = EntityPluralName;
  2142. //Obtain the referenced primarykey reference name.
  2143. string ColumnReferencePluralName = GetColumnReferencePluralName( foreignKey.Parent.Columns[foreignKey.Columns[0].Name] );
  2144. string ColumnReferenceName = GetColumnReferenceName( foreignKey.Parent.Columns[foreignKey.Columns[0].Name] );
  2145. //Is exist use it but generate alternative name.
  2146. if( ColumnReferencePluralName != null )
  2147. {
  2148. EntityGenName = ColumnReferencePluralName;
  2149. EntityGenSimpleName = ColumnReferenceName;
  2150. }
  2151. else
  2152. {
  2153. //To avoid duplicate.
  2154. if( !( string.IsNullOrEmpty( Temp ) ) )
  2155. {
  2156. if( Temp == EntityGenName )
  2157. {
  2158. EntityGenName = EntityPluralName + Counter;
  2159. Counter++;
  2160. Temp = EntityGenName;
  2161. }
  2162. else
  2163. {
  2164. EntityGenName = EntityPluralName;
  2165. Temp = EntityGenName;
  2166. }
  2167. }
  2168. else
  2169. {
  2170. EntityGenName = EntityPluralName;
  2171. Temp = EntityGenName;
  2172. }
  2173. EntityGenSimpleName = GetEntityName( table );
  2174. }
  2175. //Get the foreingKey column name.
  2176. string OtherKey = foreignKey.Columns[0].Name;
  2177. //Get the column name of primary key referenced by this foreignkey.
  2178. string ThisKey = GetReferencedTable( foreignKey ).Columns.OfType<Column>( ).Where( c => c.InPrimaryKey == true ).First( ).Name;
  2179. Output.AppendLine( Indent( string.Format( "[Association(Name=\"{0}\", Storage=\"_{1}\", OtherKey=\"{2}\", ThisKey= \"{3}\")]", ParseForeignkeyName(foreignKey.Name), EntityGenName, OtherKey, ThisKey ), 6 ) );
  2180. //if( GetIsSerializableOption( table ) )
  2181. //{
  2182. // Output.AppendLine( Indent( string.Format( "[DataMember(Order={0})]", DataMemberCounter ), 6 ) );
  2183. //}
  2184. Output.AppendLine( Indent( string.Format( "public EntitySet<{0}> {1}", EntityName, EntityGenName ), 6 ) );
  2185. Output.AppendLine( Indent( "{", 6 ) );
  2186. Output.AppendLine( Indent( "get", 8 ) );
  2187. Output.AppendLine( Indent( "{", 8 ) );
  2188. Output.AppendLine( Indent( string.Format( "if ((this.serializing && (this._{0}.HasLoadedOrAssignedValues == false)))", EntityGenName ), 10 ) );
  2189. Output.AppendLine( Indent( "{", 10 ) );
  2190. Output.AppendLine( Indent( "return null;", 12 ) );
  2191. Output.AppendLine( Indent( "}", 10 ) );
  2192. Output.AppendLine( Indent( string.Format( "return this._{0};", EntityGenName ), 10 ) );
  2193. Output.AppendLine( Indent( "}", 8 ) );
  2194. Output.AppendLine( Indent( "set", 8 ) );
  2195. Output.AppendLine( Indent( "{", 8 ) );
  2196. Output.AppendLine( Indent( string.Format( "this._{0}.Assign(value);", EntityGenName ), 10 ) );
  2197. Output.AppendLine( Indent( "}", 8 ) );
  2198. Output.AppendLine( Indent( "}", 6 ) );
  2199. //
  2200. Output.AppendLine( Indent( string.Format( "private void attach_{0}({1} entity)", EntityGenName, EntityName ), 6 ) );
  2201. Output.AppendLine( Indent( "{", 6 ) );
  2202. Output.AppendLine( Indent( "this.OnPropertyChanging();", 8 ) );
  2203. Output.AppendLine( Indent( string.Format( "entity.{0} = this;", EntityGenSimpleName ), 8 ) );
  2204. Output.AppendLine( Indent( "}", 6 ) );
  2205. Output.AppendLine( Indent( string.Format( "private void detach_{0}({1} entity)", EntityGenName, EntityName ), 6 ) );
  2206. Output.AppendLine( Indent( "{", 6 ) );
  2207. Output.AppendLine( Indent( "this.OnPropertyChanging();", 8 ) );
  2208. Output.AppendLine( Indent( string.Format( "entity.{0} = null;", EntityGenSimpleName ), 8 ) );
  2209. Output.AppendLine( Indent( "}", 6 ) );
  2210. //Incremente member order.
  2211. DataMemberCounter++;
  2212. }
  2213. }
  2214. Output.AppendLine( Indent( "#endregion", 6 ) );
  2215. #endregion
  2216. #region Serialization
  2217. Output.AppendLine( Indent( "#region Serialization", 6 ) );
  2218. Output.AppendLine( Indent( "[OnDeserializing()]", 6 ) );
  2219. Output.AppendLine( Indent( "[System.ComponentModel.EditorBrowsableAttribute(EditorBrowsableState.Never)]", 6 ) );
  2220. Output.AppendLine( Indent( "public void OnDeserializing(StreamingContext context)", 6 ) );
  2221. Output.AppendLine( Indent( "{", 6 ) );
  2222. Output.AppendLine( Indent( "this.Initialize();", 8 ) );
  2223. Output.AppendLine( Indent( "}", 6 ) );
  2224. Output.AppendLine( Indent( "[OnSerializing()]", 6 ) );
  2225. Output.AppendLine( Indent( "[System.ComponentModel.EditorBrowsableAttribute(EditorBrowsableState.Never)]", 6 ) );
  2226. Output.AppendLine( Indent( "public void OnSerializing(StreamingContext context)", 6 ) );
  2227. Output.AppendLine( Indent( "{", 6 ) );
  2228. Output.AppendLine( Indent( "this.serializing = true;", 8 ) );
  2229. Output.AppendLine( Indent( "}", 6 ) );
  2230. Output.AppendLine( Indent( "[OnSerialized()]", 6 ) );
  2231. Output.AppendLine( Indent( "[System.ComponentModel.EditorBrowsableAttribute(EditorBrowsableState.Never)]", 6 ) );
  2232. Output.AppendLine( Indent( "public void OnSerialized(StreamingContext context)", 6 ) );
  2233. Output.AppendLine( Indent( "{", 6 ) );
  2234. Output.AppendLine( Indent( "this.serializing = false;", 8 ) );
  2235. Output.AppendLine( Indent( "}", 6 ) );
  2236. Output.AppendLine( Indent( "#endregion", 6 ) );
  2237. #endregion
  2238. #region Property Change Event Handling
  2239. Output.AppendLine( Indent( "#region PropertyChange event handling", 6 ) );
  2240. Output.AppendLine( Indent( "private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);", 6 ) );
  2241. Output.AppendLine( Indent( "public event PropertyChangingEventHandler PropertyChanging;", 6 ) );
  2242. Output.AppendLine( Indent( "public event PropertyChangedEventHandler PropertyChanged;", 6 ) );
  2243. if( GetPreventingDebugOption( ) )
  2244. {
  2245. Output.AppendLine( Indent( "[System.Diagnostics.DebuggerNonUserCodeAttribute()]", 6 ) );
  2246. }
  2247. Output.AppendLine( Indent( "protected void OnPropertyChanging()", 6 ) );
  2248. Output.AppendLine( Indent( "{", 6 ) );
  2249. Output.AppendLine( Indent( "if (this.PropertyChanging != null) this.PropertyChanging(this, emptyChangingEventArgs);", 8 ) );
  2250. Output.AppendLine( Indent( "}", 6 ) );
  2251. if( GetPreventingDebugOption( ) )
  2252. {
  2253. Output.AppendLine( Indent( "[System.Diagnostics.DebuggerNonUserCodeAttribute()]", 6 ) );
  2254. }
  2255. Output.AppendLine( Indent( "protected void OnPropertyChanged(string propertyName)", 6 ) );
  2256. Output.AppendLine( Indent( "{", 6 ) );
  2257. Output.AppendLine( Indent( "if (this.PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));", 8 ) );
  2258. Output.AppendLine( Indent( "}", 6 ) );
  2259. Output.AppendLine( Indent( "#endregion", 6 ) );
  2260. #endregion
  2261. #region Extensibility Method Definitions
  2262. Output.AppendLine( Indent( "#region Extensibility methods", 6 ) );
  2263. Output.AppendLine( Indent( "partial void OnLoaded();", 6 ) );
  2264. Output.AppendLine( Indent( "partial void OnValidate(System.Data.Linq.ChangeAction action);", 6 ) );
  2265. Output.AppendLine( Indent( "partial void OnCreated();", 6 ) );
  2266. foreach( Column column in table.Columns )
  2267. {
  2268. Output.AppendLine( Indent( string.Format( "partial void On{0}Changing({1} value);", column.Name, GetNullableClrType( column ) ), 6 ) );
  2269. Output.AppendLine( Indent( string.Format( "partial void On{0}Changed();", column.Name ), 6 ) );
  2270. }
  2271. Output.AppendLine( Indent( "#endregion", 6 ) );
  2272. #endregion
  2273. Output.AppendLine( Indent( "}", 2 ) );
  2274. Output.AppendLine( "}" );
  2275. return Output.ToString();
  2276. }
  2277. public void GenerateMultipleFiles( string savePath, List<Table> tables)
  2278. {
  2279. ProgressBar.Maximum = tables.Count; //ProgressBar
  2280. ProgressBar.Value = 0;
  2281. ProgressBar.Visible = true;
  2282. //
  2283. //Write the context class.
  2284. string DataContextPath = savePath + @"\" + GetContextName( ) + ".cs";
  2285. using( StreamWriter Wr1 = new StreamWriter( DataContextPath ) )
  2286. {
  2287. Wr1.Write( GetDatacontextClassCode( tables ) );
  2288. Wr1.Flush( );
  2289. }
  2290. ProgressBar.PerformStep( );
  2291. foreach( Table table in tables )
  2292. {
  2293. ProgressBar.PerformStep( );
  2294. string _filePath = savePath + @"\" + GetEntityName( table ) + ".cs";
  2295. using( StreamWriter Wr2 = new StreamWriter( _filePath ) )
  2296. {
  2297. //Pass the current table and the current table collection.
  2298. Wr2.Write( GetEntityClassCode( table, tables ) );
  2299. Wr2.Flush( );
  2300. }
  2301. }
  2302. ProgressBar.Value = 0;
  2303. ProgressBar.Visible = false;
  2304. //
  2305. //StreamWriter Wr=new StreamWriter(savePath + "
  2306. }
  2307. public void GenerateMultipleFiles( string savePath )
  2308. {
  2309. if( Directory.Exists( savePath ) )
  2310. {
  2311. if( Directory.GetFiles( savePath ).Count( ) > 0 )
  2312. {
  2313. if( ShowConfirmationMessage("All files will be deleted. Are you agree?" ) == DialogResult.OK )
  2314. {
  2315. Directory.Delete( savePath, true );
  2316. Directory.CreateDirectory( savePath );
  2317. }
  2318. }
  2319. }
  2320. else
  2321. {
  2322. Directory.CreateDirectory( savePath );
  2323. }
  2324. //Gets list of treenodes under de root node.
  2325. if( GetOnlySelectedTablesOption( ) )
  2326. {
  2327. //Get the checked nodes under root node.
  2328. List<TreeNode> _nodesCol = DbTree.Nodes[0].Nodes.OfType<TreeNode>( ).Where( c => c.Checked ).ToList();
  2329. List<Table> _tables = new List<Table>();
  2330. foreach (TreeNode node in _nodesCol)
  2331. {
  2332. Hashtable _nodeTag = (Hashtable)node.Tag;
  2333. string _schemaName = _nodeTag["Schema"].ToString();
  2334. string _tableName = _nodeTag["Name"].ToString();
  2335. _tables.Add(_currentDatabase.Tables[_tableName, _schemaName ]);
  2336. }
  2337. GenerateMultipleFiles( savePath, _tables );
  2338. ShowinfoMessage( "Generation code was successful." );
  2339. }
  2340. else
  2341. {
  2342. //Get all nodes under root node.
  2343. List<TreeNode> _nodesCol = DbTree.Nodes[0].Nodes.OfType<TreeNode>( ).ToList( );
  2344. List<Table> _tables = new List<Table>();
  2345. foreach (TreeNode node in _nodesCol)
  2346. {
  2347. Hashtable _nodeTag = (Hashtable)node.Tag;
  2348. string _schemaName = _nodeTag["Schema"].ToString( );
  2349. string _tableName = _nodeTag["Name"].ToString( );
  2350. _tables.Add( _currentDatabase.Tables[_tableName, _schemaName] );
  2351. }
  2352. GenerateMultipleFiles( savePath, _tables );
  2353. ShowinfoMessage( "Generation code was successful." );
  2354. }
  2355. }
  2356. public void GenerateUniqueFile( string savePath )
  2357. {
  2358. }
  2359. public void GenerateLinqToSqlClasses( )
  2360. {
  2361. try
  2362. {
  2363. string _savePath = GetSavePath( );
  2364. //Check if it should generate multiples classes
  2365. if( GetGenerateMultipleClassesOption( ) )
  2366. {
  2367. GenerateMultipleFiles( _savePath );
  2368. }
  2369. else
  2370. {
  2371. GenerateUniqueFile( _savePath );
  2372. }
  2373. }
  2374. #if DEBUG
  2375. catch( Exception ex ) { ShowErrorMessage( ex.Message + "\n" + ex.StackTrace ); }
  2376. #else
  2377. catch( Exception ex ) { ShowErrorMessage( ex.Message ); }
  2378. #endif
  2379. }
  2380. #endregion
  2381. #region General methods
  2382. #endregion
  2383. #region SMO methods
  2384. private string GetServerConnectionString( string serverName )
  2385. {
  2386. XElement XServers = XElement.Load( "Servers.xml" );
  2387. XElement Server = (from p in XServers.Elements( "Server" )
  2388. where p.Attribute( "Name" ).Value == serverName
  2389. select p).Single();
  2390. return Server.Element( "ConnectionString" ).Value;
  2391. }
  2392. /// <summary>
  2393. /// This method gets column description (MS_Description) and fill field. Retrieves extended
  2394. /// properties collection
  2395. /// </summary>
  2396. /// <param name="node"></param>
  2397. ///
  2398. private void GetDatabaseDescription( TreeNode node )
  2399. {
  2400. try
  2401. {
  2402. if( DbTree.SelectedNode != null )
  2403. {
  2404. //Retrieve table extended properties.
  2405. Smo.ExtendedPropertyCollection PropCol = _currentDatabase.ExtendedProperties;
  2406. //Populate extended properties view.
  2407. PopulateExtendedProperties( PropCol );
  2408. //Fill de description field.
  2409. if( PropCol[ConfigValues.DescriptionLabel] != null )
  2410. {
  2411. //Show in text field to edit.
  2412. FieldDescription.Text = PropCol[ConfigValues.DescriptionLabel].Value.ToString( );
  2413. }
  2414. else
  2415. {
  2416. //Create a extended property an inizialize it to a empty value.
  2417. Smo.ExtendedProperty ColumnDescriptionExtProperty = new ExtendedProperty( _currentDatabase, ConfigValues.DescriptionLabel, string.Empty );
  2418. PropCol.Add( ColumnDescriptionExtProperty );
  2419. _currentDatabase.Alter( );
  2420. FieldDescription.Text = ColumnDescriptionExtProperty.ToString( );
  2421. }
  2422. }
  2423. }
  2424. catch( Exception ex ) { MessageBox.Show( ex.Message ); }
  2425. }
  2426. private void GetColumnDescription( TreeNode node )
  2427. {
  2428. try
  2429. {
  2430. if( DbTree.SelectedNode != null )
  2431. {
  2432. Hashtable ParentTagValues = (Hashtable)node.Parent.Tag;
  2433. Hashtable TagValues = (Hashtable)node.Tag;
  2434. string SchemaName = ParentTagValues["Schema"].ToString( );
  2435. string TableName = ParentTagValues["Name"].ToString( );
  2436. _currentTable = _currentDatabase.Tables[TableName, SchemaName];
  2437. //
  2438. _currentColumn = _currentTable.Columns[node.Text];
  2439. //Retrieve table extended properties.
  2440. Smo.ExtendedPropertyCollection PropCol = _currentColumn.ExtendedProperties;
  2441. //Populate extended properties view.
  2442. PopulateExtendedProperties( PropCol );
  2443. //Fill de description field.
  2444. if( PropCol[ConfigValues.DescriptionLabel] != null )
  2445. {
  2446. //Show in text field to edit.
  2447. FieldDescription.Text = PropCol[ConfigValues.DescriptionLabel].Value.ToString( );
  2448. }
  2449. else
  2450. {
  2451. //Create a extended property an inizialize it to a empty value.
  2452. Smo.ExtendedProperty ColumnDescriptionExtProperty = new ExtendedProperty( _currentColumn, ConfigValues.DescriptionLabel, string.Empty );
  2453. PropCol.Add( ColumnDescriptionExtProperty );
  2454. _currentColumn.Alter( );
  2455. FieldDescription.Text = ColumnDescriptionExtProperty.ToString( );
  2456. }
  2457. }
  2458. }
  2459. catch( Exception ex ) { MessageBox.Show( ex.Message ); }
  2460. }
  2461. private void GetTableDescription( TreeNode node )
  2462. {
  2463. try
  2464. {
  2465. if( DbTree.SelectedNode != null )
  2466. {
  2467. Hashtable TagValues = (Hashtable)node.Tag;
  2468. string SchemaName = TagValues["Schema"].ToString( );
  2469. string TableName = TagValues["Name"].ToString( );
  2470. _currentTable = _currentDatabase.Tables[TableName, SchemaName];
  2471. //Retrieve table extended properties.
  2472. Smo.ExtendedPropertyCollection PropCol = _currentTable.ExtendedProperties;
  2473. //Populate extended properties view.
  2474. PopulateExtendedProperties( PropCol );
  2475. //Fill de description field.
  2476. if( PropCol[ConfigValues.DescriptionLabel] != null )
  2477. {
  2478. //Show in text field to edit.
  2479. FieldDescription.Text = PropCol[ConfigValues.DescriptionLabel].Value.ToString( );
  2480. }
  2481. else
  2482. {
  2483. //Create a extended property an inizialize it to a empty value.
  2484. Smo.ExtendedProperty TableDescriptionExtProperty = new ExtendedProperty( _currentTable, ConfigValues.DescriptionLabel, string.Empty );
  2485. PropCol.Add( TableDescriptionExtProperty );
  2486. _currentTable.Alter( );
  2487. FieldDescription.Text = TableDescriptionExtProperty.ToString( );
  2488. }
  2489. }
  2490. }
  2491. catch( Exception ex ) { MessageBox.Show( ex.Message ); }
  2492. }
  2493. /// <summary>
  2494. /// Save object description.
  2495. /// </summary>
  2496. /// <param name="table"></param>
  2497. private void SaveObjectDescription( SqlSmoObject smoObject, string objectType )
  2498. {
  2499. Smo.ExtendedPropertyCollection PropertiesCol = null;
  2500. try
  2501. {
  2502. //
  2503. switch( objectType )
  2504. {
  2505. case NODETYPE_DB:
  2506. Database Db = (Database)smoObject;
  2507. PropertiesCol = Db.ExtendedProperties;
  2508. PropertiesCol[ConfigValues.DescriptionLabel].Value = FieldDescription.Text;
  2509. Db.Alter( );
  2510. break;
  2511. case NODETYPE_TABLE:
  2512. Table t = (Table)smoObject;
  2513. PropertiesCol = t.ExtendedProperties;
  2514. PropertiesCol[ConfigValues.DescriptionLabel].Value = FieldDescription.Text;
  2515. t.Alter( );
  2516. break;
  2517. case NODETYPE_COLUMN:
  2518. Column c = (Column)smoObject;
  2519. PropertiesCol = c.ExtendedProperties;
  2520. PropertiesCol[ConfigValues.DescriptionLabel].Value = FieldDescription.Text;
  2521. c.Alter( );
  2522. break;
  2523. default:
  2524. break;
  2525. }
  2526. PopulateExtendedProperties( PropertiesCol );
  2527. }
  2528. catch( Exception ex ) { MessageBox.Show( ex.Message ); }
  2529. }
  2530. private void SetCurrentObject( TreeNode node, string objectType )
  2531. {
  2532. Hashtable TagValues;
  2533. switch( objectType )
  2534. {
  2535. case NODETYPE_DB:
  2536. //Get the metadata object to retrieve metadata values.
  2537. TagValues = (Hashtable)node.Tag;
  2538. string DatabaseName = TagValues["Name"].ToString( );
  2539. //Set the current object to table object.
  2540. _currentObject = _currentDatabase;
  2541. _currentObjectType = NODETYPE_DB;
  2542. break;
  2543. case NODETYPE_TABLE:
  2544. //Get the metadata object to retrieve metadata values.
  2545. TagValues = (Hashtable)node.Tag;
  2546. string SchemaTableName = TagValues["Schema"].ToString( );
  2547. string TableName = TagValues["Name"].ToString( );
  2548. //Set the current object to table object.
  2549. _currentObject = _currentDatabase.Tables[TableName, SchemaTableName];
  2550. _currentObjectType = NODETYPE_TABLE;
  2551. break;
  2552. case NODETYPE_COLUMN:
  2553. //Get the metadata object to retrieve metadata values.
  2554. TagValues = (Hashtable)node.Tag;
  2555. string ColumnName = TagValues["Name"].ToString( );
  2556. //Set the current object to table object.
  2557. _currentObject = _currentTable.Columns[ColumnName];
  2558. _currentObjectType = NODETYPE_COLUMN;
  2559. break;
  2560. default:
  2561. break;
  2562. }
  2563. }
  2564. private void Connect( )
  2565. {
  2566. try
  2567. {
  2568. }
  2569. catch( SqlException ex ) { MessageBox.Show( ex.Message ); }
  2570. }
  2571. private void Disconnect( )
  2572. {
  2573. try
  2574. {
  2575. if( _serverConn != null )
  2576. {
  2577. _serverConn.Disconnect( );
  2578. _serverConnected = false;
  2579. _serverConn = null; _conn = null; _serverObject = null;
  2580. ClearDatabaseControls( );
  2581. DisableDatabaseControls( );
  2582. }
  2583. }
  2584. catch( SqlException ex ) { MessageBox.Show( ex.Message ); }
  2585. }
  2586. private void ActivateServerConnection( )
  2587. {
  2588. try
  2589. {
  2590. Disconnect( );
  2591. //Check if CurrentServerConnectinString is valid.
  2592. if( !string.IsNullOrEmpty( _currentServerConnectionString ) )
  2593. {
  2594. if( _conn == null )
  2595. {
  2596. _conn = new SqlConnection( _currentServerConnectionString );
  2597. }
  2598. //if(Conn.State==ConnectionState.Closed)
  2599. // Conn.Open( );
  2600. //this.Text = "Connected";
  2601. _serverConn = new ServerConnection( _conn );
  2602. if( _serverObject == null )
  2603. _serverObject = new Server( _serverConn );
  2604. //
  2605. PopulateDatabases( );
  2606. _serverConnected = true; //Set the current state.
  2607. EnableDatabaseControls( );
  2608. }
  2609. else
  2610. {
  2611. MessageBox.Show( "Server is not selected." );
  2612. }
  2613. }
  2614. catch( SqlException ex ) { MessageBox.Show( ex.Message ); }
  2615. catch( Exception ex ) { MessageBox.Show( ex.Message ); }
  2616. }
  2617. #endregion
  2618. #region Events
  2619. #region Form events
  2620. private void Main_Load( object sender, EventArgs e )
  2621. {
  2622. }
  2623. private void Mainform_Resize( object sender, EventArgs e )
  2624. {
  2625. }
  2626. #endregion
  2627. #region Menu events
  2628. private void disconnectToolStripMenuItem_Click( object sender, EventArgs e )
  2629. {
  2630. Disconnect( );
  2631. }
  2632. private void exitToolStripMenuItem_Click( object sender, EventArgs e )
  2633. {
  2634. this.Dispose( );
  2635. }
  2636. private void connectToolStripMenuItem_Click( object sender, EventArgs e )
  2637. {
  2638. ActivateServerConnection( );
  2639. }
  2640. private void aboutToolStripMenuItem_Click( object sender, EventArgs e )
  2641. {
  2642. About AboutForm = new About( );
  2643. AboutForm.Show( );
  2644. }
  2645. private void refreshToolStripMenuItem_Click( object sender, EventArgs e )
  2646. {
  2647. if(_serverConnected)
  2648. PopulateTables( true );
  2649. }
  2650. private void ExPropContext_Opening( object sender, CancelEventArgs e )
  2651. {
  2652. //Enable/Disable context menu options.
  2653. switch( _currentObjectType )
  2654. {
  2655. case NODETYPE_DB:
  2656. ExPropContext.Items["gwTableScopeDelete"].Enabled = false;
  2657. ExPropContext.Items["gwDatabaseScopeDelete"].Enabled = false;
  2658. ExPropContext.Items["gwDatabaseScopeModify"].Enabled = false;
  2659. ExPropContext.Items["gwTableScopeModify"].Enabled = false;
  2660. ExPropContext.Items["gwDatabaseScopeModify"].Enabled = false;
  2661. ExPropContext.Items["gwSelectedScopeModify"].Enabled = false;
  2662. break;
  2663. case NODETYPE_TABLE:
  2664. ExPropContext.Items["gwTableScopeDelete"].Enabled = false;
  2665. ExPropContext.Items["gwDatabaseScopeDelete"].Enabled = true;
  2666. ExPropContext.Items["gwDatabaseScopeModify"].Enabled = true;
  2667. ExPropContext.Items["gwTableScopeModify"].Enabled = false;
  2668. ExPropContext.Items["gwDatabaseScopeModify"].Enabled = true;
  2669. ExPropContext.Items["gwSelectedScopeModify"].Enabled = true;
  2670. break;
  2671. case NODETYPE_COLUMN:
  2672. ExPropContext.Items["gwTableScopeDelete"].Enabled = true;
  2673. ExPropContext.Items["gwDatabaseScopeDelete"].Enabled = false;
  2674. ExPropContext.Items["gwDatabaseScopeModify"].Enabled = false;
  2675. ExPropContext.Items["gwTableScopeModify"].Enabled = true;
  2676. ExPropContext.Items["gwDatabaseScopeModify"].Enabled = false;
  2677. ExPropContext.Items["gwSelectedScopeModify"].Enabled = false;
  2678. break;
  2679. default:
  2680. break;
  2681. }
  2682. }
  2683. //ContextMenu Operations
  2684. private void ExPropContext_ItemClicked( object sender, ToolStripItemClickedEventArgs e )
  2685. {
  2686. switch( e.ClickedItem.Name)
  2687. {
  2688. case "gwTableScopeDelete":
  2689. if( _currentDatabase != null )
  2690. {
  2691. //Extended properties selected.
  2692. if( DbProperties.SelectedRows.Count > 0 )
  2693. {
  2694. //Only one selected.
  2695. if( DbProperties.SelectedRows.Count == 1 )
  2696. {
  2697. if( ShowConfirmationMessage("Are you sure to delete this property in all tables of the current database?") == DialogResult.OK )
  2698. {
  2699. var PropertyName = DbProperties.SelectedRows[0].Cells[0].Value.ToString( );
  2700. DeleteGlobalProperty( _currentTable, NODETYPE_TABLE, PropertyName );
  2701. }
  2702. }
  2703. }
  2704. }
  2705. else
  2706. {
  2707. ShowAlertMessage( "None database object selected." );
  2708. }
  2709. break;
  2710. case "gwDatabaseScopeDelete":
  2711. if( _currentDatabase != null )
  2712. {
  2713. //Extended properties selected.
  2714. if( DbProperties.SelectedRows.Count > 0 )
  2715. {
  2716. //Only one selected.
  2717. if( DbProperties.SelectedRows.Count == 1 )
  2718. {
  2719. if( ShowConfirmationMessage( "Are you sure to delete this property in all tables of the current database?" ) == DialogResult.OK )
  2720. {
  2721. var PropertyName = DbProperties.SelectedRows[0].Cells[0].Value.ToString( );
  2722. DeleteGlobalProperty( _currentDatabase, NODETYPE_DB, PropertyName );
  2723. }
  2724. }
  2725. }
  2726. }
  2727. else
  2728. {
  2729. ShowAlertMessage( "None database object selected." );
  2730. }
  2731. break;
  2732. case "gw":
  2733. break;
  2734. default:
  2735. break;
  2736. }
  2737. }
  2738. //Add
  2739. private void gwScopeDatabaseAddProperty( object sender, EventArgs e )
  2740. {
  2741. if( _currentDatabase != null )
  2742. {
  2743. CreatePropertyForm GpForm = new CreatePropertyForm( );
  2744. if( GpForm.ShowDialog( ) == DialogResult.OK )
  2745. {
  2746. string _propertyName = GpForm.PropertyName;
  2747. string _propertyDefaultValue = GpForm.PropertyDefaultValue;
  2748. //Check if name o default are empty.
  2749. if( !string.IsNullOrEmpty( _propertyName ) )
  2750. {
  2751. AddExtendedPropertyAtScope( NODETYPE_DB, _propertyName, _propertyDefaultValue, Scope.DatabaseScope );
  2752. }
  2753. else
  2754. {
  2755. ShowAlertMessage( "Name or defaultValue fields are empty or are invalid." );
  2756. }
  2757. }
  2758. }
  2759. else
  2760. {
  2761. ShowAlertMessage( "None database object selected." );
  2762. }
  2763. }
  2764. private void gwScopeTableAddProperty( object sender, EventArgs e )
  2765. {
  2766. if( _currentTable != null )
  2767. {
  2768. CreatePropertyForm GpForm = new CreatePropertyForm( );
  2769. if( GpForm.ShowDialog( ) == DialogResult.OK )
  2770. {
  2771. string _propertyName = GpForm.PropertyName;
  2772. string _propertyDefaultValue = GpForm.PropertyDefaultValue;
  2773. //Check if name o default are empty.
  2774. if( !string.IsNullOrEmpty( _propertyName )
  2775. )
  2776. {
  2777. AddExtendedProperty( _currentTable, NODETYPE_TABLE, _propertyName, _propertyDefaultValue );
  2778. }
  2779. else
  2780. {
  2781. ShowAlertMessage( "Name or defaultValue fields are empty." );
  2782. }
  2783. }
  2784. }
  2785. else
  2786. {
  2787. ShowAlertMessage( "None table object selected." );
  2788. }
  2789. }
  2790. private void gwScopeSelectedAddProperty( object sender, EventArgs e )
  2791. {
  2792. if( _currentDatabase != null )
  2793. {
  2794. CreatePropertyForm GpForm = new CreatePropertyForm( );
  2795. if( GpForm.ShowDialog( ) == DialogResult.OK )
  2796. {
  2797. string _propertyName = GpForm.PropertyName;
  2798. string _propertyDefaultValue = GpForm.PropertyDefaultValue;
  2799. //Check if name o default are empty.
  2800. if( !string.IsNullOrEmpty( _propertyName ) )
  2801. {
  2802. AddExtendedPropertyAtScope( NODETYPE_DB, _propertyName, _propertyDefaultValue, Scope.SelectedScope );
  2803. }
  2804. else
  2805. {
  2806. ShowAlertMessage( "Name or defaultValue fields are empty or are invalid." );
  2807. }
  2808. }
  2809. }
  2810. else
  2811. {
  2812. ShowAlertMessage( "None database object selected." );
  2813. }
  2814. }
  2815. private void gwScopeTableSelectedAddProperty( object sender, EventArgs e )
  2816. {
  2817. }
  2818. private void generateLinqToSqlClassesToolStripMenuItem_Click( object sender, EventArgs e )
  2819. {
  2820. GenerateLinqToSqlClasses( );
  2821. }
  2822. private void preferencesToolStripMenuItem_Click( object sender, EventArgs e )
  2823. {
  2824. Options Op = new Options( );
  2825. if( Op.ShowDialog( ) == DialogResult.OK )
  2826. {
  2827. LoadConfiguration( );
  2828. }
  2829. }
  2830. //
  2831. private void gwTableScopeDelete_Click( object sender, EventArgs e )
  2832. {
  2833. }
  2834. private void gwDatabaseScopeDelete_Click( object sender, EventArgs e )
  2835. {
  2836. }
  2837. private void gwTableScopeModify_Click( object sender, EventArgs e )
  2838. {
  2839. }
  2840. private void gwSelectedScopeModify_Click( object sender, EventArgs e )
  2841. {
  2842. if( !( DbProperties.SelectedRows.Count == 0 ) )
  2843. {
  2844. EditPropertyForm EpForm = new EditPropertyForm( );
  2845. EpForm.fOldName.Text = DbProperties.SelectedRows[0].Cells[0].Value.ToString( );
  2846. EpForm.fNewName.Text = DbProperties.SelectedRows[0].Cells[0].Value.ToString( );
  2847. EpForm.fOldValue.Text = DbProperties.SelectedRows[0].Cells[1].Value.ToString( );
  2848. if( EpForm.ShowDialog( ) == DialogResult.OK )
  2849. {
  2850. if( EpForm.fCheckNames.Checked )
  2851. {
  2852. if( string.IsNullOrEmpty( EpForm.OldName ) || string.IsNullOrEmpty( EpForm.NewName ) )
  2853. {
  2854. ShowAlertMessage("Can't edit because OldName or NewName has invalid values.");
  2855. //MessageBox.Show( "Can't edit because OldName or NewName has invalid values." );
  2856. return;
  2857. }
  2858. if( EpForm.OldName == EpForm.NewName )
  2859. {
  2860. ShowAlertMessage( "Can't edit because OldName or NewName values are identical." );
  2861. //MessageBox.Show( "Can't edit because OldName or NewName has identical values." );
  2862. return;
  2863. }
  2864. //Change the name recreating the property in old tables.
  2865. UpdatePropertyAtScope( NODETYPE_TABLE, EpForm.OldName, EpForm.NewName, Scope.SelectedScope, true );
  2866. }
  2867. if( EpForm.fCheckValues.Checked )
  2868. {
  2869. //Chanve the value.
  2870. UpdatePropertyAtScope( NODETYPE_TABLE, EpForm.OldValue, EpForm.NewValue, Scope.SelectedScope, false );
  2871. }
  2872. }
  2873. }
  2874. }
  2875. private void gwDatabaseScopeModify_Click( object sender, EventArgs e )
  2876. {
  2877. if( !( DbProperties.SelectedRows.Count == 0 ) )
  2878. {
  2879. EditPropertyForm EpForm = new EditPropertyForm( );
  2880. EpForm.fOldName.Text = DbProperties.SelectedRows[0].Cells[0].Value.ToString( );
  2881. EpForm.fNewName.Text = DbProperties.SelectedRows[0].Cells[0].Value.ToString( );
  2882. EpForm.fOldValue.Text = DbProperties.SelectedRows[0].Cells[1].Value.ToString( );
  2883. if( EpForm.ShowDialog( ) == DialogResult.OK )
  2884. {
  2885. //Wait WaitForm = new Wait( );
  2886. //WaitForm.Show ( );
  2887. if( EpForm.fCheckNames.Checked )
  2888. {
  2889. if( string.IsNullOrEmpty( EpForm.OldName ) || string.IsNullOrEmpty( EpForm.NewName ) )
  2890. {
  2891. ShowAlertMessage( "Can't edit because OldName or NewName has invalid values." );
  2892. //MessageBox.Show( "Can't edit because OldName or NewName has invalid values." );
  2893. return;
  2894. }
  2895. if( EpForm.OldName == EpForm.NewName )
  2896. {
  2897. ShowAlertMessage( "Can't edit because OldName or NewName values are identical." );
  2898. //MessageBox.Show( "Can't edit because OldName or NewName has identical values." );
  2899. return;
  2900. }
  2901. //Change the name recreating the property in old tables.
  2902. UpdatePropertyAtScope( NODETYPE_TABLE, EpForm.OldName, EpForm.NewName, Scope.DatabaseScope, true );
  2903. }
  2904. if( EpForm.fCheckValues.Checked )
  2905. {
  2906. //Chanve the value.
  2907. UpdatePropertyAtScope( NODETYPE_TABLE, EpForm.OldValue, EpForm.NewValue, Scope.DatabaseScope, false );
  2908. }
  2909. //WaitForm.Hide( );
  2910. //WaitForm.Dispose( );
  2911. }
  2912. }
  2913. }
  2914. private void gwAddORMExtendedProperties_Click( object sender, EventArgs e )
  2915. {
  2916. AddORMExtendedProperties( Scope.DatabaseScope );
  2917. }
  2918. #endregion
  2919. #region TreeView events
  2920. private void DbView_Click( object sender, EventArgs e )
  2921. {
  2922. }
  2923. private void DbView_NodeMouseClick( object sender, TreeNodeMouseClickEventArgs e )
  2924. {
  2925. try
  2926. {
  2927. //Get object data by node type.
  2928. DbTree.SelectedNode = e.Node;
  2929. if( e.Node.Tag != null )
  2930. {
  2931. Hashtable TagValues = (Hashtable)e.Node.Tag;
  2932. switch( TagValues["Type"].ToString( ) )
  2933. {
  2934. case NODETYPE_DB:
  2935. SetCurrentObject( e.Node, NODETYPE_DB);
  2936. GetDatabaseDescription( e.Node );
  2937. break;
  2938. case NODETYPE_TABLE:
  2939. SetCurrentObject( e.Node, NODETYPE_TABLE );
  2940. GetTableDescription( e.Node );
  2941. break;
  2942. case NODETYPE_COLUMN:
  2943. SetCurrentObject( e.Node, NODETYPE_COLUMN );
  2944. GetColumnDescription( e.Node );
  2945. break;
  2946. case NODETYPE_FK:
  2947. break;
  2948. case NODETYPE_IX:
  2949. break;
  2950. case NODETYPE_PROP:
  2951. break;
  2952. case NODETYPE_XPROP:
  2953. break;
  2954. default:
  2955. break;
  2956. }
  2957. }
  2958. }
  2959. catch( Exception ex ) { MessageBox.Show( ex.Message ); }
  2960. }
  2961. private void DbView_KeyUp( object sender, KeyEventArgs e )
  2962. {
  2963. try
  2964. {
  2965. if( DbTree.SelectedNode != null )
  2966. {
  2967. //Get object data by node type.
  2968. TreeNode CurrentNode = DbTree.SelectedNode;
  2969. if( DbTree.SelectedNode.Tag != null )
  2970. {
  2971. Hashtable TagValues = (Hashtable)CurrentNode.Tag;
  2972. switch( TagValues["Type"].ToString( ) )
  2973. {
  2974. case NODETYPE_DB:
  2975. SetCurrentObject( CurrentNode, NODETYPE_DB );
  2976. GetDatabaseDescription( CurrentNode );
  2977. break;
  2978. case NODETYPE_TABLE:
  2979. SetCurrentObject( CurrentNode, NODETYPE_TABLE );
  2980. GetTableDescription( CurrentNode );
  2981. break;
  2982. case NODETYPE_COLUMN:
  2983. SetCurrentObject( CurrentNode, NODETYPE_COLUMN );
  2984. GetColumnDescription( CurrentNode );
  2985. break;
  2986. case NODETYPE_FK:
  2987. break;
  2988. case NODETYPE_IX:
  2989. break;
  2990. case NODETYPE_PROP:
  2991. break;
  2992. case NODETYPE_XPROP:
  2993. break;
  2994. default:
  2995. break;
  2996. }
  2997. }
  2998. }
  2999. }
  3000. catch( Exception ex ) { MessageBox.Show( ex.Message ); }
  3001. }
  3002. private void DbView_KeyDown( object sender, KeyEventArgs e )
  3003. {
  3004. try
  3005. {
  3006. if( DbTree.SelectedNode != null )
  3007. {
  3008. //Get object data by node type.
  3009. TreeNode CurrentNode = DbTree.SelectedNode;
  3010. if( DbTree.SelectedNode.Tag != null )
  3011. {
  3012. Hashtable TagValues = (Hashtable)CurrentNode.Tag;
  3013. switch( TagValues["Type"].ToString( ) )
  3014. {
  3015. case NODETYPE_DB:
  3016. SetCurrentObject( CurrentNode, NODETYPE_DB );
  3017. GetDatabaseDescription( CurrentNode );
  3018. break;
  3019. case NODETYPE_TABLE:
  3020. SetCurrentObject( CurrentNode, NODETYPE_TABLE );
  3021. GetTableDescription( CurrentNode );
  3022. break;
  3023. case NODETYPE_COLUMN:
  3024. SetCurrentObject( CurrentNode, NODETYPE_COLUMN );
  3025. GetColumnDescription( CurrentNode );
  3026. break;
  3027. case NODETYPE_FK:
  3028. break;
  3029. case NODETYPE_IX:
  3030. break;
  3031. case NODETYPE_PROP:
  3032. break;
  3033. case NODETYPE_XPROP:
  3034. break;
  3035. default:
  3036. break;
  3037. }
  3038. }
  3039. }
  3040. }
  3041. catch( Exception ex ) { MessageBox.Show( ex.Message ); }
  3042. }
  3043. private void DbView_AfterSelect( object sender, TreeViewEventArgs e )
  3044. {
  3045. }
  3046. private void DbTree_BeforeExpand( object sender, TreeViewCancelEventArgs e )
  3047. {
  3048. try
  3049. {
  3050. //Get object data by node type.
  3051. DbTree.SelectedNode = e.Node;
  3052. if( e.Node.Tag != null )
  3053. {
  3054. Hashtable TagValues = (Hashtable)e.Node.Tag;
  3055. switch( TagValues["Type"].ToString( ) )
  3056. {
  3057. case NODETYPE_DB:
  3058. break;
  3059. case NODETYPE_TABLE:
  3060. //Add column nodes.
  3061. PopulateColumns( e.Node, true );
  3062. break;
  3063. case NODETYPE_COLUMN:
  3064. break;
  3065. case NODETYPE_FK:
  3066. break;
  3067. case NODETYPE_IX:
  3068. break;
  3069. case NODETYPE_PROP:
  3070. break;
  3071. case NODETYPE_XPROP:
  3072. break;
  3073. default:
  3074. break;
  3075. }
  3076. }
  3077. }
  3078. catch( Exception ex ) { MessageBox.Show( ex.Message ); }
  3079. }
  3080. private void DbTree_AfterExpand( object sender, TreeViewEventArgs e )
  3081. {
  3082. }
  3083. private void DbTree_AfterSelect( object sender, TreeViewEventArgs e )
  3084. {
  3085. }
  3086. private void DbTree_AfterCheck( object sender, TreeViewEventArgs e )
  3087. {
  3088. try
  3089. {
  3090. if( e.Node.Tag != null )
  3091. {
  3092. Hashtable TagValues = (Hashtable)e.Node.Tag;
  3093. switch( TagValues["Type"].ToString( ) )
  3094. {
  3095. case NODETYPE_DB:
  3096. foreach( TreeNode node in e.Node.Nodes )
  3097. {
  3098. node.Checked = e.Node.Checked;
  3099. }
  3100. break;
  3101. case NODETYPE_TABLE:
  3102. break;
  3103. case NODETYPE_COLUMN:
  3104. break;
  3105. case NODETYPE_FK:
  3106. break;
  3107. case NODETYPE_IX:
  3108. break;
  3109. case NODETYPE_PROP:
  3110. break;
  3111. case NODETYPE_XPROP:
  3112. break;
  3113. default:
  3114. break;
  3115. }
  3116. }
  3117. }
  3118. catch( Exception ex ) { MessageBox.Show( ex.Message ); }
  3119. }
  3120. #endregion
  3121. #region Buttons events
  3122. private void bAddProperty_Click( object sender, EventArgs e )
  3123. {
  3124. AddSingleExtendedProperty( _currentObject, _currentObjectType );
  3125. }
  3126. private void bRemoveProperty_Click( object sender, EventArgs e )
  3127. {
  3128. if( MessageBox.Show( "Are you sure to remove this property?.", "Remove confirmation", MessageBoxButtons.YesNo ) == DialogResult.Yes )
  3129. {
  3130. }
  3131. }
  3132. private void bSaveObjectDescription_Click( object sender, EventArgs e )
  3133. {
  3134. TreeNode CurrentNode = DbTree.SelectedNode;
  3135. Hashtable TagValues = (Hashtable)CurrentNode.Tag;
  3136. switch( TagValues["Type"].ToString( ) )
  3137. {
  3138. case NODETYPE_DB:
  3139. SaveObjectDescription( _currentDatabase, NODETYPE_DB );
  3140. break;
  3141. case NODETYPE_TABLE:
  3142. SaveObjectDescription( _currentTable, NODETYPE_TABLE);
  3143. break;
  3144. case NODETYPE_COLUMN:
  3145. SaveObjectDescription( _currentColumn, NODETYPE_COLUMN);
  3146. break;
  3147. case NODETYPE_FK:
  3148. break;
  3149. case NODETYPE_IX:
  3150. break;
  3151. case NODETYPE_PROP:
  3152. break;
  3153. case NODETYPE_XPROP:
  3154. break;
  3155. default:
  3156. break;
  3157. }
  3158. }
  3159. #endregion
  3160. #region Others events
  3161. private void ComboDatabases_TextChanged( object sender, EventArgs e )
  3162. {
  3163. PopulateTables( false );
  3164. }
  3165. private void fTableDesc_Leave( object sender, EventArgs e )
  3166. {
  3167. //Save description value depend on settings
  3168. if( ConfigValues.SaveOnLostFocus )
  3169. {
  3170. if( DbTree.SelectedNode != null )
  3171. {
  3172. //Get object data by node type.
  3173. TreeNode CurrentNode = DbTree.SelectedNode;
  3174. if( DbTree.SelectedNode.Tag != null )
  3175. {
  3176. Hashtable TagValues = (Hashtable)CurrentNode.Tag;
  3177. switch( TagValues["Type"].ToString( ) )
  3178. {
  3179. case NODETYPE_DB:
  3180. SaveObjectDescription( _currentDatabase, NODETYPE_DB );
  3181. break;
  3182. case NODETYPE_TABLE:
  3183. SaveObjectDescription( _currentTable, NODETYPE_TABLE );
  3184. break;
  3185. case NODETYPE_COLUMN:
  3186. SaveObjectDescription( _currentColumn, NODETYPE_COLUMN );
  3187. break;
  3188. case NODETYPE_FK:
  3189. break;
  3190. case NODETYPE_IX:
  3191. break;
  3192. case NODETYPE_PROP:
  3193. break;
  3194. case NODETYPE_XPROP:
  3195. break;
  3196. default:
  3197. break;
  3198. }
  3199. }
  3200. }
  3201. }
  3202. }
  3203. #endregion
  3204. #region ToolStrip events
  3205. private void ServersList_TextChanged( object sender, EventArgs e )
  3206. {
  3207. }
  3208. private void ServersList_SelectedIndexChanged( object sender, EventArgs e )
  3209. {
  3210. //On change server update the current conectionstring.
  3211. _currentServerConnectionString = GetServerConnectionString( ServersList.SelectedItem.ToString( ) );
  3212. }
  3213. #endregion
  3214. #region PropertiesDatagrid events
  3215. private void DbProperties_CellBeginEdit( object sender, DataGridViewCellCancelEventArgs e )
  3216. {
  3217. _propertyOldName = DbProperties.Rows[e.RowIndex].Cells[0].Value.ToString( );
  3218. if( _propertyOldName == ConfigValues.DescriptionLabel )
  3219. {
  3220. DbProperties.EndEdit( );
  3221. }
  3222. }
  3223. private void DbProperties_CellEndEdit( object sender, DataGridViewCellEventArgs e )
  3224. {
  3225. //Name is the first columns index 0
  3226. var Name = DbProperties.Rows[e.RowIndex].Cells[0].Value.ToString( );
  3227. var Value = DbProperties.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString( );
  3228. if( e.ColumnIndex == 0 )
  3229. {
  3230. //Update property name, only update if not is description property.
  3231. if( !( _propertyOldName == ConfigValues.DescriptionLabel ) )
  3232. {
  3233. UpdateProperty( _currentObject, _currentObjectType, _propertyOldName, Value, true );
  3234. }
  3235. }
  3236. else
  3237. {
  3238. //Update the property value.
  3239. UpdateProperty( _currentObject, _currentObjectType, Name, Value, false );
  3240. }
  3241. PopulateExtendedProperties( _currentPropertiesCollection );
  3242. }
  3243. private void DbProperties_UserDeletedRow( object sender, DataGridViewRowEventArgs e )
  3244. {
  3245. var Name = e.Row.Cells[0].Value.ToString( );
  3246. RemoveProperty( _currentObject, _currentObjectType, Name );
  3247. }
  3248. private void DbProperties_CellContentDoubleClick( object sender, DataGridViewCellEventArgs e )
  3249. {
  3250. }
  3251. private void DbProperties_CellMouseDoubleClick( object sender, DataGridViewCellMouseEventArgs e )
  3252. {
  3253. if( e.ColumnIndex > 0 )
  3254. {
  3255. EditText EditTextForm = new EditText( );
  3256. EditTextForm.SetText( DbProperties.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString( ) );
  3257. if( EditTextForm.ShowDialog( ) == DialogResult.OK )
  3258. {
  3259. DbProperties.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = EditTextForm.EditedText;
  3260. }
  3261. EditTextForm.Dispose( );
  3262. }
  3263. }
  3264. #endregion
  3265. #endregion
  3266. }
  3267. internal static class ConfigValues
  3268. {
  3269. internal static string DescriptionLabel { get; set; }
  3270. internal static bool SaveOnLostFocus { get; set; }
  3271. internal static bool ViewSystemDatabases { get; set; }
  3272. internal static bool ViewSystemTables{ get; set; }
  3273. internal static bool OverrideProperties { get; set; }
  3274. }
  3275. internal enum Scope
  3276. {
  3277. DatabaseScope, TableScope, SelectedScope
  3278. }
  3279. }