diff --git a/Ginger/Ginger/Actions/ActionEditPages/ActDataSourcePage.xaml.cs b/Ginger/Ginger/Actions/ActionEditPages/ActDataSourcePage.xaml.cs index 33df8af947..3e348b9b52 100644 --- a/Ginger/Ginger/Actions/ActionEditPages/ActDataSourcePage.xaml.cs +++ b/Ginger/Ginger/Actions/ActionEditPages/ActDataSourcePage.xaml.cs @@ -18,6 +18,7 @@ limitations under the License. using amdocs.ginger.GingerCoreNET; using Amdocs.Ginger.Common; +using Amdocs.Ginger.CoreNET.DataSource; using Ginger.UserControls; using Ginger.UserControlsLib.TextEditor.Common; using GingerCore; @@ -26,7 +27,6 @@ limitations under the License. using GingerCore.DataSource; using GingerCore.GeneralLib; using GingerCore.Helpers; -using NPOI.OpenXmlFormats.Dml; using System; using System.Collections.Generic; using System.Data; @@ -515,6 +515,7 @@ private void InitPageData() GingerCore.GeneralLib.BindingHandler.ObjFieldBinding(RowSelectorValue, ComboBox.TextProperty, mActDSTblElem, ActDSTableElement.Fields.LocateRowValue); GingerCore.GeneralLib.BindingHandler.ObjFieldBinding(ByQuery, RadioButton.IsCheckedProperty, mActDSTblElem, ActDSTableElement.Fields.ByQuery); GingerCore.GeneralLib.BindingHandler.ObjFieldBinding(QueryVal, TextBox.TextProperty, mActDSTblElem, ActDSTableElement.Fields.QueryValue); + GingerCore.GeneralLib.BindingHandler.ObjFieldBinding(cmbKeyName, ComboBox.TextProperty, mActDSTblElem, ActDSTableElement.Fields.KeyName); if (mActDSTblElem == null || (mActDSTblElem.DSName == null && mActDSTblElem.DSTableName == null) || (mActDSTblElem.DSName == "" && mActDSTblElem.DSTableName == "")) { @@ -1161,406 +1162,20 @@ private void UpdateValueExpression() ErrorLabel.Content = ""; txtValueExpression.Text = string.Empty; TextBlockHelper TBH = new TextBlockHelper(txtValueExpression); - TBH.AddText("{DS Name="); - TBH.AddBoldText(mDataSourceName); - TBH.AddText(" DST="); - TBH.AddBoldText(mDSTable.Name); - TBH.AddText(" MASD="); - - if (MarkAsDone.IsChecked == true) - { - TBH.AddBoldText("Y"); - } - else - { - TBH.AddBoldText("N"); - } - - if (ControlActionComboBox.SelectedValue != null) + if (SelectedCell.IsChecked == true) { - if (ControlActionComboBox.SelectedValue.ToString() == "ExportToExcel" && (DataSource.DSType.ToString().Equals("LiteDataBase"))) - { - TBH.AddText(" Query QUERY="); - if (mActDSTblElem.ExcelConfig == null) - { - TBH.AddBoldText(mActDSTblElem.ExcelPath + "," + mActDSTblElem.ExcelSheetName); - } - else - { - TBH.AddBoldText(mActDSTblElem.ExcelConfig.ExcelPath + "," + mActDSTblElem.ExcelConfig.ExcelSheetName); - } - - TBH.AddText("}"); - mActDSTblElem.ValueExp = TBH.GetText(); - return; - } - } - if (ByQuery.IsChecked == true) - { - TBH.AddText(" Query QUERY="); - TBH.AddBoldText(QueryVal.Text); - TBH.AddText("}"); - mActDSTblElem.ValueExp = TBH.GetText(); - return; - } - - if (mDSTable.DSTableType == DataSourceTable.eDSTableType.GingerKeyValue) - { - TBH.AddText(" Query QUERY="); - TBH.AddText("db." + mDSTable.Name); - mActDSTblElem.IsKeyValueTable = true; - if (ControlActionComboBox.SelectedValue != null) - { - if (ControlActionComboBox.SelectedValue.ToString() == ActDSTableElement.eControlAction.GetValue.ToString()) - { - if (cmbKeyName.SelectedItem == null) - { - TBH.AddText(".select GINGER_KET_VALUE where GINGER_KEY_NAME=\"" + cmbKeyName.Text + "\""); - } - else - { - TBH.AddText(".select GINGER_KEY_VALUE where GINGER_KEY_NAME=\"" + cmbKeyName.SelectedItem.ToString() + "\""); - } - } - - else if (ControlActionComboBox.SelectedValue.ToString() == ActDSTableElement.eControlAction.SetValue.ToString()) - { - if (cmbKeyName.SelectedItem == null) - { - TBH.AddText(".update GINGER_KEY_VALUE = \"" + mActDSTblElem.ValueUC + "\" where GINGER_KEY_NAME=\"" + cmbKeyName.Text + "\""); - } - else - { - TBH.AddText(".update GINGER_KEY_VALUE = \"" + mActDSTblElem.ValueUC + "\" where GINGER_KEY_NAME=\"" + cmbKeyName.SelectedItem.ToString() + "\""); - } - } - else if (ControlActionComboBox.SelectedValue.ToString() == ActDSTableElement.eControlAction.DeleteRow.ToString()) - { - if (cmbKeyName.SelectedItem == null) - { - TBH.AddBoldText(".delete GINGER_KEY_NAME=\"" + cmbKeyName.Text + "\""); - } - else - { - TBH.AddText(".delete GINGER_KEY_NAME=\"" + cmbKeyName.SelectedItem.ToString() + "\""); - } - - } - else if (ControlActionComboBox.SelectedValue.ToString() == ActDSTableElement.eControlAction.RowCount.ToString()) - { - TBH.AddBoldText(".count"); - TBH.AddText("}"); - mActDSTblElem.ValueExp = TBH.GetText(); - - return; - } - else if (ControlActionComboBox.SelectedValue.ToString() == ActDSTableElement.eControlAction.AddRow.ToString()) - { - TBH.AddBoldText(".insert"); - TBH.AddText("}"); - mActDSTblElem.ValueExp = TBH.GetText(); - - return; - } - } - TBH.AddText("}"); - mActDSTblElem.ValueExp = TBH.GetText(); - return; - } - else if (Customized.IsChecked == true) - { - mActDSTblElem.IsKeyValueTable = false; - TBH.AddText(" IDEN=Cust ICOLVAL="); - if (cmbColumnValue.SelectedIndex != -1) - { - TBH.AddBoldText(cmbColumnValue.SelectedItem.ToString()); - } - else - { - TBH.AddBoldText(cmbColumnValue.Text); - } - - TBH.AddText(" IROW="); - if (RowNum.IsChecked == true) - { - TBH.AddUnderLineText("RowNum"); - TBH.AddText(" ROWNUM="); - if (RowSelectorValue.SelectedIndex != -1) - { - TBH.AddBoldText(RowSelectorValue.SelectedItem.ToString()); - } - else - { - TBH.AddBoldText(RowSelectorValue.Text); - } - } - else if (NextAvailable.IsChecked == true) - { - TBH.AddUnderLineText("NxtAvail"); - } - else if (Where.IsChecked == true) - { - TBH.AddUnderLineText("Where"); - - // - TBH.AddText(" COND="); - for (int i = 0; i < mActDSTblElem.WhereConditions.Count; i++) - { - string wQuery = ""; - string wCond = mActDSTblElem.WhereConditions[i].wCondition.ToString(); - string wColVal = "[" + mActDSTblElem.WhereConditions[i].wTableColumn.ToString().Trim() + "]"; - string wOpr = mActDSTblElem.WhereConditions[i].wOperator.ToString(); - string wRowVal = mActDSTblElem.WhereConditions[i].wValue.ToString(); - if (wRowVal.IndexOf("{DS Name") == -1) - { - wRowVal = wRowVal.Replace("'", "''"); - } - - if (wCond == "EMPTY") - { - wCond = ""; - } - - if (wOpr == "Equals") - { - if (wColVal == "[GINGER_ID]") - { - wQuery = wQuery + " " + wCond + " " + wColVal + " = " + wRowVal; - } - else - { - wQuery = wQuery + " " + wCond + " " + wColVal + " = '" + wRowVal + "'"; - } - } - else if (wOpr == "NotEquals") - { - if (wColVal == "[GINGER_ID]") - { - wQuery = wQuery + " " + wCond + " " + wColVal + " <> " + wRowVal; - } - else - { - wQuery = wQuery + " " + wCond + " " + wColVal + " <> '" + wRowVal + "'"; - } - } - else if (wOpr == "Contains") - { - wQuery = wQuery + " " + wCond + " " + wColVal + " contains " + "\"" + wRowVal + "\""; - } - //else if (wOpr == "NotContains") - // wQuery = wQuery + " " + wCond + " " + wColVal + " not contains " + "\"" + wRowVal + "\""; - else if (wOpr == "StartsWith") - { - wQuery = wQuery + " " + wCond + " " + wColVal + " like " + "\"" + wRowVal + "\""; - } - //else if (wOpr == "NotStartsWith") - // wQuery = wQuery + " " + wCond + " " + wColVal + " ! like + "\"" + wRowVal + "\""; - //else if (wOpr == "EndsWith") - // wQuery = wQuery + " " + wCond + " " + wColVal + " LIKE '%" + wRowVal + "'"; - //else if (wOpr == "NotEndsWith") - // wQuery = wQuery + " " + wCond + " " + wColVal + " NOT LIKE '%" + wRowVal + "'"; - //else if (wOpr == "IsNull") - // wQuery = wQuery + " " + wCond + " " + wColVal + " IS NULL"; - //else if (wOpr == "IsNotNull") - // wQuery = wQuery + " " + wCond + " " + wColVal + " IS NOT NULL"; - - TBH.AddBoldText(wQuery); - } - } - TBH.AddText(" Query QUERY="); - - TBH.AddText("db." + mDSTable.Name); - //Get ColunmNA - if (cmbColumnValue.SelectedIndex != -1) + TBH.AddText("{DS Name="); + TBH.AddBoldText(mDataSourceName); + TBH.AddText(" DST="); + if (MarkAsDone.IsChecked == true) { - mActDSTblElem.LocateColTitle = cmbColumnValue.SelectedItem.ToString(); + TBH.AddBoldText("Y"); } else { - mActDSTblElem.LocateColTitle = cmbColumnValue.Text; + TBH.AddBoldText("N"); } - //add operation - if (ControlActionComboBox.SelectedValue != null) - { - if (ControlActionComboBox.SelectedValue.ToString() == "GetValue") - { - if (Where.IsChecked == true) - { - TBH.AddBoldText(".select $ where "); - } - else - { - TBH.AddBoldText(".find"); - } - } - else if (ControlActionComboBox.SelectedValue.ToString() == "SetValue") - { - TBH.AddBoldText(".update "); - } - else if (ControlActionComboBox.SelectedValue.ToString() == "DeleteRow") - { TBH.AddBoldText(".delete"); } - else if (ControlActionComboBox.SelectedValue.ToString() == "RowCount") - { - TBH.AddBoldText(".count"); - TBH.AddText("}"); - mActDSTblElem.ValueExp = TBH.GetText(); - - return; - } - else if (ControlActionComboBox.SelectedValue.ToString() == "AvailableRowCount") - { - TBH.AddBoldText(".find GINGER_USED= \"False\""); - TBH.AddText("}"); - mActDSTblElem.ValueExp = TBH.GetText(); - - return; - } - else if (ControlActionComboBox.SelectedValue.ToString() == "MarkAsDone") - { - TBH.AddBoldText(".update GINGER_USED= \"True\""); - } - else if (ControlActionComboBox.SelectedValue.ToString() == "DeleteAll") - { - TBH.AddBoldText(".delete"); - TBH.AddText("}"); - mActDSTblElem.ValueExp = TBH.GetText(); - return; - } - else if (ControlActionComboBox.SelectedValue.ToString() == "MarkAllUnUsed") - { - TBH.AddBoldText(".update GINGER_USED= \"False\" "); - TBH.AddText("}"); - mActDSTblElem.ValueExp = TBH.GetText(); - - return; - } - else if (ControlActionComboBox.SelectedValue.ToString() == "MarkAllUsed") - { - TBH.AddBoldText(".update GINGER_USED= \"True\""); - TBH.AddText("}"); - mActDSTblElem.ValueExp = TBH.GetText(); - - return; - } - - // next where / other condition - if (Customized.IsChecked == true) - { - if (NextAvailable.IsChecked == true) - { - if (ControlActionComboBox.SelectedValue.ToString() == "SetValue") - { - if (cmbColumnValue.SelectedIndex != -1) - { - TBH.AddBoldText(cmbColumnValue.SelectedItem.ToString() + " = \"" + mActDSTblElem.ValueUC + "\" where GINGER_USED =\"False\""); - } - else - { - string col = cmbColumnValue.Text; - TBH.AddBoldText(col + " = \"" + mActDSTblElem.ValueUC + "\" where GINGER_USED =\"False\""); - } - - } - else if (ControlActionComboBox.SelectedValue.ToString() != "MarkAsDone") - { - TBH.AddBoldText(" GINGER_USED =\"False\""); - } - } - else if (RowNum.IsChecked == true) - { - if (ControlActionComboBox.SelectedValue.ToString() == "SetValue") - { - if (cmbColumnValue.SelectedIndex != -1) - { - TBH.AddBoldText(cmbColumnValue.SelectedItem.ToString() + " = \"" + mActDSTblElem.ValueUC + "\""); - } - else - { - string col = cmbColumnValue.Text; - TBH.AddBoldText(col + " = \"" + mActDSTblElem.ValueUC + "\""); - } - } - } - else if (Where.IsChecked == true) - { - mActDSTblElem.ByWhere = true; - if (ControlActionComboBox.SelectedValue.ToString() == "SetValue") - { - if (cmbColumnValue.SelectedIndex != -1) - { - TBH.AddBoldText(cmbColumnValue.SelectedItem.ToString() + " = \"" + mActDSTblElem.ValueUC + "\" where"); - } - else - { - string col = cmbColumnValue.Text; - TBH.AddBoldText(col + " = \"" + mActDSTblElem.ValueUC + "\" where"); - } - - } - for (int i = 0; i < mActDSTblElem.WhereConditions.Count; i++) - { - string wQuery = ""; - string wCond = mActDSTblElem.WhereConditions[i].wCondition.ToString().ToLower(); - string wColVal = mActDSTblElem.WhereConditions[i].wTableColumn.ToString().Trim(); - string wOpr = mActDSTblElem.WhereConditions[i].wOperator.ToString(); - string wRowVal = mActDSTblElem.WhereConditions[i].wValue.ToString(); - - if (wCond == "empty") - { - wCond = ""; - } - - if (wOpr == "Equals") - { - if (wColVal == "GINGER_ID") - { - wQuery = wQuery + " " + wCond + " " + wColVal + " = " + wRowVal; - } - else - { - wQuery = wQuery + " " + wCond + " " + wColVal + " = \"" + wRowVal + "\""; - } - } - else if (wOpr == "NotEquals") - { - if (wColVal == "GINGER_ID") - { - wQuery = wQuery + " " + wCond + " " + wColVal + " != " + wRowVal; - } - else - { - wQuery = wQuery + " " + wCond + " " + wColVal + " != \"" + wRowVal + "\""; - } - } - else if (wOpr == "Contains") - { - wQuery = wQuery + " " + wCond + " " + wColVal + " contains " + "\"" + wRowVal + "\""; - } - //else if (wOpr == "NotContains") - // wQuery = wQuery + " " + wCond + " " + wColVal + " not contains " + "\"" + wRowVal + "\""; - else if (wOpr == "StartsWith") - { - wQuery = wQuery + " " + wCond + " " + wColVal + " like " + "\"" + wRowVal + "\""; - } - //else if (wOpr == "NotStartsWith") - // wQuery = wQuery + " " + wCond + " " + wColVal + " ! like " + "\"" + wRowVal + "\""; - //else if (wOpr == "EndsWith") - // wQuery = wQuery + " " + wCond + " " + wColVal + " LIKE '%" + wRowVal + "'"; - //else if (wOpr == "NotEndsWith") - // wQuery = wQuery + " " + wCond + " " + wColVal + " NOT LIKE '%" + wRowVal + "'"; - //else if (wOpr == "IsNull") - // wQuery = wQuery + " " + wCond + " " + wColVal + " IS NULL"; - //else if (wOpr == "IsNotNull") - // wQuery = wQuery + " " + wCond + " " + wColVal + " IS NOT NULL"; - TBH.AddText(wQuery); - } - } - } - } - } - else if (SelectedCell.IsChecked == true) - { TBH.AddText(" Query QUERY="); mActDSTblElem.BySelectedCell = true; List SelectedItemsList = new List(); @@ -1571,22 +1186,31 @@ private void UpdateValueExpression() } else { - SelectedItemsList = grdTableData.Grid.SelectedCells.Cast().ToList(); + SelectedItemsList = grdTableData?.Grid?.SelectedCells?.Cast()?.ToList(); string selColName = ((DataGridCellInfo)SelectedItemsList[0]).Column.Header.ToString(); selColName = selColName.Replace("__", "_"); string SelCellGingerId = ((DataRowView)((DataGridCellInfo)SelectedItemsList[0]).Item).Row["GINGER_ID"].ToString(); + // "db." + mDSTable.Name + ".select $." + selColName + " where GINGER_ID=" + SelCellGingerId + + //TBH.AddText($"SELECT {selColName} FROM {mDSTable.Name} where GINGER_ID = {SelCellGingerId}"); TBH.AddText("db." + mDSTable.Name + ".select $." + selColName + " where GINGER_ID=" + SelCellGingerId); mActDSTblElem.VarName = selColName; } + TBH.AddText("}"); + mActDSTblElem.ValueExp = TBH.GetText(); + } + else + { + LiteDBSQLTranslator liteDBSQLTranslator = new(mActDSTblElem); + string calculatedValueExpression = mActDSTblElem.ValueExp = liteDBSQLTranslator.CreateValueExpression(); + TBH.AddText(calculatedValueExpression); } if (mDSTable.DSTableType == DataSourceTable.eDSTableType.GingerKeyValue) { mActDSTblElem.MarkUpdate = false; } - TBH.AddText("}"); - mActDSTblElem.ValueExp = TBH.GetText(); } } diff --git a/Ginger/Ginger/Ginger.csproj b/Ginger/Ginger/Ginger.csproj index b2facb2b66..1204b3fd52 100644 --- a/Ginger/Ginger/Ginger.csproj +++ b/Ginger/Ginger/Ginger.csproj @@ -665,7 +665,7 @@ - + diff --git a/Ginger/Ginger/Run/RunSetsExecutionsHistoryPage.xaml.cs b/Ginger/Ginger/Run/RunSetsExecutionsHistoryPage.xaml.cs index b6f470bd40..65497d2154 100644 --- a/Ginger/Ginger/Run/RunSetsExecutionsHistoryPage.xaml.cs +++ b/Ginger/Ginger/Run/RunSetsExecutionsHistoryPage.xaml.cs @@ -253,8 +253,7 @@ private void DeleteExecutionReports(System.Collections.IList runSetReports) { LiteDbManager dbManager = new LiteDbManager(executionLoggerHelper.GetLoggerDirectory(WorkSpace.Instance.Solution.LoggerConfigurations.CalculatedLoggerFolder)); var result = dbManager.GetRunSetLiteData(); - List filterData = null; - filterData = result.IncludeAll().Find(a => a._id.ToString() == runSetReport.GUID).ToList(); + List filterData = LiteDbRunSet.IncludeAllReferences(result).Find(a => a._id.Equals(new LiteDB.ObjectId(runSetReport.GUID))).ToList(); LiteDbConnector dbConnector = new LiteDbConnector(Path.Combine(mRunSetExecsRootFolder, "GingerExecutionResults.db")); dbConnector.DeleteDocumentByLiteDbRunSet(filterData[0]); diff --git a/Ginger/Ginger/RunSetPageLib/RunnerPage.xaml.cs b/Ginger/Ginger/RunSetPageLib/RunnerPage.xaml.cs index 4d39778f4e..62c7f3ca98 100644 --- a/Ginger/Ginger/RunSetPageLib/RunnerPage.xaml.cs +++ b/Ginger/Ginger/RunSetPageLib/RunnerPage.xaml.cs @@ -433,7 +433,7 @@ private void GenerateBFReport(BusinessFlow bf) LiteDbManager dbManager = new LiteDbManager(WorkSpace.Instance.Solution.SolutionOperations.ConvertSolutionRelativePath(WorkSpace.Instance.Solution.LoggerConfigurations.CalculatedLoggerFolder)); var result = dbManager.GetRunSetLiteData(); - List filterData = dbManager.FilterCollection(result, Query.All()); + List filterData = dbManager.FilterCollection(LiteDbRunSet.IncludeAllReferences(result), Query.All()); LiteDbRunSet runSetLast = filterData.Last(); //runSetLast._id = new ObjectId(); @@ -466,7 +466,7 @@ private void GenerateBFReport(BusinessFlow bf) } catch (Exception ex) { - + Reporter.ToLog(eLogLevel.ERROR, "Failed to generate business flow report", ex); } } diff --git a/Ginger/GingerCoreCommon/GingerCoreCommon.csproj b/Ginger/GingerCoreCommon/GingerCoreCommon.csproj index c8a3f11603..67eb6ff60b 100644 --- a/Ginger/GingerCoreCommon/GingerCoreCommon.csproj +++ b/Ginger/GingerCoreCommon/GingerCoreCommon.csproj @@ -34,7 +34,7 @@ - + diff --git a/Ginger/GingerCoreNET/DataSource/ActDSTableElement.cs b/Ginger/GingerCoreNET/DataSource/ActDSTableElement.cs index 25c8cd621c..ba8479b359 100644 --- a/Ginger/GingerCoreNET/DataSource/ActDSTableElement.cs +++ b/Ginger/GingerCoreNET/DataSource/ActDSTableElement.cs @@ -18,13 +18,11 @@ limitations under the License. using amdocs.ginger.GingerCoreNET; using Amdocs.Ginger.Common; -using Amdocs.Ginger.Common.Enums; using Amdocs.Ginger.Common.InterfacesLib; using Amdocs.Ginger.CoreNET.DataSource; using Amdocs.Ginger.Repository; using GingerCore.DataSource; using GingerCoreNET.SolutionRepositoryLib.RepositoryObjectsLib.PlatformsLib; -using NPOI.SS.Formula.Functions; using System; using System.Collections.Generic; using System.Data; @@ -86,6 +84,16 @@ public override void Execute() if (DataSource.DSType == DataSourceBase.eDSType.LiteDataBase) { GingerCoreNET.DataSource.GingerLiteDB liteDB = new GingerCoreNET.DataSource.GingerLiteDB(); + string value = GetInputParamValue("Value"); + if (!string.IsNullOrEmpty(value)) + { + ValueExpression mValueExpression = new(WorkSpace.Instance.RunsetExecutor.RunsetExecutionEnvironment, RunOnBusinessFlow, WorkSpace.Instance.SolutionRepository.GetAllRepositoryItems()); + mValueExpression.Value = value; + ValueUC = mValueExpression.ValueCalculated; + } + + LiteDBSQLTranslator liteDBSQLTranslator = new (this); + this.ValueExp = liteDBSQLTranslator.CreateValueExpression(); string Query = ValueExp.Substring(ValueExp.IndexOf("QUERY=") + 6, ValueExp.Length - (ValueExp.IndexOf("QUERY=") + 7)); liteDB.FileFullPath = WorkSpace.Instance.Solution.SolutionOperations.ConvertSolutionRelativePath(DataSource.FileFullPath); @@ -281,6 +289,24 @@ public override void Execute() } + + private string mKeyName; + [IsSerializedForLocalRepository] + public string KeyName + { + get + { + return mKeyName; + } + set + { + if(!string.Equals(mKeyName , value)) + { + mKeyName = value; + OnPropertyChanged(nameof(KeyName)); + } + } + } private eControlAction mControlAction; [IsSerializedForLocalRepository] public eControlAction ControlAction diff --git a/Ginger/GingerCoreNET/DataSource/LiteDB.cs b/Ginger/GingerCoreNET/DataSource/LiteDB.cs index 8175ad058b..4e11841e07 100644 --- a/Ginger/GingerCoreNET/DataSource/LiteDB.cs +++ b/Ginger/GingerCoreNET/DataSource/LiteDB.cs @@ -36,85 +36,18 @@ namespace GingerCoreNET.DataSource public class GingerLiteDB : DataSourceBase { int count = 1; - private LiteDatabase _database; - - private LiteDatabase Database - { - get => _database; - set - { - if (_database != value) - { - _database = value; - FillDataGridView(null); - } - } - } - public void FillDataGridView(IEnumerable documents) + private string ConnectionString { - if (documents != null) + get { - var dt = new LiteDataTable(documents.ToString()); - foreach (var doc in documents) - { - var dr = dt.NewRow() as LiteDataRow; - if (dr != null) - { - dr.UnderlyingValue = doc; - foreach (var property in doc.RawValue) - { - if (!property.Value.IsMaxValue && !property.Value.IsMinValue) - { - if (!dt.Columns.Contains(property.Key)) - { - dt.Columns.Add(new DataColumn(property.Key, typeof(string))); - } - switch (property.Value.Type) - { - case BsonType.Null: - dr[property.Key] = "[NULL]"; - break; - case BsonType.Document: - dr[property.Key] = property.Value.AsDocument.RawValue.ContainsKey("_type") - ? $"[OBJECT: {property.Value.AsDocument.RawValue["_type"]}]" - : "[OBJECT]"; - break; - case BsonType.Array: - dr[property.Key] = $"[ARRAY({property.Value.AsArray.Count})]"; - break; - case BsonType.Binary: - dr[property.Key] = $"[BINARY({property.Value.AsBinary.Length})]"; - break; - case BsonType.DateTime: - dr[property.Key] = property.Value.AsDateTime.ToString("yyyy-MM-dd HH:mm:ss.fff"); - break; - case BsonType.String: - dr[property.Key] = property.Value.AsString; - break; - case BsonType.Int32: - case BsonType.Int64: - dr[property.Key] = property.Value.AsInt64.ToString(); - break; - case BsonType.Decimal: - case BsonType.Double: - dr[property.Key] = property.Value.AsDecimal.ToString(CultureInfo.InvariantCulture); - break; - default: - dr[property.Key] = property.Value.ToString(); - break; - } - } - } - dt.Rows.Add(dr); - } - } + return $"filename={FileFullPath}; connection=Shared; upgrade=true"; } } public override void AddColumn(string tableName, string columnName, string columnType) { try { - using (var db = new LiteDatabase(FileFullPath)) + using (var db = new LiteDatabase(ConnectionString)) { var results = db.GetCollection(tableName).Find(Query.All(), 0).ToList(); var table = db.GetCollection(tableName); @@ -133,7 +66,7 @@ public override void AddColumn(string tableName, string columnName, string colum public override void AddTable(string tableName, string columnList = "") { - using (var db = new LiteDatabase(FileFullPath)) + using (var db = new LiteDatabase(ConnectionString)) { var table = db.GetCollection(tableName); @@ -169,115 +102,78 @@ public override string CopyTable(string tableName) } if (CopyTableName != tableName) { - using (var db = new LiteDatabase(FileFullPath)) + using (var db = new LiteDatabase(ConnectionString)) { var CopyTable = db.GetCollection(CopyTableName); var table = db.GetCollection(tableName); DataTable dtChange = new DataTable(CopyTableName); - dtChange = datatable(tableName, CopyTableName); - SaveTable(dtChange); + dtChange = datatable(table.FindAll() , CopyTableName); + SaveTable(dtChange , CopyTable); } } return CopyTableName; } - public DataTable datatable(string tableName, string CopyTableName = null) + public DataTable datatable(IEnumerable results , string CopyTableName = null) { - using (var db = new LiteDatabase(FileFullPath)) + if (CopyTableName == null) { - var results = db.GetCollection(tableName).Find(Query.All(), 0); - if (CopyTableName == null) - { - CopyTableName = results.ToString(); - } - var dt = new LiteDataTable(CopyTableName); - foreach (var doc in results) + CopyTableName = results.ToString(); + } + var dt = new LiteDataTable(CopyTableName); + foreach (var doc in results) + { + var dr = dt.NewRow() as LiteDataRow; + if (dr != null) { - var dr = dt.NewRow() as LiteDataRow; - if (dr != null) + dr.UnderlyingValue = doc; + foreach (var property in doc.RawValue) { - dr.UnderlyingValue = doc; - foreach (var property in doc.RawValue) + if (!property.Value.IsMaxValue && !property.Value.IsMinValue) { - if (!property.Value.IsMaxValue && !property.Value.IsMinValue) + if (!dt.Columns.Contains(property.Key)) { - if (!dt.Columns.Contains(property.Key)) - { - dt.Columns.Add(property.Key, typeof(string)); + dt.Columns.Add(property.Key, typeof(string)); - } - switch (property.Value.Type) - { - case BsonType.Null: - dr[property.Key] = "[NULL]"; - break; - case BsonType.Document: - dr[property.Key] = property.Value.AsDocument.RawValue.ContainsKey("_type") - ? $"[OBJECT: {property.Value.AsDocument.RawValue["_type"]}]" - : "[OBJECT]"; - break; - case BsonType.Array: - dr[property.Key] = $"[ARRAY({property.Value.AsArray.Count})]"; - break; - case BsonType.Binary: - dr[property.Key] = $"[BINARY({property.Value.AsBinary.Length})]"; - break; - case BsonType.DateTime: - dr[property.Key] = property.Value.AsDateTime.ToString("yyyy-MM-dd HH:mm:ss.fff"); - break; - case BsonType.String: - dr[property.Key] = property.Value.AsString; - break; - case BsonType.Int32: - case BsonType.Int64: - dr[property.Key] = property.Value.AsInt64.ToString(); - break; - case BsonType.Decimal: - case BsonType.Double: - dr[property.Key] = property.Value.AsDecimal.ToString(CultureInfo.InvariantCulture); - break; - default: - dr[property.Key] = property.Value.ToString(); - break; - } - string ads = property.Key.ToString(); - if (ads == "GINGER_ID") - { - if (property.Value.AsString == "") - { - dr[property.Key] = count.ToString(); - count++; - } - } - else + } + SetDataRow(dr, property); + string ads = property.Key.ToString(); + if (ads == "GINGER_ID") + { + if (property.Value.ToString() == "") { - dr[property.Key] = property.Value.AsString; + dr[property.Key] = count.ToString(); + count++; } - if (ads == "GINGER_USED") + } + else + { + dr[property.Key] = property.Value.RawValue.ToString(); + } + if (ads == "GINGER_USED") + { + if (property.Value.RawValue.ToString() == "") { - if (property.Value.AsString == "") - { - dr[property.Key] = "False"; - } + dr[property.Key] = "False"; } } } - dt.Rows.Add(dr.ItemArray); } + dt.Rows.Add(dr.ItemArray); } - // converting Litedatatable to Datatable - DataTable dttable = dt; - dttable.Rows.Add(dt.Rows); - dttable.TableName = CopyTableName; - return dttable; } + // converting Litedatatable to Datatable + DataTable dttable = dt; + dttable.Rows.Add(dt.Rows); + dttable.TableName = CopyTableName; + return dttable; } public override void DeleteTable(string tableName) { - using (var db = new LiteDatabase(FileFullPath)) + using (var db = new LiteDatabase(ConnectionString)) { db.DropCollection(tableName); } @@ -292,9 +188,9 @@ public override bool ExporttoExcel(string TableName, string sExcelPath, string s dataTable = GetQueryOutput(TableName); var whereCond = string.Empty; var selectedColumn = string.Empty; - if (sTableQueryValue.ToLower().Contains(" where ")) + if (sTableQueryValue.Contains(" where ")) { - var index = sTableQueryValue.ToLower().IndexOf(" where "); + var index = sTableQueryValue.IndexOf(" where "); whereCond = sTableQueryValue.Substring(index); selectedColumn = sTableQueryValue.Substring(0, index); @@ -326,99 +222,73 @@ public override bool ExporttoExcel(string TableName, string sExcelPath, string s public override List GetColumnList(string tableName) { - List mColumnNames = new List(); - - using (var db = new LiteDatabase(FileFullPath)) + List mColumnNames = new (); + using (var db = new LiteDatabase(ConnectionString)) { if (tableName == "") { return mColumnNames; } var results = db.GetCollection(tableName).Find(Query.All(), 0).ToList(); - var dt = new LiteDataTable(results.ToString()); - foreach (var doc in results) + mColumnNames = GetColumnList(results, tableName); + //var name = mColumnNames.RemoveAll(i => i.Contains("Name")); Commented this as we are not able to see columnNames which contain "Name" keyword in it. + + } + return mColumnNames; + } + + private List GetColumnList(IList results , string tableName) + { + var dt = new LiteDataTable(results.ToString()); + List mColumnNames = new (); + + foreach (var doc in results) + { + var dr = dt.NewRow() as LiteDataRow; + if (dr != null) { - var dr = dt.NewRow() as LiteDataRow; - if (dr != null) + dr.UnderlyingValue = doc; + foreach (var property in doc.RawValue) { - dr.UnderlyingValue = doc; - foreach (var property in doc.RawValue) + if (!property.Value.IsMaxValue && !property.Value.IsMinValue) { - if (!property.Value.IsMaxValue && !property.Value.IsMinValue) + if (!dt.Columns.Contains(property.Key)) { - if (!dt.Columns.Contains(property.Key)) - { - dt.Columns.Add(property.Key, typeof(string)); - mColumnNames.Add(dt.Columns.ToString()); - } - switch (property.Value.Type) - { - case BsonType.Null: - dr[property.Key] = "[NULL]"; - break; - case BsonType.Document: - dr[property.Key] = property.Value.AsDocument.RawValue.ContainsKey("_type") - ? $"[OBJECT: {property.Value.AsDocument.RawValue["_type"]}]" - : "[OBJECT]"; - break; - case BsonType.Array: - dr[property.Key] = $"[ARRAY({property.Value.AsArray.Count})]"; - break; - case BsonType.Binary: - dr[property.Key] = $"[BINARY({property.Value.AsBinary.Length})]"; - break; - case BsonType.DateTime: - dr[property.Key] = property.Value.AsDateTime.ToString("yyyy-MM-dd HH:mm:ss.fff"); - break; - case BsonType.String: - dr[property.Key] = property.Value.AsString; - break; - case BsonType.Int32: - case BsonType.Int64: - dr[property.Key] = property.Value.AsInt64.ToString(); - break; - case BsonType.Decimal: - case BsonType.Double: - dr[property.Key] = property.Value.AsDecimal.ToString(CultureInfo.InvariantCulture); - break; - default: - dr[property.Key] = property.Value.ToString(); - break; - } - string ads = property.Key.ToString(); - if (ads == "GINGER_ID") - { - if (property.Value.AsString == "") - { - dr[property.Key] = count.ToString(); - count++; - } + dt.Columns.Add(property.Key, typeof(string)); + mColumnNames.Add(dt.Columns.ToString()); + } - } - else + SetDataRow(dr, property); + string ads = property.Key.ToString(); + if (ads == "GINGER_ID") + { + if (property.Value.ToString() == "") { - dr[property.Key] = property.Value.AsString; + dr[property.Key] = count.ToString(); + count++; } } + else + { + dr[property.Key] = property.Value.RawValue == null ? string.Empty : property.Value.RawValue.ToString(); + } } - dt.Rows.Add(dr.ItemArray); } + dt.Rows.Add(dr.ItemArray); } - DataTable aa = dt; - aa.TableName = tableName; + } + DataTable aa = dt; + aa.TableName = tableName; - foreach (DataColumn column in aa.Columns) + foreach (DataColumn column in aa.Columns) + { + if (column.ColumnName != "System.Data.DataColumnCollection") { - if (column.ColumnName != "System.Data.DataColumnCollection") - { - mColumnNames.Add(column.ToString()); - } + mColumnNames.Add(column.ToString()); } - - var itemToRemove = mColumnNames.RemoveAll(x => x.Contains("System.Data.DataColumnCollection")); - var s = mColumnNames.RemoveAll(a => a.Contains("_id")); - //var name = mColumnNames.RemoveAll(i => i.Contains("Name")); Commented this as we are not able to see columnNames which contain "Name" keyword in it. - } + + var itemToRemove = mColumnNames.RemoveAll(x => x.Contains("System.Data.DataColumnCollection")); + var s = mColumnNames.RemoveAll(a => a.Contains("_id")); return mColumnNames; } @@ -434,7 +304,7 @@ public String GetQueryOutput(string query, string col, int rownumber, bool mark if (mark) { string rowID = row["GINGER_ID"].ToString(); - datatble = GetQueryOutput("db." + DSTableName + ".update GINGER_USED = \"True\" where GINGER_ID= " + rowID); + GetQueryOutput($"UPDATE {DSTableName} SET GINGER_USED = \"True\" where GINGER_ID = {rowID}"); } returnVal = Convert.ToString(row[col]); } @@ -450,7 +320,7 @@ public override DataTable GetQueryOutput(string query) List mColumnNames = new List(); DataTable dataTable = new DataTable(); bool duplicate = false; - using (var db = new LiteDatabase(FileFullPath)) + using (var db = new LiteDatabase(ConnectionString)) { var results = db.GetCollection(query).Find(Query.All(), 0).ToList(); try @@ -474,17 +344,25 @@ public override DataTable GetQueryOutput(string query) { dt.Columns.Add(property.Key, typeof(string)); } - if (property.Value.AsString == "System.Collections.Generic.Dictionary`2[System.String,BsonValue]" || property.Value.AsString == "System.Collections.Generic.Dictionary`2[System.String,LiteDB.BsonValue]") + if(property.Value.RawValue != null) { - dr[property.Key] = ""; - } - else if (property.Value.AsString == "System.Data.DataRowCollection" || property.Value.AsString == "System.Collections.Generic.Dictionary`2[System.String,LiteDB.BsonValue]") - { - duplicate = true; + if (property.Value.RawValue.ToString() == "System.Collections.Generic.Dictionary`2[System.String,BsonValue]" || property.Value.RawValue.ToString() == "System.Collections.Generic.Dictionary`2[System.String,LiteDB.BsonValue]") + { + dr[property.Key] = ""; + } + else if (property.Value.RawValue.ToString() == "System.Data.DataRowCollection" || property.Value.RawValue.ToString() == "System.Collections.Generic.Dictionary`2[System.String,LiteDB.BsonValue]") + { + duplicate = true; + } + else + { + dr[property.Key] = property.Value.RawValue.ToString(); + } } else { - dr[property.Key] = property.Value.AsString; + dr[property.Key] = string.Empty; + } } } @@ -533,14 +411,14 @@ public override DataTable GetQueryOutput(string query) // If we need to run a direct query try { - var resultdxs = db.Engine.Run(query); - // Converting BSON to JSON - JArray array = new JArray(); - foreach (BsonValue bs in db.Engine.Run(query)) + JArray array = new (); + // This query needs SQL Command + BsonValue[] result = db.Execute(query).ToArray(); + foreach (BsonValue bs in result) { - string js = LiteDB.JsonSerializer.Serialize(bs, true, true); - if (js == "0") + string js = LiteDB.JsonSerializer.Serialize(bs); + if (js == "0" || js == "1") { return dataTable; } @@ -609,12 +487,15 @@ public override DataTable GetQueryOutput(string query) catch (Exception ex) { Reporter.ToLog(eLogLevel.WARN, "Exception Occurred while doing LiteDB GetQueryOutput", ex); + db.Dispose(); } } } catch (Exception ex) { Reporter.ToLog(eLogLevel.ERROR, "Exception Occurred while doing LiteDB GetQueryOutput", ex); + db.Dispose(); + } } dataTable.AcceptChanges(); @@ -654,7 +535,7 @@ public override ObservableList GetTablesList() { DataTable Datatable = new DataTable(); ObservableList mDataSourceTableDetails = new ObservableList(); - using (var db = new LiteDatabase(FileFullPath)) + using (var db = new LiteDatabase(ConnectionString)) { IEnumerable Tables = db.GetCollectionNames(); foreach (string table in Tables) @@ -675,7 +556,7 @@ public override ObservableList GetTablesList() { dt.Columns.Add(property.Key, typeof(string)); } - dr[property.Key] = property.Value.AsString; + dr[property.Key] = property.Value.RawValue == null ? string.Empty : property.Value.RawValue.ToString(); } } dt.Rows.Add(dr); @@ -690,21 +571,13 @@ public override ObservableList GetTablesList() } public override bool IsTableExist(string tableName) { - using (var db = new LiteDatabase(FileFullPath)) - { - IEnumerable Tables = db.GetCollectionNames(); - foreach (string table in Tables) - { - if (tableName == table) - { return true; } - } - } - return false; + using var db = new LiteDatabase(ConnectionString); + return db.CollectionExists(tableName); } public override void RemoveColumn(string tableName, string columnName) { - using (var db = new LiteDatabase(FileFullPath)) + using (var db = new LiteDatabase(ConnectionString)) { var results = db.GetCollection(tableName).Find(Query.All(), 0).ToList(); var table = db.GetCollection(tableName); @@ -722,7 +595,7 @@ public override void RenameTable(string tableName, string newTableName) bool tableExist = false; try { - using (var db = new LiteDatabase(FileFullPath)) + using (var db = new LiteDatabase(ConnectionString)) { tableExist = db.CollectionExists(newTableName); if (!tableExist) @@ -747,9 +620,10 @@ public override void RenameTable(string tableName, string newTableName) public override bool RunQuery(string query) { - using (LiteDatabase db = new LiteDatabase(FileFullPath)) + using (LiteDatabase db = new LiteDatabase(ConnectionString)) { - var result = db.Engine.Run(query); + // SQL Command needed here: + var result = db.Execute(query); } return true; @@ -757,7 +631,8 @@ public override bool RunQuery(string query) public void RunQuery(string query, int LocateRowValue, string DSTableName, bool MarkUpdate = false, bool NextAvai = false) { - DataTable dt = GetQueryOutput("db." + DSTableName + ".find"); + //db." + DSTableName + ".find" + DataTable dt = GetQueryOutput($"SELECT $ FROM {DSTableName}"); DataRow row = dt.Rows[LocateRowValue]; string rowValue = Convert.ToString(row["GINGER_ID"]); @@ -769,7 +644,8 @@ public void RunQuery(string query, int LocateRowValue, string DSTableName, bool //Nextavailable else if (NextAvai) { - DataTable datatble = GetQueryOutput("db." + DSTableName + ".find GINGER_USED = \"False\" limit 1"); + //"db." + DSTableName + ".find + DataTable datatble = GetQueryOutput($"SELECT $ FROM {DSTableName} WHERE GINGER_USED = \"False\" LIMIT 1"); if (datatble != null && datatble.Columns.Count > 0) { row = datatble.Rows[LocateRowValue]; @@ -781,7 +657,8 @@ public void RunQuery(string query, int LocateRowValue, string DSTableName, bool if (MarkUpdate) { - GetQueryOutput("db." + DSTableName + ".update GINGER_USED = \"True\" where GINGER_USED =\"False\" and GINGER_ID= " + rowID); + // "db." + DSTableName + ".update GINGER_USED = \"True\" where GINGER_USED =\"False\" and GINGER_ID= " + rowID + GetQueryOutput($"UPDATE {DSTableName} SET GINGER_USED = \"True\" WHERE GINGER_USED =\"False\" and GINGER_ID= {rowID}"); } } return; @@ -793,8 +670,8 @@ public void RunQuery(string query, int LocateRowValue, string DSTableName, bool { RunQuery(query); string[] querysplit = query.Split(new[] { "GINGER_ID =" }, StringSplitOptions.None); - - dt = GetQueryOutput("db." + DSTableName + ".find GINGER_ID=" + querysplit[1]); + //"db." + DSTableName + ".find GINGER_ID=" + querysplit[1] + dt = GetQueryOutput($"SELECT $ FROM {DSTableName} WHERE GINGER_ID = {querysplit[1]}"); row = dt.Rows[0]; } @@ -806,8 +683,8 @@ public void RunQuery(string query, int LocateRowValue, string DSTableName, bool if (MarkUpdate) { string rowID = Convert.ToString(row["GINGER_ID"]); - - GetQueryOutput("db." + DSTableName + ".update GINGER_USED = \"True\" where GINGER_ID= " + rowID); + // "db." + DSTableName + ".update GINGER_USED = \"True\" where GINGER_ID= " + rowID + GetQueryOutput($"UPDATE {DSTableName} SET GINGER_USED = \"True\" WHERE GINGER_ID= {rowID} "); } } @@ -815,15 +692,16 @@ public void RunQuery(string query, int LocateRowValue, string DSTableName, bool public string GetResultString(string query) { string result = null; - using (LiteDatabase db = new LiteDatabase(FileFullPath)) + using (LiteDatabase db = new LiteDatabase(ConnectionString)) { - var resultdxs = db.Engine.Run(query); + // SQL query needed here + var resultdxs = db.Execute(query).ToArray(); foreach (BsonValue bs in resultdxs) { BsonDocument aa = bs.AsDocument; foreach (KeyValuePair keyval in aa.RawValue) { - result = keyval.Value.AsString; + result = keyval.Value.RawValue.ToString(); } } } @@ -833,12 +711,14 @@ public string GetResultString(string query) public object GetResult(string query) { object result = null; - using (LiteDatabase db = new LiteDatabase(FileFullPath)) + using (LiteDatabase db = new LiteDatabase(ConnectionString)) { - var resultdxs = db.Engine.Run(query); + //SQL command needed here + + var resultdxs = db.Execute(query).ToArray(); foreach (BsonValue bs in resultdxs) { - result = bs.AsString; + result = bs.RawValue; } } return result; @@ -854,7 +734,7 @@ public string GetResut(string query, string DSTableName, bool MarkUpdate) if (MarkUpdate) { string[] tokens = query.Split(new[] { "where" }, StringSplitOptions.None); - string Newquery = "db." + DSTableName + ".update GINGER_USED = \"True\" where " + tokens[1]; + string Newquery = $"UPDATE {DSTableName} SET GINGER_USED = \"True\" WHERE {tokens[1]}"; RunQuery(Newquery); } return row[0].ToString(); @@ -868,62 +748,63 @@ public override void SaveTable(DataTable dataTable) dataTable.AcceptChanges(); } - using (LiteDatabase db = new LiteDatabase(FileFullPath)) + using (LiteDatabase db = new LiteDatabase(ConnectionString)) { dataTable.DefaultView.Sort = "GINGER_ID"; var table = db.GetCollection(dataTable.ToString()); - var doc = BsonMapper.Global.ToDocument(table); + SaveTable(dataTable , table); + } + } + private void SaveTable(DataTable dataTable, ILiteCollection table) + { + var doc = BsonMapper.Global.ToDocument(table); - DataTable changed = dataTable.GetChanges(); - DataTable dtChange = dataTable; - //if datatable is empty - if (dtChange.Rows.Count == 0 && changed == null) - { - return; - } - table.Delete(Query.All()); - List batch = new List(); - if ((dtChange != null)) + DataTable changed = dataTable.GetChanges(); + DataTable dtChange = dataTable; + //if datatable is empty + if (dtChange.Rows.Count == 0 && changed == null) + { + return; + } + + table.DeleteAll(); + + List batch = new List(); + if ((dtChange != null)) + { + foreach (DataRow dr in dtChange.Rows) { - foreach (DataRow dr in dtChange.Rows) + if (dr.RowState != DataRowState.Deleted)//Commit after row is deleted { - if (dr.RowState != DataRowState.Deleted)//Commit after row is deleted + if (dr.RowState.Equals(DataRowState.Added) || dr.RowState.Equals(DataRowState.Modified)) { - if (dr.RowState.Equals(DataRowState.Added) || dr.RowState.Equals(DataRowState.Modified)) - { - dr["GINGER_LAST_UPDATED_BY"] = System.Environment.UserName; - dr["GINGER_LAST_UPDATE_DATETIME"] = DateTime.Now.ToString(); - } - - if (dr["GINGER_ID"] != null || string.IsNullOrWhiteSpace((Convert.ToString(dr["GINGER_ID"])))) - { - dr["GINGER_ID"] = dtChange.Rows.IndexOf(dr) + 1; - } - - var dictionary = dr.Table.Columns.Cast().ToDictionary(col => col.ColumnName, col => dr[col.ColumnName]); + dr["GINGER_LAST_UPDATED_BY"] = System.Environment.UserName; + dr["GINGER_LAST_UPDATE_DATETIME"] = DateTime.Now.ToString(); + } - var mapper = new BsonMapper(); - var sd = mapper.ToDocument(dictionary); + if (dr["GINGER_ID"] != null || string.IsNullOrWhiteSpace((Convert.ToString(dr["GINGER_ID"])))) + { + dr["GINGER_ID"] = dtChange.Rows.IndexOf(dr) + 1; + } - var nobj = mapper.ToObject>(doc); + var dictionary = dr.Table.Columns.Cast().ToDictionary(col => col.ColumnName, col => dr[col.ColumnName]); - batch.Add(new BsonDocument(sd)); - table.Upsert(batch); - } + var mapper = new BsonMapper(); + var sd = mapper.ToDocument(dictionary); + batch.Add(new BsonDocument(sd)); + table.Upsert(batch); } } - dtChange.AcceptChanges(); - var result = db.GetCollection(table.Name).Find(Query.All()).ToList(); - - if (dataTable.Rows.Count > result.Count) - { - table.Upsert(batch); - } + } + dtChange.AcceptChanges(); + var result = table.Find(Query.All()).ToList(); - var rea = db.GetCollection(table.Name).Find(Query.All(), 0).ToList(); + if (dataTable.Rows.Count > result.Count) + { + table.Upsert(batch); } - } + } public override void UpdateTableList(ObservableList dsTableList) { throw new NotImplementedException(); @@ -1058,19 +939,16 @@ public void Execute(ActDSTableElement actDSTable, string Query) // By Selected Cell else { - dt = GetQueryOutput(Query); + string[] tokens = Query.Split(new[] { "where" }, StringSplitOptions.None); + + dt = GetQueryOutput($"SELECT $ FROM {actDSTable.DSTableName} where {tokens[1]}"); dt.TableName = actDSTable.DSTableName; DataRow row = dt.Rows[0]; if (actDSTable.MarkUpdate) { - string[] tokens = Query.Split(new[] { "where" }, StringSplitOptions.None); - DataTable dataTable = GetQueryOutput("db." + actDSTable.DSTableName + ".find" + tokens[1]); - dataTable.TableName = actDSTable.DSTableName; - DataRow rown = dataTable.Rows[0]; - string rowID = Convert.ToString(rown["GINGER_ID"]); - string query = "db." + actDSTable.DSTableName + ".update GINGER_USED = \"True\" where GINGER_ID= \"" + rowID + "\""; - RunQuery(query); + string rowID = Convert.ToString(row["GINGER_ID"]); + RunQuery($"UPDATE {actDSTable.DSTableName} SET GINGER_USED = \"True\" WHERE GINGER_ID= \"{rowID}\""); } actDSTable.AddOrUpdateReturnParamActual(actDSTable.VarName, row[0].ToString()); } @@ -1085,9 +963,9 @@ public void Execute(ActDSTableElement actDSTable, string Query) //By Selected Cell if (actDSTable.BySelectedCell) { - string[] tokens = Query.Split(new[] { "where" }, StringSplitOptions.None); + string[] tokens = Query.ToLower().Split(new[] { "where" }, StringSplitOptions.None); string updateParamValue = tokens[0].Substring(tokens[0].LastIndexOf(".") + 1) + "= \"" + actDSTable.Value + "\" where"; - RunQuery("db." + actDSTable.DSTableName + ".update " + updateParamValue + tokens[1]); + RunQuery($"UPDATE {actDSTable.DSTableName} SET {updateParamValue} {tokens[1]}"); } // Customized Query else if (actDSTable.Customized) @@ -1121,7 +999,7 @@ public void Execute(ActDSTableElement actDSTable, string Query) break; case eControlAction.RowCount: - var a = GetResult(Query); + var a = GetRowCount(actDSTable.DSTableName); actDSTable.AddOrUpdateReturnParamActual("Count", a.ToString()); break; case eControlAction.AvailableRowCount: @@ -1150,15 +1028,16 @@ public void Execute(ActDSTableElement actDSTable, string Query) //By Selected Cell else if (actDSTable.BySelectedCell) { - string[] tokens = Query.Split(new[] { "where" }, StringSplitOptions.None); - RunQuery("db." + actDSTable.DSTableName + ".delete " + tokens[1]); + string[] tokens = Query.ToLower().Split(new[] { "where" }, StringSplitOptions.None); + //"db." + actDSTable.DSTableName + ".delete " + tokens[1] + RunQuery($"DELETE {actDSTable.DSTableName} WHERE {tokens[1]}"); } // Customized Query else if (actDSTable.Customized) { if (actDSTable.ByRowNum) { - dt = GetQueryOutput("db." + actDSTable.DSTableName + ".find"); + dt = GetQueryOutput($"Select $ FROM {actDSTable.DSTableName}"); int x = Int32.Parse(actDSTable.LocateRowValue); DataRow row = dt.Rows[x]; string rowValue = Convert.ToString(row["GINGER_ID"]); @@ -1167,11 +1046,10 @@ public void Execute(ActDSTableElement actDSTable, string Query) } else if (actDSTable.ByNextAvailable) { - dt = GetQueryOutput("db." + actDSTable.DSTableName + ".find GINGER_USED=\"False\""); + dt = GetQueryOutput($"SELECT $ FROM {actDSTable.DSTableName} WHERE GINGER_USED=\"False\""); DataRow row = dt.Rows[0]; string rowValue = Convert.ToString(row["GINGER_ID"]); - string query = "db." + actDSTable.DSTableName + ".delete GINGER_ID=" + rowValue; - GetResult(query); + GetResult($"DELETE {actDSTable.DSTableName} WHERE GINGER_ID = {rowValue}"); actDSTable.AddOrUpdateReturnParamActual("Output", "Success"); } else @@ -1239,7 +1117,7 @@ public override string AddNewCustomizedTableQuery() public override int GetRowCount(string TableName) { - return GetQueryOutput("db." + TableName + ".find").Rows.Count; + return GetQueryOutput($"SELECT $ FROM {TableName}").Rows.Count; } public override string AddNewKeyValueTableQuery() @@ -1251,10 +1129,9 @@ public override string GetExtension() { return ".db"; } - public override DataTable GetKeyName(string mDSTableName) { - return GetQueryOutput("db." + mDSTableName + ".select GINGER_KEY_NAME where GINGER_KEY_NAME != null"); + return GetQueryOutput($"SELECT GINGER_KEY_NAME FROM {mDSTableName} WHERE GINGER_KEY_NAME != NULL"); } bool isDeleteAllExecuted = false; @@ -1270,23 +1147,13 @@ public override void DeleteAll(List AllItemsList, string TName = null) public void DeleteDBTableContents(string TName) { - using (LiteDatabase db = new LiteDatabase(FileFullPath)) + using (LiteDatabase db = new LiteDatabase(ConnectionString)) { var table = db.GetCollection(TName); - List ColumnList = GetColumnList(TName); - table.Delete(Query.All()); - List batch = new List(); - //bool b = ColumnList.Any(s => s.Contains("GINGER_USED")); - //string[] List = null; - //if (b) - //{ - // List = AddNewCustomizedTableQuery().Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries); - //} - //else - //{ - // List = AddNewKeyValueTableQuery().Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries); - //} + List ColumnList = GetColumnList(table.FindAll().ToList() , TName); + table.DeleteAll(); + List batch = new List(); var doc = new BsonDocument(); @@ -1326,11 +1193,49 @@ public override string UpdateDSReturnValues(string Name, string sColList, string } } } - query = "db." + Name + ".insert {" + colvalues + "GINGER_LAST_UPDATED_BY:\"" + System.Environment.UserName - + "\"" + ",GINGER_LAST_UPDATE_DATETIME:\"" + DateTime.Now.ToString() + "\"" + "}"; - + query = $"INSERT INTO {Name} VALUES {{ {colvalues} GINGER_LAST_UPDATED_BY: \"{System.Environment.UserName}\",GINGER_LAST_UPDATE_DATETIME:\"{ DateTime.Now.ToString()}\"}}"; return query; } + + public static void SetDataRow(DataRow dr , KeyValuePair property) + { + + switch (property.Value.Type) + { + case BsonType.Null: + dr[property.Key] = "[NULL]"; + break; + case BsonType.Document: + dr[property.Key] = property.Value.AsDocument.RawValue.ContainsKey("_type") + ? $"[OBJECT: {property.Value.AsDocument.RawValue["_type"]}]" + : "[OBJECT]"; + break; + case BsonType.Array: + dr[property.Key] = $"[ARRAY({property.Value.AsArray.Count})]"; + break; + case BsonType.Binary: + dr[property.Key] = $"[BINARY({property.Value.AsBinary.Length})]"; + break; + case BsonType.DateTime: + dr[property.Key] = property.Value.AsDateTime.ToString("yyyy-MM-dd HH:mm:ss.fff"); + break; + case BsonType.String: + dr[property.Key] = property.Value.AsString; + break; + case BsonType.Int32: + case BsonType.Int64: + dr[property.Key] = property.Value.AsInt64.ToString(); + break; + case BsonType.Decimal: + case BsonType.Double: + dr[property.Key] = property.Value.AsDecimal.ToString(CultureInfo.InvariantCulture); + break; + default: + dr[property.Key] = property.Value.RawValue == null ? string.Empty : property.Value.RawValue.ToString(); + break; + } + + } } } diff --git a/Ginger/GingerCoreNET/DataSource/LiteDBSQLTranslator.cs b/Ginger/GingerCoreNET/DataSource/LiteDBSQLTranslator.cs new file mode 100644 index 0000000000..e8ebdd209b --- /dev/null +++ b/Ginger/GingerCoreNET/DataSource/LiteDBSQLTranslator.cs @@ -0,0 +1,378 @@ +using GingerCore.Actions; +using System; +using System.Text; + +namespace Amdocs.Ginger.CoreNET.DataSource +{ + /// + /// Purpose of this class is to convert the previous liteDB version's Shell command to SQL like command along with creating queries in + /// accordance with the LiteDB version 5.0.17 + /// The translated queries are subsequently used in the LiteDB.cs class + /// + public class LiteDBSQLTranslator + { + private readonly ActDSTableElement actDSTableElement; + private StringBuilder queryBuilder; + public LiteDBSQLTranslator(ActDSTableElement actDSTableElement) + { + ArgumentNullException.ThrowIfNull(actDSTableElement); + this.actDSTableElement = actDSTableElement; + queryBuilder = new (); + } + public string CreateValueExpression() + { + if (actDSTableElement.BySelectedCell) + { + return this.actDSTableElement.ValueExp; + } + + queryBuilder = new(); + queryBuilder.Append($"DS Name={actDSTableElement.DSName} DST={actDSTableElement.DSTableName} MASD="); + if (actDSTableElement.MarkUpdate) + { + queryBuilder.Append('Y'); + } + else + { + queryBuilder.Append('N'); + } + + if (actDSTableElement.ByQuery) + { + queryBuilder.Append(" Query QUERY="); + queryBuilder.Append(actDSTableElement.QueryValue); + queryBuilder.Append('}'); + return queryBuilder.ToString(); + } + + CustomizedSQLQuery.InitForCustomized(actDSTableElement , queryBuilder); + queryBuilder.Append(" Query QUERY="); + switch (actDSTableElement.ControlAction) + { + case ActDSTableElement.eControlAction.ExportToExcel: + ValueExpressionForExportToExcel(); + break; + case ActDSTableElement.eControlAction.GetValue: + ValueExpressionForGetValue(); + break; + case ActDSTableElement.eControlAction.SetValue: + ValueExpressionForSetValue(); + break; + case ActDSTableElement.eControlAction.DeleteRow: + ValueExpressionForDeleteRow(); + break; + case ActDSTableElement.eControlAction.RowCount: + ValueExpressionForRowCount(); + break; + case ActDSTableElement.eControlAction.AvailableRowCount: + ValueExpressionForAvailableRowCount(); + break; + case ActDSTableElement.eControlAction.AddRow: + ValueExpressionForAddRow(); + break; + case ActDSTableElement.eControlAction.MarkAsDone: + ValueExpressionForMarkAsDone(); + break; + case ActDSTableElement.eControlAction.DeleteAll: + ValueExpressionForDeleteAll(); + break; + case ActDSTableElement.eControlAction.MarkAllUsed: + ValueExpressionForMarkAllUsed(); + break; + case ActDSTableElement.eControlAction.MarkAllUnUsed: + ValueExpressionForMarkAllUnused(); + break; + } + queryBuilder.Append('}'); + + return queryBuilder.ToString(); + } + private void ValueExpressionForExportToExcel() + { + + if (actDSTableElement.ExcelConfig == null) + { + queryBuilder.Append($"{actDSTableElement.ExcelPath},{actDSTableElement.ExcelSheetName}"); + } + else + { + queryBuilder.Append($"{actDSTableElement.ExcelConfig.ExcelPath},{actDSTableElement.ExcelConfig.ExcelSheetName}"); + } + } + + private void ValueExpressionForGetValue() + { + if (actDSTableElement.IsKeyValueTable) + { + GingerKeyValueSQLQuery.GetValueForGingerKeyValue(actDSTableElement , queryBuilder); + } + + else if (actDSTableElement.Customized) + { + CustomizedSQLQuery.GetValueForCustomized(actDSTableElement , queryBuilder); + } + } + + private void ValueExpressionForSetValue() + { + if (actDSTableElement.IsKeyValueTable) + { + GingerKeyValueSQLQuery.SetValueForGingerKeyValue(actDSTableElement , queryBuilder); + } + else if (actDSTableElement.Customized) + { + CustomizedSQLQuery.SetValueForCustomized(actDSTableElement, queryBuilder); + } + } + + private void ValueExpressionForDeleteRow() + { + if (actDSTableElement.IsKeyValueTable) + { + GingerKeyValueSQLQuery.DeleteRowForGingerKeyValue(actDSTableElement , queryBuilder); + } + + else if (actDSTableElement.Customized) + { + CustomizedSQLQuery.DeleteRowForForCustomized(actDSTableElement, queryBuilder); + } + } + + private void ValueExpressionForRowCount() + { + queryBuilder.Append($"Select COUNT(*) FROM {actDSTableElement.DSTableName}"); + } + + private void ValueExpressionForAddRow() + { + queryBuilder.Append($"INSERT INTO {actDSTableElement.DSTableName}"); + } + + private void ValueExpressionForAvailableRowCount() + { + queryBuilder.Append($"SELECT $ FROM {actDSTableElement.DSTableName} where GINGER_USED= \"False\""); + } + + private void ValueExpressionForMarkAsDone() + { + queryBuilder.Append($"UPDATE {actDSTableElement.DSTableName} SET GINGER_USED= \"True\""); + if (actDSTableElement.ByWhere) + { + queryBuilder.Append(" where "); + CustomizedSQLQuery.SetWhereConditions(actDSTableElement , queryBuilder); + } + } + + private void ValueExpressionForDeleteAll() + { + queryBuilder.Append($"DELETE {actDSTableElement.DSTableName}"); + } + + private void ValueExpressionForMarkAllUsed() + { + queryBuilder.Append($"UPDATE {actDSTableElement.DSTableName} SET GINGER_USED= \"True\""); + } + + private void ValueExpressionForMarkAllUnused() + { + queryBuilder.Append($"UPDATE {actDSTableElement.DSTableName} SET GINGER_USED = \"True\""); + } + } + + static class GingerKeyValueSQLQuery + { + public static void GetValueForGingerKeyValue(ActDSTableElement actDSTableElement, StringBuilder queryBuilder) + { + // db.MyKeyValueDataTable.select GINGER_KEY_VALUE where GINGER_KEY_NAME="Name" + string ValueExp = actDSTableElement.ValueExp; + string Query = string.IsNullOrEmpty(ValueExp) ? string.Empty : + ValueExp.Substring(ValueExp.IndexOf("QUERY=") + 6, ValueExp.Length - (ValueExp.IndexOf("QUERY=") + 7)); + + if (!string.IsNullOrEmpty(Query) && Query.StartsWith("db")) + { + string GingerKeyName = Query.Split("GINGER_KEY_NAME=")?[1]; + + queryBuilder.Append($"SELECT Ginger_KEY_VALUE FROM {actDSTableElement.DSTableName} where GINGER_KEY_NAME={GingerKeyName}"); + } + else + { + queryBuilder.Append($"SELECT Ginger_KEY_VALUE FROM {actDSTableElement.DSTableName} where GINGER_KEY_NAME={actDSTableElement.KeyName}"); + } + + } + + public static void SetValueForGingerKeyValue(ActDSTableElement actDSTableElement, StringBuilder queryBuilder) + { + //$"Update {mDSTable.Name} SET GINGER_KEY_VALUE = \"{mActDSTblElem.ValueUC}\" where GINGER_KEY_NAME=\"{cmbKeyName.Text}\"" + string ValueExp = actDSTableElement.ValueExp; + string Query = string.IsNullOrEmpty(ValueExp) ? string.Empty : + ValueExp.Substring(ValueExp.IndexOf("QUERY=") + 6, ValueExp.Length - (ValueExp.IndexOf("QUERY=") + 7)); + + if (!string.IsNullOrEmpty(Query) && Query.StartsWith("db")) + { + string GingerKeyName = Query.Split("GINGER_KEY_NAME=")?[1]; + + queryBuilder.Append($"UPDATE {actDSTableElement.DSTableName} SET GINGER_KEY_VALUE = \"{actDSTableElement.ValueUC}\" where GINGER_KEY_NAME={GingerKeyName}"); + } + else + { + queryBuilder.Append($"UPDATE {actDSTableElement.DSTableName} SET GINGER_KEY_VALUE = \"{actDSTableElement.ValueUC}\" where GINGER_KEY_NAME=\"{actDSTableElement.KeyName}\""); + } + } + + public static void DeleteRowForGingerKeyValue(ActDSTableElement actDSTableElement, StringBuilder queryBuilder) + { + string ValueExp = actDSTableElement.ValueExp; + string Query = string.IsNullOrEmpty(ValueExp) ? string.Empty : + ValueExp.Substring(ValueExp.IndexOf("QUERY=") + 6, ValueExp.Length - (ValueExp.IndexOf("QUERY=") + 7)); + + if (!string.IsNullOrEmpty(Query) && Query.StartsWith("db")) + { + string GingerKeyName = Query.Split("GINGER_KEY_NAME=")?[1]; + queryBuilder.Append($"Delete {actDSTableElement.DSTableName} where GINGER_KEY_NAME={GingerKeyName}"); + } + else + { + queryBuilder.Append($"Delete {actDSTableElement.DSTableName} where GINGER_KEY_NAME=\"{actDSTableElement.KeyName}\""); + } + } + } + + + static class CustomizedSQLQuery + { + public static void InitForCustomized(ActDSTableElement actDSTableElement, StringBuilder queryBuilder) + { + if (!actDSTableElement.Customized) + { + return; + } + + queryBuilder.Append($" IDEN=Cust ICOLVAL={actDSTableElement.LocateColTitle} IROW="); + + if (actDSTableElement.ByRowNum) + { + queryBuilder.Append($"RowNum ROWNUM={actDSTableElement.LocateRowValue}"); + } + else if (actDSTableElement.ByNextAvailable) + { + queryBuilder.Append("NxtAvail"); + } + else if (actDSTableElement.ByWhere) + { + queryBuilder.Append("Where COND="); + SetWhereConditions(actDSTableElement , queryBuilder); + } + } + public static void GetValueForCustomized(ActDSTableElement actDSTableElement, StringBuilder queryBuilder) + { + + if (actDSTableElement.ByWhere) + { + queryBuilder.Append($"SELECT $ FROM {actDSTableElement.DSTableName} where "); + SetWhereConditions(actDSTableElement , queryBuilder); + + } + else if (actDSTableElement.ByNextAvailable) + { + queryBuilder.Append($"SELECT $ FROM {actDSTableElement.DSTableName} where GINGER_USED =\"False\""); + } + else if (actDSTableElement.ByRowNum) + { + queryBuilder.Append($"SELECT $ FROM {actDSTableElement.DSTableName}"); + } + } + public static void SetValueForCustomized(ActDSTableElement actDSTableElement, StringBuilder queryBuilder) + { + if (actDSTableElement.ByWhere) + { + queryBuilder.Append($"Update {actDSTableElement.DSTableName} SET {actDSTableElement.LocateColTitle} = \"{actDSTableElement.ValueUC}\" where "); + SetWhereConditions(actDSTableElement , queryBuilder); + } + else if (actDSTableElement.ByRowNum) + { + queryBuilder.Append($"Update {actDSTableElement.DSTableName} SET {actDSTableElement.LocateColTitle} = \"{actDSTableElement.ValueUC}\""); + + } + else if (actDSTableElement.ByNextAvailable) + { + queryBuilder.Append($"Update {actDSTableElement.DSTableName} SET {actDSTableElement.LocateColTitle} = \"{actDSTableElement.ValueUC}\" where GINGER_USED =\"False\""); + } + } + + public static void DeleteRowForForCustomized(ActDSTableElement actDSTableElement, StringBuilder queryBuilder) + { + if (actDSTableElement.ByWhere) + { + queryBuilder.Append($"DELETE {actDSTableElement.DSTableName} where "); + SetWhereConditions(actDSTableElement , queryBuilder); + } + + else if (actDSTableElement.ByNextAvailable) + { + queryBuilder.Append($"DELETE {actDSTableElement.DSTableName} where GINGER_USED =\"False\""); + } + + else if (actDSTableElement.ByRowNum) + { + queryBuilder.Append($"DELETE {actDSTableElement.DSTableName} where"); + } + + } + public static void SetWhereConditions(ActDSTableElement actDSTableElement, StringBuilder queryBuilder) + { + if (actDSTableElement.WhereConditions == null) + { + return; + } + + for (int i = 0; i < actDSTableElement.WhereConditions.Count; i++) + { + string wQuery = ""; + string wCond = actDSTableElement.WhereConditions[i].wCondition.ToString().ToLower(); + string wColVal = actDSTableElement.WhereConditions[i].wTableColumn.ToString().Trim(); + string wOpr = actDSTableElement.WhereConditions[i].wOperator.ToString(); + string wRowVal = actDSTableElement.WhereConditions[i].wValue.ToString(); + + if (wCond == "empty") + { + wCond = ""; + } + + if (wOpr == "Equals") + { + if (wColVal == "GINGER_ID") + { + wQuery = wQuery + " " + wCond + " " + wColVal + " = " + wRowVal; + } + else + { + wQuery = wQuery + " " + wCond + " " + wColVal + " = \"" + wRowVal + "\""; + } + } + else if (wOpr == "NotEquals") + { + if (wColVal == "GINGER_ID") + { + wQuery = wQuery + " " + wCond + " " + wColVal + " != " + wRowVal; + } + else + { + wQuery = wQuery + " " + wCond + " " + wColVal + " != \"" + wRowVal + "\""; + } + } + else if (wOpr == "Contains") + { + wQuery = wQuery + " " + wCond + " " + wColVal + " contains " + "\"" + wRowVal + "\""; + } + else if (wOpr == "StartsWith") + { + wQuery = wQuery + " " + wCond + " " + wColVal + " like " + "\"" + wRowVal + "\""; + } + queryBuilder.Append(wQuery); + } + + } + } + +} diff --git a/Ginger/GingerCoreNET/GingerCoreNET.csproj b/Ginger/GingerCoreNET/GingerCoreNET.csproj index fc38f4d1fd..33026dcc4b 100644 --- a/Ginger/GingerCoreNET/GingerCoreNET.csproj +++ b/Ginger/GingerCoreNET/GingerCoreNET.csproj @@ -254,7 +254,7 @@ - + diff --git a/Ginger/GingerCoreNET/LiteDBFolder/LiteDbConnector.cs b/Ginger/GingerCoreNET/LiteDBFolder/LiteDbConnector.cs index 9fab65af2b..ac8668994e 100644 --- a/Ginger/GingerCoreNET/LiteDBFolder/LiteDbConnector.cs +++ b/Ginger/GingerCoreNET/LiteDBFolder/LiteDbConnector.cs @@ -28,18 +28,18 @@ namespace Amdocs.Ginger.CoreNET.LiteDBFolder public class LiteDbConnector { public string ConnectionString { get; set; } - public LiteDbConnector(string connectionString) + public LiteDbConnector(string filePath) { - this.ConnectionString = connectionString; + this.ConnectionString = $"filename={filePath}; connection=Shared; upgrade=true"; } public EntityBuilder GetMapper() { return BsonMapper.Global.Entity(); } - public LiteCollection GetCollection(string collectionName) + public ILiteCollection GetCollection(string collectionName) { - LiteCollection collection = null; + ILiteCollection collection = null; try { using (var db = new LiteDatabase(this.ConnectionString)) @@ -54,7 +54,9 @@ public LiteCollection GetCollection(string collectionName) return collection; } - public bool DeleteCollectionItems(LiteCollection baseColl, Query query) +/* + * This function is not used anywhere + * public bool DeleteCollectionItems(LiteCollection baseColl, Query query) { bool result = false; try @@ -70,7 +72,7 @@ public bool DeleteCollectionItems(LiteCollection baseColl, Query query) } return result; } - public bool DeleteDocumentByLiteDbRunSet(LiteDbRunSet liteDbRunSet, eExecutedFrom executedFrom = eExecutedFrom.Run) +*/ public bool DeleteDocumentByLiteDbRunSet(LiteDbRunSet liteDbRunSet, eExecutedFrom executedFrom = eExecutedFrom.Run) { bool result = true; var runSetLiteColl = GetCollection(NameInDb()); @@ -113,12 +115,16 @@ public string NameInDb() var name = typeof(T).Name + "s"; return name; } - public List FilterCollection(LiteCollection baseColl, Query query) + public List FilterCollection(ILiteCollection baseColl, Query query) { - return baseColl.IncludeAll().Find(query).ToList(); + return baseColl.Find(query).ToList(); + } + public List FilterCollection(ILiteCollection baseColl , BsonExpression expression) + { + return baseColl.Find(expression).ToList(); } - public void SetCollection(LiteCollection baseColl, List updateData) + public void SetCollection(ILiteCollection baseColl, List updateData) { try { diff --git a/Ginger/GingerCoreNET/LiteDBFolder/LiteDbManager.cs b/Ginger/GingerCoreNET/LiteDBFolder/LiteDbManager.cs index 42613cfe9d..7e91e201ee 100644 --- a/Ginger/GingerCoreNET/LiteDBFolder/LiteDbManager.cs +++ b/Ginger/GingerCoreNET/LiteDBFolder/LiteDbManager.cs @@ -65,17 +65,17 @@ public LiteDbRunSet GetLatestExecutionRunsetData(string runsetId) List filterData = null; if (!string.IsNullOrEmpty(runsetId)) { - filterData = result.IncludeAll().Find(a => a._id.ToString() == runsetId).ToList(); + filterData = LiteDbRunSet.IncludeAllReferences(result).Find(a => a._id.Equals(new ObjectId(runsetId))).ToList(); } else { - runsetId = result.IncludeAll().Max(x => x._id).AsString; - filterData = result.IncludeAll().Find(a => a._id.ToString() == runsetId).ToList(); + ObjectId runsetObjectID = LiteDbRunSet.IncludeAllReferences(result).Max(x => x._id); + filterData = LiteDbRunSet.IncludeAllReferences(result).Find(a => a._id.Equals(runsetObjectID)).ToList(); } return filterData.Last(); } - public List FilterCollection(LiteCollection baseColl, Query query) + public List FilterCollection(ILiteCollection baseColl, Query query) { return dbConnector.FilterCollection(baseColl, query); } @@ -85,32 +85,32 @@ public bool DeleteDocumentByLiteDbRunSet(LiteDbRunSet liteDbRunSet) return dbConnector.DeleteDocumentByLiteDbRunSet(liteDbRunSet); } - public LiteCollection GetObjectLiteData(string reportLevelName) + public ILiteCollection GetObjectLiteData(string reportLevelName) { return dbConnector.GetCollection(reportLevelName); } - public LiteCollection GetRunSetLiteData() + public ILiteCollection GetRunSetLiteData() { return dbConnector.GetCollection(NameInDb()); } - public LiteCollection GetRunnerLiteData() + public ILiteCollection GetRunnerLiteData() { return dbConnector.GetCollection(NameInDb()); } - public LiteCollection GetBfLiteData() + public ILiteCollection GetBfLiteData() { return dbConnector.GetCollection(NameInDb()); } - private LiteCollection GetActGrLiteData() + private ILiteCollection GetActGrLiteData() { return dbConnector.GetCollection(NameInDb()); } - public LiteCollection GetActivitiesLiteData() + public ILiteCollection GetActivitiesLiteData() { return dbConnector.GetCollection(NameInDb()); } - public LiteCollection GetActionsLiteData() + public ILiteCollection GetActionsLiteData() { return dbConnector.GetCollection(NameInDb()); } diff --git a/Ginger/GingerCoreNET/LiteDBFolder/LiteDbReportBase.cs b/Ginger/GingerCoreNET/LiteDBFolder/LiteDbReportBase.cs index 091eb3b4ee..217b46a50d 100644 --- a/Ginger/GingerCoreNET/LiteDBFolder/LiteDbReportBase.cs +++ b/Ginger/GingerCoreNET/LiteDBFolder/LiteDbReportBase.cs @@ -21,6 +21,7 @@ limitations under the License. using Amdocs.Ginger.CoreNET.Execution; using Amdocs.Ginger.Repository; using Ginger.Reports; +using LiteDB; using System; using System.Collections.Generic; using System.Linq; @@ -263,6 +264,18 @@ internal void SetReportData(RunSetReport runSetReport) GingerVersion = ApplicationInfo.ApplicationUIversion; RunStatus = (runSetReport.RunSetExecutionStatus == eRunStatus.Automated) ? eRunStatus.Automated.ToString() : SetStatus(RunnersColl); } + public static ILiteCollection IncludeAllReferences(ILiteCollection liteCollection) + { + return liteCollection + .Include(runset => runset.RunnersColl) + .Include(runset => runset.RunnersColl.Select((runner) => runner.AllBusinessFlowsColl)) + .Include(runset => runset.RunnersColl.Select((runner) => runner.AllBusinessFlowsColl.Select(businessFlow => businessFlow.AllActivitiesColl))) + .Include(runset => runset.RunnersColl.Select((runner) => runner.AllBusinessFlowsColl.Select(businessFlow => businessFlow.ActivitiesGroupsColl))) + .Include(runset => runset.RunnersColl.Select((runner) => runner.AllBusinessFlowsColl.Select(businessFlow => businessFlow.AllActivitiesColl.Select(activity => activity.AllActionsColl)))) + .Include(runset => runset.RunnersColl.Select((runner) => runner.AllBusinessFlowsColl.Select(businessFlow => businessFlow.ActivitiesGroupsColl.Select(activityGroup => activityGroup.AllActivitiesColl.Select(activity => activity.AllActionsColl))))) + ; + + } } public class LiteDbRunner : LiteDbReportBase { @@ -351,6 +364,14 @@ internal void SetReportData(GingerReport gingerReport) ApplicationAgentsMappingList = gingerReport.ApplicationAgentsMappingList; RunStatus = SetStatus(BusinessFlowsColl); } + public static ILiteCollection IncludeAllReferences(ILiteCollection liteCollection) + { + return liteCollection + .Include((runner) => runner.BusinessFlowsColl) + .Include((runner) => runner.AllBusinessFlowsColl.Select((businessFlow) => businessFlow.AllActivitiesColl.Select((activity) => activity.AllActionsColl))) + .Include((runner) => runner.AllBusinessFlowsColl.Select((businessFlow) => businessFlow.ActivitiesGroupsColl.Select((activityGroup) => activityGroup.AllActivitiesColl.Select((activity) => activity.AllActionsColl)))); + } + } public class LiteDbBusinessFlow : LiteDbReportBase { @@ -492,6 +513,15 @@ public void SetReportData(BusinessFlowReport bfReport) ExternalID2 = bfReport.ExternalID2; } + public static ILiteCollection IncludeAllReferences(ILiteCollection liteCollection) + { + return liteCollection + .Include((businessFlow) => businessFlow.ActivitiesGroupsColl) + .Include((businessFlow) => businessFlow.AllActivitiesColl) + .Include((businessFlow) => businessFlow.ActivitiesGroupsColl.Select((activityGroup) => activityGroup.AllActivitiesColl.Select((activity) => activity.AllActionsColl))) + .Include((businessFlow) => businessFlow.AllActivitiesColl.Select((activity) => activity.AllActionsColl)); + } + } public class LiteDbActivityGroup : LiteDbReportBase @@ -584,6 +614,13 @@ internal void SetReportData(ActivityGroupReport agReport) ExternalID = agReport.ExternalID; ExternalID2 = agReport.ExternalID2; } + public static ILiteCollection IncludeAllReferences(ILiteCollection liteCollection) + { + return liteCollection + .Include((activityGroup) => activityGroup.AllActivitiesColl) + .Include((activityGroup) => activityGroup.AllActivitiesColl.Select((activity) => activity.AllActionsColl)); + } + } public class LiteDbActivity : LiteDbReportBase { @@ -688,6 +725,11 @@ public void SetReportData(ActivityReport activityReport) ExternalID = activityReport.ExternalID; ExternalID2 = activityReport.ExternalID2; } + public static ILiteCollection IncludeAllReferences(ILiteCollection liteCollection) + { + return liteCollection.Include((activity) => activity.AllActionsColl); + } + } public class LiteDbAction : LiteDbReportBase diff --git a/Ginger/GingerCoreNET/Run/RunListenerLib/ExecutionLoggerManager.cs b/Ginger/GingerCoreNET/Run/RunListenerLib/ExecutionLoggerManager.cs index 0ae628fc3a..6ae97cb951 100644 --- a/Ginger/GingerCoreNET/Run/RunListenerLib/ExecutionLoggerManager.cs +++ b/Ginger/GingerCoreNET/Run/RunListenerLib/ExecutionLoggerManager.cs @@ -39,6 +39,7 @@ limitations under the License. using System.Text; using static GingerCore.ALM.PublishToALMConfig; using Activity = GingerCore.Activity; +using JsonWriter = Newtonsoft.Json.JsonWriter; namespace Ginger.Run { diff --git a/Ginger/GingerCoreNET/Run/RunListenerLib/LiteDBRepository.cs b/Ginger/GingerCoreNET/Run/RunListenerLib/LiteDBRepository.cs index 8cbcac100c..0c1dc0291f 100644 --- a/Ginger/GingerCoreNET/Run/RunListenerLib/LiteDBRepository.cs +++ b/Ginger/GingerCoreNET/Run/RunListenerLib/LiteDBRepository.cs @@ -163,7 +163,7 @@ private object MapActivityToLiteDb(Activity activity, Context context, eExecuted if (activity.LiteDbId != null && ExecutionLoggerManager.RunSetReport != null && ExecutionLoggerManager.RunSetReport.RunSetExecutionStatus == Execution.eRunStatus.Automated) // missing Executed from { AR._id = ObjectId.NewObjectId(); - var ARToUpdate = liteDbManager.GetActivitiesLiteData().IncludeAll().Find(x => x._id == AR._id).ToList(); + var ARToUpdate = LiteDbActivity.IncludeAllReferences(liteDbManager.GetActivitiesLiteData()).Find(x => x._id == AR._id).ToList(); if (ARToUpdate.Count > 0) { foreach (var action in (ARToUpdate[0] as LiteDbActivity).ActionsColl) diff --git a/Ginger/GingerCoreNETUnitTest/DataSource/DataSourceTest.cs b/Ginger/GingerCoreNETUnitTest/DataSource/DataSourceTest.cs index efe6565156..35c067ae10 100644 --- a/Ginger/GingerCoreNETUnitTest/DataSource/DataSourceTest.cs +++ b/Ginger/GingerCoreNETUnitTest/DataSource/DataSourceTest.cs @@ -38,14 +38,10 @@ public class DataSourceTest [ClassInitialize] public static void ClassInitialize(TestContext TestContext) { - string Connectionstring = "filename=" + TestResources.GetTestResourcesFile(@"Solutions" + Path.DirectorySeparatorChar + "BasicSimple" + Path.DirectorySeparatorChar + "DataSources" + Path.DirectorySeparatorChar + "LiteDB.db") + "; mode=Exclusive"; + string Connectionstring = TestResources.GetTestResourcesFile(@"Solutions" + Path.DirectorySeparatorChar + "BasicSimple" + Path.DirectorySeparatorChar + "DataSources" + Path.DirectorySeparatorChar + "LiteDB.db"); excelFilePath = TestResources.GetTestResourcesFile(@"Excel" + Path.DirectorySeparatorChar + "ExportedDS.xlsx"); liteDB.FileFullPath = Connectionstring; - - - - } [TestMethod] @@ -116,7 +112,7 @@ public void RenameTable() public void GetResult() { //Arrange - string Query = "db.MyCustomizedDataTable.find limit 1"; + string Query = "SELECT $ FROM MyCustomizedDataTable limit 1"; //Act object res = liteDB.GetResult(Query); @@ -147,7 +143,7 @@ public void SaveTable() //Act liteDB.SaveTable(dataTable); - var a = liteDB.GetResult("db.MyCustomizedDataTable.count"); + var a = liteDB.GetRowCount("MyCustomizedDataTable").ToString(); //Assert Assert.AreEqual("1", a, "RowCount"); @@ -188,7 +184,7 @@ public void AddRow() //Act liteDB.SaveTable(dataTable); - var a = liteDB.GetResult("db.MyCustomizedDataTable.count"); + var a = liteDB.GetRowCount("MyCustomizedDataTable").ToString(); //Assert Assert.AreEqual("1", a, "RowCount"); @@ -200,7 +196,7 @@ public void ExecuteGetValueNextAvailable() { //Arrange ActDSTableElement actDSTable = new ActDSTableElement(); - string query = "db.MyCustomizedDataTable.find limit 1"; + string query = "SELECT $ FROM MyCustomizedDataTable limit 1"; actDSTable.ControlAction = ActDSTableElement.eControlAction.GetValue; actDSTable.Customized = true; actDSTable.ByNextAvailable = true; @@ -223,7 +219,7 @@ public void ExecuteGetValueByRowNum() { //Arrange ActDSTableElement actDSTable = new ActDSTableElement(); - string query = "db.MyCustomizedDataTable.find limit 1"; + string query = "SELECT $ FROM MyCustomizedDataTable limit 1"; actDSTable.ControlAction = ActDSTableElement.eControlAction.GetValue; actDSTable.Customized = true; actDSTable.ByNextAvailable = false; @@ -247,7 +243,7 @@ public void ExecuteGetValueByQuery() { //Arrange ActDSTableElement actDSTable = new ActDSTableElement(); - string query = "db.MyCustomizedDataTable.find limit 1"; + string query = "SELECT $ FROM MyCustomizedDataTable limit 1"; actDSTable.ControlAction = ActDSTableElement.eControlAction.GetValue; actDSTable.Customized = false; actDSTable.ByNextAvailable = false; @@ -285,12 +281,12 @@ public void ExecuteMarkAsDone() //Clean up ActDSTableElement actDSTable = new ActDSTableElement(); - string query = "db.MyCustomizedDataTable.update GINGER_USED= \"False\""; + string query = "update MyCustomizedDataTable SET GINGER_USED = \"False\""; actDSTable.ControlAction = ActDSTableElement.eControlAction.MarkAllUnUsed; liteDB.Execute(actDSTable, query); //Arrange - query = "db.MyCustomizedDataTable.update GINGER_USED= \"True\""; + query = "update MyCustomizedDataTable SET GINGER_USED = \"True\""; actDSTable.ControlAction = ActDSTableElement.eControlAction.MarkAsDone; actDSTable.DSTableName = "MyCustomizedDataTable"; actDSTable.Customized = true; @@ -305,7 +301,7 @@ public void ExecuteMarkAsDone() liteDB.Execute(actDSTable, query); //Assert - query = "db.MyCustomizedDataTable.find GINGER_USED= \"True\""; + query = "SELECT $ FROM MyCustomizedDataTable where GINGER_USED= \"True\""; DataTable dt = liteDB.GetQueryOutput(query); Assert.AreEqual(1, dt.Rows.Count); @@ -335,7 +331,7 @@ public void CopyTable() public void GetQueryOutput() { //Arrange - string Query = "db.MyCustomizedDataTable.find limit 1"; + string Query = "SELECT $ FROM MyCustomizedDataTable limit 1"; //Act DataTable res = liteDB.GetQueryOutput(Query); @@ -348,7 +344,7 @@ public void GetQueryOutput() public void ExportToExcel() { //Arrange - string Query = "db.MyCustomizedDataTable.find limit 1"; + string Query = "SELECT $ FROM MyCustomizedDataTable limit 1"; //Act DataTable dt = liteDB.GetQueryOutput(Query); @@ -367,7 +363,7 @@ public void CommitDb() ObservableList dataSourceTableList = liteDB.GetTablesList(); DataSourceTable dataSource = null; List mColumnNames = null; - string Query = "db.MyCustomizedDataTable.find limit 1"; + string Query = "SELECT $ FROM MyCustomizedDataTable LIMIT 1"; foreach (DataSourceTable dataSourceTable in dataSourceTableList) { diff --git a/Ginger/GingerCoreNETUnitTest/LiteDb/LiteDbMoq.cs b/Ginger/GingerCoreNETUnitTest/LiteDb/LiteDbMoq.cs index 46ee65b2a8..3430c94256 100644 --- a/Ginger/GingerCoreNETUnitTest/LiteDb/LiteDbMoq.cs +++ b/Ginger/GingerCoreNETUnitTest/LiteDb/LiteDbMoq.cs @@ -22,6 +22,10 @@ public GingerBusinessFlow() { ActivitiesGroupColl = new List(); } + public static ILiteCollection IncludeAllReferences(ILiteCollection gingerBusinessFlow) + { + return gingerBusinessFlow.Include((gBf) => gBf.ActivitiesGroupColl); + } } class GingerActvityGroup : GingerBaseData diff --git a/Ginger/GingerCoreNETUnitTest/LiteDb/LiteDbTest.cs b/Ginger/GingerCoreNETUnitTest/LiteDb/LiteDbTest.cs index 0dc129e3de..246e8bf519 100644 --- a/Ginger/GingerCoreNETUnitTest/LiteDb/LiteDbTest.cs +++ b/Ginger/GingerCoreNETUnitTest/LiteDb/LiteDbTest.cs @@ -28,7 +28,7 @@ public void WriteToLiteDb() public void ReadAndUpdateLiteDbData() { var bfLiteColl = dbConector.GetCollection("BusinessFlows"); - var filterData = dbConector.FilterCollection(bfLiteColl, Query.Contains("Name", "bf name")); + var filterData = dbConector.FilterCollection(GingerBusinessFlow.IncludeAllReferences(bfLiteColl), Query.Contains("Name", "bf name")); filterData.ForEach(a => a.Name = a.Name + " Modified BF"); dbConector.SetCollection(bfLiteColl, filterData); Assert.IsTrue(bfLiteColl.Count() > 0); @@ -83,12 +83,12 @@ private List GetGingerBf(List acGrpData) } - private LiteCollection GetBfLiteData() + private ILiteCollection GetBfLiteData() { return dbConector.GetCollection("BusinessFlows"); } - private LiteCollection GetActGrLiteData() + private ILiteCollection GetActGrLiteData() { return dbConector.GetCollection("ActivityGroups"); }