-
Notifications
You must be signed in to change notification settings - Fork 2
/
AbstractSqlDataService.cs
3041 lines (2935 loc) · 101 KB
/
AbstractSqlDataService.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
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
992
993
994
995
996
997
998
999
1000
#region license
/*
Copyright 2005 - 2021 Advantage Solutions, s. r. o.
This file is part of ORIGAM (http://www.origam.org).
ORIGAM is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
ORIGAM is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with ORIGAM. If not, see <http://www.gnu.org/licenses/>.
*/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Linq;
using System.Security.Principal;
using System.Text;
using log4net;
using Origam.DA.ObjectPersistence;
using Origam.DA.Service.Generators;
using Origam.Extensions;
using Origam.Schema;
using Origam.Schema.EntityModel;
using Origam.Services;
using Origam.Workbench.Services;
namespace Origam.DA.Service
{
#region Data Loader
internal class DataLoader
{
private static readonly ILog log
= LogManager.GetLogger(
System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public string ConnectionString = null;
public DataStructureFilterSet FilterSet = null;
public DataStructureSortSet SortSet = null;
public DataStructureEntity Entity = null;
public DataStructureQuery Query = null;
public DataStructure DataStructure = null;
public DataSet Dataset = null;
public AbstractSqlDataService DataService = null;
public IDbTransaction Transaction = null;
public string TransactionId;
public UserProfile CurrentProfile = null;
public int Timeout;
public void Fill()
{
IDbConnection connection = (Transaction == null)
? DataService.GetConnection(ConnectionString)
: Transaction.Connection;
try
{
DbDataAdapter adapter;
switch(Query.DataSourceType)
{
case QueryDataSourceType.DataStructure:
{
var selectParameters = new SelectParameters
{
DataStructure = DataStructure,
Entity = Entity,
Filter = FilterSet,
SortSet = SortSet,
Parameters = Query.Parameters.ToHashtable(),
Paging = Query.Paging,
ColumnsInfo = Query.ColumnsInfo,
AggregatedColumns = Query.AggregatedColumns
};
adapter = DataService.GetAdapter(
selectParameters, CurrentProfile);
break;
}
case QueryDataSourceType.DataStructureEntity:
{
adapter = DataService.GetSelectRowAdapter(
Entity, FilterSet, Query.ColumnsInfo);
break;
}
default:
throw new ArgumentOutOfRangeException(
"DataSourceType",
Query.DataSourceType,
ResourceUtils.GetString("UnknownDataSource"));
}
IDbDataAdapter dbDataAdapter = adapter;
dbDataAdapter.SelectCommand.Connection = connection;
dbDataAdapter.SelectCommand.Transaction = Transaction;
dbDataAdapter.SelectCommand.CommandTimeout = Timeout;
// ignore any extra fields returned by the select statement
// e.g. RowNum returned when paging is turned on
adapter.MissingMappingAction = MissingMappingAction.Ignore;
DataService.BuildParameters(
Query.Parameters,
dbDataAdapter.SelectCommand.Parameters,
CurrentProfile);
try
{
if(Transaction == null)
{
connection.Open();
}
Dataset.Tables[Entity.Name].BeginLoadData();
DataService.TraceCommand(
dbDataAdapter.SelectCommand, TransactionId);
adapter.Fill(Dataset);
Dataset.Tables[Entity.Name].EndLoadData();
}
catch(Exception ex)
{
HandleException(
exception: ex,
commandText: dbDataAdapter.SelectCommand.CommandText,
logAsDebug: (Entity.Name == "AsapModelVersion")
&& (ex is SqlException)
&& (ex.HResult == -2146232060));
}
finally
{
((IDbDataAdapter)adapter).SelectCommand.Transaction = null;
((IDbDataAdapter)adapter).SelectCommand.Connection = null;
}
}
finally
{
try
{
if(Transaction == null)
{
connection.Close();
}
}
catch
{
}
if(Transaction == null)
{
connection.Dispose();
}
}
}
private void HandleException(
Exception exception, string commandText, bool logAsDebug)
{
if(log.IsErrorEnabled && !logAsDebug)
{
log.LogOrigamError(
$"{exception.Message}, SQL: {commandText}",
exception);
}
else if(log.IsDebugEnabled && logAsDebug)
{
log.Debug(
$"{exception.Message}, SQL: {commandText}",
exception);
}
var standardMessage = ResourceUtils.GetString(
"ErrorLoadingData",
(Entity.EntityDefinition as TableMappingItem)?.MappedObjectName,
Entity.Name,
Environment.NewLine, exception.Message);
DataService.HandleException(exception, standardMessage, null);
}
}
#endregion
// version of log4net for NetStandard 1.3 does not have the method
// LogManager.GetLogger(string)... have to use the overload with Type
// as parameter
public class ConcurrencyExceptionLogger
{
}
public abstract class AbstractSqlDataService : AbstractDataService
{
private readonly Profiler profiler = new Profiler();
private static readonly ILog log = LogManager.GetLogger(
System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Special logger for concurrency exception detail logging
private static readonly ILog concurrencyLog = LogManager.GetLogger(
typeof(ConcurrencyExceptionLogger));
private IDbDataAdapterFactory adapterFactory;
private string connectionString = "";
private const int DATA_VISUALIZATION_MAX_LENGTH = 100;
#region Constructors
public AbstractSqlDataService()
{
}
public AbstractSqlDataService(
string connection, int bulkInsertThreshold, int updateBatchSize)
{
connectionString = connection;
UpdateBatchSize = updateBatchSize;
BulkInsertThreshold = bulkInsertThreshold;
}
#endregion
public override string ConnectionString
{
get => connectionString;
set => connectionString = value;
}
public override IDbDataAdapterFactory DbDataAdapterFactory
{
get => adapterFactory;
internal set => adapterFactory = value;
}
#region Public Methods
public abstract string CreateSystemRole(string roleName);
public abstract string CreateInsert(int fieldCount);
internal override IDbTransaction GetTransaction(
string transactionId, IsolationLevel isolationLevel)
{
IDbTransaction transaction;
if(transactionId == null)
{
var connection = GetConnection(ConnectionString);
connection.Open();
transaction = connection.BeginTransaction(isolationLevel);
}
else
{
if(!(ResourceMonitor.GetTransaction(
transactionId, ConnectionString)
is OrigamDbTransaction origamDbTransaction))
{
transaction = GetTransaction(null, isolationLevel);
ResourceMonitor.RegisterTransaction(transactionId,
ConnectionString, new OrigamDbTransaction(transaction));
}
else
{
transaction = origamDbTransaction.Transaction;
if(transaction.IsolationLevel != isolationLevel)
{
throw new Exception("Existing transaction has a different isolation level then the current query. When using a different isolation level the query has to be executed under a different or no transaction.");
}
}
}
return transaction;
}
public override DataSet LoadDataSet(
DataStructureQuery dataStructureQuery,
IPrincipal principal, string transactionId)
{
var loadedDataSet = LoadDataSet(
dataStructureQuery, principal, null, transactionId);
profiler.LogRememberedExecutionTimes();
return loadedDataSet;
}
public override DataSet LoadDataSet(DataStructureQuery query,
IPrincipal principal, DataSet dataset, string transactionId)
{
var settings = ConfigurationManager.GetActiveConfiguration();
int timeout = settings.DataServiceSelectTimeout;
UserProfile currentProfile = null;
if(query.LoadByIdentity)
{
currentProfile = SecurityManager.GetProfileProvider()
.GetProfile(principal.Identity) as UserProfile;
}
if(PersistenceProvider == null)
{
throw new NullReferenceException(
ResourceUtils.GetString("NoProviderForMS"));
}
ArrayList entities;
DataStructure dataStructure = null;
DataStructureFilterSet filterSet = null;
DataStructureSortSet sortSet = null;
switch(query.DataSourceType)
{
case QueryDataSourceType.DataStructure:
{
dataStructure = GetDataStructure(query);
filterSet = GetFilterSet(query.MethodId);
sortSet = GetSortSet(query.SortSetId);
if(string.IsNullOrEmpty(query.Entity))
{
entities = dataStructure.Entities;
}
else
{
entities = new ArrayList();
foreach(DataStructureEntity dataStructureEntity
in dataStructure.Entities)
{
if(dataStructureEntity.Name == query.Entity)
{
entities.Add(dataStructureEntity);
break;
}
}
if(entities.Count == 0)
{
throw new ArgumentOutOfRangeException(
$"Entity {query.Entity} not found in data structure {dataStructure.Path}.");
}
}
if(dataset == null)
{
dataset = GetDataset(dataStructure, query.DefaultSetId);
}
break;
}
case QueryDataSourceType.DataStructureEntity:
{
entities = new ArrayList();
filterSet = GetFilterSet(query.MethodId);
entities.Add(GetDataStructureEntity(query));
if(dataset == null)
{
throw new NullReferenceException(
ResourceUtils.GetString("DataSetMustBeProvided"));
}
break;
}
default:
{
throw new ArgumentOutOfRangeException(
"DataSourceType", query.DataSourceType,
ResourceUtils.GetString("UnknownDataSource"));
}
}
IDictionary<DataColumn, string> expressions
= DatasetTools.RemoveExpressions(dataset, true);
if((dataset.Tables.Count > 1) && query.Paging)
{
throw new Exception(
"Paging is allowed only on data structures with a single entity.");
}
bool enforceConstraints = dataset.EnforceConstraints;
dataset.EnforceConstraints = false;
foreach(DataStructureEntity entity in entities)
{
if(LoadWillReturnZeroResults(
dataset, entity, query.DataSourceType))
{
continue;
}
// Skip self joins, they are just relations, not really entities
if((entity.Columns.Count > 0)
&& !(entity.Entity is IAssociation association
&& association.IsSelfJoin))
{
profiler.ExecuteAndRememberLoadDuration(
entity: entity,
actionToExecute: () =>
{
var loader = new DataLoader
{
ConnectionString = connectionString,
DataService = this,
Dataset = dataset,
TransactionId = transactionId
};
if(transactionId != null)
{
loader.Transaction
= GetTransaction(transactionId,
query.IsolationLevel);
}
loader.DataStructure = dataStructure;
loader.Entity = entity;
loader.FilterSet = filterSet;
loader.SortSet = sortSet;
loader.Query = query;
loader.Timeout = timeout;
loader.CurrentProfile = currentProfile;
loader.Fill();
});
}
}
if(query.EnforceConstraints)
{
try
{
dataset.EnforceConstraints = enforceConstraints;
}
catch(Exception ex)
{
try
{
log.LogOrigamError(
DebugClass.ListRowErrors(dataset), ex);
using(var writer = System.IO.File.CreateText(
AppDomain.CurrentDomain.BaseDirectory
+ @"\debug\"
+ DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss-")
+ DateTime.Now.Ticks
+ "___MsSqlDataService_error.txt"))
{
writer.WriteLine(DebugClass.ListRowErrors(dataset));
writer.Close();
}
}
catch
{
}
throw;
}
}
DatasetTools.SetExpressions(expressions);
return dataset;
}
private bool LoadWillReturnZeroResults(DataSet dataset,
DataStructureEntity entity, QueryDataSourceType dataSourceType)
{
DataStructureEntity rootEntity = entity.RootEntity;
if(dataSourceType == QueryDataSourceType.DataStructureEntity)
{
return false;
}
if(rootEntity == entity)
{
return false;
}
if(entity.RelationType != RelationType.Normal)
{
return false;
}
if(!(rootEntity.Entity is TableMappingItem mappingItem))
{
return false;
}
string rootEntityTableName = mappingItem.MappedObjectName;
DataTable rootTable = dataset.Tables
.Cast<DataTable>()
.FirstOrDefault(
table => table.TableName == rootEntityTableName);
return (rootTable != null) && (rootTable.Rows.Count == 0);
}
public override int UpdateData(
DataStructureQuery query, IPrincipal userProfile, DataSet dataset,
string transactionId)
{
return UpdateData(
query, userProfile, dataset, transactionId, false);
}
public override int UpdateData(
DataStructureQuery query, IPrincipal userProfile, DataSet dataset,
string transactionId, bool forceBulkInsert)
{
if(log.IsDebugEnabled)
{
log.RunHandled(() =>
{
log.DebugFormat("UpdateData; Data Structure Id: {0}",
query.DataSourceId);
var stringBuilder = new StringBuilder();
var stringWriter
= new System.IO.StringWriter(stringBuilder);
dataset.WriteXml(stringWriter, XmlWriteMode.DiffGram);
log.DebugFormat("UpdateData; {0}", stringBuilder);
});
}
var newTransaction = (transactionId == null);
if(transactionId == null)
{
transactionId = Guid.NewGuid().ToString();
}
// If there is nothing to update, we quit immediately
if(!dataset.HasChanges())
{
return 0;
}
UserProfile profile = null;
if(query.LoadByIdentity)
{
profile = SecurityManager.GetProfileProvider().GetProfile(
userProfile.Identity) as UserProfile;
}
var stateMachine = StateMachine;
DataSet changedDataset = dataset;
DataStructure dataStructure = GetDataStructure(query);
if(dataStructure.IsLocalized)
{
throw new OrigamException(
$"Couldn't update localized data structure `{dataStructure.Name}' ({dataStructure.Id})");
}
IDbTransaction transaction = GetTransaction(
transactionId, query.IsolationLevel);
IDbConnection connection = transaction.Connection;
var currentEntityName = "";
var lastTableName = "";
ArrayList entities = dataStructure.Entities;
var changedTables = new ArrayList();
var deletedRowIds = new ArrayList();
var rowStates = new[]
{
DataRowState.Deleted, DataRowState.Added, DataRowState.Modified
};
DataTable changedTable = null;
try
{
foreach(var rowState in rowStates)
{
var actualEntities = entities;
// for delete use reverse entity order
if(rowState == DataRowState.Deleted)
{
actualEntities = new ArrayList(entities.Count);
for(var i = entities.Count - 1; i >= 0; i--)
{
actualEntities.Add(entities[i]);
}
}
foreach(DataStructureEntity entity in actualEntities)
{
currentEntityName = entity.Name;
// We check if the dataset actually contains the entity.
// E.g. for self-joins the entity name is not contained
// in the dataset but that does not matter
// because we save such an entity once anyway.
if(!(entity.EntityDefinition
is TableMappingItem tableMapping)
|| !changedDataset.Tables.Contains(currentEntityName))
{
continue;
}
lastTableName = dataset.Tables[currentEntityName]
.DisplayExpression.Replace("'", "");
if(lastTableName == "")
{
lastTableName = currentEntityName;
}
// we clone the table because if without complete dataset,
// some expressions might not work if they reference
// other entities
changedTable = DatasetTools.CloneTable(
changedDataset.Tables[entity.Name], false);
foreach(DataRow row
in changedDataset.Tables[entity.Name].Rows)
{
if(row.RowState == rowState)
{
// Constraints might fail right here if the
// source dataset has constraints turned off,
// e.g. through a flag in a sequential workflow.
// That is OK. Otherwise they would fail
// in the database.
changedTable.ImportRow(row);
}
}
if(tableMapping.DatabaseObjectType
== DatabaseMappingObjectType.Table)
{
if(changedTable != null)
{
if((stateMachine != null)
&& query.FireStateMachineEvents)
{
stateMachine.OnDataChanging(
changedTable, transactionId);
}
}
var rowCount = changedTable.Rows.Count;
if(rowCount > 0)
{
profiler.ExecuteAndLogStoreActionDuration(
entity: entity,
actionToExecute: () =>
{
ExecuteUpdate(query, transactionId,
profile, dataStructure,
transaction, connection,
deletedRowIds, changedTable,
rowState, entity, rowCount,
forceBulkInsert);
});
}
}
// finally add the table to a list of changed tables so
// changes can be accepted later
if(!changedTables.Contains(changedTable.TableName))
{
changedTables.Add(changedTable.TableName);
}
}
}
// execute the state machine events
if((stateMachine != null) && query.FireStateMachineEvents)
{
stateMachine.OnDataChanged(
dataset, changedTables, transactionId);
}
// accept changes
AcceptChanges(dataset, changedTables, query, transactionId,
userProfile);
profiler.LogRememberedExecutionTimes();
// delete attachments if any
if((deletedRowIds.Count > 0)
&& query.SynchronizeAttachmentsOnDelete)
{
var attachmentService = ServiceManager.Services
.GetService<IAttachmentService>();
foreach(Guid recordId in deletedRowIds)
{
attachmentService.RemoveAttachment(
recordId, transactionId);
}
}
if(newTransaction)
{
ResourceMonitor.Commit(transactionId);
}
}
catch(DBConcurrencyException ex)
{
if(log.IsErrorEnabled)
{
log.Error("DBConcurrencyException occurred! See \"Origam.DA.Service.ConcurrencyExceptionLogger\" logger (Debug mode) for more details");
}
if(concurrencyLog.IsDebugEnabled)
{
concurrencyLog.DebugFormat(
"Concurrency exception data structure query details: ds: `{0}', method: `{1}', sortSet: `{2}', default set: `{3}'",
query.DataSourceId,
query.MethodId,
query.SortSetId,
query.DefaultSetId);
}
var errorString = ComposeConcurrencyErrorMessage(userProfile,
dataset, transactionId, currentEntityName, lastTableName,
ex);
if (newTransaction)
{
ResourceMonitor.Rollback(transactionId);
transactionId = null;
}
// log before throw (because there are some place(s)
// where the exception isn't caught
if(concurrencyLog.IsDebugEnabled)
{
concurrencyLog.DebugFormat(
"Concurrency exception details: {0}", errorString);
}
throw new DBConcurrencyException(errorString, ex);
}
catch (Exception ex)
{
if(log.IsErrorEnabled)
{
log.LogOrigamError("Update failed", ex);
}
if(newTransaction)
{
ResourceMonitor.Rollback(transactionId);
}
ComposeGeneralErrorMessage(lastTableName, changedTable, ex);
throw;
}
finally
{
if(transactionId == null)
{
connection.Close();
connection.Dispose();
}
}
return 0;
}
private void ComposeGeneralErrorMessage(
string lastTableName, DataTable changedTable, Exception exception)
{
DataRow errorRow = DatasetTools.GetErrorRow(changedTable);
if(errorRow == null)
{
return;
}
string rowErrorMessage = null;
var operation = "";
switch(errorRow.RowState)
{
case DataRowState.Added:
{
operation = ResourceUtils.GetString(
"ErrorCouldNotAddRow");
break;
}
case DataRowState.Deleted:
{
operation = ResourceUtils.GetString(
"ErrorCouldNotDeleteRow");
break;
}
case DataRowState.Modified:
{
operation = ResourceUtils.GetString(
"ErrorCouldNotModifyRow");
break;
}
}
var recordDescription = DatasetTools.GetRowDescription(
errorRow);
if(recordDescription != null)
{
recordDescription = " " + recordDescription;
}
rowErrorMessage = string.Format(
operation, lastTableName, recordDescription);
HandleException(exception, rowErrorMessage, errorRow);
}
private string ComposeConcurrencyErrorMessage(IPrincipal userProfile,
DataSet dataset, string transactionId, string currentEntityName,
string lastTableName, DBConcurrencyException exception)
{
var concurrentUserName = "";
var errorString = "";
try
{
DataTable table = dataset.Tables[currentEntityName];
// if the row in the queue is being deleted we will not find it
// in the original data
// in that case we will use the row provided by the event
// which contains the data
DataRow row = table.Rows.Find(
DatasetTools.PrimaryKey(exception.Row))
?? exception.Row;
// load the existing row from the database to see what changes
// have been made by the other user
DataSet storedData = CloneDatasetForActualRow(table);
var entityId = (Guid)table.ExtendedProperties["Id"];
var entity = GetEntity(entityId);
var rowName = DatasetTools.PrimaryKey(row)[0].ToString();
IDataEntityColumn describingField
= entity.EntityDefinition.DescribingField;
if((describingField != null)
&& table.Columns.Contains(describingField.Name))
{
if(!row.IsNull(describingField.Name))
{
rowName = row[describingField.Name].ToString();
}
}
LoadActualRow(storedData, entityId, Guid.Empty, row,
userProfile, transactionId);
DataTable storedTable = storedData.Tables[currentEntityName];
if(storedTable.Rows.Count == 0)
{
errorString = ResourceUtils.GetString(
"DataDeletedByOtherUserException", rowName,
lastTableName);
}
else
{
DataRow storedRow = storedTable.Rows[0];
if(storedTable.Columns.Contains("RecordUpdatedBy")
&& !storedRow.IsNull("RecordUpdatedBy"))
{
var concurrentProfile = SecurityManager
.GetProfileProvider().GetProfile(
(Guid)storedRow["RecordUpdatedBy"])
as UserProfile;
concurrentUserName = concurrentProfile.FullName;
}
errorString = ResourceUtils.GetString(
"DataChangedByOtherUserException", rowName,
lastTableName, concurrentUserName);
foreach(DataColumn column in row.Table.Columns)
{
IDataEntityColumn field = GetField(
(Guid)column.ExtendedProperties["Id"]);
if((column.ColumnName == "RecordUpdatedBy")
|| !(field is FieldMappingItem))
{
continue;
}
string storedValue = null;
string myValue = null;
if(!storedRow.IsNull(column.ColumnName))
{
storedValue = storedRow[column.ColumnName]
.ToString();
}
if(!row.IsNull(column, DataRowVersion.Original))
{
myValue = row[column, DataRowVersion.Original]
.ToString();
}
if(storedValue != null && storedValue.Equals(myValue)
|| (storedValue == null && myValue == null))
{
continue;
}
if(column.ExtendedProperties.Contains(
Const.DefaultLookupIdAttribute))
{
var lookupService = ServiceManager.Services
.GetService<IDataLookupService>();
// this is a lookup column,
// we pass the looked-up value
var lookupId
= (Guid)column.ExtendedProperties[
Const.DefaultLookupIdAttribute];
if(myValue != "")
{
myValue = lookupService.GetDisplayText(
lookupId, myValue, transactionId)
.ToString();
}
if(storedValue != "")
{
storedValue = lookupService
.GetDisplayText(lookupId,
storedValue, transactionId)
.ToString();
}
}
errorString += Environment.NewLine
+ "- "
+ column.Caption
+ ": "
+ (myValue ?? "null")
+ " > "
+ (storedValue ?? "null");
}
}
while(row.Table.ParentRelations.Count > 0)
{
row = row.GetParentRow(row.Table.ParentRelations[0]);
row.RowError = ResourceUtils.GetString("ChildErrors");
}
}
catch
{
}
return errorString;
}
private void ExecuteUpdate(
DataStructureQuery query,
string transactionId,
UserProfile profile,
DataStructure dataStructure,
IDbTransaction transaction,
IDbConnection connection,
ArrayList deletedRowIds,
DataTable changedTable,
DataRowState rowState,
DataStructureEntity entity,
int rowCount,
bool forceBulkInsert)
{
// LOGGING
LogData(changedTable, profile, transactionId, connection,
transaction);
if((forceBulkInsert || ((BulkInsertThreshold != 0)
&& (rowCount > BulkInsertThreshold)))
&& (rowState == DataRowState.Added))
{
BulkInsert(entity, connection,
transaction, changedTable);
if(log.IsInfoEnabled)
{
log.Info("BulkCopy; Entity: "
+ changedTable?.TableName
+ ", " + rowState
+ " " + rowCount
+ " row(s). Transaction id: "
+ transactionId);
}
}
else
{
DataStructureFilterSet filter = GetFilterSet(query.MethodId);
DataStructureSortSet sortSet = GetSortSet(query.SortSetId);
// CONFIGURE DATA ADAPTER
var adapterParameters = new SelectParameters
{
DataStructure = dataStructure,
Entity = entity,
Filter = filter,
SortSet = sortSet,
Parameters = query.Parameters.ToHashtable(),
Paging = false
};
DbDataAdapter adapter = GetAdapter(adapterParameters, profile);
SetConnection(adapter, connection);
SetTransaction(adapter, transaction);
if(UpdateBatchSize != 0)
{
adapter.InsertCommand.UpdatedRowSource
= UpdateRowSource.None;
adapter.UpdateCommand.UpdatedRowSource
= UpdateRowSource.None;
adapter.DeleteCommand.UpdatedRowSource
= UpdateRowSource.None;
adapter.UpdateBatchSize = UpdateBatchSize;
}
switch(rowState)
{
// EXECUTE THE UPDATE
case DataRowState.Modified:
{
TraceCommand(((IDbDataAdapter)adapter).UpdateCommand,
transactionId);
break;
}
case DataRowState.Deleted:
{
TraceCommand(((IDbDataAdapter)adapter).DeleteCommand,
transactionId);
// remember row in order to delete an attachment later
// at the end of updateData
if((changedTable.PrimaryKey.Length == 1)
&& (changedTable.PrimaryKey[0].DataType
== typeof(Guid)))
{
// entity has a primary key Id taken from IOrigamEntity2
foreach (DataRow row in changedTable.Rows)
{
deletedRowIds.Add(
row[changedTable.PrimaryKey[0].ColumnName,
DataRowVersion.Original]);
}
}
break;
}
case DataRowState.Added:
{
TraceCommand(((IDbDataAdapter)adapter).InsertCommand,
transactionId);
break;
}
}
int result = adapter.Update(changedTable);
if(log.IsInfoEnabled)
{
log.Info(
"UpdateData; Entity: "
+ changedTable.TableName
+ ", "
+ rowState
+ " "
+ result
+ " row(s). Transaction id: "
+ transactionId);
}
// FREE THE ADAPTER
SetTransaction(adapter, null);
SetConnection(adapter, null);
// CHECK CONCURRENCY VIOLATION
if(result != rowCount)
{
throw new DBConcurrencyException(
ResourceUtils.GetString(
"ConcurrencyViolation",
changedTable.TableName));
}
}
}
internal virtual void BulkInsert(
DataStructureEntity entity,
IDbConnection connection,
IDbTransaction transaction,
DataTable table)
{
throw new NotImplementedException();
}
private Hashtable GetScalarCommandCache()
{
Hashtable context = OrigamUserContext.Context;
lock (context)