Repository navigation
Expand file tree
/
Copy pathDataConnectionBase.cs
More file actions
991 lines (904 loc) · 36.6 KB
/
Copy pathDataConnectionBase.cs
File metadata and controls
991 lines (904 loc) · 36.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Drawing.Design;
using System.Linq;
using System.Reflection;
using FastReport.Data.JsonConnection;
using FastReport.Utils;
namespace FastReport.Data
{
/// <summary>
/// The base class for all data connection components such as <see cref="MsSqlDataConnection"/>.
/// </summary>
/// <example>This example shows how to add a new MS Access connection to the report.
/// <code>
/// Report report1;
/// MsAccessDataConnection conn = new MsAccessDataConnection();
/// conn.DataSource = @"c:\data.mdb";
/// report1.Dictionary.Connections.Add(conn);
/// conn.CreateAllTables();
/// </code>
/// </example>
public abstract partial class DataConnectionBase : DataComponentBase, IParent
{
#region Fields
private DataSet dataSet;
private TableCollection tables;
private bool isSqlBased;
private bool canContainProcedures;
private string connectionString;
private string connectionStringExpression;
private bool loginPrompt;
private int commandTimeout;
private string lastConnectionString;
#endregion
#region Properties
/// <summary>
/// Gets an internal <b>DataSet</b> object that contains all data tables.
/// </summary>
[Browsable(false)]
public DataSet DataSet
{
get
{
if (dataSet == null)
dataSet = CreateDataSet();
return dataSet;
}
}
/// <summary>
/// Gets a collection of data tables in this connection.
/// </summary>
/// <remarks>
/// To add a table to the connection, you must either create a new TableDataSource and add it
/// to this collection or call the <see cref="CreateAllTables()"/> method which will add
/// all tables available in the database.
/// </remarks>
[Browsable(false)]
public TableCollection Tables
{
get { return tables; }
}
/// <summary>
/// Gets or sets a connection string that contains all connection parameters.
/// </summary>
/// <remarks>
/// <para>To modify some parameter of the connection, use respective
/// <b>ConnectionStringBuilder</b> class.</para>
/// <para><b>Security note:</b> the connection string may contain a user name/password.
/// This information is stored in a report file. By default, it is crypted using the standard
/// FastReport's password. Since FastReport's source code is available to anyone who paid for it,
/// it may be insecure to use the standard password. For more security, you should use own
/// password. To do this, specify it in the <b>Crypter.DefaultPassword</b> property.</para>
/// </remarks>
/// <example>This example demonstrates how to change a connection string:
/// <code>
/// OleDbConnectionStringBuilder builder = new OleDbConnectionStringBuilder(oleDbConnection1.ConnectionString);
/// builder.PersistSecurityInfo = false;
/// oleDbConnection1.ConnectionString = builder.ToString();
/// </code>
/// </example>
[Category("Data")]
[Browsable(true)]
public string ConnectionString
{
get
{
if (Report != null && Report.IsRunning && !String.IsNullOrEmpty(ConnectionStringExpression))
return Report.Calc(ConnectionStringExpression).ToString();
return connectionString;
}
set
{
SetConnectionString(Crypter.DecryptString(value));
}
}
/// <summary>
/// Gets or sets an expression that returns a connection string.
/// </summary>
/// <remarks>
/// Use this property to set the connection string dynamically.
/// <para/>The recommended way to do this is to define a report parameter. You can do this in the
/// "Data" window. Once you have defined the parameter, you can use it to pass a value
/// to the connection. Set the <b>ConnectionStringExpression</b> property of the
/// connection object to the report parameter's name (so it will look like [myReportParam]).
/// To pass a value to the report parameter from your application, use the
/// <see cref="Report.SetParameterValue"/> method.
/// <note type="caution">
/// Once you set value for this property, the <see cref="ConnectionString"/> property will be ignored
/// when report is run.
/// </note>
/// </remarks>
[Category("Data")]
[Editor("FastReport.TypeEditors.ExpressionEditor, FastReport", typeof(UITypeEditor))]
public string ConnectionStringExpression
{
get
{
return connectionStringExpression;
}
set { connectionStringExpression = value; }
}
/// <summary>
/// Gets or sets a value indicates if this connection is SQL-based.
/// </summary>
[Browsable(false)]
public bool IsSqlBased
{
get { return isSqlBased; }
set { isSqlBased = value; }
}
/// <summary>
/// Gets or sets a value indicates if this connection can contain procedures.
/// </summary>
[Browsable(false)]
public bool CanContainProcedures
{
get { return canContainProcedures; }
set { canContainProcedures = value; }
}
/// <summary>
/// Gets or sets a value indicating whether a login dialog appears immediately before opening a connection.
/// </summary>
/// <remarks>
/// Set <b>LoginPrompt</b> to <b>true</b> to provide login dialog when establishing a connection. If this
/// property is <b>false</b> (by default), you should provide login information (user name and password)
/// in the <see cref="ConnectionString"/> property. Though that property is stored in a crypted form,
/// this may be insecure.
/// <para/>Another way to pass login information to the connection is to use
/// <see cref="ConnectionStringExpression"/> property that is bound to the report parameter. In that
/// case you supply the entire connection string from your application.
/// </remarks>
[Category("Data")]
[DefaultValue(false)]
public bool LoginPrompt
{
get { return loginPrompt; }
set { loginPrompt = value; }
}
/// <summary>
/// Gets or sets the command timeout, in seconds.
/// </summary>
[Category("Data")]
[DefaultValue(30)]
public int CommandTimeout
{
get { return commandTimeout; }
set { commandTimeout = value; }
}
internal List<XmlItem> TablesStructure { get; set; }
#endregion
#region Private Methods
private void GetDBObjectNames(string name, List<string> list)
{
DataTable schema = null;
DbConnection conn = GetConnection();
try
{
OpenConnection(conn);
schema = conn.GetSchema("Tables", new string[] { null, null, null, name });
}
finally
{
DisposeConnection(conn);
}
foreach (DataRow row in schema.Rows)
{
list.Add(row["TABLE_NAME"].ToString());
}
}
private string PrepareSelectCommand(string selectCommand, string tableName, DbConnection connection)
{
if (String.IsNullOrEmpty(selectCommand))
{
selectCommand = "select * from " + QuoteIdentifier(tableName, connection);
}
return selectCommand;
}
private TableDataSource FindTableDataSource(DataTable table)
{
foreach (TableDataSource c in Tables)
{
if (c.Table == table)
return c;
}
return null;
}
#endregion
#region Protected Methods
/// <inheritdoc/>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
DisposeDataSet();
}
/// <summary>
/// Initializes a <b>DataSet</b> instance.
/// </summary>
/// <returns>The <b>DataSet</b> object.</returns>
/// <remarks>
/// This method is used to support FastReport infrastructure. You don't need to use it.
/// </remarks>
protected virtual DataSet CreateDataSet()
{
DataSet dataSet = new DataSet();
dataSet.EnforceConstraints = false;
return dataSet;
}
/// <summary>
/// Disposes a <b>DataSet</b>.
/// </summary>
/// <remarks>
/// This method is used to support FastReport infrastructure. You don't need to use it.
/// </remarks>
protected void DisposeDataSet()
{
if (dataSet != null)
dataSet.Dispose();
dataSet = null;
}
/// <summary>
/// Sets the connection string.
/// </summary>
/// <param name="value">New connection string.</param>
/// <remarks>
/// Use this method if you need to perform some actions when the connection string is set.
/// </remarks>
protected virtual void SetConnectionString(string value)
{
connectionString = value;
}
/// <summary>
/// Gets a connection string that contains username and password specified.
/// </summary>
/// <param name="userName">User name.</param>
/// <param name="password">Password.</param>
/// <remarks>
/// Override this method to pass login information to the connection. Typical implementation
/// must get the existing <see cref="ConnectionString"/>, merge specified login information into it
/// and return the new value.
/// </remarks>
protected virtual string GetConnectionStringWithLoginInfo(string userName, string password)
{
return ConnectionString;
}
#endregion
#region IParent Members
/// <inheritdoc/>
public bool CanContain(Base child)
{
return child is TableDataSource;
}
/// <inheritdoc/>
public void GetChildObjects(ObjectCollection list)
{
foreach (TableDataSource c in Tables)
{
list.Add(c);
}
}
/// <inheritdoc/>
public void AddChild(Base child)
{
Tables.Add(child as TableDataSource);
}
/// <inheritdoc/>
public void RemoveChild(Base child)
{
Tables.Remove(child as TableDataSource);
}
/// <inheritdoc/>
public int GetChildOrder(Base child)
{
// we don't need to handle database objects' order.
return 0;
}
/// <inheritdoc/>
public void SetChildOrder(Base child, int order)
{
// do nothing
}
/// <inheritdoc/>
public void UpdateLayout(float dx, float dy)
{
// do nothing
}
#endregion
#region Public Methods
/// <summary>
/// Fills the <see cref="Tables"/> collection with all tables available in the database.
/// </summary>
/// <remarks>
/// This method does not read the table data; to do this, call the
/// <see cref="TableDataSource.LoadData"/> method of each table.
/// </remarks>
public void CreateAllTables()
{
CreateAllTables(true);
}
/// <summary>
/// Fills the <see cref="Tables"/> collection with all tables available in the database.
/// </summary>
/// <param name="initSchema">Set to <b>true</b> to initialize each table's schema.</param>
public virtual void CreateAllTables(bool initSchema)
{
List<string> tableNames = new List<string>();
tableNames.AddRange(GetTableNames());
FilterTables(tableNames);
List<string> procedureNames = new List<string>();
if (canContainProcedures)
procedureNames.AddRange(GetProcedureNames());
// remove tables with tablename that does not exist in the connection.
for (int i = 0; i < Tables.Count; i++)
{
TableDataSource table = Tables[i];
bool found = !String.IsNullOrEmpty(table.SelectCommand);
// skip tables with non-empty selectcommand
if (!found)
{
foreach (string tableName in tableNames)
{
if (String.Compare(table.TableName, tableName, true) == 0)
{
found = true;
break;
}
}
}
// table name not found between actual tablenames. It may happen if we have edited the connection.
if (!found)
{
table.Dispose();
i--;
}
}
int tableNumber = 0;
// now create tables that are not created yet.
foreach (string tableName in tableNames)
{
bool found = false;
foreach (TableDataSource table in Tables)
{
if (String.Compare(table.TableName, tableName, true) == 0)
{
found = true;
break;
}
}
if (!found)
{
TableDataSource table = null;
if (procedureNames.Contains(tableName))
{
table = CreateProcedure(tableName);
}
else
table = new TableDataSource();
string fixedTableName = tableName.Replace(".", "_").Replace("[", "").Replace("]", "").Replace("\"", "");
if (Report != null)
{
table.Name = Report.Dictionary.CreateUniqueName(fixedTableName);
table.Alias = Report.Dictionary.CreateUniqueAlias(table.Alias);
}
else
table.Name = fixedTableName;
table.TableName = tableName;
table.Connection = this;
table.Enabled = false;
if (TablesStructure != null)
{
table.Enabled = TablesStructure[tableNumber].Properties.Where(prop => prop.Key == "Enabled").Select(res => res.Value).First() == "true";
}
Tables.Add(table);
tableNumber++;
}
}
initSchema = true;
// init table schema
if (initSchema)
{
foreach (TableDataSource table in Tables)
{
table.InitSchema();
}
}
}
/// <summary>
/// Create the stored procedure.
/// </summary>
public virtual TableDataSource CreateProcedure(string tableName)
{
ProcedureDataSource table = new ProcedureDataSource();
table.SelectCommand = tableName;
DbConnection conn = GetConnection();
DataTable shemaParametrs;
try
{
OpenConnection(conn);
shemaParametrs = conn.GetSchema("PROCEDURE_PARAMETRS", new string[] { null, null, tableName });
foreach (DataRow row in shemaParametrs.Rows)
{
ParameterDirection direction = ParameterDirection.Input;
switch (row["PARAMETER_MODE"].ToString())
{
case "IN":
direction = ParameterDirection.Input;
break;
case "INOUT":
direction = ParameterDirection.InputOutput;
break;
case "OUT":
direction = ParameterDirection.Output;
break;
}
table.Parameters.Add(new ProcedureParameter()
{
Name = row["PARAMETER_NAME"].ToString(),
DataType = Convert.ToInt32(row["DATA_TYPE"].ToString()),
Direction = direction
});
}
}
finally
{
DisposeConnection(conn);
}
return table;
}
/// <summary>
/// Creates the relations between tables. Applies to XmlDataConnection only.
/// </summary>
public virtual void CreateRelations()
{
if (Report != null)
{
foreach (DataRelation relation in DataSet.Relations)
{
Relation rel = new Relation();
rel.Name = relation.RelationName;
rel.ParentDataSource = FindTableDataSource(relation.ParentTable);
rel.ChildDataSource = FindTableDataSource(relation.ChildTable);
string[] parentColumns = new string[relation.ParentColumns.Length];
string[] childColumns = new string[relation.ChildColumns.Length];
for (int i = 0; i < relation.ParentColumns.Length; i++)
{
parentColumns[i] = relation.ParentColumns[i].Caption;
}
for (int i = 0; i < relation.ChildColumns.Length; i++)
{
childColumns[i] = relation.ChildColumns[i].Caption;
}
rel.ParentColumns = parentColumns;
rel.ChildColumns = childColumns;
if (Report.Dictionary.Relations.FindEqual(rel) == null)
Report.Dictionary.Relations.Add(rel);
else
rel.Dispose();
}
}
}
/// <summary>
/// Gets an array of table names available in the database.
/// </summary>
/// <returns>An array of strings.</returns>
public virtual string[] GetTableNames()
{
List<string> list = new List<string>();
GetDBObjectNames("TABLE", list);
GetDBObjectNames("VIEW", list);
if(canContainProcedures)
list.AddRange(GetProcedureNames());
return list.ToArray();
}
/// <summary>
/// Gets an array of table names available in the database.
/// </summary>
/// <returns>An array of strings.</returns>
public virtual string[] GetProcedureNames()
{
List<string> list = new List<string>();
DataTable schema = null;
DbConnection conn = GetConnection();
if (conn != null)
{
try
{
OpenConnection(conn);
schema = conn.GetSchema("PROCEDURE");
foreach (DataRow row in schema.Rows)
{
list.Add(row["PROCEDURE_NAME"].ToString());
}
}
finally
{
DisposeConnection(conn);
}
}
return list.ToArray();
}
/// <summary>
/// Returns a type of connection.
/// </summary>
/// <returns><b>Type</b> instance.</returns>
/// <remarks>
/// You should override this method if you developing a new connection component.
/// <para/>If your connection component does not use data connection, you need to override
/// the <see cref="FillTableSchema"/> and <see cref="FillTableData"/> methods instead.
/// </remarks>
/// <example>Here is the example of this method implementation:
/// <code>
/// public override Type GetConnectionType()
/// {
/// return typeof(OleDbConnection);
/// }
/// </code>
/// </example>
public virtual Type GetConnectionType()
{
return null;
}
/// <summary>
/// Returns a connection object.
/// </summary>
/// <returns>The <b>DbConnection</b> instance.</returns>
/// <remarks>Either creates a new <b>DbConnection</b> instance of type provided by the
/// <see cref="GetConnectionType"/> method, or returns the application connection if set
/// in the Config.DesignerSettings.ApplicationConnection.</remarks>
public DbConnection GetConnection()
{
Type connectionType = GetConnectionType();
if (connectionType != null)
{
DbConnection connection = GetDefaultConnection();
if (connection != null)
return connection;
// create a new connection object
connection = Activator.CreateInstance(connectionType) as DbConnection;
connection.ConnectionString = ConnectionString;
return connection;
}
return null;
}
/// <summary>
/// Opens a specified connection object.
/// </summary>
/// <param name="connection">Connection to open.</param>
/// <remarks>
/// Use this method to open a connection returned by the <see cref="GetConnection"/> method.
/// <para/>This method displays a login dialog if your connection has the <see cref="LoginPrompt"/>
/// property set to <b>true</b>. Once you have entered an user name and password in
/// this dialog, it will remeber the entered values and will not used anymore in this report session.
/// </remarks>
public void OpenConnection(DbConnection connection)
{
if (connection.State == ConnectionState.Open)
return;
if (!String.IsNullOrEmpty(lastConnectionString))
{
// connection string is already provided, use it and skip other logic.
connection.ConnectionString = lastConnectionString;
}
else
{
// try the global DatabaseLogin event
string oldConnectionString = ConnectionString;
DatabaseLoginEventArgs e = new DatabaseLoginEventArgs(ConnectionString);
Config.ReportSettings.OnDatabaseLogin(this, e);
// that event may do the following:
// - modify the ConnectionString
// - modify the username/password
// - there is no event handler attached to the event, so it does nothing.
if (oldConnectionString != e.ConnectionString)
{
// the connection string was modified. Set the FLastConnectionString to use it next time silently.
lastConnectionString = e.ConnectionString;
}
else
{
if (!String.IsNullOrEmpty(e.UserName) || !String.IsNullOrEmpty(e.Password))
{
// the username/password was modified. Get new connection string
lastConnectionString = GetConnectionStringWithLoginInfo(e.UserName, e.Password);
}
else if (LoginPrompt)
{
ShowLoginForm(lastConnectionString);
}
}
// update the connection if it's not done yet
if (!String.IsNullOrEmpty(lastConnectionString))
connection.ConnectionString = lastConnectionString;
}
connection.Open();
Config.ReportSettings.OnAfterDatabaseLogin(this, new AfterDatabaseLoginEventArgs(connection));
}
/// <summary>
/// Disposes a connection.
/// </summary>
/// <param name="connection">The connection to dispose.</param>
public void DisposeConnection(DbConnection connection)
{
if (ShouldNotDispose(connection))
return;
if (connection != null)
connection.Dispose();
}
/// <summary>
/// Returns a <see cref="DbDataAdapter"/> object that is specific to this connection.
/// </summary>
/// <param name="selectCommand">The SQL command used to fetch a table data rows.</param>
/// <param name="connection">The connection object.</param>
/// <param name="parameters">The select command parameters.</param>
/// <returns>The <b>DbDataAdapter</b> object.</returns>
/// <remarks>
/// You should override this method if you are developing a new connection component. In this method,
/// you need to create the adapter and set its <b>SelectCommand</b>'s parameters.
/// <para/>If your connection does not use data adapter, you need to override
/// the <see cref="FillTableSchema"/> and <see cref="FillTableData"/> methods instead.
/// </remarks>
/// <example>Here is the example of this method implementation:
/// <code>
/// public override DbDataAdapter GetAdapter(string selectCommand, DbConnection connection,
/// CommandParameterCollection parameters)
/// {
/// OleDbDataAdapter adapter = new OleDbDataAdapter(selectCommand, connection as OleDbConnection);
/// foreach (CommandParameter p in parameters)
/// {
/// OleDbParameter parameter = adapter.SelectCommand.Parameters.Add(p.Name, (OleDbType)p.DataType, p.Size);
/// parameter.Value = p.Value;
/// }
/// return adapter;
/// }
/// </code>
/// </example>
public virtual DbDataAdapter GetAdapter(string selectCommand, DbConnection connection,
CommandParameterCollection parameters)
{
return null;
}
/// <summary>
/// Gets the type of parameter that is specific to this connection.
/// </summary>
/// <returns>The parameter's type.</returns>
/// <remarks>
/// This property is used in the report designer to display available data types when you edit the
/// connection parameters. For example, the type of OleDbConnection parameter is a <b>OleDbType</b>.
/// </remarks>
public virtual Type GetParameterType()
{
return null;
}
/// <summary>
/// Quotes the specified DB identifier such as table name or column name.
/// </summary>
/// <param name="value">Identifier to quote.</param>
/// <param name="connection">The opened DB connection.</param>
/// <returns>The quoted identifier.</returns>
public abstract string QuoteIdentifier(string value, DbConnection connection);
/// <summary>
/// Fills the table schema.
/// </summary>
/// <param name="table">DataTable to fill.</param>
/// <param name="selectCommand">The SQL select command.</param>
/// <param name="parameters">SQL parameters.</param>
/// <remarks>
/// Usually you don't need to use this method. Internally it uses the <see cref="GetConnection"/> and
/// <see cref="GetAdapter"/> methods to fill the table schema. If you create own connection component
/// that does not use nor connection or adapter, then you need to override this method.
/// </remarks>
public virtual void FillTableSchema(DataTable table, string selectCommand,
CommandParameterCollection parameters)
{
DbConnection conn = GetConnection();
try
{
OpenConnection(conn);
TableDataSource dataSource = FindTableDataSource(table);
// prepare select command
if (!(dataSource is ProcedureDataSource))
selectCommand = PrepareSelectCommand(selectCommand, table.TableName, conn);
// read the table schema
using (DbDataAdapter adapter = GetAdapter(selectCommand, conn, parameters))
{
adapter.SelectCommand.CommandType = dataSource is ProcedureDataSource ? CommandType.StoredProcedure : CommandType.Text;
adapter.SelectCommand.CommandTimeout = CommandTimeout;
adapter.FillSchema(table, SchemaType.Source);
}
}
finally
{
DisposeConnection(conn);
}
}
/// <summary>
/// Fills the table data.
/// </summary>
/// <param name="table">DataTable to fill.</param>
/// <param name="selectCommand">The SQL select command.</param>
/// <param name="parameters">SQL parameters.</param>
/// <remarks>
/// Usually you don't need to use this method. Internally it uses the <see cref="GetConnection"/> and
/// <see cref="GetAdapter"/> methods to fill the table data. If you create own connection component
/// that does not use nor connection or adapter, then you need to override this method.
/// </remarks>
public virtual void FillTableData(DataTable table, string selectCommand,
CommandParameterCollection parameters)
{
DbConnection conn = GetConnection();
try
{
OpenConnection(conn);
TableDataSource dataSource = FindTableDataSource(table);
// prepare select command
if (!(dataSource is ProcedureDataSource))
selectCommand = PrepareSelectCommand(selectCommand, table.TableName, conn);
// read the table
using (DbDataAdapter adapter = GetAdapter(selectCommand, conn, parameters))
{
adapter.SelectCommand.CommandType = FindTableDataSource(table) is ProcedureDataSource ? CommandType.StoredProcedure : CommandType.Text;
adapter.SelectCommand.CommandTimeout = CommandTimeout;
table.Clear();
adapter.Fill(table);
if(canContainProcedures)
foreach (DbParameter dp in adapter.SelectCommand.Parameters)
{
if (dp.Direction != ParameterDirection.Input)
{
foreach (CommandParameter cp in dataSource.Parameters)
{
if (cp.Name == dp.ParameterName)
{
cp.Value = dp.Value;
Parameter parameter = Report.GetParameter(dataSource.Name + "_" + cp.Name);
if (parameter != null)
parameter.Value = dp.Value;
}
}
}
}
}
}
finally
{
DisposeConnection(conn);
}
}
/// <summary>
/// Creates table.
/// For internal use only.
/// </summary>
public virtual void CreateTable(TableDataSource source)
{
if (source.Table == null)
{
source.Table = new DataTable(source.TableName);
DataSet.Tables.Add(source.Table);
}
}
internal virtual void FillTable(TableDataSource source)
{
if (source.Table != null)
{
bool parametersChanged = false;
foreach (CommandParameter par in source.Parameters)
{
object value = par.Value;
if (!Object.Equals(value, par.LastValue))
{
par.LastValue = value;
parametersChanged = true;
}
}
if (source.ForceLoadData || source.Table.Rows.Count == 0 || parametersChanged)
FillTableData(source.Table, source.SelectCommand, source.Parameters);
}
}
/// <summary>
/// Deletes table.
/// For internal use only.
/// </summary>
public virtual void DeleteTable(TableDataSource source)
{
if (source.Table != null)
{
if (dataSet != null)
dataSet.Tables.Remove(source.Table);
source.Table.Dispose();
source.Table = null;
}
}
/// <summary>
/// Clone table.
/// For internal use only.
/// </summary>
public virtual void Clone()
{
XmlItem item = new XmlItem();
using(FRWriter writer = new FRWriter(item))
{
writer.SerializeTo = SerializeTo.Clipboard;
writer.BlobStore = new BlobStore(false);
writer.Write(this);
}
using (FRReader reader = new FRReader(Report, item))
{
reader.DeserializeFrom = SerializeTo.Clipboard;
reader.BlobStore = new BlobStore(false);
var connection = Activator.CreateInstance(this.GetType()) as DataConnectionBase;
connection.Parent = this.Parent;
connection.SetReport(Report);
reader.Read(connection);
connection.CreateUniqueName();
foreach (TableDataSource table in connection.Tables)
table.CreateUniqueName();
Report.Dictionary.AddChild(connection);
}
}
protected void CreateUniqueNames(DataConnectionBase copyTo)
{
int i = 1;
string s;
do
{
s = this.Alias + i.ToString();
i++;
}
while (Report.Dictionary.FindByAlias(s) != null);
copyTo.Alias = s;
copyTo.Name = s;
}
/// <inheritdoc/>
public override void Serialize(FRWriter writer)
{
writer.ItemName = ClassName;
if (Name != "")
writer.WriteStr("Name", Name);
if (Restrictions != Restrictions.None)
writer.WriteValue("Restrictions", Restrictions);
if (!String.IsNullOrEmpty(ConnectionString))
writer.WriteStr("ConnectionString", Crypter.EncryptString(ConnectionString));
if (!String.IsNullOrEmpty(ConnectionStringExpression))
writer.WriteStr("ConnectionStringExpression", ConnectionStringExpression);
if (LoginPrompt)
writer.WriteBool("LoginPrompt", true);
if (CommandTimeout != 30)
writer.WriteInt("CommandTimeout", CommandTimeout);
SerializeDesignExt(writer);
if (writer.SaveChildren)
{
foreach (TableDataSource c in Tables)
{
if (c.Enabled)
writer.Write(c);
}
}
}
/// <inheritdoc/>
public override string[] GetExpressions()
{
return new string[] { ConnectionStringExpression };
}
partial void SetConnectionStringBrowsableAttribute();
#endregion
/// <summary>
/// Initializes a new instance of the <see cref="DataConnectionBase"/> class with default settings.
/// </summary>
public DataConnectionBase()
{
tables = new TableCollection(this);
connectionString = "";
connectionStringExpression = "";
IsSqlBased = true;
canContainProcedures = false;
commandTimeout = 30;
SetFlags(Flags.CanEdit, true);
SetConnectionStringBrowsableAttribute();
}
partial void SerializeDesignExt(FRWriter writer);
}
}