diff --git a/Ginger/GingerCoreNET/AnalyzerLib/AnalyzeAction.cs b/Ginger/GingerCoreNET/AnalyzerLib/AnalyzeAction.cs index 104969c02c..89caded557 100644 --- a/Ginger/GingerCoreNET/AnalyzerLib/AnalyzeAction.cs +++ b/Ginger/GingerCoreNET/AnalyzerLib/AnalyzeAction.cs @@ -70,8 +70,8 @@ public static List Analyze(BusinessFlow BusinessFlow, Activity if (parentActivity.GetAct(f.GetGuidFromValue(true), f.GetNameFromValue(true)) == null) { AnalyzeAction AA = CreateNewIssue(BusinessFlow, parentActivity, a); - AA.Description = "Flow control is mapped to Action which does not exist"; ; - AA.Details = "'" + GoToActionName + "' Action does not exist in '" + parentActivity.ActivityName + "' " + GingerDicser.GetTermResValue(eTermResKey.Activity); + AA.Description = "Flow control is mapped to Action which does not exist"; + AA.Details = $"'{ GoToActionName }' Action does not exist in '{ parentActivity.ActivityName }' { GingerDicser.GetTermResValue(eTermResKey.Activity)}"; AA.HowToFix = "Remap the Flow Control Action"; if (parentActivity.Acts.FirstOrDefault(x => x.Description == f.GetNameFromValue()) != null) @@ -101,14 +101,14 @@ public static List Analyze(BusinessFlow BusinessFlow, Activity if (BusinessFlow.GetActivity(f.GetGuidFromValue(true), f.GetNameFromValue(true)) == null) { AnalyzeAction AA = CreateNewIssue(BusinessFlow, parentActivity, a); - AA.Description = "Flow control is mapped to " + GingerDicser.GetTermResValue(eTermResKey.Activity) + " which does not exist"; ; - AA.Details = "'" + GoToActivity + "' " + GingerDicser.GetTermResValue(eTermResKey.Activity) + " does not exist in the '" + BusinessFlow.Name + " ' " + GingerDicser.GetTermResValue(eTermResKey.BusinessFlow); + AA.Description = $"Flow control is mapped to { GingerDicser.GetTermResValue(eTermResKey.Activity) } which does not exist"; ; + AA.Details = $"'{ GoToActivity }'{ GingerDicser.GetTermResValue(eTermResKey.Activity) } does not exist in the '{ BusinessFlow.Name } ' { GingerDicser.GetTermResValue(eTermResKey.BusinessFlow)}"; AA.HowToFix = "Remap the Flow Control Action"; if (BusinessFlow.Activities.FirstOrDefault(x => x.ActivityName == f.GetNameFromValue()) != null) { //can be auto fix - AA.HowToFix = "Remap Flow Control " + GingerDicser.GetTermResValue(eTermResKey.Activity) + ". Auto fix found other " + GingerDicser.GetTermResValue(eTermResKey.Activity) + " with the same name so it will fix the mapping to this " + GingerDicser.GetTermResValue(eTermResKey.Activity) + "."; + AA.HowToFix = $"Remap Flow Control { GingerDicser.GetTermResValue(eTermResKey.Activity) }. Auto fix found other { GingerDicser.GetTermResValue(eTermResKey.Activity) } with the same name so it will fix the mapping to this { GingerDicser.GetTermResValue(eTermResKey.Activity) }."; AA.ErrorInfoObject = f; AA.CanAutoFix = AnalyzerItemBase.eCanFix.Yes; AA.FixItHandler = FixFlowControlWrongActivityMapping; @@ -130,8 +130,8 @@ public static List Analyze(BusinessFlow BusinessFlow, Activity if (BusinessFlow.Activities.IndexOf(parentActivity) == (BusinessFlow.Activities.Count - 1)) { AnalyzeAction AA = CreateNewIssue(BusinessFlow, parentActivity, a); - AA.Description = "Flow control is mapped to " + GingerDicser.GetTermResValue(eTermResKey.Activity) + " which does not exist"; ; - AA.Details = "Flow Control is set to 'GoToNextActivity' but the parent " + GingerDicser.GetTermResValue(eTermResKey.Activity) + " is last one in flow."; + AA.Description = $"Flow control is mapped to { GingerDicser.GetTermResValue(eTermResKey.Activity) } which does not exist"; + AA.Details = $"Flow Control is set to 'GoToNextActivity' but the parent { GingerDicser.GetTermResValue(eTermResKey.Activity) } is last one in flow."; AA.HowToFix = "Remap the Flow Control Action"; AA.CanAutoFix = AnalyzerItemBase.eCanFix.No; AA.IssueType = eType.Error; @@ -150,8 +150,8 @@ public static List Analyze(BusinessFlow BusinessFlow, Activity if (!BusinessFlow.CheckIfVariableExists(vals[0].ToString().Trim(), parentActivity)) { AnalyzeAction AA = CreateNewIssue(BusinessFlow, parentActivity, a); - AA.Description = "Flow control mapped to " + GingerDicser.GetTermResValue(eTermResKey.Variable) + " which does not exist"; ; - AA.Details = "'" + vals[0].Trim() + "' " + GingerDicser.GetTermResValue(eTermResKey.Variable) + " does not exist in parent items"; + AA.Description = $"Flow control mapped to { GingerDicser.GetTermResValue(eTermResKey.Variable) } which does not exist"; ; + AA.Details = $"'{ vals[0].Trim() }' { GingerDicser.GetTermResValue(eTermResKey.Variable) } does not exist in parent items"; AA.HowToFix = "Remap the Flow Control Action"; AA.CanAutoFix = AnalyzerItemBase.eCanFix.No; AA.IssueType = eType.Error; @@ -172,8 +172,8 @@ public static List Analyze(BusinessFlow BusinessFlow, Activity if (activities.FirstOrDefault(x => x.ActivityName == RunSharedRepositoryActivity) == null) { AnalyzeAction AA = CreateNewIssue(BusinessFlow, parentActivity, a); - AA.Description = "Flow control mapped to Shared Repository " + GingerDicser.GetTermResValue(eTermResKey.Activity) + " which does not exist"; - AA.Details = "'" + RunSharedRepositoryActivity + "' " + GingerDicser.GetTermResValue(eTermResKey.Activity) + " does not exist in Shared Repository"; + AA.Description = $"Flow control mapped to Shared Repository { GingerDicser.GetTermResValue(eTermResKey.Activity) } which does not exist"; + AA.Details = $"'{ RunSharedRepositoryActivity }' { GingerDicser.GetTermResValue(eTermResKey.Activity) } does not exist in Shared Repository"; AA.HowToFix = "Remap the Flow Control Action"; AA.CanAutoFix = AnalyzerItemBase.eCanFix.No; AA.IssueType = eType.Error; @@ -192,8 +192,8 @@ public static List Analyze(BusinessFlow BusinessFlow, Activity if (BusinessFlow.Activities.FirstOrDefault(x => x.ActivityName == activityToGoTo) == null) { AnalyzeAction AA = CreateNewIssue(BusinessFlow, parentActivity, a); - AA.Description = "Flow control mapped to " + GingerDicser.GetTermResValue(eTermResKey.Activity) + " which does not exist"; - AA.Details = "'" + activityToGoTo + "' " + GingerDicser.GetTermResValue(eTermResKey.Activity) + " does not exist in the parent " + GingerDicser.GetTermResValue(eTermResKey.BusinessFlow); + AA.Description = $"Flow control mapped to { GingerDicser.GetTermResValue(eTermResKey.Activity) } which does not exist"; + AA.Details = $"'{ activityToGoTo }' { GingerDicser.GetTermResValue(eTermResKey.Activity) } does not exist in the parent { GingerDicser.GetTermResValue(eTermResKey.BusinessFlow)}"; AA.HowToFix = "Remap the Flow Control Action"; AA.CanAutoFix = AnalyzerItemBase.eCanFix.No; AA.IssueType = eType.Error; @@ -314,12 +314,12 @@ public static List Analyze(BusinessFlow BusinessFlow, Activity if (BusinessFlow.GetAllVariables(parentActivity).Where(x => x.Name == Var).Select(x => x.Name).FirstOrDefault() == null) { AnalyzeAction AA = CreateNewIssue(BusinessFlow, parentActivity, a); - AA.Description = "The " + GingerDicser.GetTermResValue(eTermResKey.Variable) + " '" + Var + "' is missing"; - AA.Details = "The " + GingerDicser.GetTermResValue(eTermResKey.Variable) + ": '" + Var + "' Does not exist In " + GingerDicser.GetTermResValue(eTermResKey.BusinessFlow) + " '" + BusinessFlow.Name + "' => " + GingerDicser.GetTermResValue(eTermResKey.Activity) + " '" + parentActivity.ActivityName + "' =>" + "Action '" + a.Description + "' "; - AA.HowToFix = " Create new " + GingerDicser.GetTermResValue(eTermResKey.Variable) + " or Delete it from the action"; + AA.Description = $"The { GingerDicser.GetTermResValue(eTermResKey.Variable) } '{ Var }' is missing"; + AA.Details = $"The { GingerDicser.GetTermResValue(eTermResKey.Variable) }: '{ Var }' Does not exist In { GingerDicser.GetTermResValue(eTermResKey.BusinessFlow) } '{ BusinessFlow.Name }' => { GingerDicser.GetTermResValue(eTermResKey.Activity) } '{ parentActivity.ActivityName }' => Action '{ a.Description }' "; + AA.HowToFix = $" Create new { GingerDicser.GetTermResValue(eTermResKey.Variable) } or Delete it from the action"; AA.CanAutoFix = AnalyzerItemBase.eCanFix.No; AA.IssueType = eType.Error; - AA.Impact = GingerDicser.GetTermResValue(eTermResKey.Activity) + " will fail due to missing " + GingerDicser.GetTermResValue(eTermResKey.Variable); + AA.Impact = $"{GingerDicser.GetTermResValue(eTermResKey.Activity) } will fail due to missing { GingerDicser.GetTermResValue(eTermResKey.Variable)}"; AA.Severity = eSeverity.High; AA.IssueCategory = eIssueCategory.MissingVariable; @@ -341,12 +341,12 @@ public static List Analyze(BusinessFlow BusinessFlow, Activity if (globalParam == null) { AnalyzeAction AA = CreateNewIssue(BusinessFlow, parentActivity, a); - AA.Description = "The Application Global Parameter " + Param + " is missing"; - AA.Details = "The Application Global Parameter: '" + Param + "' Does not exist in Models Global Parameters"; + AA.Description = $"The Application Global Parameter { Param } is missing"; + AA.Details = $"The Application Global Parameter: '{ Param }' Does not exist in Models Global Parameters"; AA.HowToFix = " Create new Application Global Parameter or Delete it from the action."; AA.CanAutoFix = AnalyzerItemBase.eCanFix.No; AA.IssueType = eType.Error; - AA.Impact = GingerDicser.GetTermResValue(eTermResKey.Activity) + " will fail due to missing " + GingerDicser.GetTermResValue(eTermResKey.Variable); + AA.Impact = $"{GingerDicser.GetTermResValue(eTermResKey.Activity)} will fail due to missing { GingerDicser.GetTermResValue(eTermResKey.Variable)}"; AA.Severity = eSeverity.High; IssuesList.Add(AA); } @@ -359,9 +359,9 @@ public static List Analyze(BusinessFlow BusinessFlow, Activity foreach (string Param in mMissingStoreToGlobalParameters) { AnalyzeAction AA = CreateNewIssue(BusinessFlow, parentActivity, a); - AA.Description = "The Output Value with Parameter '" + Param + "' is having store to Parameter which doesn't exist anymore"; - AA.Details = "The Output Value with Parameter: '" + Param + "' can be found at " + GingerDicser.GetTermResValue(eTermResKey.BusinessFlow) + " '" + BusinessFlow.Name + "' => " + GingerDicser.GetTermResValue(eTermResKey.Activity) + " '" + parentActivity.ActivityName + "' =>" + "Action '" + a.Description + "' "; - AA.HowToFix = " Create new Parameter and change to it in the 'Store to' dropdown under the above path"; + AA.Description = $"The Output Value with Parameter '{ Param }' is having store to Parameter which doesn't exist anymore"; + AA.Details = $"The Output Value with Parameter: '{ Param }' can be found at { GingerDicser.GetTermResValue(eTermResKey.BusinessFlow) } '{ BusinessFlow.Name }' => { GingerDicser.GetTermResValue(eTermResKey.Activity) } '{ parentActivity.ActivityName }' => Action '{ a.Description }' "; + AA.HowToFix = " Create new Parameter and change to it in the 'Store to' drop-down under the above path"; AA.CanAutoFix = AnalyzerItemBase.eCanFix.No; AA.IssueType = eType.Error; AA.Impact = GingerDicser.GetTermResValue(eTermResKey.Activity) + " will fail due to missing Parameter"; @@ -379,12 +379,12 @@ public static List Analyze(BusinessFlow BusinessFlow, Activity { string list = string.Join(",", driverActs.Select(x => x.ActionDescription).ToList().ToArray()); AnalyzeAction AA = CreateNewIssue(BusinessFlow, parentActivity, a); - AA.Description = GingerDicser.GetTermResValue(eTermResKey.Activity) + " has forbidden combinations"; - AA.Details = GingerDicser.GetTermResValue(eTermResKey.Activity) + " has " + a.ActionDescription + " Action with the following platform actions: " + list + ".\nPlatform action inside this current " + GingerDicser.GetTermResValue(eTermResKey.Activity) + " will try to activate the agent before the application is launch(will cause agent issue)."; - AA.HowToFix = "Open the " + GingerDicser.GetTermResValue(eTermResKey.BusinessFlow) + " " + GingerDicser.GetTermResValue(eTermResKey.Activity) + " and put " + a.ActionDescription + " Action in a separate " + GingerDicser.GetTermResValue(eTermResKey.Activity); + AA.Description = $"{GingerDicser.GetTermResValue(eTermResKey.Activity) } has forbidden combinations"; + AA.Details = $"{GingerDicser.GetTermResValue(eTermResKey.Activity) } has { a.ActionDescription } Action with the following platform actions: { list }.\nPlatform action inside this current { GingerDicser.GetTermResValue(eTermResKey.Activity) } will try to activate the agent before the application is launch(will cause agent issue)."; + AA.HowToFix = $"Open the { GingerDicser.GetTermResValue(eTermResKey.BusinessFlow) } { GingerDicser.GetTermResValue(eTermResKey.Activity) } and put { a.ActionDescription } Action in a separate { GingerDicser.GetTermResValue(eTermResKey.Activity)}"; AA.CanAutoFix = AnalyzerItemBase.eCanFix.No; // we can autofix by delete, but don't want to AA.IssueType = eType.Error; - AA.Impact = GingerDicser.GetTermResValue(eTermResKey.Activity) + " will be executed and will fail due to java agent connection"; + AA.Impact = $"{GingerDicser.GetTermResValue(eTermResKey.Activity) } will be executed and will fail due to java agent connection"; AA.Severity = eSeverity.High; IssuesList.Add(AA); @@ -411,8 +411,8 @@ public static List Analyze(BusinessFlow BusinessFlow, Activity { AnalyzeAction AA = CreateNewIssue(BusinessFlow, parentActivity, a); AA.Description = "Action's mapped Page Objects Model is missing"; - AA.Details = "Action " + a.ActionDescription + " has mapped Page Objects Model which is missing, reason can be that the Page Objects Model has been deleted after mapping it to this action."; - AA.HowToFix = "Open the " + GingerDicser.GetTermResValue(eTermResKey.BusinessFlow) + " " + GingerDicser.GetTermResValue(eTermResKey.Activity) + " and the Action in order to map different Page Objects Model and Element"; + AA.Details = $"Action { a.ActionDescription } has mapped Page Objects Model which is missing, reason can be that the Page Objects Model has been deleted after mapping it to this action."; + AA.HowToFix = $"Open the { GingerDicser.GetTermResValue(eTermResKey.BusinessFlow) } { GingerDicser.GetTermResValue(eTermResKey.Activity) } and the Action in order to map different Page Objects Model and Element"; AA.CanAutoFix = AnalyzerItemBase.eCanFix.No; AA.IssueType = eType.Error; AA.Impact = "Action will fail during execution"; @@ -428,8 +428,8 @@ public static List Analyze(BusinessFlow BusinessFlow, Activity { AnalyzeAction AA = CreateNewIssue(BusinessFlow, parentActivity, a); AA.Description = "Page Objects Model Element which mapped to this action is missing"; - AA.Details = "Action " + a.ActionDescription + " has mapped Page Objects Model Element which is missing, reason can be that the Element has been deleted after mapping it to this action."; - AA.HowToFix = "Open the " + GingerDicser.GetTermResValue(eTermResKey.BusinessFlow) + " " + GingerDicser.GetTermResValue(eTermResKey.Activity) + " and the Action in order to map different Element"; + AA.Details = $"Action { a.ActionDescription } has mapped Page Objects Model Element which is missing, reason can be that the Element has been deleted after mapping it to this action."; + AA.HowToFix = $"Open the { GingerDicser.GetTermResValue(eTermResKey.BusinessFlow) } { GingerDicser.GetTermResValue(eTermResKey.Activity) } and the Action in order to map different Element"; AA.CanAutoFix = AnalyzerItemBase.eCanFix.No; AA.IssueType = eType.Error; AA.Impact = "Action will fail during execution"; @@ -445,8 +445,8 @@ public static List Analyze(BusinessFlow BusinessFlow, Activity //TODO: try to find the failure outside exception AnalyzeAction AA = CreateNewIssue(BusinessFlow, parentActivity, a); AA.Description = "Action's mapped Page Objects Model or Element is invalid"; - AA.Details = "Action " + a.ActionDescription + " has invalid mapped Page Objects Model or Element."; - AA.HowToFix = "Open the " + GingerDicser.GetTermResValue(eTermResKey.BusinessFlow) + " " + GingerDicser.GetTermResValue(eTermResKey.Activity) + " and the Action in order to map different Page Objects Model and Element"; + AA.Details = $"Action { a.ActionDescription } has invalid mapped Page Objects Model or Element."; + AA.HowToFix = $"Open the { GingerDicser.GetTermResValue(eTermResKey.BusinessFlow) } { GingerDicser.GetTermResValue(eTermResKey.Activity) } and the Action in order to map different Page Objects Model and Element"; AA.CanAutoFix = AnalyzerItemBase.eCanFix.No; AA.IssueType = eType.Error; AA.Impact = "Action will fail during execution"; @@ -464,8 +464,8 @@ public static List Analyze(BusinessFlow BusinessFlow, Activity if (a.InputValues.Where(aiv => AIV != null && aiv != null && aiv.Param == AIV.Param).ToList().Count > 1) { AnalyzeAction AA = CreateNewIssue(BusinessFlow, parentActivity, a); - AA.Description = "The Input Value Parameter " + AIV.Param + " is Duplicate"; - AA.Details = "The Input Value Parameter: '" + AIV.Param + "' is duplicate in the ActInputValues"; + AA.Description = $"The Input Value Parameter { AIV.Param } is Duplicate"; + AA.Details = $"The Input Value Parameter: '{ AIV.Param }' is duplicate in the ActInputValues"; AA.HowToFix = "Open action Edit page and save it."; AA.CanAutoFix = AnalyzerItemBase.eCanFix.Yes; AA.IssueType = eType.Warning; @@ -586,7 +586,7 @@ public static void AnalyzeValueExpInAction(Act action, BusinessFlow businessFlow mActivity = activity, Description = $"Cannot Calculate Value Expression: {filteredValueExp}", ItemName = action.Description, - ItemParent = businessFlow.Name + " > " + activity.ActivityName, + ItemParent = $"{businessFlow.Name } > { activity.ActivityName}", mAction = action, mBusinessFlow = businessFlow, ItemClass = "Action", diff --git a/Ginger/GingerCoreNET/Drivers/CoreDrivers/Web/ActionHandlers/ActBrowserElementHandler.cs b/Ginger/GingerCoreNET/Drivers/CoreDrivers/Web/ActionHandlers/ActBrowserElementHandler.cs index 870bca4eb5..fcb861194f 100644 --- a/Ginger/GingerCoreNET/Drivers/CoreDrivers/Web/ActionHandlers/ActBrowserElementHandler.cs +++ b/Ginger/GingerCoreNET/Drivers/CoreDrivers/Web/ActionHandlers/ActBrowserElementHandler.cs @@ -20,6 +20,7 @@ limitations under the License. using Amdocs.Ginger.Common; using Amdocs.Ginger.Common.UIElement; using Amdocs.Ginger.CoreNET.Drivers.CoreDrivers.Web.Exceptions; +using Amdocs.Ginger.CoreNET.Drivers.CoreDrivers.Web.Playwright; using Amdocs.Ginger.Repository; using GingerCore; using GingerCore.Actions; @@ -27,6 +28,7 @@ limitations under the License. using System; using System.Collections.Generic; using System.Linq; +using System.Reflection; using System.Text.Json; using System.Text.Json.Nodes; using System.Threading.Tasks; @@ -145,6 +147,29 @@ internal async Task HandleAsync() case ActBrowserElement.eControlAction.SwitchToDefaultWindow: await HandleSwitchToDefaultWindowOperationAsync(); break; + case ActBrowserElement.eControlAction.AcceptMessageBox: + await HandleAcceptMessageBoxOperationAsync(); + break; + case ActBrowserElement.eControlAction.DismissMessageBox: + await HandleDismissMessageBoxOperationAsync(); + break; + case ActBrowserElement.eControlAction.GetMessageBoxText: + _act.AddOrUpdateReturnParamActual("Actual", HandleGetMessageBoxTextOperation()); + break; + case ActBrowserElement.eControlAction.SetAlertBoxText: + string MessageBoxText = _act.GetInputParamCalculatedValue("Value"); + await HandleSetMessageBoxTextOperationAsync(MessageBoxText); + break; + + case ActBrowserElement.eControlAction.StartMonitoringNetworkLog: + await HandleStartMonitoringNetworkLogOperationAsync(); + break; + case ActBrowserElement.eControlAction.GetNetworkLog: + await HandleGetNetworkLogOperationAsync(); + break; + case ActBrowserElement.eControlAction.StopMonitoringNetworkLog: + await HandleStopMonitoringNetworkLogOperationAsync(); + break; default: string operationName = Common.GeneralLib.General.GetEnumValueDescription(typeof(ActBrowserElement.eControlAction), _act.ControlAction); _act.Error = $"Operation '{operationName}' is not supported"; @@ -538,5 +563,132 @@ private async Task HandleSwitchToDefaultWindowOperationAsync() await _browser.CurrentWindow.SetTabAsync(firstTab); } + /// + /// This asynchronous method accepts a message box (such as a dialog box) in the current browser tab. + /// If an error occurs, it logs the error and updates the Error property. + /// + /// + private async Task HandleAcceptMessageBoxOperationAsync() + { + try + { + await ((PlaywrightBrowserTab)_browser!.CurrentWindow.CurrentTab).AcceptMessageBox(); + } + catch (Exception ex) + { + _act.Error = $"Error when handling message box operation."; + Reporter.ToLog(eLogLevel.ERROR, $"Method - {MethodBase.GetCurrentMethod().Name}, Error - {ex.Message}", ex); + return; + } + } + /// + /// This asynchronous method dismisses a message box (closes it) in the current browser tab. + /// If an error occurs, it logs the error and updates the Error property. + /// + /// + private async Task HandleDismissMessageBoxOperationAsync() + { + try + { + await ((PlaywrightBrowserTab)_browser!.CurrentWindow.CurrentTab).DismissMessageBox(); + } + catch (Exception ex) + { + _act.Error = $"Error when handling message box operation."; + Reporter.ToLog(eLogLevel.ERROR, $"Method - {MethodBase.GetCurrentMethod().Name}, Error - {ex.Message}", ex); + return; + } + } + /// + /// This method retrieves the text of the message box from the current browser tab. + /// If an error occurs, it logs the error and returns an empty string. + + /// + /// + private string HandleGetMessageBoxTextOperation() + { + try + { + return ((PlaywrightBrowserTab)_browser!.CurrentWindow.CurrentTab).GetMessageBoxText(); + } + catch (Exception ex) + { + _act.Error = $"Error when handling message box operation."; + Reporter.ToLog(eLogLevel.ERROR, $"Method - {MethodBase.GetCurrentMethod().Name}, Error - {ex.Message}", ex); + return string.Empty; + } + } + /// + /// This asynchronous method sets the text of the message box in the current browser tab. + /// If an error occurs, it logs the error. + /// + /// + /// + private async Task HandleSetMessageBoxTextOperationAsync(string MessageBoxText) + { + try + { + await ((PlaywrightBrowserTab)_browser!.CurrentWindow.CurrentTab).SetMessageBoxText(MessageBoxText); + } + catch (Exception ex) + { + _act.Error = $"Error when handling message box operation."; + Reporter.ToLog(eLogLevel.ERROR, $"Method - {MethodBase.GetCurrentMethod().Name}, Error - {ex.Message}", ex); + } + } + /// + /// This asynchronous method starts monitoring and capturing network logs in the current browser tab. If an error occurs, + /// it logs the error and updates the Error property. + /// + /// + private async Task HandleStartMonitoringNetworkLogOperationAsync() + { + try + { + await ((PlaywrightBrowserTab)_browser!.CurrentWindow.CurrentTab).StartCaptureNetworkLog(_act); + } + catch (Exception ex) + { + _act.Error = $"Error when handling Network log operation."; + Reporter.ToLog(eLogLevel.ERROR, $"Method - {MethodBase.GetCurrentMethod().Name}, Error - {ex.Message}", ex); + return; + } + } + /// + /// This asynchronous method retrieves the captured network logs from the current browser tab. + /// If an error occurs, it logs the error and updates the Error property. + /// + /// + private async Task HandleGetNetworkLogOperationAsync() + { + try + { + await ((PlaywrightBrowserTab)_browser!.CurrentWindow.CurrentTab).GetCaptureNetworkLog(_act); + } + catch (Exception ex) + { + _act.Error = $"Error when handling Network log operation."; + Reporter.ToLog(eLogLevel.ERROR, $"Method - {MethodBase.GetCurrentMethod().Name}, Error - {ex.Message}", ex); + return; + } + } + /// + /// This asynchronous method stops monitoring and capturing network logs in the current browser tab. + /// If an error occurs, it logs the error and updates the Error property. + /// + /// + private async Task HandleStopMonitoringNetworkLogOperationAsync() + { + try + { + await ((PlaywrightBrowserTab)_browser!.CurrentWindow.CurrentTab).StopCaptureNetworkLog(_act); + } + catch (Exception ex) + { + _act.Error = $"Error when handling Network log operation."; + Reporter.ToLog(eLogLevel.ERROR, $"Method - {MethodBase.GetCurrentMethod().Name}, Error - {ex.Message}", ex); + return; + } + } } } diff --git a/Ginger/GingerCoreNET/Drivers/CoreDrivers/Web/BrowserHelper.cs b/Ginger/GingerCoreNET/Drivers/CoreDrivers/Web/BrowserHelper.cs new file mode 100644 index 0000000000..7d0fb1169e --- /dev/null +++ b/Ginger/GingerCoreNET/Drivers/CoreDrivers/Web/BrowserHelper.cs @@ -0,0 +1,75 @@ +using amdocs.ginger.GingerCoreNET; +using Amdocs.Ginger.Common; +using GingerCore.Actions; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Threading.Tasks; + +namespace Amdocs.Ginger.CoreNET.Drivers.CoreDrivers.Web +{ + internal class BrowserHelper + { + private readonly ActBrowserElement _act; + public BrowserHelper(ActBrowserElement act) { + _act = act; + } + + public bool ShouldMonitorAllUrls() + { + return _act.GetOrCreateInputParam(nameof(ActBrowserElement.eMonitorUrl)).Value == nameof(ActBrowserElement.eMonitorUrl.AllUrl); + } + + public bool ShouldMonitorUrl(string requestUrl) + { + return _act.GetOrCreateInputParam(nameof(ActBrowserElement.eMonitorUrl)).Value == nameof(ActBrowserElement.eMonitorUrl.SelectedUrl) + && _act.UpdateOperationInputValues != null + && _act.UpdateOperationInputValues.Any(x => !string.IsNullOrEmpty(x.ValueForDriver) && requestUrl.ToLower().Contains(x.ValueForDriver.ToLower())); + } + + public string CreateNetworkLogFile(string Filename, List> networkLogList) + { + if (string.IsNullOrEmpty(Filename)) + { + Reporter.ToLog(eLogLevel.INFO, $"Method - {MethodBase.GetCurrentMethod().Name}, Filename should not be empty"); + } + + if (networkLogList == null) + { + Reporter.ToLog(eLogLevel.INFO, $"Method - {MethodBase.GetCurrentMethod().Name}, networkLogList should not be empty"); + } + string FullFilePath = string.Empty; + try + { + string FullDirectoryPath = System.IO.Path.Combine(WorkSpace.Instance.Solution.Folder, "Documents", "NetworkLog"); + if (!System.IO.Directory.Exists(FullDirectoryPath)) + { + System.IO.Directory.CreateDirectory(FullDirectoryPath); + } + + FullFilePath = $"FullDirectoryPath{Path.PathSeparator}{Filename}_{DateTime.Now.Day.ToString() }_{ DateTime.Now.Month.ToString() }_{ DateTime.Now.Year.ToString() }_{DateTime.Now.Millisecond.ToString()}.har"; + if (!System.IO.File.Exists(FullFilePath)) + { + string FileContent = JsonConvert.SerializeObject(networkLogList.Select(x => x.Item2).ToList()); + + using (Stream fileStream = System.IO.File.Create(FullFilePath)) + { + fileStream.Close(); + } + System.IO.File.WriteAllText(FullFilePath, FileContent); + } + } + catch(Exception ex) + { + Reporter.ToLog(eLogLevel.ERROR, $"Method - {MethodBase.GetCurrentMethod().Name} Error: {ex.Message}", ex); + } + return FullFilePath; + + + } + } +} diff --git a/Ginger/GingerCoreNET/Drivers/CoreDrivers/Web/Playwright/PlaywrightBrowserTab.cs b/Ginger/GingerCoreNET/Drivers/CoreDrivers/Web/Playwright/PlaywrightBrowserTab.cs index ecad81981b..99333987fd 100644 --- a/Ginger/GingerCoreNET/Drivers/CoreDrivers/Web/Playwright/PlaywrightBrowserTab.cs +++ b/Ginger/GingerCoreNET/Drivers/CoreDrivers/Web/Playwright/PlaywrightBrowserTab.cs @@ -16,15 +16,20 @@ limitations under the License. */ #endregion +using Amdocs.Ginger.Common; using Amdocs.Ginger.Common.UIElement; using Amdocs.Ginger.CoreNET.Drivers.CoreDrivers.Web.Exceptions; using Deque.AxeCore.Commons; using Deque.AxeCore.Playwright; +using GingerCore.Actions; using Microsoft.Playwright; +using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Drawing; +using System.IO; using System.Linq; +using System.Reflection; using System.Text.Json; using System.Text.Json.Nodes; using System.Threading.Tasks; @@ -63,8 +68,14 @@ internal sealed class PlaywrightBrowserTab : IBrowserTab private readonly LinkedList _consoleMessages = []; private IFrame _currentFrame; private bool _isClosed = false; + List> networkResponseLogList; + List> networkRequestLogList; + ActBrowserElement _act; + public bool isNetworkLogMonitoringStarted = false; + IDialog dialogs; public bool IsClosed => _isClosed; + BrowserHelper _BrowserHelper; internal PlaywrightBrowserTab(IPlaywrightPage playwrightPage, IBrowserTab.OnTabClose onTabClose) { @@ -73,6 +84,7 @@ internal PlaywrightBrowserTab(IPlaywrightPage playwrightPage, IBrowserTab.OnTabC _currentFrame = _playwrightPage.MainFrame; _playwrightPage.Console += OnConsoleMessage; _playwrightPage.Close += OnPlaywrightPageClose; + _playwrightPage.Dialog += OnPlaywrightDialog; } private void RemoveEventHandlers() @@ -605,6 +617,308 @@ public static bool IsFrameLocatorSupported(eLocateBy locateBy) { return SupportedFrameLocators.Contains(locateBy); } + /// + /// This asynchronous method initiates the process of capturing network logs for the current page. + /// It sets up the necessary data structures and event handlers to monitor network requests and responses. + /// + /// + /// + public async Task StartCaptureNetworkLog(ActBrowserElement act) + { + _act = act; + _BrowserHelper = new BrowserHelper(act); + try + { + networkRequestLogList = []; + networkResponseLogList = []; + _playwrightPage.Request += OnNetworkRequestSent; + _playwrightPage.Response += OnNetworkResponseReceived; + isNetworkLogMonitoringStarted = true; + } + catch(Exception ex) + { + Reporter.ToLog(eLogLevel.ERROR, $"Method - {MethodBase.GetCurrentMethod().Name}, Error - {ex.Message}", ex); + } + + } + /// + /// This asynchronous method retrieves the captured network logs (requests and responses) for the current browser element and stores them in the act object. + /// It only performs the action if network log monitoring has been started. + /// + /// + /// + public async Task GetCaptureNetworkLog(ActBrowserElement act) + { + _act = act; + _BrowserHelper = new BrowserHelper(act); + try + { + await Task.Run(() => + { + if (isNetworkLogMonitoringStarted) + { + act.AddOrUpdateReturnParamActual("Raw Request", Newtonsoft.Json.JsonConvert.SerializeObject(networkRequestLogList.Select(x => x.Item2).ToList(), Formatting.Indented)); + act.AddOrUpdateReturnParamActual("Raw Response", Newtonsoft.Json.JsonConvert.SerializeObject(networkResponseLogList.Select(x => x.Item2).ToList(), Formatting.Indented)); + foreach (var val in networkRequestLogList.ToList()) + { + act.AddOrUpdateReturnParamActual($"{act.ControlAction.ToString()} {val.Item1}", Convert.ToString(val.Item2)); + } + + foreach (var val in networkResponseLogList.ToList()) + { + act.AddOrUpdateReturnParamActual($"{act.ControlAction.ToString()} {val.Item1}", Convert.ToString(val.Item2)); + } + } + else + { + act.ExInfo = $"Action is skipped,{nameof(ActBrowserElement.eControlAction.StartMonitoringNetworkLog)} Action is not started"; + act.Status = Amdocs.Ginger.CoreNET.Execution.eRunStatus.Skipped; + } + }); + } + catch (Exception ex) + { + Reporter.ToLog(eLogLevel.ERROR, $"Method - {MethodBase.GetCurrentMethod().Name}, Error - {ex.Message}", ex); + } + } + /// + /// This asynchronous method stops the network log capture by unsubscribing from the network request and response events. + /// It then processes and stores the captured logs, saves them to files, and attaches the files as artifacts to the act object. + /// + /// + + public async Task StopCaptureNetworkLog(ActBrowserElement act) + { + _act = act; + _BrowserHelper = new BrowserHelper(act); + try + { + await Task.Run(() => + { + try + { + _playwrightPage.Request -= OnNetworkRequestSent; + _playwrightPage.Response -= OnNetworkResponseReceived; + isNetworkLogMonitoringStarted = false; + act.AddOrUpdateReturnParamActual("Raw Request", Newtonsoft.Json.JsonConvert.SerializeObject(networkRequestLogList.Select(x => x.Item2).ToList())); + act.AddOrUpdateReturnParamActual("Raw Response", Newtonsoft.Json.JsonConvert.SerializeObject(networkResponseLogList.Select(x => x.Item2).ToList())); + foreach (var val in networkRequestLogList) + { + act.AddOrUpdateReturnParamActual($"{act.ControlAction.ToString()} {val.Item1}", Convert.ToString(val.Item2)); + } + foreach (var val in networkResponseLogList) + { + act.AddOrUpdateReturnParamActual($"{act.ControlAction.ToString()} {val.Item1}", Convert.ToString(val.Item2)); + } + string requestPath = _BrowserHelper.CreateNetworkLogFile("NetworklogRequest", networkRequestLogList); + act.ExInfo = $"RequestFile : {requestPath}\n"; + string responsePath = _BrowserHelper.CreateNetworkLogFile("NetworklogResponse", networkResponseLogList); + act.ExInfo = $"{act.ExInfo} ResponseFile : {responsePath}\n"; + + act.AddOrUpdateReturnParamActual("RequestFile", requestPath); + act.AddOrUpdateReturnParamActual("ResponseFile", responsePath); + + Act.AddArtifactToAction(Path.GetFileName(requestPath), act, requestPath); + + Act.AddArtifactToAction(Path.GetFileName(responsePath), act, responsePath); + } + catch (Exception ex) + { + Reporter.ToLog(eLogLevel.ERROR, $"Method - {MethodBase.GetCurrentMethod().Name}, Error - {ex.Message}", ex); + } + }); + } + catch (Exception ex) + { + Reporter.ToLog(eLogLevel.ERROR, $"Method - {MethodBase.GetCurrentMethod().Name}, Error - {ex.Message}", ex); + } + + } + + + /// + /// This method handles the network request event, capturing the details of outgoing network requests. + /// It adds the request URL and its serialized data to the network log if the request matches the specified criteria. + /// + /// + /// + private async void OnNetworkRequestSent(object? sender, IRequest request) + { + try + { + if (_BrowserHelper.ShouldMonitorAllUrls() || _BrowserHelper.ShouldMonitorUrl( request.Url)) + { + networkRequestLogList.Add(new Tuple($"RequestUrl:{ request.Url}", JsonConvert.SerializeObject(request, Formatting.Indented, + new JsonSerializerSettings + { + ReferenceLoopHandling = ReferenceLoopHandling.Ignore + }) + )); + } + } + catch (Exception ex) + { + Reporter.ToLog(eLogLevel.ERROR, $"Method - {MethodBase.GetCurrentMethod().Name}, Error - {ex.Message}", ex); + } + } + /// + /// This method handles the network response event, capturing details about the response once it's received. + /// It checks if the response should be logged based on the configured criteria and adds relevant information to the network response log. + /// + /// + /// + private async void OnNetworkResponseReceived(object? sender, IResponse response) + { + await response.FinishedAsync(); + try + { + if (response != null) + { + string monitorType = _act.GetOrCreateInputParam(nameof(ActBrowserElement.eMonitorUrl)).Value; + if (_BrowserHelper.ShouldMonitorAllUrls() || _BrowserHelper.ShouldMonitorUrl(response.Url)) + { + if (_act.GetOrCreateInputParam(nameof(ActBrowserElement.eRequestTypes)).Value == ActBrowserElement.eRequestTypes.FetchOrXHR.ToString()) + { + if (response.Request.ResourceType.Equals("XHR",StringComparison.CurrentCultureIgnoreCase) || response.Request.ResourceType.Equals("FETCH", StringComparison.CurrentCultureIgnoreCase)) + { + networkResponseLogList.Add(new Tuple($"ResponseUrl:{ response.Url}", JsonConvert.SerializeObject(response, Formatting.Indented, + new JsonSerializerSettings + { + ReferenceLoopHandling = ReferenceLoopHandling.Ignore + }) + )); + } + } + else + { + networkResponseLogList.Add(new Tuple($"ResponseUrl:{response.Url}", JsonConvert.SerializeObject(response, Formatting.Indented, + new JsonSerializerSettings + { + ReferenceLoopHandling = ReferenceLoopHandling.Ignore + }) + )); + } + } + } + } + catch (Exception ex) + { + Reporter.ToLog(eLogLevel.ERROR, $"Method - {MethodBase.GetCurrentMethod().Name}, Error - {ex.Message}", ex); + } + } + + + + + + private async void OnPlaywrightDialog(object? sender, IDialog e) + { + try + { + dialogs = e; + } + catch (Exception ex) + { + Reporter.ToLog(eLogLevel.ERROR, $"Method - {MethodBase.GetCurrentMethod().Name}, Error - {ex.Message}", ex); + } + } + /// + /// This asynchronous method accepts (clicks the "OK" or equivalent) on a message box or dialog. + /// + /// + public async Task AcceptMessageBox() + { + try + { + if (dialogs != null) + { + await dialogs.AcceptAsync(); + } + else + { + Reporter.ToLog(eLogLevel.WARN, "No dialog to accept."); + } + } + catch (Exception ex) + { + Reporter.ToLog(eLogLevel.ERROR, $"Method - {MethodBase.GetCurrentMethod().Name}, Error - {ex.Message}", ex); + } + + } + /// + /// This asynchronous method dismisses (closes or cancels) a message box or dialog. + /// + /// + public async Task DismissMessageBox() + { + try + { + if (dialogs != null) + { + await dialogs.DismissAsync(); + } + else + { + Reporter.ToLog(eLogLevel.WARN, "No dialog to dismiss."); + } + + } + catch (Exception ex) + { + Reporter.ToLog(eLogLevel.ERROR, $"Method - {MethodBase.GetCurrentMethod().Name}, Error - {ex.Message}", ex); + } + + } + /// + /// This method retrieves the text content of the current message box or dialog. + /// + /// + public string GetMessageBoxText() + { + try + { + if (dialogs != null) + { + return dialogs.Message; + } + else + { + Reporter.ToLog(eLogLevel.WARN, "No dialog to get message."); + return string.Empty; + } + } + catch (Exception ex) + { + Reporter.ToLog(eLogLevel.ERROR, $"Method - {MethodBase.GetCurrentMethod().Name}, Error - {ex.Message}", ex); + return "Error While Get Message Box Text"; + } + + } + /// + /// This asynchronous method sets the text (usually for a prompt dialog) in the message box. + /// + /// + /// + public async Task SetMessageBoxText(string MessageBoxText) + { + try + { + if (dialogs != null) + { + await dialogs.AcceptAsync(promptText: MessageBoxText); + } + else + { + Reporter.ToLog(eLogLevel.WARN, "No dialog to accept."); + + } + } + catch (Exception ex) + { + Reporter.ToLog(eLogLevel.ERROR, "Error While Accept Message", ex); + } + + } } } diff --git a/Ginger/GingerCoreNET/Drivers/CoreDrivers/Web/Playwright/PlaywrightDriver.cs b/Ginger/GingerCoreNET/Drivers/CoreDrivers/Web/Playwright/PlaywrightDriver.cs index 3f0fdc1858..ee99b6bc5d 100644 --- a/Ginger/GingerCoreNET/Drivers/CoreDrivers/Web/Playwright/PlaywrightDriver.cs +++ b/Ginger/GingerCoreNET/Drivers/CoreDrivers/Web/Playwright/PlaywrightDriver.cs @@ -1810,6 +1810,13 @@ public string GetViewport() ActBrowserElement.eControlAction.SwitchToParentFrame, ActBrowserElement.eControlAction.SwitchWindow, ActBrowserElement.eControlAction.SwitchToDefaultWindow, + ActBrowserElement.eControlAction.AcceptMessageBox, + ActBrowserElement.eControlAction.DismissMessageBox, + ActBrowserElement.eControlAction.GetMessageBoxText, + ActBrowserElement.eControlAction.SetAlertBoxText, + ActBrowserElement.eControlAction.StartMonitoringNetworkLog, + ActBrowserElement.eControlAction.GetNetworkLog, + ActBrowserElement.eControlAction.StopMonitoringNetworkLog, ]; } } diff --git a/Ginger/GingerCoreNET/Drivers/CoreDrivers/Web/Selenium/SeleniumDriver.cs b/Ginger/GingerCoreNET/Drivers/CoreDrivers/Web/Selenium/SeleniumDriver.cs index 8159a92631..20716b025b 100644 --- a/Ginger/GingerCoreNET/Drivers/CoreDrivers/Web/Selenium/SeleniumDriver.cs +++ b/Ginger/GingerCoreNET/Drivers/CoreDrivers/Web/Selenium/SeleniumDriver.cs @@ -71,7 +71,7 @@ limitations under the License. using System.Threading; using System.Threading.Tasks; using static GingerCoreNET.GeneralLib.General; -using DevToolsDomains = OpenQA.Selenium.DevTools.V125.DevToolsSessionDomains; +using DevToolsDomains = OpenQA.Selenium.DevTools.V127.DevToolsSessionDomains; //.V125.DevToolsSessionDomains; @@ -88,6 +88,7 @@ public class SeleniumDriver : GingerWebDriver, IVirtualDriver, IWindowExplorer, INetwork interceptor; public bool isNetworkLogMonitoringStarted = false; ActBrowserElement mAct; + BrowserHelper _BrowserHelper; private int mDriverProcessId = 0; private readonly ShadowDOM shadowDOM = new(); private const string CHROME_DRIVER_NAME = "chromedriver"; @@ -8390,6 +8391,7 @@ private void HandleSwitchToDefaultDOM() public async void ActBrowserElementHandler(ActBrowserElement act) { + _BrowserHelper = new BrowserHelper(act); try { string AgentType = GetAgentAppName(); @@ -10891,9 +10893,9 @@ private void SetUPDevTools(IWebDriver webDriver) try { //DevTool Session - devToolsSession = devTools.GetDevToolsSession(125); + devToolsSession = devTools.GetDevToolsSession(127); devToolsDomains = devToolsSession.GetVersionSpecificDomains(); - devToolsDomains.Network.Enable(new OpenQA.Selenium.DevTools.V125.Network.EnableCommandSettings()); + devToolsDomains.Network.Enable(new OpenQA.Selenium.DevTools.V127.Network.EnableCommandSettings()); blockOrUnblockUrls(); } catch (Exception ex) @@ -10919,60 +10921,75 @@ private void blockOrUnblockUrls() { if (mAct.ControlAction == ActBrowserElement.eControlAction.SetBlockedUrls) { - devToolsDomains.Network.SetBlockedURLs(new OpenQA.Selenium.DevTools.V125.Network.SetBlockedURLsCommandSettings() { Urls = getBlockedUrlsArray(mAct.GetInputParamCalculatedValue("sBlockedUrls")) }); + devToolsDomains.Network.SetBlockedURLs(new OpenQA.Selenium.DevTools.V127.Network.SetBlockedURLsCommandSettings() { Urls = getBlockedUrlsArray(mAct.GetInputParamCalculatedValue("sBlockedUrls")) }); } else if (mAct.ControlAction == ActBrowserElement.eControlAction.UnblockeUrls) { - devToolsDomains.Network.SetBlockedURLs(new OpenQA.Selenium.DevTools.V125.Network.SetBlockedURLsCommandSettings() { Urls = new string[] { } }); + devToolsDomains.Network.SetBlockedURLs(new OpenQA.Selenium.DevTools.V127.Network.SetBlockedURLsCommandSettings() { Urls = new string[] { } }); } Thread.Sleep(300); } } public async Task GetNetworkLogAsync(ActBrowserElement act) { - if (isNetworkLogMonitoringStarted) + try { - act.AddOrUpdateReturnParamActual("Raw Request", Newtonsoft.Json.JsonConvert.SerializeObject(networkRequestLogList.Select(x => x.Item2).ToList())); - act.AddOrUpdateReturnParamActual("Raw Response", Newtonsoft.Json.JsonConvert.SerializeObject(networkResponseLogList.Select(x => x.Item2).ToList())); - foreach (var val in networkRequestLogList.ToList()) - { - act.AddOrUpdateReturnParamActual(act.ControlAction.ToString() + " " + val.Item1.ToString(), Convert.ToString(val.Item2)); - } + if (isNetworkLogMonitoringStarted) + { + act.AddOrUpdateReturnParamActual("Raw Request", Newtonsoft.Json.JsonConvert.SerializeObject(networkRequestLogList.Select(x => x.Item2).ToList())); + act.AddOrUpdateReturnParamActual("Raw Response", Newtonsoft.Json.JsonConvert.SerializeObject(networkResponseLogList.Select(x => x.Item2).ToList())); + foreach (var val in networkRequestLogList.ToList()) + { + act.AddOrUpdateReturnParamActual($"{act.ControlAction.ToString()} {val.Item1}", Convert.ToString(val.Item2)); + } - foreach (var val in networkResponseLogList.ToList()) - { - act.AddOrUpdateReturnParamActual(act.ControlAction.ToString() + " " + val.Item1.ToString(), Convert.ToString(val.Item2)); - } + foreach (var val in networkResponseLogList.ToList()) + { + act.AddOrUpdateReturnParamActual($"{act.ControlAction.ToString()} {val.Item1}", Convert.ToString(val.Item2)); + } + } + else + { + act.ExInfo = $"Action is skipped,{nameof(ActBrowserElement.eControlAction.StartMonitoringNetworkLog)} Action is not started"; + act.Status = Amdocs.Ginger.CoreNET.Execution.eRunStatus.Skipped; + } } - else + catch(Exception ex) { - act.ExInfo = "Action is skipped," + ActBrowserElement.eControlAction.StartMonitoringNetworkLog.ToString() + " Action is not started"; - act.Status = Amdocs.Ginger.CoreNET.Execution.eRunStatus.Skipped; + Reporter.ToLog(eLogLevel.ERROR, $"Method - {MethodBase.GetCurrentMethod().Name}, Error - {ex.Message}", ex); } + } public async Task StartMonitoringNetworkLog(IWebDriver webDriver) { - networkRequestLogList = []; - networkResponseLogList = []; - interceptor = webDriver.Manage().Network; + try + { + networkRequestLogList = []; + networkResponseLogList = []; + interceptor = webDriver.Manage().Network; - ProjEnvironment projEnv = GetCurrentProjectEnvironment(); + ProjEnvironment projEnv = GetCurrentProjectEnvironment(); - ValueExpression VE = new ValueExpression(projEnv, BusinessFlow); + ValueExpression VE = new ValueExpression(projEnv, BusinessFlow); - foreach (ActInputValue item in mAct.UpdateOperationInputValues) - { - item.Value = item.Param; - item.ValueForDriver = VE.Calculate(item.Param); - } + foreach (ActInputValue item in mAct.UpdateOperationInputValues) + { + item.Value = item.Param; + item.ValueForDriver = VE.Calculate(item.Param); + } - interceptor.NetworkRequestSent += OnNetworkRequestSent; - interceptor.NetworkResponseReceived += OnNetworkResponseReceived; + interceptor.NetworkRequestSent += OnNetworkRequestSent; + interceptor.NetworkResponseReceived += OnNetworkResponseReceived; - await interceptor.StartMonitoring(); - isNetworkLogMonitoringStarted = true; + await interceptor.StartMonitoring(); + isNetworkLogMonitoringStarted = true; + } + catch (Exception ex) + { + Reporter.ToLog(eLogLevel.ERROR, $"Method - {MethodBase.GetCurrentMethod().Name}, Error - {ex.Message}", ex); + } } private ProjEnvironment GetCurrentProjectEnvironment() @@ -11001,25 +11018,25 @@ public async Task StopMonitoringNetworkLog(ActBrowserElement act) interceptor.NetworkResponseReceived -= OnNetworkResponseReceived; interceptor.ClearRequestHandlers(); interceptor.ClearResponseHandlers(); - act.AddOrUpdateReturnParamActual("Raw Request", Newtonsoft.Json.JsonConvert.SerializeObject(networkRequestLogList.Select(x => x.Item2).ToList())); - act.AddOrUpdateReturnParamActual("Raw Response", Newtonsoft.Json.JsonConvert.SerializeObject(networkResponseLogList.Select(x => x.Item2).ToList())); + act.AddOrUpdateReturnParamActual("Raw Request", Newtonsoft.Json.JsonConvert.SerializeObject(networkRequestLogList.Select(x => x.Item2).ToList(), Formatting.Indented)); + act.AddOrUpdateReturnParamActual("Raw Response", Newtonsoft.Json.JsonConvert.SerializeObject(networkResponseLogList.Select(x => x.Item2).ToList(), Formatting.Indented)); foreach (var val in networkRequestLogList.ToList()) { - act.AddOrUpdateReturnParamActual(act.ControlAction.ToString() + " " + val.Item1.ToString(), Convert.ToString(val.Item2)); + act.AddOrUpdateReturnParamActual($"{act.ControlAction.ToString()} {val.Item1}", Convert.ToString(val.Item2)); } - foreach (var val in networkRequestLogList.ToList()) + foreach (var val in networkResponseLogList.ToList()) { - act.AddOrUpdateReturnParamActual(act.ControlAction.ToString() + " " + val.Item1.ToString(), Convert.ToString(val.Item2)); + act.AddOrUpdateReturnParamActual($"{act.ControlAction.ToString() } {val.Item1}", Convert.ToString(val.Item2)); } - await devToolsDomains.Network.Disable(new OpenQA.Selenium.DevTools.V125.Network.DisableCommandSettings()); + await devToolsDomains.Network.Disable(new OpenQA.Selenium.DevTools.V127.Network.DisableCommandSettings()); devToolsSession.Dispose(); devTools.CloseDevToolsSession(); - string requestPath = CreateNetworkLogFile("NetworklogRequest"); - act.ExInfo = "RequestFile : " + requestPath + "\n"; - string responsePath = CreateNetworkLogFile("NetworklogResponse"); - act.ExInfo = act.ExInfo + "ResponseFile : " + responsePath + "\n"; + string requestPath = _BrowserHelper.CreateNetworkLogFile("NetworklogRequest", networkRequestLogList); + act.ExInfo = $"RequestFile : { requestPath }\n"; + string responsePath = _BrowserHelper.CreateNetworkLogFile("NetworklogResponse", networkResponseLogList); + act.ExInfo = $"{act.ExInfo} ResponseFile : {responsePath}\n"; act.AddOrUpdateReturnParamActual("RequestFile", requestPath); act.AddOrUpdateReturnParamActual("ResponseFile", responsePath); @@ -11030,41 +11047,17 @@ public async Task StopMonitoringNetworkLog(ActBrowserElement act) } else { - act.ExInfo = "Action is skipped," + ActBrowserElement.eControlAction.StartMonitoringNetworkLog.ToString() + " Action is not started"; + act.ExInfo = $"Action is skipped,{nameof(ActBrowserElement.eControlAction.StartMonitoringNetworkLog)} Action is not started"; act.Status = Amdocs.Ginger.CoreNET.Execution.eRunStatus.Skipped; } } catch (Exception ex) { - throw ex; + Reporter.ToLog(eLogLevel.ERROR, $"Method - {MethodBase.GetCurrentMethod().Name}, Error - {ex.Message}", ex); } } - private string CreateNetworkLogFile(string Filename) - { - string FullFilePath = string.Empty; - string FullDirectoryPath = System.IO.Path.Combine(WorkSpace.Instance.Solution.Folder, "Documents", "NetworkLog"); - if (!System.IO.Directory.Exists(FullDirectoryPath)) - { - System.IO.Directory.CreateDirectory(FullDirectoryPath); - } - - FullFilePath = FullDirectoryPath + @"\" + Filename + DateTime.Now.Day.ToString() + "_" + DateTime.Now.Month.ToString() + "_" + DateTime.Now.Year.ToString() + "_" + DateTime.Now.Millisecond.ToString() + ".har"; - if (!System.IO.File.Exists(FullFilePath)) - { - string FileContent = Filename.Contains("Request") ? JsonConvert.SerializeObject(networkRequestLogList.Select(x => x.Item2).ToList()) : JsonConvert.SerializeObject(networkResponseLogList.Select(x => x.Item2).ToList()); - - using (Stream fileStream = System.IO.File.Create(FullFilePath)) - { - fileStream.Close(); - } - System.IO.File.WriteAllText(FullFilePath, FileContent); - - } - return FullFilePath; - } - private int CreateConsoleLogFile(string filePath, string logs, ActBrowserElement act) { string calculatedFilePath = WorkSpace.Instance.Solution.SolutionOperations.ConvertSolutionRelativePath(filePath); @@ -11100,28 +11093,18 @@ private void OnNetworkRequestSent(object sender, NetworkRequestSentEventArgs e) { try { - if (IsToMonitorAllUrls() || IsToMonitorOnlySelectedUrls(e.RequestUrl)) + if (_BrowserHelper.ShouldMonitorAllUrls() || _BrowserHelper.ShouldMonitorUrl( e.RequestUrl)) { - networkRequestLogList.Add(new Tuple("RequestUrl:" + e.RequestUrl, JsonConvert.SerializeObject(e))); + networkRequestLogList.Add(new Tuple($"RequestUrl: {e.RequestUrl}", JsonConvert.SerializeObject(e, Formatting.Indented))); } + } catch (Exception ex) { - Reporter.ToLog(eLogLevel.ERROR, "Error in OnNetworkRequestSent ", ex); + Reporter.ToLog(eLogLevel.ERROR, $"Method - {MethodBase.GetCurrentMethod().Name}, Error - {ex.Message}", ex); } - } - - private bool IsToMonitorAllUrls() - { - return mAct.GetOrCreateInputParam(nameof(ActBrowserElement.eMonitorUrl)).Value == ActBrowserElement.eMonitorUrl.AllUrl.ToString(); - } +} - private bool IsToMonitorOnlySelectedUrls(string requestUrl) - { - return mAct.GetOrCreateInputParam(nameof(ActBrowserElement.eMonitorUrl)).Value == ActBrowserElement.eMonitorUrl.SelectedUrl.ToString() - && mAct.UpdateOperationInputValues != null - && mAct.UpdateOperationInputValues.Any(x => !string.IsNullOrEmpty(x.ValueForDriver) && requestUrl.ToLower().Contains(x.ValueForDriver.ToLower())); - } private void OnNetworkResponseReceived(object sender, NetworkResponseReceivedEventArgs e) { @@ -11129,24 +11112,24 @@ private void OnNetworkResponseReceived(object sender, NetworkResponseReceivedEve { string monitorType = mAct.GetOrCreateInputParam(nameof(ActBrowserElement.eMonitorUrl)).Value; - if (IsToMonitorAllUrls() || IsToMonitorOnlySelectedUrls(e.ResponseUrl)) + if (_BrowserHelper.ShouldMonitorAllUrls() || _BrowserHelper.ShouldMonitorUrl(e.ResponseUrl)) { if (mAct.GetOrCreateInputParam(nameof(ActBrowserElement.eRequestTypes)).Value == ActBrowserElement.eRequestTypes.FetchOrXHR.ToString()) { - if (e.ResponseResourceType == "XHR") + if (e.ResponseResourceType.Equals("XHR", StringComparison.CurrentCultureIgnoreCase) || e.ResponseResourceType.Equals("FETCH", StringComparison.CurrentCultureIgnoreCase)) { - networkResponseLogList.Add(new Tuple("ResponseUrl:" + e.ResponseUrl, JsonConvert.SerializeObject(e))); + networkResponseLogList.Add(new Tuple($"ResponseUrl:{e.ResponseUrl}", JsonConvert.SerializeObject(e, Formatting.Indented))); } } else { - networkResponseLogList.Add(new Tuple("ResponseUrl:" + e.ResponseUrl, JsonConvert.SerializeObject(e))); + networkResponseLogList.Add(new Tuple($"ResponseUrl:{e.ResponseUrl}", JsonConvert.SerializeObject(e, Formatting.Indented))); } } } catch (Exception ex) { - Reporter.ToLog(eLogLevel.ERROR, "Error in OnNetworkResponseReceived ", ex); + Reporter.ToLog(eLogLevel.ERROR, $"Method - {MethodBase.GetCurrentMethod().Name}, Error - {ex.Message}", ex); } }