Compare commits

...
87 Commits
Author SHA1 Message Date
jjenko 9078e99741 Merge pull request 'B2026-090 Populate Step Properties Panel when PROMS restores saved display tabs' (#833) from B2026-090 into Development
good for testing phase
2026-10-29 14:15:03 -04:00
mschill bbaea7ab67 B2026-090 Populate Step Properties Panel when PROMS restores saved display tabs 2026-10-29 14:08:56 -04:00
jjenko dc22ff6e3b Merge pull request 'B2026-086 Have Shortcut Keys for adding an RNO auto-work instead of having to press a button after shortcut key' (#832) from B2026-086 into Development
good for testing phase
2026-10-26 08:41:17 -04:00
mschill 72359319a4 B2026-086 Have Shortcut Keys for adding an RNO auto-work instead of having to press a button after shortcut key 2026-10-23 14:41:29 -04:00
jjenko f663e4f956 Merge pull request 'B2026-091 RO Editor - Change Default Prefix to take existing prefixes into account for Setpoint/Graphics DBs' (#831) from B2026-091 into Development
good for testing
2026-10-22 09:25:45 -04:00
mschill 87e163af15 B2026-091 RO Editor - Change Default Prefix to take existing prefixes into account for Setpoint/Graphics DBs 2026-10-22 07:30:36 -04:00
jjenko cb5bb715cf Merge pull request 'B2026-085 Disable Symbols when leave a TextBox' (#830) from B2026-085 into Development
good for testing phase
2026-10-20 10:54:10 -04:00
mschill 3929c5c36f B2026-085 Disable Symbols when leave a TextBox 2026-10-20 10:24:23 -04:00
jjenko 901d2e522b Merge pull request 'Update to TUECall' (#829) from B2026-077 into Development
ready for testing
2026-10-19 13:59:40 -04:00
mschill 17841b83be Update to TUECall 2026-10-19 13:45:22 -04:00
jjenko 29b4cc3089 Merge pull request 'C2026-061 Update the description in V button Options for "Show Prompt for Continuous Action and Time Critical Summaries" under "Opening in MS Word".' (#828) from C2026-061 into Development
good for testing phase
2026-10-16 08:59:56 -04:00
mschill 0700c05f4c C2026-061 Update the description in V button Options for "Show Prompt for Continuous Action and Time Critical Summaries" under "Opening in MS Word". 2026-10-16 06:02:50 -04:00
jjenko 8791402e39 Merge pull request 'B2026-078 Hide Delete and Open Button for Library Documents with any occurrences.' (#827) from B2026-078 into Development
good for testing phase
2026-10-15 14:48:57 -04:00
mschill 95115f445d B2026-078 Hide Delete and Open Button for Library Documents with any occurrences. 2026-10-15 14:25:49 -04:00
jjenko 93f82b2745 Merge pull request 'C2026-058 Check all Tables for if Acc Page Id Prefix is Used More than Once' (#826) from C2026-058 into Development
good for testing phase
2026-10-15 13:08:24 -04:00
jjenko 3bf928a035 Merge pull request 'B2026-077 – Update Format inheritance to use index id instead of position/order.' (#819) from B2026-077 into Development
good for testing
2026-10-15 13:07:08 -04:00
mschill 82f11fa696 C2026-058 Check all Tables for if Acc Page Id Prefix is Used More than Once 2026-10-15 11:27:45 -04:00
mschill 9c9e12ff57 Merge branch 'Development' into B2026-077 2026-10-14 09:25:05 -04:00
jjenko ae9fb0eb67 Merge pull request 'F2026-025 Added a sub-step tab definition for a fifth level sequential sub-step in the Bryon-Braidwood EOP format' (#825) from F2026-025_BraidwoodByron_StepLevelTab into Development
Format only change - approve by customer
Good for testing
2026-10-14 09:11:33 -04:00
jjenko 1c837accd7 F2026-025 Added a sub-step tab definition for a fifth level sequential sub-step in the Bryon-Braidwood EOP format 2026-10-14 09:11:11 -04:00
mschill b188a3af99 Merge branch 'B2026-077' of https://git.volian.com/Volian/SourceCode into B2026-077 2026-10-07 09:13:35 -04:00
mschill a8033f3e51 Updating to latest Dev 2026-10-07 09:13:19 -04:00
jjenko d69ab535d5 Merge pull request 'C2026 043 tech debt v1' (#817) from C2026-043-Tech-Debt_v1 into Development
passed testing with separate test executable.
no additional testing for this pull request needed.
2026-10-07 08:43:27 -04:00
mschill 49a3e647a2 Merge branch 'Development' into C2026-043-Tech-Debt_v1 2026-10-01 10:12:01 -04:00
mschill 2e3ef1e86f Merge branch 'Development' into B2026-077 2026-10-01 10:11:32 -04:00
jjenko 95a3039c96 Merge pull request 'C2026-060 Export with slash in folder name' (#824) from C2026-060 into Development
good for testing
2026-10-01 10:10:29 -04:00
jjenko ae2f765119 Merge pull request 'B2026-084 Spell Check crashing' (#823) from B2026-084 into Development
good for testing
2026-10-01 10:09:38 -04:00
mschill 9e85b43f64 Sleep when closing tabs 2026-10-01 09:00:59 -04:00
mschill 14fd0d34e2 C2026-060 Export with slash in folder name 2026-10-01 08:00:13 -04:00
mschill d045205d16 B2026-084 Spell Check crashing 2026-10-01 07:32:44 -04:00
mschill b2741d341c Bring up to date with Dev -- clearing merge conflicts 2026-09-30 10:23:57 -04:00
mschill e0614051f8 Merge branch 'Development' into B2026-077 2026-09-30 10:08:22 -04:00
mschill abe0444275 Merge pull request 'F2026-023 Code fix to so that single Notes do not get a bullet and format tweaks in the EOP and SAMG formats' (#822) from F2026-023_Farley_Arial_Tweaks into Development
Looks Good. Ready for QA.
2026-09-30 10:08:11 -04:00
jjenko 576b967f57 F2026-023 Code fix to so that single Notes do not get a bullet and format tweaks in the EOP and SAMG formats 2026-09-30 10:04:20 -04:00
mschill 7da1f86c86 Merge branch 'Development' into B2026-077 2026-09-30 08:21:21 -04:00
jjenko 6481e6cbba Merge pull request 'B2026-080 – Remove unicode from the Document Already Checked Out message box' (#821) from B2026-080 into Development
good for testing
2026-09-30 08:20:44 -04:00
mschill c151a9676f Merge branch 'Development' into B2026-080 2026-09-30 08:10:06 -04:00
mschill dddc464bad B2026-080 – Remove unicode from the Document Already Checked Out message box 2026-09-30 08:12:40 -04:00
jjenko b1bc954105 Merge pull request 'Remove Debug items from Source control that never should have been checked in for W2PGrid' (#820) from Clean_Debug_W2PGrid into Development
just moved un-used stuff out of project
No testing needed.
2026-09-29 09:25:20 -04:00
mschill 1ad5331ba9 Remove Debug items from Source control that never should have been checked in for W2PGrid 2026-09-29 07:51:33 -04:00
mschill f5f9975363 B2026-077 – Update Format inheritance to use index id instead of position/order. 2026-09-28 14:15:48 -04:00
mschill 8c8c876309 Remove SCLA Scoping 2026-09-23 11:04:30 -04:00
mschill 874f9241b8 Clean up in frmVEPROMS.cs --- hard coded based on RICH's PC name 2026-09-22 09:03:42 -04:00
mschill a680e8800d Add back in removed side effect code for printing grids with merged cells / checking boundaries 2026-09-15 13:30:48 -04:00
mschill 17e9a88a16 Merge branch 'Development' into C2026-043-Tech-Debt_v1 2026-09-15 13:13:13 -04:00
mschill 8df20f32ce Merge pull request 'B2026-076 - Update Base format to move new type to bottom' (#818) from B2026-076 into Development
Ready for QA
2026-09-15 11:59:46 -04:00
mschill 6ca427a7c6 B2026-076 - Update Base format to move new 2026-09-15 12:01:22 -04:00
mschill fe95afcf8f avoid Local Context 2026-09-15 08:29:29 -04:00
mschill 7c95b115e4 Check if connection state is closed before opening 2026-09-15 08:21:18 -04:00
mschill 5d4e5d9a1f Make Sure Connection is open when working with Local Context 2026-09-15 08:06:53 -04:00
mschill ac773b8ada Remove commented out code 2026-09-14 15:48:34 -04:00
mschill 42f1c1735d Merge branch 'Development' into C2026-043-Tech-Debt_v1 2026-09-14 15:31:58 -04:00
mschill 1c6f3e3e3c CSLA - R to Z 2026-09-14 15:30:10 -04:00
mschill 14a8922976 Merge pull request 'C2026-054 Text change for Open Tabs from Previous Session dialog box' (#815) from C2026-054-Text-change-for-Open-Tabs-from-Previous-Session into Development
Looks Good. Ready for QA.
2026-09-14 05:36:50 -04:00
plarsen 2f5affabbe C2026-054-Text-change-for-Open-Tabs-from-Previous-Session 2026-09-12 07:47:56 -04:00
mschill d238d6aed2 CSLA - R - Group 1 2026-09-11 16:03:51 -04:00
plarsen 44c86e5d80 C2026-054-Text-change-for-Open-Tabs-from-Previous-Session 2026-09-11 12:13:16 -04:00
mschill d9f8f6cb37 CSLA - M through P 2026-09-11 09:50:40 -04:00
plarsen d5859f2a01 C2026-054-Text-change-for-Open-Tabs-from-Previous-Session 2026-09-10 16:10:08 -04:00
mschill e41a4ea65d CSLA - Is 2026-09-10 16:02:04 -04:00
jjenko 506c826eb3 Merge pull request 'C2026 048 tool tip update' (#814) from C2026-048-Tool-Tip-Update into Development
good for testing phase
2026-09-10 14:00:18 -04:00
plarsen 96839f8379 Merge branch 'Development' into C2026-048-Tool-Tip-Update 2026-09-10 13:53:21 -04:00
plarsen f6e42d933e C2026-048-Tool-Tip-Update 2026-09-10 11:11:06 -04:00
mschill 8674b93723 Merge branch 'Development' into C2026-043-Tech-Debt_v1 2026-09-09 15:54:32 -04:00
mschill da8d25082f CSLA - G 2026-09-09 15:52:32 -04:00
mschill 28b79bf81b Merge pull request 'C2026-053' (#813) from C2026-053_restore_only_Proc_section_tabs into Development
Looks Good - Ready For QA
2026-09-09 14:54:21 -04:00
jjenko a87e23af7e C2026-053
When restoring the open procedure tabs while starting up PROMS, don’t restore any of the Word section tabs.
2026-09-09 14:51:51 -04:00
mschill f2b064f459 CSLA - E & F 2026-09-09 14:08:28 -04:00
mschill a69a2270a6 CLSA - Ds 2026-09-08 08:55:36 -04:00
mschill c21f366bb9 Bring Tech Debt up to current Development 2026-09-04 14:42:37 -04:00
mschill 1e0e3a7114 Merge pull request 'B2026-074 Fixed issue where PROMS would hang when opening multiple saved Word section tabs. Also, we now save and restore to the step location of saved procedure editor sections.' (#812) from B2026-074_restore_proc_tabs into Development
Looks good. Ready for QA.
2026-09-04 10:47:44 -04:00
jjenko 7333247b52 B2026-074 Fixed issue where PROMS would hang when opening multiple saved Word section tabs. Also, we now save and restore to the step location of saved procedure editor sections. 2026-09-04 10:44:35 -04:00
jjenko e16b3262d9 Merge pull request 'C2026-041-invisible-position-changes-as-differences' (#807) from C2026-041-invisible-position-changes-as-differences into Development
good for QA
2026-09-03 08:56:31 -04:00
plarsen edc5bc611b C2026-041-invisible-position-changes-as-differences 2026-09-02 16:27:59 -04:00
plarsen c32121c4c4 C2026-041-invisible-position-changes-as-differences 2026-09-02 15:48:26 -04:00
plarsen 213b8d18f7 C2026-041-invisible-position-changes-as-differences 2026-09-02 14:47:09 -04:00
plarsen 8e7be9723e Merge branch 'Development' into C2026-041-invisible-position-changes-as-differences 2026-09-02 08:03:22 -04:00
plarsen 61394a8b26 Merge branch 'Development' of https://git.volian.com/Volian/SourceCode into Development 2026-09-02 08:01:43 -04:00
plarsen 1cb397f47b C2026-041-invisible-position-changes-as-differences 2026-09-02 08:01:06 -04:00
plarsen 0137ccc5b3 C2026-041-invisible-position-changes-as-differences 2026-08-26 09:42:46 -04:00
plarsen 21c4936ee8 C2026-041-invisible-position-changes-as-differences 2026-08-24 13:47:02 -04:00
plarsen df2311dbda C2026-041-invisible-position-changes-as-differences 2026-08-24 10:51:54 -04:00
plarsen 034aa67e31 C2026-041-invisible-position-changes-as-differences 2026-08-18 17:37:12 -04:00
plarsen f8ab3c57be C2026-041-invisible-position-changes-as-differences 2026-08-18 13:33:10 -04:00
plarsen 6376d4669b C2026-041-invisible-position-changes-as-differences 2026-08-18 13:22:29 -04:00
plarsen f9cce608d6 Merge branch 'Development' of https://git.volian.com/Volian/SourceCode into Development 2026-08-17 18:41:57 -04:00
plarsen 3d65b7c34a Development 2026-08-17 18:40:16 -04:00
258 changed files with 13700 additions and 38717 deletions

No files matched your search

+14
View File
@@ -30,6 +30,7 @@
{ {
this.components = new System.ComponentModel.Container(); this.components = new System.ComponentModel.Container();
this.panel1 = new System.Windows.Forms.Panel(); this.panel1 = new System.Windows.Forms.Panel();
this.cbUseTruncatedData = new System.Windows.Forms.CheckBox();
this.btnUC = new System.Windows.Forms.Button(); this.btnUC = new System.Windows.Forms.Button();
this.cbCaseSensitive = new System.Windows.Forms.CheckBox(); this.cbCaseSensitive = new System.Windows.Forms.CheckBox();
this.cbFile2 = new System.Windows.Forms.ComboBox(); this.cbFile2 = new System.Windows.Forms.ComboBox();
@@ -72,6 +73,7 @@
// //
this.panel1.Controls.Add(this.btnUC); this.panel1.Controls.Add(this.btnUC);
this.panel1.Controls.Add(this.cbCaseSensitive); this.panel1.Controls.Add(this.cbCaseSensitive);
this.panel1.Controls.Add(this.cbUseTruncatedData);
this.panel1.Controls.Add(this.cbFile2); this.panel1.Controls.Add(this.cbFile2);
this.panel1.Controls.Add(this.cbFile1); this.panel1.Controls.Add(this.cbFile1);
this.panel1.Controls.Add(this.tbSearch); this.panel1.Controls.Add(this.tbSearch);
@@ -87,6 +89,17 @@
this.panel1.Size = new System.Drawing.Size(707, 80); this.panel1.Size = new System.Drawing.Size(707, 80);
this.panel1.TabIndex = 0; this.panel1.TabIndex = 0;
// //
// cbUseTruncatedData // C2026-041
//
this.cbUseTruncatedData.AutoSize = true;
this.cbUseTruncatedData.Location = new System.Drawing.Point(456, 56);
this.cbUseTruncatedData.Name = "cbUseTruncatedData";
this.cbUseTruncatedData.Size = new System.Drawing.Size(123, 17);
this.cbUseTruncatedData.TabIndex = 11;
this.cbUseTruncatedData.Text = "Use Truncated Data";
this.tt.SetToolTip(this.cbUseTruncatedData, "Set the Search to be Case Sensitive\r\nUppercase and Lowercase will not match");
this.cbUseTruncatedData.UseVisualStyleBackColor = true;
//
// btnUC // btnUC
// //
this.btnUC.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.btnUC.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
@@ -381,6 +394,7 @@
private System.Windows.Forms.ComboBox cbFile2; private System.Windows.Forms.ComboBox cbFile2;
private System.Windows.Forms.ComboBox cbFile1; private System.Windows.Forms.ComboBox cbFile1;
private System.Windows.Forms.CheckBox cbCaseSensitive; private System.Windows.Forms.CheckBox cbCaseSensitive;
private System.Windows.Forms.CheckBox cbUseTruncatedData;
private System.Windows.Forms.Button btnUC; private System.Windows.Forms.Button btnUC;
private System.Windows.Forms.ToolTip tt; private System.Windows.Forms.ToolTip tt;
} }
+69 -43
View File
@@ -43,15 +43,15 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Data; using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO; using System.IO;
using System.Text.RegularExpressions; using System.Linq;
using System.Xml.Serialization;
using System.Xml.Schema;
using System.Xml;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
namespace Baseline namespace Baseline
{ {
@@ -67,11 +67,11 @@ namespace Baseline
StartsWith, StartsWith,
EndsWith, EndsWith,
Regex Regex
} }
public partial class frmBaseline : Form public partial class frmBaseline : Form
{ {
public IgnoreLines MyIgnore { get; set; } = new IgnoreLines(); public IgnoreLines MyIgnore { get; set; } = new IgnoreLines();
private LastWas myLast = LastWas.Search; private LastWas myLast = LastWas.Search;
private Settings MySettings; private Settings MySettings;
public string MyStatus public string MyStatus
{ {
@@ -141,13 +141,13 @@ namespace Baseline
this.Location = Properties.Settings.Default.Location; this.Location = Properties.Settings.Default.Location;
this.Size = Properties.Settings.Default.Size; this.Size = Properties.Settings.Default.Size;
this.WindowState = Properties.Settings.Default.WidnowState; this.WindowState = Properties.Settings.Default.WidnowState;
if(Properties.Settings.Default.Ignore != null && Properties.Settings.Default.Ignore != "") if (Properties.Settings.Default.Ignore != null && Properties.Settings.Default.Ignore != "")
MyIgnore = IgnoreLines.Get(Properties.Settings.Default.Ignore); MyIgnore = IgnoreLines.Get(Properties.Settings.Default.Ignore);
MySettings = new Settings MySettings = new Settings
{ {
IgnoreLines = new BindingList<string>() IgnoreLines = new BindingList<string>()
}; };
splitContainer1.SplitterDistance = Properties.Settings.Default.Split1; splitContainer1.SplitterDistance = Properties.Settings.Default.Split1;
splitContainer2.SplitterDistance = Properties.Settings.Default.Split2; splitContainer2.SplitterDistance = Properties.Settings.Default.Split2;
splitContainer3.SplitterDistance = Properties.Settings.Default.Split3; splitContainer3.SplitterDistance = Properties.Settings.Default.Split3;
if (Properties.Settings.Default.MRU1 != null && Properties.Settings.Default.MRU1.Count > 0) if (Properties.Settings.Default.MRU1 != null && Properties.Settings.Default.MRU1.Count > 0)
@@ -218,7 +218,7 @@ namespace Baseline
lbResults2.Items.Clear(); lbResults2.Items.Clear();
MyStatus = "Searching..."; MyStatus = "Searching...";
// Perform DebugPagination Comparison // Perform DebugPagination Comparison
FindFiles fnd = new FindFiles(cbFile1.Text, cbFile2.Text, "DebugPagination.txt",MyIgnore); FindFiles fnd = new FindFiles(cbFile1.Text, cbFile2.Text, "DebugPagination.txt",MyIgnore, cbUseTruncatedData.Checked);
lbDifferent.DataSource = fnd; lbDifferent.DataSource = fnd;
lbDifferent.DisplayMember = "File1"; lbDifferent.DisplayMember = "File1";
MyStatus = string.Format("{0} Differences Found", fnd.Count); MyStatus = string.Format("{0} Differences Found", fnd.Count);
@@ -708,8 +708,9 @@ namespace Baseline
lbResults1.Items.Clear(); lbResults1.Items.Clear();
lbResults2.Items.Clear(); lbResults2.Items.Clear();
MyStatus = "Searching..."; MyStatus = "Searching...";
// Perform code to find DebugMeta files with diffences
FindFiles fnd = new FindFiles(cbFile1.Text, cbFile2.Text, "DebugMeta.txt",MyIgnore); FindFiles fnd = new FindFiles(cbFile1.Text, cbFile2.Text, "DebugMeta.txt", MyIgnore, cbUseTruncatedData.Checked);
lbDifferent.DataSource = fnd; lbDifferent.DataSource = fnd;
lbDifferent.DisplayMember = "File1"; lbDifferent.DisplayMember = "File1";
MyStatus = string.Format("{0} Differences Found", fnd.Count); MyStatus = string.Format("{0} Differences Found", fnd.Count);
@@ -732,7 +733,7 @@ namespace Baseline
lbResults2.Items.Clear(); lbResults2.Items.Clear();
MyStatus = "Searching..."; MyStatus = "Searching...";
//Perform Search //Perform Search
FindFiles fnd = new FindFiles(cbFile1.Text, cbFile2.Text, "DebugMeta.txt", tbSearch.Text, SearchType.Contains, cbCaseSensitive.Checked); FindFiles fnd = new FindFiles(cbFile1.Text, cbFile2.Text, "DebugMeta.txt", tbSearch.Text, SearchType.Contains, cbCaseSensitive.Checked, cbUseTruncatedData.Checked);
lbDifferent.DataSource = fnd; lbDifferent.DataSource = fnd;
lbDifferent.DisplayMember = "File1"; lbDifferent.DisplayMember = "File1";
MyStatus = string.Format("{0} Differences Found", fnd.Count); MyStatus = string.Format("{0} Differences Found", fnd.Count);
@@ -814,6 +815,7 @@ namespace Baseline
CompareOneFile(ff.File1, ff.File2); CompareOneFile(ff.File1, ff.File2);
} }
} }
} }
public enum SearchType public enum SearchType
{ {
@@ -838,20 +840,22 @@ namespace Baseline
public partial class FindFiles : List<FindFile> public partial class FindFiles : List<FindFile>
{ {
private readonly string _FileName; private readonly string _FileName;
public string FileName => _FileName;
/// <summary> public string FileName => _FileName;
/// Build list of DocVersion Folders with differences
/// </summary> /// <summary>
/// <param name="path1">Base path</param> /// Build list of DocVersion Folders with differences
/// <param name="path2">Compare path</param> /// </summary>
/// <param name="fileName">filename</param> /// <param name="path1">Base path</param>
/// <param name="myIgnore">Ignore list</param> /// <param name="path2">Compare path</param>
public FindFiles(string path1, string path2, string fileName,IgnoreLines myIgnore) /// <param name="fileName">filename</param>
/// <param name="myIgnore">Ignore list</param>
public FindFiles(string path1, string path2, string fileName,IgnoreLines myIgnore, bool TruncatedDataFg)
{ {
DirectoryInfo di1 = new DirectoryInfo(path1); DirectoryInfo di1 = new DirectoryInfo(path1);
DirectoryInfo di2 = new DirectoryInfo(path2); DirectoryInfo di2 = new DirectoryInfo(path2);
_FileName = fileName; _FileName = fileName;
FillByCompare(di1, di2, fileName, myIgnore); FillByCompare(di1, di2, fileName, myIgnore, TruncatedDataFg);
} }
/// <summary> /// <summary>
/// Fill for a search /// Fill for a search
@@ -862,12 +866,12 @@ namespace Baseline
/// <param name="searchText"></param> /// <param name="searchText"></param>
/// <param name="searchType"></param> /// <param name="searchType"></param>
/// <param name="caseSensitive"></param> /// <param name="caseSensitive"></param>
public FindFiles(string path1, string path2, string fileName, string searchText, SearchType searchType, bool caseSensitive) public FindFiles(string path1, string path2, string fileName, string searchText, SearchType searchType, bool caseSensitive, bool useTruncatedData)
{ {
DirectoryInfo di1 = new DirectoryInfo(path1); DirectoryInfo di1 = new DirectoryInfo(path1);
DirectoryInfo di2 = new DirectoryInfo(path2); DirectoryInfo di2 = new DirectoryInfo(path2);
_FileName = fileName; _FileName = fileName;
FillByCompare(di1, di2, fileName,searchText,searchType, caseSensitive); FillByCompare(di1, di2, fileName,searchText,searchType, caseSensitive, useTruncatedData);
} }
/// <summary> /// <summary>
/// Fill results by search /// Fill results by search
@@ -878,13 +882,13 @@ namespace Baseline
/// <param name="searchText"></param> /// <param name="searchText"></param>
/// <param name="searchType"></param> /// <param name="searchType"></param>
/// <param name="caseSensitive"></param> /// <param name="caseSensitive"></param>
private void FillByCompare(DirectoryInfo di1, DirectoryInfo di2, string fileName, string searchText, SearchType searchType, bool caseSensitive) private void FillByCompare(DirectoryInfo di1, DirectoryInfo di2, string fileName, string searchText, SearchType searchType, bool caseSensitive, bool UseTruncatedData)
{ {
foreach (DirectoryInfo diChild1 in di1.GetDirectories()) foreach (DirectoryInfo diChild1 in di1.GetDirectories())
{ {
DirectoryInfo diChild2 = new DirectoryInfo(di2.FullName + "\\" + diChild1.Name); DirectoryInfo diChild2 = new DirectoryInfo(di2.FullName + "\\" + diChild1.Name);
if (diChild2.Exists) if (diChild2.Exists)
FillByCompare(diChild1, diChild2, fileName,searchText,searchType,caseSensitive); FillByCompare(diChild1, diChild2, fileName,searchText,searchType,caseSensitive, UseTruncatedData);
} }
foreach (FileInfo fiChild1 in di1.GetFiles(fileName)) foreach (FileInfo fiChild1 in di1.GetFiles(fileName))
{ {
@@ -958,27 +962,49 @@ namespace Baseline
} }
return false; return false;
} }
private void FillByCompare(DirectoryInfo di1, DirectoryInfo di2, string fileName, IgnoreLines myIgnore) private void FillByCompare(DirectoryInfo di1, DirectoryInfo di2, string fileName, IgnoreLines myIgnore, bool isTruncatedChecked = false)
{ {
foreach (DirectoryInfo diChild1 in di1.GetDirectories()) foreach (DirectoryInfo diChild1 in di1.GetDirectories())
{ {
DirectoryInfo diChild2 = new DirectoryInfo(di2.FullName + "\\" + diChild1.Name); DirectoryInfo diChild2 = new DirectoryInfo(Path.Combine(di2.FullName, diChild1.Name));
if (diChild2.Exists) if (diChild2.Exists)
FillByCompare(diChild1, diChild2, fileName,myIgnore);// Recursively work on Sub-Folders FillByCompare(diChild1, diChild2, fileName,myIgnore, isTruncatedChecked);// Recursively work on Sub-Folders
} }
foreach (FileInfo fiChild1 in di1.GetFiles(fileName)) foreach (FileInfo fiChild1 in di1.GetFiles(fileName))
{ {
FileInfo fiChild2 = new FileInfo(di2.FullName + "\\" + fiChild1.Name); FileInfo fiChild2 = new FileInfo(Path.Combine(di2.FullName, fiChild1.Name));
if (fiChild2.Exists) FileInfo fiChild1_truncated = new FileInfo(fiChild1.FullName.Replace(".txt", "_Truncated.txt"));
FileInfo fiChild2_truncated = new FileInfo(fiChild2.FullName.Replace(".txt", "_Truncated.txt"));
//truncate checked and both files exist
if (isTruncatedChecked && fiChild1_truncated.Exists && fiChild2_truncated.Exists)
{ {
if (CompareFile(fiChild1, fiChild2,myIgnore)) if (CompareFile(fiChild1_truncated, fiChild2_truncated, myIgnore))
Add(new FindFile(fiChild1.FullName, fiChild2.FullName));// Process Each File Add(new FindFile(fiChild1_truncated.FullName, fiChild2_truncated.FullName));
}
//truncate checked and only file 1 truncate files exist
else if (isTruncatedChecked && fiChild1_truncated.Exists && fiChild2.Exists)
{
if (CompareFile(fiChild1_truncated, fiChild2, myIgnore))
Add(new FindFile(fiChild1_truncated.FullName, fiChild2.FullName));
}
//truncate checked and only file 2 truncate files exist
else if (isTruncatedChecked && fiChild2_truncated.Exists)
{
if (CompareFile(fiChild1, fiChild2_truncated, myIgnore))
Add(new FindFile(fiChild1.FullName, fiChild2_truncated.FullName));
}
//truncated not checked or truncate files dont exist
else if (fiChild2.Exists)
{
if (CompareFile(fiChild1, fiChild2, myIgnore))
Add(new FindFile(fiChild1.FullName, fiChild2.FullName));
} }
} }
} }
private bool CompareFile(FileInfo fiChild1, FileInfo fiChild2,IgnoreLines myIgnore) private bool CompareFile(FileInfo fiChild1, FileInfo fiChild2,IgnoreLines myIgnore)
{ {
if (fiChild1.Name == "DebugMeta.txt") if (fiChild1.Name == "DebugMeta.txt" || fiChild1.Name == "DebugMeta_Truncated.txt")
{ {
IEnumerable<string> lines1 = ReadFilteredLines(fiChild1.FullName, false, myIgnore);//LINQ Read lines without ignored lines IEnumerable<string> lines1 = ReadFilteredLines(fiChild1.FullName, false, myIgnore);//LINQ Read lines without ignored lines
IEnumerable<string> lines2 = ReadFilteredLines(fiChild2.FullName, false, myIgnore);//LINQ Read lines without ignored lines IEnumerable<string> lines2 = ReadFilteredLines(fiChild2.FullName, false, myIgnore);//LINQ Read lines without ignored lines
-3
View File
@@ -120,9 +120,6 @@
<metadata name="tt.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"> <metadata name="tt.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>306, 17</value> <value>306, 17</value>
</metadata> </metadata>
<metadata name="tt.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>306, 17</value>
</metadata>
<metadata name="fbd.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"> <metadata name="fbd.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value> <value>17, 17</value>
</metadata> </metadata>
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -127,12 +127,13 @@ namespace ROEditor
private string origPrefix; private string origPrefix;
private string origValue; private string origValue;
private int dbtype; private int dbtype;
private bool IsNewGroup = false;
/// <summary> /// <summary>
/// Required designer variable. /// Required designer variable.
/// </summary> /// </summary>
private System.ComponentModel.Container components = null; private System.ComponentModel.Container components = null;
public GroupDefFrm(VlnXmlElement pelem, RODB rodb, string gpname,int idbtype) public GroupDefFrm(VlnXmlElement pelem, RODB rodb, string gpname,int idbtype, bool newgrp = false)
{ {
myrodb = rodb; myrodb = rodb;
elem = pelem; elem = pelem;
@@ -143,7 +144,8 @@ namespace ROEditor
// //
InitializeComponent(); InitializeComponent();
FillInData(); FillInData();
} IsNewGroup = newgrp;
}
private string CvtUserFldToFld(string fldname) private string CvtUserFldToFld(string fldname)
{ {
@@ -655,11 +657,22 @@ namespace ROEditor
tmpn.FirstChild.Value = tmpstr2; //tmpn.FirstChild.Value.Replace(CvtUserFldToFld(origGroup), this.tbGroup.Text); tmpn.FirstChild.Value = tmpstr2; //tmpn.FirstChild.Value.Replace(CvtUserFldToFld(origGroup), this.tbGroup.Text);
modified=true; modified=true;
} }
if ((elem.HasAttribute("AccPageIDPrefix")&&this.tbPrefix.Text != origPrefix) || this.tbPrefix.Modified==true) if ((elem.HasAttribute("AccPageIDPrefix")&&(tbPrefix.Text != origPrefix || IsNewGroup)) || tbPrefix.Modified)
{ {
elem.SetAttribute("AccPageIDPrefix",this.tbPrefix.Text); elem.SetAttribute("AccPageIDPrefix",this.tbPrefix.Text);
modified=true; modified=true;
} IsNewGroup = false;
if (myrodb.IsDuplicateAccPagePrefix(elem, tbPrefix.Text))
{
tbPrefix.Text = origPrefix;
elem.SetAttribute("AccPageIDPrefix", origPrefix);
modified = false;
MessageBox.Show($"The Prefix field used for the \"Accessory Pages Access\" values should be unique. The fields used in these values can be found under \"Properties\" of an RO Group. If these are not unique, you may have trouble utilizing these ROs within Word Sections in PROMS. Cannot save.", "Problem saving data");
DialogResult = DialogResult.Cancel;
return;
}
}
bool success=true; bool success=true;
if (modified==true) success = myrodb.RODB_WriteRO(elem); if (modified==true) success = myrodb.RODB_WriteRO(elem);
if (modified == true && success == true && modaccpageid==true) if (modified == true && success == true && modaccpageid==true)
@@ -44,9 +44,7 @@
*********************************************************************************************/ *********************************************************************************************/
using System; using System;
using System.Drawing;
using System.Collections; using System.Collections;
using System.ComponentModel;
using System.Windows.Forms; using System.Windows.Forms;
using System.Xml; using System.Xml;
using System.Text; using System.Text;
@@ -282,148 +280,176 @@ namespace ROEditor
} }
private void btnContinue_Click(object sender, System.EventArgs e) private void btnContinue_Click(object sender, System.EventArgs e)
{ {
bool success; bool success;
if (this.tbGroup.Text == null || this.tbGroup.Text == "") if (this.tbGroup.Text == null || this.tbGroup.Text == "")
{ {
MessageBox.Show("Need to specify group name."); MessageBox.Show("Need to specify group name.");
return; return;
} }
// if this was already saved, i.e. user hit continue button already, // if this was already saved, i.e. user hit continue button already,
// just return; // just return;
if (this.tbGroup.Text == lastSavedGroup) if (this.tbGroup.Text == lastSavedGroup)
{ {
this.Close(); this.Close();
return; return;
} }
lastSavedGroup = this.tbGroup.Text; lastSavedGroup = this.tbGroup.Text;
int dbtype=-1; int dbtype = -1;
if (this.rbbtnGraphics.Checked == true) dbtype = 1; if (this.rbbtnGraphics.Checked == true) dbtype = 1;
else if (this.rbbtnSetpoint.Checked == true) dbtype = 2; else if (this.rbbtnSetpoint.Checked == true) dbtype = 2;
else if (this.rbbtnUserDef.Checked == true) dbtype = 3; else if (this.rbbtnUserDef.Checked == true) dbtype = 3;
if (dbtype<0) if (dbtype < 0)
{ {
MessageBox.Show("Need to define type of group."); MessageBox.Show("Need to define type of group.");
return; return;
} }
Cursor.Current = Cursors.WaitCursor; Cursor.Current = Cursors.WaitCursor;
// make a new table with the next table name id // make a new table with the next table name id
tbname = myrodb.RODB_GetNextGroupTable(); tbname = myrodb.RODB_GetNextGroupTable();
if (tbname == null) if (tbname == null)
{ {
Cursor.Current = Cursors.Default; Cursor.Current = Cursors.Default;
return; return;
} }
toprecid = myrodb.RODB_AddNewTable(tbname, this.tbGroup.Text); toprecid = myrodb.RODB_AddNewTable(tbname, this.tbGroup.Text);
if (toprecid == null) if (toprecid == null)
{ {
Cursor.Current = Cursors.Default; Cursor.Current = Cursors.Default;
return; return;
} }
// for the given type, copy over the required fields. // for the given type, copy over the required fields.
success = myrodb.RODB_CopyFieldDefs("ROMaster",tbname,dbtype); success = myrodb.RODB_CopyFieldDefs("ROMaster", tbname, dbtype);
if (success == false) if (success == false)
{ {
Cursor.Current = Cursors.Default; Cursor.Current = Cursors.Default;
return; return;
} }
// create top level group node with input name. // create top level group node with input name.
nelem = (VlnXmlElement) elem.OwnerDocument.CreateElement("vlnGroup"); nelem = (VlnXmlElement)elem.OwnerDocument.CreateElement("vlnGroup");
nelem.InnerText = CvtUserFldToFld(this.tbGroup.Text); nelem.InnerText = CvtUserFldToFld(this.tbGroup.Text);
nelem.SetAttribute("Table",tbname); nelem.SetAttribute("Table", tbname);
nelem.SetAttribute("ParentID", "00000000"); nelem.SetAttribute("ParentID", "00000000");
string nrecid = myrodb.RODB_GetNextRecId(tbname); string nrecid = myrodb.RODB_GetNextRecId(tbname);
nelem.SetAttribute("RecID", nrecid); nelem.SetAttribute("RecID", nrecid);
elem.AppendChild((XmlNode) nelem); elem.AppendChild((XmlNode)nelem);
success = myrodb.RODB_InsertGroup(nelem); success = myrodb.RODB_InsertGroup(nelem);
Cursor.Current = Cursors.Default; Cursor.Current = Cursors.Default;
if (success == false) return; if (success == false) return;
nelem.SetAttribute("TreeNotData", "True"); nelem.SetAttribute("TreeNotData", "True");
nelem.SetAttribute("MenuTitle", this.tbGroup.Text); nelem.SetAttribute("MenuTitle", this.tbGroup.Text);
nelem.SetAttribute("MasterRecID",toprecid); nelem.SetAttribute("MasterRecID", toprecid);
nelem.SetAttribute("HasChild", "False"); nelem.SetAttribute("HasChild", "False");
// if this is a setpoint db or image db, get fields and find those fields needed // if this is a setpoint db or image db, get fields and find those fields needed
// to define ro & group. This is hardcoded, yuk. // to define ro & group. This is hardcoded, yuk.
if(dbtype == 1 || dbtype == 2) if (dbtype == 1 || dbtype == 2)
{ {
ArrayList FieldList = myrodb.RODB_GetFields(nelem, (uint) RecordType.Schema); ArrayList FieldList = myrodb.RODB_GetFields(nelem, (uint)RecordType.Schema);
string[] fldlist=null, grplist=null; string[] fldlist = null, grplist = null;
ROField rof; ROField rof;
string curfld; string curfld;
StringBuilder Inuse = new StringBuilder(); StringBuilder Inuse = new StringBuilder();
// Get list of inuse fields for the rro. // Get list of inuse fields for the rro.
if (dbtype == 1) if (dbtype == 1)
fldlist = new string[] {"Name", "Image ID", "Image"}; fldlist = new string[] { "Name", "Image ID", "Image" };
else else
fldlist = new string[] {"Setpoint ID", "Setpoint Value", "Associated System Component", "Applicability", "Revision", "Short Description", fldlist = new string[] {"Setpoint ID", "Setpoint Value", "Associated System Component", "Applicability", "Revision", "Short Description",
"Description", "Key Assumptions", "Basis", "References"}; "Description", "Key Assumptions", "Basis", "References"};
for (int i=0; i< fldlist.Length; i++) for (int i = 0; i < fldlist.Length; i++)
{ {
curfld = fldlist[i]; curfld = fldlist[i];
for (int j=0; j<FieldList.Count; j++) for (int j = 0; j < FieldList.Count; j++)
{ {
rof = (ROField) FieldList[j]; rof = (ROField)FieldList[j];
if (rof.GetFieldname == curfld) if (rof.GetFieldname == curfld)
{ {
if (i==fldlist.Length-1) // last one don't add ' ' if (i == fldlist.Length - 1) // last one don't add ' '
Inuse.Append(rof.GetRecID); Inuse.Append(rof.GetRecID);
else else
Inuse.Append(rof.GetRecID+" "); Inuse.Append(rof.GetRecID + " ");
break; break;
} }
} }
} }
nelem.SetAttribute("FieldsInUse", Inuse.ToString()); nelem.SetAttribute("FieldsInUse", Inuse.ToString());
// Get list of group inuse fields. // Get list of group inuse fields.
Inuse.Remove(0,Inuse.Length); Inuse.Remove(0, Inuse.Length);
if (dbtype == 1) if (dbtype == 1)
grplist = new string[] {"Group"}; grplist = new string[] { "Group" };
else else
grplist = new string[] {"Parameter"}; grplist = new string[] { "Parameter" };
for (int i=0; i< grplist.Length; i++) for (int i = 0; i < grplist.Length; i++)
{ {
curfld = grplist[i]; curfld = grplist[i];
for (int j=0; j<FieldList.Count; j++) for (int j = 0; j < FieldList.Count; j++)
{ {
rof = (ROField) FieldList[j]; rof = (ROField)FieldList[j];
if (rof.GetFieldname == curfld) if (rof.GetFieldname == curfld)
{ {
if (i == grplist.Length-1) // last, don't add ' ' if (i == grplist.Length - 1) // last, don't add ' '
Inuse.Append(rof.GetRecID); Inuse.Append(rof.GetRecID);
else else
Inuse.Append(rof.GetRecID+" "); Inuse.Append(rof.GetRecID + " ");
break; break;
} }
} }
} }
nelem.SetAttribute("GroupFieldsInUse", Inuse.ToString()); nelem.SetAttribute("GroupFieldsInUse", Inuse.ToString());
if (dbtype == 2) // Setpoint string defaultPfix = "UD";
{ if (dbtype == 2) // Setpoint
nelem.SetAttribute("RetVal","<Setpoint__Value>"); {
nelem.SetAttribute("MenuItem","<Setpoint__Value,5,17> <Short__Description>"); nelem.SetAttribute("RetVal", "<Setpoint__Value>");
nelem.SetAttribute("GroupMenuItem","<Parameter>"); nelem.SetAttribute("MenuItem", "<Setpoint__Value,5,17> <Short__Description>");
nelem.SetAttribute("AccPageIDPrefix","SP2"); nelem.SetAttribute("GroupMenuItem", "<Parameter>");
nelem.SetAttribute("AccPageID","<Setpoint__ID>"); defaultPfix = "SP";
} nelem.SetAttribute("AccPageIDPrefix", "SP2");
else if (dbtype == 1) // image nelem.SetAttribute("AccPageID", "<Setpoint__ID>");
{ }
nelem.SetAttribute("RetVal","<Image>"); else if (dbtype == 1) // image
nelem.SetAttribute("MenuItem","<Name>"); {
nelem.SetAttribute("GroupMenuItem","<Group>"); nelem.SetAttribute("RetVal", "<Image>");
nelem.SetAttribute("AccPageIDPrefix","IG2"); nelem.SetAttribute("MenuItem", "<Name>");
nelem.SetAttribute("AccPageID","<Image__ID>"); nelem.SetAttribute("GroupMenuItem", "<Group>");
} defaultPfix = "IG";
success = myrodb.RODB_WriteRO(nelem); nelem.SetAttribute("AccPageIDPrefix", "IG2");
if (success == false) return; nelem.SetAttribute("AccPageID", "<Image__ID>");
} }
//B2026-091 RO Editor - Change Default Prefix to take existing prefixes into account for Setpoint/Graphics DBs
//if duplicate prefix - then change it so it will be unique
int x = 2;
while (nelem.HasAttribute("AccPageIDPrefix") && myrodb.IsDuplicateAccPagePrefix(nelem, nelem.GetAttribute("AccPageIDPrefix")))
{
nelem.SetAttribute("AccPageIDPrefix", $"{defaultPfix}{x}");
x++;
}
success = myrodb.RODB_WriteRO(nelem);
if (success == false) return;
}
// now let the user specify the group name, etc to define the group. // now let the user specify the group name, etc to define the group.
GroupDefFrm grdef = new GroupDefFrm(nelem,myrodb,nelem.InnerText,dbtype); DialogResult dlgrslt = DialogResult.OK;
grdef.ShowDialog(); using (GroupDefFrm grdef = new GroupDefFrm(nelem, myrodb, nelem.InnerText, dbtype, true))
} {
private void txtBox_KeyDown(object sender, KeyEventArgs e) dlgrslt = grdef.ShowDialog();
}
//If New Group and prefix would not be unique, remove the group
//needed because groups get autoadded with defaults
//before user has a chance to enter things like Acc Page Prefix
if (dlgrslt == DialogResult.Cancel)
{
XmlNode pn = nelem.ParentNode;
XmlNode nd = (XmlNode)nelem;
myrodb.RODB_DeleteGroup(nd, null, null);
pn.RemoveChild(nelem);
DialogResult = DialogResult.Cancel;
Close();
}
}
private void txtBox_KeyDown(object sender, KeyEventArgs e)
{ {
if (Clipboard.GetDataObject().GetDataPresent(DataFormats.Text)) if (Clipboard.GetDataObject().GetDataPresent(DataFormats.Text))
{ {
@@ -336,7 +336,8 @@ namespace RODBInterface
public abstract bool RODB_GetGroupAndSubgroups(VlnXmlElement node, StringBuilder sb); public abstract bool RODB_GetGroupAndSubgroups(VlnXmlElement node, StringBuilder sb);
public abstract bool RODB_GetChildData(VlnXmlElement node, bool CheckChildCount); public abstract bool RODB_GetChildData(VlnXmlElement node, bool CheckChildCount);
public abstract bool IsDuplicateAccPageID(VlnXmlElement ro, string newacc); public abstract bool IsDuplicateAccPageID(VlnXmlElement ro, string newacc);
public abstract VlnXmlElement RODB_ReadRO(string tbl, string recid); public abstract bool IsDuplicateAccPagePrefix(VlnXmlElement ro, string pfix);
public abstract VlnXmlElement RODB_ReadRO(string tbl, string recid);
public abstract bool RODB_WriteRO(VlnXmlElement ro, bool movedRO = false); public abstract bool RODB_WriteRO(VlnXmlElement ro, bool movedRO = false);
public abstract bool RODB_InsertRO(VlnXmlElement ro); public abstract bool RODB_InsertRO(VlnXmlElement ro);
public abstract ushort RODB_GetFieldType(VlnXmlElement elem, string TableName, string Fld); public abstract ushort RODB_GetFieldType(VlnXmlElement elem, string TableName, string Fld);
@@ -2026,23 +2027,23 @@ namespace RODBInterface
return true; return true;
} }
public override bool IsDuplicateAccPageID(VlnXmlElement ro, string newacc) public override bool IsDuplicateAccPageID(VlnXmlElement ro, string newacc)
{ {
string strcheck, inacc = null; string strcheck, inacc = null;
bool isdup = false; bool isdup = false;
int indx = newacc.IndexOf("'"); int indx = newacc.IndexOf("'");
if (indx >= 0) if (indx >= 0)
inacc = newacc.Insert(indx, "'"); inacc = newacc.Insert(indx, "'");
else else
inacc = newacc; inacc = newacc;
strcheck = "SELECT Count(RecID) AS CNT FROM " + ro.GetAttribute("Table") + " WHERE AccPageID = '" + inacc + "'"; strcheck = "SELECT Count(RecID) AS CNT FROM " + ro.GetAttribute("Table") + " WHERE AccPageID = '" + inacc + "'";
if (ro.HasAttribute("RecID")) // new ro's don't have recid defined yet before this test. if (ro.HasAttribute("RecID")) // new ro's don't have recid defined yet before this test.
strcheck = strcheck + " AND (NOT RecID = '" + ro.GetAttribute("RecID") + "')"; strcheck = strcheck + " AND (NOT RecID = '" + ro.GetAttribute("RecID") + "')";
try try
{ {
DBE.Command(strcheck); DBE.Command(strcheck);
DBE.Reader(); DBE.Reader();
} }
catch (Exception e) catch (Exception e)
{ {
@@ -2062,7 +2063,71 @@ namespace RODBInterface
return isdup; return isdup;
} }
public override VlnXmlElement RODB_ReadRO(string tbl, string recid) //C2026-058 Check all Tables for if Acc Page Id Prefix is Used More than Once
public override bool IsDuplicateAccPagePrefix(VlnXmlElement ro, string pfix)
{
// Loop through and build sql
StringBuilder strGetData = new StringBuilder();
List<string> all_tables = RODB_GetAllTables();
if (all_tables.Count == 0) return false;
foreach (string table in all_tables)
{
//if not the first item, add a union all
if (strGetData.Length > 0)
{ strGetData.Append(" UNION ALL "); }
//All info's containing AccPageIDPrefix should be RecType 3 (Group)
//Note if you use LIKE or ALIKE
// WHERE Info ALIKE '%AccPageIDPrefix%'"
// WHERE Info LIKE '*AccPageIDPrefix*'
//Then it truncates Info only pulling back the 1st 255 characters
strGetData.Append($"SELECT Info, '{table}' AS TBL FROM {table} WHERE RecType = 3");
}
try
{
DBE.Command(strGetData.ToString());
DBE.Reader();
}
catch (Exception e)
{
MessageBox.Show(e.Message, "Error getting Acc Page ID Prefix Data");
return true;
}
while (DBE.Read())
{
string Info = DBE.GetString(0);
string tbl = DBE.GetString(1);
using (XmlTextReader rdr = new XmlTextReader(Info, XmlNodeType.Element, null))
{
VlnXmlElement retele = null;
try
{
XmlNode nd = ROXml.ReadNode(rdr);
retele = (VlnXmlElement)nd;
}
catch
{
//do nothing not a valid item to check
}
if (retele != null && tbl != ro.GetAttribute("Table") && retele.GetAttribute("AccPageIDPrefix").ToLower() == pfix.ToLower())
{
DBE.CommandDispose();
DBE.ReaderClose();
return true; //another table contains the prefix - return true
}
}
}
DBE.CommandDispose();
DBE.ReaderClose();
return false;
}
public override VlnXmlElement RODB_ReadRO(string tbl, string recid)
{ {
ShowCount.ReadRo++; ShowCount.ReadRo++;
VlnXmlElement retele = null; VlnXmlElement retele = null;
@@ -3104,6 +3169,33 @@ namespace RODBInterface
} }
} }
} }
//C2026-058 Check all Tables for if Acc Page Id Prefix is Used More than Once
//Get all Tables in the MS Access DB
public List<string> RODB_GetAllTables()
{
List<string> tables = new List<string>();
using (System.Data.OleDb.OleDbConnection connection = new System.Data.OleDb.OleDbConnection(strDatabaseConnectionCommand))
{
connection.Open();
using (System.Data.OleDb.OleDbCommand command = connection.CreateCommand())
{
using (DataTable schema = connection.GetSchema("Tables"))
{
foreach (DataRow row in schema.Rows)
{
if (row["TABLE_TYPE"].ToString() == "TABLE")
{
tables.Add(row["TABLE_NAME"].ToString());
}
}
}
}
}
return tables;
}
} }
} }
@@ -50,7 +50,7 @@ namespace RODBInterface
SqlConnection cn = new SqlConnection(SqlConnectionStr); SqlConnection cn = new SqlConnection(SqlConnectionStr);
try try
{ {
cn.Open(); if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
if (OnlyConnectOnce && ROAPP_SqlConnectionOnce == null) ROAPP_SqlConnectionOnce = cn; if (OnlyConnectOnce && ROAPP_SqlConnectionOnce == null) ROAPP_SqlConnectionOnce = cn;
return cn; return cn;
} }
@@ -1357,13 +1357,13 @@ namespace RODBInterface
{ {
command.CommandText = "getCountRecidByAccidNotRecid"; command.CommandText = "getCountRecidByAccidNotRecid";
command.Parameters.AddWithValue("RecID", ro.GetAttribute("RecID")); command.Parameters.AddWithValue("RecID", ro.GetAttribute("RecID"));
} }
else else
command.CommandText = "getCountRecidByAccid"; command.CommandText = "getCountRecidByAccid";
command.Parameters.AddWithValue("@AccPageID", inacc); command.Parameters.AddWithValue("@AccPageID", inacc);
command.Parameters.AddWithValue("@ROTable", ro.GetAttribute("Table")); command.Parameters.AddWithValue("@ROTable", ro.GetAttribute("Table"));
using (SqlDataReader reader = command.ExecuteReader()) using (SqlDataReader reader = command.ExecuteReader())
{ {
if (reader.Read()) if (reader.Read())
{ {
@@ -1383,7 +1383,38 @@ namespace RODBInterface
} }
return isdup; return isdup;
} }
public override VlnXmlElement RODB_ReadRO(string tbl, string recid) public override bool IsDuplicateAccPagePrefix(VlnXmlElement ro, string pfix)
{
try
{
using (SqlConnection cn = ROAPP_SqlConnection)
{
SqlCommand command = new SqlCommand();
command.Connection = cn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "checkAccPagePrefixUsed";
command.Parameters.AddWithValue("@Prefix", pfix);
command.Parameters.AddWithValue("@ROTable", ro.GetAttribute("Table"));
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.Read())
{
int cnt = reader.GetInt32(0);
if (cnt > 0)
return true;
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error on IsDuplicateAccPagePrefix");
return true;
}
return false;
}
public override VlnXmlElement RODB_ReadRO(string tbl, string recid)
{ {
ShowCount.ReadRo++; ShowCount.ReadRo++;
VlnXmlElement retele = null; VlnXmlElement retele = null;
@@ -1220,6 +1220,11 @@ namespace ctlXMLEditLib
mytextbox.Enter += new System.EventHandler(this.txtBox_Enter); mytextbox.Enter += new System.EventHandler(this.txtBox_Enter);
mytextbox.Leave += new System.EventHandler(this.txtBox_Leave); mytextbox.Leave += new System.EventHandler(this.txtBox_Leave);
} }
else
{
//B2026-085 Disable Symbols when leave a TextBox
mytextbox.Leave += txtBox_Leave_DisableSymbols;
}
string labelAnnot; string labelAnnot;
bool imgchld = false; bool imgchld = false;
@@ -1311,7 +1316,12 @@ namespace ctlXMLEditLib
tb.Text = dfTxt; tb.Text = dfTxt;
tb.ForeColor = SystemColors.GrayText; tb.ForeColor = SystemColors.GrayText;
} }
}
txtBox_Leave_DisableSymbols(sender, e);
}
//B2026-085 Disable Symbols when leave a TextBox
private void txtBox_Leave_DisableSymbols(object sender, EventArgs e) => OnEnableDisableSymbolsBtn(new ctlXMLEditEventArgs(DisplaySymBolBtn:false));
// C2021-026 Event handler for Parent/Child child textbox // C2021-026 Event handler for Parent/Child child textbox
// If the textbox is set to gray, then we are using the parent value // If the textbox is set to gray, then we are using the parent value
+158 -2
View File
@@ -25035,6 +25035,162 @@ IF (@@Error = 0) PRINT 'Trigger Alteration: tr_Contents_Delete Succeeded'
ELSE PRINT 'Trigger Alteration: tr_Contents_Delete Error on Creation' ELSE PRINT 'Trigger Alteration: tr_Contents_Delete Error on Creation'
GO GO
/****** Object: View [dbo].[vwDupAccIDs] ***********************/
If Exists(SELECT * FROM sys.objects Where name = 'vwDupAccIDs' AND type in (N'V'))
DROP VIEW [dbo].[vwDupAccIDs]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
==========================================================================================================
Author: Matthew Schill
Create Date: 10/7/2026
Description: View for Duplicate Accessory Page IDs in ROs in PROMS
Usage: Select * FROM dbo.vwDupAccIDs Order by RofstID, AccPageID, GroupTitle
==========================================================================================================
*/
CREATE View [dbo].[vwDupAccIDs]
AS
SELECT rochild.AccPageID, NUMAccPageIDs,
AccPageIDPrefix = dbiAP, GroupTitle = dbiTitle,
title, value, roid, rochild.RofstID
FROM
vwRofstData_RofstChildren rochild
INNER JOIN
(SELECT ROFstID = Max(ROFstID)
FROM ROFsts
Group by RODbID) latestfsts
ON latestfsts.ROFstID = rochild.RofstID
INNER JOIN
(SELECT NUMAccPageIDs=COunt(*), RoFstID, AccPageID FROM
vwRofstData_RofstChildren
WHERE AccPageID IS NOT NULL
Group by RoFstID, AccPageID
Having Count(*) > 1
) dupAcc
ON latestfsts.ROFstID = dupAcc.RofstID
AND dupAcc.AccPageID = rochild.AccPageID
go
IF (@@Error = 0) PRINT 'View [vwDupAccIDs] Succeeded'
ELSE PRINT 'View [vwDupAccIDs] Error on Creation'
go
/****** Object: StoredProcedure [getDupAccIDs] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getDupAccIDs]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE [getDupAccIDs];
GO
/*
==========================================================================================================
Author: Matthew Schill
Create Date: 10/7/2026
Description: Procedure for Duplicate Accessory Page IDs in ROs in PROMS
==========================================================================================================
*/
CREATE PROCEDURE [dbo].[getDupAccIDs]
AS
BEGIN
Select * FROM dbo.vwDupAccIDs Order by RofstID, AccPageID, GroupTitle
RETURN
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getDupAccIDs Succeeded'
ELSE PRINT 'Procedure Creation: getDupAccIDs Error on Creation'
GO
/****** Object: StoredProcedure [getDupAccPrefixes] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getDupAccPrefixes]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE [getDupAccPrefixes];
GO
/*
==========================================================================================================
Author: Matthew Schill
Create Date: 10/7/2026
Description: Procedure for Duplicate Accessory Page Prefixes in ROs in PROMS
==========================================================================================================
*/
CREATE PROCEDURE [dbo].[getDupAccPrefixes]
AS
BEGIN
SELECT AccPageIDPrefix = dbiAP, GroupTitle = dbiTitle
FROM
RofstDatabase
INNER JOIN
(SELECT ROFstID = Max(ROFstID)
FROM ROFsts
Group by RODbID) latestfsts
ON latestfsts.ROFstID = RofstDatabase.RofstID
INNER JOIN
(SELECT RoFstID, APPrefix = dbiAP FROM
RofstDatabase
Group by RoFstID, dbiAP
Having Count(*) > 1
) dupAcc
ON latestfsts.ROFstID = dupAcc.RofstID AND APPrefix = dbiAP
Order by dbiAP, dbiTitle
RETURN
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getDupAccPrefixes Succeeded'
ELSE PRINT 'Procedure Creation: getDupAccPrefixes Error on Creation'
GO
/****** Object: StoredProcedure [getDocsDupAccIDs] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[getDocsDupAccIDs]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE [getDocsDupAccIDs];
GO
/*
==========================================================================================================
Author: Matthew Schill
Create Date: 10/7/2026
Description: Get PROMS Documents containing Duplicate Accessory Page IDs
==========================================================================================================
*/
CREATE PROCEDURE [dbo].[getDocsDupAccIDs]
AS
BEGIN
Select Path = CASE WHEN VN.ParentName = VN.GrandParentName THEN ''
ELSE VN.GrandParentName + '->' END +
VN.ParentName + '->' + VN.FolderName + '->' + Pth.Path + '`' + Text,
AccPageID, DupAcc.roid, Contents.ContentID
FROM dbo.vwDupAccIDs DupAcc
INNER JOIN DROUsages with (NoLock) ON LEFT(DROUsages.ROID,12) = LEFT(DupAcc.roid,12)
INNER JOIN Entries with (NoLock) on DROUsages.DocID = Entries.DocID
INNER JOIN Contents with (NoLock) on Contents.ContentID = Entries.ContentID
INNER JOIN Items with (NoLock) on Contents.ContentID = Items.ContentID
INNER JOIN vefn_getversionItems('') vi on Contents.contentID = vi.contentID
INNER JOIN VEFN_GetVersionNames() VN ON vi.VersionID = VN.VersionID
OUTER APPLY
(Select Path = REPLACE(dbo.ve_GetPath(Items.ItemID), '\u8209?', '-')) Pth
Order by GrandParentName, ParentName, FolderName, Path, Text, AccPageID
RETURN
END
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getDocsDupAccIDs Succeeded'
ELSE PRINT 'Procedure Creation: getDocsDupAccIDs Error on Creation'
GO
/* /*
--------------------------------------------------------------------------- ---------------------------------------------------------------------------
| ADD New Code Before this Block | | ADD New Code Before this Block |
@@ -25068,8 +25224,8 @@ BEGIN TRY -- Try Block
DECLARE @RevDate varchar(255) DECLARE @RevDate varchar(255)
DECLARE @RevDescription varchar(255) DECLARE @RevDescription varchar(255)
set @RevDate = '07/16/2026 8:30 AM' set @RevDate = '10/7/2026 9:30 AM'
set @RevDescription = 'Reworked ve_GetParentItem for Performance improvement' set @RevDescription = 'Added Reports for Duplicate Acc Page IDs in ROs'
Select cast(@RevDate as datetime) RevDate, @RevDescription RevDescription Select cast(@RevDate as datetime) RevDate, @RevDescription RevDescription
PRINT 'SQL Code Revision ' + @RevDate + ' - ' + @RevDescription PRINT 'SQL Code Revision ' + @RevDate + ' - ' + @RevDescription
+31 -1
View File
@@ -263,7 +263,7 @@ WITH EXECUTE AS OWNER
AS AS
SELECT COUNT (RecID) SELECT COUNT (RecID)
FROM [ROALL] FROM [ROALL]
WHERE [ROTable]=@ROTable AND AccPageID=@AccPageID WHERE [ROTable]=@ROTable AND AccPageID=@AccPageID
GO GO
-- Display the status of Proc creation -- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: getCountRecidByAccid Succeeded' IF (@@Error = 0) PRINT 'Procedure Creation: getCountRecidByAccid Succeeded'
@@ -827,4 +827,34 @@ IF (@@Error = 0) PRINT 'Table Creation: ROALL Succeeded'
ELSE PRINT 'Table Creation: DeleteLog ROALL on Creation' ELSE PRINT 'Table Creation: DeleteLog ROALL on Creation'
GO GO
/****** Object: StoredProcedure [dbo].[checkAccPagePrefixUsed] ******/
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[checkAccPagePrefixUsed]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE [checkAccPagePrefixUsed];
GO
/*****************************************************************************
Volian Enterprises - Proprietary Information - DO NOT COPY OR DISTRIBUTE
Copyright 2026 - Volian Enterprises, Inc. All rights reserved.
*****************************************************************************/
CREATE PROCEDURE [dbo].[checkAccPagePrefixUsed]
(
@Prefix char(32),
@ROTable char(8)
)
WITH EXECUTE AS OWNER
AS
SELECT COUNT(*)
FROM
(
SELECT ROTable, cast(info as xml) xinfo
FROM [ROALL]
WHERE Info LIKE '%AccPageIDPrefix%' AND ROTable <> @ROTable
) TBL
cross apply
xinfo.nodes('vlnGroup') t1(r1)
WHERE r1.value('@AccPageIDPrefix','varchar(max)') = @Prefix
GO
-- Display the status of Proc creation
IF (@@Error = 0) PRINT 'Procedure Creation: checkAccPagePrefixUsed Succeeded'
ELSE PRINT 'Procedure Creation: checkAccPagePrefixUsed Error on Creation'
GO
@@ -380,6 +380,7 @@
</EmbeddedResource> </EmbeddedResource>
<EmbeddedResource Include="frmGenTools.resx"> <EmbeddedResource Include="frmGenTools.resx">
<DependentUpon>frmGenTools.cs</DependentUpon> <DependentUpon>frmGenTools.cs</DependentUpon>
<SubType>Designer</SubType>
</EmbeddedResource> </EmbeddedResource>
<EmbeddedResource Include="frmPDFStatusForm.resx"> <EmbeddedResource Include="frmPDFStatusForm.resx">
<DependentUpon>frmPDFStatusForm.cs</DependentUpon> <DependentUpon>frmPDFStatusForm.cs</DependentUpon>
+10 -9
View File
@@ -1,4 +1,5 @@
namespace VEPROMS namespace VEPROMS
{ {
partial class dlgCheckOpenTabs partial class dlgCheckOpenTabs
@@ -42,12 +43,12 @@ namespace VEPROMS
// //
this.labelX1.BackgroundStyle.CornerType = DevComponents.DotNetBar.eCornerType.Square; this.labelX1.BackgroundStyle.CornerType = DevComponents.DotNetBar.eCornerType.Square;
this.labelX1.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.labelX1.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.labelX1.Location = new System.Drawing.Point(23, 2); this.labelX1.Location = new System.Drawing.Point(23, 5);
this.labelX1.Name = "labelX1"; this.labelX1.Name = "labelX1";
this.labelX1.Size = new System.Drawing.Size(363, 78); this.labelX1.Size = new System.Drawing.Size(363, 90);
this.labelX1.TabIndex = 0; this.labelX1.TabIndex = 0;
this.labelX1.Text = "Would you like for PROMS to reopen the tabs that you had open during your last se" + this.labelX1.Text = "Would you like for PROMS to reopen the tabs that you had open during your last se" +
"ssion?"; "ssion?" + System.Environment.NewLine + System.Environment.NewLine + "NOTE: This will not apply to Word section tabs that were previously open.";
this.labelX1.WordWrap = true; this.labelX1.WordWrap = true;
// //
// cbRemember // cbRemember
@@ -56,20 +57,20 @@ namespace VEPROMS
// //
// //
this.cbRemember.BackgroundStyle.CornerType = DevComponents.DotNetBar.eCornerType.Square; this.cbRemember.BackgroundStyle.CornerType = DevComponents.DotNetBar.eCornerType.Square;
this.cbRemember.Location = new System.Drawing.Point(23, 75); this.cbRemember.Location = new System.Drawing.Point(23, 100);
this.cbRemember.Name = "cbRemember"; this.cbRemember.Name = "cbRemember";
this.cbRemember.Size = new System.Drawing.Size(376, 47); this.cbRemember.Size = new System.Drawing.Size(376, 55);
this.cbRemember.Style = DevComponents.DotNetBar.eDotNetBarStyle.StyleManagerControlled; this.cbRemember.Style = DevComponents.DotNetBar.eDotNetBarStyle.StyleManagerControlled;
this.cbRemember.TabIndex = 1; this.cbRemember.TabIndex = 1;
this.cbRemember.Text = "Check this box to not be prompted in the future when opening PROMS. \nNote that th" + this.cbRemember.Text = "Check this box to not be prompted in the future when opening PROMS. \nNote that th" +
"ese settings can be adjusted at any time from the \nOPTIONS menu for PROMS."; "ese settings can be adjusted at any time from the \nOPTIONS menu for PROMS.";
// //
// btnOpenTabs // btnOpenTabs
// //
this.btnOpenTabs.AccessibleRole = System.Windows.Forms.AccessibleRole.PushButton; this.btnOpenTabs.AccessibleRole = System.Windows.Forms.AccessibleRole.PushButton;
this.btnOpenTabs.ColorTable = DevComponents.DotNetBar.eButtonColor.OrangeWithBackground; this.btnOpenTabs.ColorTable = DevComponents.DotNetBar.eButtonColor.OrangeWithBackground;
this.btnOpenTabs.DialogResult = System.Windows.Forms.DialogResult.Yes; this.btnOpenTabs.DialogResult = System.Windows.Forms.DialogResult.Yes;
this.btnOpenTabs.Location = new System.Drawing.Point(23, 139); this.btnOpenTabs.Location = new System.Drawing.Point(23, 165);
this.btnOpenTabs.Name = "btnOpenTabs"; this.btnOpenTabs.Name = "btnOpenTabs";
this.btnOpenTabs.Size = new System.Drawing.Size(150, 42); this.btnOpenTabs.Size = new System.Drawing.Size(150, 42);
this.btnOpenTabs.Style = DevComponents.DotNetBar.eDotNetBarStyle.StyleManagerControlled; this.btnOpenTabs.Style = DevComponents.DotNetBar.eDotNetBarStyle.StyleManagerControlled;
@@ -82,7 +83,7 @@ namespace VEPROMS
this.btnNoTabs.AccessibleRole = System.Windows.Forms.AccessibleRole.PushButton; this.btnNoTabs.AccessibleRole = System.Windows.Forms.AccessibleRole.PushButton;
this.btnNoTabs.ColorTable = DevComponents.DotNetBar.eButtonColor.OrangeWithBackground; this.btnNoTabs.ColorTable = DevComponents.DotNetBar.eButtonColor.OrangeWithBackground;
this.btnNoTabs.DialogResult = System.Windows.Forms.DialogResult.No; this.btnNoTabs.DialogResult = System.Windows.Forms.DialogResult.No;
this.btnNoTabs.Location = new System.Drawing.Point(216, 139); this.btnNoTabs.Location = new System.Drawing.Point(216, 165);
this.btnNoTabs.Name = "btnNoTabs"; this.btnNoTabs.Name = "btnNoTabs";
this.btnNoTabs.Size = new System.Drawing.Size(150, 42); this.btnNoTabs.Size = new System.Drawing.Size(150, 42);
this.btnNoTabs.Style = DevComponents.DotNetBar.eDotNetBarStyle.StyleManagerControlled; this.btnNoTabs.Style = DevComponents.DotNetBar.eDotNetBarStyle.StyleManagerControlled;
@@ -94,7 +95,7 @@ namespace VEPROMS
// //
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(411, 193); this.ClientSize = new System.Drawing.Size(411, 220);
this.ControlBox = false; this.ControlBox = false;
this.Controls.Add(this.btnNoTabs); this.Controls.Add(this.btnNoTabs);
this.Controls.Add(this.btnOpenTabs); this.Controls.Add(this.btnOpenTabs);
@@ -163,7 +163,7 @@ namespace VEPROMS
} }
if (MyFolder != null) if (MyFolder != null)
{ {
sfd.FileName = string.Format("{0}-{1}.expx", Database.ActiveDatabase, MyFolder.Name); sfd.FileName = string.Format("{0}-{1}.expx", Database.ActiveDatabase, MyFolder.Name.Replace("/", "_").Replace("\\", "_"));
if (sfd.ShowDialog(this) == DialogResult.OK && sfd.FileName != string.Empty) if (sfd.ShowDialog(this) == DialogResult.OK && sfd.FileName != string.Empty)
{ {
txtExport.Text = sfd.FileName; txtExport.Text = sfd.FileName;
+227 -56
View File
@@ -441,69 +441,240 @@ namespace VEPROMS
txtResults.Clear(); txtResults.Clear();
txtResults.AppendText("Generating User Access Control Report"); txtResults.AppendText("Generating User Access Control Report");
using (DataTable dt = UserReports.GetUserAccessControlData()) //Get data and Create excel file from it
{ Create_ExcelFile(UserReports.GetUserAccessControlData(), "UAC Report", filename);
// Start Excel and get Application object.
xls.Application excel = new xls.Application
{
// Make Excel invisible and disable alerts.
Visible = false,
DisplayAlerts = false
};
// Create a new Workbook. DateTime pEnd = DateTime.Now;
xls.Workbook excelworkBook = excel.Workbooks.Add();
// Create a Worksheet.
var workSheet = (xls.Worksheet)excelworkBook.ActiveSheet;
workSheet.Name = "UAC Report";
// column headings
for (var i = 0; i < dt.Columns.Count; i++)
{
workSheet.Cells[1, i + 1] = dt.Columns[i].ColumnName;
}
// rows
for (var i = 0; i < dt.Rows.Count; i++)
{
for (var j = 0; j < dt.Columns.Count; j++)
{
workSheet.Cells[i + 2, j + 1] = dt.Rows[i][j];
}
}
//resize the columns to match the data
workSheet.Columns.AutoFit();
//freeze the top row, and highlight those cells
workSheet.Application.ActiveWindow.SplitRow = 1;
workSheet.Application.ActiveWindow.FreezePanes = true;
workSheet.Cells.Range[workSheet.Cells[1, 1], workSheet.Cells[1, dt.Columns.Count]].Interior.Color = xls.XlRgbColor.rgbLightBlue;
//save the excel file
excelworkBook.SaveAs(filename);
excelworkBook.Close();
excel.Quit();
//release any in use com objects
releaseObject(workSheet);
releaseObject(excelworkBook);
releaseObject(excel);
}
DateTime pEnd = DateTime.Now;
txtProcess.AppendText($"Completed: {pEnd:MM/dd/yyyy @ HH:mm}"); txtProcess.AppendText($"Completed: {pEnd:MM/dd/yyyy @ HH:mm}");
Application.DoEvents(); Application.DoEvents();
Cursor = Cursors.Default; Cursor = Cursors.Default;
MessageBox.Show("Generate User Access Control Report Completed", "User Access Control Report"); MessageBox.Show("Generate User Access Control Report Completed", "User Access Control Report");
} }
//C2025-009 Report for tracking PROMS Users / security #region Duplicate Accessory Page IDs
//for releasing any Excel com objects still in memory
private void releaseObject(object obj) //C2026-058 Report for tracking Duplicate Accessory Page IDs in ROs in PROMS
//hold the filename for cases when scheduled for later
private string DupAccIDsfilename;
private void btnDupAccIDs_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(DupAccIDsfilename))
{
SaveFileDialog sfd = new SaveFileDialog
{
Filter = "Excel XLS (*.xlsx)|*.xlsx",
FileName = "DupAccIDsReport.xlsx"
};
if (sfd.ShowDialog() == DialogResult.OK)
{
DupAccIDsfilename = sfd.FileName;
}
}
if (!CheckProcessLater()) return; // delay processing if set//B2017-221 Allow the batch dialog to close when waiting to process.
txtProcess.Clear();
txtResults.Clear();
if (!string.IsNullOrEmpty(DupAccIDsfilename))
{
Generate_DupAccIDs_Report(DupAccIDsfilename);
}
DupAccIDsfilename = null;
}
private void Generate_DupAccIDs_Report(string filename)
{
Cursor = Cursors.WaitCursor;
DateTime pStart = DateTime.Now;
txtProcess.AppendText("Generate Duplicate Accessory Page IDs Report in PROMS");
txtProcess.AppendText(Environment.NewLine);
txtProcess.AppendText($"Started: {pStart:MM/dd/yyyy @ HH:mm}");
txtProcess.AppendText(Environment.NewLine);
Application.DoEvents();
txtResults.Clear();
txtResults.AppendText("Generating Duplicate Accessory Page IDs Report");
//Get data and Create excel file from it
Create_ExcelFile(UserReports.GetDupAccIDsData(), "Dup Acc IDs", filename);
DateTime pEnd = DateTime.Now;
txtProcess.AppendText($"Completed: {pEnd:MM/dd/yyyy @ HH:mm}");
Application.DoEvents();
Cursor = Cursors.Default;
MessageBox.Show("Generate Duplicate Accessory Page IDs Report Completed", "Duplicate Accessory Page IDs Report");
}
//C2026-058 Report for tracking Duplicate Accessory Page Prefixes in ROs in PROMS
//hold the filename for cases when scheduled for later
private string DupAccPrefixesfilename;
private void btnDupAccPrefixes_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(DupAccPrefixesfilename))
{
SaveFileDialog sfd = new SaveFileDialog
{
Filter = "Excel XLS (*.xlsx)|*.xlsx",
FileName = "DupAccPrefixesReport.xlsx"
};
if (sfd.ShowDialog() == DialogResult.OK)
{
DupAccPrefixesfilename = sfd.FileName;
}
}
if (!CheckProcessLater()) return; // delay processing if set//B2017-221 Allow the batch dialog to close when waiting to process.
txtProcess.Clear();
txtResults.Clear();
if (!string.IsNullOrEmpty(DupAccPrefixesfilename))
{
Generate_DupAccPrefixes_Report(DupAccPrefixesfilename);
}
DupAccPrefixesfilename = null;
}
private void Generate_DupAccPrefixes_Report(string filename)
{
Cursor = Cursors.WaitCursor;
DateTime pStart = DateTime.Now;
txtProcess.AppendText("Generate Duplicate Accessory Page Prefixes Report in PROMS");
txtProcess.AppendText(Environment.NewLine);
txtProcess.AppendText($"Started: {pStart:MM/dd/yyyy @ HH:mm}");
txtProcess.AppendText(Environment.NewLine);
Application.DoEvents();
txtResults.Clear();
txtResults.AppendText("Generating Duplicate Accessory Page Prefixes Report");
//Get data and Create excel file from it
Create_ExcelFile(UserReports.GetDupAccPrefixesData(), "Dup Acc Prefixes", filename);
DateTime pEnd = DateTime.Now;
txtProcess.AppendText($"Completed: {pEnd:MM/dd/yyyy @ HH:mm}");
Application.DoEvents();
Cursor = Cursors.Default;
MessageBox.Show("Generate Duplicate Accessory Page Prefixes Report Completed", "Duplicate Accessory Page Prefixes Report");
}
//C2026-058 Report for tracking Word Sections/Documents containing Duplicate Accessory Page IDs
//hold the filename for cases when scheduled for later
private string WordDocsDupAccIDsfilename;
private void btnWordDocsDupAccIDs_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(WordDocsDupAccIDsfilename))
{
SaveFileDialog sfd = new SaveFileDialog
{
Filter = "Excel XLS (*.xlsx)|*.xlsx",
FileName = "WordDocsDupAccIDsReport.xlsx"
};
if (sfd.ShowDialog() == DialogResult.OK)
{
WordDocsDupAccIDsfilename = sfd.FileName;
}
}
if (!CheckProcessLater()) return; // delay processing if set//B2017-221 Allow the batch dialog to close when waiting to process.
txtProcess.Clear();
txtResults.Clear();
if (!string.IsNullOrEmpty(WordDocsDupAccIDsfilename))
{
Generate_WordDocsDupAccIDs_Report(WordDocsDupAccIDsfilename);
}
WordDocsDupAccIDsfilename = null;
}
private void Generate_WordDocsDupAccIDs_Report(string filename)
{
Cursor = Cursors.WaitCursor;
DateTime pStart = DateTime.Now;
txtProcess.AppendText("Generate Word Sections Containing Duplicate Accessory Page IDs Report in PROMS");
txtProcess.AppendText(Environment.NewLine);
txtProcess.AppendText($"Started: {pStart:MM/dd/yyyy @ HH:mm}");
txtProcess.AppendText(Environment.NewLine);
Application.DoEvents();
txtResults.Clear();
txtResults.AppendText("Generating Word Sections Containing Duplicate Accessory Page IDs Report");
//Get data and Create excel file from it
Create_ExcelFile(UserReports.GetDocsDupAccIDsData(), "Word Dup AccIDs", filename);
DateTime pEnd = DateTime.Now;
txtProcess.AppendText($"Completed: {pEnd:MM/dd/yyyy @ HH:mm}");
Application.DoEvents();
Cursor = Cursors.Default;
MessageBox.Show("Generate Word Sections Containing Duplicate Accessory Page IDs Report Completed", "Word Sections Containing Duplicate Accessory Page IDs Report");
}
#endregion
//C2026-058 Check all Tables for if Acc Page Id Prefix is Used More than Once
//Create an excel file made up of data table dt,
//with worksheet named (name) and file name (filename)
private void Create_ExcelFile(DataTable dt, string name, string filename)
{
// Start Excel and get Application object.
xls.Application excel = new xls.Application
{
// Make Excel invisible and disable alerts.
Visible = false,
DisplayAlerts = false
};
// Create a new Workbook.
xls.Workbook excelworkBook = excel.Workbooks.Add();
// Create a Worksheet.
var workSheet = (xls.Worksheet)excelworkBook.ActiveSheet;
workSheet.Name = name;
// column headings
for (var i = 0; i < dt.Columns.Count; i++)
{
workSheet.Cells[1, i + 1] = dt.Columns[i].ColumnName;
}
// rows
for (var i = 0; i < dt.Rows.Count; i++)
{
for (var j = 0; j < dt.Columns.Count; j++)
{
workSheet.Cells[i + 2, j + 1] = dt.Rows[i][j];
}
}
//resize the columns to match the data
workSheet.Columns.AutoFit();
//freeze the top row, and highlight those cells
workSheet.Application.ActiveWindow.SplitRow = 1;
workSheet.Application.ActiveWindow.FreezePanes = true;
workSheet.Cells.Range[workSheet.Cells[1, 1], workSheet.Cells[1, dt.Columns.Count]].Interior.Color = xls.XlRgbColor.rgbLightBlue;
//save the excel file
excelworkBook.SaveAs(filename);
excelworkBook.Close();
excel.Quit();
//release any in use com objects
releaseObject(workSheet);
releaseObject(excelworkBook);
releaseObject(excel);
}
//C2025-009 Report for tracking PROMS Users / security
//for releasing any Excel com objects still in memory
private void releaseObject(object obj)
{ {
try try
{ {
+77 -13
View File
@@ -52,6 +52,9 @@
this.panelEx1 = new DevComponents.DotNetBar.PanelEx(); this.panelEx1 = new DevComponents.DotNetBar.PanelEx();
this.sideNav1 = new DevComponents.DotNetBar.Controls.SideNav(); this.sideNav1 = new DevComponents.DotNetBar.Controls.SideNav();
this.sideNavPanel6 = new DevComponents.DotNetBar.Controls.SideNavPanel(); this.sideNavPanel6 = new DevComponents.DotNetBar.Controls.SideNavPanel();
this.btnWrdDupAcc = new DevComponents.DotNetBar.ButtonX();
this.line2 = new DevComponents.DotNetBar.Controls.Line();
this.btnUAC = new DevComponents.DotNetBar.ButtonX();
this.sideNavPanel5 = new DevComponents.DotNetBar.Controls.SideNavPanel(); this.sideNavPanel5 = new DevComponents.DotNetBar.Controls.SideNavPanel();
this.btn_ShowUsers = new DevComponents.DotNetBar.ButtonX(); this.btn_ShowUsers = new DevComponents.DotNetBar.ButtonX();
this.sideNavPanel1 = new DevComponents.DotNetBar.Controls.SideNavPanel(); this.sideNavPanel1 = new DevComponents.DotNetBar.Controls.SideNavPanel();
@@ -80,7 +83,8 @@
this.lblAdmToolProgressType = new DevComponents.DotNetBar.LabelX(); this.lblAdmToolProgressType = new DevComponents.DotNetBar.LabelX();
this.buttonItem1 = new DevComponents.DotNetBar.ButtonItem(); this.buttonItem1 = new DevComponents.DotNetBar.ButtonItem();
this.superTooltip1 = new DevComponents.DotNetBar.SuperTooltip(); this.superTooltip1 = new DevComponents.DotNetBar.SuperTooltip();
this.btnUAC = new DevComponents.DotNetBar.ButtonX(); this.btnDupAccPrefix = new DevComponents.DotNetBar.ButtonX();
this.btnDupAccIDs = new DevComponents.DotNetBar.ButtonX();
((System.ComponentModel.ISupportInitialize)(this.splitContainer3)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.splitContainer3)).BeginInit();
this.splitContainer3.Panel1.SuspendLayout(); this.splitContainer3.Panel1.SuspendLayout();
this.splitContainer3.Panel2.SuspendLayout(); this.splitContainer3.Panel2.SuspendLayout();
@@ -442,6 +446,10 @@
// //
// sideNavPanel6 // sideNavPanel6
// //
this.sideNavPanel6.Controls.Add(this.btnDupAccIDs);
this.sideNavPanel6.Controls.Add(this.btnDupAccPrefix);
this.sideNavPanel6.Controls.Add(this.btnWrdDupAcc);
this.sideNavPanel6.Controls.Add(this.line2);
this.sideNavPanel6.Controls.Add(this.btnUAC); this.sideNavPanel6.Controls.Add(this.btnUAC);
this.sideNavPanel6.Dock = System.Windows.Forms.DockStyle.Fill; this.sideNavPanel6.Dock = System.Windows.Forms.DockStyle.Fill;
this.sideNavPanel6.Location = new System.Drawing.Point(88, 31); this.sideNavPanel6.Location = new System.Drawing.Point(88, 31);
@@ -449,6 +457,44 @@
this.sideNavPanel6.Size = new System.Drawing.Size(292, 493); this.sideNavPanel6.Size = new System.Drawing.Size(292, 493);
this.sideNavPanel6.TabIndex = 14; this.sideNavPanel6.TabIndex = 14;
// //
// btnWrdDupAcc
//
this.btnWrdDupAcc.AccessibleRole = System.Windows.Forms.AccessibleRole.PushButton;
this.btnWrdDupAcc.Checked = true;
this.btnWrdDupAcc.ColorTable = DevComponents.DotNetBar.eButtonColor.OrangeWithBackground;
this.btnWrdDupAcc.Location = new System.Drawing.Point(26, 94);
this.btnWrdDupAcc.Name = "btnWrdDupAcc";
this.btnWrdDupAcc.Size = new System.Drawing.Size(211, 39);
this.btnWrdDupAcc.Style = DevComponents.DotNetBar.eDotNetBarStyle.StyleManagerControlled;
this.superTooltip1.SetSuperTooltip(this.btnWrdDupAcc, new DevComponents.DotNetBar.SuperTooltipInfo("Word Sections Containing Duplicate Accessory Page IDs Report", "", resources.GetString("btnWrdDupAcc.SuperTooltip"), null, null, DevComponents.DotNetBar.eTooltipColor.Gray));
this.btnWrdDupAcc.TabIndex = 31;
this.btnWrdDupAcc.Text = "Run Word Sections Containing Duplicate Accessory Page IDs Report";
this.btnWrdDupAcc.Click += new System.EventHandler(this.btnWordDocsDupAccIDs_Click);
//
// line2
//
this.line2.BackColor = System.Drawing.Color.Transparent;
this.line2.Location = new System.Drawing.Point(5, 71);
this.line2.Name = "line2";
this.line2.Size = new System.Drawing.Size(285, 12);
this.line2.TabIndex = 30;
this.line2.Text = "line2";
//
// btnUAC
//
this.btnUAC.AccessibleRole = System.Windows.Forms.AccessibleRole.PushButton;
this.btnUAC.Checked = true;
this.btnUAC.ColorTable = DevComponents.DotNetBar.eButtonColor.OrangeWithBackground;
this.btnUAC.Location = new System.Drawing.Point(35, 30);
this.btnUAC.Name = "btnUAC";
this.btnUAC.Size = new System.Drawing.Size(187, 23);
this.btnUAC.Style = DevComponents.DotNetBar.eDotNetBarStyle.StyleManagerControlled;
this.superTooltip1.SetSuperTooltip(this.btnUAC, new DevComponents.DotNetBar.SuperTooltipInfo("UAC Report", "", "This will return a report containing info on when users were added to PROMS and w" +
"hen users were added to specific PROMS security groups.", null, null, DevComponents.DotNetBar.eTooltipColor.Gray));
this.btnUAC.TabIndex = 0;
this.btnUAC.Text = "Run User Access Control Report";
this.btnUAC.Click += new System.EventHandler(this.btnUAC_Click);
//
// sideNavPanel5 // sideNavPanel5
// //
this.sideNavPanel5.Controls.Add(this.btn_ShowUsers); this.sideNavPanel5.Controls.Add(this.btn_ShowUsers);
@@ -785,19 +831,33 @@
this.superTooltip1.DefaultTooltipSettings = new DevComponents.DotNetBar.SuperTooltipInfo("", "", "", null, null, DevComponents.DotNetBar.eTooltipColor.Gray); this.superTooltip1.DefaultTooltipSettings = new DevComponents.DotNetBar.SuperTooltipInfo("", "", "", null, null, DevComponents.DotNetBar.eTooltipColor.Gray);
this.superTooltip1.LicenseKey = "F962CEC7-CD8F-4911-A9E9-CAB39962FC1F"; this.superTooltip1.LicenseKey = "F962CEC7-CD8F-4911-A9E9-CAB39962FC1F";
// //
// btnUAC // btnDupAccPrefix
// //
this.btnUAC.AccessibleRole = System.Windows.Forms.AccessibleRole.PushButton; this.btnDupAccPrefix.AccessibleRole = System.Windows.Forms.AccessibleRole.PushButton;
this.btnUAC.Checked = true; this.btnDupAccPrefix.Checked = true;
this.btnUAC.ColorTable = DevComponents.DotNetBar.eButtonColor.OrangeWithBackground; this.btnDupAccPrefix.ColorTable = DevComponents.DotNetBar.eButtonColor.OrangeWithBackground;
this.btnUAC.Location = new System.Drawing.Point(35, 30); this.btnDupAccPrefix.Location = new System.Drawing.Point(26, 156);
this.btnUAC.Name = "btnUAC"; this.btnDupAccPrefix.Name = "btnDupAccPrefix";
this.btnUAC.Size = new System.Drawing.Size(187, 23); this.btnDupAccPrefix.Size = new System.Drawing.Size(211, 39);
this.btnUAC.Style = DevComponents.DotNetBar.eDotNetBarStyle.StyleManagerControlled; this.btnDupAccPrefix.Style = DevComponents.DotNetBar.eDotNetBarStyle.StyleManagerControlled;
this.btnUAC.TabIndex = 0; this.superTooltip1.SetSuperTooltip(this.btnDupAccPrefix, new DevComponents.DotNetBar.SuperTooltipInfo("Word Sections Containing Duplicate Accessory Page IDs Report", "", resources.GetString("btnDupAccPrefix.SuperTooltip"), null, null, DevComponents.DotNetBar.eTooltipColor.Gray));
this.btnUAC.Text = "Run User Access Control Report"; this.btnDupAccPrefix.TabIndex = 32;
this.superTooltip1.SetSuperTooltip(this.btnUAC, new DevComponents.DotNetBar.SuperTooltipInfo("UAC Report", "", "This will return a report containing info on when users were added to PROMS and when users were added to specific PROMS security groups.", null, null, DevComponents.DotNetBar.eTooltipColor.Gray)); this.btnDupAccPrefix.Text = "Run Duplicate Accessory Page Prefixes Report";
this.btnUAC.Click += new System.EventHandler(this.btnUAC_Click); this.btnDupAccPrefix.Click += new System.EventHandler(this.btnDupAccPrefixes_Click);
//
// btnDupAccIDs
//
this.btnDupAccIDs.AccessibleRole = System.Windows.Forms.AccessibleRole.PushButton;
this.btnDupAccIDs.Checked = true;
this.btnDupAccIDs.ColorTable = DevComponents.DotNetBar.eButtonColor.OrangeWithBackground;
this.btnDupAccIDs.Location = new System.Drawing.Point(26, 220);
this.btnDupAccIDs.Name = "btnDupAccIDs";
this.btnDupAccIDs.Size = new System.Drawing.Size(211, 39);
this.btnDupAccIDs.Style = DevComponents.DotNetBar.eDotNetBarStyle.StyleManagerControlled;
this.superTooltip1.SetSuperTooltip(this.btnDupAccIDs, new DevComponents.DotNetBar.SuperTooltipInfo("Word Sections Containing Duplicate Accessory Page IDs Report", "", resources.GetString("btnDupAccIDs.SuperTooltip"), null, null, DevComponents.DotNetBar.eTooltipColor.Gray));
this.btnDupAccIDs.TabIndex = 33;
this.btnDupAccIDs.Text = "Run Duplicate Accessory Page IDs Report";
this.btnDupAccIDs.Click += new System.EventHandler(this.btnDupAccIDs_Click);
// //
// frmGenTools // frmGenTools
// //
@@ -889,6 +949,10 @@
private DevComponents.DotNetBar.Controls.WarningBox warningBox3; private DevComponents.DotNetBar.Controls.WarningBox warningBox3;
private DevComponents.DotNetBar.ButtonItem buttonItem1; private DevComponents.DotNetBar.ButtonItem buttonItem1;
private DevComponents.DotNetBar.ButtonX btnUAC; private DevComponents.DotNetBar.ButtonX btnUAC;
private DevComponents.DotNetBar.ButtonX btnWrdDupAcc;
private DevComponents.DotNetBar.Controls.Line line2;
private DevComponents.DotNetBar.ButtonX btnDupAccIDs;
private DevComponents.DotNetBar.ButtonX btnDupAccPrefix;
} }
} }
+22 -9
View File
@@ -117,10 +117,25 @@
<resheader name="writer"> <resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader> </resheader>
<metadata name="superTooltip1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<assembly alias="System.Drawing" name="System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" /> <assembly alias="System.Drawing" name="System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<data name="superTooltip1.TrayLocation" type="System.Drawing.Point, System.Drawing">
<value>17, 17</value>
</data>
<data name="btnDupAccIDs.SuperTooltip" xml:space="preserve">
<value>If multiple ROs contain the same Accessory Page IDs, then users could inadvertently use the wrong RO in word documents since those print and save by Accessory Page ID).
This will return a report containing info on ROs that have Duplicate Accessory Page IDs. This can be reviewed and used in conjunction with the other Supplicate Accessory Page ID/Prefix Reports to ensure that ROs and RO Groups are properly set up. Common reasons for Duplicate Accessory Page IDs Include: RO Groups unintentionally set up with duplicate prefixes, fields in ROs that Accessory Page Access uses that have the same text but are upper vs lower case, and some duplicates may be RO Groups that were never intended to be used in PROMS (these may be only used as a group heading).</value>
</data>
<data name="btnDupAccPrefix.SuperTooltip" xml:space="preserve">
<value>If multiple ROs contain the same Accessory Page IDs, then users could inadvertently use the wrong RO in word documents since those print and save by Accessory Page ID.
This will return a report containing info on which RO Groups have duplicate Accessory Page Prefixes. This can be run and used to clean up RO Groups so that they have unique Accessory Page Prefixes.</value>
</data>
<data name="btnWrdDupAcc.SuperTooltip" xml:space="preserve">
<value>If multiple ROs contain the same Accessory Page IDs, then users could inadvertently use the wrong RO in word documents since those print and save by Accessory Page ID.
This will return a report containing info on which Word Sections Contain ROs that have Duplicate Accessory Page IDs. This can be run before cleaning up Duplicates and then utilized after to identify which Word Sections may need edited to the newly updated Accessory Page IDs.</value>
</data>
<data name="warningBox3.Image" type="System.Drawing.Bitmap, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64"> <data name="warningBox3.Image" type="System.Drawing.Bitmap, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value> <value>
iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAALGPC/xhBQAAAp5JREFUOE+F iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAALGPC/xhBQAAAp5JREFUOE+F
@@ -138,9 +153,6 @@
ud8AKwnMnBpmYFAAAAAASUVORK5CYII= ud8AKwnMnBpmYFAAAAAASUVORK5CYII=
</value> </value>
</data> </data>
<metadata name="superTooltip1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<data name="swCkObsoleteROData.SuperTooltip" xml:space="preserve"> <data name="swCkObsoleteROData.SuperTooltip" xml:space="preserve">
<value>Referenced Objects databases are associated with a procedure set (such as Working Draft). <value>Referenced Objects databases are associated with a procedure set (such as Working Draft).
@@ -189,7 +201,8 @@ Should an item become orphaned (disconnected) from the rest of the data, it will
This tool may take an extended period of time to execute. This tool may take an extended period of time to execute.
</value> </value>
</data> </data>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <assembly alias="mscorlib" name="mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<value>46</value> <data name="$this.TrayHeight" type="System.Int32, mscorlib">
</metadata> <value>49</value>
</data>
</root> </root>
File diff suppressed because it is too large. Load diff
+167 -177
View File
@@ -66,10 +66,6 @@ namespace VEPROMS
} }
else // Step Tab Panel else // Step Tab Panel
{ {
// The following line was broken into separate lines because a NullReferenceError was occurring.
// Now we should be able to tell what is wrong by which line causes the Null Reference Error
// RHM 20101217
//SelectedDVI = value.MyStepPanel.MyProcedureItemInfo.MyProcedure.ActiveParent as DocVersionInfo;
StepPanel stepPanel = value.MyStepPanel; StepPanel stepPanel = value.MyStepPanel;
ItemInfo itemInfo = stepPanel.MyProcedureItemInfo; ItemInfo itemInfo = stepPanel.MyProcedureItemInfo;
ProcedureInfo procedureInfo = itemInfo.MyProcedure; ProcedureInfo procedureInfo = itemInfo.MyProcedure;
@@ -293,31 +289,7 @@ namespace VEPROMS
// cleanup from previous run: // cleanup from previous run:
TmpFile.RemoveAllTmps(); TmpFile.RemoveAllTmps();
if (VlnSettings.DebugMode) Database.ConnectionName = "VEPROMS_LOCAL";
{
//use local data (for development/debug mode)
if (Environment.MachineName == "RMARK-PC")
Database.ConnectionName = "VEPROMS_RMARK_DEBUG";
else if (Environment.MachineName == "WINDOWS7-RHM")
Database.ConnectionName = "VEPROMS_RMARK_DEBUG";
else if (Environment.UserName.ToUpper() == "BODINE")
Database.ConnectionName = "VEPROMS_BODINE_DEBUG";
else
Database.ConnectionName = "VEPROMS_LOCAL";
}
else
{
// use server data (default)
// - except for the volian laptop and Rich's Demo version where we need to use local data
if (Environment.MachineName == "RMARK-PC")
Database.ConnectionName = "VEPROMS_RMARK_DEMO";
else if (Environment.MachineName == "WINDOWS7-RHM")
Database.ConnectionName = "VEPROMS_RMARK_DEMO";
else if (Environment.UserName.ToUpper() == "BODINE")
Database.ConnectionName = "VEPROMS_BODINE_DEMO";
else
Database.ConnectionName = "VEPROMS_LOCAL";
}
InitializeComponent(); InitializeComponent();
@@ -1539,7 +1511,7 @@ namespace VEPROMS
displayRO.MyROFST = SelectedROFst; displayRO.MyROFST = SelectedROFst;
// B2023-021: force Load of Step Prop/RO panel RO tree by passing in // B2023-021: force Load of Step Prop/RO panel RO tree by passing in
// true to LoadTree // true to LoadTree
if (!_WeAreExitingPROMS) displayRO.LoadTree(true); if (!_WeAreExitingPROMS) displayRO.LoadTree(this,true);
} }
} }
@@ -1757,160 +1729,158 @@ namespace VEPROMS
public bool ClosingWithError = false; // B2019-098: prevent looping between error & exit dialog public bool ClosingWithError = false; // B2019-098: prevent looping between error & exit dialog
private bool _WeAreExitingPROMS = false; // B2019-101 if exiting PROMS from main window don't prompt on each child window (separate windows) private bool _WeAreExitingPROMS = false; // B2019-101 if exiting PROMS from main window don't prompt on each child window (separate windows)
private void frmVEPROMS_FormClosing(object sender, FormClosingEventArgs e) private void frmVEPROMS_FormClosing(object sender, FormClosingEventArgs e)
{ {
// B2017-212 If the user uses the X button in Word to close the word attachment, PROMS thinks that the user wants to close out of PROMS as well // B2017-212 If the user uses the X button in Word to close the word attachment, PROMS thinks that the user wants to close out of PROMS as well
// trap for this and close only the Word tab in PROMS // trap for this and close only the Word tab in PROMS
// B2017-214 added a null reference check // B2017-214 added a null reference check
// B2010-071 Since we cannot tell if the user click on the X in Word or the X in PROMS, ask if the current tab // B2010-071 Since we cannot tell if the user click on the X in Word or the X in PROMS, ask if the current tab
// should be closed or if we should exit PROMS or just Cancel to continue working // should be closed or if we should exit PROMS or just Cancel to continue working
if (tc._MyDisplayTabItems.Count < 1) // If all thabs are closed in the editor will indicate that in the database. if (tc._MyDisplayTabItems.Count < 1) // If all thabs are closed in the editor will indicate that in the database.
{ {
Item.DeactivateStateDisplayTabTmp(MySessionInfo.UserID); Item.DeactivateStateDisplayTabTmp(MySessionInfo.UserID);
} }
if (!_WeAreExitingPROMS && !ClosingWithError && tc.SelectedDisplayTabItem != null && tc._MyDisplayTabItems.Count > 0) if (!_WeAreExitingPROMS && !ClosingWithError && tc.SelectedDisplayTabItem != null && tc._MyDisplayTabItems.Count > 0)
{ {
// B2019-071 dialog to ask user if we are to close one tab or exit // B2019-071 dialog to ask user if we are to close one tab or exit
DlgCloseTabsOrExit dctoe = new DlgCloseTabsOrExit(MyParent == null, PROMSWindowForms.Count > 0); DlgCloseTabsOrExit dctoe = new DlgCloseTabsOrExit(MyParent == null, PROMSWindowForms.Count > 0);
dctoe.ShowDialog(); dctoe.ShowDialog();
// B2019-101 flag that we are exiting from PROMS main window (separate windows) // B2019-101 flag that we are exiting from PROMS main window (separate windows)
_WeAreExitingPROMS = (MyParent == null && dctoe.ExitPROMS); _WeAreExitingPROMS = (MyParent == null && dctoe.ExitPROMS);
if (dctoe.Cancel) // B2019-071 user decided to not close any tab and not exit PROMS - so do nothing and continue working if (dctoe.Cancel) // B2019-071 user decided to not close any tab and not exit PROMS - so do nothing and continue working
{ {
e.Cancel = true; e.Cancel = true;
dctoe.Close(); dctoe.Close();
return; return;
} }
string stk = vlnStackTrace.StackToString(); string stk = vlnStackTrace.StackToString();
if (!stk.Contains("Exception")) if (!stk.Contains("Exception"))
{ {
// B2018-091 Allow PROMS to close if only MSWord sections have been opened. // B2018-091 Allow PROMS to close if only MSWord sections have been opened.
// B2019-071 we will now close one or all of the tabs (even step editor ones) // B2019-071 we will now close one or all of the tabs (even step editor ones)
if (_WeAreExitingPROMS) if (_WeAreExitingPROMS)
{ {
int TabItemID;
int cnt = 0;
// Deactivate previous procedure tab state by user // Deactivate previous procedure tab state by user
Item.DeactivateStateDisplayTabTmp(MySessionInfo.UserID); Item.DeactivateStateDisplayTabTmp(MySessionInfo.UserID);
// Save current procedure tab state // Save current procedure tab state
//B2024-082 Remember Tabs Not opening in correct order
//B2024-082 Remember Tabs Not opening in correct order int cnt = 0;
foreach (DisplayTabItem dti in tc.MyBar.Items) foreach (DisplayTabItem dti in tc.MyBar.Items)
{ {
cnt++; cnt++;
ItemInfo itminfo = dti.MyItemInfo;
string DisplayTabID = dti.MyKey; string DisplayTabID = dti.MyKey;
TabItemID = dti.MyItemInfo.ItemID;
string DisplayTabName = dti.ToString(); string DisplayTabName = dti.ToString();
// B2026-074 if a Word section, save the ItemID of the entire Word section
// else if a Step Editor section, save the ItemID of the step part the user was on
int TabItemID = itminfo.HasWordContent ? itminfo.ItemID : dti.MyStepTabPanel.MyStepTabRibbon.MyEditItem.MyItemInfo.ItemID;
Item.AddDisplayTabsState(TabItemID, DisplayTabID, DisplayTabName, MySessionInfo.UserID, cnt); Item.AddDisplayTabsState(TabItemID, DisplayTabID, DisplayTabName, MySessionInfo.UserID, cnt);
} }
} }
int n = tc._MyDisplayTabItems.Count; int n = tc._MyDisplayTabItems.Count;
while (n-- > 0 && tc._MyDisplayTabItems.Count > 0)
while (n-- > 0 && tc._MyDisplayTabItems.Count > 0) {
{ tc.CloseTabItem(tc.SelectedDisplayTabItem);
// B2019-071 close just the current tab and continue working
tc.CloseTabItem(tc.SelectedDisplayTabItem); if (!dctoe.ExitPROMS)
{
// B2019-071 close just the current tab and continue working
if (!dctoe.ExitPROMS)
{
e.Cancel = true; e.Cancel = true;
dctoe.Close(); dctoe.Close();
return; return;
} }
} }
if (tc.SelectedDisplayTabItem != null && tc._MyDisplayTabItems.Count > 0 && dctoe.ExitPROMS) if (tc.SelectedDisplayTabItem != null && tc._MyDisplayTabItems.Count > 0 && dctoe.ExitPROMS)
{ {
_MyLog.WarnFormat($"Stack Does not contain an Exception\r\nPROMS will Not Exit. Stack : \r\n{stk}"); _MyLog.WarnFormat($"Stack Does not contain an Exception\r\nPROMS will Not Exit. Stack : \r\n{stk}");
e.Cancel = true; // If Display Items still exist don't close. e.Cancel = true; // If Display Items still exist don't close.
} }
dctoe.Close(); dctoe.Close();
} }
} }
//C2015-022 Separate Windows - if child windows are open and we are closing the main PROMS window, give user a chance to not close PROMS and that child windows //C2015-022 Separate Windows - if child windows are open and we are closing the main PROMS window, give user a chance to not close PROMS and that child windows
// B2019-101 if we are exiting from PROMS main window no need to prompt user about child windows. // B2019-101 if we are exiting from PROMS main window no need to prompt user about child windows.
if (MyParent == null && PROMSWindowForms != null && PROMSWindowForms.Count > 0 && !_WeAreExitingPROMS) if (MyParent == null && PROMSWindowForms != null && PROMSWindowForms.Count > 0 && !_WeAreExitingPROMS)
{ {
DialogResult dr = MessageBox.Show("Close all of the child windows and exit PROMS?", "Exit PROMS", MessageBoxButtons.YesNo); DialogResult dr = MessageBox.Show("Close all of the child windows and exit PROMS?", "Exit PROMS", MessageBoxButtons.YesNo);
if (dr == DialogResult.No) if (dr == DialogResult.No)
{ {
e.Cancel = true; e.Cancel = true;
return; return;
} }
} }
// This keeps PROMS from Hanging under certain circumstances // This keeps PROMS from Hanging under certain circumstances
tc.ShuttingDown = true; tc.ShuttingDown = true;
// B2019-161 When shutting down output the timing information (to the error log) // B2019-161 When shutting down output the timing information (to the error log)
if (VolianTimer.TimingsOn) if (VolianTimer.TimingsOn)
VolianTimer.ShowTimers(); VolianTimer.ShowTimers();
foreach (DisplayTabItem dti in tc.MyBar.Items) foreach (DisplayTabItem dti in tc.MyBar.Items)
{ {
if (dti.MyDSOTabPanel != null) if (dti.MyDSOTabPanel != null)
dti.MyDSOTabPanel.CloseDSO(); dti.MyDSOTabPanel.CloseDSO();
else else
MySessionInfo.CheckInItem(dti.OwnerID); //C2015-022 Separate Windows closing child form only left procedure ownership active MySessionInfo.CheckInItem(dti.OwnerID); //C2015-022 Separate Windows closing child form only left procedure ownership active
} }
if (MyParent == null) if (MyParent == null)
{ {
if (MyActivityTimer != null) if (MyActivityTimer != null)
{ {
MyActivityTimer.Dispose(); MyActivityTimer.Dispose();
_MyLog.Debug("VEPROMS FormClosing - dispose timer"); _MyLog.Debug("VEPROMS FormClosing - dispose timer");
} }
// C2015-022: part of separate windows upgrade close all of the child windows before closing the main PROMS window // C2015-022: part of separate windows upgrade close all of the child windows before closing the main PROMS window
if (PROMSWindowForms != null && PROMSWindowForms.Count > 0) if (PROMSWindowForms != null && PROMSWindowForms.Count > 0)
{ {
foreach (int k in PROMSWindowForms.Keys) foreach (int k in PROMSWindowForms.Keys)
{ {
frmVEPROMS child = PROMSWindowForms[k]; frmVEPROMS child = PROMSWindowForms[k];
_RemoveFromPROMSWindowForms = false; _RemoveFromPROMSWindowForms = false;
child._RemoveFromPROMSWindowForms = false; child._RemoveFromPROMSWindowForms = false;
child._WeAreExitingPROMS = _WeAreExitingPROMS; child._WeAreExitingPROMS = _WeAreExitingPROMS;
child.Close(); child.Close();
child.MySessionInfo.EndSession(); child.MySessionInfo.EndSession();
} }
} }
MySessionInfo?.EndSession(); MySessionInfo?.EndSession();
// Save the location and size of the VE-PROMS application for this user // Save the location and size of the VE-PROMS application for this user
if (WindowState == FormWindowState.Normal) if (WindowState == FormWindowState.Normal)
{ {
Settings.Default.Location = Location; Settings.Default.Location = Location;
Settings.Default.Size = Size; Settings.Default.Size = Size;
} }
if (MyVersionWindowList != null) if (MyVersionWindowList != null)
{ {
Settings.Default.VersionWindows = MyVersionWindowList.ToSettings(); Settings.Default.VersionWindows = MyVersionWindowList.ToSettings();
} }
Settings.Default.WindowState = WindowState; Settings.Default.WindowState = WindowState;
Settings.Default.QATItems = ribbonControl1.QatLayout; Settings.Default.QATItems = ribbonControl1.QatLayout;
SaveMRU(); SaveMRU();
DebugPagination.Close(); DebugPagination.Close();
DebugText.Close(); DebugText.Close();
BaselineMetaFile.Close(); // C2018-004 create meta file for baseline compares BaselineMetaFile.Close(); // C2018-004 create meta file for baseline compares
} }
} }
void frmVEPROMS_FormClosed(object sender, System.Windows.Forms.FormClosedEventArgs e) void frmVEPROMS_FormClosed(object sender, System.Windows.Forms.FormClosedEventArgs e)
{ {
// Close any open documents // Close any open documents
tc.Dispose(); tc.Dispose();
@@ -2423,10 +2393,10 @@ namespace VEPROMS
} }
// Add retrieve displaytabs state here. // Add retrieve displaytabs state here.
openDisplaytabstate(); OpenDisplaytabstate();
} }
public void openDisplaytabstate() private void OpenDisplaytabstate()
{ {
// Retrieve edit tab state from database. // Retrieve edit tab state from database.
DataTable DisPlayTabState = Item.GetDisplayTabs(VlnSettings.UserID); DataTable DisPlayTabState = Item.GetDisplayTabs(VlnSettings.UserID);
@@ -2449,31 +2419,50 @@ namespace VEPROMS
usersettings.SetUserSettings(true, result == DialogResult.Yes); usersettings.SetUserSettings(true, result == DialogResult.Yes);
} }
if (result == DialogResult.Yes) if (result == DialogResult.Yes)
{ {
// B2026-074 added flag (LoadingSavedProcTabs) to supress unnecessary event calls
// this will help prevent PROMS from getting stuck continuously looping through the same events
// when Word procedure tabs are restored.
// C2026-053 leaving this flag in her for now should we decide to trouble-shoot reopening of Word tabs later on.
tc.LoadingSavedProcTabs = true; // we check for this flag in DSOTabPanel.cs when opening Word sections
EditItem LastEditItem = null; //to hold last edit item. Needed in case last tab is a Word Section
foreach (DataRow TabState in DisPlayTabState.Rows) foreach (DataRow TabState in DisPlayTabState.Rows)
{ {
int _ItemID = (int)TabState["ItemID"]; int _ItemID = (int)TabState["ItemID"];
ItemInfo _Procedure = ItemInfo.Get(_ItemID); ItemInfo _Procedure = ItemInfo.Get(_ItemID);
// Open procedure in the editor. // C2026-053 Open procedure tab but only if it's NOT a Word section
if (_Procedure == null) continue; //skip and continue with foreach // Needed to disable opening saved Word sections - at least for now.
// We were running into performace and random hanging issues with the Word tabs - maybe windows event related.
if (_Procedure == null || _Procedure.HasWordContent) continue; //skip and continue with foreach
OpenItem(_Procedure); OpenItem(_Procedure);
if (tc.MyEditItem == null) continue; // skip and continue with foreach if (tc.MyEditItem == null) continue; // skip and continue with foreach
// SelectedStepTabPanel needs to be set so the print buttons on the ribbon will work. // SelectedStepTabPanel needs to be set so the print buttons on the ribbon will work.
SelectedStepTabPanel = tc.MyEditItem.MyStepPanel.MyStepTabPanel; SelectedStepTabPanel = tc.MyEditItem.MyStepPanel.MyStepTabPanel;
//CSM B2024-090 - if last displaytab item, LastEditItem = tc.MyEditItem; //set last tab index
//select the steptab panel for it if ((DisPlayTabState.Rows.IndexOf(TabState) == DisPlayTabState.Rows.Count - 1))
//and set the EditItem for Find/Replace
//otherwise will cause PROMS to crash if Find clicked before a Tab is given Focus
if ((DisPlayTabState.Rows.IndexOf(TabState) == DisPlayTabState.Rows.Count - 1))
{ {
SelectedStepTabPanel.Select(); SelectedStepTabPanel.Select();
dlgFindReplace.MyEditItem = tc.MyEditItem; }
SpellChecker.MyEditItem = tc.MyEditItem; //B2025-043 Remember Tabs is not setting the EditItem for the active window causing a PROMS crash when Spell Check }
} //CSM B2024-090 - if last displaytab item,
} //select the steptab panel for it
//and set the EditItem for Find/Replace
//otherwise will cause PROMS to crash if Find clicked before a Tab is given Focus
if (LastEditItem != null)
{
dlgFindReplace.MyEditItem = LastEditItem;
SpellChecker.MyEditItem = LastEditItem; //B2025-043 Remember Tabs is not setting the EditItem for the active window causing a PROMS crash when Spell Check
//B2026-090 Populate Step Properties Panel when PROMS restores saved display tabs
LastEditItem.MyStepPanel.BringToFront();
LastEditItem.MyStepPanel.Select();
Application.DoEvents();
tc_ItemSelectedChanged(this, new ItemSelectedChangedEventArgs(tc.MyEditItem));
}
tc.LoadingSavedProcTabs = false;
} }
} }
} }
@@ -3133,7 +3122,8 @@ namespace VEPROMS
_MyLog.WarnFormat("===============Override Close===================="); _MyLog.WarnFormat("===============Override Close====================");
} }
tc.CloseTabItem(dti); System.Threading.Thread.Sleep(500); //wait 1/2 a second to see if it closes on it's own
tc.CloseTabItem(dti);
} }
_TimeActivity1.Close(); _TimeActivity1.Close();
@@ -4022,7 +4012,7 @@ namespace VEPROMS
displayRO.MyRTB = SelectedStepTabPanel?.MyStepPanel.SelectedEditItem?.MyStepRTB; displayRO.MyRTB = SelectedStepTabPanel?.MyStepPanel.SelectedEditItem?.MyStepRTB;
displayRO.LoadTree(); //B2022-026 RO Memory reduction coding (Jakes Merge) displayRO.LoadTree(this); //B2022-026 RO Memory reduction coding (Jakes Merge)
} }
#endregion #endregion
@@ -4168,7 +4158,7 @@ namespace VEPROMS
// need this to update RO Tree after UpdateRofst (B2015-226) // need this to update RO Tree after UpdateRofst (B2015-226)
// B2022-026 RO Memory reduction coding (Jakes Merge) // B2022-026 RO Memory reduction coding (Jakes Merge)
displayRO.MyROFST = SelectedROFst; displayRO.MyROFST = SelectedROFst;
displayRO.LoadTree(); displayRO.LoadTree(this);
// resetting the MyROFSTLookup for the search & reports panels will refresh the RO trees after UpdateRofst in each of those panels (B2015-226) // resetting the MyROFSTLookup for the search & reports panels will refresh the RO trees after UpdateRofst in each of those panels (B2015-226)
if (SelectedDVI != null) if (SelectedDVI != null)
@@ -4243,7 +4233,7 @@ namespace VEPROMS
//C2026-008 Re-Architect RO.FST to include RO Modification date/time //C2026-008 Re-Architect RO.FST to include RO Modification date/time
// if ROFST got updated, // if ROFST got updated,
// set the Selected FST so it is in sync // set the Selected FST so it is in sync
if (!_WeAreExitingPROMS && displayRO.LoadTree(true)) if (!_WeAreExitingPROMS && displayRO.LoadTree(this,true))
{ {
SelectedROFst = displayRO.MyROFST; SelectedROFst = displayRO.MyROFST;
} }
@@ -4342,7 +4332,7 @@ namespace VEPROMS
// B2022-026 RO Memory reduction coding (Jakes Merge) // B2022-026 RO Memory reduction coding (Jakes Merge)
displayRO.MyRTB = null; displayRO.MyRTB = null;
displayRO.LoadTree(); displayRO.LoadTree(this);
} }
infotabTags.Visible = false; infotabTags.Visible = false;
@@ -4429,7 +4419,7 @@ namespace VEPROMS
//C2026-008 Re-Architect RO.FST to include RO Modification date/time //C2026-008 Re-Architect RO.FST to include RO Modification date/time
// if ROFST got updated, // if ROFST got updated,
// set the Selected FST so it is in sync // set the Selected FST so it is in sync
if (!_WeAreExitingPROMS && displayRO.LoadTree()) if (!_WeAreExitingPROMS && displayRO.LoadTree(this))
{ {
SelectedROFst = displayRO.MyROFST; SelectedROFst = displayRO.MyROFST;
} }
@@ -4460,7 +4450,7 @@ namespace VEPROMS
// B2022-026 RO Memory reduction coding (Jakes Merge) // B2022-026 RO Memory reduction coding (Jakes Merge)
displayRO.SetFindDocROButton(false); displayRO.SetFindDocROButton(false);
if (!_WeAreExitingPROMS) displayRO.LoadTree(); if (!_WeAreExitingPROMS) displayRO.LoadTree(this);
//C2019-036 View Only mode work with Checked Out Procedures //C2019-036 View Only mode work with Checked Out Procedures
//In View Only Mode - Step Properties should be disabled //In View Only Mode - Step Properties should be disabled
@@ -4481,7 +4471,7 @@ namespace VEPROMS
displayRO.ROTypeFilter = E_ROValueType.All; // allow all RO types for Word attachments (but fix) displayRO.ROTypeFilter = E_ROValueType.All; // allow all RO types for Word attachments (but fix)
displayRO.SetFindDocROButton(true); displayRO.SetFindDocROButton(true);
displayRO.LoadTree(); displayRO.LoadTree(this);
} }
} }
@@ -4607,7 +4597,7 @@ namespace VEPROMS
//C2026-008 Re-Architect RO.FST to include RO Modification date/time //C2026-008 Re-Architect RO.FST to include RO Modification date/time
// if ROFST got updated, // if ROFST got updated,
// set the Selected FST so it is in sync // set the Selected FST so it is in sync
if (displayRO.LoadTree()) if (displayRO.LoadTree(this))
{ {
SelectedROFst = displayRO.MyROFST; SelectedROFst = displayRO.MyROFST;
} }
@@ -283,7 +283,7 @@ namespace VEPROMS.CSLA.Library
_UserID = userID; _UserID = userID;
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
private void DataPortal_Delete(DeleteCriteria criteria) private void DataPortal_Delete(DeleteCriteria criteria)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Item.DataPortal_Delete", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Item.DataPortal_Delete", GetHashCode());
@@ -324,7 +324,7 @@ namespace VEPROMS.CSLA.Library
_procList = procList; _procList = procList;
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
private void DataPortal_Delete(DeleteAnnotationProcByTypeCriteria criteria) private void DataPortal_Delete(DeleteAnnotationProcByTypeCriteria criteria)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Item.DataPortal_Delete", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Item.DataPortal_Delete", GetHashCode());
@@ -365,7 +365,7 @@ namespace VEPROMS.CSLA.Library
_versionID = versionID; _versionID = versionID;
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
private void DataPortal_Delete(DeleteAnnotationDocvByTypeCriteria criteria) private void DataPortal_Delete(DeleteAnnotationDocvByTypeCriteria criteria)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Delete Annotations by Type Docv", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Delete Annotations by Type Docv", GetHashCode());
@@ -420,7 +420,7 @@ namespace VEPROMS.CSLA.Library
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
private getAnnotationCountProcCriteria DataPortal_Fetch(getAnnotationCountProcCriteria criteria) private getAnnotationCountProcCriteria DataPortal_Fetch(getAnnotationCountProcCriteria criteria)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Item.DataPortal_Fetch", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Item.DataPortal_Fetch", GetHashCode());
@@ -477,7 +477,7 @@ namespace VEPROMS.CSLA.Library
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
private getAnnotationCountDocvCriteria DataPortal_Fetch(getAnnotationCountDocvCriteria criteria) private getAnnotationCountDocvCriteria DataPortal_Fetch(getAnnotationCountDocvCriteria criteria)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Annotation.DataPortal_Fetch", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Annotation.DataPortal_Fetch", GetHashCode());
@@ -2388,7 +2388,7 @@ namespace VEPROMS.CSLA.Library
_UserID = userID; _UserID = userID;
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
private void DataPortal_Delete(DeleteCriteria criteria) private void DataPortal_Delete(DeleteCriteria criteria)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Item.DataPortal_Delete", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Item.DataPortal_Delete", GetHashCode());
@@ -178,7 +178,7 @@ namespace VEPROMS.CSLA.Library
} }
else if (si.ProcessID != ProcessID && objectType == CheckOutType.Document) else if (si.ProcessID != ProcessID && objectType == CheckOutType.Document)
{ {
message = string.Format("The document {0} is already checked out to {1}", DocumentInfo.Get(objectID).DocumentEntries[0].MyContent.Text, si.UserID); message = string.Format("The document {0} is already checked out to {1}", ItemInfo.ConvertToDisplayText(DocumentInfo.Get(objectID).DocumentEntries[0].MyContent.Text), si.UserID);
rv = rv && false; rv = rv && false;
} }
else if (si.ProcessID != ProcessID && objectType == CheckOutType.DocVersion) else if (si.ProcessID != ProcessID && objectType == CheckOutType.DocVersion)
@@ -198,7 +198,7 @@ namespace VEPROMS.CSLA.Library
message = message + string.Format("The procedure {0} is already checked out to {1}", name, si.UserID) + Environment.NewLine; message = message + string.Format("The procedure {0} is already checked out to {1}", name, si.UserID) + Environment.NewLine;
} }
else if (oi.OwnerType == 1) else if (oi.OwnerType == 1)
message = message + string.Format("The document {0} is already checked out to {1}", DocumentInfo.Get(oi.OwnerItemID).DocumentEntries[0].MyContent.Text, si.UserID) + Environment.NewLine; message = message + string.Format("The document {0} is already checked out to {1}", ItemInfo.ConvertToDisplayText(DocumentInfo.Get(oi.OwnerItemID).DocumentEntries[0].MyContent.Text), si.UserID) + Environment.NewLine;
else if (oi.OwnerType == 2) else if (oi.OwnerType == 2)
message += string.Format("The working draft is already checked out to {0}", si.UserID); message += string.Format("The working draft is already checked out to {0}", si.UserID);
rv = rv && false; rv = rv && false;
@@ -221,7 +221,7 @@ namespace VEPROMS.CSLA.Library
message = message + string.Format("The procedure {0} is already checked out to {1}", name, si.UserID) + Environment.NewLine; message = message + string.Format("The procedure {0} is already checked out to {1}", name, si.UserID) + Environment.NewLine;
} }
else if (oi.OwnerType == 1) else if (oi.OwnerType == 1)
message = message + string.Format("The document {0} is already checked out to {1}", DocumentInfo.Get(oi.OwnerItemID).DocumentEntries[0].MyContent.Text, si.UserID) + Environment.NewLine; message = message + string.Format("The document {0} is already checked out to {1}", ItemInfo.ConvertToDisplayText(DocumentInfo.Get(oi.OwnerItemID).DocumentEntries[0].MyContent.Text), si.UserID) + Environment.NewLine;
else if (oi.OwnerType == 2) else if (oi.OwnerType == 2)
message += string.Format("The working draft is already checked out to {0}", si.UserID); message += string.Format("The working draft is already checked out to {0}", si.UserID);
else if (oi.OwnerType == 3) else if (oi.OwnerType == 3)
@@ -25,7 +25,7 @@ namespace VEPROMS.CSLA.Library
public int DocID => _DocID; public int DocID => _DocID;
public DocIDCriteria(int docID) => _DocID = docID; public DocIDCriteria(int docID) => _DocID = docID;
} }
[Transactional(TransactionalTypes.TransactionScope)]
private void DataPortal_Delete(DocIDCriteria criteria) private void DataPortal_Delete(DocIDCriteria criteria)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Pdf.DataPortal_Delete", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Pdf.DataPortal_Delete", GetHashCode());
+20 -10
View File
@@ -128,17 +128,27 @@ namespace VEPROMS.CSLA.Library
int sibCount = SiblingCount(xmlNode); int sibCount = SiblingCount(xmlNode);
return string.Format("{0}/{1}[{2}]", parentPath, xmlNode.Name, sibCount); return string.Format("{0}/{1}[{2}]", parentPath, xmlNode.Name, sibCount);
} }
public static XmlNode InheritLookup(XmlNode xmlNode, string path, bool stepLookup) //B2026-077 – Update Format inheritance to use index id instead of position/order.
public static string PathByIndex(XmlNode xmlNode)
{
if (xmlNode.Name == "TransTypes" || xmlNode.Name == "Step")
{
string parentPath = xmlNode.ParentNode == xmlNode.OwnerDocument ? "" : Path(xmlNode.ParentNode);
string Indx = xmlNode.Attributes["Index"].Value;
return $@"{parentPath}/{xmlNode.Name}[@Index='{Indx}']";
}
else
{
return Path(xmlNode);
}
}
public static XmlNode InheritLookup(XmlNode xmlNode, string path, bool stepLookup)
{ {
//stepLookup = false; // 8/2 change for inheritance //stepLookup = false; // 8/2 change for inheritance
if (xmlNode == null) return null;// No path to match if (xmlNode == null) return null;// No path to match
string xPath = Path(xmlNode);// Build xPath from xmlNode string xPath = PathByIndex(xmlNode);// Build xPath from xmlNode
if (xmlNode.Name == "TransTypes")
{ vlnFormatDocument fd = (vlnFormatDocument)xmlNode.OwnerDocument;//First Get the vlnFormatDocument - This also ties it to a FormatInfo object
string TransIndex = xmlNode.Attributes["Index"].Value;
xPath = System.Text.RegularExpressions.Regex.Replace(xPath, @"\[[0-9]*\]$", @"[@Index='" + TransIndex + @"']");
}
vlnFormatDocument fd = (vlnFormatDocument)xmlNode.OwnerDocument;//First Get the vlnFormatDocument - This also ties it to a FormatInfo object
while(fd.MyFormat.MyIParent != null) while(fd.MyFormat.MyIParent != null)
{ {
fd = fd.MyFormat.MyIParent.PlantFormat.XmlDoc;// Get the parents vlnFormatDocument fd = fd.MyFormat.MyIParent.PlantFormat.XmlDoc;// Get the parents vlnFormatDocument
@@ -167,14 +177,14 @@ namespace VEPROMS.CSLA.Library
{ {
if (xmlNode == null) return null;// No path to match if (xmlNode == null) return null;// No path to match
string xPath = Path(xmlNode);// Build xPath from xmlNode string xPath = Path(xmlNode);// Build xPath from xmlNode
vlnFormatDocument fd = (vlnFormatDocument)xmlNode.OwnerDocument;//First Get the vlnFormatDocument - This also ties it to a FormatInfo object vlnFormatDocument fd = (vlnFormatDocument)xmlNode.OwnerDocument;//First Get the vlnFormatDocument - This also ties it to a FormatInfo object
while (fd.MyFormat.MyIParent != null) while (fd.MyFormat.MyIParent != null)
{ {
fd = fd.MyFormat.MyIParent.PlantFormat.XmlDoc;// Get the parents vlnFormatDocument fd = fd.MyFormat.MyIParent.PlantFormat.XmlDoc;// Get the parents vlnFormatDocument
if (fd != null) if (fd != null)
{ {
XmlNode xp = fd.SelectSingleNode(xPath);// Get the related node XmlNode xp = fd.SelectSingleNode(xPath);// Get the related node
if (xp != null) if (xp != null)
{ {
XmlNodeList xl = xp.SelectNodes(path); XmlNodeList xl = xp.SelectNodes(path);
if (xl != null && xl.Count > 0) if (xl != null && xl.Count > 0)
@@ -610,7 +610,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Annotation.DataPortal_Fetch", ex); throw new DbCslaException("Annotation.DataPortal_Fetch", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Insert() protected override void DataPortal_Insert()
{ {
try try
@@ -635,7 +635,7 @@ namespace VEPROMS.CSLA.Library
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Annotation.DataPortal_Insert", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Annotation.DataPortal_Insert", GetHashCode());
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
internal void SQLInsert() internal void SQLInsert()
{ {
if (!IsDirty) return; if (!IsDirty) return;
@@ -643,8 +643,9 @@ namespace VEPROMS.CSLA.Library
{ {
_MyAnnotationType?.Update(); _MyAnnotationType?.Update();
_MyItem?.Update(); _MyItem?.Update();
using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
using (SqlCommand cm = cn.CreateCommand()) using (SqlCommand cm = cn.CreateCommand())
{ {
cm.CommandType = CommandType.StoredProcedure; cm.CommandType = CommandType.StoredProcedure;
@@ -688,7 +689,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Annotation.SQLInsert", ex); throw new DbCslaException("Annotation.SQLInsert", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
public static byte[] Add(SqlConnection cn, ref int annotationID, Item myItem, AnnotationType myAnnotationType, string rtfText, string searchText, string config, DateTime dts, string userID) public static byte[] Add(SqlConnection cn, ref int annotationID, Item myItem, AnnotationType myAnnotationType, string rtfText, string searchText, string config, DateTime dts, string userID)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Annotation.Add", 0); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Annotation.Add", 0);
@@ -731,7 +732,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Annotation.Add", ex); throw new DbCslaException("Annotation.Add", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Update() protected override void DataPortal_Update()
{ {
if (!IsDirty) return; // If not dirty - nothing to do if (!IsDirty) return; // If not dirty - nothing to do
@@ -754,7 +755,7 @@ namespace VEPROMS.CSLA.Library
if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; if (!ex.Message.EndsWith("has been edited by another user.")) throw ex;
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
internal void SQLUpdate() internal void SQLUpdate()
{ {
if (!IsDirty) return; // If not dirty - nothing to do if (!IsDirty) return; // If not dirty - nothing to do
@@ -763,8 +764,9 @@ namespace VEPROMS.CSLA.Library
{ {
_MyAnnotationType?.Update(); _MyAnnotationType?.Update();
_MyItem?.Update(); _MyItem?.Update();
using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
if (base.IsDirty) if (base.IsDirty)
{ {
using (SqlCommand cm = cn.CreateCommand()) using (SqlCommand cm = cn.CreateCommand())
@@ -811,8 +813,9 @@ namespace VEPROMS.CSLA.Library
if (!IsDirty) return; if (!IsDirty) return;
if (base.IsDirty) if (base.IsDirty)
{ {
using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
if (IsNew) if (IsNew)
_LastChanged = Annotation.Add(cn, ref _AnnotationID, _MyItem, _MyAnnotationType, _RtfText, _SearchText, _Config, _DTS, _UserID); _LastChanged = Annotation.Add(cn, ref _AnnotationID, _MyItem, _MyAnnotationType, _RtfText, _SearchText, _Config, _DTS, _UserID);
else else
@@ -822,7 +825,7 @@ namespace VEPROMS.CSLA.Library
MarkOld(); MarkOld();
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
public static byte[] Update(SqlConnection cn, ref int annotationID, int itemID, int typeID, string rtfText, string searchText, string config, DateTime dts, string userID, ref byte[] lastChanged) public static byte[] Update(SqlConnection cn, ref int annotationID, int itemID, int typeID, string rtfText, string searchText, string config, DateTime dts, string userID, ref byte[] lastChanged)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Annotation.Update", 0); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Annotation.Update", 0);
@@ -861,12 +864,12 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Annotation.Update", ex); throw new DbCslaException("Annotation.Update", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_DeleteSelf() protected override void DataPortal_DeleteSelf()
{ {
DataPortal_Delete(new PKCriteria(_AnnotationID)); DataPortal_Delete(new PKCriteria(_AnnotationID));
} }
[Transactional(TransactionalTypes.TransactionScope)]
private void DataPortal_Delete(PKCriteria criteria) private void DataPortal_Delete(PKCriteria criteria)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Annotation.DataPortal_Delete", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Annotation.DataPortal_Delete", GetHashCode());
@@ -891,7 +894,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Annotation.DataPortal_Delete", ex); throw new DbCslaException("Annotation.DataPortal_Delete", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
public static void Remove(SqlConnection cn, int annotationID) public static void Remove(SqlConnection cn, int annotationID)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Annotation.Remove", 0); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Annotation.Remove", 0);
@@ -943,7 +946,7 @@ namespace VEPROMS.CSLA.Library
{ {
using (SqlConnection cn = Database.VEPROMS_SqlConnection) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
cn.Open(); if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
using (SqlCommand cm = cn.CreateCommand()) using (SqlCommand cm = cn.CreateCommand())
{ {
cm.CommandType = CommandType.StoredProcedure; cm.CommandType = CommandType.StoredProcedure;
@@ -555,7 +555,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("AnnotationAudit.DataPortal_Fetch", ex); throw new DbCslaException("AnnotationAudit.DataPortal_Fetch", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Insert() protected override void DataPortal_Insert()
{ {
try try
@@ -580,14 +580,15 @@ namespace VEPROMS.CSLA.Library
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] AnnotationAudit.DataPortal_Insert", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] AnnotationAudit.DataPortal_Insert", GetHashCode());
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
internal void SQLInsert() internal void SQLInsert()
{ {
if (!IsDirty) return; if (!IsDirty) return;
try try
{ {
using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
using (SqlCommand cm = cn.CreateCommand()) using (SqlCommand cm = cn.CreateCommand())
{ {
cm.CommandType = CommandType.StoredProcedure; cm.CommandType = CommandType.StoredProcedure;
@@ -627,7 +628,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("AnnotationAudit.SQLInsert", ex); throw new DbCslaException("AnnotationAudit.SQLInsert", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
public static void Add(SqlConnection cn, ref long auditID, int annotationID, int itemID, int typeID, string rtfText, string searchText, string config, DateTime dts, string userID, int deleteStatus) public static void Add(SqlConnection cn, ref long auditID, int annotationID, int itemID, int typeID, string rtfText, string searchText, string config, DateTime dts, string userID, int deleteStatus)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] AnnotationAudit.Add", 0); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] AnnotationAudit.Add", 0);
@@ -667,7 +668,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("AnnotationAudit.Add", ex); throw new DbCslaException("AnnotationAudit.Add", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Update() protected override void DataPortal_Update()
{ {
if (!IsDirty) return; // If not dirty - nothing to do if (!IsDirty) return; // If not dirty - nothing to do
@@ -690,15 +691,16 @@ namespace VEPROMS.CSLA.Library
if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; if (!ex.Message.EndsWith("has been edited by another user.")) throw ex;
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
internal void SQLUpdate() internal void SQLUpdate()
{ {
if (!IsDirty) return; // If not dirty - nothing to do if (!IsDirty) return; // If not dirty - nothing to do
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] AnnotationAudit.SQLUpdate", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] AnnotationAudit.SQLUpdate", GetHashCode());
try try
{ {
using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
if (base.IsDirty) if (base.IsDirty)
{ {
using (SqlCommand cm = cn.CreateCommand()) using (SqlCommand cm = cn.CreateCommand())
@@ -740,8 +742,9 @@ namespace VEPROMS.CSLA.Library
if (!IsDirty) return; if (!IsDirty) return;
if (base.IsDirty) if (base.IsDirty)
{ {
using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
if (IsNew) if (IsNew)
AnnotationAudit.Add(cn, ref _AuditID, _AnnotationID, _ItemID, _TypeID, _RtfText, _SearchText, _Config, _DTS, _UserID, _DeleteStatus); AnnotationAudit.Add(cn, ref _AuditID, _AnnotationID, _ItemID, _TypeID, _RtfText, _SearchText, _Config, _DTS, _UserID, _DeleteStatus);
else else
@@ -751,7 +754,7 @@ namespace VEPROMS.CSLA.Library
MarkOld(); MarkOld();
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
public static void Update(SqlConnection cn, ref long auditID, int annotationID, int itemID, int typeID, string rtfText, string searchText, string config, DateTime dts, string userID, int deleteStatus) public static void Update(SqlConnection cn, ref long auditID, int annotationID, int itemID, int typeID, string rtfText, string searchText, string config, DateTime dts, string userID, int deleteStatus)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] AnnotationAudit.Update", 0); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] AnnotationAudit.Update", 0);
@@ -786,12 +789,12 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("AnnotationAudit.Update", ex); throw new DbCslaException("AnnotationAudit.Update", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_DeleteSelf() protected override void DataPortal_DeleteSelf()
{ {
DataPortal_Delete(new PKCriteria(_AuditID)); DataPortal_Delete(new PKCriteria(_AuditID));
} }
[Transactional(TransactionalTypes.TransactionScope)]
private void DataPortal_Delete(PKCriteria criteria) private void DataPortal_Delete(PKCriteria criteria)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] AnnotationAudit.DataPortal_Delete", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] AnnotationAudit.DataPortal_Delete", GetHashCode());
@@ -816,7 +819,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("AnnotationAudit.DataPortal_Delete", ex); throw new DbCslaException("AnnotationAudit.DataPortal_Delete", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
public static void Remove(SqlConnection cn, long auditID) public static void Remove(SqlConnection cn, long auditID)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] AnnotationAudit.Remove", 0); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] AnnotationAudit.Remove", 0);
@@ -868,7 +871,7 @@ namespace VEPROMS.CSLA.Library
{ {
using (SqlConnection cn = Database.VEPROMS_SqlConnection) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
cn.Open(); if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
using (SqlCommand cm = cn.CreateCommand()) using (SqlCommand cm = cn.CreateCommand())
{ {
cm.CommandType = CommandType.StoredProcedure; cm.CommandType = CommandType.StoredProcedure;
@@ -691,7 +691,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("AnnotationType.DataPortal_Fetch", ex); throw new DbCslaException("AnnotationType.DataPortal_Fetch", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Insert() protected override void DataPortal_Insert()
{ {
try try
@@ -716,14 +716,15 @@ namespace VEPROMS.CSLA.Library
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] AnnotationType.DataPortal_Insert", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] AnnotationType.DataPortal_Insert", GetHashCode());
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
internal void SQLInsert() internal void SQLInsert()
{ {
if (!IsDirty) return; if (!IsDirty) return;
try try
{ {
using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
using (SqlCommand cm = cn.CreateCommand()) using (SqlCommand cm = cn.CreateCommand())
{ {
cm.CommandType = CommandType.StoredProcedure; cm.CommandType = CommandType.StoredProcedure;
@@ -765,7 +766,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("AnnotationType.SQLInsert", ex); throw new DbCslaException("AnnotationType.SQLInsert", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
public static byte[] Add(SqlConnection cn, ref int typeID, string name, string config, DateTime dts, string userID) public static byte[] Add(SqlConnection cn, ref int typeID, string name, string config, DateTime dts, string userID)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] AnnotationType.Add", 0); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] AnnotationType.Add", 0);
@@ -805,7 +806,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("AnnotationType.Add", ex); throw new DbCslaException("AnnotationType.Add", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Update() protected override void DataPortal_Update()
{ {
if (!IsDirty) return; // If not dirty - nothing to do if (!IsDirty) return; // If not dirty - nothing to do
@@ -828,15 +829,16 @@ namespace VEPROMS.CSLA.Library
if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; if (!ex.Message.EndsWith("has been edited by another user.")) throw ex;
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
internal void SQLUpdate() internal void SQLUpdate()
{ {
if (!IsDirty) return; // If not dirty - nothing to do if (!IsDirty) return; // If not dirty - nothing to do
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] AnnotationType.SQLUpdate", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] AnnotationType.SQLUpdate", GetHashCode());
try try
{ {
using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
if (base.IsDirty) if (base.IsDirty)
{ {
using (SqlCommand cm = cn.CreateCommand()) using (SqlCommand cm = cn.CreateCommand())
@@ -881,8 +883,9 @@ namespace VEPROMS.CSLA.Library
if (!IsDirty) return; if (!IsDirty) return;
if (base.IsDirty) if (base.IsDirty)
{ {
using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
if (IsNew) if (IsNew)
_LastChanged = AnnotationType.Add(cn, ref _TypeID, _Name, _Config, _DTS, _UserID); _LastChanged = AnnotationType.Add(cn, ref _TypeID, _Name, _Config, _DTS, _UserID);
else else
@@ -893,7 +896,7 @@ namespace VEPROMS.CSLA.Library
} }
_AnnotationTypeAnnotations?.Update(this); _AnnotationTypeAnnotations?.Update(this);
} }
[Transactional(TransactionalTypes.TransactionScope)]
public static byte[] Update(SqlConnection cn, ref int typeID, string name, string config, DateTime dts, string userID, ref byte[] lastChanged) public static byte[] Update(SqlConnection cn, ref int typeID, string name, string config, DateTime dts, string userID, ref byte[] lastChanged)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] AnnotationType.Update", 0); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] AnnotationType.Update", 0);
@@ -929,9 +932,9 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("AnnotationType.Update", ex); throw new DbCslaException("AnnotationType.Update", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_DeleteSelf() => DataPortal_Delete(new PKCriteria(_TypeID)); protected override void DataPortal_DeleteSelf() => DataPortal_Delete(new PKCriteria(_TypeID));
[Transactional(TransactionalTypes.TransactionScope)]
private void DataPortal_Delete(PKCriteria criteria) private void DataPortal_Delete(PKCriteria criteria)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] AnnotationType.DataPortal_Delete", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] AnnotationType.DataPortal_Delete", GetHashCode());
@@ -956,7 +959,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("AnnotationType.DataPortal_Delete", ex); throw new DbCslaException("AnnotationType.DataPortal_Delete", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
public static void Remove(SqlConnection cn, int typeID) public static void Remove(SqlConnection cn, int typeID)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] AnnotationType.Remove", 0); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] AnnotationType.Remove", 0);
@@ -1008,7 +1011,7 @@ namespace VEPROMS.CSLA.Library
{ {
using (SqlConnection cn = Database.VEPROMS_SqlConnection) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
cn.Open(); if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
using (SqlCommand cm = cn.CreateCommand()) using (SqlCommand cm = cn.CreateCommand())
{ {
cm.CommandType = CommandType.StoredProcedure; cm.CommandType = CommandType.StoredProcedure;
@@ -395,8 +395,9 @@ namespace VEPROMS.CSLA.Library
{ {
// if we're not dirty then don't update the database // if we're not dirty then don't update the database
if (!IsDirty) return; if (!IsDirty) return;
using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
_LastChanged = Annotation.Add(cn, ref _AnnotationID, _MyItem, myAnnotationType, _RtfText, _SearchText, _Config, _DTS, _UserID); _LastChanged = Annotation.Add(cn, ref _AnnotationID, _MyItem, myAnnotationType, _RtfText, _SearchText, _Config, _DTS, _UserID);
} }
@@ -406,8 +407,9 @@ namespace VEPROMS.CSLA.Library
{ {
// if we're not dirty then don't update the database // if we're not dirty then don't update the database
if (!IsDirty) return; if (!IsDirty) return;
using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
_LastChanged = Annotation.Update(cn, ref _AnnotationID, _ItemID, myAnnotationType.TypeID, _RtfText, _SearchText, _Config, _DTS, _UserID, ref _LastChanged); _LastChanged = Annotation.Update(cn, ref _AnnotationID, _ItemID, myAnnotationType.TypeID, _RtfText, _SearchText, _Config, _DTS, _UserID, ref _LastChanged);
} }
@@ -420,8 +422,9 @@ namespace VEPROMS.CSLA.Library
if (!IsDirty) return; if (!IsDirty) return;
// if we're new then don't update the database // if we're new then don't update the database
if (IsNew) return; if (IsNew) return;
using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
Annotation.Remove(cn, _AnnotationID); Annotation.Remove(cn, _AnnotationID);
} }
@@ -667,7 +667,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Assignment.DataPortal_Fetch", ex); throw new DbCslaException("Assignment.DataPortal_Fetch", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Insert() protected override void DataPortal_Insert()
{ {
try try
@@ -692,7 +692,7 @@ namespace VEPROMS.CSLA.Library
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Assignment.DataPortal_Insert", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Assignment.DataPortal_Insert", GetHashCode());
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
internal void SQLInsert() internal void SQLInsert()
{ {
if (!IsDirty) return; if (!IsDirty) return;
@@ -701,8 +701,9 @@ namespace VEPROMS.CSLA.Library
_MyFolder?.Update(); _MyFolder?.Update();
_MyGroup?.Update(); _MyGroup?.Update();
_MyRole?.Update(); _MyRole?.Update();
using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
using (SqlCommand cm = cn.CreateCommand()) using (SqlCommand cm = cn.CreateCommand())
{ {
cm.CommandType = CommandType.StoredProcedure; cm.CommandType = CommandType.StoredProcedure;
@@ -746,7 +747,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Assignment.SQLInsert", ex); throw new DbCslaException("Assignment.SQLInsert", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
public static byte[] Add(SqlConnection cn, ref int aid, Group myGroup, Role myRole, Folder myFolder, SmartDate startDate, SmartDate endDate, DateTime dts, string usrID) public static byte[] Add(SqlConnection cn, ref int aid, Group myGroup, Role myRole, Folder myFolder, SmartDate startDate, SmartDate endDate, DateTime dts, string usrID)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Assignment.Add", 0); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Assignment.Add", 0);
@@ -789,7 +790,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Assignment.Add", ex); throw new DbCslaException("Assignment.Add", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Update() protected override void DataPortal_Update()
{ {
if (!IsDirty) return; // If not dirty - nothing to do if (!IsDirty) return; // If not dirty - nothing to do
@@ -812,7 +813,7 @@ namespace VEPROMS.CSLA.Library
if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; if (!ex.Message.EndsWith("has been edited by another user.")) throw ex;
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
internal void SQLUpdate() internal void SQLUpdate()
{ {
if (!IsDirty) return; // If not dirty - nothing to do if (!IsDirty) return; // If not dirty - nothing to do
@@ -822,8 +823,9 @@ namespace VEPROMS.CSLA.Library
_MyFolder?.Update(); _MyFolder?.Update();
_MyGroup?.Update(); _MyGroup?.Update();
_MyRole?.Update(); _MyRole?.Update();
using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
if (base.IsDirty) if (base.IsDirty)
{ {
using (SqlCommand cm = cn.CreateCommand()) using (SqlCommand cm = cn.CreateCommand())
@@ -870,8 +872,9 @@ namespace VEPROMS.CSLA.Library
if (!IsDirty) return; if (!IsDirty) return;
if (base.IsDirty) if (base.IsDirty)
{ {
using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
if (IsNew) if (IsNew)
_LastChanged = Assignment.Add(cn, ref _AID, _MyGroup, _MyRole, _MyFolder, new SmartDate(_StartDate), new SmartDate(_EndDate), _DTS, _UsrID); _LastChanged = Assignment.Add(cn, ref _AID, _MyGroup, _MyRole, _MyFolder, new SmartDate(_StartDate), new SmartDate(_EndDate), _DTS, _UsrID);
else else
@@ -881,7 +884,7 @@ namespace VEPROMS.CSLA.Library
MarkOld(); MarkOld();
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
public static byte[] Update(SqlConnection cn, ref int aid, int gid, int rid, int folderID, SmartDate startDate, SmartDate endDate, DateTime dts, string usrID, ref byte[] lastChanged) public static byte[] Update(SqlConnection cn, ref int aid, int gid, int rid, int folderID, SmartDate startDate, SmartDate endDate, DateTime dts, string usrID, ref byte[] lastChanged)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Assignment.Update", 0); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Assignment.Update", 0);
@@ -920,9 +923,9 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Assignment.Update", ex); throw new DbCslaException("Assignment.Update", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_DeleteSelf() => DataPortal_Delete(new PKCriteria(_AID)); protected override void DataPortal_DeleteSelf() => DataPortal_Delete(new PKCriteria(_AID));
[Transactional(TransactionalTypes.TransactionScope)]
private void DataPortal_Delete(PKCriteria criteria) private void DataPortal_Delete(PKCriteria criteria)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Assignment.DataPortal_Delete", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Assignment.DataPortal_Delete", GetHashCode());
@@ -947,7 +950,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Assignment.DataPortal_Delete", ex); throw new DbCslaException("Assignment.DataPortal_Delete", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
public static void Remove(SqlConnection cn, int aid) public static void Remove(SqlConnection cn, int aid)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Assignment.Remove", 0); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Assignment.Remove", 0);
@@ -999,7 +1002,7 @@ namespace VEPROMS.CSLA.Library
{ {
using (SqlConnection cn = Database.VEPROMS_SqlConnection) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
cn.Open(); if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
using (SqlCommand cm = cn.CreateCommand()) using (SqlCommand cm = cn.CreateCommand())
{ {
cm.CommandType = CommandType.StoredProcedure; cm.CommandType = CommandType.StoredProcedure;
@@ -648,7 +648,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Association.DataPortal_Fetch", ex); throw new DbCslaException("Association.DataPortal_Fetch", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Insert() protected override void DataPortal_Insert()
{ {
try try
@@ -673,7 +673,7 @@ namespace VEPROMS.CSLA.Library
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Association.DataPortal_Insert", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Association.DataPortal_Insert", GetHashCode());
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
internal void SQLInsert() internal void SQLInsert()
{ {
if (!IsDirty) return; if (!IsDirty) return;
@@ -681,8 +681,9 @@ namespace VEPROMS.CSLA.Library
{ {
_MyDocVersion?.Update(); _MyDocVersion?.Update();
_MyROFst?.Update(); _MyROFst?.Update();
using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
using (SqlCommand cm = cn.CreateCommand()) using (SqlCommand cm = cn.CreateCommand())
{ {
cm.CommandType = CommandType.StoredProcedure; cm.CommandType = CommandType.StoredProcedure;
@@ -724,7 +725,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Association.SQLInsert", ex); throw new DbCslaException("Association.SQLInsert", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
public static byte[] Add(SqlConnection cn, ref int associationID, DocVersion myDocVersion, ROFst myROFst, string config, DateTime dts, string userID) public static byte[] Add(SqlConnection cn, ref int associationID, DocVersion myDocVersion, ROFst myROFst, string config, DateTime dts, string userID)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Association.Add", 0); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Association.Add", 0);
@@ -765,7 +766,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Association.Add", ex); throw new DbCslaException("Association.Add", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Update() protected override void DataPortal_Update()
{ {
if (!IsDirty) return; // If not dirty - nothing to do if (!IsDirty) return; // If not dirty - nothing to do
@@ -788,7 +789,7 @@ namespace VEPROMS.CSLA.Library
if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; if (!ex.Message.EndsWith("has been edited by another user.")) throw ex;
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
internal void SQLUpdate() internal void SQLUpdate()
{ {
if (!IsDirty) return; // If not dirty - nothing to do if (!IsDirty) return; // If not dirty - nothing to do
@@ -797,8 +798,9 @@ namespace VEPROMS.CSLA.Library
{ {
_MyDocVersion?.Update(); _MyDocVersion?.Update();
_MyROFst?.Update(); _MyROFst?.Update();
using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
if (base.IsDirty) if (base.IsDirty)
{ {
using (SqlCommand cm = cn.CreateCommand()) using (SqlCommand cm = cn.CreateCommand())
@@ -843,8 +845,9 @@ namespace VEPROMS.CSLA.Library
if (!IsDirty) return; if (!IsDirty) return;
if (base.IsDirty) if (base.IsDirty)
{ {
using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
if (IsNew) if (IsNew)
_LastChanged = Association.Add(cn, ref _AssociationID, _MyDocVersion, _MyROFst, _Config, _DTS, _UserID); _LastChanged = Association.Add(cn, ref _AssociationID, _MyDocVersion, _MyROFst, _Config, _DTS, _UserID);
else else
@@ -854,7 +857,7 @@ namespace VEPROMS.CSLA.Library
MarkOld(); MarkOld();
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
public static byte[] Update(SqlConnection cn, ref int associationID, int versionID, int rOFstID, string config, DateTime dts, string userID, ref byte[] lastChanged) public static byte[] Update(SqlConnection cn, ref int associationID, int versionID, int rOFstID, string config, DateTime dts, string userID, ref byte[] lastChanged)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Association.Update", 0); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Association.Update", 0);
@@ -891,9 +894,9 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Association.Update", ex); throw new DbCslaException("Association.Update", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_DeleteSelf() => DataPortal_Delete(new PKCriteria(_AssociationID)); protected override void DataPortal_DeleteSelf() => DataPortal_Delete(new PKCriteria(_AssociationID));
[Transactional(TransactionalTypes.TransactionScope)]
private void DataPortal_Delete(PKCriteria criteria) private void DataPortal_Delete(PKCriteria criteria)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Association.DataPortal_Delete", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Association.DataPortal_Delete", GetHashCode());
@@ -918,7 +921,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Association.DataPortal_Delete", ex); throw new DbCslaException("Association.DataPortal_Delete", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
public static void Remove(SqlConnection cn, int associationID) public static void Remove(SqlConnection cn, int associationID)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Association.Remove", 0); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Association.Remove", 0);
@@ -970,7 +973,7 @@ namespace VEPROMS.CSLA.Library
{ {
using (SqlConnection cn = Database.VEPROMS_SqlConnection) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
cn.Open(); if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
using (SqlCommand cm = cn.CreateCommand()) using (SqlCommand cm = cn.CreateCommand())
{ {
cm.CommandType = CommandType.StoredProcedure; cm.CommandType = CommandType.StoredProcedure;
+16 -13
View File
@@ -567,7 +567,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Check.DataPortal_Fetch", ex); throw new DbCslaException("Check.DataPortal_Fetch", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Insert() protected override void DataPortal_Insert()
{ {
try try
@@ -592,7 +592,7 @@ namespace VEPROMS.CSLA.Library
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Check.DataPortal_Insert", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Check.DataPortal_Insert", GetHashCode());
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
internal void SQLInsert() internal void SQLInsert()
{ {
if (!IsDirty) return; if (!IsDirty) return;
@@ -600,8 +600,9 @@ namespace VEPROMS.CSLA.Library
{ {
_MyRevision?.Update(); _MyRevision?.Update();
_MyStage?.Update(); _MyStage?.Update();
using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
using (SqlCommand cm = cn.CreateCommand()) using (SqlCommand cm = cn.CreateCommand())
{ {
cm.CommandType = CommandType.StoredProcedure; cm.CommandType = CommandType.StoredProcedure;
@@ -643,7 +644,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Check.SQLInsert", ex); throw new DbCslaException("Check.SQLInsert", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
public static byte[] Add(SqlConnection cn, ref int checkID, Revision myRevision, Stage myStage, string consistencyChecks, DateTime dts, string userID) public static byte[] Add(SqlConnection cn, ref int checkID, Revision myRevision, Stage myStage, string consistencyChecks, DateTime dts, string userID)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Check.Add", 0); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Check.Add", 0);
@@ -684,7 +685,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Check.Add", ex); throw new DbCslaException("Check.Add", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Update() protected override void DataPortal_Update()
{ {
if (!IsDirty) return; // If not dirty - nothing to do if (!IsDirty) return; // If not dirty - nothing to do
@@ -707,7 +708,7 @@ namespace VEPROMS.CSLA.Library
if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; if (!ex.Message.EndsWith("has been edited by another user.")) throw ex;
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
internal void SQLUpdate() internal void SQLUpdate()
{ {
if (!IsDirty) return; // If not dirty - nothing to do if (!IsDirty) return; // If not dirty - nothing to do
@@ -716,8 +717,9 @@ namespace VEPROMS.CSLA.Library
{ {
_MyRevision?.Update(); _MyRevision?.Update();
_MyStage?.Update(); _MyStage?.Update();
using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
if (base.IsDirty) if (base.IsDirty)
{ {
using (SqlCommand cm = cn.CreateCommand()) using (SqlCommand cm = cn.CreateCommand())
@@ -762,8 +764,9 @@ namespace VEPROMS.CSLA.Library
if (!IsDirty) return; if (!IsDirty) return;
if (base.IsDirty) if (base.IsDirty)
{ {
using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
if (IsNew) if (IsNew)
_LastChanged = Check.Add(cn, ref _CheckID, _MyRevision, _MyStage, _ConsistencyChecks, _DTS, _UserID); _LastChanged = Check.Add(cn, ref _CheckID, _MyRevision, _MyStage, _ConsistencyChecks, _DTS, _UserID);
else else
@@ -773,7 +776,7 @@ namespace VEPROMS.CSLA.Library
MarkOld(); MarkOld();
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
public static byte[] Update(SqlConnection cn, ref int checkID, int revisionID, int stageID, string consistencyChecks, DateTime dts, string userID, ref byte[] lastChanged) public static byte[] Update(SqlConnection cn, ref int checkID, int revisionID, int stageID, string consistencyChecks, DateTime dts, string userID, ref byte[] lastChanged)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Check.Update", 0); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Check.Update", 0);
@@ -810,9 +813,9 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Check.Update", ex); throw new DbCslaException("Check.Update", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_DeleteSelf() => DataPortal_Delete(new PKCriteria(_CheckID)); protected override void DataPortal_DeleteSelf() => DataPortal_Delete(new PKCriteria(_CheckID));
[Transactional(TransactionalTypes.TransactionScope)]
private void DataPortal_Delete(PKCriteria criteria) private void DataPortal_Delete(PKCriteria criteria)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Check.DataPortal_Delete", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Check.DataPortal_Delete", GetHashCode());
@@ -837,7 +840,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Check.DataPortal_Delete", ex); throw new DbCslaException("Check.DataPortal_Delete", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
public static void Remove(SqlConnection cn, int checkID) public static void Remove(SqlConnection cn, int checkID)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Check.Remove", 0); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Check.Remove", 0);
@@ -889,7 +892,7 @@ namespace VEPROMS.CSLA.Library
{ {
using (SqlConnection cn = Database.VEPROMS_SqlConnection) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
cn.Open(); if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
using (SqlCommand cm = cn.CreateCommand()) using (SqlCommand cm = cn.CreateCommand())
{ {
cm.CommandType = CommandType.StoredProcedure; cm.CommandType = CommandType.StoredProcedure;
@@ -705,7 +705,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Connection.DataPortal_Fetch", ex); throw new DbCslaException("Connection.DataPortal_Fetch", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Insert() protected override void DataPortal_Insert()
{ {
try try
@@ -730,14 +730,15 @@ namespace VEPROMS.CSLA.Library
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Connection.DataPortal_Insert", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Connection.DataPortal_Insert", GetHashCode());
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
internal void SQLInsert() internal void SQLInsert()
{ {
if (!IsDirty) return; if (!IsDirty) return;
try try
{ {
using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
using (SqlCommand cm = cn.CreateCommand()) using (SqlCommand cm = cn.CreateCommand())
{ {
cm.CommandType = CommandType.StoredProcedure; cm.CommandType = CommandType.StoredProcedure;
@@ -782,7 +783,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Connection.SQLInsert", ex); throw new DbCslaException("Connection.SQLInsert", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
public static byte[] Add(SqlConnection cn, ref int dbid, string name, string title, string connectionString, int serverType, string config, DateTime dts, string usrID) public static byte[] Add(SqlConnection cn, ref int dbid, string name, string title, string connectionString, int serverType, string config, DateTime dts, string usrID)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Connection.Add", 0); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Connection.Add", 0);
@@ -825,7 +826,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Connection.Add", ex); throw new DbCslaException("Connection.Add", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Update() protected override void DataPortal_Update()
{ {
if (!IsDirty) return; // If not dirty - nothing to do if (!IsDirty) return; // If not dirty - nothing to do
@@ -848,15 +849,16 @@ namespace VEPROMS.CSLA.Library
if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; if (!ex.Message.EndsWith("has been edited by another user.")) throw ex;
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
internal void SQLUpdate() internal void SQLUpdate()
{ {
if (!IsDirty) return; // If not dirty - nothing to do if (!IsDirty) return; // If not dirty - nothing to do
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Connection.SQLUpdate", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Connection.SQLUpdate", GetHashCode());
try try
{ {
using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
if (base.IsDirty) if (base.IsDirty)
{ {
using (SqlCommand cm = cn.CreateCommand()) using (SqlCommand cm = cn.CreateCommand())
@@ -904,8 +906,9 @@ namespace VEPROMS.CSLA.Library
if (!IsDirty) return; if (!IsDirty) return;
if (base.IsDirty) if (base.IsDirty)
{ {
using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
if (IsNew) if (IsNew)
_LastChanged = Connection.Add(cn, ref _DBID, _Name, _Title, _ConnectionString, _ServerType, _Config, _DTS, _UsrID); _LastChanged = Connection.Add(cn, ref _DBID, _Name, _Title, _ConnectionString, _ServerType, _Config, _DTS, _UsrID);
else else
@@ -916,7 +919,7 @@ namespace VEPROMS.CSLA.Library
} }
_ConnectionFolders?.Update(this); _ConnectionFolders?.Update(this);
} }
[Transactional(TransactionalTypes.TransactionScope)]
public static byte[] Update(SqlConnection cn, ref int dbid, string name, string title, string connectionString, int serverType, string config, DateTime dts, string usrID, ref byte[] lastChanged) public static byte[] Update(SqlConnection cn, ref int dbid, string name, string title, string connectionString, int serverType, string config, DateTime dts, string usrID, ref byte[] lastChanged)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Connection.Update", 0); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Connection.Update", 0);
@@ -955,12 +958,12 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Connection.Update", ex); throw new DbCslaException("Connection.Update", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_DeleteSelf() protected override void DataPortal_DeleteSelf()
{ {
DataPortal_Delete(new PKCriteria(_DBID)); DataPortal_Delete(new PKCriteria(_DBID));
} }
[Transactional(TransactionalTypes.TransactionScope)]
private void DataPortal_Delete(PKCriteria criteria) private void DataPortal_Delete(PKCriteria criteria)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Connection.DataPortal_Delete", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Connection.DataPortal_Delete", GetHashCode());
@@ -985,7 +988,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Connection.DataPortal_Delete", ex); throw new DbCslaException("Connection.DataPortal_Delete", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
public static void Remove(SqlConnection cn, int dbid) public static void Remove(SqlConnection cn, int dbid)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Connection.Remove", 0); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Connection.Remove", 0);
@@ -1037,7 +1040,7 @@ namespace VEPROMS.CSLA.Library
{ {
using (SqlConnection cn = Database.VEPROMS_SqlConnection) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
cn.Open(); if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
using (SqlCommand cm = cn.CreateCommand()) using (SqlCommand cm = cn.CreateCommand())
{ {
cm.CommandType = CommandType.StoredProcedure; cm.CommandType = CommandType.StoredProcedure;
@@ -429,8 +429,9 @@ namespace VEPROMS.CSLA.Library
{ {
// if we're not dirty then don't update the database // if we're not dirty then don't update the database
if (!IsDirty) return; if (!IsDirty) return;
using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
_LastChanged = Folder.Add(cn, ref _FolderID, Folder.Get(_ParentID), myConnection, _Name, _Title, _ShortName, _MyFormat, _ManualOrder, _Config, _DTS, _UsrID); _LastChanged = Folder.Add(cn, ref _FolderID, Folder.Get(_ParentID), myConnection, _Name, _Title, _ShortName, _MyFormat, _ManualOrder, _Config, _DTS, _UsrID);
} }
@@ -440,8 +441,9 @@ namespace VEPROMS.CSLA.Library
{ {
// if we're not dirty then don't update the database // if we're not dirty then don't update the database
if (!IsDirty) return; if (!IsDirty) return;
using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
_LastChanged = Folder.Update(cn, ref _FolderID, _ParentID, myConnection.DBID, _Name, _Title, _ShortName, _FormatID, _ManualOrder, _Config, _DTS, _UsrID, ref _LastChanged); _LastChanged = Folder.Update(cn, ref _FolderID, _ParentID, myConnection.DBID, _Name, _Title, _ShortName, _FormatID, _ManualOrder, _Config, _DTS, _UsrID, ref _LastChanged);
} }
@@ -454,8 +456,9 @@ namespace VEPROMS.CSLA.Library
if (!IsDirty) return; if (!IsDirty) return;
// if we're new then don't update the database // if we're new then don't update the database
if (IsNew) return; if (IsNew) return;
using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
Folder.Remove(cn, _FolderID); Folder.Remove(cn, _FolderID);
} }
+16 -13
View File
@@ -1037,7 +1037,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Content.DataPortal_Fetch", ex); throw new DbCslaException("Content.DataPortal_Fetch", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Insert() protected override void DataPortal_Insert()
{ {
try try
@@ -1062,15 +1062,16 @@ namespace VEPROMS.CSLA.Library
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Content.DataPortal_Insert", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Content.DataPortal_Insert", GetHashCode());
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
internal void SQLInsert() internal void SQLInsert()
{ {
if (!IsDirty) return; if (!IsDirty) return;
try try
{ {
_MyFormat?.Update(); _MyFormat?.Update();
using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
using (SqlCommand cm = cn.CreateCommand()) using (SqlCommand cm = cn.CreateCommand())
{ {
cm.CommandType = CommandType.StoredProcedure; cm.CommandType = CommandType.StoredProcedure;
@@ -1123,7 +1124,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Content.SQLInsert", ex); throw new DbCslaException("Content.SQLInsert", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
public static byte[] Add(SqlConnection cn, ref int contentID, string number, string text, int? type, Format myFormat, string config, DateTime dts, string userID) public static byte[] Add(SqlConnection cn, ref int contentID, string number, string text, int? type, Format myFormat, string config, DateTime dts, string userID)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Content.Add", 0); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Content.Add", 0);
@@ -1166,7 +1167,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Content.Add", ex); throw new DbCslaException("Content.Add", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Update() protected override void DataPortal_Update()
{ {
if (!IsDirty) return; // If not dirty - nothing to do if (!IsDirty) return; // If not dirty - nothing to do
@@ -1189,7 +1190,7 @@ namespace VEPROMS.CSLA.Library
if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; if (!ex.Message.EndsWith("has been edited by another user.")) throw ex;
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
internal void SQLUpdate() internal void SQLUpdate()
{ {
if (!IsDirty) return; // If not dirty - nothing to do if (!IsDirty) return; // If not dirty - nothing to do
@@ -1197,8 +1198,9 @@ namespace VEPROMS.CSLA.Library
try try
{ {
_MyFormat?.Update(); _MyFormat?.Update();
using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
if (base.IsDirty) if (base.IsDirty)
{ {
using (SqlCommand cm = cn.CreateCommand()) using (SqlCommand cm = cn.CreateCommand())
@@ -1255,8 +1257,9 @@ namespace VEPROMS.CSLA.Library
if (!IsDirty) return; if (!IsDirty) return;
if (base.IsDirty) if (base.IsDirty)
{ {
using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
if (IsNew) if (IsNew)
_LastChanged = Content.Add(cn, ref _ContentID, _Number, _Text, _Type, _MyFormat, _Config, _DTS, _UserID); _LastChanged = Content.Add(cn, ref _ContentID, _Number, _Text, _Type, _MyFormat, _Config, _DTS, _UserID);
else else
@@ -1275,7 +1278,7 @@ namespace VEPROMS.CSLA.Library
_ContentTransitions?.Update(this); _ContentTransitions?.Update(this);
_MyZContent?.Update(this); _MyZContent?.Update(this);
} }
[Transactional(TransactionalTypes.TransactionScope)]
public static byte[] Update(SqlConnection cn, ref int contentID, string number, string text, int? type, int? formatID, string config, DateTime dts, string userID, ref byte[] lastChanged) public static byte[] Update(SqlConnection cn, ref int contentID, string number, string text, int? type, int? formatID, string config, DateTime dts, string userID, ref byte[] lastChanged)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Content.Update", 0); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Content.Update", 0);
@@ -1314,9 +1317,9 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Content.Update", ex); throw new DbCslaException("Content.Update", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_DeleteSelf() => DataPortal_Delete(new PKCriteria(_ContentID)); protected override void DataPortal_DeleteSelf() => DataPortal_Delete(new PKCriteria(_ContentID));
[Transactional(TransactionalTypes.TransactionScope)]
private void DataPortal_Delete(PKCriteria criteria) private void DataPortal_Delete(PKCriteria criteria)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Content.DataPortal_Delete", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Content.DataPortal_Delete", GetHashCode());
@@ -1341,7 +1344,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Content.DataPortal_Delete", ex); throw new DbCslaException("Content.DataPortal_Delete", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
public static void Remove(SqlConnection cn, int contentID) public static void Remove(SqlConnection cn, int contentID)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Content.Remove", 0); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Content.Remove", 0);
@@ -1393,7 +1396,7 @@ namespace VEPROMS.CSLA.Library
{ {
using (SqlConnection cn = Database.VEPROMS_SqlConnection) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
cn.Open(); if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
using (SqlCommand cm = cn.CreateCommand()) using (SqlCommand cm = cn.CreateCommand())
{ {
cm.CommandType = CommandType.StoredProcedure; cm.CommandType = CommandType.StoredProcedure;
@@ -569,7 +569,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("ContentAudit.DataPortal_Fetch", ex); throw new DbCslaException("ContentAudit.DataPortal_Fetch", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Insert() protected override void DataPortal_Insert()
{ {
try try
@@ -594,14 +594,15 @@ namespace VEPROMS.CSLA.Library
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ContentAudit.DataPortal_Insert", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ContentAudit.DataPortal_Insert", GetHashCode());
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
internal void SQLInsert() internal void SQLInsert()
{ {
if (!IsDirty) return; if (!IsDirty) return;
try try
{ {
using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
using (SqlCommand cm = cn.CreateCommand()) using (SqlCommand cm = cn.CreateCommand())
{ {
cm.CommandType = CommandType.StoredProcedure; cm.CommandType = CommandType.StoredProcedure;
@@ -641,7 +642,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("ContentAudit.SQLInsert", ex); throw new DbCslaException("ContentAudit.SQLInsert", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
public static void Add(SqlConnection cn, ref long auditID, int contentID, string number, string text, int? type, int? formatID, string config, DateTime dts, string userID, int deleteStatus) public static void Add(SqlConnection cn, ref long auditID, int contentID, string number, string text, int? type, int? formatID, string config, DateTime dts, string userID, int deleteStatus)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ContentAudit.Add", 0); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ContentAudit.Add", 0);
@@ -681,7 +682,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("ContentAudit.Add", ex); throw new DbCslaException("ContentAudit.Add", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Update() protected override void DataPortal_Update()
{ {
if (!IsDirty) return; // If not dirty - nothing to do if (!IsDirty) return; // If not dirty - nothing to do
@@ -704,15 +705,16 @@ namespace VEPROMS.CSLA.Library
if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; if (!ex.Message.EndsWith("has been edited by another user.")) throw ex;
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
internal void SQLUpdate() internal void SQLUpdate()
{ {
if (!IsDirty) return; // If not dirty - nothing to do if (!IsDirty) return; // If not dirty - nothing to do
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ContentAudit.SQLUpdate", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ContentAudit.SQLUpdate", GetHashCode());
try try
{ {
using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
if (base.IsDirty) if (base.IsDirty)
{ {
using (SqlCommand cm = cn.CreateCommand()) using (SqlCommand cm = cn.CreateCommand())
@@ -754,8 +756,9 @@ namespace VEPROMS.CSLA.Library
if (!IsDirty) return; if (!IsDirty) return;
if (base.IsDirty) if (base.IsDirty)
{ {
using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
if (IsNew) if (IsNew)
ContentAudit.Add(cn, ref _AuditID, _ContentID, _Number, _Text, _Type, _FormatID, _Config, _DTS, _UserID, _DeleteStatus); ContentAudit.Add(cn, ref _AuditID, _ContentID, _Number, _Text, _Type, _FormatID, _Config, _DTS, _UserID, _DeleteStatus);
else else
@@ -765,7 +768,7 @@ namespace VEPROMS.CSLA.Library
MarkOld(); MarkOld();
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
public static void Update(SqlConnection cn, ref long auditID, int contentID, string number, string text, int? type, int? formatID, string config, DateTime dts, string userID, int deleteStatus) public static void Update(SqlConnection cn, ref long auditID, int contentID, string number, string text, int? type, int? formatID, string config, DateTime dts, string userID, int deleteStatus)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ContentAudit.Update", 0); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ContentAudit.Update", 0);
@@ -800,12 +803,12 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("ContentAudit.Update", ex); throw new DbCslaException("ContentAudit.Update", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_DeleteSelf() protected override void DataPortal_DeleteSelf()
{ {
DataPortal_Delete(new PKCriteria(_AuditID)); DataPortal_Delete(new PKCriteria(_AuditID));
} }
[Transactional(TransactionalTypes.TransactionScope)]
private void DataPortal_Delete(PKCriteria criteria) private void DataPortal_Delete(PKCriteria criteria)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ContentAudit.DataPortal_Delete", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ContentAudit.DataPortal_Delete", GetHashCode());
@@ -830,7 +833,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("ContentAudit.DataPortal_Delete", ex); throw new DbCslaException("ContentAudit.DataPortal_Delete", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
public static void Remove(SqlConnection cn, long auditID) public static void Remove(SqlConnection cn, long auditID)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ContentAudit.Remove", 0); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] ContentAudit.Remove", 0);
@@ -375,8 +375,9 @@ namespace VEPROMS.CSLA.Library
{ {
// if we're not dirty then don't update the database // if we're not dirty then don't update the database
if (!IsDirty) return; if (!IsDirty) return;
using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
_LastChanged = Detail.Add(cn, ref _DetailID, myContent, _ItemType, _Text, _Config, _DTS, _UserID); _LastChanged = Detail.Add(cn, ref _DetailID, myContent, _ItemType, _Text, _Config, _DTS, _UserID);
} }
@@ -386,8 +387,9 @@ namespace VEPROMS.CSLA.Library
{ {
// if we're not dirty then don't update the database // if we're not dirty then don't update the database
if (!IsDirty) return; if (!IsDirty) return;
using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
_LastChanged = Detail.Update(cn, ref _DetailID, myContent.ContentID, _ItemType, _Text, _Config, _DTS, _UserID, ref _LastChanged); _LastChanged = Detail.Update(cn, ref _DetailID, myContent.ContentID, _ItemType, _Text, _Config, _DTS, _UserID, ref _LastChanged);
} }
@@ -400,8 +402,9 @@ namespace VEPROMS.CSLA.Library
if (!IsDirty) return; if (!IsDirty) return;
// if we're new then don't update the database // if we're new then don't update the database
if (IsNew) return; if (IsNew) return;
using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
Detail.Remove(cn, _DetailID); Detail.Remove(cn, _DetailID);
} }
@@ -254,8 +254,9 @@ namespace VEPROMS.CSLA.Library
{ {
// if we're not dirty then don't update the database // if we're not dirty then don't update the database
if (!IsDirty) return; if (!IsDirty) return;
using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
_LastChanged = Item.Add(cn, ref _ItemID, Item.Get((int)_PreviousID), myContent, _DTS, _UserID); _LastChanged = Item.Add(cn, ref _ItemID, Item.Get((int)_PreviousID), myContent, _DTS, _UserID);
} }
@@ -265,8 +266,9 @@ namespace VEPROMS.CSLA.Library
{ {
// if we're not dirty then don't update the database // if we're not dirty then don't update the database
if (!IsDirty) return; if (!IsDirty) return;
using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
_LastChanged = Item.Update(cn, ref _ItemID, _PreviousID, myContent.ContentID, _DTS, _UserID, ref _LastChanged); _LastChanged = Item.Update(cn, ref _ItemID, _PreviousID, myContent.ContentID, _DTS, _UserID, ref _LastChanged);
} }
@@ -279,8 +281,9 @@ namespace VEPROMS.CSLA.Library
if (!IsDirty) return; if (!IsDirty) return;
// if we're new then don't update the database // if we're new then don't update the database
if (IsNew) return; if (IsNew) return;
using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
Item.Remove(cn, _ItemID); Item.Remove(cn, _ItemID);
} }
@@ -324,8 +324,9 @@ namespace VEPROMS.CSLA.Library
{ {
// if we're not dirty then don't update the database // if we're not dirty then don't update the database
if (!IsDirty) return; if (!IsDirty) return;
using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
_LastChanged = Part.Add(cn, myContent, _FromType, _MyItem, _DTS, _UserID); _LastChanged = Part.Add(cn, myContent, _FromType, _MyItem, _DTS, _UserID);
} }
@@ -335,8 +336,9 @@ namespace VEPROMS.CSLA.Library
{ {
// if we're not dirty then don't update the database // if we're not dirty then don't update the database
if (!IsDirty) return; if (!IsDirty) return;
using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
_LastChanged = Part.Update(cn, myContent.ContentID, _FromType, _ItemID, _DTS, _UserID, ref _LastChanged); _LastChanged = Part.Update(cn, myContent.ContentID, _FromType, _ItemID, _DTS, _UserID, ref _LastChanged);
} }
@@ -348,8 +350,9 @@ namespace VEPROMS.CSLA.Library
if (!IsDirty) return; if (!IsDirty) return;
// if we're new then don't update the database // if we're new then don't update the database
if (IsNew) return; if (IsNew) return;
using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
Part.Remove(cn, myContent.ContentID, _FromType); Part.Remove(cn, myContent.ContentID, _FromType);
} }
@@ -402,8 +402,9 @@ namespace VEPROMS.CSLA.Library
{ {
// if we're not dirty then don't update the database // if we're not dirty then don't update the database
if (!IsDirty) return; if (!IsDirty) return;
using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
_LastChanged = RoUsage.Add(cn, ref _ROUsageID, myContent, _ROID, _Config, _DTS, _UserID, _MyRODb); _LastChanged = RoUsage.Add(cn, ref _ROUsageID, myContent, _ROID, _Config, _DTS, _UserID, _MyRODb);
} }
@@ -413,8 +414,9 @@ namespace VEPROMS.CSLA.Library
{ {
// if we're not dirty then don't update the database // if we're not dirty then don't update the database
if (!IsDirty) return; if (!IsDirty) return;
using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
_LastChanged = RoUsage.Update(cn, ref _ROUsageID, myContent.ContentID, _ROID, _Config, _DTS, _UserID, ref _LastChanged, _RODbID); _LastChanged = RoUsage.Update(cn, ref _ROUsageID, myContent.ContentID, _ROID, _Config, _DTS, _UserID, ref _LastChanged, _RODbID);
} }
@@ -427,8 +429,9 @@ namespace VEPROMS.CSLA.Library
if (!IsDirty) return; if (!IsDirty) return;
// if we're new then don't update the database // if we're new then don't update the database
if (IsNew) return; if (IsNew) return;
using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
RoUsage.Remove(cn, _ROUsageID); RoUsage.Remove(cn, _ROUsageID);
} }
@@ -478,8 +478,9 @@ namespace VEPROMS.CSLA.Library
{ {
// if we're not dirty then don't update the database // if we're not dirty then don't update the database
if (!IsDirty) return; if (!IsDirty) return;
using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
string pattern = string.Format(@"<START\]\\v0([^#]*)\\v #Link:Transition(|Range):[0-9]* <CTID={0}>( [0-9]*){{1,2}}\[END>", _TransitionID); string pattern = string.Format(@"<START\]\\v0([^#]*)\\v #Link:Transition(|Range):[0-9]* <CTID={0}>( [0-9]*){{1,2}}\[END>", _TransitionID);
Match m = Regex.Match(myContent.Text, pattern); Match m = Regex.Match(myContent.Text, pattern);
if (m.Groups.Count > 1 && m.Groups[1].Value.ToUpper().Contains("(PAGE ~)")) // B2020-089, check for upper case Page ~ in case step was upper cased if (m.Groups.Count > 1 && m.Groups[1].Value.ToUpper().Contains("(PAGE ~)")) // B2020-089, check for upper case Page ~ in case step was upper cased
@@ -495,8 +496,9 @@ namespace VEPROMS.CSLA.Library
{ {
// if we're not dirty then don't update the database // if we're not dirty then don't update the database
if (!IsDirty) return; if (!IsDirty) return;
using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
_LastChanged = Transition.Update(cn, ref _TransitionID, myContent.ContentID, _ToID, _RangeID, _IsRange, _TranType, _Config, _DTS, _UserID, ref _LastChanged); _LastChanged = Transition.Update(cn, ref _TransitionID, myContent.ContentID, _ToID, _RangeID, _IsRange, _TranType, _Config, _DTS, _UserID, ref _LastChanged);
} }
@@ -509,8 +511,9 @@ namespace VEPROMS.CSLA.Library
if (!IsDirty) return; if (!IsDirty) return;
// if we're new then don't update the database // if we're new then don't update the database
if (IsNew) return; if (IsNew) return;
using (SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
Transition.Remove(cn, _TransitionID); Transition.Remove(cn, _TransitionID);
} }
+132 -267
View File
@@ -13,8 +13,6 @@ using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
using Csla.Validation; using Csla.Validation;
@@ -58,6 +56,7 @@ namespace VEPROMS.CSLA.Library
} }
#endregion #endregion
#region Collection #region Collection
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static List<DROUsage> _CacheList = new List<DROUsage>(); private static List<DROUsage> _CacheList = new List<DROUsage>();
protected static void AddToCache(DROUsage dROUsage) protected static void AddToCache(DROUsage dROUsage)
{ {
@@ -67,6 +66,7 @@ namespace VEPROMS.CSLA.Library
{ {
while (_CacheList.Contains(dROUsage)) _CacheList.Remove(dROUsage); // In RemoveFromCache while (_CacheList.Contains(dROUsage)) _CacheList.Remove(dROUsage); // In RemoveFromCache
} }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static Dictionary<string, List<DROUsage>> _CacheByPrimaryKey = new Dictionary<string, List<DROUsage>>(); private static Dictionary<string, List<DROUsage>> _CacheByPrimaryKey = new Dictionary<string, List<DROUsage>>();
private static void ConvertListToDictionary() private static void ConvertListToDictionary()
{ {
@@ -92,15 +92,9 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
#region Business Methods #region Business Methods
private string _ErrorMessage = string.Empty; private string _ErrorMessage = string.Empty;
public string ErrorMessage public string ErrorMessage => _ErrorMessage;
{
get { return _ErrorMessage; }
}
private static int _nextDROUsageID = -1; private static int _nextDROUsageID = -1;
public static int NextDROUsageID public static int NextDROUsageID => _nextDROUsageID--;
{
get { return _nextDROUsageID--; }
}
private int _DROUsageID; private int _DROUsageID;
[System.ComponentModel.DataObjectField(true, true)] [System.ComponentModel.DataObjectField(true, true)]
public int DROUsageID public int DROUsageID
@@ -261,7 +255,7 @@ namespace VEPROMS.CSLA.Library
if (base.IsDirty || list.Contains(this)) if (base.IsDirty || list.Contains(this))
return base.IsDirty; return base.IsDirty;
list.Add(this); list.Add(this);
return base.IsDirty || (_MyDocument == null ? false : _MyDocument.IsDirtyList(list)) || (_MyRODb == null ? false : _MyRODb.IsDirtyList(list)); return base.IsDirty || (_MyDocument != null && _MyDocument.IsDirtyList(list)) || (_MyRODb != null && _MyRODb.IsDirtyList(list));
} }
public override bool IsValid public override bool IsValid
{ {
@@ -270,28 +264,16 @@ namespace VEPROMS.CSLA.Library
public bool IsValidList(List<object> list) public bool IsValidList(List<object> list)
{ {
if (list.Contains(this)) if (list.Contains(this))
return (IsNew && !IsDirty) ? true : base.IsValid; return (IsNew && !IsDirty) || base.IsValid;
list.Add(this); list.Add(this);
return ((IsNew && !IsDirty) ? true : base.IsValid) && (_MyDocument == null ? true : _MyDocument.IsValidList(list)) && (_MyRODb == null ? true : _MyRODb.IsValidList(list)); return ((IsNew && !IsDirty) || base.IsValid) && (_MyDocument == null || _MyDocument.IsValidList(list)) && (_MyRODb == null || _MyRODb.IsValidList(list));
} }
// CSLATODO: Replace base DROUsage.ToString function as necessary
/// <summary>
/// Overrides Base ToString
/// </summary>
/// <returns>A string representation of current DROUsage</returns>
//public override string ToString()
//{
// return base.ToString();
//}
// CSLATODO: Check DROUsage.GetIdValue to assure that the ID returned is unique // CSLATODO: Check DROUsage.GetIdValue to assure that the ID returned is unique
/// <summary> /// <summary>
/// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// Overrides Base GetIdValue - Used internally by CSLA to determine equality
/// </summary> /// </summary>
/// <returns>A Unique ID for the current DROUsage</returns> /// <returns>A Unique ID for the current DROUsage</returns>
protected override object GetIdValue() protected override object GetIdValue() => MyDROUsageUnique; // Absolutely Unique ID
{
return MyDROUsageUnique; // Absolutely Unique ID
}
#endregion #endregion
#region ValidationRules #region ValidationRules
[NonSerialized] [NonSerialized]
@@ -321,8 +303,8 @@ namespace VEPROMS.CSLA.Library
get get
{ {
IVEHasBrokenRules hasBrokenRules = HasBrokenRules; IVEHasBrokenRules hasBrokenRules = HasBrokenRules;
if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; if (Equals(hasBrokenRules)) return BrokenRulesCollection;
return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); return (hasBrokenRules?.BrokenRules);
} }
} }
protected override void AddBusinessRules() protected override void AddBusinessRules()
@@ -369,35 +351,11 @@ namespace VEPROMS.CSLA.Library
} }
return true; return true;
} }
// Sample data comparison validation rule
//private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e)
//{
// if (_started > _ended)
// {
// e.Description = "Start date can't be after end date";
// return false;
// }
// else
// return true;
//}
#endregion #endregion
#region Authorization Rules #region Authorization Rules
protected override void AddAuthorizationRules() protected override void AddAuthorizationRules()
{ {
//CSLATODO: Who can read/write which fields //CSLATODO: Who can read/write which fields
//AuthorizationRules.AllowRead(DROUsageID, "<Role(s)>");
//AuthorizationRules.AllowRead(DocID, "<Role(s)>");
//AuthorizationRules.AllowRead(ROID, "<Role(s)>");
//AuthorizationRules.AllowRead(Config, "<Role(s)>");
//AuthorizationRules.AllowRead(DTS, "<Role(s)>");
//AuthorizationRules.AllowRead(UserID, "<Role(s)>");
//AuthorizationRules.AllowRead(RODbID, "<Role(s)>");
//AuthorizationRules.AllowWrite(DocID, "<Role(s)>");
//AuthorizationRules.AllowWrite(ROID, "<Role(s)>");
//AuthorizationRules.AllowWrite(Config, "<Role(s)>");
//AuthorizationRules.AllowWrite(DTS, "<Role(s)>");
//AuthorizationRules.AllowWrite(UserID, "<Role(s)>");
//AuthorizationRules.AllowWrite(RODbID, "<Role(s)>");
_DROUsageExtension.AddAuthorizationRules(AuthorizationRules); _DROUsageExtension.AddAuthorizationRules(AuthorizationRules);
} }
protected override void AddInstanceAuthorizationRules() protected override void AddInstanceAuthorizationRules()
@@ -405,42 +363,14 @@ namespace VEPROMS.CSLA.Library
//CSLATODO: Who can read/write which fields //CSLATODO: Who can read/write which fields
_DROUsageExtension.AddInstanceAuthorizationRules(AuthorizationRules); _DROUsageExtension.AddInstanceAuthorizationRules(AuthorizationRules);
} }
public static bool CanAddObject()
{
// CSLATODO: Can Add Authorization
//return Csla.ApplicationContext.User.IsInRole("ProjectManager");
return true;
}
public static bool CanGetObject()
{
// CSLATODO: CanGet Authorization
return true;
}
public static bool CanDeleteObject()
{
// CSLATODO: CanDelete Authorization
//bool result = false;
//if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true;
//if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true;
//return result;
return true;
}
public static bool CanEditObject()
{
// CSLATODO: CanEdit Authorization
//return Csla.ApplicationContext.User.IsInRole("ProjectManager");
return true;
}
#endregion #endregion
#region Factory Methods #region Factory Methods
public int CurrentEditLevel public int CurrentEditLevel => EditLevel;
{ get { return EditLevel; } }
private static int _DROUsageUnique = 0; private static int _DROUsageUnique = 0;
protected static int DROUsageUnique protected static int DROUsageUnique => ++_DROUsageUnique;
{ get { return ++_DROUsageUnique; } } private readonly int _MyDROUsageUnique = DROUsageUnique;
private int _MyDROUsageUnique = DROUsageUnique; // Absolutely Unique ID - Editable
public int MyDROUsageUnique // Absolutely Unique ID - Editable public int MyDROUsageUnique => _MyDROUsageUnique;
{ get { return _MyDROUsageUnique; } }
protected DROUsage() protected DROUsage()
{/* require use of factory methods */ {/* require use of factory methods */
AddToCache(this); AddToCache(this);
@@ -449,15 +379,11 @@ namespace VEPROMS.CSLA.Library
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~DROUsage() ~DROUsage()
{ {
_CountFinalized++; _CountFinalized++;
@@ -482,8 +408,6 @@ namespace VEPROMS.CSLA.Library
} }
public static DROUsage New() public static DROUsage New()
{ {
if (!CanAddObject())
throw new System.Security.SecurityException("User not authorized to add a DROUsage");
try try
{ {
return DataPortal.Create<DROUsage>(); return DataPortal.Create<DROUsage>();
@@ -554,8 +478,6 @@ namespace VEPROMS.CSLA.Library
} }
public static DROUsage Get(int dROUsageID) public static DROUsage Get(int dROUsageID)
{ {
if (!CanGetObject())
throw new System.Security.SecurityException("User not authorized to view a DROUsage");
try try
{ {
DROUsage tmp = GetCachedByPrimaryKey(dROUsageID); DROUsage tmp = GetCachedByPrimaryKey(dROUsageID);
@@ -581,14 +503,9 @@ namespace VEPROMS.CSLA.Library
if (dr.Read()) return new DROUsage(dr); if (dr.Read()) return new DROUsage(dr);
return null; return null;
} }
internal DROUsage(SafeDataReader dr) internal DROUsage(SafeDataReader dr) => ReadData(dr);
{
ReadData(dr);
}
public static void Delete(int dROUsageID) public static void Delete(int dROUsageID)
{ {
if (!CanDeleteObject())
throw new System.Security.SecurityException("User not authorized to remove a DROUsage");
try try
{ {
DataPortal.Delete(new PKCriteria(dROUsageID)); DataPortal.Delete(new PKCriteria(dROUsageID));
@@ -600,12 +517,6 @@ namespace VEPROMS.CSLA.Library
} }
public override DROUsage Save() public override DROUsage Save()
{ {
if (IsDeleted && !CanDeleteObject())
throw new System.Security.SecurityException("User not authorized to remove a DROUsage");
else if (IsNew && !CanAddObject())
throw new System.Security.SecurityException("User not authorized to add a DROUsage");
else if (!CanEditObject())
throw new System.Security.SecurityException("User not authorized to update a DROUsage");
try try
{ {
BuildRefreshList(); BuildRefreshList();
@@ -625,13 +536,9 @@ namespace VEPROMS.CSLA.Library
[Serializable()] [Serializable()]
protected class PKCriteria protected class PKCriteria
{ {
private int _DROUsageID; private readonly int _DROUsageID;
public int DROUsageID public int DROUsageID => _DROUsageID;
{ get { return _DROUsageID; } } public PKCriteria(int dROUsageID) => _DROUsageID = dROUsageID;
public PKCriteria(int dROUsageID)
{
_DROUsageID = dROUsageID;
}
} }
// CSLATODO: If Create needs to access DB - It should not be marked RunLocal // CSLATODO: If Create needs to access DB - It should not be marked RunLocal
[RunLocal()] [RunLocal()]
@@ -703,7 +610,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("DROUsage.DataPortal_Fetch", ex); throw new DbCslaException("DROUsage.DataPortal_Fetch", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Insert() protected override void DataPortal_Insert()
{ {
try try
@@ -728,40 +635,48 @@ namespace VEPROMS.CSLA.Library
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DROUsage.DataPortal_Insert", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DROUsage.DataPortal_Insert", GetHashCode());
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
internal void SQLInsert() internal void SQLInsert()
{ {
if (!this.IsDirty) return; if (!IsDirty) return;
try try
{ {
if (_MyDocument != null) _MyDocument.Update(); _MyDocument?.Update();
if (_MyRODb != null) _MyRODb.Update(); _MyRODb?.Update();
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = Database.VEPROMS_SqlConnection)
using (SqlCommand cm = cn.CreateCommand())
{ {
cm.CommandType = CommandType.StoredProcedure; if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
cm.CommandTimeout = Database.SQLTimeout; using (SqlCommand cm = cn.CreateCommand())
cm.CommandText = "addDROUsage"; {
// Input All Fields - Except Calculated Columns cm.CommandType = CommandType.StoredProcedure;
cm.Parameters.AddWithValue("@DocID", DocID); cm.CommandTimeout = Database.SQLTimeout;
cm.Parameters.AddWithValue("@ROID", _ROID); cm.CommandText = "addDROUsage";
cm.Parameters.AddWithValue("@Config", _Config); // Input All Fields - Except Calculated Columns
if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); cm.Parameters.AddWithValue("@DocID", DocID);
cm.Parameters.AddWithValue("@UserID", _UserID); cm.Parameters.AddWithValue("@ROID", _ROID);
cm.Parameters.AddWithValue("@RODbID", RODbID); cm.Parameters.AddWithValue("@Config", _Config);
// Output Calculated Columns if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS);
SqlParameter param_DROUsageID = new SqlParameter("@newDROUsageID", SqlDbType.Int); cm.Parameters.AddWithValue("@UserID", _UserID);
param_DROUsageID.Direction = ParameterDirection.Output; cm.Parameters.AddWithValue("@RODbID", RODbID);
cm.Parameters.Add(param_DROUsageID); // Output Calculated Columns
SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); SqlParameter param_DROUsageID = new SqlParameter("@newDROUsageID", SqlDbType.Int)
param_LastChanged.Direction = ParameterDirection.Output; {
cm.Parameters.Add(param_LastChanged); Direction = ParameterDirection.Output
// CSLATODO: Define any additional output parameters };
cm.ExecuteNonQuery(); cm.Parameters.Add(param_DROUsageID);
// Save all values being returned from the Procedure SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp)
_DROUsageID = (int)cm.Parameters["@newDROUsageID"].Value; {
_LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; Direction = ParameterDirection.Output
};
cm.Parameters.Add(param_LastChanged);
// CSLATODO: Define any additional output parameters
cm.ExecuteNonQuery();
// Save all values being returned from the Procedure
_DROUsageID = (int)cm.Parameters["@newDROUsageID"].Value;
_LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value;
}
} }
MarkOld(); MarkOld();
// update child objects // update child objects
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DROUsage.SQLInsert", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DROUsage.SQLInsert", GetHashCode());
@@ -773,7 +688,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("DROUsage.SQLInsert", ex); throw new DbCslaException("DROUsage.SQLInsert", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
public static byte[] Add(SqlConnection cn, ref int dROUsageID, Document myDocument, string roid, string config, DateTime dts, string userID, RODb myRODb) public static byte[] Add(SqlConnection cn, ref int dROUsageID, Document myDocument, string roid, string config, DateTime dts, string userID, RODb myRODb)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DROUsage.Add", 0); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DROUsage.Add", 0);
@@ -792,11 +707,15 @@ namespace VEPROMS.CSLA.Library
cm.Parameters.AddWithValue("@UserID", userID); cm.Parameters.AddWithValue("@UserID", userID);
cm.Parameters.AddWithValue("@RODbID", myRODb.RODbID); cm.Parameters.AddWithValue("@RODbID", myRODb.RODbID);
// Output Calculated Columns // Output Calculated Columns
SqlParameter param_DROUsageID = new SqlParameter("@newDROUsageID", SqlDbType.Int); SqlParameter param_DROUsageID = new SqlParameter("@newDROUsageID", SqlDbType.Int)
param_DROUsageID.Direction = ParameterDirection.Output; {
Direction = ParameterDirection.Output
};
cm.Parameters.Add(param_DROUsageID); cm.Parameters.Add(param_DROUsageID);
SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp)
param_LastChanged.Direction = ParameterDirection.Output; {
Direction = ParameterDirection.Output
};
cm.Parameters.Add(param_LastChanged); cm.Parameters.Add(param_LastChanged);
// CSLATODO: Define any additional output parameters // CSLATODO: Define any additional output parameters
cm.ExecuteNonQuery(); cm.ExecuteNonQuery();
@@ -811,7 +730,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("DROUsage.Add", ex); throw new DbCslaException("DROUsage.Add", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Update() protected override void DataPortal_Update()
{ {
if (!IsDirty) return; // If not dirty - nothing to do if (!IsDirty) return; // If not dirty - nothing to do
@@ -834,42 +753,48 @@ namespace VEPROMS.CSLA.Library
if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; if (!ex.Message.EndsWith("has been edited by another user.")) throw ex;
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
internal void SQLUpdate() internal void SQLUpdate()
{ {
if (!IsDirty) return; // If not dirty - nothing to do if (!IsDirty) return; // If not dirty - nothing to do
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DROUsage.SQLUpdate", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DROUsage.SQLUpdate", GetHashCode());
try try
{ {
if (_MyDocument != null) _MyDocument.Update(); _MyDocument?.Update();
if (_MyRODb != null) _MyRODb.Update(); _MyRODb?.Update();
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = Database.VEPROMS_SqlConnection)
if (base.IsDirty)
{ {
using (SqlCommand cm = cn.CreateCommand()) if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
if (base.IsDirty)
{ {
cm.CommandType = CommandType.StoredProcedure; using (SqlCommand cm = cn.CreateCommand())
cm.CommandTimeout = Database.SQLTimeout; {
cm.CommandText = "updateDROUsage"; cm.CommandType = CommandType.StoredProcedure;
// All Fields including Calculated Fields cm.CommandTimeout = Database.SQLTimeout;
cm.Parameters.AddWithValue("@DROUsageID", _DROUsageID); cm.CommandText = "updateDROUsage";
cm.Parameters.AddWithValue("@DocID", DocID); // All Fields including Calculated Fields
cm.Parameters.AddWithValue("@ROID", _ROID); cm.Parameters.AddWithValue("@DROUsageID", _DROUsageID);
cm.Parameters.AddWithValue("@Config", _Config); cm.Parameters.AddWithValue("@DocID", DocID);
if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); cm.Parameters.AddWithValue("@ROID", _ROID);
cm.Parameters.AddWithValue("@UserID", _UserID); cm.Parameters.AddWithValue("@Config", _Config);
cm.Parameters.AddWithValue("@LastChanged", _LastChanged); if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS);
cm.Parameters.AddWithValue("@RODbID", RODbID); cm.Parameters.AddWithValue("@UserID", _UserID);
// Output Calculated Columns cm.Parameters.AddWithValue("@LastChanged", _LastChanged);
SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); cm.Parameters.AddWithValue("@RODbID", RODbID);
param_LastChanged.Direction = ParameterDirection.Output; // Output Calculated Columns
cm.Parameters.Add(param_LastChanged); SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp)
// CSLATODO: Define any additional output parameters {
cm.ExecuteNonQuery(); Direction = ParameterDirection.Output
// Save all values being returned from the Procedure };
_LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; cm.Parameters.Add(param_LastChanged);
// CSLATODO: Define any additional output parameters
cm.ExecuteNonQuery();
// Save all values being returned from the Procedure
_LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value;
}
} }
} }
MarkOld(); MarkOld();
// use the open connection to update child objects // use the open connection to update child objects
} }
@@ -882,18 +807,22 @@ namespace VEPROMS.CSLA.Library
} }
internal void Update() internal void Update()
{ {
if (!this.IsDirty) return; if (!IsDirty) return;
if (base.IsDirty) if (base.IsDirty)
{ {
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = Database.VEPROMS_SqlConnection)
if (IsNew) {
_LastChanged = DROUsage.Add(cn, ref _DROUsageID, _MyDocument, _ROID, _Config, _DTS, _UserID, _MyRODb); if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
else if (IsNew)
_LastChanged = DROUsage.Update(cn, ref _DROUsageID, _DocID, _ROID, _Config, _DTS, _UserID, ref _LastChanged, _RODbID); _LastChanged = DROUsage.Add(cn, ref _DROUsageID, _MyDocument, _ROID, _Config, _DTS, _UserID, _MyRODb);
else
_LastChanged = DROUsage.Update(cn, ref _DROUsageID, _DocID, _ROID, _Config, _DTS, _UserID, ref _LastChanged, _RODbID);
}
MarkOld(); MarkOld();
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
public static byte[] Update(SqlConnection cn, ref int dROUsageID, int docID, string roid, string config, DateTime dts, string userID, ref byte[] lastChanged, int rODbID) public static byte[] Update(SqlConnection cn, ref int dROUsageID, int docID, string roid, string config, DateTime dts, string userID, ref byte[] lastChanged, int rODbID)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DROUsage.Update", 0); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DROUsage.Update", 0);
@@ -914,8 +843,10 @@ namespace VEPROMS.CSLA.Library
cm.Parameters.AddWithValue("@LastChanged", lastChanged); cm.Parameters.AddWithValue("@LastChanged", lastChanged);
cm.Parameters.AddWithValue("@RODbID", rODbID); cm.Parameters.AddWithValue("@RODbID", rODbID);
// Output Calculated Columns // Output Calculated Columns
SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp)
param_LastChanged.Direction = ParameterDirection.Output; {
Direction = ParameterDirection.Output
};
cm.Parameters.Add(param_LastChanged); cm.Parameters.Add(param_LastChanged);
// CSLATODO: Define any additional output parameters // CSLATODO: Define any additional output parameters
cm.ExecuteNonQuery(); cm.ExecuteNonQuery();
@@ -929,12 +860,9 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("DROUsage.Update", ex); throw new DbCslaException("DROUsage.Update", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_DeleteSelf() protected override void DataPortal_DeleteSelf() => DataPortal_Delete(new PKCriteria(_DROUsageID));
{
DataPortal_Delete(new PKCriteria(_DROUsageID));
}
[Transactional(TransactionalTypes.TransactionScope)]
private void DataPortal_Delete(PKCriteria criteria) private void DataPortal_Delete(PKCriteria criteria)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DROUsage.DataPortal_Delete", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DROUsage.DataPortal_Delete", GetHashCode());
@@ -959,7 +887,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("DROUsage.DataPortal_Delete", ex); throw new DbCslaException("DROUsage.DataPortal_Delete", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
public static void Remove(SqlConnection cn, int dROUsageID) public static void Remove(SqlConnection cn, int dROUsageID)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DROUsage.Remove", 0); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DROUsage.Remove", 0);
@@ -1000,16 +928,10 @@ namespace VEPROMS.CSLA.Library
[Serializable()] [Serializable()]
private class ExistsCommand : CommandBase private class ExistsCommand : CommandBase
{ {
private int _DROUsageID; private readonly int _DROUsageID;
private bool _exists; private bool _exists;
public bool Exists public bool Exists => _exists;
{ public ExistsCommand(int dROUsageID) => _DROUsageID = dROUsageID;
get { return _exists; }
}
public ExistsCommand(int dROUsageID)
{
_DROUsageID = dROUsageID;
}
protected override void DataPortal_Execute() protected override void DataPortal_Execute()
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DROUsage.DataPortal_Execute", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DROUsage.DataPortal_Execute", GetHashCode());
@@ -1017,7 +939,7 @@ namespace VEPROMS.CSLA.Library
{ {
using (SqlConnection cn = Database.VEPROMS_SqlConnection) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
cn.Open(); if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
using (SqlCommand cm = cn.CreateCommand()) using (SqlCommand cm = cn.CreateCommand())
{ {
cm.CommandType = CommandType.StoredProcedure; cm.CommandType = CommandType.StoredProcedure;
@@ -1039,7 +961,7 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
// Standard Default Code // Standard Default Code
#region extension #region extension
DROUsageExtension _DROUsageExtension = new DROUsageExtension(); readonly DROUsageExtension _DROUsageExtension = new DROUsageExtension();
[Serializable()] [Serializable()]
partial class DROUsageExtension : extensionBase partial class DROUsageExtension : extensionBase
{ {
@@ -1048,18 +970,9 @@ namespace VEPROMS.CSLA.Library
class extensionBase class extensionBase
{ {
// Default Values // Default Values
public virtual int DefaultDocID public virtual int DefaultDocID => 0;
{ public virtual DateTime DefaultDTS => DateTime.Now;
get { return 0; } public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID;
}
public virtual DateTime DefaultDTS
{
get { return DateTime.Now; }
}
public virtual string DefaultUserID
{
get { return Volian.Base.Library.VlnSettings.UserID; }
}
// Authorization Rules // Authorization Rules
public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules)
{ {
@@ -1088,61 +1001,13 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is DROUsage) if (destType == typeof(string) && value is DROUsage usage)
{ {
// Return the ToString value // Return the ToString value
return ((DROUsage)value).ToString(); return usage.ToString();
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
} }
#endregion #endregion
} // Namespace } // Namespace
//// The following is a sample Extension File. You can use it to create DROUsageExt.cs
//using System;
//using System.Collections.Generic;
//using System.Text;
//using Csla;
//namespace VEPROMS.CSLA.Library
//{
// public partial class DROUsage
// {
// partial class DROUsageExtension : extensionBase
// {
// // CSLATODO: Override automatic defaults
// public virtual int DefaultDocID
// {
// get { return 0; }
// }
// public virtual DateTime DefaultDTS
// {
// get { return DateTime.Now; }
// }
// public virtual string DefaultUserID
// {
// get { return Environment.UserName.ToUpper(); }
// }
// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules)
// {
// //rules.AllowRead(Dbid, "<Role(s)>");
// }
// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules)
// {
// //rules.AllowInstanceRead(Dbid, "<Role(s)>");
// }
// public new void AddValidationRules(Csla.Validation.ValidationRules rules)
// {
// rules.AddRule(
// Csla.Validation.CommonRules.StringMaxLength,
// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100));
// }
// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules)
// {
// rules.AddInstanceRule(/* Instance Validation Rule */);
// }
// }
// }
//}
@@ -13,8 +13,6 @@ using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
namespace VEPROMS.CSLA.Library namespace VEPROMS.CSLA.Library
@@ -28,14 +26,12 @@ namespace VEPROMS.CSLA.Library
public partial class DROUsageInfo : ReadOnlyBase<DROUsageInfo>, IDisposable public partial class DROUsageInfo : ReadOnlyBase<DROUsageInfo>, IDisposable
{ {
public event DROUsageInfoEvent Changed; public event DROUsageInfoEvent Changed;
private void OnChange() private void OnChange() => Changed?.Invoke(this);
{
if (Changed != null) Changed(this);
}
#region Log4Net #region Log4Net
private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endregion #endregion
#region Collection #region Collection
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static List<DROUsageInfo> _CacheList = new List<DROUsageInfo>(); private static List<DROUsageInfo> _CacheList = new List<DROUsageInfo>();
protected static void AddToCache(DROUsageInfo dROUsageInfo) protected static void AddToCache(DROUsageInfo dROUsageInfo)
{ {
@@ -45,6 +41,7 @@ namespace VEPROMS.CSLA.Library
{ {
while (_CacheList.Contains(dROUsageInfo)) _CacheList.Remove(dROUsageInfo); // In RemoveFromCache while (_CacheList.Contains(dROUsageInfo)) _CacheList.Remove(dROUsageInfo); // In RemoveFromCache
} }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static Dictionary<string, List<DROUsageInfo>> _CacheByPrimaryKey = new Dictionary<string, List<DROUsageInfo>>(); private static Dictionary<string, List<DROUsageInfo>> _CacheByPrimaryKey = new Dictionary<string, List<DROUsageInfo>>();
private static void ConvertListToDictionary() private static void ConvertListToDictionary()
{ {
@@ -74,21 +71,8 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
#region Business Methods #region Business Methods
private string _ErrorMessage = string.Empty; private string _ErrorMessage = string.Empty;
public string ErrorMessage public string ErrorMessage => _ErrorMessage;
{
get { return _ErrorMessage; }
}
protected DROUsage _Editable; protected DROUsage _Editable;
private IVEHasBrokenRules HasBrokenRules
{
get
{
IVEHasBrokenRules hasBrokenRules = null;
if (_Editable != null)
hasBrokenRules = _Editable.HasBrokenRules;
return hasBrokenRules;
}
}
private int _DROUsageID; private int _DROUsageID;
[System.ComponentModel.DataObjectField(true, true)] [System.ComponentModel.DataObjectField(true, true)]
public int DROUsageID public int DROUsageID
@@ -175,32 +159,19 @@ namespace VEPROMS.CSLA.Library
return _MyRODb; return _MyRODb;
} }
} }
// CSLATODO: Replace base DROUsageInfo.ToString function as necessary
/// <summary>
/// Overrides Base ToString
/// </summary>
/// <returns>A string representation of current DROUsageInfo</returns>
//public override string ToString()
//{
// return base.ToString();
//}
// CSLATODO: Check DROUsageInfo.GetIdValue to assure that the ID returned is unique // CSLATODO: Check DROUsageInfo.GetIdValue to assure that the ID returned is unique
/// <summary> /// <summary>
/// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// Overrides Base GetIdValue - Used internally by CSLA to determine equality
/// </summary> /// </summary>
/// <returns>A Unique ID for the current DROUsageInfo</returns> /// <returns>A Unique ID for the current DROUsageInfo</returns>
protected override object GetIdValue() protected override object GetIdValue() => MyDROUsageInfoUnique; // Absolutely Unique ID
{
return MyDROUsageInfoUnique; // Absolutely Unique ID
}
#endregion #endregion
#region Factory Methods #region Factory Methods
private static int _DROUsageInfoUnique = 0; private static int _DROUsageInfoUnique = 0;
private static int DROUsageInfoUnique private static int DROUsageInfoUnique => ++_DROUsageInfoUnique;
{ get { return ++_DROUsageInfoUnique; } } private readonly int _MyDROUsageInfoUnique = DROUsageInfoUnique;
private int _MyDROUsageInfoUnique = DROUsageInfoUnique; // Absolutely Unique ID - Info
public int MyDROUsageInfoUnique // Absolutely Unique ID - Info public int MyDROUsageInfoUnique => _MyDROUsageInfoUnique;
{ get { return _MyDROUsageInfoUnique; } }
protected DROUsageInfo() protected DROUsageInfo()
{/* require use of factory methods */ {/* require use of factory methods */
AddToCache(this); AddToCache(this);
@@ -209,15 +180,11 @@ namespace VEPROMS.CSLA.Library
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~DROUsageInfo() ~DROUsageInfo()
{ {
_CountFinalized++; _CountFinalized++;
@@ -234,10 +201,7 @@ namespace VEPROMS.CSLA.Library
if (listDROUsageInfo.Count == 0) // If there are no items left in the list if (listDROUsageInfo.Count == 0) // If there are no items left in the list
_CacheByPrimaryKey.Remove(DROUsageID.ToString()); // remove the list _CacheByPrimaryKey.Remove(DROUsageID.ToString()); // remove the list
} }
public virtual DROUsage Get() public virtual DROUsage Get() => _Editable = DROUsage.Get(_DROUsageID);
{
return _Editable = DROUsage.Get(_DROUsageID);
}
public static void Refresh(DROUsage tmp) public static void Refresh(DROUsage tmp)
{ {
string key = tmp.DROUsageID.ToString(); string key = tmp.DROUsageID.ToString();
@@ -250,22 +214,22 @@ namespace VEPROMS.CSLA.Library
{ {
if (_DocID != tmp.DocID) if (_DocID != tmp.DocID)
{ {
if (MyDocument != null) MyDocument.RefreshDocumentDROUsages(); // Update List for old value MyDocument?.RefreshDocumentDROUsages(); // Update List for old value
_DocID = tmp.DocID; // Update the value _DocID = tmp.DocID; // Update the value
} }
_MyDocument = null; // Reset list so that the next line gets a new list _MyDocument = null; // Reset list so that the next line gets a new list
if (MyDocument != null) MyDocument.RefreshDocumentDROUsages(); // Update List for new value MyDocument?.RefreshDocumentDROUsages(); // Update List for new value
_ROID = tmp.ROID; _ROID = tmp.ROID;
_Config = tmp.Config; _Config = tmp.Config;
_DTS = tmp.DTS; _DTS = tmp.DTS;
_UserID = tmp.UserID; _UserID = tmp.UserID;
if (_RODbID != tmp.RODbID) if (_RODbID != tmp.RODbID)
{ {
if (MyRODb != null) MyRODb.RefreshRODbDROUsages(); // Update List for old value MyRODb?.RefreshRODbDROUsages(); // Update List for old value
_RODbID = tmp.RODbID; // Update the value _RODbID = tmp.RODbID; // Update the value
} }
_MyRODb = null; // Reset list so that the next line gets a new list _MyRODb = null; // Reset list so that the next line gets a new list
if (MyRODb != null) MyRODb.RefreshRODbDROUsages(); // Update List for new value MyRODb?.RefreshRODbDROUsages(); // Update List for new value
_DROUsageInfoExtension.Refresh(this); _DROUsageInfoExtension.Refresh(this);
OnChange();// raise an event OnChange();// raise an event
} }
@@ -285,11 +249,11 @@ namespace VEPROMS.CSLA.Library
_UserID = tmp.UserID; _UserID = tmp.UserID;
if (_RODbID != tmp.RODbID) if (_RODbID != tmp.RODbID)
{ {
if (MyRODb != null) MyRODb.RefreshRODbDROUsages(); // Update List for old value MyRODb?.RefreshRODbDROUsages(); // Update List for old value
_RODbID = tmp.RODbID; // Update the value _RODbID = tmp.RODbID; // Update the value
} }
_MyRODb = null; // Reset list so that the next line gets a new list _MyRODb = null; // Reset list so that the next line gets a new list
if (MyRODb != null) MyRODb.RefreshRODbDROUsages(); // Update List for new value MyRODb?.RefreshRODbDROUsages(); // Update List for new value
_DROUsageInfoExtension.Refresh(this); _DROUsageInfoExtension.Refresh(this);
OnChange();// raise an event OnChange();// raise an event
} }
@@ -305,11 +269,11 @@ namespace VEPROMS.CSLA.Library
{ {
if (_DocID != tmp.DocID) if (_DocID != tmp.DocID)
{ {
if (MyDocument != null) MyDocument.RefreshDocumentDROUsages(); // Update List for old value MyDocument?.RefreshDocumentDROUsages(); // Update List for old value
_DocID = tmp.DocID; // Update the value _DocID = tmp.DocID; // Update the value
} }
_MyDocument = null; // Reset list so that the next line gets a new list _MyDocument = null; // Reset list so that the next line gets a new list
if (MyDocument != null) MyDocument.RefreshDocumentDROUsages(); // Update List for new value MyDocument?.RefreshDocumentDROUsages(); // Update List for new value
_ROID = tmp.ROID; _ROID = tmp.ROID;
_Config = tmp.Config; _Config = tmp.Config;
_DTS = tmp.DTS; _DTS = tmp.DTS;
@@ -319,8 +283,6 @@ namespace VEPROMS.CSLA.Library
} }
public static DROUsageInfo Get(int dROUsageID) public static DROUsageInfo Get(int dROUsageID)
{ {
//if (!CanGetObject())
// throw new System.Security.SecurityException("User not authorized to view a DROUsage");
try try
{ {
DROUsageInfo tmp = GetCachedByPrimaryKey(dROUsageID); DROUsageInfo tmp = GetCachedByPrimaryKey(dROUsageID);
@@ -359,13 +321,9 @@ namespace VEPROMS.CSLA.Library
[Serializable()] [Serializable()]
protected class PKCriteria protected class PKCriteria
{ {
private int _DROUsageID; private readonly int _DROUsageID;
public int DROUsageID public int DROUsageID => _DROUsageID;
{ get { return _DROUsageID; } } public PKCriteria(int dROUsageID) => _DROUsageID = dROUsageID;
public PKCriteria(int dROUsageID)
{
_DROUsageID = dROUsageID;
}
} }
private void ReadData(SafeDataReader dr) private void ReadData(SafeDataReader dr)
{ {
@@ -426,7 +384,7 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
// Standard Refresh // Standard Refresh
#region extension #region extension
DROUsageInfoExtension _DROUsageInfoExtension = new DROUsageInfoExtension(); readonly DROUsageInfoExtension _DROUsageInfoExtension = new DROUsageInfoExtension();
[Serializable()] [Serializable()]
partial class DROUsageInfoExtension : extensionBase { } partial class DROUsageInfoExtension : extensionBase { }
[Serializable()] [Serializable()]
@@ -442,10 +400,10 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is DROUsageInfo) if (destType == typeof(string) && value is DROUsageInfo info)
{ {
// Return the ToString value // Return the ToString value
return ((DROUsageInfo)value).ToString(); return info.ToString();
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
@@ -13,8 +13,6 @@ using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
namespace VEPROMS.CSLA.Library namespace VEPROMS.CSLA.Library
@@ -28,11 +26,10 @@ namespace VEPROMS.CSLA.Library
{ {
#region Log4Net #region Log4Net
private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endregion #endregion
#region Business Methods #region Business Methods
internal new IList<DROUsageInfo> Items internal new IList<DROUsageInfo> Items => base.Items;
{ get { return base.Items; } } public void AddEvents()
public void AddEvents()
{ {
foreach (DROUsageInfo tmp in this) foreach (DROUsageInfo tmp in this)
{ {
@@ -44,23 +41,19 @@ namespace VEPROMS.CSLA.Library
for (int i = 0; i < Count; i++) for (int i = 0; i < Count; i++)
{ {
if (base[i] == sender) if (base[i] == sender)
this.OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, i)); OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, i));
} }
} }
private bool _Disposed = false; private bool _Disposed = false;
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed ~DROUsageInfoList()
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~DROUsageInfoList()
{ {
_CountFinalized++; _CountFinalized++;
} }
@@ -97,26 +90,12 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Error on DROUsageInfoList.Get", ex); throw new DbCslaException("Error on DROUsageInfoList.Get", ex);
} }
} }
/// <summary> /// <summary>
/// Reset the list of all DROUsageInfo. /// Reset the list of all DROUsageInfo.
/// </summary> /// </summary>
public static void Reset() public static void Reset() => _DROUsageInfoList = null;
{
_DROUsageInfoList = null; public static DROUsageInfoList GetByDocID(int docID)
}
// CSLATODO: Add alternative gets -
//public static DROUsageInfoList Get(<criteria>)
//{
// try
// {
// return DataPortal.Fetch<DROUsageInfoList>(new FilteredCriteria(<criteria>));
// }
// catch (Exception ex)
// {
// throw new DbCslaException("Error on DROUsageInfoList.Get", ex);
// }
//}
public static DROUsageInfoList GetByDocID(int docID)
{ {
try try
{ {
@@ -150,7 +129,7 @@ namespace VEPROMS.CSLA.Library
#region Data Access Portal #region Data Access Portal
private void DataPortal_Fetch() private void DataPortal_Fetch()
{ {
this.RaiseListChangedEvents = false; RaiseListChangedEvents = false;
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DROUsageInfoList.DataPortal_Fetch", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DROUsageInfoList.DataPortal_Fetch", GetHashCode());
try try
{ {
@@ -164,7 +143,7 @@ namespace VEPROMS.CSLA.Library
using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
{ {
IsReadOnly = false; IsReadOnly = false;
while (dr.Read()) this.Add(new DROUsageInfo(dr)); while (dr.Read()) Add(new DROUsageInfo(dr));
IsReadOnly = true; IsReadOnly = true;
} }
} }
@@ -175,16 +154,13 @@ namespace VEPROMS.CSLA.Library
if (_MyLog.IsErrorEnabled) _MyLog.Error("DROUsageInfoList.DataPortal_Fetch", ex); if (_MyLog.IsErrorEnabled) _MyLog.Error("DROUsageInfoList.DataPortal_Fetch", ex);
throw new DbCslaException("DROUsageInfoList.DataPortal_Fetch", ex); throw new DbCslaException("DROUsageInfoList.DataPortal_Fetch", ex);
} }
this.RaiseListChangedEvents = true; RaiseListChangedEvents = true;
} }
[Serializable()] [Serializable()]
private class DocIDCriteria private class DocIDCriteria
{ {
public DocIDCriteria(int docID) public DocIDCriteria(int docID) => _DocID = docID;
{ private int _DocID;
_DocID = docID;
}
private int _DocID;
public int DocID public int DocID
{ {
get { return _DocID; } get { return _DocID; }
@@ -193,7 +169,7 @@ namespace VEPROMS.CSLA.Library
} }
private void DataPortal_Fetch(DocIDCriteria criteria) private void DataPortal_Fetch(DocIDCriteria criteria)
{ {
this.RaiseListChangedEvents = false; RaiseListChangedEvents = false;
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DROUsageInfoList.DataPortal_FetchDocID", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DROUsageInfoList.DataPortal_FetchDocID", GetHashCode());
try try
{ {
@@ -208,7 +184,7 @@ namespace VEPROMS.CSLA.Library
using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
{ {
IsReadOnly = false; IsReadOnly = false;
while (dr.Read()) this.Add(new DROUsageInfo(dr)); while (dr.Read()) Add(new DROUsageInfo(dr));
IsReadOnly = true; IsReadOnly = true;
} }
} }
@@ -219,16 +195,13 @@ namespace VEPROMS.CSLA.Library
if (_MyLog.IsErrorEnabled) _MyLog.Error("DROUsageInfoList.DataPortal_FetchDocID", ex); if (_MyLog.IsErrorEnabled) _MyLog.Error("DROUsageInfoList.DataPortal_FetchDocID", ex);
throw new DbCslaException("DROUsageInfoList.DataPortal_Fetch", ex); throw new DbCslaException("DROUsageInfoList.DataPortal_Fetch", ex);
} }
this.RaiseListChangedEvents = true; RaiseListChangedEvents = true;
} }
[Serializable()] [Serializable()]
private class RODbIDCriteria private class RODbIDCriteria
{ {
public RODbIDCriteria(int rODbID) public RODbIDCriteria(int rODbID) => _RODbID = rODbID;
{ private int _RODbID;
_RODbID = rODbID;
}
private int _RODbID;
public int RODbID public int RODbID
{ {
get { return _RODbID; } get { return _RODbID; }
@@ -237,7 +210,7 @@ namespace VEPROMS.CSLA.Library
} }
private void DataPortal_Fetch(RODbIDCriteria criteria) private void DataPortal_Fetch(RODbIDCriteria criteria)
{ {
this.RaiseListChangedEvents = false; RaiseListChangedEvents = false;
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DROUsageInfoList.DataPortal_FetchRODbID", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DROUsageInfoList.DataPortal_FetchRODbID", GetHashCode());
try try
{ {
@@ -252,7 +225,7 @@ namespace VEPROMS.CSLA.Library
using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
{ {
IsReadOnly = false; IsReadOnly = false;
while (dr.Read()) this.Add(new DROUsageInfo(dr)); while (dr.Read()) Add(new DROUsageInfo(dr));
IsReadOnly = true; IsReadOnly = true;
} }
} }
@@ -263,48 +236,37 @@ namespace VEPROMS.CSLA.Library
if (_MyLog.IsErrorEnabled) _MyLog.Error("DROUsageInfoList.DataPortal_FetchRODbID", ex); if (_MyLog.IsErrorEnabled) _MyLog.Error("DROUsageInfoList.DataPortal_FetchRODbID", ex);
throw new DbCslaException("DROUsageInfoList.DataPortal_Fetch", ex); throw new DbCslaException("DROUsageInfoList.DataPortal_Fetch", ex);
} }
this.RaiseListChangedEvents = true; RaiseListChangedEvents = true;
} }
#endregion #endregion
#region ICustomTypeDescriptor impl #region ICustomTypeDescriptor impl
public String GetClassName() public string GetClassName() => TypeDescriptor.GetClassName(this, true);
{ return TypeDescriptor.GetClassName(this, true); } public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true);
public AttributeCollection GetAttributes() public string GetComponentName() => TypeDescriptor.GetComponentName(this, true);
{ return TypeDescriptor.GetAttributes(this, true); } public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true);
public String GetComponentName() public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true);
{ return TypeDescriptor.GetComponentName(this, true); } public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true);
public TypeConverter GetConverter() public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true);
{ return TypeDescriptor.GetConverter(this, true); } public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true);
public EventDescriptor GetDefaultEvent() public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true);
{ return TypeDescriptor.GetDefaultEvent(this, true); } public object GetPropertyOwner(PropertyDescriptor pd) => this;
public PropertyDescriptor GetDefaultProperty() /// <summary>
{ return TypeDescriptor.GetDefaultProperty(this, true); } /// Called to get the properties of this type. Returns properties with certain
public object GetEditor(Type editorBaseType) /// attributes. this restriction is not implemented here.
{ return TypeDescriptor.GetEditor(this, editorBaseType, true); } /// </summary>
public EventDescriptorCollection GetEvents(Attribute[] attributes) /// <param name="attributes"></param>
{ return TypeDescriptor.GetEvents(this, attributes, true); } /// <returns></returns>
public EventDescriptorCollection GetEvents() public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties();
{ return TypeDescriptor.GetEvents(this, true); } /// <summary>
public object GetPropertyOwner(PropertyDescriptor pd) /// Called to get the properties of this type.
{ return this; } /// </summary>
/// <summary> /// <returns></returns>
/// Called to get the properties of this type. Returns properties with certain public PropertyDescriptorCollection GetProperties()
/// attributes. this restriction is not implemented here.
/// </summary>
/// <param name="attributes"></param>
/// <returns></returns>
public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{ return GetProperties(); }
/// <summary>
/// Called to get the properties of this type.
/// </summary>
/// <returns></returns>
public PropertyDescriptorCollection GetProperties()
{ {
// Create a collection object to hold property descriptors // Create a collection object to hold property descriptors
PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null);
// Iterate the list // Iterate the list
for (int i = 0; i < this.Items.Count; i++) for (int i = 0; i < Items.Count; i++)
{ {
// Create a property descriptor for the item and add to the property descriptor collection // Create a property descriptor for the item and add to the property descriptor collection
DROUsageInfoListPropertyDescriptor pd = new DROUsageInfoListPropertyDescriptor(this, i); DROUsageInfoListPropertyDescriptor pd = new DROUsageInfoListPropertyDescriptor(this, i);
@@ -321,7 +283,6 @@ namespace VEPROMS.CSLA.Library
/// </summary> /// </summary>
public partial class DROUsageInfoListPropertyDescriptor : vlnListPropertyDescriptor public partial class DROUsageInfoListPropertyDescriptor : vlnListPropertyDescriptor
{ {
private DROUsageInfo Item { get { return (DROUsageInfo)_Item; } }
public DROUsageInfoListPropertyDescriptor(DROUsageInfoList collection, int index) : base(collection, index) { ;} public DROUsageInfoListPropertyDescriptor(DROUsageInfoList collection, int index) : base(collection, index) { ;}
} }
#endregion #endregion
@@ -330,10 +291,10 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is DROUsageInfoList) if (destType == typeof(string) && value is DROUsageInfoList list)
{ {
// Return department and department role separated by comma. // Return department and department role separated by comma.
return ((DROUsageInfoList)value).Items.Count.ToString() + " DROUsages"; return $"{list.Items.Count} DROUsages";
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
+169 -193
View File
@@ -15,7 +15,6 @@ using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration; using System.Configuration;
using System.IO; using System.IO;
using System.ComponentModel;
using System.Diagnostics; using System.Diagnostics;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
@@ -35,79 +34,76 @@ namespace VEPROMS.CSLA.Library
private static string _DBServer = null; private static string _DBServer = null;
private static DateTime _RevDate=DateTime.MinValue; private static DateTime _RevDate=DateTime.MinValue;
public static DateTime RevDate public static DateTime RevDate
{ {
get { return Database._RevDate; } get { return _RevDate; }
set { Database._RevDate = value; } set { _RevDate = value; }
} }
private static string _RevDescription= "Unknown"; private static string _RevDescription= "Unknown";
public static string RevDescription public static string RevDescription
{
get { return Database._RevDescription; }
set { Database._RevDescription = value; }
}
public static string DBServer
{
get
{
if (_DBServer == null)
{ {
string cnstr = null; get { return _RevDescription; }
try set { _RevDescription = value; }
}
public static string DBServer
{
get
{ {
using (SqlConnection cn = Database.VEPROMS_SqlConnection) if (_DBServer == null)
{ {
cnstr = cn.ConnectionString; string cnstr = null;
try try
{ {
using (SqlCommand cmd = new SqlCommand("vesp_GetSQLCodeRevision", cn)) using (SqlConnection cn = VEPROMS_SqlConnection)
{ {
cmd.CommandType = CommandType.StoredProcedure; cnstr = cn.ConnectionString;
cmd.CommandTimeout = 0; try
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{ {
_RevDate = dr.GetDateTime(0); using (SqlCommand cmd = new SqlCommand("vesp_GetSQLCodeRevision", cn))
_RevDescription = dr.GetString(1); {
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = 0;
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
_RevDate = dr.GetDateTime(0);
_RevDescription = dr.GetString(1);
}
}
} }
catch (Exception)
{
_RevDate = DateTime.MinValue;
_RevDescription = "Unknown";
}
string server = "";
string db = "";
Match m = Regex.Match(cnstr, "Data Source=([^;]+)(;[^;]+)*;*Initial Catalog=([^;]+)(;[^;]+)*");
if (m.Success && m.Groups.Count > 4)
{
server = m.Groups[1].Value;
db = m.Groups[3].Value;
}
_DBServer = string.Format("{0} - {1} [SQL:{2:yyMM.ddHH}]", server, db, RevDate);
} }
} }
catch (Exception ex) catch (Exception)
{ {
_RevDate = DateTime.MinValue; _DBServer = cnstr;
_RevDescription = "Unknown";
} }
string server = "";
string db = "";
Match m = Regex.Match(cnstr, "Data Source=([^;]+)(;[^;]+)*;*Initial Catalog=([^;]+)(;[^;]+)*");
if (m.Success && m.Groups.Count > 4)
{
server = m.Groups[1].Value;
db = m.Groups[3].Value;
}
_DBServer = string.Format("{0} - {1} [SQL:{2:yyMM.ddHH}]", server, db, RevDate);
} }
} return _DBServer;
catch (Exception)
{
_DBServer = cnstr;
} }
} }
return _DBServer;
}
}
private static int _DefaultTimeout = 600; // 600 seconds, i.e. 10 minutes private static int _DefaultTimeout = 600; // 600 seconds, i.e. 10 minutes
public static int DefaultTimeout public static int DefaultTimeout
{ {
get { return _DefaultTimeout; } get { return _DefaultTimeout; }
set { _DefaultTimeout = value; } set { _DefaultTimeout = value; }
} }
public static int SQLTimeout public static int SQLTimeout => _DefaultTimeout / 20;
{ public static void LogException(string s, Exception ex)
get { return _DefaultTimeout/20; }
}
public static void LogException(string s, Exception ex)
{ {
int i = 0; int i = 0;
Console.WriteLine("Error - {0}", s); Console.WriteLine("Error - {0}", s);
@@ -122,7 +118,7 @@ public static string DBServer
get { return _LoggingInfo; } get { return _LoggingInfo; }
set { _LoggingInfo = value; } set { _LoggingInfo = value; }
} }
static System.Diagnostics.Process _CurrentProcess = System.Diagnostics.Process.GetCurrentProcess(); static readonly System.Diagnostics.Process _CurrentProcess = Process.GetCurrentProcess();
public static void LogInfo(string s, int hashCode) public static void LogInfo(string s, int hashCode)
{ {
if (_LoggingInfo) if (_LoggingInfo)
@@ -136,8 +132,8 @@ public static string DBServer
private static string _ConnectionName = "VEPROMS"; private static string _ConnectionName = "VEPROMS";
public static string ConnectionName public static string ConnectionName
{ {
get { return Database._ConnectionName; } get { return _ConnectionName; }
set { Database._ConnectionName = value; _VEPROMS_Connection = null; /* Reset Connection */ } set { _ConnectionName = value; _VEPROMS_Connection = null; /* Reset Connection */ }
} }
private static bool _TrackDBUsage = false; private static bool _TrackDBUsage = false;
public static bool TrackDBUsage public static bool TrackDBUsage
@@ -145,7 +141,8 @@ public static string DBServer
get { return _TrackDBUsage; } get { return _TrackDBUsage; }
set { _TrackDBUsage = value; } set { _TrackDBUsage = value; }
} }
private static Dictionary<string, int> _Methods = new Dictionary<string, int>(); [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static Dictionary<string, int> _Methods = new Dictionary<string, int>();
public static void ShowDBTracking(string fileName) public static void ShowDBTracking(string fileName)
{ {
DebugDBTrack.Open(VlnSettings.TemporaryFolder + "\\" + fileName); DebugDBTrack.Open(VlnSettings.TemporaryFolder + "\\" + fileName);
@@ -159,12 +156,7 @@ public static string DBServer
{ {
if (TrackDBUsage) if (TrackDBUsage)
{ {
string str = Volian.Base.Library.vlnStackTrace.CalledFromCSLA; string str = vlnStackTrace.CalledFromCSLA;
//if (str.Contains("ItemAndChildren"))
//{
// ShowDictionary(Methods);
// Methods = new Dictionary<string, int>();
//}
if (!_Methods.ContainsKey(str)) if (!_Methods.ContainsKey(str))
_Methods.Add(str, 1); _Methods.Add(str, 1);
else else
@@ -177,7 +169,7 @@ public static string DBServer
DateTime.Today.ToLongDateString(); DateTime.Today.ToLongDateString();
// If DBConnection.XML exists, use the connection string from DBConnection.XML // If DBConnection.XML exists, use the connection string from DBConnection.XML
string cnOverride = System.Windows.Forms.Application.StartupPath + @"\DBConnection.XML"; string cnOverride = System.Windows.Forms.Application.StartupPath + @"\DBConnection.XML";
if (System.IO.File.Exists(cnOverride)) if (File.Exists(cnOverride))
{ {
System.Xml.XmlDocument xd = new System.Xml.XmlDocument(); System.Xml.XmlDocument xd = new System.Xml.XmlDocument();
xd.Load(cnOverride); xd.Load(cnOverride);
@@ -209,12 +201,8 @@ public static string DBServer
} }
} }
// Otherwise get the value from the ConfigurationManager // Otherwise get the value from the ConfigurationManager
ConnectionStringSettings cs = ConfigurationManager.ConnectionStrings[ConnectionName]; ConnectionStringSettings cs = ConfigurationManager.ConnectionStrings[ConnectionName] ?? throw new ApplicationException("Database.cs Could not find connection " + ConnectionName);
if (cs == null) string constr = FixServer(cs.ConnectionString);
{
throw new ApplicationException("Database.cs Could not find connection " + ConnectionName);
}
string constr = FixServer(cs.ConnectionString);
if (constr.Contains("{MENU}")) if (constr.Contains("{MENU}"))
{ {
constr = ChooseDatabase(constr); constr = ChooseDatabase(constr);
@@ -240,10 +228,10 @@ public static string DBServer
} }
private static string FixServer(string connectionString) private static string FixServer(string connectionString)
{ {
string serverName = Volian.Base.Library.VlnSettings.GetServer(); string serverName = VlnSettings.GetServer();
if (serverName != null && serverName != "") if (serverName != null && serverName != "")
{ {
System.Text.RegularExpressions.Match mServer = System.Text.RegularExpressions.Regex.Match(connectionString, ".*Data Source=([^;]*).*"); System.Text.RegularExpressions.Match mServer = Regex.Match(connectionString, ".*Data Source=([^;]*).*");
if (mServer.Success) if (mServer.Success)
{ {
connectionString = connectionString.Substring(0, mServer.Groups[1].Index) + serverName + connectionString.Substring(mServer.Groups[1].Index + mServer.Groups[1].Length); connectionString = connectionString.Substring(0, mServer.Groups[1].Index) + serverName + connectionString.Substring(mServer.Groups[1].Index + mServer.Groups[1].Length);
@@ -254,24 +242,22 @@ public static string DBServer
private static string _SelectedDatabase; private static string _SelectedDatabase;
public static string SelectedDatabase public static string SelectedDatabase
{ {
get { return Database._SelectedDatabase; } get { return _SelectedDatabase; }
set { Database._SelectedDatabase = value; } set { _SelectedDatabase = value; }
} }
public static string ActiveDatabase public static string ActiveDatabase
{ {
get get
{ {
string activeDatabase = SelectedDatabase; string activeDatabase = SelectedDatabase ?? Regex.Replace(VEPROMS_Connection, "^.*Initial Catalog=([^;]*);.*$", "$1", RegexOptions.IgnoreCase);
if(activeDatabase == null) return activeDatabase;
activeDatabase = Regex.Replace(VEPROMS_Connection, "^.*Initial Catalog=([^;]*);.*$", "$1", RegexOptions.IgnoreCase);
return activeDatabase;
} }
} }
private static string _LastDatabase="NoDefault"; private static string _LastDatabase="NoDefault";
public static string LastDatabase public static string LastDatabase
{ {
get { return Database._LastDatabase; } get { return _LastDatabase; }
set { Database._LastDatabase = value; } set { _LastDatabase = value; }
} }
private static string ChooseDatabase(string constr) private static string ChooseDatabase(string constr)
{ {
@@ -300,95 +286,98 @@ public static string DBServer
return constr.Replace("{MENU}", _SelectedDatabase); return constr.Replace("{MENU}", _SelectedDatabase);
} }
private static System.Windows.Forms.ContextMenuStrip BuildDatabaseMenu(string constr) private static System.Windows.Forms.ContextMenuStrip BuildDatabaseMenu(string constr)
{ {
string tmp = constr.Replace("{MENU}", "master"); string tmp = constr.Replace("{MENU}", "master");
SqlConnection cn = new SqlConnection(tmp); using (SqlConnection cn = new SqlConnection(tmp))
cn.Open(); {
// SqlDataAdapter da = new SqlDataAdapter("select name from sysdatabases where name like 'VEP%' order by name", cn); if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
//SqlDataAdapter da = new SqlDataAdapter("select name, case when object_id('[' + name + ']..Items') is null then 'Not PROMS' when object_id('[' + name + ']..Revisions') is not null then 'Approval' when object_id('[' + name + ']..ContentAudits') is not null then 'Change Manager' else 'Original' end functionality from sysdatabases where name not in ('master','model','msdb','tempdb') order by name", cn); using (SqlDataAdapter da = new SqlDataAdapter("select name, 'Approval' functionality from sysdatabases where name not in ('master','model','msdb','tempdb') order by name", cn))
SqlDataAdapter da = new SqlDataAdapter("select name, 'Approval' functionality from sysdatabases where name not in ('master','model','msdb','tempdb') order by name", cn); {
da.SelectCommand.CommandTimeout = 300; // 300 sec timeout da.SelectCommand.CommandTimeout = 300; // 300 sec timeout
DataSet ds = new DataSet(); DataSet ds = new DataSet();
try try
{ {
da.Fill(ds); da.Fill(ds);
} }
catch (Exception ex) catch (Exception ex)
{ {
System.Windows.Forms.MessageBox.Show(ex.GetType().Name, ex.Message); System.Windows.Forms.MessageBox.Show(ex.GetType().Name, ex.Message);
throw(new Exception("Cannot Load Data List",ex)); throw (new Exception("Cannot Load Data List", ex));
} }
cn.Close(); cn.Close();
System.Windows.Forms.ContextMenuStrip cms = new System.Windows.Forms.ContextMenuStrip(); System.Windows.Forms.ContextMenuStrip cms = new System.Windows.Forms.ContextMenuStrip();
cms.Items.Add("Choose Database"); cms.Items.Add("Choose Database");
System.Windows.Forms.ToolStripMenuItem tsmi = cms.Items[0] as System.Windows.Forms.ToolStripMenuItem; System.Windows.Forms.ToolStripMenuItem tsmi = cms.Items[0] as System.Windows.Forms.ToolStripMenuItem;
tsmi.BackColor = System.Drawing.Color.FromKnownColor(System.Drawing.KnownColor.ActiveCaption);// System.Drawing.Color.Pink; tsmi.BackColor = System.Drawing.Color.FromKnownColor(System.Drawing.KnownColor.ActiveCaption);// System.Drawing.Color.Pink;
tsmi.ForeColor = System.Drawing.Color.FromKnownColor(System.Drawing.KnownColor.ActiveCaptionText); tsmi.ForeColor = System.Drawing.Color.FromKnownColor(System.Drawing.KnownColor.ActiveCaptionText);
tsmi.Font = new System.Drawing.Font(tsmi.Font, System.Drawing.FontStyle.Bold); tsmi.Font = new System.Drawing.Font(tsmi.Font, System.Drawing.FontStyle.Bold);
foreach (DataRow dr in ds.Tables[0].Rows) foreach (DataRow dr in ds.Tables[0].Rows)
{ {
if (dr["functionality"].ToString() == "Approval" && !dr["name"].ToString().EndsWith("_RO")) // don't display sql ro databases in list if (dr["functionality"].ToString() == "Approval" && !dr["name"].ToString().EndsWith("_RO")) // don't display sql ro databases in list
cms.Items.Add(dr["name"].ToString(), null, new EventHandler(Database_Click)); cms.Items.Add(dr["name"].ToString(), null, new EventHandler(Database_Click));
} }
return cms; return cms;
} }
}
}
static void Database_Click(object sender, EventArgs e) static void Database_Click(object sender, EventArgs e)
{ {
System.Windows.Forms.ToolStripMenuItem tsmi = sender as System.Windows.Forms.ToolStripMenuItem; if (sender is System.Windows.Forms.ToolStripMenuItem tsmi)
if (tsmi != null) {
{ _SelectedDatabase = tsmi.Text;
_SelectedDatabase = tsmi.Text; }
} }
}
public static SqlConnection VEPROMS_SqlConnection public static SqlConnection VEPROMS_SqlConnection
{ {
get get
{ {
string strConn = VEPROMS_Connection; // If failure - Fail (Don't try to catch) string strConn = VEPROMS_Connection; // If failure - Fail (Don't try to catch)
// Attempt to make a connection // Attempt to make a connection
//note - cannot use using here as it will close the connection and it needs to return it as open
SqlConnection cn = new SqlConnection(strConn); SqlConnection cn = new SqlConnection(strConn);
try try
{ {
cn.Open(); if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
return cn; return cn;
} }
catch (SqlException exsql) catch (SqlException exsql)
{ {
const string strAttachError = "An attempt to attach an auto-named database for file "; const string strAttachError = "An attempt to attach an auto-named database for file ";
if (exsql.Message.StartsWith(strAttachError)) if (exsql.Message.StartsWith(strAttachError))
{// Check to see if the file is missing {// Check to see if the file is missing
string sFile = exsql.Message.Substring(strAttachError.Length); string sFile = exsql.Message.Substring(strAttachError.Length);
sFile = sFile.Substring(0, sFile.IndexOf(" failed")); sFile = sFile.Substring(0, sFile.IndexOf(" failed"));
// "An attempt to attach an auto-named database for file <mdf file> failed" // "An attempt to attach an auto-named database for file <mdf file> failed"
if (strConn.ToLower().IndexOf("user instance=true") < 0) if (strConn.ToLower().IndexOf("user instance=true") < 0)
{ {
throw new ApplicationException("Connection String missing attribute: User Instance=True"); throw new ApplicationException("Connection String missing attribute: User Instance=True");
} }
if (System.IO.File.Exists(sFile)) if (File.Exists(sFile))
{ {
throw new ApplicationException("Database file " + sFile + " Cannot be opened\r\n", exsql); throw new ApplicationException("Database file " + sFile + " Cannot be opened\r\n", exsql);
} }
else else
{ {
throw new FileNotFoundException("Database file " + sFile + " Not Found", exsql); throw new FileNotFoundException("Database file " + sFile + " Not Found", exsql);
} }
} }
else else
{ {
//Open a MesageBox so the user is given some feedback that the connection has failed. //Open a MesageBox so the user is given some feedback that the connection has failed.
ReportInnermostException(exsql,strConn); ReportInnermostException(exsql, strConn);
throw new ApplicationException("Failure on Connect", exsql); throw new ApplicationException("Failure on Connect", exsql);
} }
} }
catch (Exception ex)// Throw Application Exception on Failure catch (Exception ex)// Throw Application Exception on Failure
{ {
if (_MyLog.IsErrorEnabled) _MyLog.Error("Connection Error", ex); if (_MyLog.IsErrorEnabled) _MyLog.Error("Connection Error", ex);
throw new ApplicationException("Failure on Connect", ex); throw new ApplicationException("Failure on Connect", ex);
} }
} }
} }
/// <summary> /// <summary>
/// Open a MessageBox with the exception type, the connection string and the exception message /// Open a MessageBox with the exception type, the connection string and the exception message
/// </summary> /// </summary>
@@ -400,15 +389,13 @@ public static string DBServer
while (ex.InnerException != null) while (ex.InnerException != null)
ex = ex.InnerException; ex = ex.InnerException;
System.Windows.Forms.MessageBox.Show(string.Format("{0}\r\n\r\nConnection String ={1}", ex.Message,conn) System.Windows.Forms.MessageBox.Show(string.Format("{0}\r\n\r\nConnection String ={1}", ex.Message,conn)
,"PROMS - " + ex.GetType().FullName, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Exclamation); , $"PROMS - {ex.GetType().FullName}", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Exclamation);
System.Diagnostics.Process.GetCurrentProcess().Kill(); Process.GetCurrentProcess().Kill();
} }
public static void PurgeData() public static void PurgeData()
{ {
try try
{ {
//SqlConnection cn = VEPROMS_SqlConnection;
//SqlCommand cmd = new SqlCommand("purgedata", cn);
using (SqlConnection cn = VEPROMS_SqlConnection) using (SqlConnection cn = VEPROMS_SqlConnection)
{ {
using (SqlCommand cmd = new SqlCommand("purgedata", cn)) using (SqlCommand cmd = new SqlCommand("purgedata", cn))
@@ -458,8 +445,6 @@ public static string DBServer
{ {
try try
{ {
//SqlConnection cn = VEPROMS_SqlConnection;
//SqlCommand cmd = new SqlCommand("purgedata", cn);
using (SqlConnection cn = Database.VEPROMS_SqlConnection) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
using (SqlCommand cmd = new SqlCommand("purgedata", cn)) using (SqlCommand cmd = new SqlCommand("purgedata", cn))
@@ -483,11 +468,8 @@ public static string DBServer
{ {
private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private string _ErrorMessage = string.Empty; private string _ErrorMessage = string.Empty;
public string ErrorMessage public string ErrorMessage => _ErrorMessage;
{ private ProposedTransition _ProposedTransition;
get { return _ErrorMessage; }
}
private ProposedTransition _ProposedTransition;
public ProposedTransition ProposedTransition public ProposedTransition ProposedTransition
{ {
get { return _ProposedTransition; } get { return _ProposedTransition; }
@@ -508,10 +490,12 @@ public static string DBServer
#region Factory Methods #region Factory Methods
public static ProposedTransition Execute(int fromID, int toID) public static ProposedTransition Execute(int fromID, int toID)
{ {
CanTransitionBeCreatedCommand cmd = new CanTransitionBeCreatedCommand(); CanTransitionBeCreatedCommand cmd = new CanTransitionBeCreatedCommand
cmd.FromID = fromID; {
cmd.ToID = toID; FromID = fromID,
cmd = DataPortal.Execute<CanTransitionBeCreatedCommand>(cmd); ToID = toID
};
cmd = DataPortal.Execute<CanTransitionBeCreatedCommand>(cmd);
return cmd.ProposedTransition; return cmd.ProposedTransition;
} }
private CanTransitionBeCreatedCommand() private CanTransitionBeCreatedCommand()
@@ -536,8 +520,6 @@ public static string DBServer
{ {
try try
{ {
//SqlConnection cn = VEPROMS_SqlConnection;
//SqlCommand cmd = new SqlCommand("purgedata", cn);
using (SqlConnection cn = Database.VEPROMS_SqlConnection) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
using (SqlCommand cmd = new SqlCommand("vesp_CanTransitionBeCreated", cn)) using (SqlCommand cmd = new SqlCommand("vesp_CanTransitionBeCreated", cn))
@@ -571,16 +553,10 @@ public static string DBServer
{ {
private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private string _ErrorMessage = string.Empty; private string _ErrorMessage = string.Empty;
public string ErrorMessage public string ErrorMessage => _ErrorMessage;
{ private List<InvalidTransition> _InvalidTransitions;
get { return _ErrorMessage; } public List<InvalidTransition> InvalidTransitions => _InvalidTransitions;
} private int _ItemID;
private List<InvalidTransition> _InvalidTransitions;
public List<InvalidTransition> InvalidTransitions
{
get { return _InvalidTransitions; }
}
private int _ItemID;
public int ItemID public int ItemID
{ {
get { return _ItemID; } get { return _ItemID; }
@@ -595,10 +571,12 @@ public static string DBServer
#region Factory Methods #region Factory Methods
public static List<InvalidTransition> Execute(int itemID, string newAppl) public static List<InvalidTransition> Execute(int itemID, string newAppl)
{ {
WillTransitionsBeValidCommand cmd = new WillTransitionsBeValidCommand(); WillTransitionsBeValidCommand cmd = new WillTransitionsBeValidCommand
cmd.ItemID = itemID; {
cmd.NewAppl = newAppl; ItemID = itemID,
cmd = DataPortal.Execute<WillTransitionsBeValidCommand>(cmd); NewAppl = newAppl
};
cmd = DataPortal.Execute<WillTransitionsBeValidCommand>(cmd);
return cmd.InvalidTransitions; return cmd.InvalidTransitions;
} }
private WillTransitionsBeValidCommand() private WillTransitionsBeValidCommand()
@@ -626,8 +604,6 @@ public static string DBServer
{ {
try try
{ {
//SqlConnection cn = VEPROMS_SqlConnection;
//SqlCommand cmd = new SqlCommand("purgedata", cn);
using (SqlConnection cn = Database.VEPROMS_SqlConnection) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
using (SqlCommand cmd = new SqlCommand("vesp_WillTransitionsBeValid", cn)) using (SqlCommand cmd = new SqlCommand("vesp_WillTransitionsBeValid", cn))
+130 -261
View File
@@ -13,8 +13,6 @@ using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
using Csla.Validation; using Csla.Validation;
@@ -37,10 +35,7 @@ namespace VEPROMS.CSLA.Library
if (IsDirty) if (IsDirty)
refreshDetails.Add(this); refreshDetails.Add(this);
} }
private void ClearRefreshList() private void ClearRefreshList() => _RefreshDetails = new List<Detail>();
{
_RefreshDetails = new List<Detail>();
}
private void BuildRefreshList() private void BuildRefreshList()
{ {
ClearRefreshList(); ClearRefreshList();
@@ -57,6 +52,7 @@ namespace VEPROMS.CSLA.Library
} }
#endregion #endregion
#region Collection #region Collection
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static List<Detail> _CacheList = new List<Detail>(); private static List<Detail> _CacheList = new List<Detail>();
protected static void AddToCache(Detail detail) protected static void AddToCache(Detail detail)
{ {
@@ -66,6 +62,7 @@ namespace VEPROMS.CSLA.Library
{ {
while (_CacheList.Contains(detail)) _CacheList.Remove(detail); // In RemoveFromCache while (_CacheList.Contains(detail)) _CacheList.Remove(detail); // In RemoveFromCache
} }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static Dictionary<string, List<Detail>> _CacheByPrimaryKey = new Dictionary<string, List<Detail>>(); private static Dictionary<string, List<Detail>> _CacheByPrimaryKey = new Dictionary<string, List<Detail>>();
private static void ConvertListToDictionary() private static void ConvertListToDictionary()
{ {
@@ -91,15 +88,9 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
#region Business Methods #region Business Methods
private string _ErrorMessage = string.Empty; private string _ErrorMessage = string.Empty;
public string ErrorMessage public string ErrorMessage => _ErrorMessage;
{
get { return _ErrorMessage; }
}
private static int _nextDetailID = -1; private static int _nextDetailID = -1;
public static int NextDetailID public static int NextDetailID => _nextDetailID--;
{
get { return _nextDetailID--; }
}
private int _DetailID; private int _DetailID;
[System.ComponentModel.DataObjectField(true, true)] [System.ComponentModel.DataObjectField(true, true)]
public int DetailID public int DetailID
@@ -248,37 +239,22 @@ namespace VEPROMS.CSLA.Library
if (base.IsDirty || list.Contains(this)) if (base.IsDirty || list.Contains(this))
return base.IsDirty; return base.IsDirty;
list.Add(this); list.Add(this);
return base.IsDirty || (_MyContent == null ? false : _MyContent.IsDirtyList(list)); return base.IsDirty || (_MyContent != null && _MyContent.IsDirtyList(list));
}
public override bool IsValid
{
get { return IsValidList(new List<object>()); }
} }
public override bool IsValid => IsValidList(new List<object>());
public bool IsValidList(List<object> list) public bool IsValidList(List<object> list)
{ {
if (list.Contains(this)) if (list.Contains(this))
return (IsNew && !IsDirty) ? true : base.IsValid; return (IsNew && !IsDirty) || base.IsValid;
list.Add(this); list.Add(this);
return ((IsNew && !IsDirty) ? true : base.IsValid) && (_MyContent == null ? true : _MyContent.IsValidList(list)); return ((IsNew && !IsDirty) || base.IsValid) && (_MyContent == null || _MyContent.IsValidList(list));
} }
// CSLATODO: Replace base Detail.ToString function as necessary
/// <summary>
/// Overrides Base ToString
/// </summary>
/// <returns>A string representation of current Detail</returns>
//public override string ToString()
//{
// return base.ToString();
//}
// CSLATODO: Check Detail.GetIdValue to assure that the ID returned is unique // CSLATODO: Check Detail.GetIdValue to assure that the ID returned is unique
/// <summary> /// <summary>
/// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// Overrides Base GetIdValue - Used internally by CSLA to determine equality
/// </summary> /// </summary>
/// <returns>A Unique ID for the current Detail</returns> /// <returns>A Unique ID for the current Detail</returns>
protected override object GetIdValue() protected override object GetIdValue() => MyDetailUnique; // Absolutely Unique ID
{
return MyDetailUnique; // Absolutely Unique ID
}
#endregion #endregion
#region ValidationRules #region ValidationRules
[NonSerialized] [NonSerialized]
@@ -307,8 +283,8 @@ namespace VEPROMS.CSLA.Library
get get
{ {
IVEHasBrokenRules hasBrokenRules = HasBrokenRules; IVEHasBrokenRules hasBrokenRules = HasBrokenRules;
if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; if (Equals(hasBrokenRules)) return BrokenRulesCollection;
return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); return hasBrokenRules?.BrokenRules;
} }
} }
protected override void AddBusinessRules() protected override void AddBusinessRules()
@@ -345,35 +321,11 @@ namespace VEPROMS.CSLA.Library
} }
return true; return true;
} }
// Sample data comparison validation rule
//private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e)
//{
// if (_started > _ended)
// {
// e.Description = "Start date can't be after end date";
// return false;
// }
// else
// return true;
//}
#endregion #endregion
#region Authorization Rules #region Authorization Rules
protected override void AddAuthorizationRules() protected override void AddAuthorizationRules()
{ {
//CSLATODO: Who can read/write which fields //CSLATODO: Who can read/write which fields
//AuthorizationRules.AllowRead(DetailID, "<Role(s)>");
//AuthorizationRules.AllowRead(ContentID, "<Role(s)>");
//AuthorizationRules.AllowRead(ItemType, "<Role(s)>");
//AuthorizationRules.AllowRead(Text, "<Role(s)>");
//AuthorizationRules.AllowRead(Config, "<Role(s)>");
//AuthorizationRules.AllowRead(DTS, "<Role(s)>");
//AuthorizationRules.AllowRead(UserID, "<Role(s)>");
//AuthorizationRules.AllowWrite(ContentID, "<Role(s)>");
//AuthorizationRules.AllowWrite(ItemType, "<Role(s)>");
//AuthorizationRules.AllowWrite(Text, "<Role(s)>");
//AuthorizationRules.AllowWrite(Config, "<Role(s)>");
//AuthorizationRules.AllowWrite(DTS, "<Role(s)>");
//AuthorizationRules.AllowWrite(UserID, "<Role(s)>");
_DetailExtension.AddAuthorizationRules(AuthorizationRules); _DetailExtension.AddAuthorizationRules(AuthorizationRules);
} }
protected override void AddInstanceAuthorizationRules() protected override void AddInstanceAuthorizationRules()
@@ -381,42 +333,14 @@ namespace VEPROMS.CSLA.Library
//CSLATODO: Who can read/write which fields //CSLATODO: Who can read/write which fields
_DetailExtension.AddInstanceAuthorizationRules(AuthorizationRules); _DetailExtension.AddInstanceAuthorizationRules(AuthorizationRules);
} }
public static bool CanAddObject()
{
// CSLATODO: Can Add Authorization
//return Csla.ApplicationContext.User.IsInRole("ProjectManager");
return true;
}
public static bool CanGetObject()
{
// CSLATODO: CanGet Authorization
return true;
}
public static bool CanDeleteObject()
{
// CSLATODO: CanDelete Authorization
//bool result = false;
//if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true;
//if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true;
//return result;
return true;
}
public static bool CanEditObject()
{
// CSLATODO: CanEdit Authorization
//return Csla.ApplicationContext.User.IsInRole("ProjectManager");
return true;
}
#endregion #endregion
#region Factory Methods #region Factory Methods
public int CurrentEditLevel public int CurrentEditLevel => EditLevel;
{ get { return EditLevel; } }
private static int _DetailUnique = 0; private static int _DetailUnique = 0;
protected static int DetailUnique protected static int DetailUnique => ++_DetailUnique;
{ get { return ++_DetailUnique; } } private readonly int _MyDetailUnique = DetailUnique;
private int _MyDetailUnique = DetailUnique; // Absolutely Unique ID - Editable
public int MyDetailUnique // Absolutely Unique ID - Editable public int MyDetailUnique => _MyDetailUnique;
{ get { return _MyDetailUnique; } }
protected Detail() protected Detail()
{/* require use of factory methods */ {/* require use of factory methods */
AddToCache(this); AddToCache(this);
@@ -425,15 +349,11 @@ namespace VEPROMS.CSLA.Library
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~Detail() ~Detail()
{ {
_CountFinalized++; _CountFinalized++;
@@ -458,8 +378,6 @@ namespace VEPROMS.CSLA.Library
} }
public static Detail New() public static Detail New()
{ {
if (!CanAddObject())
throw new System.Security.SecurityException("User not authorized to add a Detail");
try try
{ {
return DataPortal.Create<Detail>(); return DataPortal.Create<Detail>();
@@ -531,8 +449,6 @@ namespace VEPROMS.CSLA.Library
} }
public static Detail Get(int detailID) public static Detail Get(int detailID)
{ {
if (!CanGetObject())
throw new System.Security.SecurityException("User not authorized to view a Detail");
try try
{ {
Detail tmp = GetCachedByPrimaryKey(detailID); Detail tmp = GetCachedByPrimaryKey(detailID);
@@ -558,14 +474,9 @@ namespace VEPROMS.CSLA.Library
if (dr.Read()) return new Detail(dr); if (dr.Read()) return new Detail(dr);
return null; return null;
} }
internal Detail(SafeDataReader dr) internal Detail(SafeDataReader dr) => ReadData(dr);
{
ReadData(dr);
}
public static void Delete(int detailID) public static void Delete(int detailID)
{ {
if (!CanDeleteObject())
throw new System.Security.SecurityException("User not authorized to remove a Detail");
try try
{ {
DataPortal.Delete(new PKCriteria(detailID)); DataPortal.Delete(new PKCriteria(detailID));
@@ -577,12 +488,6 @@ namespace VEPROMS.CSLA.Library
} }
public override Detail Save() public override Detail Save()
{ {
if (IsDeleted && !CanDeleteObject())
throw new System.Security.SecurityException("User not authorized to remove a Detail");
else if (IsNew && !CanAddObject())
throw new System.Security.SecurityException("User not authorized to add a Detail");
else if (!CanEditObject())
throw new System.Security.SecurityException("User not authorized to update a Detail");
try try
{ {
BuildRefreshList(); BuildRefreshList();
@@ -602,13 +507,9 @@ namespace VEPROMS.CSLA.Library
[Serializable()] [Serializable()]
protected class PKCriteria protected class PKCriteria
{ {
private int _DetailID; private readonly int _DetailID;
public int DetailID public int DetailID => _DetailID;
{ get { return _DetailID; } } public PKCriteria(int detailID) => _DetailID = detailID;
public PKCriteria(int detailID)
{
_DetailID = detailID;
}
} }
// CSLATODO: If Create needs to access DB - It should not be marked RunLocal // CSLATODO: If Create needs to access DB - It should not be marked RunLocal
[RunLocal()] [RunLocal()]
@@ -679,7 +580,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Detail.DataPortal_Fetch", ex); throw new DbCslaException("Detail.DataPortal_Fetch", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Insert() protected override void DataPortal_Insert()
{ {
try try
@@ -704,39 +605,47 @@ namespace VEPROMS.CSLA.Library
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Detail.DataPortal_Insert", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Detail.DataPortal_Insert", GetHashCode());
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
internal void SQLInsert() internal void SQLInsert()
{ {
if (!this.IsDirty) return; if (!IsDirty) return;
try try
{ {
if (_MyContent != null) _MyContent.Update(); _MyContent?.Update();
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = Database.VEPROMS_SqlConnection)
using (SqlCommand cm = cn.CreateCommand())
{ {
cm.CommandType = CommandType.StoredProcedure; if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
cm.CommandTimeout = Database.SQLTimeout; using (SqlCommand cm = cn.CreateCommand())
cm.CommandText = "addDetail"; {
// Input All Fields - Except Calculated Columns cm.CommandType = CommandType.StoredProcedure;
cm.Parameters.AddWithValue("@ContentID", ContentID); cm.CommandTimeout = Database.SQLTimeout;
cm.Parameters.AddWithValue("@ItemType", _ItemType); cm.CommandText = "addDetail";
cm.Parameters.AddWithValue("@Text", _Text); // Input All Fields - Except Calculated Columns
cm.Parameters.AddWithValue("@Config", _Config); cm.Parameters.AddWithValue("@ContentID", ContentID);
if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); cm.Parameters.AddWithValue("@ItemType", _ItemType);
cm.Parameters.AddWithValue("@UserID", _UserID); cm.Parameters.AddWithValue("@Text", _Text);
// Output Calculated Columns cm.Parameters.AddWithValue("@Config", _Config);
SqlParameter param_DetailID = new SqlParameter("@newDetailID", SqlDbType.Int); if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS);
param_DetailID.Direction = ParameterDirection.Output; cm.Parameters.AddWithValue("@UserID", _UserID);
cm.Parameters.Add(param_DetailID); // Output Calculated Columns
SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); SqlParameter param_DetailID = new SqlParameter("@newDetailID", SqlDbType.Int)
param_LastChanged.Direction = ParameterDirection.Output; {
cm.Parameters.Add(param_LastChanged); Direction = ParameterDirection.Output
// CSLATODO: Define any additional output parameters };
cm.ExecuteNonQuery(); cm.Parameters.Add(param_DetailID);
// Save all values being returned from the Procedure SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp)
_DetailID = (int)cm.Parameters["@newDetailID"].Value; {
_LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; Direction = ParameterDirection.Output
};
cm.Parameters.Add(param_LastChanged);
// CSLATODO: Define any additional output parameters
cm.ExecuteNonQuery();
// Save all values being returned from the Procedure
_DetailID = (int)cm.Parameters["@newDetailID"].Value;
_LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value;
}
} }
MarkOld(); MarkOld();
// update child objects // update child objects
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Detail.SQLInsert", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Detail.SQLInsert", GetHashCode());
@@ -748,7 +657,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Detail.SQLInsert", ex); throw new DbCslaException("Detail.SQLInsert", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
public static byte[] Add(SqlConnection cn, ref int detailID, Content myContent, int itemType, string text, string config, DateTime dts, string userID) public static byte[] Add(SqlConnection cn, ref int detailID, Content myContent, int itemType, string text, string config, DateTime dts, string userID)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Detail.Add", 0); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Detail.Add", 0);
@@ -767,11 +676,15 @@ namespace VEPROMS.CSLA.Library
if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts); if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts);
cm.Parameters.AddWithValue("@UserID", userID); cm.Parameters.AddWithValue("@UserID", userID);
// Output Calculated Columns // Output Calculated Columns
SqlParameter param_DetailID = new SqlParameter("@newDetailID", SqlDbType.Int); SqlParameter param_DetailID = new SqlParameter("@newDetailID", SqlDbType.Int)
param_DetailID.Direction = ParameterDirection.Output; {
Direction = ParameterDirection.Output
};
cm.Parameters.Add(param_DetailID); cm.Parameters.Add(param_DetailID);
SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp)
param_LastChanged.Direction = ParameterDirection.Output; {
Direction = ParameterDirection.Output
};
cm.Parameters.Add(param_LastChanged); cm.Parameters.Add(param_LastChanged);
// CSLATODO: Define any additional output parameters // CSLATODO: Define any additional output parameters
cm.ExecuteNonQuery(); cm.ExecuteNonQuery();
@@ -786,7 +699,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Detail.Add", ex); throw new DbCslaException("Detail.Add", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Update() protected override void DataPortal_Update()
{ {
if (!IsDirty) return; // If not dirty - nothing to do if (!IsDirty) return; // If not dirty - nothing to do
@@ -809,41 +722,47 @@ namespace VEPROMS.CSLA.Library
if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; if (!ex.Message.EndsWith("has been edited by another user.")) throw ex;
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
internal void SQLUpdate() internal void SQLUpdate()
{ {
if (!IsDirty) return; // If not dirty - nothing to do if (!IsDirty) return; // If not dirty - nothing to do
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Detail.SQLUpdate", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Detail.SQLUpdate", GetHashCode());
try try
{ {
if (_MyContent != null) _MyContent.Update(); _MyContent?.Update();
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = Database.VEPROMS_SqlConnection)
if (base.IsDirty)
{ {
using (SqlCommand cm = cn.CreateCommand()) if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
if (base.IsDirty)
{ {
cm.CommandType = CommandType.StoredProcedure; using (SqlCommand cm = cn.CreateCommand())
cm.CommandTimeout = Database.SQLTimeout; {
cm.CommandText = "updateDetail"; cm.CommandType = CommandType.StoredProcedure;
// All Fields including Calculated Fields cm.CommandTimeout = Database.SQLTimeout;
cm.Parameters.AddWithValue("@DetailID", _DetailID); cm.CommandText = "updateDetail";
cm.Parameters.AddWithValue("@ContentID", ContentID); // All Fields including Calculated Fields
cm.Parameters.AddWithValue("@ItemType", _ItemType); cm.Parameters.AddWithValue("@DetailID", _DetailID);
cm.Parameters.AddWithValue("@Text", _Text); cm.Parameters.AddWithValue("@ContentID", ContentID);
cm.Parameters.AddWithValue("@Config", _Config); cm.Parameters.AddWithValue("@ItemType", _ItemType);
if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); cm.Parameters.AddWithValue("@Text", _Text);
cm.Parameters.AddWithValue("@UserID", _UserID); cm.Parameters.AddWithValue("@Config", _Config);
cm.Parameters.AddWithValue("@LastChanged", _LastChanged); if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS);
// Output Calculated Columns cm.Parameters.AddWithValue("@UserID", _UserID);
SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); cm.Parameters.AddWithValue("@LastChanged", _LastChanged);
param_LastChanged.Direction = ParameterDirection.Output; // Output Calculated Columns
cm.Parameters.Add(param_LastChanged); SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp)
// CSLATODO: Define any additional output parameters {
cm.ExecuteNonQuery(); Direction = ParameterDirection.Output
// Save all values being returned from the Procedure };
_LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; cm.Parameters.Add(param_LastChanged);
// CSLATODO: Define any additional output parameters
cm.ExecuteNonQuery();
// Save all values being returned from the Procedure
_LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value;
}
} }
} }
MarkOld(); MarkOld();
// use the open connection to update child objects // use the open connection to update child objects
} }
@@ -856,18 +775,22 @@ namespace VEPROMS.CSLA.Library
} }
internal void Update() internal void Update()
{ {
if (!this.IsDirty) return; if (!IsDirty) return;
if (base.IsDirty) if (base.IsDirty)
{ {
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = Database.VEPROMS_SqlConnection)
if (IsNew) {
_LastChanged = Detail.Add(cn, ref _DetailID, _MyContent, _ItemType, _Text, _Config, _DTS, _UserID); if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
else if (IsNew)
_LastChanged = Detail.Update(cn, ref _DetailID, _ContentID, _ItemType, _Text, _Config, _DTS, _UserID, ref _LastChanged); _LastChanged = Detail.Add(cn, ref _DetailID, _MyContent, _ItemType, _Text, _Config, _DTS, _UserID);
else
_LastChanged = Detail.Update(cn, ref _DetailID, _ContentID, _ItemType, _Text, _Config, _DTS, _UserID, ref _LastChanged);
}
MarkOld(); MarkOld();
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
public static byte[] Update(SqlConnection cn, ref int detailID, int contentID, int itemType, string text, string config, DateTime dts, string userID, ref byte[] lastChanged) public static byte[] Update(SqlConnection cn, ref int detailID, int contentID, int itemType, string text, string config, DateTime dts, string userID, ref byte[] lastChanged)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Detail.Update", 0); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Detail.Update", 0);
@@ -888,8 +811,10 @@ namespace VEPROMS.CSLA.Library
cm.Parameters.AddWithValue("@UserID", userID); cm.Parameters.AddWithValue("@UserID", userID);
cm.Parameters.AddWithValue("@LastChanged", lastChanged); cm.Parameters.AddWithValue("@LastChanged", lastChanged);
// Output Calculated Columns // Output Calculated Columns
SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp)
param_LastChanged.Direction = ParameterDirection.Output; {
Direction = ParameterDirection.Output
};
cm.Parameters.Add(param_LastChanged); cm.Parameters.Add(param_LastChanged);
// CSLATODO: Define any additional output parameters // CSLATODO: Define any additional output parameters
cm.ExecuteNonQuery(); cm.ExecuteNonQuery();
@@ -903,12 +828,12 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Detail.Update", ex); throw new DbCslaException("Detail.Update", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_DeleteSelf() protected override void DataPortal_DeleteSelf()
{ {
DataPortal_Delete(new PKCriteria(_DetailID)); DataPortal_Delete(new PKCriteria(_DetailID));
} }
[Transactional(TransactionalTypes.TransactionScope)]
private void DataPortal_Delete(PKCriteria criteria) private void DataPortal_Delete(PKCriteria criteria)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Detail.DataPortal_Delete", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Detail.DataPortal_Delete", GetHashCode());
@@ -933,7 +858,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Detail.DataPortal_Delete", ex); throw new DbCslaException("Detail.DataPortal_Delete", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
public static void Remove(SqlConnection cn, int detailID) public static void Remove(SqlConnection cn, int detailID)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Detail.Remove", 0); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Detail.Remove", 0);
@@ -974,16 +899,10 @@ namespace VEPROMS.CSLA.Library
[Serializable()] [Serializable()]
private class ExistsCommand : CommandBase private class ExistsCommand : CommandBase
{ {
private int _DetailID; private readonly int _DetailID;
private bool _exists; private bool _exists;
public bool Exists public bool Exists => _exists;
{ public ExistsCommand(int detailID) => _DetailID = detailID;
get { return _exists; }
}
public ExistsCommand(int detailID)
{
_DetailID = detailID;
}
protected override void DataPortal_Execute() protected override void DataPortal_Execute()
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Detail.DataPortal_Execute", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Detail.DataPortal_Execute", GetHashCode());
@@ -991,7 +910,7 @@ namespace VEPROMS.CSLA.Library
{ {
using (SqlConnection cn = Database.VEPROMS_SqlConnection) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
cn.Open(); if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
using (SqlCommand cm = cn.CreateCommand()) using (SqlCommand cm = cn.CreateCommand())
{ {
cm.CommandType = CommandType.StoredProcedure; cm.CommandType = CommandType.StoredProcedure;
@@ -1013,7 +932,7 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
// Standard Default Code // Standard Default Code
#region extension #region extension
DetailExtension _DetailExtension = new DetailExtension(); readonly DetailExtension _DetailExtension = new DetailExtension();
[Serializable()] [Serializable()]
partial class DetailExtension : extensionBase partial class DetailExtension : extensionBase
{ {
@@ -1022,14 +941,8 @@ namespace VEPROMS.CSLA.Library
class extensionBase class extensionBase
{ {
// Default Values // Default Values
public virtual DateTime DefaultDTS public virtual DateTime DefaultDTS => DateTime.Now;
{ public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID;
get { return DateTime.Now; }
}
public virtual string DefaultUserID
{
get { return Volian.Base.Library.VlnSettings.UserID; }
}
// Authorization Rules // Authorization Rules
public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules)
{ {
@@ -1058,57 +971,13 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is Detail) if (destType == typeof(string) && value is Detail detail)
{ {
// Return the ToString value // Return the ToString value
return ((Detail)value).ToString(); return detail.ToString();
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
} }
#endregion #endregion
} // Namespace } // Namespace
//// The following is a sample Extension File. You can use it to create DetailExt.cs
//using System;
//using System.Collections.Generic;
//using System.Text;
//using Csla;
//namespace VEPROMS.CSLA.Library
//{
// public partial class Detail
// {
// partial class DetailExtension : extensionBase
// {
// // CSLATODO: Override automatic defaults
// public virtual DateTime DefaultDTS
// {
// get { return DateTime.Now; }
// }
// public virtual string DefaultUserID
// {
// get { return Environment.UserName.ToUpper(); }
// }
// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules)
// {
// //rules.AllowRead(Dbid, "<Role(s)>");
// }
// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules)
// {
// //rules.AllowInstanceRead(Dbid, "<Role(s)>");
// }
// public new void AddValidationRules(Csla.Validation.ValidationRules rules)
// {
// rules.AddRule(
// Csla.Validation.CommonRules.StringMaxLength,
// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100));
// }
// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules)
// {
// rules.AddInstanceRule(/* Instance Validation Rule */);
// }
// }
// }
//}
@@ -13,8 +13,6 @@ using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
namespace VEPROMS.CSLA.Library namespace VEPROMS.CSLA.Library
@@ -28,14 +26,12 @@ namespace VEPROMS.CSLA.Library
public partial class DetailInfo : ReadOnlyBase<DetailInfo>, IDisposable public partial class DetailInfo : ReadOnlyBase<DetailInfo>, IDisposable
{ {
public event DetailInfoEvent Changed; public event DetailInfoEvent Changed;
private void OnChange() private void OnChange() => Changed?.Invoke(this);
{
if (Changed != null) Changed(this);
}
#region Log4Net #region Log4Net
private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endregion #endregion
#region Collection #region Collection
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static List<DetailInfo> _CacheList = new List<DetailInfo>(); private static List<DetailInfo> _CacheList = new List<DetailInfo>();
protected static void AddToCache(DetailInfo detailInfo) protected static void AddToCache(DetailInfo detailInfo)
{ {
@@ -45,6 +41,7 @@ namespace VEPROMS.CSLA.Library
{ {
while (_CacheList.Contains(detailInfo)) _CacheList.Remove(detailInfo); // In RemoveFromCache while (_CacheList.Contains(detailInfo)) _CacheList.Remove(detailInfo); // In RemoveFromCache
} }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static Dictionary<string, List<DetailInfo>> _CacheByPrimaryKey = new Dictionary<string, List<DetailInfo>>(); private static Dictionary<string, List<DetailInfo>> _CacheByPrimaryKey = new Dictionary<string, List<DetailInfo>>();
private static void ConvertListToDictionary() private static void ConvertListToDictionary()
{ {
@@ -74,21 +71,8 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
#region Business Methods #region Business Methods
private string _ErrorMessage = string.Empty; private string _ErrorMessage = string.Empty;
public string ErrorMessage public string ErrorMessage => _ErrorMessage;
{
get { return _ErrorMessage; }
}
protected Detail _Editable; protected Detail _Editable;
private IVEHasBrokenRules HasBrokenRules
{
get
{
IVEHasBrokenRules hasBrokenRules = null;
if (_Editable != null)
hasBrokenRules = _Editable.HasBrokenRules;
return hasBrokenRules;
}
}
private int _DetailID; private int _DetailID;
[System.ComponentModel.DataObjectField(true, true)] [System.ComponentModel.DataObjectField(true, true)]
public int DetailID public int DetailID
@@ -164,32 +148,19 @@ namespace VEPROMS.CSLA.Library
return _UserID; return _UserID;
} }
} }
// CSLATODO: Replace base DetailInfo.ToString function as necessary
/// <summary>
/// Overrides Base ToString
/// </summary>
/// <returns>A string representation of current DetailInfo</returns>
//public override string ToString()
//{
// return base.ToString();
//}
// CSLATODO: Check DetailInfo.GetIdValue to assure that the ID returned is unique // CSLATODO: Check DetailInfo.GetIdValue to assure that the ID returned is unique
/// <summary> /// <summary>
/// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// Overrides Base GetIdValue - Used internally by CSLA to determine equality
/// </summary> /// </summary>
/// <returns>A Unique ID for the current DetailInfo</returns> /// <returns>A Unique ID for the current DetailInfo</returns>
protected override object GetIdValue() protected override object GetIdValue() => MyDetailInfoUnique; // Absolutely Unique ID
{
return MyDetailInfoUnique; // Absolutely Unique ID
}
#endregion #endregion
#region Factory Methods #region Factory Methods
private static int _DetailInfoUnique = 0; private static int _DetailInfoUnique = 0;
private static int DetailInfoUnique private static int DetailInfoUnique => ++_DetailInfoUnique;
{ get { return ++_DetailInfoUnique; } } private readonly int _MyDetailInfoUnique = DetailInfoUnique;
private int _MyDetailInfoUnique = DetailInfoUnique; // Absolutely Unique ID - Info
public int MyDetailInfoUnique // Absolutely Unique ID - Info public int MyDetailInfoUnique => _MyDetailInfoUnique;
{ get { return _MyDetailInfoUnique; } }
protected DetailInfo() protected DetailInfo()
{/* require use of factory methods */ {/* require use of factory methods */
AddToCache(this); AddToCache(this);
@@ -198,15 +169,11 @@ namespace VEPROMS.CSLA.Library
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~DetailInfo() ~DetailInfo()
{ {
_CountFinalized++; _CountFinalized++;
@@ -223,10 +190,7 @@ namespace VEPROMS.CSLA.Library
if (listDetailInfo.Count == 0) // If there are no items left in the list if (listDetailInfo.Count == 0) // If there are no items left in the list
_CacheByPrimaryKey.Remove(DetailID.ToString()); // remove the list _CacheByPrimaryKey.Remove(DetailID.ToString()); // remove the list
} }
public virtual Detail Get() public virtual Detail Get() => _Editable = Detail.Get(_DetailID);
{
return _Editable = Detail.Get(_DetailID);
}
public static void Refresh(Detail tmp) public static void Refresh(Detail tmp)
{ {
string key = tmp.DetailID.ToString(); string key = tmp.DetailID.ToString();
@@ -239,11 +203,11 @@ namespace VEPROMS.CSLA.Library
{ {
if (_ContentID != tmp.ContentID) if (_ContentID != tmp.ContentID)
{ {
if (MyContent != null) MyContent.RefreshContentDetails(); // Update List for old value MyContent?.RefreshContentDetails(); // Update List for old value
_ContentID = tmp.ContentID; // Update the value _ContentID = tmp.ContentID; // Update the value
} }
_MyContent = null; // Reset list so that the next line gets a new list _MyContent = null; // Reset list so that the next line gets a new list
if (MyContent != null) MyContent.RefreshContentDetails(); // Update List for new value MyContent?.RefreshContentDetails(); // Update List for new value
_ItemType = tmp.ItemType; _ItemType = tmp.ItemType;
_Text = tmp.Text; _Text = tmp.Text;
_Config = tmp.Config; _Config = tmp.Config;
@@ -272,8 +236,6 @@ namespace VEPROMS.CSLA.Library
} }
public static DetailInfo Get(int detailID) public static DetailInfo Get(int detailID)
{ {
//if (!CanGetObject())
// throw new System.Security.SecurityException("User not authorized to view a Detail");
try try
{ {
DetailInfo tmp = GetCachedByPrimaryKey(detailID); DetailInfo tmp = GetCachedByPrimaryKey(detailID);
@@ -312,13 +274,9 @@ namespace VEPROMS.CSLA.Library
[Serializable()] [Serializable()]
protected class PKCriteria protected class PKCriteria
{ {
private int _DetailID; private readonly int _DetailID;
public int DetailID public int DetailID => _DetailID;
{ get { return _DetailID; } } public PKCriteria(int detailID) => _DetailID = detailID;
public PKCriteria(int detailID)
{
_DetailID = detailID;
}
} }
private void ReadData(SafeDataReader dr) private void ReadData(SafeDataReader dr)
{ {
@@ -379,7 +337,7 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
// Standard Refresh // Standard Refresh
#region extension #region extension
DetailInfoExtension _DetailInfoExtension = new DetailInfoExtension(); readonly DetailInfoExtension _DetailInfoExtension = new DetailInfoExtension();
[Serializable()] [Serializable()]
partial class DetailInfoExtension : extensionBase { } partial class DetailInfoExtension : extensionBase { }
[Serializable()] [Serializable()]
@@ -395,10 +353,10 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is DetailInfo) if (destType == typeof(string) && value is DetailInfo info)
{ {
// Return the ToString value // Return the ToString value
return ((DetailInfo)value).ToString(); return info.ToString();
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
@@ -13,8 +13,6 @@ using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
namespace VEPROMS.CSLA.Library namespace VEPROMS.CSLA.Library
@@ -28,11 +26,10 @@ namespace VEPROMS.CSLA.Library
{ {
#region Log4Net #region Log4Net
private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endregion #endregion
#region Business Methods #region Business Methods
internal new IList<DetailInfo> Items internal new IList<DetailInfo> Items => base.Items;
{ get { return base.Items; } } public void AddEvents()
public void AddEvents()
{ {
foreach (DetailInfo tmp in this) foreach (DetailInfo tmp in this)
{ {
@@ -51,16 +48,12 @@ namespace VEPROMS.CSLA.Library
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed ~DetailInfoList()
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~DetailInfoList()
{ {
_CountFinalized++; _CountFinalized++;
} }
@@ -97,26 +90,12 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Error on DetailInfoList.Get", ex); throw new DbCslaException("Error on DetailInfoList.Get", ex);
} }
} }
/// <summary> /// <summary>
/// Reset the list of all DetailInfo. /// Reset the list of all DetailInfo.
/// </summary> /// </summary>
public static void Reset() public static void Reset() => _DetailInfoList = null;
{
_DetailInfoList = null; public static DetailInfoList GetByContentID(int contentID)
}
// CSLATODO: Add alternative gets -
//public static DetailInfoList Get(<criteria>)
//{
// try
// {
// return DataPortal.Fetch<DetailInfoList>(new FilteredCriteria(<criteria>));
// }
// catch (Exception ex)
// {
// throw new DbCslaException("Error on DetailInfoList.Get", ex);
// }
//}
public static DetailInfoList GetByContentID(int contentID)
{ {
try try
{ {
@@ -166,11 +145,8 @@ namespace VEPROMS.CSLA.Library
[Serializable()] [Serializable()]
private class ContentIDCriteria private class ContentIDCriteria
{ {
public ContentIDCriteria(int contentID) public ContentIDCriteria(int contentID) => _ContentID = contentID;
{ private int _ContentID;
_ContentID = contentID;
}
private int _ContentID;
public int ContentID public int ContentID
{ {
get { return _ContentID; } get { return _ContentID; }
@@ -207,41 +183,30 @@ namespace VEPROMS.CSLA.Library
} }
this.RaiseListChangedEvents = true; this.RaiseListChangedEvents = true;
} }
#endregion #endregion
#region ICustomTypeDescriptor impl #region ICustomTypeDescriptor impl
public String GetClassName() public String GetClassName() => TypeDescriptor.GetClassName(this, true);
{ return TypeDescriptor.GetClassName(this, true); } public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true);
public AttributeCollection GetAttributes() public String GetComponentName() => TypeDescriptor.GetComponentName(this, true);
{ return TypeDescriptor.GetAttributes(this, true); } public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true);
public String GetComponentName() public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true);
{ return TypeDescriptor.GetComponentName(this, true); } public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true);
public TypeConverter GetConverter() public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true);
{ return TypeDescriptor.GetConverter(this, true); } public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true);
public EventDescriptor GetDefaultEvent() public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true);
{ return TypeDescriptor.GetDefaultEvent(this, true); } public object GetPropertyOwner(PropertyDescriptor pd) => this;
public PropertyDescriptor GetDefaultProperty() /// <summary>
{ return TypeDescriptor.GetDefaultProperty(this, true); } /// Called to get the properties of this type. Returns properties with certain
public object GetEditor(Type editorBaseType) /// attributes. this restriction is not implemented here.
{ return TypeDescriptor.GetEditor(this, editorBaseType, true); } /// </summary>
public EventDescriptorCollection GetEvents(Attribute[] attributes) /// <param name="attributes"></param>
{ return TypeDescriptor.GetEvents(this, attributes, true); } /// <returns></returns>
public EventDescriptorCollection GetEvents() public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties();
{ return TypeDescriptor.GetEvents(this, true); } /// <summary>
public object GetPropertyOwner(PropertyDescriptor pd) /// Called to get the properties of this type.
{ return this; } /// </summary>
/// <summary> /// <returns></returns>
/// Called to get the properties of this type. Returns properties with certain public PropertyDescriptorCollection GetProperties()
/// attributes. this restriction is not implemented here.
/// </summary>
/// <param name="attributes"></param>
/// <returns></returns>
public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{ return GetProperties(); }
/// <summary>
/// Called to get the properties of this type.
/// </summary>
/// <returns></returns>
public PropertyDescriptorCollection GetProperties()
{ {
// Create a collection object to hold property descriptors // Create a collection object to hold property descriptors
PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null);
@@ -263,7 +228,6 @@ namespace VEPROMS.CSLA.Library
/// </summary> /// </summary>
public partial class DetailInfoListPropertyDescriptor : vlnListPropertyDescriptor public partial class DetailInfoListPropertyDescriptor : vlnListPropertyDescriptor
{ {
private DetailInfo Item { get { return (DetailInfo)_Item; } }
public DetailInfoListPropertyDescriptor(DetailInfoList collection, int index) : base(collection, index) { ;} public DetailInfoListPropertyDescriptor(DetailInfoList collection, int index) : base(collection, index) { ;}
} }
#endregion #endregion
@@ -272,10 +236,10 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is DetailInfoList) if (destType == typeof(string) && value is DetailInfoList list)
{ {
// Return department and department role separated by comma. // Return department and department role separated by comma.
return ((DetailInfoList)value).Items.Count.ToString() + " Details"; return $"{list.Items.Count} Details";
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
+143 -298
View File
@@ -13,8 +13,6 @@ using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
using Csla.Validation; using Csla.Validation;
@@ -72,6 +70,7 @@ namespace VEPROMS.CSLA.Library
} }
#endregion #endregion
#region Collection #region Collection
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static List<DocVersion> _CacheList = new List<DocVersion>(); private static List<DocVersion> _CacheList = new List<DocVersion>();
protected static void AddToCache(DocVersion docVersion) protected static void AddToCache(DocVersion docVersion)
{ {
@@ -81,6 +80,7 @@ namespace VEPROMS.CSLA.Library
{ {
while (_CacheList.Contains(docVersion)) _CacheList.Remove(docVersion); // In RemoveFromCache while (_CacheList.Contains(docVersion)) _CacheList.Remove(docVersion); // In RemoveFromCache
} }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static Dictionary<string, List<DocVersion>> _CacheByPrimaryKey = new Dictionary<string, List<DocVersion>>(); private static Dictionary<string, List<DocVersion>> _CacheByPrimaryKey = new Dictionary<string, List<DocVersion>>();
private static void ConvertListToDictionary() private static void ConvertListToDictionary()
{ {
@@ -106,15 +106,9 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
#region Business Methods #region Business Methods
private string _ErrorMessage = string.Empty; private string _ErrorMessage = string.Empty;
public string ErrorMessage public string ErrorMessage => _ErrorMessage;
{
get { return _ErrorMessage; }
}
private static int _nextVersionID = -1; private static int _nextVersionID = -1;
public static int NextVersionID public static int NextVersionID => _nextVersionID--;
{
get { return _nextVersionID--; }
}
private int _VersionID; private int _VersionID;
[System.ComponentModel.DataObjectField(true, true)] [System.ComponentModel.DataObjectField(true, true)]
public int VersionID public int VersionID
@@ -362,10 +356,7 @@ namespace VEPROMS.CSLA.Library
return _DocVersionAssociations; return _DocVersionAssociations;
} }
} }
public void Reset_DocVersionAssociations() public void Reset_DocVersionAssociations() => _DocVersionAssociationCount = -1;
{
_DocVersionAssociationCount = -1;
}
public override bool IsDirty public override bool IsDirty
{ {
get get
@@ -380,37 +371,22 @@ namespace VEPROMS.CSLA.Library
if (base.IsDirty || list.Contains(this)) if (base.IsDirty || list.Contains(this))
return base.IsDirty; return base.IsDirty;
list.Add(this); list.Add(this);
return base.IsDirty || (_DocVersionAssociations == null ? false : _DocVersionAssociations.IsDirtyList(list)) || (_MyFolder == null ? false : _MyFolder.IsDirtyList(list)) || (_MyFormat == null ? false : _MyFormat.IsDirtyList(list)) || (_MyItem == null ? false : _MyItem.IsDirtyList(list)); return base.IsDirty || (_DocVersionAssociations != null && _DocVersionAssociations.IsDirtyList(list)) || (_MyFolder != null && _MyFolder.IsDirtyList(list)) || (_MyFormat != null && _MyFormat.IsDirtyList(list)) || (_MyItem != null && _MyItem.IsDirtyList(list));
}
public override bool IsValid
{
get { return IsValidList(new List<object>()); }
} }
public override bool IsValid => IsValidList(new List<object>());
public bool IsValidList(List<object> list) public bool IsValidList(List<object> list)
{ {
if (list.Contains(this)) if (list.Contains(this))
return (IsNew && !IsDirty) ? true : base.IsValid; return (IsNew && !IsDirty) || base.IsValid;
list.Add(this); list.Add(this);
return ((IsNew && !IsDirty) ? true : base.IsValid) && (_DocVersionAssociations == null ? true : _DocVersionAssociations.IsValidList(list)) && (_MyFolder == null ? true : _MyFolder.IsValidList(list)) && (_MyFormat == null ? true : _MyFormat.IsValidList(list)) && (_MyItem == null ? true : _MyItem.IsValidList(list)); return ((IsNew && !IsDirty) || base.IsValid) && (_DocVersionAssociations == null || _DocVersionAssociations.IsValidList(list)) && (_MyFolder == null || _MyFolder.IsValidList(list)) && (_MyFormat == null || _MyFormat.IsValidList(list)) && (_MyItem == null || _MyItem.IsValidList(list));
} }
// CSLATODO: Replace base DocVersion.ToString function as necessary
/// <summary>
/// Overrides Base ToString
/// </summary>
/// <returns>A string representation of current DocVersion</returns>
//public override string ToString()
//{
// return base.ToString();
//}
// CSLATODO: Check DocVersion.GetIdValue to assure that the ID returned is unique // CSLATODO: Check DocVersion.GetIdValue to assure that the ID returned is unique
/// <summary> /// <summary>
/// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// Overrides Base GetIdValue - Used internally by CSLA to determine equality
/// </summary> /// </summary>
/// <returns>A Unique ID for the current DocVersion</returns> /// <returns>A Unique ID for the current DocVersion</returns>
protected override object GetIdValue() protected override object GetIdValue() => MyDocVersionUnique; // Absolutely Unique ID
{
return MyDocVersionUnique; // Absolutely Unique ID
}
#endregion #endregion
#region ValidationRules #region ValidationRules
[NonSerialized] [NonSerialized]
@@ -442,8 +418,8 @@ namespace VEPROMS.CSLA.Library
get get
{ {
IVEHasBrokenRules hasBrokenRules = HasBrokenRules; IVEHasBrokenRules hasBrokenRules = HasBrokenRules;
if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; if (Equals(hasBrokenRules)) return BrokenRulesCollection;
return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); return hasBrokenRules?.BrokenRules;
} }
} }
protected override void AddBusinessRules() protected override void AddBusinessRules()
@@ -483,41 +459,10 @@ namespace VEPROMS.CSLA.Library
} }
return true; return true;
} }
// Sample data comparison validation rule
//private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e)
//{
// if (_started > _ended)
// {
// e.Description = "Start date can't be after end date";
// return false;
// }
// else
// return true;
//}
#endregion #endregion
#region Authorization Rules #region Authorization Rules
protected override void AddAuthorizationRules() protected override void AddAuthorizationRules()
{ {
//CSLATODO: Who can read/write which fields
//AuthorizationRules.AllowRead(VersionID, "<Role(s)>");
//AuthorizationRules.AllowRead(FolderID, "<Role(s)>");
//AuthorizationRules.AllowRead(VersionType, "<Role(s)>");
//AuthorizationRules.AllowRead(Name, "<Role(s)>");
//AuthorizationRules.AllowRead(Title, "<Role(s)>");
//AuthorizationRules.AllowRead(ItemID, "<Role(s)>");
//AuthorizationRules.AllowRead(FormatID, "<Role(s)>");
//AuthorizationRules.AllowRead(Config, "<Role(s)>");
//AuthorizationRules.AllowRead(DTS, "<Role(s)>");
//AuthorizationRules.AllowRead(UserID, "<Role(s)>");
//AuthorizationRules.AllowWrite(FolderID, "<Role(s)>");
//AuthorizationRules.AllowWrite(VersionType, "<Role(s)>");
//AuthorizationRules.AllowWrite(Name, "<Role(s)>");
//AuthorizationRules.AllowWrite(Title, "<Role(s)>");
//AuthorizationRules.AllowWrite(ItemID, "<Role(s)>");
//AuthorizationRules.AllowWrite(FormatID, "<Role(s)>");
//AuthorizationRules.AllowWrite(Config, "<Role(s)>");
//AuthorizationRules.AllowWrite(DTS, "<Role(s)>");
//AuthorizationRules.AllowWrite(UserID, "<Role(s)>");
_DocVersionExtension.AddAuthorizationRules(AuthorizationRules); _DocVersionExtension.AddAuthorizationRules(AuthorizationRules);
} }
protected override void AddInstanceAuthorizationRules() protected override void AddInstanceAuthorizationRules()
@@ -525,55 +470,14 @@ namespace VEPROMS.CSLA.Library
//CSLATODO: Who can read/write which fields //CSLATODO: Who can read/write which fields
_DocVersionExtension.AddInstanceAuthorizationRules(AuthorizationRules); _DocVersionExtension.AddInstanceAuthorizationRules(AuthorizationRules);
} }
public static bool CanAddObject()
{
// CSLATODO: Can Add Authorization
//return Csla.ApplicationContext.User.IsInRole("ProjectManager");
return true;
}
public static bool CanGetObject()
{
// CSLATODO: CanGet Authorization
return true;
}
public static bool CanDeleteObject()
{
// CSLATODO: CanDelete Authorization
//bool result = false;
//if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true;
//if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true;
//return result;
return true;
}
/// <summary>
/// determines if related records (Foreign Keys) will keep this Item from being deleted
/// </summary>
public bool CanDelete
{
get
{
// Check to make sure that there are not any related records
int usedByCount = 0;
usedByCount += _DocVersionAssociationCount;
return (usedByCount == 0);
}
}
public static bool CanEditObject()
{
// CSLATODO: CanEdit Authorization
//return Csla.ApplicationContext.User.IsInRole("ProjectManager");
return true;
}
#endregion #endregion
#region Factory Methods #region Factory Methods
public int CurrentEditLevel public int CurrentEditLevel => EditLevel;
{ get { return EditLevel; } }
private static int _DocVersionUnique = 0; private static int _DocVersionUnique = 0;
protected static int DocVersionUnique protected static int DocVersionUnique => ++_DocVersionUnique;
{ get { return ++_DocVersionUnique; } } private readonly int _MyDocVersionUnique = DocVersionUnique;
private int _MyDocVersionUnique = DocVersionUnique; // Absolutely Unique ID - Editable
public int MyDocVersionUnique // Absolutely Unique ID - Editable public int MyDocVersionUnique => _MyDocVersionUnique;
{ get { return _MyDocVersionUnique; } }
protected DocVersion() protected DocVersion()
{/* require use of factory methods */ {/* require use of factory methods */
AddToCache(this); AddToCache(this);
@@ -582,15 +486,11 @@ namespace VEPROMS.CSLA.Library
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~DocVersion() ~DocVersion()
{ {
_CountFinalized++; _CountFinalized++;
@@ -615,8 +515,6 @@ namespace VEPROMS.CSLA.Library
} }
public static DocVersion New() public static DocVersion New()
{ {
if (!CanAddObject())
throw new System.Security.SecurityException("User not authorized to add a DocVersion");
try try
{ {
return DataPortal.Create<DocVersion>(); return DataPortal.Create<DocVersion>();
@@ -692,8 +590,6 @@ namespace VEPROMS.CSLA.Library
} }
public static DocVersion Get(int versionID) public static DocVersion Get(int versionID)
{ {
if (!CanGetObject())
throw new System.Security.SecurityException("User not authorized to view a DocVersion");
try try
{ {
DocVersion tmp = GetCachedByPrimaryKey(versionID); DocVersion tmp = GetCachedByPrimaryKey(versionID);
@@ -725,8 +621,6 @@ namespace VEPROMS.CSLA.Library
} }
public static void Delete(int versionID) public static void Delete(int versionID)
{ {
if (!CanDeleteObject())
throw new System.Security.SecurityException("User not authorized to remove a DocVersion");
try try
{ {
DataPortal.Delete(new PKCriteria(versionID)); DataPortal.Delete(new PKCriteria(versionID));
@@ -738,12 +632,6 @@ namespace VEPROMS.CSLA.Library
} }
public override DocVersion Save() public override DocVersion Save()
{ {
if (IsDeleted && !CanDeleteObject())
throw new System.Security.SecurityException("User not authorized to remove a DocVersion");
else if (IsNew && !CanAddObject())
throw new System.Security.SecurityException("User not authorized to add a DocVersion");
else if (!CanEditObject())
throw new System.Security.SecurityException("User not authorized to update a DocVersion");
try try
{ {
BuildRefreshList(); BuildRefreshList();
@@ -763,13 +651,9 @@ namespace VEPROMS.CSLA.Library
[Serializable()] [Serializable()]
protected class PKCriteria protected class PKCriteria
{ {
private int _VersionID; private readonly int _VersionID;
public int VersionID public int VersionID => _VersionID;
{ get { return _VersionID; } } public PKCriteria(int versionID) => _VersionID = versionID;
public PKCriteria(int versionID)
{
_VersionID = versionID;
}
} }
// CSLATODO: If Create needs to access DB - It should not be marked RunLocal // CSLATODO: If Create needs to access DB - It should not be marked RunLocal
[RunLocal()] [RunLocal()]
@@ -848,7 +732,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("DocVersion.DataPortal_Fetch", ex); throw new DbCslaException("DocVersion.DataPortal_Fetch", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Insert() protected override void DataPortal_Insert()
{ {
try try
@@ -873,47 +757,55 @@ namespace VEPROMS.CSLA.Library
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocVersion.DataPortal_Insert", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocVersion.DataPortal_Insert", GetHashCode());
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
internal void SQLInsert() internal void SQLInsert()
{ {
if (!this.IsDirty) return; if (!IsDirty) return;
try try
{ {
if (_MyFolder != null) _MyFolder.Update(); _MyFolder?.Update();
if (_MyFormat != null) _MyFormat.Update(); _MyFormat?.Update();
if (_MyItem != null) _MyItem.Update(); _MyItem?.Update();
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = Database.VEPROMS_SqlConnection)
using (SqlCommand cm = cn.CreateCommand())
{ {
cm.CommandType = CommandType.StoredProcedure; if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
cm.CommandTimeout = Database.SQLTimeout; using (SqlCommand cm = cn.CreateCommand())
cm.CommandText = "addDocVersion"; {
// Input All Fields - Except Calculated Columns cm.CommandType = CommandType.StoredProcedure;
cm.Parameters.AddWithValue("@FolderID", FolderID); cm.CommandTimeout = Database.SQLTimeout;
cm.Parameters.AddWithValue("@VersionType", _VersionType); cm.CommandText = "addDocVersion";
cm.Parameters.AddWithValue("@Name", _Name); // Input All Fields - Except Calculated Columns
cm.Parameters.AddWithValue("@Title", _Title); cm.Parameters.AddWithValue("@FolderID", FolderID);
cm.Parameters.AddWithValue("@ItemID", ItemID); cm.Parameters.AddWithValue("@VersionType", _VersionType);
cm.Parameters.AddWithValue("@FormatID", FormatID); cm.Parameters.AddWithValue("@Name", _Name);
cm.Parameters.AddWithValue("@Config", _Config); cm.Parameters.AddWithValue("@Title", _Title);
if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); cm.Parameters.AddWithValue("@ItemID", ItemID);
cm.Parameters.AddWithValue("@UserID", _UserID); cm.Parameters.AddWithValue("@FormatID", FormatID);
// Output Calculated Columns cm.Parameters.AddWithValue("@Config", _Config);
SqlParameter param_VersionID = new SqlParameter("@newVersionID", SqlDbType.Int); if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS);
param_VersionID.Direction = ParameterDirection.Output; cm.Parameters.AddWithValue("@UserID", _UserID);
cm.Parameters.Add(param_VersionID); // Output Calculated Columns
SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); SqlParameter param_VersionID = new SqlParameter("@newVersionID", SqlDbType.Int)
param_LastChanged.Direction = ParameterDirection.Output; {
cm.Parameters.Add(param_LastChanged); Direction = ParameterDirection.Output
// CSLATODO: Define any additional output parameters };
cm.ExecuteNonQuery(); cm.Parameters.Add(param_VersionID);
// Save all values being returned from the Procedure SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp)
_VersionID = (int)cm.Parameters["@newVersionID"].Value; {
_LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; Direction = ParameterDirection.Output
};
cm.Parameters.Add(param_LastChanged);
// CSLATODO: Define any additional output parameters
cm.ExecuteNonQuery();
// Save all values being returned from the Procedure
_VersionID = (int)cm.Parameters["@newVersionID"].Value;
_LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value;
}
} }
MarkOld(); MarkOld();
// update child objects // update child objects
if (_DocVersionAssociations != null) _DocVersionAssociations.Update(this); _DocVersionAssociations?.Update(this);
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocVersion.SQLInsert", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocVersion.SQLInsert", GetHashCode());
} }
catch (Exception ex) catch (Exception ex)
@@ -923,7 +815,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("DocVersion.SQLInsert", ex); throw new DbCslaException("DocVersion.SQLInsert", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
public static byte[] Add(SqlConnection cn, ref int versionID, Folder myFolder, int versionType, string name, string title, Item myItem, Format myFormat, string config, DateTime dts, string userID) public static byte[] Add(SqlConnection cn, ref int versionID, Folder myFolder, int versionType, string name, string title, Item myItem, Format myFormat, string config, DateTime dts, string userID)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocVersion.Add", 0); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocVersion.Add", 0);
@@ -945,11 +837,15 @@ namespace VEPROMS.CSLA.Library
if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts); if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts);
cm.Parameters.AddWithValue("@UserID", userID); cm.Parameters.AddWithValue("@UserID", userID);
// Output Calculated Columns // Output Calculated Columns
SqlParameter param_VersionID = new SqlParameter("@newVersionID", SqlDbType.Int); SqlParameter param_VersionID = new SqlParameter("@newVersionID", SqlDbType.Int)
param_VersionID.Direction = ParameterDirection.Output; {
Direction = ParameterDirection.Output
};
cm.Parameters.Add(param_VersionID); cm.Parameters.Add(param_VersionID);
SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp)
param_LastChanged.Direction = ParameterDirection.Output; {
Direction = ParameterDirection.Output
};
cm.Parameters.Add(param_LastChanged); cm.Parameters.Add(param_LastChanged);
// CSLATODO: Define any additional output parameters // CSLATODO: Define any additional output parameters
cm.ExecuteNonQuery(); cm.ExecuteNonQuery();
@@ -964,7 +860,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("DocVersion.Add", ex); throw new DbCslaException("DocVersion.Add", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Update() protected override void DataPortal_Update()
{ {
if (!IsDirty) return; // If not dirty - nothing to do if (!IsDirty) return; // If not dirty - nothing to do
@@ -987,49 +883,55 @@ namespace VEPROMS.CSLA.Library
if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; if (!ex.Message.EndsWith("has been edited by another user.")) throw ex;
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
internal void SQLUpdate() internal void SQLUpdate()
{ {
if (!IsDirty) return; // If not dirty - nothing to do if (!IsDirty) return; // If not dirty - nothing to do
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocVersion.SQLUpdate", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocVersion.SQLUpdate", GetHashCode());
try try
{ {
if (_MyFolder != null) _MyFolder.Update(); _MyFolder?.Update();
if (_MyFormat != null) _MyFormat.Update(); _MyFormat?.Update();
if (_MyItem != null) _MyItem.Update(); _MyItem?.Update();
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = Database.VEPROMS_SqlConnection)
if (base.IsDirty)
{ {
using (SqlCommand cm = cn.CreateCommand()) if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
if (base.IsDirty)
{ {
cm.CommandType = CommandType.StoredProcedure; using (SqlCommand cm = cn.CreateCommand())
cm.CommandTimeout = Database.SQLTimeout; {
cm.CommandText = "updateDocVersion"; cm.CommandType = CommandType.StoredProcedure;
// All Fields including Calculated Fields cm.CommandTimeout = Database.SQLTimeout;
cm.Parameters.AddWithValue("@VersionID", _VersionID); cm.CommandText = "updateDocVersion";
cm.Parameters.AddWithValue("@FolderID", FolderID); // All Fields including Calculated Fields
cm.Parameters.AddWithValue("@VersionType", _VersionType); cm.Parameters.AddWithValue("@VersionID", _VersionID);
cm.Parameters.AddWithValue("@Name", _Name); cm.Parameters.AddWithValue("@FolderID", FolderID);
cm.Parameters.AddWithValue("@Title", _Title); cm.Parameters.AddWithValue("@VersionType", _VersionType);
cm.Parameters.AddWithValue("@ItemID", ItemID); cm.Parameters.AddWithValue("@Name", _Name);
cm.Parameters.AddWithValue("@FormatID", FormatID); cm.Parameters.AddWithValue("@Title", _Title);
cm.Parameters.AddWithValue("@Config", _Config); cm.Parameters.AddWithValue("@ItemID", ItemID);
if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); cm.Parameters.AddWithValue("@FormatID", FormatID);
cm.Parameters.AddWithValue("@UserID", _UserID); cm.Parameters.AddWithValue("@Config", _Config);
cm.Parameters.AddWithValue("@LastChanged", _LastChanged); if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS);
// Output Calculated Columns cm.Parameters.AddWithValue("@UserID", _UserID);
SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); cm.Parameters.AddWithValue("@LastChanged", _LastChanged);
param_LastChanged.Direction = ParameterDirection.Output; // Output Calculated Columns
cm.Parameters.Add(param_LastChanged); SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp)
// CSLATODO: Define any additional output parameters {
cm.ExecuteNonQuery(); Direction = ParameterDirection.Output
// Save all values being returned from the Procedure };
_LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; cm.Parameters.Add(param_LastChanged);
// CSLATODO: Define any additional output parameters
cm.ExecuteNonQuery();
// Save all values being returned from the Procedure
_LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value;
}
} }
} }
MarkOld(); MarkOld();
// use the open connection to update child objects // use the open connection to update child objects
if (_DocVersionAssociations != null) _DocVersionAssociations.Update(this); _DocVersionAssociations?.Update(this);
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -1040,19 +942,23 @@ namespace VEPROMS.CSLA.Library
} }
internal void Update() internal void Update()
{ {
if (!this.IsDirty) return; if (!IsDirty) return;
if (base.IsDirty) if (base.IsDirty)
{ {
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = Database.VEPROMS_SqlConnection)
if (IsNew) {
_LastChanged = DocVersion.Add(cn, ref _VersionID, _MyFolder, _VersionType, _Name, _Title, _MyItem, _MyFormat, _Config, _DTS, _UserID); if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
else if (IsNew)
_LastChanged = DocVersion.Update(cn, ref _VersionID, _FolderID, _VersionType, _Name, _Title, _ItemID, _FormatID, _Config, _DTS, _UserID, ref _LastChanged); _LastChanged = DocVersion.Add(cn, ref _VersionID, _MyFolder, _VersionType, _Name, _Title, _MyItem, _MyFormat, _Config, _DTS, _UserID);
else
_LastChanged = DocVersion.Update(cn, ref _VersionID, _FolderID, _VersionType, _Name, _Title, _ItemID, _FormatID, _Config, _DTS, _UserID, ref _LastChanged);
}
MarkOld(); MarkOld();
} }
if (_DocVersionAssociations != null) _DocVersionAssociations.Update(this); _DocVersionAssociations?.Update(this);
} }
[Transactional(TransactionalTypes.TransactionScope)]
public static byte[] Update(SqlConnection cn, ref int versionID, int folderID, int versionType, string name, string title, int? itemID, int? formatID, string config, DateTime dts, string userID, ref byte[] lastChanged) public static byte[] Update(SqlConnection cn, ref int versionID, int folderID, int versionType, string name, string title, int? itemID, int? formatID, string config, DateTime dts, string userID, ref byte[] lastChanged)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocVersion.Update", 0); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocVersion.Update", 0);
@@ -1076,8 +982,10 @@ namespace VEPROMS.CSLA.Library
cm.Parameters.AddWithValue("@UserID", userID); cm.Parameters.AddWithValue("@UserID", userID);
cm.Parameters.AddWithValue("@LastChanged", lastChanged); cm.Parameters.AddWithValue("@LastChanged", lastChanged);
// Output Calculated Columns // Output Calculated Columns
SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp)
param_LastChanged.Direction = ParameterDirection.Output; {
Direction = ParameterDirection.Output
};
cm.Parameters.Add(param_LastChanged); cm.Parameters.Add(param_LastChanged);
// CSLATODO: Define any additional output parameters // CSLATODO: Define any additional output parameters
cm.ExecuteNonQuery(); cm.ExecuteNonQuery();
@@ -1091,12 +999,12 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("DocVersion.Update", ex); throw new DbCslaException("DocVersion.Update", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_DeleteSelf() protected override void DataPortal_DeleteSelf()
{ {
DataPortal_Delete(new PKCriteria(_VersionID)); DataPortal_Delete(new PKCriteria(_VersionID));
} }
[Transactional(TransactionalTypes.TransactionScope)]
private void DataPortal_Delete(PKCriteria criteria) private void DataPortal_Delete(PKCriteria criteria)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocVersion.DataPortal_Delete", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocVersion.DataPortal_Delete", GetHashCode());
@@ -1121,7 +1029,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("DocVersion.DataPortal_Delete", ex); throw new DbCslaException("DocVersion.DataPortal_Delete", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
public static void Remove(SqlConnection cn, int versionID) public static void Remove(SqlConnection cn, int versionID)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocVersion.Remove", 0); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocVersion.Remove", 0);
@@ -1162,16 +1070,10 @@ namespace VEPROMS.CSLA.Library
[Serializable()] [Serializable()]
private class ExistsCommand : CommandBase private class ExistsCommand : CommandBase
{ {
private int _VersionID; private readonly int _VersionID;
private bool _exists; private bool _exists;
public bool Exists public bool Exists => _exists;
{ public ExistsCommand(int versionID) => _VersionID = versionID;
get { return _exists; }
}
public ExistsCommand(int versionID)
{
_VersionID = versionID;
}
protected override void DataPortal_Execute() protected override void DataPortal_Execute()
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocVersion.DataPortal_Execute", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocVersion.DataPortal_Execute", GetHashCode());
@@ -1179,7 +1081,7 @@ namespace VEPROMS.CSLA.Library
{ {
using (SqlConnection cn = Database.VEPROMS_SqlConnection) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
cn.Open(); if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
using (SqlCommand cm = cn.CreateCommand()) using (SqlCommand cm = cn.CreateCommand())
{ {
cm.CommandType = CommandType.StoredProcedure; cm.CommandType = CommandType.StoredProcedure;
@@ -1201,7 +1103,7 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
// Standard Default Code // Standard Default Code
#region extension #region extension
DocVersionExtension _DocVersionExtension = new DocVersionExtension(); readonly DocVersionExtension _DocVersionExtension = new DocVersionExtension();
[Serializable()] [Serializable()]
partial class DocVersionExtension : extensionBase partial class DocVersionExtension : extensionBase
{ {
@@ -1210,18 +1112,9 @@ namespace VEPROMS.CSLA.Library
class extensionBase class extensionBase
{ {
// Default Values // Default Values
public virtual int DefaultVersionType public virtual int DefaultVersionType => 0;
{ public virtual DateTime DefaultDTS => DateTime.Now;
get { return 0; } public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID;
}
public virtual DateTime DefaultDTS
{
get { return DateTime.Now; }
}
public virtual string DefaultUserID
{
get { return Volian.Base.Library.VlnSettings.UserID; }
}
// Authorization Rules // Authorization Rules
public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules)
{ {
@@ -1250,61 +1143,13 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is DocVersion) if (destType == typeof(string) && value is DocVersion version)
{ {
// Return the ToString value // Return the ToString value
return ((DocVersion)value).ToString(); return version.ToString();
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
} }
#endregion #endregion
} // Namespace } // Namespace
//// The following is a sample Extension File. You can use it to create DocVersionExt.cs
//using System;
//using System.Collections.Generic;
//using System.Text;
//using Csla;
//namespace VEPROMS.CSLA.Library
//{
// public partial class DocVersion
// {
// partial class DocVersionExtension : extensionBase
// {
// // CSLATODO: Override automatic defaults
// public virtual int DefaultVersionType
// {
// get { return 0; }
// }
// public virtual DateTime DefaultDTS
// {
// get { return DateTime.Now; }
// }
// public virtual string DefaultUserID
// {
// get { return Environment.UserName.ToUpper(); }
// }
// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules)
// {
// //rules.AllowRead(Dbid, "<Role(s)>");
// }
// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules)
// {
// //rules.AllowInstanceRead(Dbid, "<Role(s)>");
// }
// public new void AddValidationRules(Csla.Validation.ValidationRules rules)
// {
// rules.AddRule(
// Csla.Validation.CommonRules.StringMaxLength,
// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100));
// }
// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules)
// {
// rules.AddInstanceRule(/* Instance Validation Rule */);
// }
// }
// }
//}
@@ -9,12 +9,9 @@
// ======================================================================== // ========================================================================
using System; using System;
using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
using Csla.Validation; using Csla.Validation;
@@ -31,11 +28,8 @@ namespace VEPROMS.CSLA.Library
private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endregion #endregion
#region Business Methods #region Business Methods
private string _ErrorMessage = string.Empty; private readonly string _ErrorMessage = string.Empty;
public string ErrorMessage public string ErrorMessage => _ErrorMessage;
{
get { return _ErrorMessage; }
}
private int _AssociationID; private int _AssociationID;
[System.ComponentModel.DataObjectField(true, true)] [System.ComponentModel.DataObjectField(true, true)]
public int AssociationID public int AssociationID
@@ -145,15 +139,6 @@ namespace VEPROMS.CSLA.Library
} }
} }
private byte[] _LastChanged = new byte[8];//timestamp private byte[] _LastChanged = new byte[8];//timestamp
private int _ROFst_RODbID;
public int ROFst_RODbID
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
return _ROFst_RODbID;
}
}
private byte[] _ROFst_ROLookup; private byte[] _ROFst_ROLookup;
public byte[] ROFst_ROLookup public byte[] ROFst_ROLookup
{ {
@@ -163,7 +148,7 @@ namespace VEPROMS.CSLA.Library
return _ROFst_ROLookup; return _ROFst_ROLookup;
} }
} }
private string _ROFst_Config = string.Empty; private readonly string _ROFst_Config = string.Empty;
public string ROFst_Config public string ROFst_Config
{ {
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
@@ -172,7 +157,7 @@ namespace VEPROMS.CSLA.Library
return _ROFst_Config; return _ROFst_Config;
} }
} }
private DateTime _ROFst_DTS = new DateTime(); private readonly DateTime _ROFst_DTS = new DateTime();
public DateTime ROFst_DTS public DateTime ROFst_DTS
{ {
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
@@ -181,7 +166,7 @@ namespace VEPROMS.CSLA.Library
return _ROFst_DTS; return _ROFst_DTS;
} }
} }
private string _ROFst_UserID = string.Empty; private readonly string _ROFst_UserID = string.Empty;
public string ROFst_UserID public string ROFst_UserID
{ {
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
@@ -195,10 +180,7 @@ namespace VEPROMS.CSLA.Library
/// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// Overrides Base GetIdValue - Used internally by CSLA to determine equality
/// </summary> /// </summary>
/// <returns>A Unique ID for the current DocVersionAssociation</returns> /// <returns>A Unique ID for the current DocVersionAssociation</returns>
protected override object GetIdValue() protected override object GetIdValue() => MyDocVersionAssociationUnique; // Absolutely Unique ID
{
return MyDocVersionAssociationUnique; // Absolutely Unique ID
}
// CSLATODO: Replace base DocVersionAssociation.ToString function as necessary // CSLATODO: Replace base DocVersionAssociation.ToString function as necessary
/// <summary> /// <summary>
/// Overrides Base ToString /// Overrides Base ToString
@@ -222,18 +204,15 @@ namespace VEPROMS.CSLA.Library
if (base.IsDirty || list.Contains(this)) if (base.IsDirty || list.Contains(this))
return base.IsDirty; return base.IsDirty;
list.Add(this); list.Add(this);
return base.IsDirty || (_MyROFst == null ? false : _MyROFst.IsDirtyList(list)); return base.IsDirty || (_MyROFst != null && _MyROFst.IsDirtyList(list));
}
public override bool IsValid
{
get { return IsValidList(new List<object>()); }
} }
public override bool IsValid => IsValidList(new List<object>());
public bool IsValidList(List<object> list) public bool IsValidList(List<object> list)
{ {
if (list.Contains(this)) if (list.Contains(this))
return (IsNew && !IsDirty) ? true : base.IsValid; return (IsNew && !IsDirty) || base.IsValid;
list.Add(this); list.Add(this);
return ((IsNew && !IsDirty) ? true : base.IsValid) && (_MyROFst == null ? true : _MyROFst.IsValidList(list)); return ((IsNew && !IsDirty) || base.IsValid) && (_MyROFst == null || _MyROFst.IsValidList(list));
} }
#endregion #endregion
#region ValidationRules #region ValidationRules
@@ -264,7 +243,7 @@ namespace VEPROMS.CSLA.Library
{ {
IVEHasBrokenRules hasBrokenRules = HasBrokenRules; IVEHasBrokenRules hasBrokenRules = HasBrokenRules;
if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; if (this.Equals(hasBrokenRules)) return BrokenRulesCollection;
return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); return hasBrokenRules?.BrokenRules;
} }
} }
protected override void AddBusinessRules() protected override void AddBusinessRules()
@@ -289,76 +268,21 @@ namespace VEPROMS.CSLA.Library
} }
return true; return true;
} }
// Sample data comparison validation rule
//private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e)
//{
// if (_started > _ended)
// {
// e.Description = "Start date can't be after end date";
// return false;
// }
// else
// return true;
//}
#endregion #endregion
#region Authorization Rules #region Authorization Rules
protected override void AddAuthorizationRules() protected override void AddAuthorizationRules()
{ {
//CSLATODO: Who can read/write which fields
//AuthorizationRules.AllowRead(AssociationID, "<Role(s)>");
//AuthorizationRules.AllowRead(ROFstID, "<Role(s)>");
//AuthorizationRules.AllowWrite(ROFstID, "<Role(s)>");
//AuthorizationRules.AllowRead(Config, "<Role(s)>");
//AuthorizationRules.AllowWrite(Config, "<Role(s)>");
//AuthorizationRules.AllowRead(DTS, "<Role(s)>");
//AuthorizationRules.AllowWrite(DTS, "<Role(s)>");
//AuthorizationRules.AllowRead(UserID, "<Role(s)>");
//AuthorizationRules.AllowWrite(UserID, "<Role(s)>");
}
public static bool CanAddObject()
{
// CSLATODO: Can Add Authorization
//return Csla.ApplicationContext.User.IsInRole("ProjectManager");
return true;
}
public static bool CanGetObject()
{
// CSLATODO: CanGet Authorization
return true;
}
public static bool CanDeleteObject()
{
// CSLATODO: CanDelete Authorization
//bool result = false;
//if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true;
//if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true;
//return result;
return true;
}
public static bool CanEditObject()
{
// CSLATODO: CanEdit Authorization
//return Csla.ApplicationContext.User.IsInRole("ProjectManager");
return true;
} }
#endregion #endregion
#region Factory Methods #region Factory Methods
public int CurrentEditLevel public int CurrentEditLevel => EditLevel;
{ get { return EditLevel; } }
private static int _DocVersionAssociationUnique = 0; private static int _DocVersionAssociationUnique = 0;
private static int DocVersionAssociationUnique private static int DocVersionAssociationUnique => ++_DocVersionAssociationUnique;
{ get { return ++_DocVersionAssociationUnique; } } private readonly int _MyDocVersionAssociationUnique = DocVersionAssociationUnique;
private int _MyDocVersionAssociationUnique = DocVersionAssociationUnique; // Absolutely Unique ID - Editable FK
public int MyDocVersionAssociationUnique // Absolutely Unique ID - Editable FK public int MyDocVersionAssociationUnique => _MyDocVersionAssociationUnique;
{ get { return _MyDocVersionAssociationUnique; } } internal static DocVersionAssociation New(ROFst myROFst) => new DocVersionAssociation(myROFst);
internal static DocVersionAssociation New(ROFst myROFst) internal static DocVersionAssociation Get(SafeDataReader dr) => new DocVersionAssociation(dr);
{
return new DocVersionAssociation(myROFst);
}
internal static DocVersionAssociation Get(SafeDataReader dr)
{
return new DocVersionAssociation(dr);
}
public DocVersionAssociation() public DocVersionAssociation()
{ {
MarkAsChild(); MarkAsChild();
@@ -386,15 +310,11 @@ namespace VEPROMS.CSLA.Library
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~DocVersionAssociation() ~DocVersionAssociation()
{ {
_CountFinalized++; _CountFinalized++;
@@ -420,12 +340,7 @@ namespace VEPROMS.CSLA.Library
dr.GetBytes("LastChanged", 0, _LastChanged, 0, 8); dr.GetBytes("LastChanged", 0, _LastChanged, 0, 8);
// B2023-020: setting RO Database on new working draft crashes. Query 'getAssociationsByVersionID' had been modified // B2023-020: setting RO Database on new working draft crashes. Query 'getAssociationsByVersionID' had been modified
// for memory improvements to not return the ROFst values, so don't Get the values. Comment out for now. // for memory improvements to not return the ROFst values, so don't Get the values. Comment out for now.
//_ROFst_RODbID = dr.GetInt32("ROFst_RODbID");
//_ROFst_ROLookup = (byte[])dr.GetValue("ROFst_ROLookup");
_ROFst_ROLookup = null; // B2022-026 RO Memory reduction - use ROlookup of null to know if we loaded the RO.FST file _ROFst_ROLookup = null; // B2022-026 RO Memory reduction - use ROlookup of null to know if we loaded the RO.FST file
//_ROFst_Config = dr.GetString("ROFst_Config");
//_ROFst_DTS = dr.GetDateTime("ROFst_DTS");
//_ROFst_UserID = dr.GetString("ROFst_UserID");
} }
catch (Exception ex) // FKItem Fetch catch (Exception ex) // FKItem Fetch
{ {
@@ -438,32 +353,45 @@ namespace VEPROMS.CSLA.Library
{ {
// if we're not dirty then don't update the database // if we're not dirty then don't update the database
if (!this.IsDirty) return; if (!this.IsDirty) return;
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = Database.VEPROMS_SqlConnection)
_LastChanged = Association.Add(cn, ref _AssociationID, myDocVersion, _MyROFst, _Config, _DTS, _UserID); {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
_LastChanged = Association.Add(cn, ref _AssociationID, myDocVersion, _MyROFst, _Config, _DTS, _UserID);
}
MarkOld(); MarkOld();
} }
internal void Update(DocVersion myDocVersion) internal void Update(DocVersion myDocVersion)
{ {
// if we're not dirty then don't update the database // if we're not dirty then don't update the database
if (!this.IsDirty) return; if (!this.IsDirty) return;
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = Database.VEPROMS_SqlConnection)
_LastChanged = Association.Update(cn, ref _AssociationID, myDocVersion.VersionID, _ROFstID, _Config, _DTS, _UserID, ref _LastChanged); {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
_LastChanged = Association.Update(cn, ref _AssociationID, myDocVersion.VersionID, _ROFstID, _Config, _DTS, _UserID, ref _LastChanged);
}
MarkOld(); MarkOld();
} }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")]
internal void DeleteSelf(DocVersion myDocVersion) internal void DeleteSelf(DocVersion myDocVersion)
{ {
// if we're not dirty then don't update the database // if we're not dirty then don't update the database
if (!this.IsDirty) return; if (!this.IsDirty) return;
// if we're new then don't update the database // if we're new then don't update the database
if (this.IsNew) return; if (this.IsNew) return;
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = Database.VEPROMS_SqlConnection)
Association.Remove(cn, _AssociationID); {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
Association.Remove(cn, _AssociationID);
}
MarkNew(); MarkNew();
} }
#endregion #endregion
// Standard Default Code // Standard Default Code
#region extension #region extension
DocVersionAssociationExtension _DocVersionAssociationExtension = new DocVersionAssociationExtension(); readonly DocVersionAssociationExtension _DocVersionAssociationExtension = new DocVersionAssociationExtension();
[Serializable()] [Serializable()]
partial class DocVersionAssociationExtension : extensionBase partial class DocVersionAssociationExtension : extensionBase
{ {
@@ -472,14 +400,8 @@ namespace VEPROMS.CSLA.Library
class extensionBase class extensionBase
{ {
// Default Values // Default Values
public virtual DateTime DefaultDTS public virtual DateTime DefaultDTS => DateTime.Now;
{ public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID;
get { return DateTime.Now; }
}
public virtual string DefaultUserID
{
get { return Volian.Base.Library.VlnSettings.UserID; }
}
// Authorization Rules // Authorization Rules
public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules)
{ {
@@ -508,57 +430,13 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is DocVersionAssociation) if (destType == typeof(string) && value is DocVersionAssociation association)
{ {
// Return the ToString value // Return the ToString value
return ((DocVersionAssociation)value).ToString(); return association.ToString();
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
} }
#endregion #endregion
} // Namespace } // Namespace
//// The following is a sample Extension File. You can use it to create DocVersionAssociationExt.cs
//using System;
//using System.Collections.Generic;
//using System.Text;
//using Csla;
//namespace VEPROMS.CSLA.Library
//{
// public partial class DocVersionAssociation
// {
// partial class DocVersionAssociationExtension : extensionBase
// {
// // CSLATODO: Override automatic defaults
// public virtual DateTime DefaultDTS
// {
// get { return DateTime.Now; }
// }
// public virtual string DefaultUserID
// {
// get { return Environment.UserName.ToUpper(); }
// }
// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules)
// {
// //rules.AllowRead(Dbid, "<Role(s)>");
// }
// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules)
// {
// //rules.AllowInstanceRead(Dbid, "<Role(s)>");
// }
// public new void AddValidationRules(Csla.Validation.ValidationRules rules)
// {
// rules.AddRule(
// Csla.Validation.CommonRules.StringMaxLength,
// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100));
// }
// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules)
// {
// rules.AddInstanceRule(/* Instance Validation Rule */);
// }
// }
// }
//}
@@ -13,8 +13,6 @@ using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
using Csla.Validation; using Csla.Validation;
@@ -31,13 +29,10 @@ namespace VEPROMS.CSLA.Library
private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endregion #endregion
#region Business Methods #region Business Methods
private string _ErrorMessage = string.Empty; private readonly string _ErrorMessage = string.Empty;
public string ErrorMessage public string ErrorMessage => _ErrorMessage;
{ // One To Many
get { return _ErrorMessage; } public DocVersionAssociation this[Association myAssociation]
}
// One To Many
public DocVersionAssociation this[Association myAssociation]
{ {
get get
{ {
@@ -47,11 +42,8 @@ namespace VEPROMS.CSLA.Library
return null; return null;
} }
} }
public new System.Collections.Generic.IList<DocVersionAssociation> Items public new System.Collections.Generic.IList<DocVersionAssociation> Items => base.Items;
{ public DocVersionAssociation GetItem(Association myAssociation)
get { return base.Items; }
}
public DocVersionAssociation GetItem(Association myAssociation)
{ {
foreach (DocVersionAssociation association in this) foreach (DocVersionAssociation association in this)
if (association.AssociationID == myAssociation.AssociationID) if (association.AssociationID == myAssociation.AssociationID)
@@ -63,7 +55,7 @@ namespace VEPROMS.CSLA.Library
if (!Contains(myROFst)) if (!Contains(myROFst))
{ {
DocVersionAssociation association = DocVersionAssociation.New(myROFst); DocVersionAssociation association = DocVersionAssociation.New(myROFst);
this.Add(association); Add(association);
return association; return association;
} }
else else
@@ -113,18 +105,18 @@ namespace VEPROMS.CSLA.Library
get { return IsValidList(new List<object>()); } get { return IsValidList(new List<object>()); }
} }
public bool IsValidList(List<object> list) public bool IsValidList(List<object> list)
{ {
// run through all the child objects // run through all the child objects
// and if any are invalid then the // and if any are invalid then the
// collection is invalid // collection is invalid
foreach (DocVersionAssociation child in this) foreach (DocVersionAssociation child in this)
if (!child.IsValidList(list)) if (!child.IsValidList(list))
{ {
//Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString());
return false; return false;
} }
return true; return true;
} }
public bool Contains(ROFst myROFst) public bool Contains(ROFst myROFst)
{ {
foreach (DocVersionAssociation association in this) foreach (DocVersionAssociation association in this)
@@ -156,20 +148,14 @@ namespace VEPROMS.CSLA.Library
get get
{ {
IVEHasBrokenRules hasBrokenRules = HasBrokenRules; IVEHasBrokenRules hasBrokenRules = HasBrokenRules;
return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); return hasBrokenRules?.BrokenRules;
} }
} }
#endregion #endregion
#region Factory Methods #region Factory Methods
internal static DocVersionAssociations New() internal static DocVersionAssociations New() => new DocVersionAssociations();
{ internal static DocVersionAssociations Get(SafeDataReader dr) => new DocVersionAssociations(dr);
return new DocVersionAssociations(); public static DocVersionAssociations GetByVersionID(int versionID)
}
internal static DocVersionAssociations Get(SafeDataReader dr)
{
return new DocVersionAssociations(dr);
}
public static DocVersionAssociations GetByVersionID(int versionID)
{ {
try try
{ {
@@ -180,11 +166,8 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Error on DocVersionAssociations.GetByVersionID", ex); throw new DbCslaException("Error on DocVersionAssociations.GetByVersionID", ex);
} }
} }
private DocVersionAssociations() private DocVersionAssociations() => MarkAsChild();
{ internal DocVersionAssociations(SafeDataReader dr)
MarkAsChild();
}
internal DocVersionAssociations(SafeDataReader dr)
{ {
MarkAsChild(); MarkAsChild();
Fetch(dr); Fetch(dr);
@@ -193,16 +176,12 @@ namespace VEPROMS.CSLA.Library
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed ~DocVersionAssociations()
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~DocVersionAssociations()
{ {
_CountFinalized++; _CountFinalized++;
} }
@@ -217,19 +196,16 @@ namespace VEPROMS.CSLA.Library
// called to load data from the database // called to load data from the database
private void Fetch(SafeDataReader dr) private void Fetch(SafeDataReader dr)
{ {
this.RaiseListChangedEvents = false; RaiseListChangedEvents = false;
while (dr.Read()) while (dr.Read())
this.Add(DocVersionAssociation.Get(dr)); Add(DocVersionAssociation.Get(dr));
this.RaiseListChangedEvents = true; RaiseListChangedEvents = true;
} }
[Serializable()] [Serializable()]
private class VersionIDCriteria private class VersionIDCriteria
{ {
public VersionIDCriteria(int versionID) public VersionIDCriteria(int versionID) => _VersionID = versionID;
{ private int _VersionID;
_VersionID = versionID;
}
private int _VersionID;
public int VersionID public int VersionID
{ {
get { return _VersionID; } get { return _VersionID; }
@@ -238,7 +214,7 @@ namespace VEPROMS.CSLA.Library
} }
private void DataPortal_Fetch(VersionIDCriteria criteria) private void DataPortal_Fetch(VersionIDCriteria criteria)
{ {
this.RaiseListChangedEvents = false; RaiseListChangedEvents = false;
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocVersionAssociations.DataPortal_FetchVersionID", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocVersionAssociations.DataPortal_FetchVersionID", GetHashCode());
try try
{ {
@@ -252,7 +228,7 @@ namespace VEPROMS.CSLA.Library
cm.CommandTimeout = Database.DefaultTimeout; cm.CommandTimeout = Database.DefaultTimeout;
using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
{ {
while (dr.Read()) this.Add(new DocVersionAssociation(dr)); while (dr.Read()) Add(new DocVersionAssociation(dr));
} }
} }
} }
@@ -262,11 +238,11 @@ namespace VEPROMS.CSLA.Library
if (_MyLog.IsErrorEnabled) _MyLog.Error("DocVersionAssociations.DataPortal_FetchVersionID", ex); if (_MyLog.IsErrorEnabled) _MyLog.Error("DocVersionAssociations.DataPortal_FetchVersionID", ex);
throw new DbCslaException("DocVersionAssociations.DataPortal_Fetch", ex); throw new DbCslaException("DocVersionAssociations.DataPortal_Fetch", ex);
} }
this.RaiseListChangedEvents = true; RaiseListChangedEvents = true;
} }
internal void Update(DocVersion docVersion) internal void Update(DocVersion docVersion)
{ {
this.RaiseListChangedEvents = false; RaiseListChangedEvents = false;
try try
{ {
// update (thus deleting) any deleted child objects // update (thus deleting) any deleted child objects
@@ -285,49 +261,38 @@ namespace VEPROMS.CSLA.Library
} }
finally finally
{ {
this.RaiseListChangedEvents = true; RaiseListChangedEvents = true;
} }
} }
#endregion #endregion
#region ICustomTypeDescriptor impl #region ICustomTypeDescriptor impl
public String GetClassName() public string GetClassName() => TypeDescriptor.GetClassName(this, true);
{ return TypeDescriptor.GetClassName(this, true); } public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true);
public AttributeCollection GetAttributes() public string GetComponentName() => TypeDescriptor.GetComponentName(this, true);
{ return TypeDescriptor.GetAttributes(this, true); } public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true);
public String GetComponentName() public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true);
{ return TypeDescriptor.GetComponentName(this, true); } public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true);
public TypeConverter GetConverter() public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true);
{ return TypeDescriptor.GetConverter(this, true); } public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true);
public EventDescriptor GetDefaultEvent() public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true);
{ return TypeDescriptor.GetDefaultEvent(this, true); } public object GetPropertyOwner(PropertyDescriptor pd) => this;
public PropertyDescriptor GetDefaultProperty() /// <summary>
{ return TypeDescriptor.GetDefaultProperty(this, true); } /// Called to get the properties of this type. Returns properties with certain
public object GetEditor(Type editorBaseType) /// attributes. this restriction is not implemented here.
{ return TypeDescriptor.GetEditor(this, editorBaseType, true); } /// </summary>
public EventDescriptorCollection GetEvents(Attribute[] attributes) /// <param name="attributes"></param>
{ return TypeDescriptor.GetEvents(this, attributes, true); } /// <returns></returns>
public EventDescriptorCollection GetEvents() public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties();
{ return TypeDescriptor.GetEvents(this, true); } /// <summary>
public object GetPropertyOwner(PropertyDescriptor pd) /// Called to get the properties of this type.
{ return this; } /// </summary>
/// <summary> /// <returns></returns>
/// Called to get the properties of this type. Returns properties with certain public PropertyDescriptorCollection GetProperties()
/// attributes. this restriction is not implemented here.
/// </summary>
/// <param name="attributes"></param>
/// <returns></returns>
public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{ return GetProperties(); }
/// <summary>
/// Called to get the properties of this type.
/// </summary>
/// <returns></returns>
public PropertyDescriptorCollection GetProperties()
{ {
// Create a collection object to hold property descriptors // Create a collection object to hold property descriptors
PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null);
// Iterate the list // Iterate the list
for (int i = 0; i < this.Items.Count; i++) for (int i = 0; i < Items.Count; i++)
{ {
// Create a property descriptor for the item and add to the property descriptor collection // Create a property descriptor for the item and add to the property descriptor collection
DocVersionAssociationsPropertyDescriptor pd = new DocVersionAssociationsPropertyDescriptor(this, i); DocVersionAssociationsPropertyDescriptor pd = new DocVersionAssociationsPropertyDescriptor(this, i);
@@ -344,7 +309,6 @@ namespace VEPROMS.CSLA.Library
/// </summary> /// </summary>
public partial class DocVersionAssociationsPropertyDescriptor : vlnListPropertyDescriptor public partial class DocVersionAssociationsPropertyDescriptor : vlnListPropertyDescriptor
{ {
private DocVersionAssociation Item { get { return (DocVersionAssociation)_Item; } }
public DocVersionAssociationsPropertyDescriptor(DocVersionAssociations collection, int index) : base(collection, index) { ;} public DocVersionAssociationsPropertyDescriptor(DocVersionAssociations collection, int index) : base(collection, index) { ;}
} }
#endregion #endregion
@@ -353,10 +317,10 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is DocVersionAssociations) if (destType == typeof(string) && value is DocVersionAssociations associations)
{ {
// Return department and department role separated by comma. // Return department and department role separated by comma.
return ((DocVersionAssociations)value).Items.Count.ToString() + " Associations"; return $"{associations.Items.Count} Associations";
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
@@ -13,8 +13,6 @@ using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
namespace VEPROMS.CSLA.Library namespace VEPROMS.CSLA.Library
@@ -28,14 +26,12 @@ namespace VEPROMS.CSLA.Library
public partial class DocVersionInfo : ReadOnlyBase<DocVersionInfo>, IDisposable public partial class DocVersionInfo : ReadOnlyBase<DocVersionInfo>, IDisposable
{ {
public event DocVersionInfoEvent Changed; public event DocVersionInfoEvent Changed;
private void OnChange() private void OnChange() => Changed?.Invoke(this);
{
if (Changed != null) Changed(this);
}
#region Log4Net #region Log4Net
private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endregion #endregion
#region Collection #region Collection
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static List<DocVersionInfo> _CacheList = new List<DocVersionInfo>(); private static List<DocVersionInfo> _CacheList = new List<DocVersionInfo>();
protected static void AddToCache(DocVersionInfo docVersionInfo) protected static void AddToCache(DocVersionInfo docVersionInfo)
{ {
@@ -45,6 +41,7 @@ namespace VEPROMS.CSLA.Library
{ {
while (_CacheList.Contains(docVersionInfo)) _CacheList.Remove(docVersionInfo); // In RemoveFromCache while (_CacheList.Contains(docVersionInfo)) _CacheList.Remove(docVersionInfo); // In RemoveFromCache
} }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static Dictionary<string, List<DocVersionInfo>> _CacheByPrimaryKey = new Dictionary<string, List<DocVersionInfo>>(); private static Dictionary<string, List<DocVersionInfo>> _CacheByPrimaryKey = new Dictionary<string, List<DocVersionInfo>>();
private static void ConvertListToDictionary() private static void ConvertListToDictionary()
{ {
@@ -74,21 +71,8 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
#region Business Methods #region Business Methods
private string _ErrorMessage = string.Empty; private string _ErrorMessage = string.Empty;
public string ErrorMessage public string ErrorMessage => _ErrorMessage;
{
get { return _ErrorMessage; }
}
protected DocVersion _Editable; protected DocVersion _Editable;
private IVEHasBrokenRules HasBrokenRules
{
get
{
IVEHasBrokenRules hasBrokenRules = null;
if (_Editable != null)
hasBrokenRules = _Editable.HasBrokenRules;
return hasBrokenRules;
}
}
private int _VersionID; private int _VersionID;
[System.ComponentModel.DataObjectField(true, true)] [System.ComponentModel.DataObjectField(true, true)]
public int VersionID public int VersionID
@@ -252,32 +236,19 @@ namespace VEPROMS.CSLA.Library
foreach (DocVersionInfo tmp in _CacheByPrimaryKey[_VersionID.ToString()]) foreach (DocVersionInfo tmp in _CacheByPrimaryKey[_VersionID.ToString()])
tmp._DocVersionAssociationCount = -1; // This will cause the data to be requeried tmp._DocVersionAssociationCount = -1; // This will cause the data to be requeried
} }
// CSLATODO: Replace base DocVersionInfo.ToString function as necessary
/// <summary>
/// Overrides Base ToString
/// </summary>
/// <returns>A string representation of current DocVersionInfo</returns>
//public override string ToString()
//{
// return base.ToString();
//}
// CSLATODO: Check DocVersionInfo.GetIdValue to assure that the ID returned is unique // CSLATODO: Check DocVersionInfo.GetIdValue to assure that the ID returned is unique
/// <summary> /// <summary>
/// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// Overrides Base GetIdValue - Used internally by CSLA to determine equality
/// </summary> /// </summary>
/// <returns>A Unique ID for the current DocVersionInfo</returns> /// <returns>A Unique ID for the current DocVersionInfo</returns>
protected override object GetIdValue() protected override object GetIdValue() => MyDocVersionInfoUnique; // Absolutely Unique ID
{
return MyDocVersionInfoUnique; // Absolutely Unique ID
}
#endregion #endregion
#region Factory Methods #region Factory Methods
private static int _DocVersionInfoUnique = 0; private static int _DocVersionInfoUnique = 0;
private static int DocVersionInfoUnique private static int DocVersionInfoUnique => ++_DocVersionInfoUnique;
{ get { return ++_DocVersionInfoUnique; } } private readonly int _MyDocVersionInfoUnique = DocVersionInfoUnique;
private int _MyDocVersionInfoUnique = DocVersionInfoUnique; // Absolutely Unique ID - Info
public int MyDocVersionInfoUnique // Absolutely Unique ID - Info public int MyDocVersionInfoUnique => _MyDocVersionInfoUnique;
{ get { return _MyDocVersionInfoUnique; } }
protected DocVersionInfo() protected DocVersionInfo()
{/* require use of factory methods */ {/* require use of factory methods */
AddToCache(this); AddToCache(this);
@@ -286,15 +257,11 @@ namespace VEPROMS.CSLA.Library
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~DocVersionInfo() ~DocVersionInfo()
{ {
_CountFinalized++; _CountFinalized++;
@@ -311,10 +278,7 @@ namespace VEPROMS.CSLA.Library
if (listDocVersionInfo.Count == 0) // If there are no items left in the list if (listDocVersionInfo.Count == 0) // If there are no items left in the list
_CacheByPrimaryKey.Remove(VersionID.ToString()); // remove the list _CacheByPrimaryKey.Remove(VersionID.ToString()); // remove the list
} }
public virtual DocVersion Get() public virtual DocVersion Get() => _Editable = DocVersion.Get(_VersionID);
{
return _Editable = DocVersion.Get(_VersionID);
}
public static void Refresh(DocVersion tmp) public static void Refresh(DocVersion tmp)
{ {
string key = tmp.VersionID.ToString(); string key = tmp.VersionID.ToString();
@@ -327,28 +291,28 @@ namespace VEPROMS.CSLA.Library
{ {
if (_FolderID != tmp.FolderID) if (_FolderID != tmp.FolderID)
{ {
if (MyFolder != null) MyFolder.RefreshFolderDocVersions(); // Update List for old value MyFolder?.RefreshFolderDocVersions(); // Update List for old value
_FolderID = tmp.FolderID; // Update the value _FolderID = tmp.FolderID; // Update the value
} }
_MyFolder = null; // Reset list so that the next line gets a new list _MyFolder = null; // Reset list so that the next line gets a new list
if (MyFolder != null) MyFolder.RefreshFolderDocVersions(); // Update List for new value MyFolder?.RefreshFolderDocVersions(); // Update List for new value
_VersionType = tmp.VersionType; _VersionType = tmp.VersionType;
_Name = tmp.Name; _Name = tmp.Name;
_Title = tmp.Title; _Title = tmp.Title;
if (_ItemID != tmp.ItemID) if (_ItemID != tmp.ItemID)
{ {
if (MyItem != null) MyItem.RefreshItemDocVersions(); // Update List for old value MyItem?.RefreshItemDocVersions(); // Update List for old value
_ItemID = tmp.ItemID; // Update the value _ItemID = tmp.ItemID; // Update the value
} }
_MyItem = null; // Reset list so that the next line gets a new list _MyItem = null; // Reset list so that the next line gets a new list
if (MyItem != null) MyItem.RefreshItemDocVersions(); // Update List for new value MyItem?.RefreshItemDocVersions(); // Update List for new value
if (_FormatID != tmp.FormatID) if (_FormatID != tmp.FormatID)
{ {
if (MyFormat != null) MyFormat.RefreshFormatDocVersions(); // Update List for old value MyFormat?.RefreshFormatDocVersions(); // Update List for old value
_FormatID = tmp.FormatID; // Update the value _FormatID = tmp.FormatID; // Update the value
} }
_MyFormat = null; // Reset list so that the next line gets a new list _MyFormat = null; // Reset list so that the next line gets a new list
if (MyFormat != null) MyFormat.RefreshFormatDocVersions(); // Update List for new value MyFormat?.RefreshFormatDocVersions(); // Update List for new value
_Config = tmp.Config; _Config = tmp.Config;
_DTS = tmp.DTS; _DTS = tmp.DTS;
_UserID = tmp.UserID; _UserID = tmp.UserID;
@@ -370,18 +334,18 @@ namespace VEPROMS.CSLA.Library
_Title = tmp.Title; _Title = tmp.Title;
if (_ItemID != tmp.ItemID) if (_ItemID != tmp.ItemID)
{ {
if (MyItem != null) MyItem.RefreshItemDocVersions(); // Update List for old value MyItem?.RefreshItemDocVersions(); // Update List for old value
_ItemID = tmp.ItemID; // Update the value _ItemID = tmp.ItemID; // Update the value
} }
_MyItem = null; // Reset list so that the next line gets a new list _MyItem = null; // Reset list so that the next line gets a new list
if (MyItem != null) MyItem.RefreshItemDocVersions(); // Update List for new value MyItem?.RefreshItemDocVersions(); // Update List for new value
if (_FormatID != tmp.FormatID) if (_FormatID != tmp.FormatID)
{ {
if (MyFormat != null) MyFormat.RefreshFormatDocVersions(); // Update List for old value MyFormat?.RefreshFormatDocVersions(); // Update List for old value
_FormatID = tmp.FormatID; // Update the value _FormatID = tmp.FormatID; // Update the value
} }
_MyFormat = null; // Reset list so that the next line gets a new list _MyFormat = null; // Reset list so that the next line gets a new list
if (MyFormat != null) MyFormat.RefreshFormatDocVersions(); // Update List for new value MyFormat?.RefreshFormatDocVersions(); // Update List for new value
_Config = tmp.Config; _Config = tmp.Config;
_DTS = tmp.DTS; _DTS = tmp.DTS;
_UserID = tmp.UserID; _UserID = tmp.UserID;
@@ -400,21 +364,21 @@ namespace VEPROMS.CSLA.Library
{ {
if (_FolderID != tmp.FolderID) if (_FolderID != tmp.FolderID)
{ {
if (MyFolder != null) MyFolder.RefreshFolderDocVersions(); // Update List for old value MyFolder?.RefreshFolderDocVersions(); // Update List for old value
_FolderID = tmp.FolderID; // Update the value _FolderID = tmp.FolderID; // Update the value
} }
_MyFolder = null; // Reset list so that the next line gets a new list _MyFolder = null; // Reset list so that the next line gets a new list
if (MyFolder != null) MyFolder.RefreshFolderDocVersions(); // Update List for new value MyFolder?.RefreshFolderDocVersions(); // Update List for new value
_VersionType = tmp.VersionType; _VersionType = tmp.VersionType;
_Name = tmp.Name; _Name = tmp.Name;
_Title = tmp.Title; _Title = tmp.Title;
if (_ItemID != tmp.ItemID) if (_ItemID != tmp.ItemID)
{ {
if (MyItem != null) MyItem.RefreshItemDocVersions(); // Update List for old value MyItem?.RefreshItemDocVersions(); // Update List for old value
_ItemID = tmp.ItemID; // Update the value _ItemID = tmp.ItemID; // Update the value
} }
_MyItem = null; // Reset list so that the next line gets a new list _MyItem = null; // Reset list so that the next line gets a new list
if (MyItem != null) MyItem.RefreshItemDocVersions(); // Update List for new value MyItem?.RefreshItemDocVersions(); // Update List for new value
_Config = tmp.Config; _Config = tmp.Config;
_DTS = tmp.DTS; _DTS = tmp.DTS;
_UserID = tmp.UserID; _UserID = tmp.UserID;
@@ -433,21 +397,21 @@ namespace VEPROMS.CSLA.Library
{ {
if (_FolderID != tmp.FolderID) if (_FolderID != tmp.FolderID)
{ {
if (MyFolder != null) MyFolder.RefreshFolderDocVersions(); // Update List for old value MyFolder?.RefreshFolderDocVersions(); // Update List for old value
_FolderID = tmp.FolderID; // Update the value _FolderID = tmp.FolderID; // Update the value
} }
_MyFolder = null; // Reset list so that the next line gets a new list _MyFolder = null; // Reset list so that the next line gets a new list
if (MyFolder != null) MyFolder.RefreshFolderDocVersions(); // Update List for new value MyFolder?.RefreshFolderDocVersions(); // Update List for new value
_VersionType = tmp.VersionType; _VersionType = tmp.VersionType;
_Name = tmp.Name; _Name = tmp.Name;
_Title = tmp.Title; _Title = tmp.Title;
if (_FormatID != tmp.FormatID) if (_FormatID != tmp.FormatID)
{ {
if (MyFormat != null) MyFormat.RefreshFormatDocVersions(); // Update List for old value MyFormat?.RefreshFormatDocVersions(); // Update List for old value
_FormatID = tmp.FormatID; // Update the value _FormatID = tmp.FormatID; // Update the value
} }
_MyFormat = null; // Reset list so that the next line gets a new list _MyFormat = null; // Reset list so that the next line gets a new list
if (MyFormat != null) MyFormat.RefreshFormatDocVersions(); // Update List for new value MyFormat?.RefreshFormatDocVersions(); // Update List for new value
_Config = tmp.Config; _Config = tmp.Config;
_DTS = tmp.DTS; _DTS = tmp.DTS;
_UserID = tmp.UserID; _UserID = tmp.UserID;
@@ -456,8 +420,6 @@ namespace VEPROMS.CSLA.Library
} }
public static DocVersionInfo Get(int versionID) public static DocVersionInfo Get(int versionID)
{ {
//if (!CanGetObject())
// throw new System.Security.SecurityException("User not authorized to view a DocVersion");
try try
{ {
DocVersionInfo tmp = GetCachedByPrimaryKey(versionID); DocVersionInfo tmp = GetCachedByPrimaryKey(versionID);
@@ -496,13 +458,9 @@ namespace VEPROMS.CSLA.Library
[Serializable()] [Serializable()]
protected class PKCriteria protected class PKCriteria
{ {
private int _VersionID; private readonly int _VersionID;
public int VersionID public int VersionID => _VersionID;
{ get { return _VersionID; } } public PKCriteria(int versionID) => _VersionID = versionID;
public PKCriteria(int versionID)
{
_VersionID = versionID;
}
} }
private void ReadData(SafeDataReader dr) private void ReadData(SafeDataReader dr)
{ {
@@ -567,7 +525,7 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
// Standard Refresh // Standard Refresh
#region extension #region extension
DocVersionInfoExtension _DocVersionInfoExtension = new DocVersionInfoExtension(); readonly DocVersionInfoExtension _DocVersionInfoExtension = new DocVersionInfoExtension();
[Serializable()] [Serializable()]
partial class DocVersionInfoExtension : extensionBase { } partial class DocVersionInfoExtension : extensionBase { }
[Serializable()] [Serializable()]
@@ -583,10 +541,10 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is DocVersionInfo) if (destType == typeof(string) && value is DocVersionInfo info)
{ {
// Return the ToString value // Return the ToString value
return ((DocVersionInfo)value).ToString(); return info.ToString();
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
@@ -13,8 +13,6 @@ using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
namespace VEPROMS.CSLA.Library namespace VEPROMS.CSLA.Library
@@ -28,11 +26,10 @@ namespace VEPROMS.CSLA.Library
{ {
#region Log4Net #region Log4Net
private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endregion #endregion
#region Business Methods #region Business Methods
internal new IList<DocVersionInfo> Items internal new IList<DocVersionInfo> Items => base.Items;
{ get { return base.Items; } } public void AddEvents()
public void AddEvents()
{ {
foreach (DocVersionInfo tmp in this) foreach (DocVersionInfo tmp in this)
{ {
@@ -44,23 +41,19 @@ namespace VEPROMS.CSLA.Library
for (int i = 0; i < Count; i++) for (int i = 0; i < Count; i++)
{ {
if (base[i] == sender) if (base[i] == sender)
this.OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, i)); OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, i));
} }
} }
private bool _Disposed = false; private bool _Disposed = false;
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed ~DocVersionInfoList()
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~DocVersionInfoList()
{ {
_CountFinalized++; _CountFinalized++;
} }
@@ -104,18 +97,7 @@ namespace VEPROMS.CSLA.Library
{ {
_DocVersionInfoList = null; _DocVersionInfoList = null;
} }
// CSLATODO: Add alternative gets -
//public static DocVersionInfoList Get(<criteria>)
//{
// try
// {
// return DataPortal.Fetch<DocVersionInfoList>(new FilteredCriteria(<criteria>));
// }
// catch (Exception ex)
// {
// throw new DbCslaException("Error on DocVersionInfoList.Get", ex);
// }
//}
public static DocVersionInfoList GetByFolderID(int folderID) public static DocVersionInfoList GetByFolderID(int folderID)
{ {
try try
@@ -164,7 +146,7 @@ namespace VEPROMS.CSLA.Library
#region Data Access Portal #region Data Access Portal
private void DataPortal_Fetch() private void DataPortal_Fetch()
{ {
this.RaiseListChangedEvents = false; RaiseListChangedEvents = false;
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocVersionInfoList.DataPortal_Fetch", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocVersionInfoList.DataPortal_Fetch", GetHashCode());
try try
{ {
@@ -178,7 +160,7 @@ namespace VEPROMS.CSLA.Library
using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
{ {
IsReadOnly = false; IsReadOnly = false;
while (dr.Read()) this.Add(new DocVersionInfo(dr)); while (dr.Read()) Add(new DocVersionInfo(dr));
IsReadOnly = true; IsReadOnly = true;
} }
} }
@@ -189,16 +171,13 @@ namespace VEPROMS.CSLA.Library
if (_MyLog.IsErrorEnabled) _MyLog.Error("DocVersionInfoList.DataPortal_Fetch", ex); if (_MyLog.IsErrorEnabled) _MyLog.Error("DocVersionInfoList.DataPortal_Fetch", ex);
throw new DbCslaException("DocVersionInfoList.DataPortal_Fetch", ex); throw new DbCslaException("DocVersionInfoList.DataPortal_Fetch", ex);
} }
this.RaiseListChangedEvents = true; RaiseListChangedEvents = true;
} }
[Serializable()] [Serializable()]
private class FolderIDCriteria private class FolderIDCriteria
{ {
public FolderIDCriteria(int folderID) public FolderIDCriteria(int folderID) => _FolderID = folderID;
{ private int _FolderID;
_FolderID = folderID;
}
private int _FolderID;
public int FolderID public int FolderID
{ {
get { return _FolderID; } get { return _FolderID; }
@@ -207,7 +186,7 @@ namespace VEPROMS.CSLA.Library
} }
private void DataPortal_Fetch(FolderIDCriteria criteria) private void DataPortal_Fetch(FolderIDCriteria criteria)
{ {
this.RaiseListChangedEvents = false; RaiseListChangedEvents = false;
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocVersionInfoList.DataPortal_FetchFolderID", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocVersionInfoList.DataPortal_FetchFolderID", GetHashCode());
try try
{ {
@@ -222,7 +201,7 @@ namespace VEPROMS.CSLA.Library
using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
{ {
IsReadOnly = false; IsReadOnly = false;
while (dr.Read()) this.Add(new DocVersionInfo(dr)); while (dr.Read()) Add(new DocVersionInfo(dr));
IsReadOnly = true; IsReadOnly = true;
} }
} }
@@ -233,16 +212,13 @@ namespace VEPROMS.CSLA.Library
if (_MyLog.IsErrorEnabled) _MyLog.Error("DocVersionInfoList.DataPortal_FetchFolderID", ex); if (_MyLog.IsErrorEnabled) _MyLog.Error("DocVersionInfoList.DataPortal_FetchFolderID", ex);
throw new DbCslaException("DocVersionInfoList.DataPortal_Fetch", ex); throw new DbCslaException("DocVersionInfoList.DataPortal_Fetch", ex);
} }
this.RaiseListChangedEvents = true; RaiseListChangedEvents = true;
} }
[Serializable()] [Serializable()]
private class FormatIDCriteria private class FormatIDCriteria
{ {
public FormatIDCriteria(int? formatID) public FormatIDCriteria(int? formatID) => _FormatID = formatID;
{ private int? _FormatID;
_FormatID = formatID;
}
private int? _FormatID;
public int? FormatID public int? FormatID
{ {
get { return _FormatID; } get { return _FormatID; }
@@ -251,7 +227,7 @@ namespace VEPROMS.CSLA.Library
} }
private void DataPortal_Fetch(FormatIDCriteria criteria) private void DataPortal_Fetch(FormatIDCriteria criteria)
{ {
this.RaiseListChangedEvents = false; RaiseListChangedEvents = false;
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocVersionInfoList.DataPortal_FetchFormatID", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocVersionInfoList.DataPortal_FetchFormatID", GetHashCode());
try try
{ {
@@ -266,7 +242,7 @@ namespace VEPROMS.CSLA.Library
using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
{ {
IsReadOnly = false; IsReadOnly = false;
while (dr.Read()) this.Add(new DocVersionInfo(dr)); while (dr.Read()) Add(new DocVersionInfo(dr));
IsReadOnly = true; IsReadOnly = true;
} }
} }
@@ -277,16 +253,13 @@ namespace VEPROMS.CSLA.Library
if (_MyLog.IsErrorEnabled) _MyLog.Error("DocVersionInfoList.DataPortal_FetchFormatID", ex); if (_MyLog.IsErrorEnabled) _MyLog.Error("DocVersionInfoList.DataPortal_FetchFormatID", ex);
throw new DbCslaException("DocVersionInfoList.DataPortal_Fetch", ex); throw new DbCslaException("DocVersionInfoList.DataPortal_Fetch", ex);
} }
this.RaiseListChangedEvents = true; RaiseListChangedEvents = true;
} }
[Serializable()] [Serializable()]
private class ItemIDCriteria private class ItemIDCriteria
{ {
public ItemIDCriteria(int? itemID) public ItemIDCriteria(int? itemID) => _ItemID = itemID;
{ private int? _ItemID;
_ItemID = itemID;
}
private int? _ItemID;
public int? ItemID public int? ItemID
{ {
get { return _ItemID; } get { return _ItemID; }
@@ -295,7 +268,7 @@ namespace VEPROMS.CSLA.Library
} }
private void DataPortal_Fetch(ItemIDCriteria criteria) private void DataPortal_Fetch(ItemIDCriteria criteria)
{ {
this.RaiseListChangedEvents = false; RaiseListChangedEvents = false;
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocVersionInfoList.DataPortal_FetchItemID", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocVersionInfoList.DataPortal_FetchItemID", GetHashCode());
try try
{ {
@@ -310,7 +283,7 @@ namespace VEPROMS.CSLA.Library
using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
{ {
IsReadOnly = false; IsReadOnly = false;
while (dr.Read()) this.Add(new DocVersionInfo(dr)); while (dr.Read()) Add(new DocVersionInfo(dr));
IsReadOnly = true; IsReadOnly = true;
} }
} }
@@ -321,48 +294,37 @@ namespace VEPROMS.CSLA.Library
if (_MyLog.IsErrorEnabled) _MyLog.Error("DocVersionInfoList.DataPortal_FetchItemID", ex); if (_MyLog.IsErrorEnabled) _MyLog.Error("DocVersionInfoList.DataPortal_FetchItemID", ex);
throw new DbCslaException("DocVersionInfoList.DataPortal_Fetch", ex); throw new DbCslaException("DocVersionInfoList.DataPortal_Fetch", ex);
} }
this.RaiseListChangedEvents = true; RaiseListChangedEvents = true;
} }
#endregion #endregion
#region ICustomTypeDescriptor impl #region ICustomTypeDescriptor impl
public String GetClassName() public string GetClassName() => TypeDescriptor.GetClassName(this, true);
{ return TypeDescriptor.GetClassName(this, true); } public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true);
public AttributeCollection GetAttributes() public string GetComponentName() => TypeDescriptor.GetComponentName(this, true);
{ return TypeDescriptor.GetAttributes(this, true); } public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true);
public String GetComponentName() public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true);
{ return TypeDescriptor.GetComponentName(this, true); } public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true);
public TypeConverter GetConverter() public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true);
{ return TypeDescriptor.GetConverter(this, true); } public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true);
public EventDescriptor GetDefaultEvent() public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true);
{ return TypeDescriptor.GetDefaultEvent(this, true); } public object GetPropertyOwner(PropertyDescriptor pd) => this;
public PropertyDescriptor GetDefaultProperty() /// <summary>
{ return TypeDescriptor.GetDefaultProperty(this, true); } /// Called to get the properties of this type. Returns properties with certain
public object GetEditor(Type editorBaseType) /// attributes. this restriction is not implemented here.
{ return TypeDescriptor.GetEditor(this, editorBaseType, true); } /// </summary>
public EventDescriptorCollection GetEvents(Attribute[] attributes) /// <param name="attributes"></param>
{ return TypeDescriptor.GetEvents(this, attributes, true); } /// <returns></returns>
public EventDescriptorCollection GetEvents() public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties();
{ return TypeDescriptor.GetEvents(this, true); } /// <summary>
public object GetPropertyOwner(PropertyDescriptor pd) /// Called to get the properties of this type.
{ return this; } /// </summary>
/// <summary> /// <returns></returns>
/// Called to get the properties of this type. Returns properties with certain public PropertyDescriptorCollection GetProperties()
/// attributes. this restriction is not implemented here.
/// </summary>
/// <param name="attributes"></param>
/// <returns></returns>
public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{ return GetProperties(); }
/// <summary>
/// Called to get the properties of this type.
/// </summary>
/// <returns></returns>
public PropertyDescriptorCollection GetProperties()
{ {
// Create a collection object to hold property descriptors // Create a collection object to hold property descriptors
PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null);
// Iterate the list // Iterate the list
for (int i = 0; i < this.Items.Count; i++) for (int i = 0; i < Items.Count; i++)
{ {
// Create a property descriptor for the item and add to the property descriptor collection // Create a property descriptor for the item and add to the property descriptor collection
DocVersionInfoListPropertyDescriptor pd = new DocVersionInfoListPropertyDescriptor(this, i); DocVersionInfoListPropertyDescriptor pd = new DocVersionInfoListPropertyDescriptor(this, i);
@@ -379,7 +341,6 @@ namespace VEPROMS.CSLA.Library
/// </summary> /// </summary>
public partial class DocVersionInfoListPropertyDescriptor : vlnListPropertyDescriptor public partial class DocVersionInfoListPropertyDescriptor : vlnListPropertyDescriptor
{ {
private DocVersionInfo Item { get { return (DocVersionInfo)_Item; } }
public DocVersionInfoListPropertyDescriptor(DocVersionInfoList collection, int index) : base(collection, index) { ;} public DocVersionInfoListPropertyDescriptor(DocVersionInfoList collection, int index) : base(collection, index) { ;}
} }
#endregion #endregion
@@ -388,10 +349,10 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is DocVersionInfoList) if (destType == typeof(string) && value is DocVersionInfoList list)
{ {
// Return department and department role separated by comma. // Return department and department role separated by comma.
return ((DocVersionInfoList)value).Items.Count.ToString() + " DocVersions"; return $"{list.Items.Count} DocVersions";
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
+142 -303
View File
@@ -13,8 +13,6 @@ using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
using Csla.Validation; using Csla.Validation;
@@ -95,6 +93,7 @@ namespace VEPROMS.CSLA.Library
} }
#endregion #endregion
#region Collection #region Collection
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static List<Document> _CacheList = new List<Document>(); private static List<Document> _CacheList = new List<Document>();
protected static void AddToCache(Document document) protected static void AddToCache(Document document)
{ {
@@ -104,6 +103,7 @@ namespace VEPROMS.CSLA.Library
{ {
while (_CacheList.Contains(document)) _CacheList.Remove(document); // In RemoveFromCache while (_CacheList.Contains(document)) _CacheList.Remove(document); // In RemoveFromCache
} }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static Dictionary<string, List<Document>> _CacheByPrimaryKey = new Dictionary<string, List<Document>>(); private static Dictionary<string, List<Document>> _CacheByPrimaryKey = new Dictionary<string, List<Document>>();
private static void ConvertListToDictionary() private static void ConvertListToDictionary()
{ {
@@ -129,15 +129,9 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
#region Business Methods #region Business Methods
private string _ErrorMessage = string.Empty; private string _ErrorMessage = string.Empty;
public string ErrorMessage public string ErrorMessage => _ErrorMessage;
{
get { return _ErrorMessage; }
}
private static int _nextDocID = -1; private static int _nextDocID = -1;
public static int NextDocID public static int NextDocID => _nextDocID--;
{
get { return _nextDocID--; }
}
private int _DocID; private int _DocID;
[System.ComponentModel.DataObjectField(true, true)] [System.ComponentModel.DataObjectField(true, true)]
public int DocID public int DocID
@@ -354,10 +348,7 @@ namespace VEPROMS.CSLA.Library
return _DocumentEntries; return _DocumentEntries;
} }
} }
public void Reset_DocumentEntries() public void Reset_DocumentEntries() => _DocumentEntryCount = -1;
{
_DocumentEntryCount = -1;
}
private int _DocumentPdfCount = 0; private int _DocumentPdfCount = 0;
/// <summary> /// <summary>
/// Count of DocumentPdfs for this Document /// Count of DocumentPdfs for this Document
@@ -389,10 +380,7 @@ namespace VEPROMS.CSLA.Library
return _DocumentPdfs; return _DocumentPdfs;
} }
} }
public void Reset_DocumentPdfs() public void Reset_DocumentPdfs() => _DocumentPdfCount = -1;
{
_DocumentPdfCount = -1;
}
public override bool IsDirty public override bool IsDirty
{ {
get get
@@ -407,37 +395,22 @@ namespace VEPROMS.CSLA.Library
if (base.IsDirty || list.Contains(this)) if (base.IsDirty || list.Contains(this))
return base.IsDirty; return base.IsDirty;
list.Add(this); list.Add(this);
return base.IsDirty || (_DocumentDROUsages == null ? false : _DocumentDROUsages.IsDirtyList(list)) || (_DocumentEntries == null ? false : _DocumentEntries.IsDirtyList(list)) || (_DocumentPdfs == null ? false : _DocumentPdfs.IsDirtyList(list)); return base.IsDirty || (_DocumentDROUsages != null && _DocumentDROUsages.IsDirtyList(list)) || (_DocumentEntries != null && _DocumentEntries.IsDirtyList(list)) || (_DocumentPdfs != null && _DocumentPdfs.IsDirtyList(list));
}
public override bool IsValid
{
get { return IsValidList(new List<object>()); }
} }
public override bool IsValid => IsValidList(new List<object>());
public bool IsValidList(List<object> list) public bool IsValidList(List<object> list)
{ {
if (list.Contains(this)) if (list.Contains(this))
return (IsNew && !IsDirty) ? true : base.IsValid; return (IsNew && !IsDirty) || base.IsValid;
list.Add(this); list.Add(this);
return ((IsNew && !IsDirty) ? true : base.IsValid) && (_DocumentDROUsages == null ? true : _DocumentDROUsages.IsValidList(list)) && (_DocumentEntries == null ? true : _DocumentEntries.IsValidList(list)) && (_DocumentPdfs == null ? true : _DocumentPdfs.IsValidList(list)); return ((IsNew && !IsDirty) || base.IsValid) && (_DocumentDROUsages == null || _DocumentDROUsages.IsValidList(list)) && (_DocumentEntries == null || _DocumentEntries.IsValidList(list)) && (_DocumentPdfs == null || _DocumentPdfs.IsValidList(list));
} }
// CSLATODO: Replace base Document.ToString function as necessary
/// <summary>
/// Overrides Base ToString
/// </summary>
/// <returns>A string representation of current Document</returns>
//public override string ToString()
//{
// return base.ToString();
//}
// CSLATODO: Check Document.GetIdValue to assure that the ID returned is unique // CSLATODO: Check Document.GetIdValue to assure that the ID returned is unique
/// <summary> /// <summary>
/// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// Overrides Base GetIdValue - Used internally by CSLA to determine equality
/// </summary> /// </summary>
/// <returns>A Unique ID for the current Document</returns> /// <returns>A Unique ID for the current Document</returns>
protected override object GetIdValue() protected override object GetIdValue() => MyDocumentUnique; // Absolutely Unique ID
{
return MyDocumentUnique; // Absolutely Unique ID
}
#endregion #endregion
#region ValidationRules #region ValidationRules
[NonSerialized] [NonSerialized]
@@ -468,8 +441,8 @@ namespace VEPROMS.CSLA.Library
get get
{ {
IVEHasBrokenRules hasBrokenRules = HasBrokenRules; IVEHasBrokenRules hasBrokenRules = HasBrokenRules;
if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; if (Equals(hasBrokenRules)) return BrokenRulesCollection;
return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); return hasBrokenRules?.BrokenRules;
} }
} }
protected override void AddBusinessRules() protected override void AddBusinessRules()
@@ -502,37 +475,11 @@ namespace VEPROMS.CSLA.Library
_DocumentExtension.AddInstanceValidationRules(ValidationRules); _DocumentExtension.AddInstanceValidationRules(ValidationRules);
// CSLATODO: Add other validation rules // CSLATODO: Add other validation rules
} }
// Sample data comparison validation rule
//private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e)
//{
// if (_started > _ended)
// {
// e.Description = "Start date can't be after end date";
// return false;
// }
// else
// return true;
//}
#endregion #endregion
#region Authorization Rules #region Authorization Rules
protected override void AddAuthorizationRules() protected override void AddAuthorizationRules()
{ {
//CSLATODO: Who can read/write which fields //CSLATODO: Who can read/write which fields
//AuthorizationRules.AllowRead(DocID, "<Role(s)>");
//AuthorizationRules.AllowRead(LibTitle, "<Role(s)>");
//AuthorizationRules.AllowRead(DocContent, "<Role(s)>");
//AuthorizationRules.AllowRead(DocAscii, "<Role(s)>");
//AuthorizationRules.AllowRead(Config, "<Role(s)>");
//AuthorizationRules.AllowRead(DTS, "<Role(s)>");
//AuthorizationRules.AllowRead(UserID, "<Role(s)>");
//AuthorizationRules.AllowRead(FileExtension, "<Role(s)>");
//AuthorizationRules.AllowWrite(LibTitle, "<Role(s)>");
//AuthorizationRules.AllowWrite(DocContent, "<Role(s)>");
//AuthorizationRules.AllowWrite(DocAscii, "<Role(s)>");
//AuthorizationRules.AllowWrite(Config, "<Role(s)>");
//AuthorizationRules.AllowWrite(DTS, "<Role(s)>");
//AuthorizationRules.AllowWrite(UserID, "<Role(s)>");
//AuthorizationRules.AllowWrite(FileExtension, "<Role(s)>");
_DocumentExtension.AddAuthorizationRules(AuthorizationRules); _DocumentExtension.AddAuthorizationRules(AuthorizationRules);
} }
protected override void AddInstanceAuthorizationRules() protected override void AddInstanceAuthorizationRules()
@@ -540,57 +487,14 @@ namespace VEPROMS.CSLA.Library
//CSLATODO: Who can read/write which fields //CSLATODO: Who can read/write which fields
_DocumentExtension.AddInstanceAuthorizationRules(AuthorizationRules); _DocumentExtension.AddInstanceAuthorizationRules(AuthorizationRules);
} }
public static bool CanAddObject()
{
// CSLATODO: Can Add Authorization
//return Csla.ApplicationContext.User.IsInRole("ProjectManager");
return true;
}
public static bool CanGetObject()
{
// CSLATODO: CanGet Authorization
return true;
}
public static bool CanDeleteObject()
{
// CSLATODO: CanDelete Authorization
//bool result = false;
//if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true;
//if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true;
//return result;
return true;
}
/// <summary>
/// determines if related records (Foreign Keys) will keep this Item from being deleted
/// </summary>
public bool CanDelete
{
get
{
// Check to make sure that there are not any related records
int usedByCount = 0;
usedByCount += _DocumentDROUsageCount;
usedByCount += _DocumentEntryCount;
usedByCount += _DocumentPdfCount;
return (usedByCount == 0);
}
}
public static bool CanEditObject()
{
// CSLATODO: CanEdit Authorization
//return Csla.ApplicationContext.User.IsInRole("ProjectManager");
return true;
}
#endregion #endregion
#region Factory Methods #region Factory Methods
public int CurrentEditLevel public int CurrentEditLevel => EditLevel;
{ get { return EditLevel; } }
private static int _DocumentUnique = 0; private static int _DocumentUnique = 0;
protected static int DocumentUnique protected static int DocumentUnique => ++_DocumentUnique;
{ get { return ++_DocumentUnique; } } private readonly int _MyDocumentUnique = DocumentUnique;
private int _MyDocumentUnique = DocumentUnique; // Absolutely Unique ID - Editable
public int MyDocumentUnique // Absolutely Unique ID - Editable public int MyDocumentUnique => _MyDocumentUnique;
{ get { return _MyDocumentUnique; } }
protected Document() protected Document()
{/* require use of factory methods */ {/* require use of factory methods */
AddToCache(this); AddToCache(this);
@@ -599,15 +503,11 @@ namespace VEPROMS.CSLA.Library
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~Document() ~Document()
{ {
_CountFinalized++; _CountFinalized++;
@@ -632,8 +532,6 @@ namespace VEPROMS.CSLA.Library
} }
public static Document New() public static Document New()
{ {
if (!CanAddObject())
throw new System.Security.SecurityException("User not authorized to add a Document");
try try
{ {
return DataPortal.Create<Document>(); return DataPortal.Create<Document>();
@@ -699,8 +597,6 @@ namespace VEPROMS.CSLA.Library
} }
public static Document Get(int docID) public static Document Get(int docID)
{ {
if (!CanGetObject())
throw new System.Security.SecurityException("User not authorized to view a Document");
try try
{ {
Document tmp = GetCachedByPrimaryKey(docID); Document tmp = GetCachedByPrimaryKey(docID);
@@ -726,14 +622,9 @@ namespace VEPROMS.CSLA.Library
if (dr.Read()) return new Document(dr); if (dr.Read()) return new Document(dr);
return null; return null;
} }
internal Document(SafeDataReader dr) internal Document(SafeDataReader dr) => ReadData(dr);
{
ReadData(dr);
}
public static void Delete(int docID) public static void Delete(int docID)
{ {
if (!CanDeleteObject())
throw new System.Security.SecurityException("User not authorized to remove a Document");
try try
{ {
DataPortal.Delete(new PKCriteria(docID)); DataPortal.Delete(new PKCriteria(docID));
@@ -745,12 +636,6 @@ namespace VEPROMS.CSLA.Library
} }
public override Document Save() public override Document Save()
{ {
if (IsDeleted && !CanDeleteObject())
throw new System.Security.SecurityException("User not authorized to remove a Document");
else if (IsNew && !CanAddObject())
throw new System.Security.SecurityException("User not authorized to add a Document");
else if (!CanEditObject())
throw new System.Security.SecurityException("User not authorized to update a Document");
try try
{ {
BuildRefreshList(); BuildRefreshList();
@@ -770,13 +655,9 @@ namespace VEPROMS.CSLA.Library
[Serializable()] [Serializable()]
protected class PKCriteria protected class PKCriteria
{ {
private int _DocID; private readonly int _DocID;
public int DocID public int DocID => _DocID;
{ get { return _DocID; } } public PKCriteria(int docID) => _DocID = docID;
public PKCriteria(int docID)
{
_DocID = docID;
}
} }
// CSLATODO: If Create needs to access DB - It should not be marked RunLocal // CSLATODO: If Create needs to access DB - It should not be marked RunLocal
[RunLocal()] [RunLocal()]
@@ -861,7 +742,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Document.DataPortal_Fetch", ex); throw new DbCslaException("Document.DataPortal_Fetch", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Insert() protected override void DataPortal_Insert()
{ {
try try
@@ -886,44 +767,52 @@ namespace VEPROMS.CSLA.Library
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Document.DataPortal_Insert", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Document.DataPortal_Insert", GetHashCode());
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
internal void SQLInsert() internal void SQLInsert()
{ {
if (!this.IsDirty) return; if (!IsDirty) return;
try try
{ {
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = Database.VEPROMS_SqlConnection)
using (SqlCommand cm = cn.CreateCommand())
{ {
cm.CommandType = CommandType.StoredProcedure; if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
cm.CommandTimeout = Database.SQLTimeout; using (SqlCommand cm = cn.CreateCommand())
cm.CommandText = "addDocument"; {
// Input All Fields - Except Calculated Columns cm.CommandType = CommandType.StoredProcedure;
cm.Parameters.AddWithValue("@LibTitle", _LibTitle); cm.CommandTimeout = Database.SQLTimeout;
cm.Parameters.AddWithValue("@DocContent", _DocContent); cm.CommandText = "addDocument";
cm.Parameters.AddWithValue("@DocAscii", _DocAscii); // Input All Fields - Except Calculated Columns
cm.Parameters.AddWithValue("@Config", _Config); cm.Parameters.AddWithValue("@LibTitle", _LibTitle);
if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); cm.Parameters.AddWithValue("@DocContent", _DocContent);
cm.Parameters.AddWithValue("@UserID", _UserID); cm.Parameters.AddWithValue("@DocAscii", _DocAscii);
cm.Parameters.AddWithValue("@FileExtension", _FileExtension); cm.Parameters.AddWithValue("@Config", _Config);
// Output Calculated Columns if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS);
SqlParameter param_DocID = new SqlParameter("@newDocID", SqlDbType.Int); cm.Parameters.AddWithValue("@UserID", _UserID);
param_DocID.Direction = ParameterDirection.Output; cm.Parameters.AddWithValue("@FileExtension", _FileExtension);
cm.Parameters.Add(param_DocID); // Output Calculated Columns
SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); SqlParameter param_DocID = new SqlParameter("@newDocID", SqlDbType.Int)
param_LastChanged.Direction = ParameterDirection.Output; {
cm.Parameters.Add(param_LastChanged); Direction = ParameterDirection.Output
// CSLATODO: Define any additional output parameters };
cm.ExecuteNonQuery(); cm.Parameters.Add(param_DocID);
// Save all values being returned from the Procedure SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp)
_DocID = (int)cm.Parameters["@newDocID"].Value; {
_LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; Direction = ParameterDirection.Output
};
cm.Parameters.Add(param_LastChanged);
// CSLATODO: Define any additional output parameters
cm.ExecuteNonQuery();
// Save all values being returned from the Procedure
_DocID = (int)cm.Parameters["@newDocID"].Value;
_LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value;
}
} }
MarkOld(); MarkOld();
// update child objects // update child objects
if (_DocumentEntries != null) _DocumentEntries.Update(this); _DocumentEntries?.Update(this);
if (_DocumentDROUsages != null) _DocumentDROUsages.Update(this); _DocumentDROUsages?.Update(this);
if (_DocumentPdfs != null) _DocumentPdfs.Update(this); _DocumentPdfs?.Update(this);
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Document.SQLInsert", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Document.SQLInsert", GetHashCode());
} }
catch (Exception ex) catch (Exception ex)
@@ -933,7 +822,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Document.SQLInsert", ex); throw new DbCslaException("Document.SQLInsert", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
public static byte[] Add(SqlConnection cn, ref int docID, string libTitle, byte[] docContent, string docAscii, string config, DateTime dts, string userID, string fileExtension) public static byte[] Add(SqlConnection cn, ref int docID, string libTitle, byte[] docContent, string docAscii, string config, DateTime dts, string userID, string fileExtension)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Document.Add", 0); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Document.Add", 0);
@@ -953,11 +842,15 @@ namespace VEPROMS.CSLA.Library
cm.Parameters.AddWithValue("@UserID", userID); cm.Parameters.AddWithValue("@UserID", userID);
cm.Parameters.AddWithValue("@FileExtension", fileExtension); cm.Parameters.AddWithValue("@FileExtension", fileExtension);
// Output Calculated Columns // Output Calculated Columns
SqlParameter param_DocID = new SqlParameter("@newDocID", SqlDbType.Int); SqlParameter param_DocID = new SqlParameter("@newDocID", SqlDbType.Int)
param_DocID.Direction = ParameterDirection.Output; {
Direction = ParameterDirection.Output
};
cm.Parameters.Add(param_DocID); cm.Parameters.Add(param_DocID);
SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp)
param_LastChanged.Direction = ParameterDirection.Output; {
Direction = ParameterDirection.Output
};
cm.Parameters.Add(param_LastChanged); cm.Parameters.Add(param_LastChanged);
// CSLATODO: Define any additional output parameters // CSLATODO: Define any additional output parameters
cm.ExecuteNonQuery(); cm.ExecuteNonQuery();
@@ -972,7 +865,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Document.Add", ex); throw new DbCslaException("Document.Add", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Update() protected override void DataPortal_Update()
{ {
if (!IsDirty) return; // If not dirty - nothing to do if (!IsDirty) return; // If not dirty - nothing to do
@@ -995,46 +888,52 @@ namespace VEPROMS.CSLA.Library
if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; if (!ex.Message.EndsWith("has been edited by another user.")) throw ex;
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
internal void SQLUpdate() internal void SQLUpdate()
{ {
if (!IsDirty) return; // If not dirty - nothing to do if (!IsDirty) return; // If not dirty - nothing to do
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Document.SQLUpdate", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Document.SQLUpdate", GetHashCode());
try try
{ {
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = Database.VEPROMS_SqlConnection)
if (base.IsDirty)
{ {
using (SqlCommand cm = cn.CreateCommand()) if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
if (base.IsDirty)
{ {
cm.CommandType = CommandType.StoredProcedure; using (SqlCommand cm = cn.CreateCommand())
cm.CommandTimeout = Database.SQLTimeout; {
cm.CommandText = "updateDocument"; cm.CommandType = CommandType.StoredProcedure;
// All Fields including Calculated Fields cm.CommandTimeout = Database.SQLTimeout;
cm.Parameters.AddWithValue("@DocID", _DocID); cm.CommandText = "updateDocument";
cm.Parameters.AddWithValue("@LibTitle", _LibTitle); // All Fields including Calculated Fields
cm.Parameters.AddWithValue("@DocContent", _DocContent); cm.Parameters.AddWithValue("@DocID", _DocID);
cm.Parameters.AddWithValue("@DocAscii", _DocAscii); cm.Parameters.AddWithValue("@LibTitle", _LibTitle);
cm.Parameters.AddWithValue("@Config", _Config); cm.Parameters.AddWithValue("@DocContent", _DocContent);
if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); cm.Parameters.AddWithValue("@DocAscii", _DocAscii);
cm.Parameters.AddWithValue("@UserID", _UserID); cm.Parameters.AddWithValue("@Config", _Config);
cm.Parameters.AddWithValue("@LastChanged", _LastChanged); if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS);
cm.Parameters.AddWithValue("@FileExtension", _FileExtension); cm.Parameters.AddWithValue("@UserID", _UserID);
// Output Calculated Columns cm.Parameters.AddWithValue("@LastChanged", _LastChanged);
SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); cm.Parameters.AddWithValue("@FileExtension", _FileExtension);
param_LastChanged.Direction = ParameterDirection.Output; // Output Calculated Columns
cm.Parameters.Add(param_LastChanged); SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp)
// CSLATODO: Define any additional output parameters {
cm.ExecuteNonQuery(); Direction = ParameterDirection.Output
// Save all values being returned from the Procedure };
_LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; cm.Parameters.Add(param_LastChanged);
// CSLATODO: Define any additional output parameters
cm.ExecuteNonQuery();
// Save all values being returned from the Procedure
_LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value;
}
} }
} }
MarkOld(); MarkOld();
// use the open connection to update child objects // use the open connection to update child objects
if (_DocumentEntries != null) _DocumentEntries.Update(this); _DocumentEntries?.Update(this);
if (_DocumentDROUsages != null) _DocumentDROUsages.Update(this); _DocumentDROUsages?.Update(this);
if (_DocumentPdfs != null) _DocumentPdfs.Update(this); _DocumentPdfs?.Update(this);
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -1045,21 +944,25 @@ namespace VEPROMS.CSLA.Library
} }
internal void Update() internal void Update()
{ {
if (!this.IsDirty) return; if (!IsDirty) return;
if (base.IsDirty) if (base.IsDirty)
{ {
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = Database.VEPROMS_SqlConnection)
if (IsNew) {
_LastChanged = Document.Add(cn, ref _DocID, _LibTitle, _DocContent, _DocAscii, _Config, _DTS, _UserID, _FileExtension); if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
else if (IsNew)
_LastChanged = Document.Update(cn, ref _DocID, _LibTitle, _DocContent, _DocAscii, _Config, _DTS, _UserID, ref _LastChanged, _FileExtension); _LastChanged = Document.Add(cn, ref _DocID, _LibTitle, _DocContent, _DocAscii, _Config, _DTS, _UserID, _FileExtension);
else
_LastChanged = Document.Update(cn, ref _DocID, _LibTitle, _DocContent, _DocAscii, _Config, _DTS, _UserID, ref _LastChanged, _FileExtension);
}
MarkOld(); MarkOld();
} }
if (_DocumentEntries != null) _DocumentEntries.Update(this); _DocumentEntries?.Update(this);
if (_DocumentDROUsages != null) _DocumentDROUsages.Update(this); _DocumentDROUsages?.Update(this);
if (_DocumentPdfs != null) _DocumentPdfs.Update(this); _DocumentPdfs?.Update(this);
} }
[Transactional(TransactionalTypes.TransactionScope)]
public static byte[] Update(SqlConnection cn, ref int docID, string libTitle, byte[] docContent, string docAscii, string config, DateTime dts, string userID, ref byte[] lastChanged, string fileExtension) public static byte[] Update(SqlConnection cn, ref int docID, string libTitle, byte[] docContent, string docAscii, string config, DateTime dts, string userID, ref byte[] lastChanged, string fileExtension)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Document.Update", 0); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Document.Update", 0);
@@ -1081,8 +984,10 @@ namespace VEPROMS.CSLA.Library
cm.Parameters.AddWithValue("@LastChanged", lastChanged); cm.Parameters.AddWithValue("@LastChanged", lastChanged);
cm.Parameters.AddWithValue("@FileExtension", fileExtension); cm.Parameters.AddWithValue("@FileExtension", fileExtension);
// Output Calculated Columns // Output Calculated Columns
SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp)
param_LastChanged.Direction = ParameterDirection.Output; {
Direction = ParameterDirection.Output
};
cm.Parameters.Add(param_LastChanged); cm.Parameters.Add(param_LastChanged);
// CSLATODO: Define any additional output parameters // CSLATODO: Define any additional output parameters
cm.ExecuteNonQuery(); cm.ExecuteNonQuery();
@@ -1096,12 +1001,9 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Document.Update", ex); throw new DbCslaException("Document.Update", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_DeleteSelf() protected override void DataPortal_DeleteSelf() => DataPortal_Delete(new PKCriteria(_DocID));
{
DataPortal_Delete(new PKCriteria(_DocID));
}
[Transactional(TransactionalTypes.TransactionScope)]
private void DataPortal_Delete(PKCriteria criteria) private void DataPortal_Delete(PKCriteria criteria)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Document.DataPortal_Delete", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Document.DataPortal_Delete", GetHashCode());
@@ -1126,7 +1028,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Document.DataPortal_Delete", ex); throw new DbCslaException("Document.DataPortal_Delete", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
public static void Remove(SqlConnection cn, int docID) public static void Remove(SqlConnection cn, int docID)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Document.Remove", 0); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Document.Remove", 0);
@@ -1167,16 +1069,10 @@ namespace VEPROMS.CSLA.Library
[Serializable()] [Serializable()]
private class ExistsCommand : CommandBase private class ExistsCommand : CommandBase
{ {
private int _DocID; private readonly int _DocID;
private bool _exists; private bool _exists;
public bool Exists public bool Exists => _exists;
{ public ExistsCommand(int docID) => _DocID = docID;
get { return _exists; }
}
public ExistsCommand(int docID)
{
_DocID = docID;
}
protected override void DataPortal_Execute() protected override void DataPortal_Execute()
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Document.DataPortal_Execute", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Document.DataPortal_Execute", GetHashCode());
@@ -1184,7 +1080,7 @@ namespace VEPROMS.CSLA.Library
{ {
using (SqlConnection cn = Database.VEPROMS_SqlConnection) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
cn.Open(); if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
using (SqlCommand cm = cn.CreateCommand()) using (SqlCommand cm = cn.CreateCommand())
{ {
cm.CommandType = CommandType.StoredProcedure; cm.CommandType = CommandType.StoredProcedure;
@@ -1206,7 +1102,7 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
// Standard Default Code // Standard Default Code
#region extension #region extension
DocumentExtension _DocumentExtension = new DocumentExtension(); readonly DocumentExtension _DocumentExtension = new DocumentExtension();
[Serializable()] [Serializable()]
partial class DocumentExtension : extensionBase partial class DocumentExtension : extensionBase
{ {
@@ -1215,18 +1111,9 @@ namespace VEPROMS.CSLA.Library
class extensionBase class extensionBase
{ {
// Default Values // Default Values
public virtual DateTime DefaultDTS public virtual DateTime DefaultDTS => DateTime.Now;
{ public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID;
get { return DateTime.Now; } public virtual string DefaultFileExtension => ".Doc";
}
public virtual string DefaultUserID
{
get { return Volian.Base.Library.VlnSettings.UserID; }
}
public virtual string DefaultFileExtension
{
get { return ".Doc"; }
}
// Authorization Rules // Authorization Rules
public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules)
{ {
@@ -1255,61 +1142,13 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is Document) if (destType == typeof(string) && value is Document doc)
{ {
// Return the ToString value // Return the ToString value
return ((Document)value).ToString(); return doc.ToString();
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
} }
#endregion #endregion
} // Namespace } // Namespace
//// The following is a sample Extension File. You can use it to create DocumentExt.cs
//using System;
//using System.Collections.Generic;
//using System.Text;
//using Csla;
//namespace VEPROMS.CSLA.Library
//{
// public partial class Document
// {
// partial class DocumentExtension : extensionBase
// {
// // CSLATODO: Override automatic defaults
// public virtual DateTime DefaultDTS
// {
// get { return DateTime.Now; }
// }
// public virtual string DefaultUserID
// {
// get { return Environment.UserName.ToUpper(); }
// }
// public virtual string DefaultFileExtension
// {
// get { return ".Doc"; }
// }
// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules)
// {
// //rules.AllowRead(Dbid, "<Role(s)>");
// }
// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules)
// {
// //rules.AllowInstanceRead(Dbid, "<Role(s)>");
// }
// public new void AddValidationRules(Csla.Validation.ValidationRules rules)
// {
// rules.AddRule(
// Csla.Validation.CommonRules.StringMaxLength,
// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100));
// }
// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules)
// {
// rules.AddInstanceRule(/* Instance Validation Rule */);
// }
// }
// }
//}
@@ -13,8 +13,6 @@ using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
using Csla.Validation; using Csla.Validation;
@@ -37,10 +35,7 @@ namespace VEPROMS.CSLA.Library
if (IsDirty) if (IsDirty)
refreshDocumentAudits.Add(this); refreshDocumentAudits.Add(this);
} }
private void ClearRefreshList() private void ClearRefreshList() => _RefreshDocumentAudits = new List<DocumentAudit>();
{
_RefreshDocumentAudits = new List<DocumentAudit>();
}
private void BuildRefreshList() private void BuildRefreshList()
{ {
ClearRefreshList(); ClearRefreshList();
@@ -56,6 +51,7 @@ namespace VEPROMS.CSLA.Library
} }
#endregion #endregion
#region Collection #region Collection
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static List<DocumentAudit> _CacheList = new List<DocumentAudit>(); private static List<DocumentAudit> _CacheList = new List<DocumentAudit>();
protected static void AddToCache(DocumentAudit documentAudit) protected static void AddToCache(DocumentAudit documentAudit)
{ {
@@ -65,6 +61,7 @@ namespace VEPROMS.CSLA.Library
{ {
while (_CacheList.Contains(documentAudit)) _CacheList.Remove(documentAudit); // In RemoveFromCache while (_CacheList.Contains(documentAudit)) _CacheList.Remove(documentAudit); // In RemoveFromCache
} }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static Dictionary<string, List<DocumentAudit>> _CacheByPrimaryKey = new Dictionary<string, List<DocumentAudit>>(); private static Dictionary<string, List<DocumentAudit>> _CacheByPrimaryKey = new Dictionary<string, List<DocumentAudit>>();
private static void ConvertListToDictionary() private static void ConvertListToDictionary()
{ {
@@ -90,15 +87,9 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
#region Business Methods #region Business Methods
private string _ErrorMessage = string.Empty; private string _ErrorMessage = string.Empty;
public string ErrorMessage public string ErrorMessage => _ErrorMessage;
{
get { return _ErrorMessage; }
}
private static int _nextAuditID = -1; private static int _nextAuditID = -1;
public static int NextAuditID public static int NextAuditID => _nextAuditID--;
{
get { return _nextAuditID--; }
}
private long _AuditID; private long _AuditID;
[System.ComponentModel.DataObjectField(true, true)] [System.ComponentModel.DataObjectField(true, true)]
public long AuditID public long AuditID
@@ -294,40 +285,14 @@ namespace VEPROMS.CSLA.Library
} }
} }
} }
public override bool IsDirty public override bool IsDirty => base.IsDirty;
{ public override bool IsValid => (IsNew && !IsDirty) || base.IsValid;
get { return base.IsDirty; }
}
public bool IsDirtyList(List<object> list)
{
return base.IsDirty;
}
public override bool IsValid
{
get { return (IsNew && !IsDirty) ? true : base.IsValid; }
}
public bool IsValidList(List<object> list)
{
return (IsNew && !IsDirty) ? true : base.IsValid;
}
// CSLATODO: Replace base DocumentAudit.ToString function as necessary
/// <summary>
/// Overrides Base ToString
/// </summary>
/// <returns>A string representation of current DocumentAudit</returns>
//public override string ToString()
//{
// return base.ToString();
//}
// CSLATODO: Check DocumentAudit.GetIdValue to assure that the ID returned is unique // CSLATODO: Check DocumentAudit.GetIdValue to assure that the ID returned is unique
/// <summary> /// <summary>
/// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// Overrides Base GetIdValue - Used internally by CSLA to determine equality
/// </summary> /// </summary>
/// <returns>A Unique ID for the current DocumentAudit</returns> /// <returns>A Unique ID for the current DocumentAudit</returns>
protected override object GetIdValue() protected override object GetIdValue() => MyDocumentAuditUnique; // Absolutely Unique ID
{
return MyDocumentAuditUnique; // Absolutely Unique ID
}
#endregion #endregion
#region ValidationRules #region ValidationRules
[NonSerialized] [NonSerialized]
@@ -355,8 +320,8 @@ namespace VEPROMS.CSLA.Library
get get
{ {
IVEHasBrokenRules hasBrokenRules = HasBrokenRules; IVEHasBrokenRules hasBrokenRules = HasBrokenRules;
if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; if (Equals(hasBrokenRules)) return BrokenRulesCollection;
return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); return (hasBrokenRules?.BrokenRules);
} }
} }
protected override void AddBusinessRules() protected override void AddBusinessRules()
@@ -389,43 +354,11 @@ namespace VEPROMS.CSLA.Library
_DocumentAuditExtension.AddInstanceValidationRules(ValidationRules); _DocumentAuditExtension.AddInstanceValidationRules(ValidationRules);
// CSLATODO: Add other validation rules // CSLATODO: Add other validation rules
} }
// Sample data comparison validation rule
//private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e)
//{
// if (_started > _ended)
// {
// e.Description = "Start date can't be after end date";
// return false;
// }
// else
// return true;
//}
#endregion #endregion
#region Authorization Rules #region Authorization Rules
protected override void AddAuthorizationRules() protected override void AddAuthorizationRules()
{ {
//CSLATODO: Who can read/write which fields //CSLATODO: Who can read/write which fields
//AuthorizationRules.AllowRead(AuditID, "<Role(s)>");
//AuthorizationRules.AllowRead(DocID, "<Role(s)>");
//AuthorizationRules.AllowRead(LibTitle, "<Role(s)>");
//AuthorizationRules.AllowRead(DocContent, "<Role(s)>");
//AuthorizationRules.AllowRead(DocAscii, "<Role(s)>");
//AuthorizationRules.AllowRead(Config, "<Role(s)>");
//AuthorizationRules.AllowRead(DTS, "<Role(s)>");
//AuthorizationRules.AllowRead(UserID, "<Role(s)>");
//AuthorizationRules.AllowRead(FileExtension, "<Role(s)>");
//AuthorizationRules.AllowRead(DocPdf, "<Role(s)>");
//AuthorizationRules.AllowRead(DeleteStatus, "<Role(s)>");
//AuthorizationRules.AllowWrite(DocID, "<Role(s)>");
//AuthorizationRules.AllowWrite(LibTitle, "<Role(s)>");
//AuthorizationRules.AllowWrite(DocContent, "<Role(s)>");
//AuthorizationRules.AllowWrite(DocAscii, "<Role(s)>");
//AuthorizationRules.AllowWrite(Config, "<Role(s)>");
//AuthorizationRules.AllowWrite(DTS, "<Role(s)>");
//AuthorizationRules.AllowWrite(UserID, "<Role(s)>");
//AuthorizationRules.AllowWrite(FileExtension, "<Role(s)>");
//AuthorizationRules.AllowWrite(DocPdf, "<Role(s)>");
//AuthorizationRules.AllowWrite(DeleteStatus, "<Role(s)>");
_DocumentAuditExtension.AddAuthorizationRules(AuthorizationRules); _DocumentAuditExtension.AddAuthorizationRules(AuthorizationRules);
} }
protected override void AddInstanceAuthorizationRules() protected override void AddInstanceAuthorizationRules()
@@ -433,42 +366,14 @@ namespace VEPROMS.CSLA.Library
//CSLATODO: Who can read/write which fields //CSLATODO: Who can read/write which fields
_DocumentAuditExtension.AddInstanceAuthorizationRules(AuthorizationRules); _DocumentAuditExtension.AddInstanceAuthorizationRules(AuthorizationRules);
} }
public static bool CanAddObject()
{
// CSLATODO: Can Add Authorization
//return Csla.ApplicationContext.User.IsInRole("ProjectManager");
return true;
}
public static bool CanGetObject()
{
// CSLATODO: CanGet Authorization
return true;
}
public static bool CanDeleteObject()
{
// CSLATODO: CanDelete Authorization
//bool result = false;
//if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true;
//if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true;
//return result;
return true;
}
public static bool CanEditObject()
{
// CSLATODO: CanEdit Authorization
//return Csla.ApplicationContext.User.IsInRole("ProjectManager");
return true;
}
#endregion #endregion
#region Factory Methods #region Factory Methods
public int CurrentEditLevel public int CurrentEditLevel => EditLevel;
{ get { return EditLevel; } }
private static int _DocumentAuditUnique = 0; private static int _DocumentAuditUnique = 0;
protected static int DocumentAuditUnique protected static int DocumentAuditUnique => ++_DocumentAuditUnique;
{ get { return ++_DocumentAuditUnique; } } private readonly int _MyDocumentAuditUnique = DocumentAuditUnique;
private int _MyDocumentAuditUnique = DocumentAuditUnique; // Absolutely Unique ID - Editable
public int MyDocumentAuditUnique // Absolutely Unique ID - Editable public int MyDocumentAuditUnique => _MyDocumentAuditUnique;
{ get { return _MyDocumentAuditUnique; } }
protected DocumentAudit() protected DocumentAudit()
{/* require use of factory methods */ {/* require use of factory methods */
AddToCache(this); AddToCache(this);
@@ -477,15 +382,11 @@ namespace VEPROMS.CSLA.Library
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~DocumentAudit() ~DocumentAudit()
{ {
_CountFinalized++; _CountFinalized++;
@@ -510,8 +411,6 @@ namespace VEPROMS.CSLA.Library
} }
public static DocumentAudit New() public static DocumentAudit New()
{ {
if (!CanAddObject())
throw new System.Security.SecurityException("User not authorized to add a DocumentAudit");
try try
{ {
return DataPortal.Create<DocumentAudit>(); return DataPortal.Create<DocumentAudit>();
@@ -564,8 +463,6 @@ namespace VEPROMS.CSLA.Library
} }
public static DocumentAudit Get(long auditID) public static DocumentAudit Get(long auditID)
{ {
if (!CanGetObject())
throw new System.Security.SecurityException("User not authorized to view a DocumentAudit");
try try
{ {
DocumentAudit tmp = GetCachedByPrimaryKey(auditID); DocumentAudit tmp = GetCachedByPrimaryKey(auditID);
@@ -591,14 +488,9 @@ namespace VEPROMS.CSLA.Library
if (dr.Read()) return new DocumentAudit(dr); if (dr.Read()) return new DocumentAudit(dr);
return null; return null;
} }
internal DocumentAudit(SafeDataReader dr) internal DocumentAudit(SafeDataReader dr) => ReadData(dr);
{
ReadData(dr);
}
public static void Delete(long auditID) public static void Delete(long auditID)
{ {
if (!CanDeleteObject())
throw new System.Security.SecurityException("User not authorized to remove a DocumentAudit");
try try
{ {
DataPortal.Delete(new PKCriteria(auditID)); DataPortal.Delete(new PKCriteria(auditID));
@@ -610,12 +502,6 @@ namespace VEPROMS.CSLA.Library
} }
public override DocumentAudit Save() public override DocumentAudit Save()
{ {
if (IsDeleted && !CanDeleteObject())
throw new System.Security.SecurityException("User not authorized to remove a DocumentAudit");
else if (IsNew && !CanAddObject())
throw new System.Security.SecurityException("User not authorized to add a DocumentAudit");
else if (!CanEditObject())
throw new System.Security.SecurityException("User not authorized to update a DocumentAudit");
try try
{ {
BuildRefreshList(); BuildRefreshList();
@@ -635,13 +521,9 @@ namespace VEPROMS.CSLA.Library
[Serializable()] [Serializable()]
protected class PKCriteria protected class PKCriteria
{ {
private long _AuditID; private readonly long _AuditID;
public long AuditID public long AuditID => _AuditID;
{ get { return _AuditID; } } public PKCriteria(long auditID) => _AuditID = auditID;
public PKCriteria(long auditID)
{
_AuditID = auditID;
}
} }
// CSLATODO: If Create needs to access DB - It should not be marked RunLocal // CSLATODO: If Create needs to access DB - It should not be marked RunLocal
[RunLocal()] [RunLocal()]
@@ -714,7 +596,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("DocumentAudit.DataPortal_Fetch", ex); throw new DbCslaException("DocumentAudit.DataPortal_Fetch", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Insert() protected override void DataPortal_Insert()
{ {
try try
@@ -739,38 +621,44 @@ namespace VEPROMS.CSLA.Library
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocumentAudit.DataPortal_Insert", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocumentAudit.DataPortal_Insert", GetHashCode());
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
internal void SQLInsert() internal void SQLInsert()
{ {
if (!this.IsDirty) return; if (!IsDirty) return;
try try
{ {
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = Database.VEPROMS_SqlConnection)
using (SqlCommand cm = cn.CreateCommand())
{ {
cm.CommandType = CommandType.StoredProcedure; if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
cm.CommandTimeout = Database.SQLTimeout; using (SqlCommand cm = cn.CreateCommand())
cm.CommandText = "addDocumentAudit"; {
// Input All Fields - Except Calculated Columns cm.CommandType = CommandType.StoredProcedure;
cm.Parameters.AddWithValue("@DocID", _DocID); cm.CommandTimeout = Database.SQLTimeout;
cm.Parameters.AddWithValue("@LibTitle", _LibTitle); cm.CommandText = "addDocumentAudit";
cm.Parameters.AddWithValue("@DocContent", _DocContent); // Input All Fields - Except Calculated Columns
cm.Parameters.AddWithValue("@DocAscii", _DocAscii); cm.Parameters.AddWithValue("@DocID", _DocID);
cm.Parameters.AddWithValue("@Config", _Config); cm.Parameters.AddWithValue("@LibTitle", _LibTitle);
if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); cm.Parameters.AddWithValue("@DocContent", _DocContent);
cm.Parameters.AddWithValue("@UserID", _UserID); cm.Parameters.AddWithValue("@DocAscii", _DocAscii);
cm.Parameters.AddWithValue("@FileExtension", _FileExtension); cm.Parameters.AddWithValue("@Config", _Config);
cm.Parameters.AddWithValue("@DocPdf", _DocPdf); if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS);
cm.Parameters.AddWithValue("@DeleteStatus", _DeleteStatus); cm.Parameters.AddWithValue("@UserID", _UserID);
// Output Calculated Columns cm.Parameters.AddWithValue("@FileExtension", _FileExtension);
SqlParameter param_AuditID = new SqlParameter("@newAuditID", SqlDbType.BigInt); cm.Parameters.AddWithValue("@DocPdf", _DocPdf);
param_AuditID.Direction = ParameterDirection.Output; cm.Parameters.AddWithValue("@DeleteStatus", _DeleteStatus);
cm.Parameters.Add(param_AuditID); // Output Calculated Columns
// CSLATODO: Define any additional output parameters SqlParameter param_AuditID = new SqlParameter("@newAuditID", SqlDbType.BigInt)
cm.ExecuteNonQuery(); {
// Save all values being returned from the Procedure Direction = ParameterDirection.Output
_AuditID = (long)cm.Parameters["@newAuditID"].Value; };
cm.Parameters.Add(param_AuditID);
// CSLATODO: Define any additional output parameters
cm.ExecuteNonQuery();
// Save all values being returned from the Procedure
_AuditID = (long)cm.Parameters["@newAuditID"].Value;
}
} }
MarkOld(); MarkOld();
// update child objects // update child objects
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocumentAudit.SQLInsert", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocumentAudit.SQLInsert", GetHashCode());
@@ -782,7 +670,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("DocumentAudit.SQLInsert", ex); throw new DbCslaException("DocumentAudit.SQLInsert", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
public static void Add(SqlConnection cn, ref long auditID, int docID, string libTitle, byte[] docContent, string docAscii, string config, DateTime dts, string userID, string fileExtension, byte[] docPdf, int deleteStatus) public static void Add(SqlConnection cn, ref long auditID, int docID, string libTitle, byte[] docContent, string docAscii, string config, DateTime dts, string userID, string fileExtension, byte[] docPdf, int deleteStatus)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocumentAudit.Add", 0); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocumentAudit.Add", 0);
@@ -805,8 +693,10 @@ namespace VEPROMS.CSLA.Library
cm.Parameters.AddWithValue("@DocPdf", docPdf); cm.Parameters.AddWithValue("@DocPdf", docPdf);
cm.Parameters.AddWithValue("@DeleteStatus", deleteStatus); cm.Parameters.AddWithValue("@DeleteStatus", deleteStatus);
// Output Calculated Columns // Output Calculated Columns
SqlParameter param_AuditID = new SqlParameter("@newAuditID", SqlDbType.BigInt); SqlParameter param_AuditID = new SqlParameter("@newAuditID", SqlDbType.BigInt)
param_AuditID.Direction = ParameterDirection.Output; {
Direction = ParameterDirection.Output
};
cm.Parameters.Add(param_AuditID); cm.Parameters.Add(param_AuditID);
// CSLATODO: Define any additional output parameters // CSLATODO: Define any additional output parameters
cm.ExecuteNonQuery(); cm.ExecuteNonQuery();
@@ -821,7 +711,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("DocumentAudit.Add", ex); throw new DbCslaException("DocumentAudit.Add", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Update() protected override void DataPortal_Update()
{ {
if (!IsDirty) return; // If not dirty - nothing to do if (!IsDirty) return; // If not dirty - nothing to do
@@ -844,39 +734,43 @@ namespace VEPROMS.CSLA.Library
if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; if (!ex.Message.EndsWith("has been edited by another user.")) throw ex;
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
internal void SQLUpdate() internal void SQLUpdate()
{ {
if (!IsDirty) return; // If not dirty - nothing to do if (!IsDirty) return; // If not dirty - nothing to do
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocumentAudit.SQLUpdate", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocumentAudit.SQLUpdate", GetHashCode());
try try
{ {
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = Database.VEPROMS_SqlConnection)
if (base.IsDirty)
{ {
using (SqlCommand cm = cn.CreateCommand()) if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
if (base.IsDirty)
{ {
cm.CommandType = CommandType.StoredProcedure; using (SqlCommand cm = cn.CreateCommand())
cm.CommandTimeout = Database.SQLTimeout; {
cm.CommandText = "updateDocumentAudit"; cm.CommandType = CommandType.StoredProcedure;
// All Fields including Calculated Fields cm.CommandTimeout = Database.SQLTimeout;
cm.Parameters.AddWithValue("@AuditID", _AuditID); cm.CommandText = "updateDocumentAudit";
cm.Parameters.AddWithValue("@DocID", _DocID); // All Fields including Calculated Fields
cm.Parameters.AddWithValue("@LibTitle", _LibTitle); cm.Parameters.AddWithValue("@AuditID", _AuditID);
cm.Parameters.AddWithValue("@DocContent", _DocContent); cm.Parameters.AddWithValue("@DocID", _DocID);
cm.Parameters.AddWithValue("@DocAscii", _DocAscii); cm.Parameters.AddWithValue("@LibTitle", _LibTitle);
cm.Parameters.AddWithValue("@Config", _Config); cm.Parameters.AddWithValue("@DocContent", _DocContent);
if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); cm.Parameters.AddWithValue("@DocAscii", _DocAscii);
cm.Parameters.AddWithValue("@UserID", _UserID); cm.Parameters.AddWithValue("@Config", _Config);
cm.Parameters.AddWithValue("@FileExtension", _FileExtension); if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS);
cm.Parameters.AddWithValue("@DocPdf", _DocPdf); cm.Parameters.AddWithValue("@UserID", _UserID);
cm.Parameters.AddWithValue("@DeleteStatus", _DeleteStatus); cm.Parameters.AddWithValue("@FileExtension", _FileExtension);
// Output Calculated Columns cm.Parameters.AddWithValue("@DocPdf", _DocPdf);
// CSLATODO: Define any additional output parameters cm.Parameters.AddWithValue("@DeleteStatus", _DeleteStatus);
cm.ExecuteNonQuery(); // Output Calculated Columns
// Save all values being returned from the Procedure // CSLATODO: Define any additional output parameters
cm.ExecuteNonQuery();
// Save all values being returned from the Procedure
}
} }
} }
MarkOld(); MarkOld();
// use the open connection to update child objects // use the open connection to update child objects
} }
@@ -889,18 +783,22 @@ namespace VEPROMS.CSLA.Library
} }
internal void Update() internal void Update()
{ {
if (!this.IsDirty) return; if (!IsDirty) return;
if (base.IsDirty) if (base.IsDirty)
{ {
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = Database.VEPROMS_SqlConnection)
if (IsNew) {
DocumentAudit.Add(cn, ref _AuditID, _DocID, _LibTitle, _DocContent, _DocAscii, _Config, _DTS, _UserID, _FileExtension, _DocPdf, _DeleteStatus); if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
else if (IsNew)
DocumentAudit.Update(cn, ref _AuditID, _DocID, _LibTitle, _DocContent, _DocAscii, _Config, _DTS, _UserID, _FileExtension, _DocPdf, _DeleteStatus); DocumentAudit.Add(cn, ref _AuditID, _DocID, _LibTitle, _DocContent, _DocAscii, _Config, _DTS, _UserID, _FileExtension, _DocPdf, _DeleteStatus);
else
DocumentAudit.Update(cn, ref _AuditID, _DocID, _LibTitle, _DocContent, _DocAscii, _Config, _DTS, _UserID, _FileExtension, _DocPdf, _DeleteStatus);
}
MarkOld(); MarkOld();
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
public static void Update(SqlConnection cn, ref long auditID, int docID, string libTitle, byte[] docContent, string docAscii, string config, DateTime dts, string userID, string fileExtension, byte[] docPdf, int deleteStatus) public static void Update(SqlConnection cn, ref long auditID, int docID, string libTitle, byte[] docContent, string docAscii, string config, DateTime dts, string userID, string fileExtension, byte[] docPdf, int deleteStatus)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocumentAudit.Update", 0); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocumentAudit.Update", 0);
@@ -936,12 +834,9 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("DocumentAudit.Update", ex); throw new DbCslaException("DocumentAudit.Update", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_DeleteSelf() protected override void DataPortal_DeleteSelf() => DataPortal_Delete(new PKCriteria(_AuditID));
{
DataPortal_Delete(new PKCriteria(_AuditID));
}
[Transactional(TransactionalTypes.TransactionScope)]
private void DataPortal_Delete(PKCriteria criteria) private void DataPortal_Delete(PKCriteria criteria)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocumentAudit.DataPortal_Delete", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocumentAudit.DataPortal_Delete", GetHashCode());
@@ -966,7 +861,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("DocumentAudit.DataPortal_Delete", ex); throw new DbCslaException("DocumentAudit.DataPortal_Delete", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
public static void Remove(SqlConnection cn, long auditID) public static void Remove(SqlConnection cn, long auditID)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocumentAudit.Remove", 0); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocumentAudit.Remove", 0);
@@ -992,7 +887,7 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
// Standard Default Code // Standard Default Code
#region extension #region extension
DocumentAuditExtension _DocumentAuditExtension = new DocumentAuditExtension(); readonly DocumentAuditExtension _DocumentAuditExtension = new DocumentAuditExtension();
[Serializable()] [Serializable()]
partial class DocumentAuditExtension : extensionBase partial class DocumentAuditExtension : extensionBase
{ {
@@ -1029,49 +924,13 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is DocumentAudit) if (destType == typeof(string) && value is DocumentAudit audit)
{ {
// Return the ToString value // Return the ToString value
return ((DocumentAudit)value).ToString(); return audit.ToString();
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
} }
#endregion #endregion
} // Namespace } // Namespace
//// The following is a sample Extension File. You can use it to create DocumentAuditExt.cs
//using System;
//using System.Collections.Generic;
//using System.Text;
//using Csla;
//namespace VEPROMS.CSLA.Library
//{
// public partial class DocumentAudit
// {
// partial class DocumentAuditExtension : extensionBase
// {
// // CSLATODO: Override automatic defaults
// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules)
// {
// //rules.AllowRead(Dbid, "<Role(s)>");
// }
// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules)
// {
// //rules.AllowInstanceRead(Dbid, "<Role(s)>");
// }
// public new void AddValidationRules(Csla.Validation.ValidationRules rules)
// {
// rules.AddRule(
// Csla.Validation.CommonRules.StringMaxLength,
// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100));
// }
// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules)
// {
// rules.AddInstanceRule(/* Instance Validation Rule */);
// }
// }
// }
//}
@@ -13,8 +13,6 @@ using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
namespace VEPROMS.CSLA.Library namespace VEPROMS.CSLA.Library
@@ -28,14 +26,12 @@ namespace VEPROMS.CSLA.Library
public partial class DocumentAuditInfo : ReadOnlyBase<DocumentAuditInfo>, IDisposable public partial class DocumentAuditInfo : ReadOnlyBase<DocumentAuditInfo>, IDisposable
{ {
public event DocumentAuditInfoEvent Changed; public event DocumentAuditInfoEvent Changed;
private void OnChange() private void OnChange() => Changed?.Invoke(this);
{
if (Changed != null) Changed(this);
}
#region Log4Net #region Log4Net
private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endregion #endregion
#region Collection #region Collection
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static List<DocumentAuditInfo> _CacheList = new List<DocumentAuditInfo>(); private static List<DocumentAuditInfo> _CacheList = new List<DocumentAuditInfo>();
protected static void AddToCache(DocumentAuditInfo documentAuditInfo) protected static void AddToCache(DocumentAuditInfo documentAuditInfo)
{ {
@@ -45,6 +41,7 @@ namespace VEPROMS.CSLA.Library
{ {
while (_CacheList.Contains(documentAuditInfo)) _CacheList.Remove(documentAuditInfo); // In RemoveFromCache while (_CacheList.Contains(documentAuditInfo)) _CacheList.Remove(documentAuditInfo); // In RemoveFromCache
} }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static Dictionary<string, List<DocumentAuditInfo>> _CacheByPrimaryKey = new Dictionary<string, List<DocumentAuditInfo>>(); private static Dictionary<string, List<DocumentAuditInfo>> _CacheByPrimaryKey = new Dictionary<string, List<DocumentAuditInfo>>();
private static void ConvertListToDictionary() private static void ConvertListToDictionary()
{ {
@@ -74,21 +71,8 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
#region Business Methods #region Business Methods
private string _ErrorMessage = string.Empty; private string _ErrorMessage = string.Empty;
public string ErrorMessage public string ErrorMessage => _ErrorMessage;
{
get { return _ErrorMessage; }
}
protected DocumentAudit _Editable; protected DocumentAudit _Editable;
private IVEHasBrokenRules HasBrokenRules
{
get
{
IVEHasBrokenRules hasBrokenRules = null;
if (_Editable != null)
hasBrokenRules = _Editable.HasBrokenRules;
return hasBrokenRules;
}
}
private long _AuditID; private long _AuditID;
[System.ComponentModel.DataObjectField(true, true)] [System.ComponentModel.DataObjectField(true, true)]
public long AuditID public long AuditID
@@ -180,32 +164,19 @@ namespace VEPROMS.CSLA.Library
return _DeleteStatus; return _DeleteStatus;
} }
} }
// CSLATODO: Replace base DocumentAuditInfo.ToString function as necessary
/// <summary>
/// Overrides Base ToString
/// </summary>
/// <returns>A string representation of current DocumentAuditInfo</returns>
//public override string ToString()
//{
// return base.ToString();
//}
// CSLATODO: Check DocumentAuditInfo.GetIdValue to assure that the ID returned is unique // CSLATODO: Check DocumentAuditInfo.GetIdValue to assure that the ID returned is unique
/// <summary> /// <summary>
/// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// Overrides Base GetIdValue - Used internally by CSLA to determine equality
/// </summary> /// </summary>
/// <returns>A Unique ID for the current DocumentAuditInfo</returns> /// <returns>A Unique ID for the current DocumentAuditInfo</returns>
protected override object GetIdValue() protected override object GetIdValue() => MyDocumentAuditInfoUnique; // Absolutely Unique ID
{
return MyDocumentAuditInfoUnique; // Absolutely Unique ID
}
#endregion #endregion
#region Factory Methods #region Factory Methods
private static int _DocumentAuditInfoUnique = 0; private static int _DocumentAuditInfoUnique = 0;
private static int DocumentAuditInfoUnique private static int DocumentAuditInfoUnique => ++_DocumentAuditInfoUnique;
{ get { return ++_DocumentAuditInfoUnique; } } private readonly int _MyDocumentAuditInfoUnique = DocumentAuditInfoUnique;
private int _MyDocumentAuditInfoUnique = DocumentAuditInfoUnique; // Absolutely Unique ID - Info
public int MyDocumentAuditInfoUnique // Absolutely Unique ID - Info public int MyDocumentAuditInfoUnique => _MyDocumentAuditInfoUnique;
{ get { return _MyDocumentAuditInfoUnique; } }
protected DocumentAuditInfo() protected DocumentAuditInfo()
{/* require use of factory methods */ {/* require use of factory methods */
AddToCache(this); AddToCache(this);
@@ -214,15 +185,11 @@ namespace VEPROMS.CSLA.Library
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~DocumentAuditInfo() ~DocumentAuditInfo()
{ {
_CountFinalized++; _CountFinalized++;
@@ -239,10 +206,7 @@ namespace VEPROMS.CSLA.Library
if (listDocumentAuditInfo.Count == 0) // If there are no items left in the list if (listDocumentAuditInfo.Count == 0) // If there are no items left in the list
_CacheByPrimaryKey.Remove(AuditID.ToString()); // remove the list _CacheByPrimaryKey.Remove(AuditID.ToString()); // remove the list
} }
public virtual DocumentAudit Get() public virtual DocumentAudit Get() => _Editable = DocumentAudit.Get(_AuditID);
{
return _Editable = DocumentAudit.Get(_AuditID);
}
public static void Refresh(DocumentAudit tmp) public static void Refresh(DocumentAudit tmp)
{ {
string key = tmp.AuditID.ToString(); string key = tmp.AuditID.ToString();
@@ -267,8 +231,6 @@ namespace VEPROMS.CSLA.Library
} }
public static DocumentAuditInfo Get(long auditID) public static DocumentAuditInfo Get(long auditID)
{ {
//if (!CanGetObject())
// throw new System.Security.SecurityException("User not authorized to view a DocumentAudit");
try try
{ {
DocumentAuditInfo tmp = GetCachedByPrimaryKey(auditID); DocumentAuditInfo tmp = GetCachedByPrimaryKey(auditID);
@@ -307,13 +269,9 @@ namespace VEPROMS.CSLA.Library
[Serializable()] [Serializable()]
protected class PKCriteria protected class PKCriteria
{ {
private long _AuditID; private readonly long _AuditID;
public long AuditID public long AuditID => _AuditID;
{ get { return _AuditID; } } public PKCriteria(long auditID) => _AuditID = auditID;
public PKCriteria(long auditID)
{
_AuditID = auditID;
}
} }
private void ReadData(SafeDataReader dr) private void ReadData(SafeDataReader dr)
{ {
@@ -377,7 +335,7 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
// Standard Refresh // Standard Refresh
#region extension #region extension
DocumentAuditInfoExtension _DocumentAuditInfoExtension = new DocumentAuditInfoExtension(); readonly DocumentAuditInfoExtension _DocumentAuditInfoExtension = new DocumentAuditInfoExtension();
[Serializable()] [Serializable()]
partial class DocumentAuditInfoExtension : extensionBase { } partial class DocumentAuditInfoExtension : extensionBase { }
[Serializable()] [Serializable()]
@@ -393,10 +351,10 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is DocumentAuditInfo) if (destType == typeof(string) && value is DocumentAuditInfo info)
{ {
// Return the ToString value // Return the ToString value
return ((DocumentAuditInfo)value).ToString(); return info.ToString();
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
@@ -13,8 +13,6 @@ using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
namespace VEPROMS.CSLA.Library namespace VEPROMS.CSLA.Library
@@ -28,11 +26,10 @@ namespace VEPROMS.CSLA.Library
{ {
#region Log4Net #region Log4Net
private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endregion #endregion
#region Business Methods #region Business Methods
internal new IList<DocumentAuditInfo> Items internal new IList<DocumentAuditInfo> Items => base.Items;
{ get { return base.Items; } } public void AddEvents()
public void AddEvents()
{ {
foreach (DocumentAuditInfo tmp in this) foreach (DocumentAuditInfo tmp in this)
{ {
@@ -51,16 +48,12 @@ namespace VEPROMS.CSLA.Library
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed ~DocumentAuditInfoList()
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~DocumentAuditInfoList()
{ {
_CountFinalized++; _CountFinalized++;
} }
@@ -97,26 +90,11 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Error on DocumentAuditInfoList.Get", ex); throw new DbCslaException("Error on DocumentAuditInfoList.Get", ex);
} }
} }
/// <summary> /// <summary>
/// Reset the list of all DocumentAuditInfo. /// Reset the list of all DocumentAuditInfo.
/// </summary> /// </summary>
public static void Reset() public static void Reset() => _DocumentAuditInfoList = null;
{ private DocumentAuditInfoList()
_DocumentAuditInfoList = null;
}
// CSLATODO: Add alternative gets -
//public static DocumentAuditInfoList Get(<criteria>)
//{
// try
// {
// return DataPortal.Fetch<DocumentAuditInfoList>(new FilteredCriteria(<criteria>));
// }
// catch (Exception ex)
// {
// throw new DbCslaException("Error on DocumentAuditInfoList.Get", ex);
// }
//}
private DocumentAuditInfoList()
{ /* require use of factory methods */ } { /* require use of factory methods */ }
#endregion #endregion
#region Data Access Portal #region Data Access Portal
@@ -149,41 +127,30 @@ namespace VEPROMS.CSLA.Library
} }
this.RaiseListChangedEvents = true; this.RaiseListChangedEvents = true;
} }
#endregion #endregion
#region ICustomTypeDescriptor impl #region ICustomTypeDescriptor impl
public String GetClassName() public string GetClassName() => TypeDescriptor.GetClassName(this, true);
{ return TypeDescriptor.GetClassName(this, true); } public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true);
public AttributeCollection GetAttributes() public string GetComponentName() => TypeDescriptor.GetComponentName(this, true);
{ return TypeDescriptor.GetAttributes(this, true); } public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true);
public String GetComponentName() public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true);
{ return TypeDescriptor.GetComponentName(this, true); } public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true);
public TypeConverter GetConverter() public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true);
{ return TypeDescriptor.GetConverter(this, true); } public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true);
public EventDescriptor GetDefaultEvent() public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true);
{ return TypeDescriptor.GetDefaultEvent(this, true); } public object GetPropertyOwner(PropertyDescriptor pd) => this;
public PropertyDescriptor GetDefaultProperty() /// <summary>
{ return TypeDescriptor.GetDefaultProperty(this, true); } /// Called to get the properties of this type. Returns properties with certain
public object GetEditor(Type editorBaseType) /// attributes. this restriction is not implemented here.
{ return TypeDescriptor.GetEditor(this, editorBaseType, true); } /// </summary>
public EventDescriptorCollection GetEvents(Attribute[] attributes) /// <param name="attributes"></param>
{ return TypeDescriptor.GetEvents(this, attributes, true); } /// <returns></returns>
public EventDescriptorCollection GetEvents() public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties();
{ return TypeDescriptor.GetEvents(this, true); } /// <summary>
public object GetPropertyOwner(PropertyDescriptor pd) /// Called to get the properties of this type.
{ return this; } /// </summary>
/// <summary> /// <returns></returns>
/// Called to get the properties of this type. Returns properties with certain public PropertyDescriptorCollection GetProperties()
/// attributes. this restriction is not implemented here.
/// </summary>
/// <param name="attributes"></param>
/// <returns></returns>
public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{ return GetProperties(); }
/// <summary>
/// Called to get the properties of this type.
/// </summary>
/// <returns></returns>
public PropertyDescriptorCollection GetProperties()
{ {
// Create a collection object to hold property descriptors // Create a collection object to hold property descriptors
PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null);
@@ -205,7 +172,6 @@ namespace VEPROMS.CSLA.Library
/// </summary> /// </summary>
public partial class DocumentAuditInfoListPropertyDescriptor : vlnListPropertyDescriptor public partial class DocumentAuditInfoListPropertyDescriptor : vlnListPropertyDescriptor
{ {
private DocumentAuditInfo Item { get { return (DocumentAuditInfo)_Item; } }
public DocumentAuditInfoListPropertyDescriptor(DocumentAuditInfoList collection, int index) : base(collection, index) { ;} public DocumentAuditInfoListPropertyDescriptor(DocumentAuditInfoList collection, int index) : base(collection, index) { ;}
} }
#endregion #endregion
@@ -214,10 +180,10 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is DocumentAuditInfoList) if (destType == typeof(string) && value is DocumentAuditInfoList list)
{ {
// Return department and department role separated by comma. // Return department and department role separated by comma.
return ((DocumentAuditInfoList)value).Items.Count.ToString() + " DocumentAudits"; return $"{list.Items.Count} DocumentAudits";
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
@@ -9,12 +9,9 @@
// ======================================================================== // ========================================================================
using System; using System;
using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
using Csla.Validation; using Csla.Validation;
@@ -31,11 +28,8 @@ namespace VEPROMS.CSLA.Library
private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endregion #endregion
#region Business Methods #region Business Methods
private string _ErrorMessage = string.Empty; private readonly string _ErrorMessage = string.Empty;
public string ErrorMessage public string ErrorMessage => _ErrorMessage;
{
get { return _ErrorMessage; }
}
private int _DROUsageID; private int _DROUsageID;
[System.ComponentModel.DataObjectField(true, true)] [System.ComponentModel.DataObjectField(true, true)]
public int DROUsageID public int DROUsageID
@@ -232,10 +226,7 @@ namespace VEPROMS.CSLA.Library
/// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// Overrides Base GetIdValue - Used internally by CSLA to determine equality
/// </summary> /// </summary>
/// <returns>A Unique ID for the current DocumentDROUsage</returns> /// <returns>A Unique ID for the current DocumentDROUsage</returns>
protected override object GetIdValue() protected override object GetIdValue() => MyDocumentDROUsageUnique; // Absolutely Unique ID
{
return MyDocumentDROUsageUnique; // Absolutely Unique ID
}
// CSLATODO: Replace base DocumentDROUsage.ToString function as necessary // CSLATODO: Replace base DocumentDROUsage.ToString function as necessary
/// <summary> /// <summary>
/// Overrides Base ToString /// Overrides Base ToString
@@ -259,18 +250,15 @@ namespace VEPROMS.CSLA.Library
if (base.IsDirty || list.Contains(this)) if (base.IsDirty || list.Contains(this))
return base.IsDirty; return base.IsDirty;
list.Add(this); list.Add(this);
return base.IsDirty || (_MyRODb == null ? false : _MyRODb.IsDirtyList(list)); return base.IsDirty || (_MyRODb != null && _MyRODb.IsDirtyList(list));
}
public override bool IsValid
{
get { return IsValidList(new List<object>()); }
} }
public override bool IsValid => IsValidList(new List<object>());
public bool IsValidList(List<object> list) public bool IsValidList(List<object> list)
{ {
if (list.Contains(this)) if (list.Contains(this))
return (IsNew && !IsDirty) ? true : base.IsValid; return (IsNew && !IsDirty) || base.IsValid;
list.Add(this); list.Add(this);
return ((IsNew && !IsDirty) ? true : base.IsValid) && (_MyRODb == null ? true : _MyRODb.IsValidList(list)); return ((IsNew && !IsDirty) || base.IsValid) && (_MyRODb == null || _MyRODb.IsValidList(list));
} }
#endregion #endregion
#region ValidationRules #region ValidationRules
@@ -300,8 +288,8 @@ namespace VEPROMS.CSLA.Library
get get
{ {
IVEHasBrokenRules hasBrokenRules = HasBrokenRules; IVEHasBrokenRules hasBrokenRules = HasBrokenRules;
if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; if (Equals(hasBrokenRules)) return BrokenRulesCollection;
return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); return hasBrokenRules?.BrokenRules;
} }
} }
protected override void AddBusinessRules() protected override void AddBusinessRules()
@@ -331,78 +319,22 @@ namespace VEPROMS.CSLA.Library
} }
return true; return true;
} }
// Sample data comparison validation rule
//private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e)
//{
// if (_started > _ended)
// {
// e.Description = "Start date can't be after end date";
// return false;
// }
// else
// return true;
//}
#endregion #endregion
#region Authorization Rules #region Authorization Rules
protected override void AddAuthorizationRules() protected override void AddAuthorizationRules()
{ {
//CSLATODO: Who can read/write which fields
//AuthorizationRules.AllowRead(DROUsageID, "<Role(s)>");
//AuthorizationRules.AllowRead(ROID, "<Role(s)>");
//AuthorizationRules.AllowWrite(ROID, "<Role(s)>");
//AuthorizationRules.AllowRead(Config, "<Role(s)>");
//AuthorizationRules.AllowWrite(Config, "<Role(s)>");
//AuthorizationRules.AllowRead(DTS, "<Role(s)>");
//AuthorizationRules.AllowWrite(DTS, "<Role(s)>");
//AuthorizationRules.AllowRead(UserID, "<Role(s)>");
//AuthorizationRules.AllowWrite(UserID, "<Role(s)>");
//AuthorizationRules.AllowRead(RODbID, "<Role(s)>");
//AuthorizationRules.AllowWrite(RODbID, "<Role(s)>");
}
public static bool CanAddObject()
{
// CSLATODO: Can Add Authorization
//return Csla.ApplicationContext.User.IsInRole("ProjectManager");
return true;
}
public static bool CanGetObject()
{
// CSLATODO: CanGet Authorization
return true;
}
public static bool CanDeleteObject()
{
// CSLATODO: CanDelete Authorization
//bool result = false;
//if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true;
//if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true;
//return result;
return true;
}
public static bool CanEditObject()
{
// CSLATODO: CanEdit Authorization
//return Csla.ApplicationContext.User.IsInRole("ProjectManager");
return true;
} }
#endregion #endregion
#region Factory Methods #region Factory Methods
public int CurrentEditLevel public int CurrentEditLevel => EditLevel;
{ get { return EditLevel; } }
private static int _DocumentDROUsageUnique = 0; private static int _DocumentDROUsageUnique = 0;
private static int DocumentDROUsageUnique private static int DocumentDROUsageUnique => ++_DocumentDROUsageUnique;
{ get { return ++_DocumentDROUsageUnique; } } private readonly int _MyDocumentDROUsageUnique = DocumentDROUsageUnique;
private int _MyDocumentDROUsageUnique = DocumentDROUsageUnique; // Absolutely Unique ID - Editable FK
public int MyDocumentDROUsageUnique // Absolutely Unique ID - Editable FK public int MyDocumentDROUsageUnique => _MyDocumentDROUsageUnique;
{ get { return _MyDocumentDROUsageUnique; } } internal static DocumentDROUsage New(string roid, RODb myRODb) => new DocumentDROUsage(roid, myRODb);
internal static DocumentDROUsage New(string roid, RODb myRODb) internal static DocumentDROUsage Get(SafeDataReader dr) => new DocumentDROUsage(dr);
{
return new DocumentDROUsage(roid, myRODb);
}
internal static DocumentDROUsage Get(SafeDataReader dr)
{
return new DocumentDROUsage(dr);
}
public DocumentDROUsage() public DocumentDROUsage()
{ {
MarkAsChild(); MarkAsChild();
@@ -431,15 +363,11 @@ namespace VEPROMS.CSLA.Library
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~DocumentDROUsage() ~DocumentDROUsage()
{ {
_CountFinalized++; _CountFinalized++;
@@ -481,33 +409,46 @@ namespace VEPROMS.CSLA.Library
internal void Insert(Document myDocument) internal void Insert(Document myDocument)
{ {
// if we're not dirty then don't update the database // if we're not dirty then don't update the database
if (!this.IsDirty) return; if (!IsDirty) return;
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = Database.VEPROMS_SqlConnection)
_LastChanged = DROUsage.Add(cn, ref _DROUsageID, myDocument, _ROID, _Config, _DTS, _UserID, _MyRODb); {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
_LastChanged = DROUsage.Add(cn, ref _DROUsageID, myDocument, _ROID, _Config, _DTS, _UserID, _MyRODb);
}
MarkOld(); MarkOld();
} }
internal void Update(Document myDocument) internal void Update(Document myDocument)
{ {
// if we're not dirty then don't update the database // if we're not dirty then don't update the database
if (!this.IsDirty) return; if (!IsDirty) return;
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = Database.VEPROMS_SqlConnection)
_LastChanged = DROUsage.Update(cn, ref _DROUsageID, myDocument.DocID, _ROID, _Config, _DTS, _UserID, ref _LastChanged, _RODbID); {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
_LastChanged = DROUsage.Update(cn, ref _DROUsageID, myDocument.DocID, _ROID, _Config, _DTS, _UserID, ref _LastChanged, _RODbID);
}
MarkOld(); MarkOld();
} }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")]
internal void DeleteSelf(Document myDocument) internal void DeleteSelf(Document myDocument)
{ {
// if we're not dirty then don't update the database // if we're not dirty then don't update the database
if (!this.IsDirty) return; if (!IsDirty) return;
// if we're new then don't update the database // if we're new then don't update the database
if (this.IsNew) return; if (IsNew) return;
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = Database.VEPROMS_SqlConnection)
DROUsage.Remove(cn, _DROUsageID); {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
DROUsage.Remove(cn, _DROUsageID);
}
MarkNew(); MarkNew();
} }
#endregion #endregion
// Standard Default Code // Standard Default Code
#region extension #region extension
DocumentDROUsageExtension _DocumentDROUsageExtension = new DocumentDROUsageExtension(); readonly DocumentDROUsageExtension _DocumentDROUsageExtension = new DocumentDROUsageExtension();
[Serializable()] [Serializable()]
partial class DocumentDROUsageExtension : extensionBase partial class DocumentDROUsageExtension : extensionBase
{ {
@@ -516,18 +457,9 @@ namespace VEPROMS.CSLA.Library
class extensionBase class extensionBase
{ {
// Default Values // Default Values
public virtual int DefaultDocID public virtual int DefaultDocID => 0;
{ public virtual DateTime DefaultDTS => DateTime.Now;
get { return 0; } public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID;
}
public virtual DateTime DefaultDTS
{
get { return DateTime.Now; }
}
public virtual string DefaultUserID
{
get { return Volian.Base.Library.VlnSettings.UserID; }
}
// Authorization Rules // Authorization Rules
public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules)
{ {
@@ -556,61 +488,13 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is DocumentDROUsage) if (destType == typeof(string) && value is DocumentDROUsage usage)
{ {
// Return the ToString value // Return the ToString value
return ((DocumentDROUsage)value).ToString(); return usage.ToString();
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
} }
#endregion #endregion
} // Namespace } // Namespace
//// The following is a sample Extension File. You can use it to create DocumentDROUsageExt.cs
//using System;
//using System.Collections.Generic;
//using System.Text;
//using Csla;
//namespace VEPROMS.CSLA.Library
//{
// public partial class DocumentDROUsage
// {
// partial class DocumentDROUsageExtension : extensionBase
// {
// // CSLATODO: Override automatic defaults
// public virtual int DefaultDocID
// {
// get { return 0; }
// }
// public virtual DateTime DefaultDTS
// {
// get { return DateTime.Now; }
// }
// public virtual string DefaultUserID
// {
// get { return Environment.UserName.ToUpper(); }
// }
// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules)
// {
// //rules.AllowRead(Dbid, "<Role(s)>");
// }
// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules)
// {
// //rules.AllowInstanceRead(Dbid, "<Role(s)>");
// }
// public new void AddValidationRules(Csla.Validation.ValidationRules rules)
// {
// rules.AddRule(
// Csla.Validation.CommonRules.StringMaxLength,
// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100));
// }
// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules)
// {
// rules.AddInstanceRule(/* Instance Validation Rule */);
// }
// }
// }
//}
@@ -13,8 +13,6 @@ using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
using Csla.Validation; using Csla.Validation;
@@ -31,13 +29,10 @@ namespace VEPROMS.CSLA.Library
private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endregion #endregion
#region Business Methods #region Business Methods
private string _ErrorMessage = string.Empty; private readonly string _ErrorMessage = string.Empty;
public string ErrorMessage public string ErrorMessage => _ErrorMessage;
{ // One To Many
get { return _ErrorMessage; } public DocumentDROUsage this[DROUsage myDROUsage]
}
// One To Many
public DocumentDROUsage this[DROUsage myDROUsage]
{ {
get get
{ {
@@ -47,11 +42,8 @@ namespace VEPROMS.CSLA.Library
return null; return null;
} }
} }
public new System.Collections.Generic.IList<DocumentDROUsage> Items public new System.Collections.Generic.IList<DocumentDROUsage> Items => base.Items;
{ public DocumentDROUsage GetItem(DROUsage myDROUsage)
get { return base.Items; }
}
public DocumentDROUsage GetItem(DROUsage myDROUsage)
{ {
foreach (DocumentDROUsage dROUsage in this) foreach (DocumentDROUsage dROUsage in this)
if (dROUsage.DROUsageID == myDROUsage.DROUsageID) if (dROUsage.DROUsageID == myDROUsage.DROUsageID)
@@ -61,7 +53,7 @@ namespace VEPROMS.CSLA.Library
public DocumentDROUsage Add(string roid, RODb myRODb) // One to Many public DocumentDROUsage Add(string roid, RODb myRODb) // One to Many
{ {
DocumentDROUsage dROUsage = DocumentDROUsage.New(roid, myRODb); DocumentDROUsage dROUsage = DocumentDROUsage.New(roid, myRODb);
this.Add(dROUsage); Add(dROUsage);
return dROUsage; return dROUsage;
} }
public void Remove(DROUsage myDROUsage) public void Remove(DROUsage myDROUsage)
@@ -103,23 +95,20 @@ namespace VEPROMS.CSLA.Library
return true; return true;
return false; return false;
} }
public override bool IsValid public override bool IsValid => IsValidList(new List<object>());
public bool IsValidList(List<object> list)
{ {
get { return IsValidList(new List<object>()); } // run through all the child objects
} // and if any are invalid then the
public bool IsValidList(List<object> list) // collection is invalid
{ foreach (DocumentDROUsage child in this)
// run through all the child objects if (!child.IsValidList(list))
// and if any are invalid then the {
// collection is invalid //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString());
foreach (DocumentDROUsage child in this) return false;
if (!child.IsValidList(list)) }
{ return true;
//Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); }
return false;
}
return true;
}
#endregion #endregion
#region ValidationRules #region ValidationRules
public IVEHasBrokenRules HasBrokenRules public IVEHasBrokenRules HasBrokenRules
@@ -137,20 +126,14 @@ namespace VEPROMS.CSLA.Library
get get
{ {
IVEHasBrokenRules hasBrokenRules = HasBrokenRules; IVEHasBrokenRules hasBrokenRules = HasBrokenRules;
return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); return hasBrokenRules?.BrokenRules;
} }
} }
#endregion #endregion
#region Factory Methods #region Factory Methods
internal static DocumentDROUsages New() internal static DocumentDROUsages New() => new DocumentDROUsages();
{ internal static DocumentDROUsages Get(SafeDataReader dr) => new DocumentDROUsages(dr);
return new DocumentDROUsages(); public static DocumentDROUsages GetByDocID(int docID)
}
internal static DocumentDROUsages Get(SafeDataReader dr)
{
return new DocumentDROUsages(dr);
}
public static DocumentDROUsages GetByDocID(int docID)
{ {
try try
{ {
@@ -161,11 +144,8 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Error on DocumentDROUsages.GetByDocID", ex); throw new DbCslaException("Error on DocumentDROUsages.GetByDocID", ex);
} }
} }
private DocumentDROUsages() private DocumentDROUsages() => MarkAsChild();
{ internal DocumentDROUsages(SafeDataReader dr)
MarkAsChild();
}
internal DocumentDROUsages(SafeDataReader dr)
{ {
MarkAsChild(); MarkAsChild();
Fetch(dr); Fetch(dr);
@@ -174,16 +154,12 @@ namespace VEPROMS.CSLA.Library
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed ~DocumentDROUsages()
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~DocumentDROUsages()
{ {
_CountFinalized++; _CountFinalized++;
} }
@@ -198,19 +174,16 @@ namespace VEPROMS.CSLA.Library
// called to load data from the database // called to load data from the database
private void Fetch(SafeDataReader dr) private void Fetch(SafeDataReader dr)
{ {
this.RaiseListChangedEvents = false; RaiseListChangedEvents = false;
while (dr.Read()) while (dr.Read())
this.Add(DocumentDROUsage.Get(dr)); Add(DocumentDROUsage.Get(dr));
this.RaiseListChangedEvents = true; RaiseListChangedEvents = true;
} }
[Serializable()] [Serializable()]
private class DocIDCriteria private class DocIDCriteria
{ {
public DocIDCriteria(int docID) public DocIDCriteria(int docID) => _DocID = docID;
{ private int _DocID;
_DocID = docID;
}
private int _DocID;
public int DocID public int DocID
{ {
get { return _DocID; } get { return _DocID; }
@@ -219,7 +192,7 @@ namespace VEPROMS.CSLA.Library
} }
private void DataPortal_Fetch(DocIDCriteria criteria) private void DataPortal_Fetch(DocIDCriteria criteria)
{ {
this.RaiseListChangedEvents = false; RaiseListChangedEvents = false;
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocumentDROUsages.DataPortal_FetchDocID", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocumentDROUsages.DataPortal_FetchDocID", GetHashCode());
try try
{ {
@@ -233,7 +206,7 @@ namespace VEPROMS.CSLA.Library
cm.CommandTimeout = Database.DefaultTimeout; cm.CommandTimeout = Database.DefaultTimeout;
using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
{ {
while (dr.Read()) this.Add(new DocumentDROUsage(dr)); while (dr.Read()) Add(new DocumentDROUsage(dr));
} }
} }
} }
@@ -243,11 +216,11 @@ namespace VEPROMS.CSLA.Library
if (_MyLog.IsErrorEnabled) _MyLog.Error("DocumentDROUsages.DataPortal_FetchDocID", ex); if (_MyLog.IsErrorEnabled) _MyLog.Error("DocumentDROUsages.DataPortal_FetchDocID", ex);
throw new DbCslaException("DocumentDROUsages.DataPortal_Fetch", ex); throw new DbCslaException("DocumentDROUsages.DataPortal_Fetch", ex);
} }
this.RaiseListChangedEvents = true; RaiseListChangedEvents = true;
} }
internal void Update(Document document) internal void Update(Document document)
{ {
this.RaiseListChangedEvents = false; RaiseListChangedEvents = false;
try try
{ {
// update (thus deleting) any deleted child objects // update (thus deleting) any deleted child objects
@@ -266,49 +239,38 @@ namespace VEPROMS.CSLA.Library
} }
finally finally
{ {
this.RaiseListChangedEvents = true; RaiseListChangedEvents = true;
} }
} }
#endregion #endregion
#region ICustomTypeDescriptor impl #region ICustomTypeDescriptor impl
public String GetClassName() public string GetClassName() => TypeDescriptor.GetClassName(this, true);
{ return TypeDescriptor.GetClassName(this, true); } public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true);
public AttributeCollection GetAttributes() public string GetComponentName() => TypeDescriptor.GetComponentName(this, true);
{ return TypeDescriptor.GetAttributes(this, true); } public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true);
public String GetComponentName() public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true);
{ return TypeDescriptor.GetComponentName(this, true); } public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true);
public TypeConverter GetConverter() public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true);
{ return TypeDescriptor.GetConverter(this, true); } public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true);
public EventDescriptor GetDefaultEvent() public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true);
{ return TypeDescriptor.GetDefaultEvent(this, true); } public object GetPropertyOwner(PropertyDescriptor pd) => this;
public PropertyDescriptor GetDefaultProperty() /// <summary>
{ return TypeDescriptor.GetDefaultProperty(this, true); } /// Called to get the properties of this type. Returns properties with certain
public object GetEditor(Type editorBaseType) /// attributes. this restriction is not implemented here.
{ return TypeDescriptor.GetEditor(this, editorBaseType, true); } /// </summary>
public EventDescriptorCollection GetEvents(Attribute[] attributes) /// <param name="attributes"></param>
{ return TypeDescriptor.GetEvents(this, attributes, true); } /// <returns></returns>
public EventDescriptorCollection GetEvents() public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties();
{ return TypeDescriptor.GetEvents(this, true); } /// <summary>
public object GetPropertyOwner(PropertyDescriptor pd) /// Called to get the properties of this type.
{ return this; } /// </summary>
/// <summary> /// <returns></returns>
/// Called to get the properties of this type. Returns properties with certain public PropertyDescriptorCollection GetProperties()
/// attributes. this restriction is not implemented here.
/// </summary>
/// <param name="attributes"></param>
/// <returns></returns>
public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{ return GetProperties(); }
/// <summary>
/// Called to get the properties of this type.
/// </summary>
/// <returns></returns>
public PropertyDescriptorCollection GetProperties()
{ {
// Create a collection object to hold property descriptors // Create a collection object to hold property descriptors
PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null);
// Iterate the list // Iterate the list
for (int i = 0; i < this.Items.Count; i++) for (int i = 0; i < Items.Count; i++)
{ {
// Create a property descriptor for the item and add to the property descriptor collection // Create a property descriptor for the item and add to the property descriptor collection
DocumentDROUsagesPropertyDescriptor pd = new DocumentDROUsagesPropertyDescriptor(this, i); DocumentDROUsagesPropertyDescriptor pd = new DocumentDROUsagesPropertyDescriptor(this, i);
@@ -325,7 +287,6 @@ namespace VEPROMS.CSLA.Library
/// </summary> /// </summary>
public partial class DocumentDROUsagesPropertyDescriptor : vlnListPropertyDescriptor public partial class DocumentDROUsagesPropertyDescriptor : vlnListPropertyDescriptor
{ {
private DocumentDROUsage Item { get { return (DocumentDROUsage)_Item; } }
public DocumentDROUsagesPropertyDescriptor(DocumentDROUsages collection, int index) : base(collection, index) { ;} public DocumentDROUsagesPropertyDescriptor(DocumentDROUsages collection, int index) : base(collection, index) { ;}
} }
#endregion #endregion
@@ -334,10 +295,10 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is DocumentDROUsages) if (destType == typeof(string) && value is DocumentDROUsages usages)
{ {
// Return department and department role separated by comma. // Return department and department role separated by comma.
return ((DocumentDROUsages)value).Items.Count.ToString() + " DROUsages"; return $"{usages.Items.Count} DROUsages";
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
@@ -13,8 +13,6 @@ using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
using Csla.Validation; using Csla.Validation;
@@ -31,13 +29,10 @@ namespace VEPROMS.CSLA.Library
private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endregion #endregion
#region Business Methods #region Business Methods
private string _ErrorMessage = string.Empty; private readonly string _ErrorMessage = string.Empty;
public string ErrorMessage public string ErrorMessage => _ErrorMessage;
{ // One To Many
get { return _ErrorMessage; } public DocumentEntry this[Entry myEntry]
}
// One To Many
public DocumentEntry this[Entry myEntry]
{ {
get get
{ {
@@ -47,11 +42,8 @@ namespace VEPROMS.CSLA.Library
return null; return null;
} }
} }
public new System.Collections.Generic.IList<DocumentEntry> Items public new System.Collections.Generic.IList<DocumentEntry> Items => base.Items;
{ public DocumentEntry GetItem(Entry myEntry)
get { return base.Items; }
}
public DocumentEntry GetItem(Entry myEntry)
{ {
foreach (DocumentEntry entry in this) foreach (DocumentEntry entry in this)
if (entry.ContentID == myEntry.ContentID) if (entry.ContentID == myEntry.ContentID)
@@ -61,7 +53,7 @@ namespace VEPROMS.CSLA.Library
public DocumentEntry Add(Entry myEntry) // One to Many public DocumentEntry Add(Entry myEntry) // One to Many
{ {
DocumentEntry entry = DocumentEntry.New(myEntry); DocumentEntry entry = DocumentEntry.New(myEntry);
this.Add(entry); Add(entry);
return entry; return entry;
} }
public void Remove(Entry myEntry) public void Remove(Entry myEntry)
@@ -103,23 +95,20 @@ namespace VEPROMS.CSLA.Library
return true; return true;
return false; return false;
} }
public override bool IsValid public override bool IsValid => IsValidList(new List<object>());
public bool IsValidList(List<object> list)
{ {
get { return IsValidList(new List<object>()); } // run through all the child objects
} // and if any are invalid then the
public bool IsValidList(List<object> list) // collection is invalid
{ foreach (DocumentEntry child in this)
// run through all the child objects if (!child.IsValidList(list))
// and if any are invalid then the {
// collection is invalid //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString());
foreach (DocumentEntry child in this) return false;
if (!child.IsValidList(list)) }
{ return true;
//Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); }
return false;
}
return true;
}
#endregion #endregion
#region ValidationRules #region ValidationRules
public IVEHasBrokenRules HasBrokenRules public IVEHasBrokenRules HasBrokenRules
@@ -137,20 +126,14 @@ namespace VEPROMS.CSLA.Library
get get
{ {
IVEHasBrokenRules hasBrokenRules = HasBrokenRules; IVEHasBrokenRules hasBrokenRules = HasBrokenRules;
return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); return hasBrokenRules?.BrokenRules;
} }
} }
#endregion #endregion
#region Factory Methods #region Factory Methods
internal static DocumentEntries New() internal static DocumentEntries New() => new DocumentEntries();
{ internal static DocumentEntries Get(SafeDataReader dr) => new DocumentEntries(dr);
return new DocumentEntries(); public static DocumentEntries GetByDocID(int docID)
}
internal static DocumentEntries Get(SafeDataReader dr)
{
return new DocumentEntries(dr);
}
public static DocumentEntries GetByDocID(int docID)
{ {
try try
{ {
@@ -161,11 +144,8 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Error on DocumentEntries.GetByDocID", ex); throw new DbCslaException("Error on DocumentEntries.GetByDocID", ex);
} }
} }
private DocumentEntries() private DocumentEntries() => MarkAsChild();
{ internal DocumentEntries(SafeDataReader dr)
MarkAsChild();
}
internal DocumentEntries(SafeDataReader dr)
{ {
MarkAsChild(); MarkAsChild();
Fetch(dr); Fetch(dr);
@@ -174,16 +154,12 @@ namespace VEPROMS.CSLA.Library
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed ~DocumentEntries()
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~DocumentEntries()
{ {
_CountFinalized++; _CountFinalized++;
} }
@@ -198,19 +174,16 @@ namespace VEPROMS.CSLA.Library
// called to load data from the database // called to load data from the database
private void Fetch(SafeDataReader dr) private void Fetch(SafeDataReader dr)
{ {
this.RaiseListChangedEvents = false; RaiseListChangedEvents = false;
while (dr.Read()) while (dr.Read())
this.Add(DocumentEntry.Get(dr)); Add(DocumentEntry.Get(dr));
this.RaiseListChangedEvents = true; RaiseListChangedEvents = true;
} }
[Serializable()] [Serializable()]
private class DocIDCriteria private class DocIDCriteria
{ {
public DocIDCriteria(int docID) public DocIDCriteria(int docID) => _DocID = docID;
{ private int _DocID;
_DocID = docID;
}
private int _DocID;
public int DocID public int DocID
{ {
get { return _DocID; } get { return _DocID; }
@@ -219,7 +192,7 @@ namespace VEPROMS.CSLA.Library
} }
private void DataPortal_Fetch(DocIDCriteria criteria) private void DataPortal_Fetch(DocIDCriteria criteria)
{ {
this.RaiseListChangedEvents = false; RaiseListChangedEvents = false;
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocumentEntries.DataPortal_FetchDocID", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocumentEntries.DataPortal_FetchDocID", GetHashCode());
try try
{ {
@@ -233,7 +206,7 @@ namespace VEPROMS.CSLA.Library
cm.CommandTimeout = Database.DefaultTimeout; cm.CommandTimeout = Database.DefaultTimeout;
using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
{ {
while (dr.Read()) this.Add(new DocumentEntry(dr)); while (dr.Read()) Add(new DocumentEntry(dr));
} }
} }
} }
@@ -243,11 +216,11 @@ namespace VEPROMS.CSLA.Library
if (_MyLog.IsErrorEnabled) _MyLog.Error("DocumentEntries.DataPortal_FetchDocID", ex); if (_MyLog.IsErrorEnabled) _MyLog.Error("DocumentEntries.DataPortal_FetchDocID", ex);
throw new DbCslaException("DocumentEntries.DataPortal_Fetch", ex); throw new DbCslaException("DocumentEntries.DataPortal_Fetch", ex);
} }
this.RaiseListChangedEvents = true; RaiseListChangedEvents = true;
} }
internal void Update(Document document) internal void Update(Document document)
{ {
this.RaiseListChangedEvents = false; RaiseListChangedEvents = false;
try try
{ {
// update (thus deleting) any deleted child objects // update (thus deleting) any deleted child objects
@@ -266,49 +239,38 @@ namespace VEPROMS.CSLA.Library
} }
finally finally
{ {
this.RaiseListChangedEvents = true; RaiseListChangedEvents = true;
} }
} }
#endregion #endregion
#region ICustomTypeDescriptor impl #region ICustomTypeDescriptor impl
public String GetClassName() public string GetClassName() => TypeDescriptor.GetClassName(this, true);
{ return TypeDescriptor.GetClassName(this, true); } public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true);
public AttributeCollection GetAttributes() public string GetComponentName() => TypeDescriptor.GetComponentName(this, true);
{ return TypeDescriptor.GetAttributes(this, true); } public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true);
public String GetComponentName() public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true);
{ return TypeDescriptor.GetComponentName(this, true); } public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true);
public TypeConverter GetConverter() public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true);
{ return TypeDescriptor.GetConverter(this, true); } public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true);
public EventDescriptor GetDefaultEvent() public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true);
{ return TypeDescriptor.GetDefaultEvent(this, true); } public object GetPropertyOwner(PropertyDescriptor pd) => this;
public PropertyDescriptor GetDefaultProperty() /// <summary>
{ return TypeDescriptor.GetDefaultProperty(this, true); } /// Called to get the properties of this type. Returns properties with certain
public object GetEditor(Type editorBaseType) /// attributes. this restriction is not implemented here.
{ return TypeDescriptor.GetEditor(this, editorBaseType, true); } /// </summary>
public EventDescriptorCollection GetEvents(Attribute[] attributes) /// <param name="attributes"></param>
{ return TypeDescriptor.GetEvents(this, attributes, true); } /// <returns></returns>
public EventDescriptorCollection GetEvents() public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties();
{ return TypeDescriptor.GetEvents(this, true); } /// <summary>
public object GetPropertyOwner(PropertyDescriptor pd) /// Called to get the properties of this type.
{ return this; } /// </summary>
/// <summary> /// <returns></returns>
/// Called to get the properties of this type. Returns properties with certain public PropertyDescriptorCollection GetProperties()
/// attributes. this restriction is not implemented here.
/// </summary>
/// <param name="attributes"></param>
/// <returns></returns>
public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{ return GetProperties(); }
/// <summary>
/// Called to get the properties of this type.
/// </summary>
/// <returns></returns>
public PropertyDescriptorCollection GetProperties()
{ {
// Create a collection object to hold property descriptors // Create a collection object to hold property descriptors
PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null);
// Iterate the list // Iterate the list
for (int i = 0; i < this.Items.Count; i++) for (int i = 0; i < Items.Count; i++)
{ {
// Create a property descriptor for the item and add to the property descriptor collection // Create a property descriptor for the item and add to the property descriptor collection
DocumentEntriesPropertyDescriptor pd = new DocumentEntriesPropertyDescriptor(this, i); DocumentEntriesPropertyDescriptor pd = new DocumentEntriesPropertyDescriptor(this, i);
@@ -325,7 +287,6 @@ namespace VEPROMS.CSLA.Library
/// </summary> /// </summary>
public partial class DocumentEntriesPropertyDescriptor : vlnListPropertyDescriptor public partial class DocumentEntriesPropertyDescriptor : vlnListPropertyDescriptor
{ {
private DocumentEntry Item { get { return (DocumentEntry)_Item; } }
public DocumentEntriesPropertyDescriptor(DocumentEntries collection, int index) : base(collection, index) { ;} public DocumentEntriesPropertyDescriptor(DocumentEntries collection, int index) : base(collection, index) { ;}
} }
#endregion #endregion
@@ -334,10 +295,10 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is DocumentEntries) if (destType == typeof(string) && value is DocumentEntries entries)
{ {
// Return department and department role separated by comma. // Return department and department role separated by comma.
return ((DocumentEntries)value).Items.Count.ToString() + " Entries"; return $"{entries.Items.Count} Entries";
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
@@ -9,12 +9,9 @@
// ======================================================================== // ========================================================================
using System; using System;
using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
using Csla.Validation; using Csla.Validation;
@@ -31,11 +28,8 @@ namespace VEPROMS.CSLA.Library
private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endregion #endregion
#region Business Methods #region Business Methods
private string _ErrorMessage = string.Empty; private readonly string _ErrorMessage = string.Empty;
public string ErrorMessage public string ErrorMessage => _ErrorMessage;
{
get { return _ErrorMessage; }
}
private int _ContentID; private int _ContentID;
[System.ComponentModel.DataObjectField(true, true)] [System.ComponentModel.DataObjectField(true, true)]
public int ContentID public int ContentID
@@ -170,35 +164,13 @@ namespace VEPROMS.CSLA.Library
/// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// Overrides Base GetIdValue - Used internally by CSLA to determine equality
/// </summary> /// </summary>
/// <returns>A Unique ID for the current DocumentEntry</returns> /// <returns>A Unique ID for the current DocumentEntry</returns>
protected override object GetIdValue() protected override object GetIdValue() => MyDocumentEntryUnique; // Absolutely Unique ID
{ public override bool IsDirty => base.IsDirty;
return MyDocumentEntryUnique; // Absolutely Unique ID [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")]
} public bool IsDirtyList(List<object> list) => base.IsDirty;
// CSLATODO: Replace base DocumentEntry.ToString function as necessary public override bool IsValid => (IsNew && !IsDirty) || base.IsValid;
/// <summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")]
/// Overrides Base ToString public bool IsValidList(List<object> list) => (IsNew && !IsDirty) || base.IsValid;
/// </summary>
/// <returns>A string representation of current DocumentEntry</returns>
//public override string ToString()
//{
// return base.ToString();
//}
public override bool IsDirty
{
get { return base.IsDirty; }
}
public bool IsDirtyList(List<object> list)
{
return base.IsDirty;
}
public override bool IsValid
{
get { return (IsNew && !IsDirty) ? true : base.IsValid; }
}
public bool IsValidList(List<object> list)
{
return (IsNew && !IsDirty) ? true : base.IsValid;
}
#endregion #endregion
#region ValidationRules #region ValidationRules
[NonSerialized] [NonSerialized]
@@ -226,8 +198,8 @@ namespace VEPROMS.CSLA.Library
get get
{ {
IVEHasBrokenRules hasBrokenRules = HasBrokenRules; IVEHasBrokenRules hasBrokenRules = HasBrokenRules;
if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; if (Equals(hasBrokenRules)) return BrokenRulesCollection;
return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); return hasBrokenRules?.BrokenRules;
} }
} }
protected override void AddBusinessRules() protected override void AddBusinessRules()
@@ -239,72 +211,22 @@ namespace VEPROMS.CSLA.Library
new Csla.Validation.CommonRules.MaxLengthRuleArgs("UserID", 100)); new Csla.Validation.CommonRules.MaxLengthRuleArgs("UserID", 100));
// CSLATODO: Add other validation rules // CSLATODO: Add other validation rules
} }
// Sample data comparison validation rule
//private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e)
//{
// if (_started > _ended)
// {
// e.Description = "Start date can't be after end date";
// return false;
// }
// else
// return true;
//}
#endregion #endregion
#region Authorization Rules #region Authorization Rules
protected override void AddAuthorizationRules() protected override void AddAuthorizationRules()
{ {
//CSLATODO: Who can read/write which fields
//AuthorizationRules.AllowRead(ContentID, "<Role(s)>");
//AuthorizationRules.AllowRead(DTS, "<Role(s)>");
//AuthorizationRules.AllowWrite(DTS, "<Role(s)>");
//AuthorizationRules.AllowRead(UserID, "<Role(s)>");
//AuthorizationRules.AllowWrite(UserID, "<Role(s)>");
}
public static bool CanAddObject()
{
// CSLATODO: Can Add Authorization
//return Csla.ApplicationContext.User.IsInRole("ProjectManager");
return true;
}
public static bool CanGetObject()
{
// CSLATODO: CanGet Authorization
return true;
}
public static bool CanDeleteObject()
{
// CSLATODO: CanDelete Authorization
//bool result = false;
//if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true;
//if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true;
//return result;
return true;
}
public static bool CanEditObject()
{
// CSLATODO: CanEdit Authorization
//return Csla.ApplicationContext.User.IsInRole("ProjectManager");
return true;
} }
#endregion #endregion
#region Factory Methods #region Factory Methods
public int CurrentEditLevel public int CurrentEditLevel => EditLevel;
{ get { return EditLevel; } }
private static int _DocumentEntryUnique = 0; private static int _DocumentEntryUnique = 0;
private static int DocumentEntryUnique private static int DocumentEntryUnique => ++_DocumentEntryUnique;
{ get { return ++_DocumentEntryUnique; } } private readonly int _MyDocumentEntryUnique = DocumentEntryUnique;
private int _MyDocumentEntryUnique = DocumentEntryUnique; // Absolutely Unique ID - Editable FK
public int MyDocumentEntryUnique // Absolutely Unique ID - Editable FK public int MyDocumentEntryUnique => _MyDocumentEntryUnique;
{ get { return _MyDocumentEntryUnique; } } internal static DocumentEntry New(Entry myEntry) => new DocumentEntry(myEntry);
internal static DocumentEntry New(Entry myEntry) internal static DocumentEntry Get(SafeDataReader dr) => new DocumentEntry(dr);
{
return new DocumentEntry(myEntry);
}
internal static DocumentEntry Get(SafeDataReader dr)
{
return new DocumentEntry(dr);
}
public DocumentEntry() public DocumentEntry()
{ {
MarkAsChild(); MarkAsChild();
@@ -331,15 +253,11 @@ namespace VEPROMS.CSLA.Library
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~DocumentEntry() ~DocumentEntry()
{ {
_CountFinalized++; _CountFinalized++;
@@ -379,33 +297,46 @@ namespace VEPROMS.CSLA.Library
internal void Insert(Document myDocument) internal void Insert(Document myDocument)
{ {
// if we're not dirty then don't update the database // if we're not dirty then don't update the database
if (!this.IsDirty) return; if (!IsDirty) return;
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = Database.VEPROMS_SqlConnection)
_LastChanged = Entry.Add(cn, _MyEntry.MyContent, myDocument, _DTS, _UserID); {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
_LastChanged = Entry.Add(cn, _MyEntry.MyContent, myDocument, _DTS, _UserID);
}
MarkOld(); MarkOld();
} }
internal void Update(Document myDocument) internal void Update(Document myDocument)
{ {
// if we're not dirty then don't update the database // if we're not dirty then don't update the database
if (!this.IsDirty) return; if (!IsDirty) return;
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = Database.VEPROMS_SqlConnection)
_LastChanged = Entry.Update(cn, _ContentID, myDocument.DocID, _DTS, _UserID, ref _LastChanged); {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
_LastChanged = Entry.Update(cn, _ContentID, myDocument.DocID, _DTS, _UserID, ref _LastChanged);
}
MarkOld(); MarkOld();
} }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")]
internal void DeleteSelf(Document myDocument) internal void DeleteSelf(Document myDocument)
{ {
// if we're not dirty then don't update the database // if we're not dirty then don't update the database
if (!this.IsDirty) return; if (!IsDirty) return;
// if we're new then don't update the database // if we're new then don't update the database
if (this.IsNew) return; if (IsNew) return;
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = Database.VEPROMS_SqlConnection)
Entry.Remove(cn, _ContentID); {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
Entry.Remove(cn, _ContentID);
}
MarkNew(); MarkNew();
} }
#endregion #endregion
// Standard Default Code // Standard Default Code
#region extension #region extension
DocumentEntryExtension _DocumentEntryExtension = new DocumentEntryExtension(); readonly DocumentEntryExtension _DocumentEntryExtension = new DocumentEntryExtension();
[Serializable()] [Serializable()]
partial class DocumentEntryExtension : extensionBase partial class DocumentEntryExtension : extensionBase
{ {
@@ -414,14 +345,8 @@ namespace VEPROMS.CSLA.Library
class extensionBase class extensionBase
{ {
// Default Values // Default Values
public virtual DateTime DefaultDTS public virtual DateTime DefaultDTS => DateTime.Now;
{ public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID;
get { return DateTime.Now; }
}
public virtual string DefaultUserID
{
get { return Volian.Base.Library.VlnSettings.UserID; }
}
// Authorization Rules // Authorization Rules
public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules)
{ {
@@ -450,57 +375,13 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is DocumentEntry) if (destType == typeof(string) && value is DocumentEntry entry)
{ {
// Return the ToString value // Return the ToString value
return ((DocumentEntry)value).ToString(); return entry.ToString();
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
} }
#endregion #endregion
} // Namespace } // Namespace
//// The following is a sample Extension File. You can use it to create DocumentEntryExt.cs
//using System;
//using System.Collections.Generic;
//using System.Text;
//using Csla;
//namespace VEPROMS.CSLA.Library
//{
// public partial class DocumentEntry
// {
// partial class DocumentEntryExtension : extensionBase
// {
// // CSLATODO: Override automatic defaults
// public virtual DateTime DefaultDTS
// {
// get { return DateTime.Now; }
// }
// public virtual string DefaultUserID
// {
// get { return Environment.UserName.ToUpper(); }
// }
// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules)
// {
// //rules.AllowRead(Dbid, "<Role(s)>");
// }
// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules)
// {
// //rules.AllowInstanceRead(Dbid, "<Role(s)>");
// }
// public new void AddValidationRules(Csla.Validation.ValidationRules rules)
// {
// rules.AddRule(
// Csla.Validation.CommonRules.StringMaxLength,
// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100));
// }
// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules)
// {
// rules.AddInstanceRule(/* Instance Validation Rule */);
// }
// }
// }
//}
@@ -13,8 +13,6 @@ using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
namespace VEPROMS.CSLA.Library namespace VEPROMS.CSLA.Library
@@ -28,14 +26,12 @@ namespace VEPROMS.CSLA.Library
public partial class DocumentInfo : ReadOnlyBase<DocumentInfo>, IDisposable public partial class DocumentInfo : ReadOnlyBase<DocumentInfo>, IDisposable
{ {
public event DocumentInfoEvent Changed; public event DocumentInfoEvent Changed;
private void OnChange() private void OnChange() => Changed?.Invoke(this);
{
if (Changed != null) Changed(this);
}
#region Log4Net #region Log4Net
private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endregion #endregion
#region Collection #region Collection
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static List<DocumentInfo> _CacheList = new List<DocumentInfo>(); private static List<DocumentInfo> _CacheList = new List<DocumentInfo>();
protected static void AddToCache(DocumentInfo documentInfo) protected static void AddToCache(DocumentInfo documentInfo)
{ {
@@ -45,6 +41,7 @@ namespace VEPROMS.CSLA.Library
{ {
while (_CacheList.Contains(documentInfo)) _CacheList.Remove(documentInfo); // In RemoveFromCache while (_CacheList.Contains(documentInfo)) _CacheList.Remove(documentInfo); // In RemoveFromCache
} }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static Dictionary<string, List<DocumentInfo>> _CacheByPrimaryKey = new Dictionary<string, List<DocumentInfo>>(); private static Dictionary<string, List<DocumentInfo>> _CacheByPrimaryKey = new Dictionary<string, List<DocumentInfo>>();
private static void ConvertListToDictionary() private static void ConvertListToDictionary()
{ {
@@ -74,21 +71,8 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
#region Business Methods #region Business Methods
private string _ErrorMessage = string.Empty; private string _ErrorMessage = string.Empty;
public string ErrorMessage public string ErrorMessage => _ErrorMessage;
{
get { return _ErrorMessage; }
}
protected Document _Editable; protected Document _Editable;
private IVEHasBrokenRules HasBrokenRules
{
get
{
IVEHasBrokenRules hasBrokenRules = null;
if (_Editable != null)
hasBrokenRules = _Editable.HasBrokenRules;
return hasBrokenRules;
}
}
private int _DocID; private int _DocID;
[System.ComponentModel.DataObjectField(true, true)] [System.ComponentModel.DataObjectField(true, true)]
public int DocID public int DocID
@@ -276,32 +260,19 @@ namespace VEPROMS.CSLA.Library
foreach (DocumentInfo tmp in _CacheByPrimaryKey[_DocID.ToString()]) foreach (DocumentInfo tmp in _CacheByPrimaryKey[_DocID.ToString()])
tmp._DocumentPdfCount = -1; // This will cause the data to be requeried tmp._DocumentPdfCount = -1; // This will cause the data to be requeried
} }
// CSLATODO: Replace base DocumentInfo.ToString function as necessary
/// <summary>
/// Overrides Base ToString
/// </summary>
/// <returns>A string representation of current DocumentInfo</returns>
//public override string ToString()
//{
// return base.ToString();
//}
// CSLATODO: Check DocumentInfo.GetIdValue to assure that the ID returned is unique // CSLATODO: Check DocumentInfo.GetIdValue to assure that the ID returned is unique
/// <summary> /// <summary>
/// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// Overrides Base GetIdValue - Used internally by CSLA to determine equality
/// </summary> /// </summary>
/// <returns>A Unique ID for the current DocumentInfo</returns> /// <returns>A Unique ID for the current DocumentInfo</returns>
protected override object GetIdValue() protected override object GetIdValue() => MyDocumentInfoUnique; // Absolutely Unique ID
{
return MyDocumentInfoUnique; // Absolutely Unique ID
}
#endregion #endregion
#region Factory Methods #region Factory Methods
private static int _DocumentInfoUnique = 0; private static int _DocumentInfoUnique = 0;
private static int DocumentInfoUnique private static int DocumentInfoUnique => ++_DocumentInfoUnique;
{ get { return ++_DocumentInfoUnique; } } private readonly int _MyDocumentInfoUnique = DocumentInfoUnique;
private int _MyDocumentInfoUnique = DocumentInfoUnique; // Absolutely Unique ID - Info
public int MyDocumentInfoUnique // Absolutely Unique ID - Info public int MyDocumentInfoUnique => _MyDocumentInfoUnique;
{ get { return _MyDocumentInfoUnique; } }
protected DocumentInfo() protected DocumentInfo()
{/* require use of factory methods */ {/* require use of factory methods */
AddToCache(this); AddToCache(this);
@@ -310,15 +281,11 @@ namespace VEPROMS.CSLA.Library
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~DocumentInfo() ~DocumentInfo()
{ {
_CountFinalized++; _CountFinalized++;
@@ -335,10 +302,7 @@ namespace VEPROMS.CSLA.Library
if (listDocumentInfo.Count == 0) // If there are no items left in the list if (listDocumentInfo.Count == 0) // If there are no items left in the list
_CacheByPrimaryKey.Remove(DocID.ToString()); // remove the list _CacheByPrimaryKey.Remove(DocID.ToString()); // remove the list
} }
public virtual Document Get() public virtual Document Get() => _Editable = Document.Get(_DocID);
{
return _Editable = Document.Get(_DocID);
}
public static void Refresh(Document tmp) public static void Refresh(Document tmp)
{ {
string key = tmp.DocID.ToString(); string key = tmp.DocID.ToString();
@@ -361,8 +325,6 @@ namespace VEPROMS.CSLA.Library
} }
public static DocumentInfo Get(int docID) public static DocumentInfo Get(int docID)
{ {
//if (!CanGetObject())
// throw new System.Security.SecurityException("User not authorized to view a Document");
try try
{ {
DocumentInfo tmp = GetCachedByPrimaryKey(docID); DocumentInfo tmp = GetCachedByPrimaryKey(docID);
@@ -401,13 +363,9 @@ namespace VEPROMS.CSLA.Library
[Serializable()] [Serializable()]
protected class PKCriteria protected class PKCriteria
{ {
private int _DocID; private readonly int _DocID;
public int DocID public int DocID => _DocID;
{ get { return _DocID; } } public PKCriteria(int docID) => _DocID = docID;
public PKCriteria(int docID)
{
_DocID = docID;
}
} }
private void ReadData(SafeDataReader dr) private void ReadData(SafeDataReader dr)
{ {
@@ -472,7 +430,7 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
// Standard Refresh // Standard Refresh
#region extension #region extension
DocumentInfoExtension _DocumentInfoExtension = new DocumentInfoExtension(); readonly DocumentInfoExtension _DocumentInfoExtension = new DocumentInfoExtension();
[Serializable()] [Serializable()]
partial class DocumentInfoExtension : extensionBase { } partial class DocumentInfoExtension : extensionBase { }
[Serializable()] [Serializable()]
@@ -488,10 +446,10 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is DocumentInfo) if (destType == typeof(string) && value is DocumentInfo info)
{ {
// Return the ToString value // Return the ToString value
return ((DocumentInfo)value).ToString(); return info.ToString();
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
@@ -13,8 +13,6 @@ using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
namespace VEPROMS.CSLA.Library namespace VEPROMS.CSLA.Library
@@ -28,11 +26,10 @@ namespace VEPROMS.CSLA.Library
{ {
#region Log4Net #region Log4Net
private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endregion #endregion
#region Business Methods #region Business Methods
internal new IList<DocumentInfo> Items internal new IList<DocumentInfo> Items => base.Items;
{ get { return base.Items; } } public void AddEvents()
public void AddEvents()
{ {
foreach (DocumentInfo tmp in this) foreach (DocumentInfo tmp in this)
{ {
@@ -44,23 +41,19 @@ namespace VEPROMS.CSLA.Library
for (int i = 0; i < Count; i++) for (int i = 0; i < Count; i++)
{ {
if (base[i] == sender) if (base[i] == sender)
this.OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, i)); OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, i));
} }
} }
private bool _Disposed = false; private bool _Disposed = false;
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed ~DocumentInfoList()
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~DocumentInfoList()
{ {
_CountFinalized++; _CountFinalized++;
} }
@@ -97,32 +90,17 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Error on DocumentInfoList.Get", ex); throw new DbCslaException("Error on DocumentInfoList.Get", ex);
} }
} }
/// <summary> /// <summary>
/// Reset the list of all DocumentInfo. /// Reset the list of all DocumentInfo.
/// </summary> /// </summary>
public static void Reset() public static void Reset() => _DocumentInfoList = null;
{ private DocumentInfoList()
_DocumentInfoList = null;
}
// CSLATODO: Add alternative gets -
//public static DocumentInfoList Get(<criteria>)
//{
// try
// {
// return DataPortal.Fetch<DocumentInfoList>(new FilteredCriteria(<criteria>));
// }
// catch (Exception ex)
// {
// throw new DbCslaException("Error on DocumentInfoList.Get", ex);
// }
//}
private DocumentInfoList()
{ /* require use of factory methods */ } { /* require use of factory methods */ }
#endregion #endregion
#region Data Access Portal #region Data Access Portal
private void DataPortal_Fetch() private void DataPortal_Fetch()
{ {
this.RaiseListChangedEvents = false; RaiseListChangedEvents = false;
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocumentInfoList.DataPortal_Fetch", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocumentInfoList.DataPortal_Fetch", GetHashCode());
try try
{ {
@@ -136,7 +114,7 @@ namespace VEPROMS.CSLA.Library
using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
{ {
IsReadOnly = false; IsReadOnly = false;
while (dr.Read()) this.Add(new DocumentInfo(dr)); while (dr.Read()) Add(new DocumentInfo(dr));
IsReadOnly = true; IsReadOnly = true;
} }
} }
@@ -147,48 +125,37 @@ namespace VEPROMS.CSLA.Library
if (_MyLog.IsErrorEnabled) _MyLog.Error("DocumentInfoList.DataPortal_Fetch", ex); if (_MyLog.IsErrorEnabled) _MyLog.Error("DocumentInfoList.DataPortal_Fetch", ex);
throw new DbCslaException("DocumentInfoList.DataPortal_Fetch", ex); throw new DbCslaException("DocumentInfoList.DataPortal_Fetch", ex);
} }
this.RaiseListChangedEvents = true; RaiseListChangedEvents = true;
} }
#endregion #endregion
#region ICustomTypeDescriptor impl #region ICustomTypeDescriptor impl
public String GetClassName() public String GetClassName() => TypeDescriptor.GetClassName(this, true);
{ return TypeDescriptor.GetClassName(this, true); } public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true);
public AttributeCollection GetAttributes() public String GetComponentName() => TypeDescriptor.GetComponentName(this, true);
{ return TypeDescriptor.GetAttributes(this, true); } public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true);
public String GetComponentName() public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true);
{ return TypeDescriptor.GetComponentName(this, true); } public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true);
public TypeConverter GetConverter() public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true);
{ return TypeDescriptor.GetConverter(this, true); } public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true);
public EventDescriptor GetDefaultEvent() public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true);
{ return TypeDescriptor.GetDefaultEvent(this, true); } public object GetPropertyOwner(PropertyDescriptor pd) => this;
public PropertyDescriptor GetDefaultProperty() /// <summary>
{ return TypeDescriptor.GetDefaultProperty(this, true); } /// Called to get the properties of this type. Returns properties with certain
public object GetEditor(Type editorBaseType) /// attributes. this restriction is not implemented here.
{ return TypeDescriptor.GetEditor(this, editorBaseType, true); } /// </summary>
public EventDescriptorCollection GetEvents(Attribute[] attributes) /// <param name="attributes"></param>
{ return TypeDescriptor.GetEvents(this, attributes, true); } /// <returns></returns>
public EventDescriptorCollection GetEvents() public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties();
{ return TypeDescriptor.GetEvents(this, true); } /// <summary>
public object GetPropertyOwner(PropertyDescriptor pd) /// Called to get the properties of this type.
{ return this; } /// </summary>
/// <summary> /// <returns></returns>
/// Called to get the properties of this type. Returns properties with certain public PropertyDescriptorCollection GetProperties()
/// attributes. this restriction is not implemented here.
/// </summary>
/// <param name="attributes"></param>
/// <returns></returns>
public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{ return GetProperties(); }
/// <summary>
/// Called to get the properties of this type.
/// </summary>
/// <returns></returns>
public PropertyDescriptorCollection GetProperties()
{ {
// Create a collection object to hold property descriptors // Create a collection object to hold property descriptors
PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null);
// Iterate the list // Iterate the list
for (int i = 0; i < this.Items.Count; i++) for (int i = 0; i < Items.Count; i++)
{ {
// Create a property descriptor for the item and add to the property descriptor collection // Create a property descriptor for the item and add to the property descriptor collection
DocumentInfoListPropertyDescriptor pd = new DocumentInfoListPropertyDescriptor(this, i); DocumentInfoListPropertyDescriptor pd = new DocumentInfoListPropertyDescriptor(this, i);
@@ -205,7 +172,6 @@ namespace VEPROMS.CSLA.Library
/// </summary> /// </summary>
public partial class DocumentInfoListPropertyDescriptor : vlnListPropertyDescriptor public partial class DocumentInfoListPropertyDescriptor : vlnListPropertyDescriptor
{ {
private DocumentInfo Item { get { return (DocumentInfo)_Item; } }
public DocumentInfoListPropertyDescriptor(DocumentInfoList collection, int index) : base(collection, index) { ;} public DocumentInfoListPropertyDescriptor(DocumentInfoList collection, int index) : base(collection, index) { ;}
} }
#endregion #endregion
@@ -214,10 +180,10 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is DocumentInfoList) if (destType == typeof(string) && value is DocumentInfoList list)
{ {
// Return department and department role separated by comma. // Return department and department role separated by comma.
return ((DocumentInfoList)value).Items.Count.ToString() + " Documents"; return $"{list.Items.Count} Documents";
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
@@ -9,12 +9,9 @@
// ======================================================================== // ========================================================================
using System; using System;
using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
using Csla.Validation; using Csla.Validation;
@@ -31,11 +28,8 @@ namespace VEPROMS.CSLA.Library
private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endregion #endregion
#region Business Methods #region Business Methods
private string _ErrorMessage = string.Empty; private readonly string _ErrorMessage = string.Empty;
public string ErrorMessage public string ErrorMessage => _ErrorMessage;
{
get { return _ErrorMessage; }
}
private int _DebugStatus; private int _DebugStatus;
/// <summary> /// <summary>
/// > 0 for Debug /// > 0 for Debug
@@ -171,35 +165,13 @@ namespace VEPROMS.CSLA.Library
/// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// Overrides Base GetIdValue - Used internally by CSLA to determine equality
/// </summary> /// </summary>
/// <returns>A Unique ID for the current DocumentPdf</returns> /// <returns>A Unique ID for the current DocumentPdf</returns>
protected override object GetIdValue() protected override object GetIdValue() => MyDocumentPdfUnique; // Absolutely Unique ID
{ public override bool IsDirty => base.IsDirty;
return MyDocumentPdfUnique; // Absolutely Unique ID [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")]
} public bool IsDirtyList(List<object> list) => base.IsDirty;
// CSLATODO: Replace base DocumentPdf.ToString function as necessary public override bool IsValid => (IsNew && !IsDirty) || base.IsValid;
/// <summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Keeping until replace CSLA")]
/// Overrides Base ToString public bool IsValidList(List<object> list) => (IsNew && !IsDirty) || base.IsValid;
/// </summary>
/// <returns>A string representation of current DocumentPdf</returns>
//public override string ToString()
//{
// return base.ToString();
//}
public override bool IsDirty
{
get { return base.IsDirty; }
}
public bool IsDirtyList(List<object> list)
{
return base.IsDirty;
}
public override bool IsValid
{
get { return (IsNew && !IsDirty) ? true : base.IsValid; }
}
public bool IsValidList(List<object> list)
{
return (IsNew && !IsDirty) ? true : base.IsValid;
}
#endregion #endregion
#region ValidationRules #region ValidationRules
[NonSerialized] [NonSerialized]
@@ -227,8 +199,8 @@ namespace VEPROMS.CSLA.Library
get get
{ {
IVEHasBrokenRules hasBrokenRules = HasBrokenRules; IVEHasBrokenRules hasBrokenRules = HasBrokenRules;
if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; if (Equals(hasBrokenRules)) return BrokenRulesCollection;
return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); return hasBrokenRules?.BrokenRules;
} }
} }
protected override void AddBusinessRules() protected override void AddBusinessRules()
@@ -240,80 +212,21 @@ namespace VEPROMS.CSLA.Library
new Csla.Validation.CommonRules.MaxLengthRuleArgs("UserID", 100)); new Csla.Validation.CommonRules.MaxLengthRuleArgs("UserID", 100));
// CSLATODO: Add other validation rules // CSLATODO: Add other validation rules
} }
// Sample data comparison validation rule
//private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e)
//{
// if (_started > _ended)
// {
// e.Description = "Start date can't be after end date";
// return false;
// }
// else
// return true;
//}
#endregion #endregion
#region Authorization Rules #region Authorization Rules
protected override void AddAuthorizationRules() protected override void AddAuthorizationRules()
{ {
//CSLATODO: Who can read/write which fields
//AuthorizationRules.AllowRead(DebugStatus, "<Role(s)>");
//AuthorizationRules.AllowRead(TopRow, "<Role(s)>");
//AuthorizationRules.AllowRead(PageLength, "<Role(s)>");
//AuthorizationRules.AllowRead(LeftMargin, "<Role(s)>");
//AuthorizationRules.AllowRead(PageWidth, "<Role(s)>");
//AuthorizationRules.AllowRead(PageCount, "<Role(s)>");
//AuthorizationRules.AllowWrite(PageCount, "<Role(s)>");
//AuthorizationRules.AllowRead(DocPdf, "<Role(s)>");
//AuthorizationRules.AllowWrite(DocPdf, "<Role(s)>");
//AuthorizationRules.AllowRead(DTS, "<Role(s)>");
//AuthorizationRules.AllowWrite(DTS, "<Role(s)>");
//AuthorizationRules.AllowRead(UserID, "<Role(s)>");
//AuthorizationRules.AllowWrite(UserID, "<Role(s)>");
}
public static bool CanAddObject()
{
// CSLATODO: Can Add Authorization
//return Csla.ApplicationContext.User.IsInRole("ProjectManager");
return true;
}
public static bool CanGetObject()
{
// CSLATODO: CanGet Authorization
return true;
}
public static bool CanDeleteObject()
{
// CSLATODO: CanDelete Authorization
//bool result = false;
//if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true;
//if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true;
//return result;
return true;
}
public static bool CanEditObject()
{
// CSLATODO: CanEdit Authorization
//return Csla.ApplicationContext.User.IsInRole("ProjectManager");
return true;
} }
#endregion #endregion
#region Factory Methods #region Factory Methods
public int CurrentEditLevel public int CurrentEditLevel => EditLevel;
{ get { return EditLevel; } }
private static int _DocumentPdfUnique = 0; private static int _DocumentPdfUnique = 0;
private static int DocumentPdfUnique private static int DocumentPdfUnique => ++_DocumentPdfUnique;
{ get { return ++_DocumentPdfUnique; } } private readonly int _MyDocumentPdfUnique = DocumentPdfUnique;
private int _MyDocumentPdfUnique = DocumentPdfUnique; // Absolutely Unique ID - Editable FK
public int MyDocumentPdfUnique // Absolutely Unique ID - Editable FK public int MyDocumentPdfUnique => _MyDocumentPdfUnique;
{ get { return _MyDocumentPdfUnique; } } internal static DocumentPdf New(int debugStatus, int topRow, int pageLength, int leftMargin, int pageWidth, double pageCount) => new DocumentPdf(debugStatus, topRow, pageLength, leftMargin, pageWidth, pageCount);
internal static DocumentPdf New(int debugStatus, int topRow, int pageLength, int leftMargin, int pageWidth, double pageCount) internal static DocumentPdf Get(SafeDataReader dr) => new DocumentPdf(dr);
{
return new DocumentPdf(debugStatus, topRow, pageLength, leftMargin, pageWidth, pageCount);
}
internal static DocumentPdf Get(SafeDataReader dr)
{
return new DocumentPdf(dr);
}
public DocumentPdf() public DocumentPdf()
{ {
MarkAsChild(); MarkAsChild();
@@ -345,15 +258,11 @@ namespace VEPROMS.CSLA.Library
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~DocumentPdf() ~DocumentPdf()
{ {
_CountFinalized++; _CountFinalized++;
@@ -392,33 +301,45 @@ namespace VEPROMS.CSLA.Library
internal void Insert(Document myDocument) internal void Insert(Document myDocument)
{ {
// if we're not dirty then don't update the database // if we're not dirty then don't update the database
if (!this.IsDirty) return; if (!IsDirty) return;
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = Database.VEPROMS_SqlConnection)
_LastChanged = Pdf.Add(cn, myDocument, _DebugStatus, _TopRow, _PageLength, _LeftMargin, _PageWidth, _PageCount, _DocPdf, _DTS, _UserID); {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
_LastChanged = Pdf.Add(cn, myDocument, _DebugStatus, _TopRow, _PageLength, _LeftMargin, _PageWidth, _PageCount, _DocPdf, _DTS, _UserID);
}
MarkOld(); MarkOld();
} }
internal void Update(Document myDocument) internal void Update(Document myDocument)
{ {
// if we're not dirty then don't update the database // if we're not dirty then don't update the database
if (!this.IsDirty) return; if (!IsDirty) return;
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = Database.VEPROMS_SqlConnection)
_LastChanged = Pdf.Update(cn, myDocument.DocID, _DebugStatus, _TopRow, _PageLength, _LeftMargin, _PageWidth, _PageCount, _DocPdf, _DTS, _UserID, ref _LastChanged); {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
_LastChanged = Pdf.Update(cn, myDocument.DocID, _DebugStatus, _TopRow, _PageLength, _LeftMargin, _PageWidth, _PageCount, _DocPdf, _DTS, _UserID, ref _LastChanged);
}
MarkOld(); MarkOld();
} }
internal void DeleteSelf(Document myDocument) internal void DeleteSelf(Document myDocument)
{ {
// if we're not dirty then don't update the database // if we're not dirty then don't update the database
if (!this.IsDirty) return; if (!IsDirty) return;
// if we're new then don't update the database // if we're new then don't update the database
if (this.IsNew) return; if (IsNew) return;
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = Database.VEPROMS_SqlConnection)
Pdf.Remove(cn, myDocument.DocID, _DebugStatus, _TopRow, _PageLength, _LeftMargin, _PageWidth); {
if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
Pdf.Remove(cn, myDocument.DocID, _DebugStatus, _TopRow, _PageLength, _LeftMargin, _PageWidth);
}
MarkNew(); MarkNew();
} }
#endregion #endregion
// Standard Default Code // Standard Default Code
#region extension #region extension
DocumentPdfExtension _DocumentPdfExtension = new DocumentPdfExtension(); readonly DocumentPdfExtension _DocumentPdfExtension = new DocumentPdfExtension();
[Serializable()] [Serializable()]
partial class DocumentPdfExtension : extensionBase partial class DocumentPdfExtension : extensionBase
{ {
@@ -427,14 +348,8 @@ namespace VEPROMS.CSLA.Library
class extensionBase class extensionBase
{ {
// Default Values // Default Values
public virtual DateTime DefaultDTS public virtual DateTime DefaultDTS => DateTime.Now;
{ public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID;
get { return DateTime.Now; }
}
public virtual string DefaultUserID
{
get { return Volian.Base.Library.VlnSettings.UserID; }
}
// Authorization Rules // Authorization Rules
public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules)
{ {
@@ -463,57 +378,13 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is DocumentPdf) if (destType == typeof(string) && value is DocumentPdf docpdf)
{ {
// Return the ToString value // Return the ToString value
return ((DocumentPdf)value).ToString(); return docpdf.ToString();
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
} }
#endregion #endregion
} // Namespace } // Namespace
//// The following is a sample Extension File. You can use it to create DocumentPdfExt.cs
//using System;
//using System.Collections.Generic;
//using System.Text;
//using Csla;
//namespace VEPROMS.CSLA.Library
//{
// public partial class DocumentPdf
// {
// partial class DocumentPdfExtension : extensionBase
// {
// // CSLATODO: Override automatic defaults
// public virtual DateTime DefaultDTS
// {
// get { return DateTime.Now; }
// }
// public virtual string DefaultUserID
// {
// get { return Environment.UserName.ToUpper(); }
// }
// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules)
// {
// //rules.AllowRead(Dbid, "<Role(s)>");
// }
// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules)
// {
// //rules.AllowInstanceRead(Dbid, "<Role(s)>");
// }
// public new void AddValidationRules(Csla.Validation.ValidationRules rules)
// {
// rules.AddRule(
// Csla.Validation.CommonRules.StringMaxLength,
// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100));
// }
// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules)
// {
// rules.AddInstanceRule(/* Instance Validation Rule */);
// }
// }
// }
//}
@@ -13,8 +13,6 @@ using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
using Csla.Validation; using Csla.Validation;
@@ -31,13 +29,10 @@ namespace VEPROMS.CSLA.Library
private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endregion #endregion
#region Business Methods #region Business Methods
private string _ErrorMessage = string.Empty; private readonly string _ErrorMessage = string.Empty;
public string ErrorMessage public string ErrorMessage => _ErrorMessage;
{ // One To Many
get { return _ErrorMessage; } public DocumentPdf this[int debugStatus, int topRow, int pageLength, int leftMargin, int pageWidth]
}
// One To Many
public DocumentPdf this[int debugStatus, int topRow, int pageLength, int leftMargin, int pageWidth]
{ {
get get
{ {
@@ -47,11 +42,8 @@ namespace VEPROMS.CSLA.Library
return null; return null;
} }
} }
public new System.Collections.Generic.IList<DocumentPdf> Items public new System.Collections.Generic.IList<DocumentPdf> Items => base.Items;
{ public DocumentPdf GetItem(int debugStatus, int topRow, int pageLength, int leftMargin, int pageWidth)
get { return base.Items; }
}
public DocumentPdf GetItem(int debugStatus, int topRow, int pageLength, int leftMargin, int pageWidth)
{ {
foreach (DocumentPdf pdf in this) foreach (DocumentPdf pdf in this)
if (pdf.DebugStatus == debugStatus && pdf.TopRow == topRow && pdf.PageLength == pageLength && pdf.LeftMargin == leftMargin && pdf.PageWidth == pageWidth) if (pdf.DebugStatus == debugStatus && pdf.TopRow == topRow && pdf.PageLength == pageLength && pdf.LeftMargin == leftMargin && pdf.PageWidth == pageWidth)
@@ -63,7 +55,7 @@ namespace VEPROMS.CSLA.Library
if (!Contains(debugStatus, topRow, pageLength, leftMargin, pageWidth)) if (!Contains(debugStatus, topRow, pageLength, leftMargin, pageWidth))
{ {
DocumentPdf pdf = DocumentPdf.New(debugStatus, topRow, pageLength, leftMargin, pageWidth, pageCount); DocumentPdf pdf = DocumentPdf.New(debugStatus, topRow, pageLength, leftMargin, pageWidth, pageCount);
this.Add(pdf); Add(pdf);
return pdf; return pdf;
} }
else else
@@ -108,23 +100,20 @@ namespace VEPROMS.CSLA.Library
return true; return true;
return false; return false;
} }
public override bool IsValid public override bool IsValid => IsValidList(new List<object>());
public bool IsValidList(List<object> list)
{ {
get { return IsValidList(new List<object>()); } // run through all the child objects
} // and if any are invalid then the
public bool IsValidList(List<object> list) // collection is invalid
{ foreach (DocumentPdf child in this)
// run through all the child objects if (!child.IsValidList(list))
// and if any are invalid then the {
// collection is invalid //Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString());
foreach (DocumentPdf child in this) return false;
if (!child.IsValidList(list)) }
{ return true;
//Console.WriteLine("Valid {0} Child {1} - {2}", child.IsValid, child.GetType().Name,child.ToString()); }
return false;
}
return true;
}
#endregion #endregion
#region ValidationRules #region ValidationRules
public IVEHasBrokenRules HasBrokenRules public IVEHasBrokenRules HasBrokenRules
@@ -142,20 +131,14 @@ namespace VEPROMS.CSLA.Library
get get
{ {
IVEHasBrokenRules hasBrokenRules = HasBrokenRules; IVEHasBrokenRules hasBrokenRules = HasBrokenRules;
return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); return hasBrokenRules?.BrokenRules;
} }
} }
#endregion #endregion
#region Factory Methods #region Factory Methods
internal static DocumentPdfs New() internal static DocumentPdfs New() => new DocumentPdfs();
{ internal static DocumentPdfs Get(SafeDataReader dr) => new DocumentPdfs(dr);
return new DocumentPdfs(); public static DocumentPdfs GetByDocID(int docID)
}
internal static DocumentPdfs Get(SafeDataReader dr)
{
return new DocumentPdfs(dr);
}
public static DocumentPdfs GetByDocID(int docID)
{ {
try try
{ {
@@ -166,11 +149,8 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Error on DocumentPdfs.GetByDocID", ex); throw new DbCslaException("Error on DocumentPdfs.GetByDocID", ex);
} }
} }
private DocumentPdfs() private DocumentPdfs() => MarkAsChild();
{ internal DocumentPdfs(SafeDataReader dr)
MarkAsChild();
}
internal DocumentPdfs(SafeDataReader dr)
{ {
MarkAsChild(); MarkAsChild();
Fetch(dr); Fetch(dr);
@@ -179,16 +159,12 @@ namespace VEPROMS.CSLA.Library
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed ~DocumentPdfs()
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~DocumentPdfs()
{ {
_CountFinalized++; _CountFinalized++;
} }
@@ -203,19 +179,16 @@ namespace VEPROMS.CSLA.Library
// called to load data from the database // called to load data from the database
private void Fetch(SafeDataReader dr) private void Fetch(SafeDataReader dr)
{ {
this.RaiseListChangedEvents = false; RaiseListChangedEvents = false;
while (dr.Read()) while (dr.Read())
this.Add(DocumentPdf.Get(dr)); Add(DocumentPdf.Get(dr));
this.RaiseListChangedEvents = true; RaiseListChangedEvents = true;
} }
[Serializable()] [Serializable()]
private class DocIDCriteria private class DocIDCriteria
{ {
public DocIDCriteria(int docID) public DocIDCriteria(int docID) => _DocID = docID;
{ private int _DocID;
_DocID = docID;
}
private int _DocID;
public int DocID public int DocID
{ {
get { return _DocID; } get { return _DocID; }
@@ -224,7 +197,7 @@ namespace VEPROMS.CSLA.Library
} }
private void DataPortal_Fetch(DocIDCriteria criteria) private void DataPortal_Fetch(DocIDCriteria criteria)
{ {
this.RaiseListChangedEvents = false; RaiseListChangedEvents = false;
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocumentPdfs.DataPortal_FetchDocID", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] DocumentPdfs.DataPortal_FetchDocID", GetHashCode());
try try
{ {
@@ -238,7 +211,7 @@ namespace VEPROMS.CSLA.Library
cm.CommandTimeout = Database.DefaultTimeout; cm.CommandTimeout = Database.DefaultTimeout;
using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
{ {
while (dr.Read()) this.Add(new DocumentPdf(dr)); while (dr.Read()) Add(new DocumentPdf(dr));
} }
} }
} }
@@ -248,11 +221,11 @@ namespace VEPROMS.CSLA.Library
if (_MyLog.IsErrorEnabled) _MyLog.Error("DocumentPdfs.DataPortal_FetchDocID", ex); if (_MyLog.IsErrorEnabled) _MyLog.Error("DocumentPdfs.DataPortal_FetchDocID", ex);
throw new DbCslaException("DocumentPdfs.DataPortal_Fetch", ex); throw new DbCslaException("DocumentPdfs.DataPortal_Fetch", ex);
} }
this.RaiseListChangedEvents = true; RaiseListChangedEvents = true;
} }
internal void Update(Document document) internal void Update(Document document)
{ {
this.RaiseListChangedEvents = false; RaiseListChangedEvents = false;
try try
{ {
// update (thus deleting) any deleted child objects // update (thus deleting) any deleted child objects
@@ -271,49 +244,38 @@ namespace VEPROMS.CSLA.Library
} }
finally finally
{ {
this.RaiseListChangedEvents = true; RaiseListChangedEvents = true;
} }
} }
#endregion #endregion
#region ICustomTypeDescriptor impl #region ICustomTypeDescriptor impl
public String GetClassName() public String GetClassName() => TypeDescriptor.GetClassName(this, true);
{ return TypeDescriptor.GetClassName(this, true); } public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true);
public AttributeCollection GetAttributes() public String GetComponentName() => TypeDescriptor.GetComponentName(this, true);
{ return TypeDescriptor.GetAttributes(this, true); } public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true);
public String GetComponentName() public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true);
{ return TypeDescriptor.GetComponentName(this, true); } public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true);
public TypeConverter GetConverter() public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true);
{ return TypeDescriptor.GetConverter(this, true); } public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true);
public EventDescriptor GetDefaultEvent() public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true);
{ return TypeDescriptor.GetDefaultEvent(this, true); } public object GetPropertyOwner(PropertyDescriptor pd) => this;
public PropertyDescriptor GetDefaultProperty() /// <summary>
{ return TypeDescriptor.GetDefaultProperty(this, true); } /// Called to get the properties of this type. Returns properties with certain
public object GetEditor(Type editorBaseType) /// attributes. this restriction is not implemented here.
{ return TypeDescriptor.GetEditor(this, editorBaseType, true); } /// </summary>
public EventDescriptorCollection GetEvents(Attribute[] attributes) /// <param name="attributes"></param>
{ return TypeDescriptor.GetEvents(this, attributes, true); } /// <returns></returns>
public EventDescriptorCollection GetEvents() public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties();
{ return TypeDescriptor.GetEvents(this, true); } /// <summary>
public object GetPropertyOwner(PropertyDescriptor pd) /// Called to get the properties of this type.
{ return this; } /// </summary>
/// <summary> /// <returns></returns>
/// Called to get the properties of this type. Returns properties with certain public PropertyDescriptorCollection GetProperties()
/// attributes. this restriction is not implemented here.
/// </summary>
/// <param name="attributes"></param>
/// <returns></returns>
public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{ return GetProperties(); }
/// <summary>
/// Called to get the properties of this type.
/// </summary>
/// <returns></returns>
public PropertyDescriptorCollection GetProperties()
{ {
// Create a collection object to hold property descriptors // Create a collection object to hold property descriptors
PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null);
// Iterate the list // Iterate the list
for (int i = 0; i < this.Items.Count; i++) for (int i = 0; i < Items.Count; i++)
{ {
// Create a property descriptor for the item and add to the property descriptor collection // Create a property descriptor for the item and add to the property descriptor collection
DocumentPdfsPropertyDescriptor pd = new DocumentPdfsPropertyDescriptor(this, i); DocumentPdfsPropertyDescriptor pd = new DocumentPdfsPropertyDescriptor(this, i);
@@ -330,7 +292,6 @@ namespace VEPROMS.CSLA.Library
/// </summary> /// </summary>
public partial class DocumentPdfsPropertyDescriptor : vlnListPropertyDescriptor public partial class DocumentPdfsPropertyDescriptor : vlnListPropertyDescriptor
{ {
private DocumentPdf Item { get { return (DocumentPdf)_Item; } }
public DocumentPdfsPropertyDescriptor(DocumentPdfs collection, int index) : base(collection, index) { ;} public DocumentPdfsPropertyDescriptor(DocumentPdfs collection, int index) : base(collection, index) { ;}
} }
#endregion #endregion
@@ -339,10 +300,10 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is DocumentPdfs) if (destType == typeof(string) && value is DocumentPdfs pdfs)
{ {
// Return department and department role separated by comma. // Return department and department role separated by comma.
return ((DocumentPdfs)value).Items.Count.ToString() + " Pdfs"; return $"{pdfs.Items.Count} Pdfs";
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
+113 -236
View File
@@ -13,8 +13,6 @@ using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
using Csla.Validation; using Csla.Validation;
@@ -57,6 +55,7 @@ namespace VEPROMS.CSLA.Library
} }
#endregion #endregion
#region Collection #region Collection
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static List<Entry> _CacheList = new List<Entry>(); private static List<Entry> _CacheList = new List<Entry>();
protected static void AddToCache(Entry entry) protected static void AddToCache(Entry entry)
{ {
@@ -66,6 +65,7 @@ namespace VEPROMS.CSLA.Library
{ {
while (_CacheList.Contains(entry)) _CacheList.Remove(entry); // In RemoveFromCache while (_CacheList.Contains(entry)) _CacheList.Remove(entry); // In RemoveFromCache
} }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static Dictionary<string, List<Entry>> _CacheByPrimaryKey = new Dictionary<string, List<Entry>>(); private static Dictionary<string, List<Entry>> _CacheByPrimaryKey = new Dictionary<string, List<Entry>>();
private static void ConvertListToDictionary() private static void ConvertListToDictionary()
{ {
@@ -91,10 +91,7 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
#region Business Methods #region Business Methods
private string _ErrorMessage = string.Empty; private string _ErrorMessage = string.Empty;
public string ErrorMessage public string ErrorMessage => _ErrorMessage;
{
get { return _ErrorMessage; }
}
private int _ContentID; private int _ContentID;
[System.ComponentModel.DataObjectField(true, true)] [System.ComponentModel.DataObjectField(true, true)]
public int ContentID public int ContentID
@@ -199,7 +196,7 @@ namespace VEPROMS.CSLA.Library
if (base.IsDirty || list.Contains(this)) if (base.IsDirty || list.Contains(this))
return base.IsDirty; return base.IsDirty;
list.Add(this); list.Add(this);
return base.IsDirty || (_MyDocument == null ? false : _MyDocument.IsDirtyList(list)); return base.IsDirty || (_MyDocument != null && _MyDocument.IsDirtyList(list));
} }
public override bool IsValid public override bool IsValid
{ {
@@ -208,28 +205,16 @@ namespace VEPROMS.CSLA.Library
public bool IsValidList(List<object> list) public bool IsValidList(List<object> list)
{ {
if (list.Contains(this)) if (list.Contains(this))
return (IsNew && !IsDirty) ? true : base.IsValid; return (IsNew && !IsDirty) || base.IsValid;
list.Add(this); list.Add(this);
return ((IsNew && !IsDirty) ? true : base.IsValid) && (_MyDocument == null ? true : _MyDocument.IsValidList(list)); return ((IsNew && !IsDirty) || base.IsValid) && (_MyDocument == null || _MyDocument.IsValidList(list));
} }
// CSLATODO: Replace base Entry.ToString function as necessary
/// <summary>
/// Overrides Base ToString
/// </summary>
/// <returns>A string representation of current Entry</returns>
//public override string ToString()
//{
// return base.ToString();
//}
// CSLATODO: Check Entry.GetIdValue to assure that the ID returned is unique // CSLATODO: Check Entry.GetIdValue to assure that the ID returned is unique
/// <summary> /// <summary>
/// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// Overrides Base GetIdValue - Used internally by CSLA to determine equality
/// </summary> /// </summary>
/// <returns>A Unique ID for the current Entry</returns> /// <returns>A Unique ID for the current Entry</returns>
protected override object GetIdValue() protected override object GetIdValue() => MyEntryUnique; // Absolutely Unique ID
{
return MyEntryUnique; // Absolutely Unique ID
}
#endregion #endregion
#region ValidationRules #region ValidationRules
[NonSerialized] [NonSerialized]
@@ -258,8 +243,8 @@ namespace VEPROMS.CSLA.Library
get get
{ {
IVEHasBrokenRules hasBrokenRules = HasBrokenRules; IVEHasBrokenRules hasBrokenRules = HasBrokenRules;
if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; if (Equals(hasBrokenRules)) return BrokenRulesCollection;
return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); return hasBrokenRules?.BrokenRules;
} }
} }
protected override void AddBusinessRules() protected override void AddBusinessRules()
@@ -288,29 +273,11 @@ namespace VEPROMS.CSLA.Library
} }
return true; return true;
} }
// Sample data comparison validation rule
//private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e)
//{
// if (_started > _ended)
// {
// e.Description = "Start date can't be after end date";
// return false;
// }
// else
// return true;
//}
#endregion #endregion
#region Authorization Rules #region Authorization Rules
protected override void AddAuthorizationRules() protected override void AddAuthorizationRules()
{ {
//CSLATODO: Who can read/write which fields //CSLATODO: Who can read/write which fields
//AuthorizationRules.AllowRead(ContentID, "<Role(s)>");
//AuthorizationRules.AllowRead(DocID, "<Role(s)>");
//AuthorizationRules.AllowRead(DTS, "<Role(s)>");
//AuthorizationRules.AllowRead(UserID, "<Role(s)>");
//AuthorizationRules.AllowWrite(DocID, "<Role(s)>");
//AuthorizationRules.AllowWrite(DTS, "<Role(s)>");
//AuthorizationRules.AllowWrite(UserID, "<Role(s)>");
_EntryExtension.AddAuthorizationRules(AuthorizationRules); _EntryExtension.AddAuthorizationRules(AuthorizationRules);
} }
protected override void AddInstanceAuthorizationRules() protected override void AddInstanceAuthorizationRules()
@@ -318,42 +285,14 @@ namespace VEPROMS.CSLA.Library
//CSLATODO: Who can read/write which fields //CSLATODO: Who can read/write which fields
_EntryExtension.AddInstanceAuthorizationRules(AuthorizationRules); _EntryExtension.AddInstanceAuthorizationRules(AuthorizationRules);
} }
public static bool CanAddObject()
{
// CSLATODO: Can Add Authorization
//return Csla.ApplicationContext.User.IsInRole("ProjectManager");
return true;
}
public static bool CanGetObject()
{
// CSLATODO: CanGet Authorization
return true;
}
public static bool CanDeleteObject()
{
// CSLATODO: CanDelete Authorization
//bool result = false;
//if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true;
//if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true;
//return result;
return true;
}
public static bool CanEditObject()
{
// CSLATODO: CanEdit Authorization
//return Csla.ApplicationContext.User.IsInRole("ProjectManager");
return true;
}
#endregion #endregion
#region Factory Methods #region Factory Methods
public int CurrentEditLevel public int CurrentEditLevel => EditLevel;
{ get { return EditLevel; } }
private static int _EntryUnique = 0; private static int _EntryUnique = 0;
protected static int EntryUnique protected static int EntryUnique => ++_EntryUnique;
{ get { return ++_EntryUnique; } } private readonly int _MyEntryUnique = EntryUnique;
private int _MyEntryUnique = EntryUnique; // Absolutely Unique ID - Editable
public int MyEntryUnique // Absolutely Unique ID - Editable public int MyEntryUnique => _MyEntryUnique;
{ get { return _MyEntryUnique; } }
protected Entry() protected Entry()
{/* require use of factory methods */ {/* require use of factory methods */
AddToCache(this); AddToCache(this);
@@ -362,15 +301,11 @@ namespace VEPROMS.CSLA.Library
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~Entry() ~Entry()
{ {
_CountFinalized++; _CountFinalized++;
@@ -395,8 +330,6 @@ namespace VEPROMS.CSLA.Library
} }
public static Entry New() public static Entry New()
{ {
if (!CanAddObject())
throw new System.Security.SecurityException("User not authorized to add a Entry");
try try
{ {
return DataPortal.Create<Entry>(); return DataPortal.Create<Entry>();
@@ -464,8 +397,6 @@ namespace VEPROMS.CSLA.Library
} }
public static Entry Get(int contentID) public static Entry Get(int contentID)
{ {
if (!CanGetObject())
throw new System.Security.SecurityException("User not authorized to view a Entry");
try try
{ {
Entry tmp = GetCachedByPrimaryKey(contentID); Entry tmp = GetCachedByPrimaryKey(contentID);
@@ -491,14 +422,9 @@ namespace VEPROMS.CSLA.Library
if (dr.Read()) return new Entry(dr); if (dr.Read()) return new Entry(dr);
return null; return null;
} }
internal Entry(SafeDataReader dr) internal Entry(SafeDataReader dr) => ReadData(dr);
{
ReadData(dr);
}
public static void Delete(int contentID) public static void Delete(int contentID)
{ {
if (!CanDeleteObject())
throw new System.Security.SecurityException("User not authorized to remove a Entry");
try try
{ {
DataPortal.Delete(new PKCriteria(contentID)); DataPortal.Delete(new PKCriteria(contentID));
@@ -510,12 +436,6 @@ namespace VEPROMS.CSLA.Library
} }
public override Entry Save() public override Entry Save()
{ {
if (IsDeleted && !CanDeleteObject())
throw new System.Security.SecurityException("User not authorized to remove a Entry");
else if (IsNew && !CanAddObject())
throw new System.Security.SecurityException("User not authorized to add a Entry");
else if (!CanEditObject())
throw new System.Security.SecurityException("User not authorized to update a Entry");
try try
{ {
BuildRefreshList(); BuildRefreshList();
@@ -535,13 +455,9 @@ namespace VEPROMS.CSLA.Library
[Serializable()] [Serializable()]
protected class PKCriteria protected class PKCriteria
{ {
private int _ContentID; private readonly int _ContentID;
public int ContentID public int ContentID => _ContentID;
{ get { return _ContentID; } } public PKCriteria(int contentID) => _ContentID = contentID;
public PKCriteria(int contentID)
{
_ContentID = contentID;
}
} }
// CSLATODO: If Create needs to access DB - It should not be marked RunLocal // CSLATODO: If Create needs to access DB - It should not be marked RunLocal
[RunLocal()] [RunLocal()]
@@ -609,7 +525,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Entry.DataPortal_Fetch", ex); throw new DbCslaException("Entry.DataPortal_Fetch", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Insert() protected override void DataPortal_Insert()
{ {
try try
@@ -634,33 +550,39 @@ namespace VEPROMS.CSLA.Library
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Entry.DataPortal_Insert", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Entry.DataPortal_Insert", GetHashCode());
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
internal void SQLInsert() internal void SQLInsert()
{ {
if (!this.IsDirty) return; if (!IsDirty) return;
try try
{ {
if (_MyDocument != null) _MyDocument.Update(); _MyDocument?.Update();
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = Database.VEPROMS_SqlConnection)
using (SqlCommand cm = cn.CreateCommand())
{ {
cm.CommandType = CommandType.StoredProcedure; if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
cm.CommandTimeout = Database.SQLTimeout; using (SqlCommand cm = cn.CreateCommand())
cm.CommandText = "addEntry"; {
// Input All Fields - Except Calculated Columns cm.CommandType = CommandType.StoredProcedure;
cm.Parameters.AddWithValue("@ContentID", ContentID); cm.CommandTimeout = Database.SQLTimeout;
cm.Parameters.AddWithValue("@DocID", DocID); cm.CommandText = "addEntry";
if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); // Input All Fields - Except Calculated Columns
cm.Parameters.AddWithValue("@UserID", _UserID); cm.Parameters.AddWithValue("@ContentID", ContentID);
// Output Calculated Columns cm.Parameters.AddWithValue("@DocID", DocID);
SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS);
param_LastChanged.Direction = ParameterDirection.Output; cm.Parameters.AddWithValue("@UserID", _UserID);
cm.Parameters.Add(param_LastChanged); // Output Calculated Columns
// CSLATODO: Define any additional output parameters SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp)
cm.ExecuteNonQuery(); {
// Save all values being returned from the Procedure Direction = ParameterDirection.Output
_LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; };
cm.Parameters.Add(param_LastChanged);
// CSLATODO: Define any additional output parameters
cm.ExecuteNonQuery();
// Save all values being returned from the Procedure
_LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value;
}
} }
MarkOld(); MarkOld();
// update child objects // update child objects
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Entry.SQLInsert", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Entry.SQLInsert", GetHashCode());
@@ -672,7 +594,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Entry.SQLInsert", ex); throw new DbCslaException("Entry.SQLInsert", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
public static byte[] Add(SqlConnection cn, Content myContent, Document myDocument, DateTime dts, string userID) public static byte[] Add(SqlConnection cn, Content myContent, Document myDocument, DateTime dts, string userID)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Entry.Add", 0); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Entry.Add", 0);
@@ -689,8 +611,10 @@ namespace VEPROMS.CSLA.Library
if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts); if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts);
cm.Parameters.AddWithValue("@UserID", userID); cm.Parameters.AddWithValue("@UserID", userID);
// Output Calculated Columns // Output Calculated Columns
SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp)
param_LastChanged.Direction = ParameterDirection.Output; {
Direction = ParameterDirection.Output
};
cm.Parameters.Add(param_LastChanged); cm.Parameters.Add(param_LastChanged);
// CSLATODO: Define any additional output parameters // CSLATODO: Define any additional output parameters
cm.ExecuteNonQuery(); cm.ExecuteNonQuery();
@@ -704,7 +628,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Entry.Add", ex); throw new DbCslaException("Entry.Add", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Update() protected override void DataPortal_Update()
{ {
if (!IsDirty) return; // If not dirty - nothing to do if (!IsDirty) return; // If not dirty - nothing to do
@@ -727,38 +651,44 @@ namespace VEPROMS.CSLA.Library
if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; if (!ex.Message.EndsWith("has been edited by another user.")) throw ex;
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
internal void SQLUpdate() internal void SQLUpdate()
{ {
if (!IsDirty) return; // If not dirty - nothing to do if (!IsDirty) return; // If not dirty - nothing to do
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Entry.SQLUpdate", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Entry.SQLUpdate", GetHashCode());
try try
{ {
if (_MyDocument != null) _MyDocument.Update(); _MyDocument?.Update();
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = Database.VEPROMS_SqlConnection)
if (base.IsDirty)
{ {
using (SqlCommand cm = cn.CreateCommand()) if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
if (base.IsDirty)
{ {
cm.CommandType = CommandType.StoredProcedure; using (SqlCommand cm = cn.CreateCommand())
cm.CommandTimeout = Database.SQLTimeout; {
cm.CommandText = "updateEntry"; cm.CommandType = CommandType.StoredProcedure;
// All Fields including Calculated Fields cm.CommandTimeout = Database.SQLTimeout;
cm.Parameters.AddWithValue("@ContentID", ContentID); cm.CommandText = "updateEntry";
cm.Parameters.AddWithValue("@DocID", DocID); // All Fields including Calculated Fields
if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); cm.Parameters.AddWithValue("@ContentID", ContentID);
cm.Parameters.AddWithValue("@UserID", _UserID); cm.Parameters.AddWithValue("@DocID", DocID);
cm.Parameters.AddWithValue("@LastChanged", _LastChanged); if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS);
// Output Calculated Columns cm.Parameters.AddWithValue("@UserID", _UserID);
SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); cm.Parameters.AddWithValue("@LastChanged", _LastChanged);
param_LastChanged.Direction = ParameterDirection.Output; // Output Calculated Columns
cm.Parameters.Add(param_LastChanged); SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp)
// CSLATODO: Define any additional output parameters {
cm.ExecuteNonQuery(); Direction = ParameterDirection.Output
// Save all values being returned from the Procedure };
_LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; cm.Parameters.Add(param_LastChanged);
// CSLATODO: Define any additional output parameters
cm.ExecuteNonQuery();
// Save all values being returned from the Procedure
_LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value;
}
} }
} }
MarkOld(); MarkOld();
// use the open connection to update child objects // use the open connection to update child objects
} }
@@ -771,14 +701,18 @@ namespace VEPROMS.CSLA.Library
} }
internal void Update(Content content) internal void Update(Content content)
{ {
if (!this.IsDirty) return; if (!IsDirty) return;
if (base.IsDirty) if (base.IsDirty)
{ {
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = Database.VEPROMS_SqlConnection)
if (IsNew) {
_LastChanged = Entry.Add(cn, content, MyDocument, _DTS, _UserID); if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
else if (IsNew)
_LastChanged = Entry.Update(cn, content.ContentID, _DocID, _DTS, _UserID, ref _LastChanged); _LastChanged = Entry.Add(cn, content, MyDocument, _DTS, _UserID);
else
_LastChanged = Entry.Update(cn, content.ContentID, _DocID, _DTS, _UserID, ref _LastChanged);
}
MarkOld(); MarkOld();
// B2018-126 & B2018-133: Refresh for library document usage change (note that original checkin had a null check for // B2018-126 & B2018-133: Refresh for library document usage change (note that original checkin had a null check for
// _MyDocument.DocumentEntries that was causing a sql Distributed Transaction Coordinator error - this was removed // _MyDocument.DocumentEntries that was causing a sql Distributed Transaction Coordinator error - this was removed
@@ -790,7 +724,7 @@ namespace VEPROMS.CSLA.Library
} }
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
public static byte[] Update(SqlConnection cn, int contentID, int docID, DateTime dts, string userID, ref byte[] lastChanged) public static byte[] Update(SqlConnection cn, int contentID, int docID, DateTime dts, string userID, ref byte[] lastChanged)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Entry.Update", 0); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Entry.Update", 0);
@@ -808,8 +742,10 @@ namespace VEPROMS.CSLA.Library
cm.Parameters.AddWithValue("@UserID", userID); cm.Parameters.AddWithValue("@UserID", userID);
cm.Parameters.AddWithValue("@LastChanged", lastChanged); cm.Parameters.AddWithValue("@LastChanged", lastChanged);
// Output Calculated Columns // Output Calculated Columns
SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp)
param_LastChanged.Direction = ParameterDirection.Output; {
Direction = ParameterDirection.Output
};
cm.Parameters.Add(param_LastChanged); cm.Parameters.Add(param_LastChanged);
// CSLATODO: Define any additional output parameters // CSLATODO: Define any additional output parameters
cm.ExecuteNonQuery(); cm.ExecuteNonQuery();
@@ -823,12 +759,9 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Entry.Update", ex); throw new DbCslaException("Entry.Update", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_DeleteSelf() protected override void DataPortal_DeleteSelf() => DataPortal_Delete(new PKCriteria(_ContentID));
{
DataPortal_Delete(new PKCriteria(_ContentID));
}
[Transactional(TransactionalTypes.TransactionScope)]
private void DataPortal_Delete(PKCriteria criteria) private void DataPortal_Delete(PKCriteria criteria)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Entry.DataPortal_Delete", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Entry.DataPortal_Delete", GetHashCode());
@@ -853,7 +786,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Entry.DataPortal_Delete", ex); throw new DbCslaException("Entry.DataPortal_Delete", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
public static void Remove(SqlConnection cn, int contentID) public static void Remove(SqlConnection cn, int contentID)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Entry.Remove", 0); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Entry.Remove", 0);
@@ -894,16 +827,10 @@ namespace VEPROMS.CSLA.Library
[Serializable()] [Serializable()]
private class ExistsCommand : CommandBase private class ExistsCommand : CommandBase
{ {
private int _ContentID; private readonly int _ContentID;
private bool _exists; private bool _exists;
public bool Exists public bool Exists => _exists;
{ public ExistsCommand(int contentID) => _ContentID = contentID;
get { return _exists; }
}
public ExistsCommand(int contentID)
{
_ContentID = contentID;
}
protected override void DataPortal_Execute() protected override void DataPortal_Execute()
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Entry.DataPortal_Execute", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Entry.DataPortal_Execute", GetHashCode());
@@ -911,7 +838,7 @@ namespace VEPROMS.CSLA.Library
{ {
using (SqlConnection cn = Database.VEPROMS_SqlConnection) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
cn.Open(); if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
using (SqlCommand cm = cn.CreateCommand()) using (SqlCommand cm = cn.CreateCommand())
{ {
cm.CommandType = CommandType.StoredProcedure; cm.CommandType = CommandType.StoredProcedure;
@@ -933,7 +860,7 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
// Standard Default Code // Standard Default Code
#region extension #region extension
EntryExtension _EntryExtension = new EntryExtension(); readonly EntryExtension _EntryExtension = new EntryExtension();
[Serializable()] [Serializable()]
partial class EntryExtension : extensionBase partial class EntryExtension : extensionBase
{ {
@@ -942,14 +869,8 @@ namespace VEPROMS.CSLA.Library
class extensionBase class extensionBase
{ {
// Default Values // Default Values
public virtual DateTime DefaultDTS public virtual DateTime DefaultDTS => DateTime.Now;
{ public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID;
get { return DateTime.Now; }
}
public virtual string DefaultUserID
{
get { return Volian.Base.Library.VlnSettings.UserID; }
}
// Authorization Rules // Authorization Rules
public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules)
{ {
@@ -978,57 +899,13 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is Entry) if (destType == typeof(string) && value is Entry entry)
{ {
// Return the ToString value // Return the ToString value
return ((Entry)value).ToString(); return entry.ToString();
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
} }
#endregion #endregion
} // Namespace } // Namespace
//// The following is a sample Extension File. You can use it to create EntryExt.cs
//using System;
//using System.Collections.Generic;
//using System.Text;
//using Csla;
//namespace VEPROMS.CSLA.Library
//{
// public partial class Entry
// {
// partial class EntryExtension : extensionBase
// {
// // CSLATODO: Override automatic defaults
// public virtual DateTime DefaultDTS
// {
// get { return DateTime.Now; }
// }
// public virtual string DefaultUserID
// {
// get { return Environment.UserName.ToUpper(); }
// }
// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules)
// {
// //rules.AllowRead(Dbid, "<Role(s)>");
// }
// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules)
// {
// //rules.AllowInstanceRead(Dbid, "<Role(s)>");
// }
// public new void AddValidationRules(Csla.Validation.ValidationRules rules)
// {
// rules.AddRule(
// Csla.Validation.CommonRules.StringMaxLength,
// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100));
// }
// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules)
// {
// rules.AddInstanceRule(/* Instance Validation Rule */);
// }
// }
// }
//}
@@ -13,8 +13,6 @@ using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
using Csla.Validation; using Csla.Validation;
@@ -37,10 +35,7 @@ namespace VEPROMS.CSLA.Library
if (IsDirty) if (IsDirty)
refreshEntryAudits.Add(this); refreshEntryAudits.Add(this);
} }
private void ClearRefreshList() private void ClearRefreshList() => _RefreshEntryAudits = new List<EntryAudit>();
{
_RefreshEntryAudits = new List<EntryAudit>();
}
private void BuildRefreshList() private void BuildRefreshList()
{ {
ClearRefreshList(); ClearRefreshList();
@@ -56,6 +51,7 @@ namespace VEPROMS.CSLA.Library
} }
#endregion #endregion
#region Collection #region Collection
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static List<EntryAudit> _CacheList = new List<EntryAudit>(); private static List<EntryAudit> _CacheList = new List<EntryAudit>();
protected static void AddToCache(EntryAudit entryAudit) protected static void AddToCache(EntryAudit entryAudit)
{ {
@@ -65,6 +61,7 @@ namespace VEPROMS.CSLA.Library
{ {
while (_CacheList.Contains(entryAudit)) _CacheList.Remove(entryAudit); // In RemoveFromCache while (_CacheList.Contains(entryAudit)) _CacheList.Remove(entryAudit); // In RemoveFromCache
} }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static Dictionary<string, List<EntryAudit>> _CacheByPrimaryKey = new Dictionary<string, List<EntryAudit>>(); private static Dictionary<string, List<EntryAudit>> _CacheByPrimaryKey = new Dictionary<string, List<EntryAudit>>();
private static void ConvertListToDictionary() private static void ConvertListToDictionary()
{ {
@@ -90,15 +87,9 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
#region Business Methods #region Business Methods
private string _ErrorMessage = string.Empty; private string _ErrorMessage = string.Empty;
public string ErrorMessage public string ErrorMessage => _ErrorMessage;
{
get { return _ErrorMessage; }
}
private static int _nextAuditID = -1; private static int _nextAuditID = -1;
public static int NextAuditID public static int NextAuditID => _nextAuditID--;
{
get { return _nextAuditID--; }
}
private long _AuditID; private long _AuditID;
[System.ComponentModel.DataObjectField(true, true)] [System.ComponentModel.DataObjectField(true, true)]
public long AuditID public long AuditID
@@ -200,40 +191,14 @@ namespace VEPROMS.CSLA.Library
} }
} }
} }
public override bool IsDirty public override bool IsDirty => base.IsDirty;
{ public override bool IsValid => (IsNew && !IsDirty) || base.IsValid;
get { return base.IsDirty; }
}
public bool IsDirtyList(List<object> list)
{
return base.IsDirty;
}
public override bool IsValid
{
get { return (IsNew && !IsDirty) ? true : base.IsValid; }
}
public bool IsValidList(List<object> list)
{
return (IsNew && !IsDirty) ? true : base.IsValid;
}
// CSLATODO: Replace base EntryAudit.ToString function as necessary
/// <summary>
/// Overrides Base ToString
/// </summary>
/// <returns>A string representation of current EntryAudit</returns>
//public override string ToString()
//{
// return base.ToString();
//}
// CSLATODO: Check EntryAudit.GetIdValue to assure that the ID returned is unique // CSLATODO: Check EntryAudit.GetIdValue to assure that the ID returned is unique
/// <summary> /// <summary>
/// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// Overrides Base GetIdValue - Used internally by CSLA to determine equality
/// </summary> /// </summary>
/// <returns>A Unique ID for the current EntryAudit</returns> /// <returns>A Unique ID for the current EntryAudit</returns>
protected override object GetIdValue() protected override object GetIdValue() => MyEntryAuditUnique; // Absolutely Unique ID
{
return MyEntryAuditUnique; // Absolutely Unique ID
}
#endregion #endregion
#region ValidationRules #region ValidationRules
[NonSerialized] [NonSerialized]
@@ -261,8 +226,8 @@ namespace VEPROMS.CSLA.Library
get get
{ {
IVEHasBrokenRules hasBrokenRules = HasBrokenRules; IVEHasBrokenRules hasBrokenRules = HasBrokenRules;
if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; if (Equals(hasBrokenRules)) return BrokenRulesCollection;
return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); return hasBrokenRules?.BrokenRules;
} }
} }
protected override void AddBusinessRules() protected override void AddBusinessRules()
@@ -281,33 +246,11 @@ namespace VEPROMS.CSLA.Library
_EntryAuditExtension.AddInstanceValidationRules(ValidationRules); _EntryAuditExtension.AddInstanceValidationRules(ValidationRules);
// CSLATODO: Add other validation rules // CSLATODO: Add other validation rules
} }
// Sample data comparison validation rule
//private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e)
//{
// if (_started > _ended)
// {
// e.Description = "Start date can't be after end date";
// return false;
// }
// else
// return true;
//}
#endregion #endregion
#region Authorization Rules #region Authorization Rules
protected override void AddAuthorizationRules() protected override void AddAuthorizationRules()
{ {
//CSLATODO: Who can read/write which fields //CSLATODO: Who can read/write which fields
//AuthorizationRules.AllowRead(AuditID, "<Role(s)>");
//AuthorizationRules.AllowRead(ContentID, "<Role(s)>");
//AuthorizationRules.AllowRead(DocID, "<Role(s)>");
//AuthorizationRules.AllowRead(DTS, "<Role(s)>");
//AuthorizationRules.AllowRead(UserID, "<Role(s)>");
//AuthorizationRules.AllowRead(DeleteStatus, "<Role(s)>");
//AuthorizationRules.AllowWrite(ContentID, "<Role(s)>");
//AuthorizationRules.AllowWrite(DocID, "<Role(s)>");
//AuthorizationRules.AllowWrite(DTS, "<Role(s)>");
//AuthorizationRules.AllowWrite(UserID, "<Role(s)>");
//AuthorizationRules.AllowWrite(DeleteStatus, "<Role(s)>");
_EntryAuditExtension.AddAuthorizationRules(AuthorizationRules); _EntryAuditExtension.AddAuthorizationRules(AuthorizationRules);
} }
protected override void AddInstanceAuthorizationRules() protected override void AddInstanceAuthorizationRules()
@@ -315,42 +258,14 @@ namespace VEPROMS.CSLA.Library
//CSLATODO: Who can read/write which fields //CSLATODO: Who can read/write which fields
_EntryAuditExtension.AddInstanceAuthorizationRules(AuthorizationRules); _EntryAuditExtension.AddInstanceAuthorizationRules(AuthorizationRules);
} }
public static bool CanAddObject()
{
// CSLATODO: Can Add Authorization
//return Csla.ApplicationContext.User.IsInRole("ProjectManager");
return true;
}
public static bool CanGetObject()
{
// CSLATODO: CanGet Authorization
return true;
}
public static bool CanDeleteObject()
{
// CSLATODO: CanDelete Authorization
//bool result = false;
//if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true;
//if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true;
//return result;
return true;
}
public static bool CanEditObject()
{
// CSLATODO: CanEdit Authorization
//return Csla.ApplicationContext.User.IsInRole("ProjectManager");
return true;
}
#endregion #endregion
#region Factory Methods #region Factory Methods
public int CurrentEditLevel public int CurrentEditLevel => EditLevel;
{ get { return EditLevel; } }
private static int _EntryAuditUnique = 0; private static int _EntryAuditUnique = 0;
protected static int EntryAuditUnique protected static int EntryAuditUnique => ++_EntryAuditUnique;
{ get { return ++_EntryAuditUnique; } } private readonly int _MyEntryAuditUnique = EntryAuditUnique;
private int _MyEntryAuditUnique = EntryAuditUnique; // Absolutely Unique ID - Editable
public int MyEntryAuditUnique // Absolutely Unique ID - Editable public int MyEntryAuditUnique => _MyEntryAuditUnique;
{ get { return _MyEntryAuditUnique; } }
protected EntryAudit() protected EntryAudit()
{/* require use of factory methods */ {/* require use of factory methods */
AddToCache(this); AddToCache(this);
@@ -359,15 +274,11 @@ namespace VEPROMS.CSLA.Library
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~EntryAudit() ~EntryAudit()
{ {
_CountFinalized++; _CountFinalized++;
@@ -392,8 +303,6 @@ namespace VEPROMS.CSLA.Library
} }
public static EntryAudit New() public static EntryAudit New()
{ {
if (!CanAddObject())
throw new System.Security.SecurityException("User not authorized to add a EntryAudit");
try try
{ {
return DataPortal.Create<EntryAudit>(); return DataPortal.Create<EntryAudit>();
@@ -431,8 +340,6 @@ namespace VEPROMS.CSLA.Library
} }
public static EntryAudit Get(long auditID) public static EntryAudit Get(long auditID)
{ {
if (!CanGetObject())
throw new System.Security.SecurityException("User not authorized to view a EntryAudit");
try try
{ {
EntryAudit tmp = GetCachedByPrimaryKey(auditID); EntryAudit tmp = GetCachedByPrimaryKey(auditID);
@@ -464,8 +371,6 @@ namespace VEPROMS.CSLA.Library
} }
public static void Delete(long auditID) public static void Delete(long auditID)
{ {
if (!CanDeleteObject())
throw new System.Security.SecurityException("User not authorized to remove a EntryAudit");
try try
{ {
DataPortal.Delete(new PKCriteria(auditID)); DataPortal.Delete(new PKCriteria(auditID));
@@ -477,12 +382,6 @@ namespace VEPROMS.CSLA.Library
} }
public override EntryAudit Save() public override EntryAudit Save()
{ {
if (IsDeleted && !CanDeleteObject())
throw new System.Security.SecurityException("User not authorized to remove a EntryAudit");
else if (IsNew && !CanAddObject())
throw new System.Security.SecurityException("User not authorized to add a EntryAudit");
else if (!CanEditObject())
throw new System.Security.SecurityException("User not authorized to update a EntryAudit");
try try
{ {
BuildRefreshList(); BuildRefreshList();
@@ -502,13 +401,9 @@ namespace VEPROMS.CSLA.Library
[Serializable()] [Serializable()]
protected class PKCriteria protected class PKCriteria
{ {
private long _AuditID; private readonly long _AuditID;
public long AuditID public long AuditID => _AuditID;
{ get { return _AuditID; } } public PKCriteria(long auditID) => _AuditID = auditID;
public PKCriteria(long auditID)
{
_AuditID = auditID;
}
} }
// CSLATODO: If Create needs to access DB - It should not be marked RunLocal // CSLATODO: If Create needs to access DB - It should not be marked RunLocal
[RunLocal()] [RunLocal()]
@@ -576,7 +471,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("EntryAudit.DataPortal_Fetch", ex); throw new DbCslaException("EntryAudit.DataPortal_Fetch", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Insert() protected override void DataPortal_Insert()
{ {
try try
@@ -601,33 +496,39 @@ namespace VEPROMS.CSLA.Library
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] EntryAudit.DataPortal_Insert", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] EntryAudit.DataPortal_Insert", GetHashCode());
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
internal void SQLInsert() internal void SQLInsert()
{ {
if (!this.IsDirty) return; if (!IsDirty) return;
try try
{ {
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = Database.VEPROMS_SqlConnection)
using (SqlCommand cm = cn.CreateCommand())
{ {
cm.CommandType = CommandType.StoredProcedure; if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
cm.CommandTimeout = Database.SQLTimeout; using (SqlCommand cm = cn.CreateCommand())
cm.CommandText = "addEntryAudit"; {
// Input All Fields - Except Calculated Columns cm.CommandType = CommandType.StoredProcedure;
cm.Parameters.AddWithValue("@ContentID", _ContentID); cm.CommandTimeout = Database.SQLTimeout;
cm.Parameters.AddWithValue("@DocID", _DocID); cm.CommandText = "addEntryAudit";
if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); // Input All Fields - Except Calculated Columns
cm.Parameters.AddWithValue("@UserID", _UserID); cm.Parameters.AddWithValue("@ContentID", _ContentID);
cm.Parameters.AddWithValue("@DeleteStatus", _DeleteStatus); cm.Parameters.AddWithValue("@DocID", _DocID);
// Output Calculated Columns if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS);
SqlParameter param_AuditID = new SqlParameter("@newAuditID", SqlDbType.BigInt); cm.Parameters.AddWithValue("@UserID", _UserID);
param_AuditID.Direction = ParameterDirection.Output; cm.Parameters.AddWithValue("@DeleteStatus", _DeleteStatus);
cm.Parameters.Add(param_AuditID); // Output Calculated Columns
// CSLATODO: Define any additional output parameters SqlParameter param_AuditID = new SqlParameter("@newAuditID", SqlDbType.BigInt)
cm.ExecuteNonQuery(); {
// Save all values being returned from the Procedure Direction = ParameterDirection.Output
_AuditID = (long)cm.Parameters["@newAuditID"].Value; };
cm.Parameters.Add(param_AuditID);
// CSLATODO: Define any additional output parameters
cm.ExecuteNonQuery();
// Save all values being returned from the Procedure
_AuditID = (long)cm.Parameters["@newAuditID"].Value;
}
} }
MarkOld(); MarkOld();
// update child objects // update child objects
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] EntryAudit.SQLInsert", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] EntryAudit.SQLInsert", GetHashCode());
@@ -639,7 +540,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("EntryAudit.SQLInsert", ex); throw new DbCslaException("EntryAudit.SQLInsert", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
public static void Add(SqlConnection cn, ref long auditID, int contentID, int docID, DateTime dts, string userID, int deleteStatus) public static void Add(SqlConnection cn, ref long auditID, int contentID, int docID, DateTime dts, string userID, int deleteStatus)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] EntryAudit.Add", 0); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] EntryAudit.Add", 0);
@@ -657,8 +558,10 @@ namespace VEPROMS.CSLA.Library
cm.Parameters.AddWithValue("@UserID", userID); cm.Parameters.AddWithValue("@UserID", userID);
cm.Parameters.AddWithValue("@DeleteStatus", deleteStatus); cm.Parameters.AddWithValue("@DeleteStatus", deleteStatus);
// Output Calculated Columns // Output Calculated Columns
SqlParameter param_AuditID = new SqlParameter("@newAuditID", SqlDbType.BigInt); SqlParameter param_AuditID = new SqlParameter("@newAuditID", SqlDbType.BigInt)
param_AuditID.Direction = ParameterDirection.Output; {
Direction = ParameterDirection.Output
};
cm.Parameters.Add(param_AuditID); cm.Parameters.Add(param_AuditID);
// CSLATODO: Define any additional output parameters // CSLATODO: Define any additional output parameters
cm.ExecuteNonQuery(); cm.ExecuteNonQuery();
@@ -673,7 +576,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("EntryAudit.Add", ex); throw new DbCslaException("EntryAudit.Add", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Update() protected override void DataPortal_Update()
{ {
if (!IsDirty) return; // If not dirty - nothing to do if (!IsDirty) return; // If not dirty - nothing to do
@@ -696,34 +599,38 @@ namespace VEPROMS.CSLA.Library
if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; if (!ex.Message.EndsWith("has been edited by another user.")) throw ex;
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
internal void SQLUpdate() internal void SQLUpdate()
{ {
if (!IsDirty) return; // If not dirty - nothing to do if (!IsDirty) return; // If not dirty - nothing to do
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] EntryAudit.SQLUpdate", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] EntryAudit.SQLUpdate", GetHashCode());
try try
{ {
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = Database.VEPROMS_SqlConnection)
if (base.IsDirty)
{ {
using (SqlCommand cm = cn.CreateCommand()) if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
if (base.IsDirty)
{ {
cm.CommandType = CommandType.StoredProcedure; using (SqlCommand cm = cn.CreateCommand())
cm.CommandTimeout = Database.SQLTimeout; {
cm.CommandText = "updateEntryAudit"; cm.CommandType = CommandType.StoredProcedure;
// All Fields including Calculated Fields cm.CommandTimeout = Database.SQLTimeout;
cm.Parameters.AddWithValue("@AuditID", _AuditID); cm.CommandText = "updateEntryAudit";
cm.Parameters.AddWithValue("@ContentID", _ContentID); // All Fields including Calculated Fields
cm.Parameters.AddWithValue("@DocID", _DocID); cm.Parameters.AddWithValue("@AuditID", _AuditID);
if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); cm.Parameters.AddWithValue("@ContentID", _ContentID);
cm.Parameters.AddWithValue("@UserID", _UserID); cm.Parameters.AddWithValue("@DocID", _DocID);
cm.Parameters.AddWithValue("@DeleteStatus", _DeleteStatus); if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS);
// Output Calculated Columns cm.Parameters.AddWithValue("@UserID", _UserID);
// CSLATODO: Define any additional output parameters cm.Parameters.AddWithValue("@DeleteStatus", _DeleteStatus);
cm.ExecuteNonQuery(); // Output Calculated Columns
// Save all values being returned from the Procedure // CSLATODO: Define any additional output parameters
cm.ExecuteNonQuery();
// Save all values being returned from the Procedure
}
} }
} }
MarkOld(); MarkOld();
// use the open connection to update child objects // use the open connection to update child objects
} }
@@ -736,18 +643,22 @@ namespace VEPROMS.CSLA.Library
} }
internal void Update() internal void Update()
{ {
if (!this.IsDirty) return; if (!IsDirty) return;
if (base.IsDirty) if (base.IsDirty)
{ {
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = Database.VEPROMS_SqlConnection)
if (IsNew) {
EntryAudit.Add(cn, ref _AuditID, _ContentID, _DocID, _DTS, _UserID, _DeleteStatus); if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
else if (IsNew)
EntryAudit.Update(cn, ref _AuditID, _ContentID, _DocID, _DTS, _UserID, _DeleteStatus); EntryAudit.Add(cn, ref _AuditID, _ContentID, _DocID, _DTS, _UserID, _DeleteStatus);
else
EntryAudit.Update(cn, ref _AuditID, _ContentID, _DocID, _DTS, _UserID, _DeleteStatus);
}
MarkOld(); MarkOld();
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
public static void Update(SqlConnection cn, ref long auditID, int contentID, int docID, DateTime dts, string userID, int deleteStatus) public static void Update(SqlConnection cn, ref long auditID, int contentID, int docID, DateTime dts, string userID, int deleteStatus)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] EntryAudit.Update", 0); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] EntryAudit.Update", 0);
@@ -778,12 +689,12 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("EntryAudit.Update", ex); throw new DbCslaException("EntryAudit.Update", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_DeleteSelf() protected override void DataPortal_DeleteSelf()
{ {
DataPortal_Delete(new PKCriteria(_AuditID)); DataPortal_Delete(new PKCriteria(_AuditID));
} }
[Transactional(TransactionalTypes.TransactionScope)]
private void DataPortal_Delete(PKCriteria criteria) private void DataPortal_Delete(PKCriteria criteria)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] EntryAudit.DataPortal_Delete", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] EntryAudit.DataPortal_Delete", GetHashCode());
@@ -808,7 +719,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("EntryAudit.DataPortal_Delete", ex); throw new DbCslaException("EntryAudit.DataPortal_Delete", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
public static void Remove(SqlConnection cn, long auditID) public static void Remove(SqlConnection cn, long auditID)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] EntryAudit.Remove", 0); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] EntryAudit.Remove", 0);
@@ -834,7 +745,7 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
// Standard Default Code // Standard Default Code
#region extension #region extension
EntryAuditExtension _EntryAuditExtension = new EntryAuditExtension(); readonly EntryAuditExtension _EntryAuditExtension = new EntryAuditExtension();
[Serializable()] [Serializable()]
partial class EntryAuditExtension : extensionBase partial class EntryAuditExtension : extensionBase
{ {
@@ -871,49 +782,14 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is EntryAudit) if (destType == typeof(string) && value is EntryAudit audit)
{ {
// Return the ToString value // Return the ToString value
return ((EntryAudit)value).ToString(); return audit.ToString();
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
} }
#endregion #endregion
} // Namespace } // Namespace
//// The following is a sample Extension File. You can use it to create EntryAuditExt.cs
//using System;
//using System.Collections.Generic;
//using System.Text;
//using Csla;
//namespace VEPROMS.CSLA.Library
//{
// public partial class EntryAudit
// {
// partial class EntryAuditExtension : extensionBase
// {
// // CSLATODO: Override automatic defaults
// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules)
// {
// //rules.AllowRead(Dbid, "<Role(s)>");
// }
// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules)
// {
// //rules.AllowInstanceRead(Dbid, "<Role(s)>");
// }
// public new void AddValidationRules(Csla.Validation.ValidationRules rules)
// {
// rules.AddRule(
// Csla.Validation.CommonRules.StringMaxLength,
// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100));
// }
// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules)
// {
// rules.AddInstanceRule(/* Instance Validation Rule */);
// }
// }
// }
//}
@@ -13,8 +13,6 @@ using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
namespace VEPROMS.CSLA.Library namespace VEPROMS.CSLA.Library
@@ -28,14 +26,12 @@ namespace VEPROMS.CSLA.Library
public partial class EntryAuditInfo : ReadOnlyBase<EntryAuditInfo>, IDisposable public partial class EntryAuditInfo : ReadOnlyBase<EntryAuditInfo>, IDisposable
{ {
public event EntryAuditInfoEvent Changed; public event EntryAuditInfoEvent Changed;
private void OnChange() private void OnChange() => Changed?.Invoke(this);
{
if (Changed != null) Changed(this);
}
#region Log4Net #region Log4Net
private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endregion #endregion
#region Collection #region Collection
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static List<EntryAuditInfo> _CacheList = new List<EntryAuditInfo>(); private static List<EntryAuditInfo> _CacheList = new List<EntryAuditInfo>();
protected static void AddToCache(EntryAuditInfo entryAuditInfo) protected static void AddToCache(EntryAuditInfo entryAuditInfo)
{ {
@@ -45,6 +41,7 @@ namespace VEPROMS.CSLA.Library
{ {
while (_CacheList.Contains(entryAuditInfo)) _CacheList.Remove(entryAuditInfo); // In RemoveFromCache while (_CacheList.Contains(entryAuditInfo)) _CacheList.Remove(entryAuditInfo); // In RemoveFromCache
} }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static Dictionary<string, List<EntryAuditInfo>> _CacheByPrimaryKey = new Dictionary<string, List<EntryAuditInfo>>(); private static Dictionary<string, List<EntryAuditInfo>> _CacheByPrimaryKey = new Dictionary<string, List<EntryAuditInfo>>();
private static void ConvertListToDictionary() private static void ConvertListToDictionary()
{ {
@@ -74,21 +71,8 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
#region Business Methods #region Business Methods
private string _ErrorMessage = string.Empty; private string _ErrorMessage = string.Empty;
public string ErrorMessage public string ErrorMessage => _ErrorMessage;
{
get { return _ErrorMessage; }
}
protected EntryAudit _Editable; protected EntryAudit _Editable;
private IVEHasBrokenRules HasBrokenRules
{
get
{
IVEHasBrokenRules hasBrokenRules = null;
if (_Editable != null)
hasBrokenRules = _Editable.HasBrokenRules;
return hasBrokenRules;
}
}
private long _AuditID; private long _AuditID;
[System.ComponentModel.DataObjectField(true, true)] [System.ComponentModel.DataObjectField(true, true)]
public long AuditID public long AuditID
@@ -144,32 +128,19 @@ namespace VEPROMS.CSLA.Library
return _DeleteStatus; return _DeleteStatus;
} }
} }
// CSLATODO: Replace base EntryAuditInfo.ToString function as necessary
/// <summary>
/// Overrides Base ToString
/// </summary>
/// <returns>A string representation of current EntryAuditInfo</returns>
//public override string ToString()
//{
// return base.ToString();
//}
// CSLATODO: Check EntryAuditInfo.GetIdValue to assure that the ID returned is unique // CSLATODO: Check EntryAuditInfo.GetIdValue to assure that the ID returned is unique
/// <summary> /// <summary>
/// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// Overrides Base GetIdValue - Used internally by CSLA to determine equality
/// </summary> /// </summary>
/// <returns>A Unique ID for the current EntryAuditInfo</returns> /// <returns>A Unique ID for the current EntryAuditInfo</returns>
protected override object GetIdValue() protected override object GetIdValue() => MyEntryAuditInfoUnique; // Absolutely Unique ID
{
return MyEntryAuditInfoUnique; // Absolutely Unique ID
}
#endregion #endregion
#region Factory Methods #region Factory Methods
private static int _EntryAuditInfoUnique = 0; private static int _EntryAuditInfoUnique = 0;
private static int EntryAuditInfoUnique private static int EntryAuditInfoUnique => ++_EntryAuditInfoUnique;
{ get { return ++_EntryAuditInfoUnique; } } private readonly int _MyEntryAuditInfoUnique = EntryAuditInfoUnique;
private int _MyEntryAuditInfoUnique = EntryAuditInfoUnique; // Absolutely Unique ID - Info
public int MyEntryAuditInfoUnique // Absolutely Unique ID - Info public int MyEntryAuditInfoUnique => _MyEntryAuditInfoUnique;
{ get { return _MyEntryAuditInfoUnique; } }
protected EntryAuditInfo() protected EntryAuditInfo()
{/* require use of factory methods */ {/* require use of factory methods */
AddToCache(this); AddToCache(this);
@@ -178,15 +149,11 @@ namespace VEPROMS.CSLA.Library
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~EntryAuditInfo() ~EntryAuditInfo()
{ {
_CountFinalized++; _CountFinalized++;
@@ -203,10 +170,7 @@ namespace VEPROMS.CSLA.Library
if (listEntryAuditInfo.Count == 0) // If there are no items left in the list if (listEntryAuditInfo.Count == 0) // If there are no items left in the list
_CacheByPrimaryKey.Remove(AuditID.ToString()); // remove the list _CacheByPrimaryKey.Remove(AuditID.ToString()); // remove the list
} }
public virtual EntryAudit Get() public virtual EntryAudit Get() => _Editable = EntryAudit.Get(_AuditID);
{
return _Editable = EntryAudit.Get(_AuditID);
}
public static void Refresh(EntryAudit tmp) public static void Refresh(EntryAudit tmp)
{ {
string key = tmp.AuditID.ToString(); string key = tmp.AuditID.ToString();
@@ -227,8 +191,6 @@ namespace VEPROMS.CSLA.Library
} }
public static EntryAuditInfo Get(long auditID) public static EntryAuditInfo Get(long auditID)
{ {
//if (!CanGetObject())
// throw new System.Security.SecurityException("User not authorized to view a EntryAudit");
try try
{ {
EntryAuditInfo tmp = GetCachedByPrimaryKey(auditID); EntryAuditInfo tmp = GetCachedByPrimaryKey(auditID);
@@ -267,13 +229,9 @@ namespace VEPROMS.CSLA.Library
[Serializable()] [Serializable()]
protected class PKCriteria protected class PKCriteria
{ {
private long _AuditID; private readonly long _AuditID;
public long AuditID public long AuditID => _AuditID;
{ get { return _AuditID; } } public PKCriteria(long auditID) => _AuditID = auditID;
public PKCriteria(long auditID)
{
_AuditID = auditID;
}
} }
private void ReadData(SafeDataReader dr) private void ReadData(SafeDataReader dr)
{ {
@@ -333,7 +291,7 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
// Standard Refresh // Standard Refresh
#region extension #region extension
EntryAuditInfoExtension _EntryAuditInfoExtension = new EntryAuditInfoExtension(); readonly EntryAuditInfoExtension _EntryAuditInfoExtension = new EntryAuditInfoExtension();
[Serializable()] [Serializable()]
partial class EntryAuditInfoExtension : extensionBase { } partial class EntryAuditInfoExtension : extensionBase { }
[Serializable()] [Serializable()]
@@ -349,10 +307,10 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is EntryAuditInfo) if (destType == typeof(string) && value is EntryAuditInfo info)
{ {
// Return the ToString value // Return the ToString value
return ((EntryAuditInfo)value).ToString(); return info.ToString();
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
@@ -13,8 +13,6 @@ using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
namespace VEPROMS.CSLA.Library namespace VEPROMS.CSLA.Library
@@ -28,11 +26,10 @@ namespace VEPROMS.CSLA.Library
{ {
#region Log4Net #region Log4Net
private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endregion #endregion
#region Business Methods #region Business Methods
internal new IList<EntryAuditInfo> Items internal new IList<EntryAuditInfo> Items => base.Items;
{ get { return base.Items; } } public void AddEvents()
public void AddEvents()
{ {
foreach (EntryAuditInfo tmp in this) foreach (EntryAuditInfo tmp in this)
{ {
@@ -51,16 +48,12 @@ namespace VEPROMS.CSLA.Library
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed ~EntryAuditInfoList()
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~EntryAuditInfoList()
{ {
_CountFinalized++; _CountFinalized++;
} }
@@ -97,26 +90,11 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Error on EntryAuditInfoList.Get", ex); throw new DbCslaException("Error on EntryAuditInfoList.Get", ex);
} }
} }
/// <summary> /// <summary>
/// Reset the list of all EntryAuditInfo. /// Reset the list of all EntryAuditInfo.
/// </summary> /// </summary>
public static void Reset() public static void Reset() => _EntryAuditInfoList = null;
{ private EntryAuditInfoList()
_EntryAuditInfoList = null;
}
// CSLATODO: Add alternative gets -
//public static EntryAuditInfoList Get(<criteria>)
//{
// try
// {
// return DataPortal.Fetch<EntryAuditInfoList>(new FilteredCriteria(<criteria>));
// }
// catch (Exception ex)
// {
// throw new DbCslaException("Error on EntryAuditInfoList.Get", ex);
// }
//}
private EntryAuditInfoList()
{ /* require use of factory methods */ } { /* require use of factory methods */ }
#endregion #endregion
#region Data Access Portal #region Data Access Portal
@@ -149,41 +127,30 @@ namespace VEPROMS.CSLA.Library
} }
this.RaiseListChangedEvents = true; this.RaiseListChangedEvents = true;
} }
#endregion #endregion
#region ICustomTypeDescriptor impl #region ICustomTypeDescriptor impl
public String GetClassName() public String GetClassName() => TypeDescriptor.GetClassName(this, true);
{ return TypeDescriptor.GetClassName(this, true); } public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true);
public AttributeCollection GetAttributes() public String GetComponentName() => TypeDescriptor.GetComponentName(this, true);
{ return TypeDescriptor.GetAttributes(this, true); } public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true);
public String GetComponentName() public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true);
{ return TypeDescriptor.GetComponentName(this, true); } public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true);
public TypeConverter GetConverter() public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true);
{ return TypeDescriptor.GetConverter(this, true); } public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true);
public EventDescriptor GetDefaultEvent() public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true);
{ return TypeDescriptor.GetDefaultEvent(this, true); } public object GetPropertyOwner(PropertyDescriptor pd) => this;
public PropertyDescriptor GetDefaultProperty() /// <summary>
{ return TypeDescriptor.GetDefaultProperty(this, true); } /// Called to get the properties of this type. Returns properties with certain
public object GetEditor(Type editorBaseType) /// attributes. this restriction is not implemented here.
{ return TypeDescriptor.GetEditor(this, editorBaseType, true); } /// </summary>
public EventDescriptorCollection GetEvents(Attribute[] attributes) /// <param name="attributes"></param>
{ return TypeDescriptor.GetEvents(this, attributes, true); } /// <returns></returns>
public EventDescriptorCollection GetEvents() public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties();
{ return TypeDescriptor.GetEvents(this, true); } /// <summary>
public object GetPropertyOwner(PropertyDescriptor pd) /// Called to get the properties of this type.
{ return this; } /// </summary>
/// <summary> /// <returns></returns>
/// Called to get the properties of this type. Returns properties with certain public PropertyDescriptorCollection GetProperties()
/// attributes. this restriction is not implemented here.
/// </summary>
/// <param name="attributes"></param>
/// <returns></returns>
public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{ return GetProperties(); }
/// <summary>
/// Called to get the properties of this type.
/// </summary>
/// <returns></returns>
public PropertyDescriptorCollection GetProperties()
{ {
// Create a collection object to hold property descriptors // Create a collection object to hold property descriptors
PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null);
@@ -205,7 +172,6 @@ namespace VEPROMS.CSLA.Library
/// </summary> /// </summary>
public partial class EntryAuditInfoListPropertyDescriptor : vlnListPropertyDescriptor public partial class EntryAuditInfoListPropertyDescriptor : vlnListPropertyDescriptor
{ {
private EntryAuditInfo Item { get { return (EntryAuditInfo)_Item; } }
public EntryAuditInfoListPropertyDescriptor(EntryAuditInfoList collection, int index) : base(collection, index) { ;} public EntryAuditInfoListPropertyDescriptor(EntryAuditInfoList collection, int index) : base(collection, index) { ;}
} }
#endregion #endregion
@@ -214,10 +180,10 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is EntryAuditInfoList) if (destType == typeof(string) && value is EntryAuditInfoList list)
{ {
// Return department and department role separated by comma. // Return department and department role separated by comma.
return ((EntryAuditInfoList)value).Items.Count.ToString() + " EntryAudits"; return $"{list.Items.Count} EntryAudits";
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
@@ -13,8 +13,6 @@ using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
namespace VEPROMS.CSLA.Library namespace VEPROMS.CSLA.Library
@@ -28,14 +26,12 @@ namespace VEPROMS.CSLA.Library
public partial class EntryInfo : ReadOnlyBase<EntryInfo>, IDisposable public partial class EntryInfo : ReadOnlyBase<EntryInfo>, IDisposable
{ {
public event EntryInfoEvent Changed; public event EntryInfoEvent Changed;
private void OnChange() private void OnChange() => Changed?.Invoke(this);
{
if (Changed != null) Changed(this);
}
#region Log4Net #region Log4Net
private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endregion #endregion
#region Collection #region Collection
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static List<EntryInfo> _CacheList = new List<EntryInfo>(); private static List<EntryInfo> _CacheList = new List<EntryInfo>();
protected static void AddToCache(EntryInfo entryInfo) protected static void AddToCache(EntryInfo entryInfo)
{ {
@@ -45,6 +41,7 @@ namespace VEPROMS.CSLA.Library
{ {
while (_CacheList.Contains(entryInfo)) _CacheList.Remove(entryInfo); // In RemoveFromCache while (_CacheList.Contains(entryInfo)) _CacheList.Remove(entryInfo); // In RemoveFromCache
} }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static Dictionary<string, List<EntryInfo>> _CacheByPrimaryKey = new Dictionary<string, List<EntryInfo>>(); private static Dictionary<string, List<EntryInfo>> _CacheByPrimaryKey = new Dictionary<string, List<EntryInfo>>();
private static void ConvertListToDictionary() private static void ConvertListToDictionary()
{ {
@@ -74,21 +71,8 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
#region Business Methods #region Business Methods
private string _ErrorMessage = string.Empty; private string _ErrorMessage = string.Empty;
public string ErrorMessage public string ErrorMessage => _ErrorMessage;
{
get { return _ErrorMessage; }
}
protected Entry _Editable; protected Entry _Editable;
private IVEHasBrokenRules HasBrokenRules
{
get
{
IVEHasBrokenRules hasBrokenRules = null;
if (_Editable != null)
hasBrokenRules = _Editable.HasBrokenRules;
return hasBrokenRules;
}
}
private int _ContentID; private int _ContentID;
[System.ComponentModel.DataObjectField(true, true)] [System.ComponentModel.DataObjectField(true, true)]
public int ContentID public int ContentID
@@ -149,32 +133,19 @@ namespace VEPROMS.CSLA.Library
return _UserID; return _UserID;
} }
} }
// CSLATODO: Replace base EntryInfo.ToString function as necessary
/// <summary>
/// Overrides Base ToString
/// </summary>
/// <returns>A string representation of current EntryInfo</returns>
//public override string ToString()
//{
// return base.ToString();
//}
// CSLATODO: Check EntryInfo.GetIdValue to assure that the ID returned is unique // CSLATODO: Check EntryInfo.GetIdValue to assure that the ID returned is unique
/// <summary> /// <summary>
/// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// Overrides Base GetIdValue - Used internally by CSLA to determine equality
/// </summary> /// </summary>
/// <returns>A Unique ID for the current EntryInfo</returns> /// <returns>A Unique ID for the current EntryInfo</returns>
protected override object GetIdValue() protected override object GetIdValue() => MyEntryInfoUnique; // Absolutely Unique ID
{
return MyEntryInfoUnique; // Absolutely Unique ID
}
#endregion #endregion
#region Factory Methods #region Factory Methods
private static int _EntryInfoUnique = 0; private static int _EntryInfoUnique = 0;
private static int EntryInfoUnique private static int EntryInfoUnique => ++_EntryInfoUnique;
{ get { return ++_EntryInfoUnique; } } private readonly int _MyEntryInfoUnique = EntryInfoUnique;
private int _MyEntryInfoUnique = EntryInfoUnique; // Absolutely Unique ID - Info
public int MyEntryInfoUnique // Absolutely Unique ID - Info public int MyEntryInfoUnique => _MyEntryInfoUnique;
{ get { return _MyEntryInfoUnique; } }
protected EntryInfo() protected EntryInfo()
{/* require use of factory methods */ {/* require use of factory methods */
AddToCache(this); AddToCache(this);
@@ -183,15 +154,11 @@ namespace VEPROMS.CSLA.Library
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~EntryInfo() ~EntryInfo()
{ {
_CountFinalized++; _CountFinalized++;
@@ -208,10 +175,7 @@ namespace VEPROMS.CSLA.Library
if (listEntryInfo.Count == 0) // If there are no items left in the list if (listEntryInfo.Count == 0) // If there are no items left in the list
_CacheByPrimaryKey.Remove(ContentID.ToString()); // remove the list _CacheByPrimaryKey.Remove(ContentID.ToString()); // remove the list
} }
public virtual Entry Get() public virtual Entry Get() => _Editable = Entry.Get(_ContentID);
{
return _Editable = Entry.Get(_ContentID);
}
public static void Refresh(Entry tmp) public static void Refresh(Entry tmp)
{ {
string key = tmp.ContentID.ToString(); string key = tmp.ContentID.ToString();
@@ -224,11 +188,11 @@ namespace VEPROMS.CSLA.Library
{ {
if (_DocID != tmp.DocID) if (_DocID != tmp.DocID)
{ {
if (MyDocument != null) MyDocument.RefreshDocumentEntries(); // Update List for old value MyDocument?.RefreshDocumentEntries(); // Update List for old value
_DocID = tmp.DocID; // Update the value _DocID = tmp.DocID; // Update the value
} }
_MyDocument = null; // Reset list so that the next line gets a new list _MyDocument = null; // Reset list so that the next line gets a new list
if (MyDocument != null) MyDocument.RefreshDocumentEntries(); // Update List for new value MyDocument?.RefreshDocumentEntries(); // Update List for new value
_DTS = tmp.DTS; _DTS = tmp.DTS;
_UserID = tmp.UserID; _UserID = tmp.UserID;
_EntryInfoExtension.Refresh(this); _EntryInfoExtension.Refresh(this);
@@ -251,8 +215,6 @@ namespace VEPROMS.CSLA.Library
} }
public static EntryInfo Get(int contentID) public static EntryInfo Get(int contentID)
{ {
//if (!CanGetObject())
// throw new System.Security.SecurityException("User not authorized to view a Entry");
try try
{ {
EntryInfo tmp = GetCachedByPrimaryKey(contentID); EntryInfo tmp = GetCachedByPrimaryKey(contentID);
@@ -291,13 +253,9 @@ namespace VEPROMS.CSLA.Library
[Serializable()] [Serializable()]
protected class PKCriteria protected class PKCriteria
{ {
private int _ContentID; private readonly int _ContentID;
public int ContentID public int ContentID => _ContentID;
{ get { return _ContentID; } } public PKCriteria(int contentID) => _ContentID = contentID;
public PKCriteria(int contentID)
{
_ContentID = contentID;
}
} }
private void ReadData(SafeDataReader dr) private void ReadData(SafeDataReader dr)
{ {
@@ -355,7 +313,7 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
// Standard Refresh // Standard Refresh
#region extension #region extension
EntryInfoExtension _EntryInfoExtension = new EntryInfoExtension(); readonly EntryInfoExtension _EntryInfoExtension = new EntryInfoExtension();
[Serializable()] [Serializable()]
partial class EntryInfoExtension : extensionBase { } partial class EntryInfoExtension : extensionBase { }
[Serializable()] [Serializable()]
@@ -371,10 +329,10 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is EntryInfo) if (destType == typeof(string) && value is EntryInfo info)
{ {
// Return the ToString value // Return the ToString value
return ((EntryInfo)value).ToString(); return info.ToString();
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
@@ -13,8 +13,6 @@ using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
namespace VEPROMS.CSLA.Library namespace VEPROMS.CSLA.Library
@@ -28,11 +26,10 @@ namespace VEPROMS.CSLA.Library
{ {
#region Log4Net #region Log4Net
private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endregion #endregion
#region Business Methods #region Business Methods
internal new IList<EntryInfo> Items internal new IList<EntryInfo> Items => base.Items;
{ get { return base.Items; } } public void AddEvents()
public void AddEvents()
{ {
foreach (EntryInfo tmp in this) foreach (EntryInfo tmp in this)
{ {
@@ -51,16 +48,12 @@ namespace VEPROMS.CSLA.Library
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed ~EntryInfoList()
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~EntryInfoList()
{ {
_CountFinalized++; _CountFinalized++;
} }
@@ -104,18 +97,6 @@ namespace VEPROMS.CSLA.Library
{ {
_EntryInfoList = null; _EntryInfoList = null;
} }
// CSLATODO: Add alternative gets -
//public static EntryInfoList Get(<criteria>)
//{
// try
// {
// return DataPortal.Fetch<EntryInfoList>(new FilteredCriteria(<criteria>));
// }
// catch (Exception ex)
// {
// throw new DbCslaException("Error on EntryInfoList.Get", ex);
// }
//}
public static EntryInfoList GetByContentID(int contentID) public static EntryInfoList GetByContentID(int contentID)
{ {
try try
@@ -180,11 +161,8 @@ namespace VEPROMS.CSLA.Library
[Serializable()] [Serializable()]
private class ContentIDCriteria private class ContentIDCriteria
{ {
public ContentIDCriteria(int contentID) public ContentIDCriteria(int contentID) => _ContentID = contentID;
{ private int _ContentID;
_ContentID = contentID;
}
private int _ContentID;
public int ContentID public int ContentID
{ {
get { return _ContentID; } get { return _ContentID; }
@@ -224,11 +202,8 @@ namespace VEPROMS.CSLA.Library
[Serializable()] [Serializable()]
private class DocIDCriteria private class DocIDCriteria
{ {
public DocIDCriteria(int docID) public DocIDCriteria(int docID) => _DocID = docID;
{ private int _DocID;
_DocID = docID;
}
private int _DocID;
public int DocID public int DocID
{ {
get { return _DocID; } get { return _DocID; }
@@ -265,41 +240,30 @@ namespace VEPROMS.CSLA.Library
} }
this.RaiseListChangedEvents = true; this.RaiseListChangedEvents = true;
} }
#endregion #endregion
#region ICustomTypeDescriptor impl #region ICustomTypeDescriptor impl
public String GetClassName() public String GetClassName() => TypeDescriptor.GetClassName(this, true);
{ return TypeDescriptor.GetClassName(this, true); } public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true);
public AttributeCollection GetAttributes() public String GetComponentName() => TypeDescriptor.GetComponentName(this, true);
{ return TypeDescriptor.GetAttributes(this, true); } public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true);
public String GetComponentName() public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true);
{ return TypeDescriptor.GetComponentName(this, true); } public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true);
public TypeConverter GetConverter() public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true);
{ return TypeDescriptor.GetConverter(this, true); } public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true);
public EventDescriptor GetDefaultEvent() public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true);
{ return TypeDescriptor.GetDefaultEvent(this, true); } public object GetPropertyOwner(PropertyDescriptor pd) => this;
public PropertyDescriptor GetDefaultProperty() /// <summary>
{ return TypeDescriptor.GetDefaultProperty(this, true); } /// Called to get the properties of this type. Returns properties with certain
public object GetEditor(Type editorBaseType) /// attributes. this restriction is not implemented here.
{ return TypeDescriptor.GetEditor(this, editorBaseType, true); } /// </summary>
public EventDescriptorCollection GetEvents(Attribute[] attributes) /// <param name="attributes"></param>
{ return TypeDescriptor.GetEvents(this, attributes, true); } /// <returns></returns>
public EventDescriptorCollection GetEvents() public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties();
{ return TypeDescriptor.GetEvents(this, true); } /// <summary>
public object GetPropertyOwner(PropertyDescriptor pd) /// Called to get the properties of this type.
{ return this; } /// </summary>
/// <summary> /// <returns></returns>
/// Called to get the properties of this type. Returns properties with certain public PropertyDescriptorCollection GetProperties()
/// attributes. this restriction is not implemented here.
/// </summary>
/// <param name="attributes"></param>
/// <returns></returns>
public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{ return GetProperties(); }
/// <summary>
/// Called to get the properties of this type.
/// </summary>
/// <returns></returns>
public PropertyDescriptorCollection GetProperties()
{ {
// Create a collection object to hold property descriptors // Create a collection object to hold property descriptors
PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null);
@@ -321,7 +285,6 @@ namespace VEPROMS.CSLA.Library
/// </summary> /// </summary>
public partial class EntryInfoListPropertyDescriptor : vlnListPropertyDescriptor public partial class EntryInfoListPropertyDescriptor : vlnListPropertyDescriptor
{ {
private EntryInfo Item { get { return (EntryInfo)_Item; } }
public EntryInfoListPropertyDescriptor(EntryInfoList collection, int index) : base(collection, index) { ;} public EntryInfoListPropertyDescriptor(EntryInfoList collection, int index) : base(collection, index) { ;}
} }
#endregion #endregion
@@ -330,10 +293,10 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is EntryInfoList) if (destType == typeof(string) && value is EntryInfoList list)
{ {
// Return department and department role separated by comma. // Return department and department role separated by comma.
return ((EntryInfoList)value).Items.Count.ToString() + " Entries"; return $"{list.Items.Count} Entries";
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
+134 -263
View File
@@ -13,8 +13,6 @@ using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
using Csla.Validation; using Csla.Validation;
@@ -58,6 +56,7 @@ namespace VEPROMS.CSLA.Library
} }
#endregion #endregion
#region Collection #region Collection
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static List<Figure> _CacheList = new List<Figure>(); private static List<Figure> _CacheList = new List<Figure>();
protected static void AddToCache(Figure figure) protected static void AddToCache(Figure figure)
{ {
@@ -67,7 +66,9 @@ namespace VEPROMS.CSLA.Library
{ {
while (_CacheList.Contains(figure)) _CacheList.Remove(figure); // In RemoveFromCache while (_CacheList.Contains(figure)) _CacheList.Remove(figure); // In RemoveFromCache
} }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static Dictionary<string, List<Figure>> _CacheByPrimaryKey = new Dictionary<string, List<Figure>>(); private static Dictionary<string, List<Figure>> _CacheByPrimaryKey = new Dictionary<string, List<Figure>>();
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static Dictionary<string, List<Figure>> _CacheByROFstID_ImageID = new Dictionary<string, List<Figure>>(); private static Dictionary<string, List<Figure>> _CacheByROFstID_ImageID = new Dictionary<string, List<Figure>>();
private static void ConvertListToDictionary() private static void ConvertListToDictionary()
{ {
@@ -102,15 +103,9 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
#region Business Methods #region Business Methods
private string _ErrorMessage = string.Empty; private string _ErrorMessage = string.Empty;
public string ErrorMessage public string ErrorMessage => _ErrorMessage;
{
get { return _ErrorMessage; }
}
private static int _nextFigureID = -1; private static int _nextFigureID = -1;
public static int NextFigureID public static int NextFigureID => _nextFigureID--;
{
get { return _nextFigureID--; }
}
private int _FigureID; private int _FigureID;
[System.ComponentModel.DataObjectField(true, true)] [System.ComponentModel.DataObjectField(true, true)]
public int FigureID public int FigureID
@@ -252,37 +247,22 @@ namespace VEPROMS.CSLA.Library
if (base.IsDirty || list.Contains(this)) if (base.IsDirty || list.Contains(this))
return base.IsDirty; return base.IsDirty;
list.Add(this); list.Add(this);
return base.IsDirty || (_MyROFst == null ? false : _MyROFst.IsDirtyList(list)) || (_MyROImage == null ? false : _MyROImage.IsDirtyList(list)); return base.IsDirty || (_MyROFst != null && _MyROFst.IsDirtyList(list)) || (_MyROImage != null && _MyROImage.IsDirtyList(list));
}
public override bool IsValid
{
get { return IsValidList(new List<object>()); }
} }
public override bool IsValid => IsValidList(new List<object>());
public bool IsValidList(List<object> list) public bool IsValidList(List<object> list)
{ {
if (list.Contains(this)) if (list.Contains(this))
return (IsNew && !IsDirty) ? true : base.IsValid; return (IsNew && !IsDirty) || base.IsValid;
list.Add(this); list.Add(this);
return ((IsNew && !IsDirty) ? true : base.IsValid) && (_MyROFst == null ? true : _MyROFst.IsValidList(list)) && (_MyROImage == null ? true : _MyROImage.IsValidList(list)); return ((IsNew && !IsDirty) || base.IsValid) && (_MyROFst == null || _MyROFst.IsValidList(list)) && (_MyROImage == null || _MyROImage.IsValidList(list));
} }
// CSLATODO: Replace base Figure.ToString function as necessary
/// <summary>
/// Overrides Base ToString
/// </summary>
/// <returns>A string representation of current Figure</returns>
//public override string ToString()
//{
// return base.ToString();
//}
// CSLATODO: Check Figure.GetIdValue to assure that the ID returned is unique // CSLATODO: Check Figure.GetIdValue to assure that the ID returned is unique
/// <summary> /// <summary>
/// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// Overrides Base GetIdValue - Used internally by CSLA to determine equality
/// </summary> /// </summary>
/// <returns>A Unique ID for the current Figure</returns> /// <returns>A Unique ID for the current Figure</returns>
protected override object GetIdValue() protected override object GetIdValue() => MyFigureUnique; // Absolutely Unique ID
{
return MyFigureUnique; // Absolutely Unique ID
}
#endregion #endregion
#region ValidationRules #region ValidationRules
[NonSerialized] [NonSerialized]
@@ -312,8 +292,8 @@ namespace VEPROMS.CSLA.Library
get get
{ {
IVEHasBrokenRules hasBrokenRules = HasBrokenRules; IVEHasBrokenRules hasBrokenRules = HasBrokenRules;
if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; if (Equals(hasBrokenRules)) return BrokenRulesCollection;
return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); return hasBrokenRules?.BrokenRules;
} }
} }
protected override void AddBusinessRules() protected override void AddBusinessRules()
@@ -355,33 +335,11 @@ namespace VEPROMS.CSLA.Library
} }
return true; return true;
} }
// Sample data comparison validation rule
//private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e)
//{
// if (_started > _ended)
// {
// e.Description = "Start date can't be after end date";
// return false;
// }
// else
// return true;
//}
#endregion #endregion
#region Authorization Rules #region Authorization Rules
protected override void AddAuthorizationRules() protected override void AddAuthorizationRules()
{ {
//CSLATODO: Who can read/write which fields //CSLATODO: Who can read/write which fields
//AuthorizationRules.AllowRead(FigureID, "<Role(s)>");
//AuthorizationRules.AllowRead(ROFstID, "<Role(s)>");
//AuthorizationRules.AllowRead(ImageID, "<Role(s)>");
//AuthorizationRules.AllowRead(Config, "<Role(s)>");
//AuthorizationRules.AllowRead(DTS, "<Role(s)>");
//AuthorizationRules.AllowRead(UserID, "<Role(s)>");
//AuthorizationRules.AllowWrite(ROFstID, "<Role(s)>");
//AuthorizationRules.AllowWrite(ImageID, "<Role(s)>");
//AuthorizationRules.AllowWrite(Config, "<Role(s)>");
//AuthorizationRules.AllowWrite(DTS, "<Role(s)>");
//AuthorizationRules.AllowWrite(UserID, "<Role(s)>");
_FigureExtension.AddAuthorizationRules(AuthorizationRules); _FigureExtension.AddAuthorizationRules(AuthorizationRules);
} }
protected override void AddInstanceAuthorizationRules() protected override void AddInstanceAuthorizationRules()
@@ -389,42 +347,14 @@ namespace VEPROMS.CSLA.Library
//CSLATODO: Who can read/write which fields //CSLATODO: Who can read/write which fields
_FigureExtension.AddInstanceAuthorizationRules(AuthorizationRules); _FigureExtension.AddInstanceAuthorizationRules(AuthorizationRules);
} }
public static bool CanAddObject()
{
// CSLATODO: Can Add Authorization
//return Csla.ApplicationContext.User.IsInRole("ProjectManager");
return true;
}
public static bool CanGetObject()
{
// CSLATODO: CanGet Authorization
return true;
}
public static bool CanDeleteObject()
{
// CSLATODO: CanDelete Authorization
//bool result = false;
//if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true;
//if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true;
//return result;
return true;
}
public static bool CanEditObject()
{
// CSLATODO: CanEdit Authorization
//return Csla.ApplicationContext.User.IsInRole("ProjectManager");
return true;
}
#endregion #endregion
#region Factory Methods #region Factory Methods
public int CurrentEditLevel public int CurrentEditLevel => EditLevel;
{ get { return EditLevel; } }
private static int _FigureUnique = 0; private static int _FigureUnique = 0;
protected static int FigureUnique protected static int FigureUnique => ++_FigureUnique;
{ get { return ++_FigureUnique; } } private readonly int _MyFigureUnique = FigureUnique;
private int _MyFigureUnique = FigureUnique; // Absolutely Unique ID - Editable
public int MyFigureUnique // Absolutely Unique ID - Editable public int MyFigureUnique => _MyFigureUnique;
{ get { return _MyFigureUnique; } }
protected Figure() protected Figure()
{/* require use of factory methods */ {/* require use of factory methods */
AddToCache(this); AddToCache(this);
@@ -433,15 +363,11 @@ namespace VEPROMS.CSLA.Library
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~Figure() ~Figure()
{ {
_CountFinalized++; _CountFinalized++;
@@ -478,8 +404,6 @@ namespace VEPROMS.CSLA.Library
} }
public static Figure New() public static Figure New()
{ {
if (!CanAddObject())
throw new System.Security.SecurityException("User not authorized to add a Figure");
try try
{ {
return DataPortal.Create<Figure>(); return DataPortal.Create<Figure>();
@@ -548,8 +472,6 @@ namespace VEPROMS.CSLA.Library
} }
public static Figure Get(int figureID) public static Figure Get(int figureID)
{ {
if (!CanGetObject())
throw new System.Security.SecurityException("User not authorized to view a Figure");
try try
{ {
Figure tmp = GetCachedByPrimaryKey(figureID); Figure tmp = GetCachedByPrimaryKey(figureID);
@@ -572,8 +494,6 @@ namespace VEPROMS.CSLA.Library
} }
public static Figure GetByROFstID_ImageID(int rOFstID, int imageID) public static Figure GetByROFstID_ImageID(int rOFstID, int imageID)
{ {
if (!CanGetObject())
throw new System.Security.SecurityException("User not authorized to view a Figure");
try try
{ {
Figure tmp = GetCachedByROFstID_ImageID(rOFstID, imageID); Figure tmp = GetCachedByROFstID_ImageID(rOFstID, imageID);
@@ -599,14 +519,9 @@ namespace VEPROMS.CSLA.Library
if (dr.Read()) return new Figure(dr); if (dr.Read()) return new Figure(dr);
return null; return null;
} }
internal Figure(SafeDataReader dr) internal Figure(SafeDataReader dr) => ReadData(dr);
{
ReadData(dr);
}
public static void Delete(int figureID) public static void Delete(int figureID)
{ {
if (!CanDeleteObject())
throw new System.Security.SecurityException("User not authorized to remove a Figure");
try try
{ {
DataPortal.Delete(new PKCriteria(figureID)); DataPortal.Delete(new PKCriteria(figureID));
@@ -618,12 +533,6 @@ namespace VEPROMS.CSLA.Library
} }
public override Figure Save() public override Figure Save()
{ {
if (IsDeleted && !CanDeleteObject())
throw new System.Security.SecurityException("User not authorized to remove a Figure");
else if (IsNew && !CanAddObject())
throw new System.Security.SecurityException("User not authorized to add a Figure");
else if (!CanEditObject())
throw new System.Security.SecurityException("User not authorized to update a Figure");
try try
{ {
BuildRefreshList(); BuildRefreshList();
@@ -643,23 +552,17 @@ namespace VEPROMS.CSLA.Library
[Serializable()] [Serializable()]
protected class PKCriteria protected class PKCriteria
{ {
private int _FigureID; private readonly int _FigureID;
public int FigureID public int FigureID => _FigureID;
{ get { return _FigureID; } } public PKCriteria(int figureID) => _FigureID = figureID;
public PKCriteria(int figureID)
{
_FigureID = figureID;
}
} }
[Serializable()] [Serializable()]
private class ROFstID_ImageIDCriteria private class ROFstID_ImageIDCriteria
{ {
private int _ROFstID; private readonly int _ROFstID;
public int ROFstID public int ROFstID => _ROFstID;
{ get { return _ROFstID; } } private readonly int _ImageID;
private int _ImageID; public int ImageID => _ImageID;
public int ImageID
{ get { return _ImageID; } }
public ROFstID_ImageIDCriteria(int rOFstID, int imageID) public ROFstID_ImageIDCriteria(int rOFstID, int imageID)
{ {
_ROFstID = rOFstID; _ROFstID = rOFstID;
@@ -771,7 +674,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Figure.DataPortal_Fetch", ex); throw new DbCslaException("Figure.DataPortal_Fetch", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Insert() protected override void DataPortal_Insert()
{ {
try try
@@ -796,39 +699,47 @@ namespace VEPROMS.CSLA.Library
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Figure.DataPortal_Insert", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Figure.DataPortal_Insert", GetHashCode());
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
internal void SQLInsert() internal void SQLInsert()
{ {
if (!this.IsDirty) return; if (!IsDirty) return;
try try
{ {
if (_MyROFst != null) _MyROFst.Update(); _MyROFst?.Update();
if (_MyROImage != null) _MyROImage.Update(); _MyROImage?.Update();
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = Database.VEPROMS_SqlConnection)
using (SqlCommand cm = cn.CreateCommand())
{ {
cm.CommandType = CommandType.StoredProcedure; if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
cm.CommandTimeout = Database.SQLTimeout; using (SqlCommand cm = cn.CreateCommand())
cm.CommandText = "addFigure"; {
// Input All Fields - Except Calculated Columns cm.CommandType = CommandType.StoredProcedure;
cm.Parameters.AddWithValue("@ROFstID", ROFstID); cm.CommandTimeout = Database.SQLTimeout;
cm.Parameters.AddWithValue("@ImageID", ImageID); cm.CommandText = "addFigure";
cm.Parameters.AddWithValue("@Config", _Config); // Input All Fields - Except Calculated Columns
if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); cm.Parameters.AddWithValue("@ROFstID", ROFstID);
cm.Parameters.AddWithValue("@UserID", _UserID); cm.Parameters.AddWithValue("@ImageID", ImageID);
// Output Calculated Columns cm.Parameters.AddWithValue("@Config", _Config);
SqlParameter param_FigureID = new SqlParameter("@newFigureID", SqlDbType.Int); if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS);
param_FigureID.Direction = ParameterDirection.Output; cm.Parameters.AddWithValue("@UserID", _UserID);
cm.Parameters.Add(param_FigureID); // Output Calculated Columns
SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); SqlParameter param_FigureID = new SqlParameter("@newFigureID", SqlDbType.Int)
param_LastChanged.Direction = ParameterDirection.Output; {
cm.Parameters.Add(param_LastChanged); Direction = ParameterDirection.Output
// CSLATODO: Define any additional output parameters };
cm.ExecuteNonQuery(); cm.Parameters.Add(param_FigureID);
// Save all values being returned from the Procedure SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp)
_FigureID = (int)cm.Parameters["@newFigureID"].Value; {
_LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; Direction = ParameterDirection.Output
};
cm.Parameters.Add(param_LastChanged);
// CSLATODO: Define any additional output parameters
cm.ExecuteNonQuery();
// Save all values being returned from the Procedure
_FigureID = (int)cm.Parameters["@newFigureID"].Value;
_LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value;
}
} }
MarkOld(); MarkOld();
// update child objects // update child objects
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Figure.SQLInsert", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Figure.SQLInsert", GetHashCode());
@@ -840,7 +751,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Figure.SQLInsert", ex); throw new DbCslaException("Figure.SQLInsert", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
public static byte[] Add(SqlConnection cn, ref int figureID, ROFst myROFst, ROImage myROImage, string config, DateTime dts, string userID) public static byte[] Add(SqlConnection cn, ref int figureID, ROFst myROFst, ROImage myROImage, string config, DateTime dts, string userID)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Figure.Add", 0); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Figure.Add", 0);
@@ -858,11 +769,15 @@ namespace VEPROMS.CSLA.Library
if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts); if (dts.Year >= 1753 && dts.Year <= 9999) cm.Parameters.AddWithValue("@DTS", dts);
cm.Parameters.AddWithValue("@UserID", userID); cm.Parameters.AddWithValue("@UserID", userID);
// Output Calculated Columns // Output Calculated Columns
SqlParameter param_FigureID = new SqlParameter("@newFigureID", SqlDbType.Int); SqlParameter param_FigureID = new SqlParameter("@newFigureID", SqlDbType.Int)
param_FigureID.Direction = ParameterDirection.Output; {
Direction = ParameterDirection.Output
};
cm.Parameters.Add(param_FigureID); cm.Parameters.Add(param_FigureID);
SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp)
param_LastChanged.Direction = ParameterDirection.Output; {
Direction = ParameterDirection.Output
};
cm.Parameters.Add(param_LastChanged); cm.Parameters.Add(param_LastChanged);
// CSLATODO: Define any additional output parameters // CSLATODO: Define any additional output parameters
cm.ExecuteNonQuery(); cm.ExecuteNonQuery();
@@ -877,7 +792,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Figure.Add", ex); throw new DbCslaException("Figure.Add", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Update() protected override void DataPortal_Update()
{ {
if (!IsDirty) return; // If not dirty - nothing to do if (!IsDirty) return; // If not dirty - nothing to do
@@ -900,41 +815,47 @@ namespace VEPROMS.CSLA.Library
if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; if (!ex.Message.EndsWith("has been edited by another user.")) throw ex;
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
internal void SQLUpdate() internal void SQLUpdate()
{ {
if (!IsDirty) return; // If not dirty - nothing to do if (!IsDirty) return; // If not dirty - nothing to do
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Figure.SQLUpdate", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Figure.SQLUpdate", GetHashCode());
try try
{ {
if (_MyROFst != null) _MyROFst.Update(); _MyROFst?.Update();
if (_MyROImage != null) _MyROImage.Update(); _MyROImage?.Update();
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = Database.VEPROMS_SqlConnection)
if (base.IsDirty)
{ {
using (SqlCommand cm = cn.CreateCommand()) if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
if (base.IsDirty)
{ {
cm.CommandType = CommandType.StoredProcedure; using (SqlCommand cm = cn.CreateCommand())
cm.CommandTimeout = Database.SQLTimeout; {
cm.CommandText = "updateFigure"; cm.CommandType = CommandType.StoredProcedure;
// All Fields including Calculated Fields cm.CommandTimeout = Database.SQLTimeout;
cm.Parameters.AddWithValue("@FigureID", _FigureID); cm.CommandText = "updateFigure";
cm.Parameters.AddWithValue("@ROFstID", ROFstID); // All Fields including Calculated Fields
cm.Parameters.AddWithValue("@ImageID", ImageID); cm.Parameters.AddWithValue("@FigureID", _FigureID);
cm.Parameters.AddWithValue("@Config", _Config); cm.Parameters.AddWithValue("@ROFstID", ROFstID);
if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS); cm.Parameters.AddWithValue("@ImageID", ImageID);
cm.Parameters.AddWithValue("@UserID", _UserID); cm.Parameters.AddWithValue("@Config", _Config);
cm.Parameters.AddWithValue("@LastChanged", _LastChanged); if (_DTS.Year >= 1753 && _DTS.Year <= 9999) cm.Parameters.AddWithValue("@DTS", _DTS);
// Output Calculated Columns cm.Parameters.AddWithValue("@UserID", _UserID);
SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); cm.Parameters.AddWithValue("@LastChanged", _LastChanged);
param_LastChanged.Direction = ParameterDirection.Output; // Output Calculated Columns
cm.Parameters.Add(param_LastChanged); SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp)
// CSLATODO: Define any additional output parameters {
cm.ExecuteNonQuery(); Direction = ParameterDirection.Output
// Save all values being returned from the Procedure };
_LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value; cm.Parameters.Add(param_LastChanged);
// CSLATODO: Define any additional output parameters
cm.ExecuteNonQuery();
// Save all values being returned from the Procedure
_LastChanged = (byte[])cm.Parameters["@newLastChanged"].Value;
}
} }
} }
MarkOld(); MarkOld();
// use the open connection to update child objects // use the open connection to update child objects
} }
@@ -947,18 +868,22 @@ namespace VEPROMS.CSLA.Library
} }
internal void Update() internal void Update()
{ {
if (!this.IsDirty) return; if (!IsDirty) return;
if (base.IsDirty) if (base.IsDirty)
{ {
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlConnection cn = Database.VEPROMS_SqlConnection)
if (IsNew) {
_LastChanged = Figure.Add(cn, ref _FigureID, _MyROFst, _MyROImage, _Config, _DTS, _UserID); if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
else if (IsNew)
_LastChanged = Figure.Update(cn, ref _FigureID, _ROFstID, _ImageID, _Config, _DTS, _UserID, ref _LastChanged); _LastChanged = Figure.Add(cn, ref _FigureID, _MyROFst, _MyROImage, _Config, _DTS, _UserID);
else
_LastChanged = Figure.Update(cn, ref _FigureID, _ROFstID, _ImageID, _Config, _DTS, _UserID, ref _LastChanged);
}
MarkOld(); MarkOld();
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
public static byte[] Update(SqlConnection cn, ref int figureID, int rOFstID, int imageID, string config, DateTime dts, string userID, ref byte[] lastChanged) public static byte[] Update(SqlConnection cn, ref int figureID, int rOFstID, int imageID, string config, DateTime dts, string userID, ref byte[] lastChanged)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Figure.Update", 0); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Figure.Update", 0);
@@ -978,8 +903,10 @@ namespace VEPROMS.CSLA.Library
cm.Parameters.AddWithValue("@UserID", userID); cm.Parameters.AddWithValue("@UserID", userID);
cm.Parameters.AddWithValue("@LastChanged", lastChanged); cm.Parameters.AddWithValue("@LastChanged", lastChanged);
// Output Calculated Columns // Output Calculated Columns
SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp); SqlParameter param_LastChanged = new SqlParameter("@newLastChanged", SqlDbType.Timestamp)
param_LastChanged.Direction = ParameterDirection.Output; {
Direction = ParameterDirection.Output
};
cm.Parameters.Add(param_LastChanged); cm.Parameters.Add(param_LastChanged);
// CSLATODO: Define any additional output parameters // CSLATODO: Define any additional output parameters
cm.ExecuteNonQuery(); cm.ExecuteNonQuery();
@@ -993,12 +920,12 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Figure.Update", ex); throw new DbCslaException("Figure.Update", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_DeleteSelf() protected override void DataPortal_DeleteSelf()
{ {
DataPortal_Delete(new PKCriteria(_FigureID)); DataPortal_Delete(new PKCriteria(_FigureID));
} }
[Transactional(TransactionalTypes.TransactionScope)]
private void DataPortal_Delete(PKCriteria criteria) private void DataPortal_Delete(PKCriteria criteria)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Figure.DataPortal_Delete", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Figure.DataPortal_Delete", GetHashCode());
@@ -1023,7 +950,7 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Figure.DataPortal_Delete", ex); throw new DbCslaException("Figure.DataPortal_Delete", ex);
} }
} }
[Transactional(TransactionalTypes.TransactionScope)]
public static void Remove(SqlConnection cn, int figureID) public static void Remove(SqlConnection cn, int figureID)
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Figure.Remove", 0); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Figure.Remove", 0);
@@ -1064,16 +991,10 @@ namespace VEPROMS.CSLA.Library
[Serializable()] [Serializable()]
private class ExistsCommand : CommandBase private class ExistsCommand : CommandBase
{ {
private int _FigureID; private readonly int _FigureID;
private bool _exists; private bool _exists;
public bool Exists public bool Exists => _exists;
{ public ExistsCommand(int figureID) => _FigureID = figureID;
get { return _exists; }
}
public ExistsCommand(int figureID)
{
_FigureID = figureID;
}
protected override void DataPortal_Execute() protected override void DataPortal_Execute()
{ {
if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Figure.DataPortal_Execute", GetHashCode()); if (_MyLog.IsDebugEnabled) _MyLog.DebugFormat("[{0}] Figure.DataPortal_Execute", GetHashCode());
@@ -1081,7 +1002,7 @@ namespace VEPROMS.CSLA.Library
{ {
using (SqlConnection cn = Database.VEPROMS_SqlConnection) using (SqlConnection cn = Database.VEPROMS_SqlConnection)
{ {
cn.Open(); if (cn.State == System.Data.ConnectionState.Closed) cn.Open();
using (SqlCommand cm = cn.CreateCommand()) using (SqlCommand cm = cn.CreateCommand())
{ {
cm.CommandType = CommandType.StoredProcedure; cm.CommandType = CommandType.StoredProcedure;
@@ -1103,7 +1024,7 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
// Standard Default Code // Standard Default Code
#region extension #region extension
FigureExtension _FigureExtension = new FigureExtension(); readonly FigureExtension _FigureExtension = new FigureExtension();
[Serializable()] [Serializable()]
partial class FigureExtension : extensionBase partial class FigureExtension : extensionBase
{ {
@@ -1112,14 +1033,8 @@ namespace VEPROMS.CSLA.Library
class extensionBase class extensionBase
{ {
// Default Values // Default Values
public virtual DateTime DefaultDTS public virtual DateTime DefaultDTS => DateTime.Now;
{ public virtual string DefaultUserID => Volian.Base.Library.VlnSettings.UserID;
get { return DateTime.Now; }
}
public virtual string DefaultUserID
{
get { return Volian.Base.Library.VlnSettings.UserID; }
}
// Authorization Rules // Authorization Rules
public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules)
{ {
@@ -1148,57 +1063,13 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is Figure) if (destType == typeof(string) && value is Figure figure)
{ {
// Return the ToString value // Return the ToString value
return ((Figure)value).ToString(); return figure.ToString();
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
} }
#endregion #endregion
} // Namespace } // Namespace
//// The following is a sample Extension File. You can use it to create FigureExt.cs
//using System;
//using System.Collections.Generic;
//using System.Text;
//using Csla;
//namespace VEPROMS.CSLA.Library
//{
// public partial class Figure
// {
// partial class FigureExtension : extensionBase
// {
// // CSLATODO: Override automatic defaults
// public virtual DateTime DefaultDTS
// {
// get { return DateTime.Now; }
// }
// public virtual string DefaultUserID
// {
// get { return Environment.UserName.ToUpper(); }
// }
// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules)
// {
// //rules.AllowRead(Dbid, "<Role(s)>");
// }
// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules)
// {
// //rules.AllowInstanceRead(Dbid, "<Role(s)>");
// }
// public new void AddValidationRules(Csla.Validation.ValidationRules rules)
// {
// rules.AddRule(
// Csla.Validation.CommonRules.StringMaxLength,
// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100));
// }
// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules)
// {
// rules.AddInstanceRule(/* Instance Validation Rule */);
// }
// }
// }
//}
@@ -13,8 +13,6 @@ using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
namespace VEPROMS.CSLA.Library namespace VEPROMS.CSLA.Library
@@ -28,14 +26,12 @@ namespace VEPROMS.CSLA.Library
public partial class FigureInfo : ReadOnlyBase<FigureInfo>, IDisposable public partial class FigureInfo : ReadOnlyBase<FigureInfo>, IDisposable
{ {
public event FigureInfoEvent Changed; public event FigureInfoEvent Changed;
private void OnChange() private void OnChange() => Changed?.Invoke(this);
{
if (Changed != null) Changed(this);
}
#region Log4Net #region Log4Net
private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endregion #endregion
#region Collection #region Collection
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static List<FigureInfo> _CacheList = new List<FigureInfo>(); private static List<FigureInfo> _CacheList = new List<FigureInfo>();
protected static void AddToCache(FigureInfo figureInfo) protected static void AddToCache(FigureInfo figureInfo)
{ {
@@ -45,6 +41,7 @@ namespace VEPROMS.CSLA.Library
{ {
while (_CacheList.Contains(figureInfo)) _CacheList.Remove(figureInfo); // In RemoveFromCache while (_CacheList.Contains(figureInfo)) _CacheList.Remove(figureInfo); // In RemoveFromCache
} }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0044:Add readonly modifier", Justification = "Keeping Collections Not ReadOnly")]
private static Dictionary<string, List<FigureInfo>> _CacheByPrimaryKey = new Dictionary<string, List<FigureInfo>>(); private static Dictionary<string, List<FigureInfo>> _CacheByPrimaryKey = new Dictionary<string, List<FigureInfo>>();
private static void ConvertListToDictionary() private static void ConvertListToDictionary()
{ {
@@ -74,21 +71,8 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
#region Business Methods #region Business Methods
private string _ErrorMessage = string.Empty; private string _ErrorMessage = string.Empty;
public string ErrorMessage public string ErrorMessage => _ErrorMessage;
{
get { return _ErrorMessage; }
}
protected Figure _Editable; protected Figure _Editable;
private IVEHasBrokenRules HasBrokenRules
{
get
{
IVEHasBrokenRules hasBrokenRules = null;
if (_Editable != null)
hasBrokenRules = _Editable.HasBrokenRules;
return hasBrokenRules;
}
}
private int _FigureID; private int _FigureID;
[System.ComponentModel.DataObjectField(true, true)] [System.ComponentModel.DataObjectField(true, true)]
public int FigureID public int FigureID
@@ -166,32 +150,19 @@ namespace VEPROMS.CSLA.Library
return _UserID; return _UserID;
} }
} }
// CSLATODO: Replace base FigureInfo.ToString function as necessary
/// <summary>
/// Overrides Base ToString
/// </summary>
/// <returns>A string representation of current FigureInfo</returns>
//public override string ToString()
//{
// return base.ToString();
//}
// CSLATODO: Check FigureInfo.GetIdValue to assure that the ID returned is unique // CSLATODO: Check FigureInfo.GetIdValue to assure that the ID returned is unique
/// <summary> /// <summary>
/// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// Overrides Base GetIdValue - Used internally by CSLA to determine equality
/// </summary> /// </summary>
/// <returns>A Unique ID for the current FigureInfo</returns> /// <returns>A Unique ID for the current FigureInfo</returns>
protected override object GetIdValue() protected override object GetIdValue() => MyFigureInfoUnique; // Absolutely Unique ID
{
return MyFigureInfoUnique; // Absolutely Unique ID
}
#endregion #endregion
#region Factory Methods #region Factory Methods
private static int _FigureInfoUnique = 0; private static int _FigureInfoUnique = 0;
private static int FigureInfoUnique private static int FigureInfoUnique => ++_FigureInfoUnique;
{ get { return ++_FigureInfoUnique; } } private readonly int _MyFigureInfoUnique = FigureInfoUnique;
private int _MyFigureInfoUnique = FigureInfoUnique; // Absolutely Unique ID - Info
public int MyFigureInfoUnique // Absolutely Unique ID - Info public int MyFigureInfoUnique => _MyFigureInfoUnique;
{ get { return _MyFigureInfoUnique; } }
protected FigureInfo() protected FigureInfo()
{/* require use of factory methods */ {/* require use of factory methods */
AddToCache(this); AddToCache(this);
@@ -200,15 +171,11 @@ namespace VEPROMS.CSLA.Library
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~FigureInfo() ~FigureInfo()
{ {
_CountFinalized++; _CountFinalized++;
@@ -225,10 +192,7 @@ namespace VEPROMS.CSLA.Library
if (listFigureInfo.Count == 0) // If there are no items left in the list if (listFigureInfo.Count == 0) // If there are no items left in the list
_CacheByPrimaryKey.Remove(FigureID.ToString()); // remove the list _CacheByPrimaryKey.Remove(FigureID.ToString()); // remove the list
} }
public virtual Figure Get() public virtual Figure Get() => _Editable = Figure.Get(_FigureID);
{
return _Editable = Figure.Get(_FigureID);
}
public static void Refresh(Figure tmp) public static void Refresh(Figure tmp)
{ {
string key = tmp.FigureID.ToString(); string key = tmp.FigureID.ToString();
@@ -241,18 +205,18 @@ namespace VEPROMS.CSLA.Library
{ {
if (_ROFstID != tmp.ROFstID) if (_ROFstID != tmp.ROFstID)
{ {
if (MyROFst != null) MyROFst.RefreshROFstFigures(); // Update List for old value MyROFst?.RefreshROFstFigures(); // Update List for old value
_ROFstID = tmp.ROFstID; // Update the value _ROFstID = tmp.ROFstID; // Update the value
} }
_MyROFst = null; // Reset list so that the next line gets a new list _MyROFst = null; // Reset list so that the next line gets a new list
if (MyROFst != null) MyROFst.RefreshROFstFigures(); // Update List for new value MyROFst?.RefreshROFstFigures(); // Update List for new value
if (_ImageID != tmp.ImageID) if (_ImageID != tmp.ImageID)
{ {
if (MyROImage != null) MyROImage.RefreshROImageFigures(); // Update List for old value MyROImage?.RefreshROImageFigures(); // Update List for old value
_ImageID = tmp.ImageID; // Update the value _ImageID = tmp.ImageID; // Update the value
} }
_MyROImage = null; // Reset list so that the next line gets a new list _MyROImage = null; // Reset list so that the next line gets a new list
if (MyROImage != null) MyROImage.RefreshROImageFigures(); // Update List for new value MyROImage?.RefreshROImageFigures(); // Update List for new value
_Config = tmp.Config; _Config = tmp.Config;
_DTS = tmp.DTS; _DTS = tmp.DTS;
_UserID = tmp.UserID; _UserID = tmp.UserID;
@@ -271,11 +235,11 @@ namespace VEPROMS.CSLA.Library
{ {
if (_ImageID != tmp.ImageID) if (_ImageID != tmp.ImageID)
{ {
if (MyROImage != null) MyROImage.RefreshROImageFigures(); // Update List for old value MyROImage?.RefreshROImageFigures(); // Update List for old value
_ImageID = tmp.ImageID; // Update the value _ImageID = tmp.ImageID; // Update the value
} }
_MyROImage = null; // Reset list so that the next line gets a new list _MyROImage = null; // Reset list so that the next line gets a new list
if (MyROImage != null) MyROImage.RefreshROImageFigures(); // Update List for new value MyROImage?.RefreshROImageFigures(); // Update List for new value
_Config = tmp.Config; _Config = tmp.Config;
_DTS = tmp.DTS; _DTS = tmp.DTS;
_UserID = tmp.UserID; _UserID = tmp.UserID;
@@ -294,11 +258,11 @@ namespace VEPROMS.CSLA.Library
{ {
if (_ROFstID != tmp.ROFstID) if (_ROFstID != tmp.ROFstID)
{ {
if (MyROFst != null) MyROFst.RefreshROFstFigures(); // Update List for old value MyROFst?.RefreshROFstFigures(); // Update List for old value
_ROFstID = tmp.ROFstID; // Update the value _ROFstID = tmp.ROFstID; // Update the value
} }
_MyROFst = null; // Reset list so that the next line gets a new list _MyROFst = null; // Reset list so that the next line gets a new list
if (MyROFst != null) MyROFst.RefreshROFstFigures(); // Update List for new value MyROFst?.RefreshROFstFigures(); // Update List for new value
_Config = tmp.Config; _Config = tmp.Config;
_DTS = tmp.DTS; _DTS = tmp.DTS;
_UserID = tmp.UserID; _UserID = tmp.UserID;
@@ -307,8 +271,6 @@ namespace VEPROMS.CSLA.Library
} }
public static FigureInfo Get(int figureID) public static FigureInfo Get(int figureID)
{ {
//if (!CanGetObject())
// throw new System.Security.SecurityException("User not authorized to view a Figure");
try try
{ {
FigureInfo tmp = GetCachedByPrimaryKey(figureID); FigureInfo tmp = GetCachedByPrimaryKey(figureID);
@@ -347,13 +309,9 @@ namespace VEPROMS.CSLA.Library
[Serializable()] [Serializable()]
protected class PKCriteria protected class PKCriteria
{ {
private int _FigureID; private readonly int _FigureID;
public int FigureID public int FigureID => _FigureID;
{ get { return _FigureID; } } public PKCriteria(int figureID) => _FigureID = figureID;
public PKCriteria(int figureID)
{
_FigureID = figureID;
}
} }
private string _ROImage_FileName = string.Empty; private string _ROImage_FileName = string.Empty;
public string ROImage_FileName public string ROImage_FileName
@@ -427,7 +385,7 @@ namespace VEPROMS.CSLA.Library
#endregion #endregion
// Standard Refresh // Standard Refresh
#region extension #region extension
FigureInfoExtension _FigureInfoExtension = new FigureInfoExtension(); readonly FigureInfoExtension _FigureInfoExtension = new FigureInfoExtension();
[Serializable()] [Serializable()]
partial class FigureInfoExtension : extensionBase { } partial class FigureInfoExtension : extensionBase { }
[Serializable()] [Serializable()]
@@ -443,10 +401,10 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is FigureInfo) if (destType == typeof(string) && value is FigureInfo info)
{ {
// Return the ToString value // Return the ToString value
return ((FigureInfo)value).ToString(); return info.ToString();
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
@@ -13,8 +13,6 @@ using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using Csla; using Csla;
using Csla.Data; using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel; using System.ComponentModel;
using System.Collections.Generic; using System.Collections.Generic;
namespace VEPROMS.CSLA.Library namespace VEPROMS.CSLA.Library
@@ -28,11 +26,10 @@ namespace VEPROMS.CSLA.Library
{ {
#region Log4Net #region Log4Net
private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endregion #endregion
#region Business Methods #region Business Methods
internal new IList<FigureInfo> Items internal new IList<FigureInfo> Items => base.Items;
{ get { return base.Items; } } public void AddEvents()
public void AddEvents()
{ {
foreach (FigureInfo tmp in this) foreach (FigureInfo tmp in this)
{ {
@@ -51,16 +48,12 @@ namespace VEPROMS.CSLA.Library
private static int _CountCreated = 0; private static int _CountCreated = 0;
private static int _CountDisposed = 0; private static int _CountDisposed = 0;
private static int _CountFinalized = 0; private static int _CountFinalized = 0;
private static int IncrementCountCreated private static int IncrementCountCreated => ++_CountCreated;
{ get { return ++_CountCreated; } } private readonly int _CountWhenCreated = IncrementCountCreated;
private int _CountWhenCreated = IncrementCountCreated; public static int CountCreated => _CountCreated;
public static int CountCreated public static int CountNotDisposed => _CountCreated - _CountDisposed;
{ get { return _CountCreated; } } public static int CountNotFinalized => _CountCreated - _CountFinalized;
public static int CountNotDisposed ~FigureInfoList()
{ get { return _CountCreated - _CountDisposed; } }
public static int CountNotFinalized
{ get { return _CountCreated - _CountFinalized; } }
~FigureInfoList()
{ {
_CountFinalized++; _CountFinalized++;
} }
@@ -97,26 +90,11 @@ namespace VEPROMS.CSLA.Library
throw new DbCslaException("Error on FigureInfoList.Get", ex); throw new DbCslaException("Error on FigureInfoList.Get", ex);
} }
} }
/// <summary> /// <summary>
/// Reset the list of all FigureInfo. /// Reset the list of all FigureInfo.
/// </summary> /// </summary>
public static void Reset() public static void Reset() => _FigureInfoList = null;
{ public static FigureInfoList GetByROFstID(int rOFstID)
_FigureInfoList = null;
}
// CSLATODO: Add alternative gets -
//public static FigureInfoList Get(<criteria>)
//{
// try
// {
// return DataPortal.Fetch<FigureInfoList>(new FilteredCriteria(<criteria>));
// }
// catch (Exception ex)
// {
// throw new DbCslaException("Error on FigureInfoList.Get", ex);
// }
//}
public static FigureInfoList GetByROFstID(int rOFstID)
{ {
try try
{ {
@@ -180,11 +158,8 @@ namespace VEPROMS.CSLA.Library
[Serializable()] [Serializable()]
private class ROFstIDCriteria private class ROFstIDCriteria
{ {
public ROFstIDCriteria(int rOFstID) public ROFstIDCriteria(int rOFstID) => _ROFstID = rOFstID;
{ private int _ROFstID;
_ROFstID = rOFstID;
}
private int _ROFstID;
public int ROFstID public int ROFstID
{ {
get { return _ROFstID; } get { return _ROFstID; }
@@ -224,11 +199,8 @@ namespace VEPROMS.CSLA.Library
[Serializable()] [Serializable()]
private class ImageIDCriteria private class ImageIDCriteria
{ {
public ImageIDCriteria(int imageID) public ImageIDCriteria(int imageID) => _ImageID = imageID;
{ private int _ImageID;
_ImageID = imageID;
}
private int _ImageID;
public int ImageID public int ImageID
{ {
get { return _ImageID; } get { return _ImageID; }
@@ -265,41 +237,30 @@ namespace VEPROMS.CSLA.Library
} }
this.RaiseListChangedEvents = true; this.RaiseListChangedEvents = true;
} }
#endregion #endregion
#region ICustomTypeDescriptor impl #region ICustomTypeDescriptor impl
public String GetClassName() public String GetClassName() => TypeDescriptor.GetClassName(this, true);
{ return TypeDescriptor.GetClassName(this, true); } public AttributeCollection GetAttributes() => TypeDescriptor.GetAttributes(this, true);
public AttributeCollection GetAttributes() public String GetComponentName() => TypeDescriptor.GetComponentName(this, true);
{ return TypeDescriptor.GetAttributes(this, true); } public TypeConverter GetConverter() => TypeDescriptor.GetConverter(this, true);
public String GetComponentName() public EventDescriptor GetDefaultEvent() => TypeDescriptor.GetDefaultEvent(this, true);
{ return TypeDescriptor.GetComponentName(this, true); } public PropertyDescriptor GetDefaultProperty() => TypeDescriptor.GetDefaultProperty(this, true);
public TypeConverter GetConverter() public object GetEditor(Type editorBaseType) => TypeDescriptor.GetEditor(this, editorBaseType, true);
{ return TypeDescriptor.GetConverter(this, true); } public EventDescriptorCollection GetEvents(Attribute[] attributes) => TypeDescriptor.GetEvents(this, attributes, true);
public EventDescriptor GetDefaultEvent() public EventDescriptorCollection GetEvents() => TypeDescriptor.GetEvents(this, true);
{ return TypeDescriptor.GetDefaultEvent(this, true); } public object GetPropertyOwner(PropertyDescriptor pd) => this;
public PropertyDescriptor GetDefaultProperty() /// <summary>
{ return TypeDescriptor.GetDefaultProperty(this, true); } /// Called to get the properties of this type. Returns properties with certain
public object GetEditor(Type editorBaseType) /// attributes. this restriction is not implemented here.
{ return TypeDescriptor.GetEditor(this, editorBaseType, true); } /// </summary>
public EventDescriptorCollection GetEvents(Attribute[] attributes) /// <param name="attributes"></param>
{ return TypeDescriptor.GetEvents(this, attributes, true); } /// <returns></returns>
public EventDescriptorCollection GetEvents() public PropertyDescriptorCollection GetProperties(Attribute[] attributes) => GetProperties();
{ return TypeDescriptor.GetEvents(this, true); } /// <summary>
public object GetPropertyOwner(PropertyDescriptor pd) /// Called to get the properties of this type.
{ return this; } /// </summary>
/// <summary> /// <returns></returns>
/// Called to get the properties of this type. Returns properties with certain public PropertyDescriptorCollection GetProperties()
/// attributes. this restriction is not implemented here.
/// </summary>
/// <param name="attributes"></param>
/// <returns></returns>
public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{ return GetProperties(); }
/// <summary>
/// Called to get the properties of this type.
/// </summary>
/// <returns></returns>
public PropertyDescriptorCollection GetProperties()
{ {
// Create a collection object to hold property descriptors // Create a collection object to hold property descriptors
PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null); PropertyDescriptorCollection pds = new PropertyDescriptorCollection(null);
@@ -321,7 +282,6 @@ namespace VEPROMS.CSLA.Library
/// </summary> /// </summary>
public partial class FigureInfoListPropertyDescriptor : vlnListPropertyDescriptor public partial class FigureInfoListPropertyDescriptor : vlnListPropertyDescriptor
{ {
private FigureInfo Item { get { return (FigureInfo)_Item; } }
public FigureInfoListPropertyDescriptor(FigureInfoList collection, int index) : base(collection, index) { ;} public FigureInfoListPropertyDescriptor(FigureInfoList collection, int index) : base(collection, index) { ;}
} }
#endregion #endregion
@@ -330,10 +290,10 @@ namespace VEPROMS.CSLA.Library
{ {
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{ {
if (destType == typeof(string) && value is FigureInfoList) if (destType == typeof(string) && value is FigureInfoList list)
{ {
// Return department and department role separated by comma. // Return department and department role separated by comma.
return ((FigureInfoList)value).Items.Count.ToString() + " Figures"; return $"{list.Items.Count} Figures";
} }
return base.ConvertTo(context, culture, value, destType); return base.ConvertTo(context, culture, value, destType);
} }
Loaded 100 of 258 files, more files were not shown because too many files have changed in this diff. Show more