public static void Execute(State state)
 {
     AgentClient agent = new AgentClient(GetAddress());
     PRIORITIES[ACTIVE_AGENT_ID].Push(ACTIVE_AGENT_ID);
     agent.TestMethod(new ExecuteInfo { AgentId = ACTIVE_AGENT_ID, ProdId = state.StateInfo, StateId = state.StateId, Message = state.StateName, StateName = state.StateName });
     agent.Close();
 }
 public void TestFixtureSetUp()
 {
     client = AgentClientBuilder.New()
         .WithIp("127.0.0.1")
         .WithPort(TestConstants.SERVER_PORT)
         .Create()
         .Start();
 }
 public static async Task KillClones(AgentClient client)
 {
     var wait = new ManualResetEvent(false);
     Task.Factory.StartNew(async () =>
     {
         await KillAllClones(client);
         wait.Set();
     });
     wait.WaitOne();
 }
Exemple #4
0
        public override void Execute(Messsage command, AgentClient client)
        {
            if (!ProcessManager.IsTaskExsits(command.TaskId))
            {
                Logger.Warn($"Task {command.TaskId} is not running.");
                return;
            }

            ProcessInfo processInfo = ProcessManager.GetProcessDetail(command.TaskId);

            if (processInfo != null)
            {
                var process = processInfo.Process;
                try
                {
                    SendExitSignal(command.TaskId.ToString(), processInfo.WorkingDirectory);
                }
                catch
                {
                    //ignore
                }
                process.WaitForExit(30000);

                try
                {
                    process.Kill();
                }
                catch (NotSupportedException nse)
                {
                    Logger.Info($"Kill task {command.TaskId} success: {nse.Message}.");
                }
                catch (Win32Exception we)
                {
                    Logger.Info($"Kill task {command.TaskId} success: {we.Message}.");
                }
                catch (InvalidOperationException ioe)
                {
                    Logger.Info($"Kill task {command.TaskId} success: {ioe.Message}.");
                }
                catch (Exception e)
                {
                    Logger.Error($"Kill task {command.TaskId} failed: {e}.");
                }
            }
        }
Exemple #5
0
        /// <summary>
        /// Initializes a new instance of the class.
        /// </summary>
        public Downloader(AdminDirs appDirs, ScadaProject project, ProjectInstance instance,
                          DeploymentProfile profile, ITransferControl transferControl)
        {
            this.appDirs         = appDirs ?? throw new ArgumentNullException(nameof(appDirs));
            this.project         = project ?? throw new ArgumentNullException(nameof(project));
            this.instance        = instance ?? throw new ArgumentNullException(nameof(instance));
            this.profile         = profile ?? throw new ArgumentNullException(nameof(profile));
            this.transferControl = transferControl ?? throw new ArgumentNullException(nameof(transferControl));
            downloadOptions      = profile.DownloadOptions;
            progressTracker      = new ProgressTracker(transferControl)
            {
                TaskCount = TaskCount
            };

            agentClient   = null;
            tempFileNames = null;
            extractDirs   = null;
        }
Exemple #6
0
        /// <summary>
        /// Creates a step report and sends it to the <see cref="AgentClient"/>.
        /// </summary>
        /// <param name="description">The description of the step.</param>
        /// /// <param name="message">A message that goes with the step.</param>
        /// <param name="passed">True if the step should be marked as passed, false otherwise.</param>
        /// <param name="screenshot">True if a screenshot should be attached to the step, false otherwise.</param>
        public void Step(string description, string message = null, bool passed = true, bool screenshot = false)
        {
            // Check whether it is necessary to report a test, too, and if so, do that.
            this.reportingCommandExecutor.ReportTest(false);

            if (!this.reportingCommandExecutor.ReportsDisabled)
            {
                string screenshotAsString = screenshot ? this.reportingCommandExecutor.GetScreenshot() : null;

                StepReport stepReport = new StepReport(description, message, passed, screenshotAsString);

                AgentClient.GetInstance().ReportStep(stepReport);
            }
            else
            {
                Logger.Trace($"Step '{description}' {(passed ? "passed" : "failed")}");
            }
        }
        public void TestFixtureSetUp()
        {
            if (!RUN_AGAINST_WINDOWS_SERVICE)
            {
                server = AgentServerBuilder.New()
                    .WithIp("<this-ip>")
                    .WithPort(TestConstants.SERVER_PORT)
                    .WithDiscovery()
                    .Create()
                    .Listen();
            }

            client = AgentClientBuilder.New()
                .WithIp("<this-ip>")
                .WithPort(TestConstants.SERVER_PORT)
                .Create()
                .Start();
        }
Exemple #8
0
        /// <summary>
        /// Initializes a new instance of the <see cref="GenericDriver"/> class.
        /// </summary>
        /// <param name="remoteAddress">The base address for the Agent API (e.g. http://localhost:8585).</param>
        /// <param name="token">The development token used to communicate with the Agent, see <a href="https://app.testproject.io/#/integrations/sdk">here</a> for more info.</param>
        /// <param name="projectName">The project name to report.</param>
        /// <param name="jobName">The job name to report.</param>
        /// <param name="disableReports">Set to true to disable all reporting (no report will be created on TestProject).</param>
        public GenericDriver(
            Uri remoteAddress   = null,
            string token        = null,
            string projectName  = null,
            string jobName      = null,
            bool disableReports = false)
        {
            AgentClient agentClient = AgentClient.GetInstance(remoteAddress, token, new GenericOptions(), new ReportSettings(projectName, jobName), disableReports, this.minGenericDriverSupportedVersion);

            this.commandExecutor = new GenericCommandExecutor(remoteAddress, disableReports);

            if (StackTraceHelper.Instance.TryDetectSpecFlow())
            {
                Logger.Info("SpecFlow detected, applying SpecFlow-specific reporting settings...");
                this.Report().DisableCommandReports(true);
                this.Report().DisableAutoTestReports(true);
            }
        }
Exemple #9
0
        /// <summary>
        /// Checks whether or not the element is a secured element.
        /// </summary>
        /// <param name="executor">The command executor used by the driver to execute WebDriver commands.</param>
        /// <param name="elementId">The unique ID of the element that the command was executed on.</param>
        /// <returns>True if the element is a secure element, false otherwise.</returns>
        private static bool IsSecuredElement(ITestProjectCommandExecutor executor, string elementId)
        {
            Dictionary <string, object> getAttributeParameters = new Dictionary <string, object>();

            getAttributeParameters.Add("id", elementId);
            getAttributeParameters.Add("name", "type");

            Command getAttributeCommand = new Command(
                new SessionId(AgentClient.GetInstance().AgentSession.SessionId),
                DriverCommand.GetElementAttribute,
                getAttributeParameters);

            Response response = executor.Execute(getAttributeCommand, true);

            string inputType = response.Status.Equals(WebDriverResult.Success) ? response.Value.ToString() : string.Empty;

            return(inputType.Equals("password") || inputType.Equals("XCUIElementTypeSecureTextField"));
        }
Exemple #10
0
        /// <summary>
        /// Extended command execution method.
        /// Allows skipping reporting for "internal" commands, for example:
        /// - Taking screenshot for manual step reporting.
        /// - Inspecting element type to determine whether redaction is required.
        /// </summary>
        /// <param name="commandToExecute">The WebDriver command to execute.</param>
        /// <param name="skipReporting">True if the command should not be reported, false otherwise.</param>
        /// <returns>The <see cref="Response"/> returned by the Agent.</returns>
        public Response Execute(Command commandToExecute, bool skipReporting)
        {
            if (commandToExecute.Name.Equals(DriverCommand.Screenshot))
            {
                // Handle users trying to take a screenshot using the generic driver
                Logger.Info("The generic driver does not support taking screenshots");

                Response response = new Response();
                response.Status    = WebDriverResult.UnableToCaptureScreen;
                response.SessionId = AgentClient.GetInstance().AgentSession.SessionId;
                response.Value     = new Dictionary <string, object>();

                return(response);
            }
            else
            {
                throw new NotImplementedException($"The generic driver cannot execute the WebDriver command '{commandToExecute.Name}'");
            }
        }
Exemple #11
0
        /// <summary>
        /// Creates a test report and sends it to the <see cref="AgentClient"/>.
        /// </summary>
        /// <param name="name">The name of the test.</param>
        /// <param name="passed">True if the test should be marked as passed, false otherwise.</param>
        /// <param name="message">A message that goes with the test.</param>
        public void Test(string name, bool passed = true, string message = null)
        {
            if (!this.reportingCommandExecutor.ReportsDisabled)
            {
                if (!this.reportingCommandExecutor.AutoTestReportsDisabled)
                {
                    Logger.Warn("Automatic reporting is enabled, disable this using DisableAutoTestReports() " +
                                "to avoid duplicates in the report.");
                }

                TestReport testReport = new TestReport(name, passed, message);

                AgentClient.GetInstance().ReportTest(testReport);
            }
            else
            {
                Logger.Trace($"Test '{name}' {(passed ? "passed" : "failed")}");
            }
        }
Exemple #12
0
        /// <summary>
        /// Executes an action using its proxy.
        /// </summary>
        /// <param name="actionProxy">The action proxy to execute.</param>
        /// <param name="by">A locator for the <see cref="IWebElement"/> to execute the action on.</param>
        /// <param name="timeoutInMilliSeconds">Timeout for the action execution duration.</param>
        /// <returns>A potentially updated <see cref="ActionProxy"/> with updated output fields (if any).</returns>
        public ActionProxy Execute(ActionProxy actionProxy, By by = null, int timeoutInMilliSeconds = -1)
        {
            if (by != null)
            {
                // Because serializing does not work 'out of the box' for By objects,
                // we need to handle that with a custom method.
                actionProxy.ProxyDescriptor.By = by.ConvertToSerializable();
            }

            // The payload to be sent to the Agent needs to be formatted first.
            actionProxy.ProxyDescriptor.Parameters = this.FormatParameters(actionProxy);

            ActionExecutionResponse response = AgentClient.GetInstance().ExecuteProxy(actionProxy, timeoutInMilliSeconds);

            if (!response.ResultType.Equals(ActionExecutionResponse.ExecutionResultType.Passed))
            {
                throw new SdkException($"Error occurred during addon action execution: {response.Message}");
            }

            foreach (ActionExecutionResponse.ResultField field in response.Fields)
            {
                if (!field.Output)
                {
                    // Skip input fields
                    continue;
                }

                var proxyField = actionProxy.GetType().GetProperty(field.Name, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);

                // Check if action has an attribute with the name of the field
                if (proxyField == null)
                {
                    Logger.Warn($"Action {actionProxy.ProxyDescriptor.Guid} does not have a field named '{field.Name}'");
                    continue;
                }

                proxyField.SetValue(actionProxy, field.Value);

                Logger.Trace($"Value of output field '{proxyField.Name}' has been set to '{proxyField.GetValue(actionProxy)}'");
            }

            return(actionProxy);
        }
 private void HandleAgentFullFrame()
 {
     try
     {
         var fullFrameData = AgentClient.GetFullFrame();
         if (fullFrameData?.ScreenImage == null)
         {
             throw new InvalidOperationException("Frame was null");
         }
         var bounds    = fullFrameData.Bounds;
         var image     = ScreenData.ImageToByteArray(fullFrameData.ScreenImage);
         var frameData = new
         {
             screenBounds = new
             {
                 top      = bounds.Top,
                 bottom   = bounds.Bottom,
                 left     = bounds.Left,
                 right    = bounds.Right,
                 height   = bounds.Height,
                 width    = bounds.Width,
                 x        = bounds.X,
                 y        = bounds.Y,
                 empty    = bounds.IsEmpty,
                 location = bounds.Location,
                 size     = bounds.Size
             },
             frameData = image.Select(b => (int)b).ToArray()
         };
         _builder.WriteMessage(frameData);
     }
     catch (Exception ex)
     {
         var data = new
         {
             frameFailed = true,
             message     = ex.Message
         };
         Console.WriteLine(ex.Message + "F**k");
         _builder.WriteMessage(data);
     }
 }
Exemple #14
0
        /// <summary>
        /// Initializes a new instance of the <see cref="BaseDriver"/> class.
        /// </summary>
        /// <param name="remoteAddress">The base address for the Agent API (e.g. http://localhost:8585).</param>
        /// <param name="token">The development token used to communicate with the Agent, see <a href="https://app.testproject.io/#/integrations/sdk">here</a> for more info.</param>
        /// <param name="driverOptions">See <see cref="DriverOptions"/> for more details.</param>
        /// <param name="projectName">The project name to report.</param>
        /// <param name="jobName">The job name to report.</param>
        /// <param name="disableReports">Set to true to disable all reporting (no report will be created on TestProject).</param>
        protected BaseDriver(
            Uri remoteAddress           = null,
            string token                = null,
            DriverOptions driverOptions = null,
            string projectName          = null,
            string jobName              = null,
            bool disableReports         = false)
            : base(
                AgentClient.GetInstance(remoteAddress, token, driverOptions, new ReportSettings(projectName, jobName), disableReports).AgentSession.Capabilities)
        {
            this.sessionId = AgentClient.GetInstance().AgentSession.SessionId;

            // Set the session ID for the base driver object to the session ID returned by the Agent.
            FieldInfo sessionIdField = typeof(RemoteWebDriver).GetField("sessionId", BindingFlags.Instance | BindingFlags.NonPublic);

            sessionIdField.SetValue(this, new SessionId(this.sessionId));

            // Create a new command executor for this driver session and set disable reporting flag
            this.commandExecutor = new CustomHttpCommandExecutor(AgentClient.GetInstance().AgentSession.RemoteAddress, disableReports);

            // If the driver returned by the Agent is in W3C mode, we need to update the command info repository
            // associated with the base RemoteWebDriver to the W3C command info repository (default is OSS).
            if (AgentClient.GetInstance().IsInW3CMode())
            {
                FieldInfo        executorField = typeof(RemoteWebDriver).GetField("executor", BindingFlags.IgnoreCase | BindingFlags.NonPublic | BindingFlags.Instance);
                ICommandExecutor executor      = (ICommandExecutor)executorField.GetValue(this);
                FieldInfo        commandInfoRepositoryField = executor.GetType().GetField("commandInfoRepository", BindingFlags.Instance | BindingFlags.NonPublic);
                commandInfoRepositoryField.SetValue(executor, new W3CWireProtocolCommandInfoRepository());
            }

            this.IsRunning = true;

            // Add shutdown hook for gracefully shutting down the driver
            this.driverShutdownThread = new DriverShutdownThread(this);

            if (StackTraceHelper.Instance.TryDetectSpecFlow())
            {
                Logger.Info("SpecFlow detected, applying SpecFlow-specific reporting settings...");
                this.Report().DisableCommandReports(true);
                this.Report().DisableAutoTestReports(true);
            }
        }
Exemple #15
0
        public override void Execute(Messsage command, AgentClient client)
        {
            if (ProcessManager.IsTaskExsits(command.TaskId))
            {
                Logger.Error($"Task {command.TaskId} is already running.");
                return;
            }

            if (string.IsNullOrEmpty(command.Version) || string.IsNullOrWhiteSpace(command.Version))
            {
                Logger.Error($"Version should not be empty.");
                return;
            }
            Logger.Info($"Start prepare workdirectory...");
            var taskDirectory = Path.Combine(Env.ProjectsDirectory, command.TaskId.ToString());

            if (!Directory.Exists(taskDirectory))
            {
                Directory.CreateDirectory(taskDirectory);
                Logger.Info($"Create task directory {taskDirectory} success.");
            }

            string workingDirectory = Path.Combine(taskDirectory, command.Version);

            if (!Directory.Exists(workingDirectory))
            {
                var packageUrl = $"{Env.PackageUrl}{command.Version}.zip";
                try
                {
                    var localPackageFilePath = Path.Combine(Env.PackagesDirectory, $"{command.Version}.zip");
                    var bytes = Env.HttpClient.GetByteArrayAsync(packageUrl).Result;
                    File.WriteAllBytes(localPackageFilePath, bytes);
                    ZipFile.ExtractToDirectory(localPackageFilePath, workingDirectory);
                }
                catch (Exception e)
                {
                    Logger.Error($"Download package {packageUrl} failed: {e}.");
                    return;
                }
            }
            ProcessManager.StartProcess(command.TaskId, command.ApplicationName, command.Arguments, workingDirectory);
        }
Exemple #16
0
        /// <summary>
        /// Report an executed WebDriver command and its result to TestProject.
        /// </summary>
        /// <param name="command">The WebDriver <see cref="Command"/> to report.</param>
        /// <param name="response">The <see cref="Response"/> from the WebDriver server upon sending the command.</param>
        public void ReportCommand(Command command, Response response)
        {
            bool isQuitCommand = command.Name.Equals(DriverCommand.Quit);

            if (!this.AutoTestReportsDisabled)
            {
                this.ReportTest(isQuitCommand);
            }

            if (isQuitCommand)
            {
                // Close the client after finishing the test using driver.Quit()
                AgentClient.GetInstance().Stop();

                // Do not report Quit() command to avoid creating a new test in the reports
                return;
            }

            if (StackTraceHelper.Instance.IsRunningInsideWait())
            {
                // We're only interested in reporting the final FindElement or FindElements call
                // (these are executed by the ExpectedConditions helper methods)
                if (
                    command.Name.Equals(DriverCommand.FindElement) ||
                    command.Name.Equals(DriverCommand.FindElements))
                {
                    this.stashedCommand = new StashedCommand(command, response.Value, response.IsPassed());
                }

                // Do not report the command right away if it's executed inside a WebDriverWait
                return;
            }

            // If we have a previously stashed command to report, report it first.
            if (this.stashedCommand != null)
            {
                this.SendCommandToAgent(this.stashedCommand.Command, this.stashedCommand.Result, this.stashedCommand.Passed);
                this.stashedCommand = null;
            }

            this.SendCommandToAgent(command, response.Value, response.IsPassed());
        }
        /// <summary>
        /// Report a failed step and test to TestProject when SpecFlow scenario execution produces an error.
        /// </summary>
        /// <param name="ex">The exception that was thrown during SpecFlow scenario execution.</param>
        public new void TraceError(Exception ex)
        {
            if (AgentClient.IsInitialized())
            {
                StepReport stepReport = new StepReport(TestProjectStepContext.CurrentStep, ex.Message, false, null);
                AgentClient.GetInstance().ReportStep(stepReport);

                // Create a preliminary test report in the AgentClient (will not be reported until AgentClient is stopped).
                AgentClient.GetInstance().SpecFlowTestReport = new TestReport(TestProjectStepContext.CurrentScenario, false, null);
            }
            else
            {
                string errorMessage = "No active Agent development session found.";

                Logger.Error(errorMessage);
                throw new AgentConnectException(errorMessage);
            }

            base.TraceError(ex);
        }
        private void HandleScroll()
        {
            if (!ScreenShareService.Streams.ContainsKey(_authClient))
            {
                return;
            }
            var delta = Convert.ToInt32(_packet.Args[0], CultureInfo.InvariantCulture);

            delta = ~delta;
            var positive  = delta > 0;
            var direction = positive ? 10 : -10;

            if (RunningAsService)
            {
                AgentClient.ScrollMouse(positive);
            }
            else
            {
                new InputSimulator().Mouse.VerticalScroll(direction);
            }
        }
        public void SetActiveMonitor()
        {
            if (_packet.Args.ElementAt(0) == null)
            {
                ScreenData.ActiveDisplay = 0;
            }
            ScreenData.ActiveDisplay = Convert.ToInt32(_packet.Args[0]);
            var activeDisplays = SystemInformation.Displays;

            if (RunningAsService)
            {
                AgentClient.SetActiveMonitor(ScreenData.ActiveDisplay);
            }
            var data = new
            {
                selectedDisplay       = ScreenData.ActiveDisplay,
                resolutionInformation = activeDisplays[ScreenData.ActiveDisplay].CurrentResolution
            };

            _builder.WriteMessage(data);
        }
    override protected void Start()
    {
        base.Start();
        if (Application.isEditor)
        {
            Application.runInBackground = true;
        }

        m_Clients             = new AgentClient[m_MaxClients];
        m_ClientConnectEvents = new OnClientConnectEvent[m_MaxClients];
        for (int i = 0; i < m_MaxClients; i++)
        {
            m_Clients[i] = new AgentClient();
        }

        m_AvailableClientSlot  = new Semaphore(m_MaxClients, m_MaxClients);
        m_ClientListenerThread = new Thread(new ThreadStart(listenClient));
        m_ClientListenerThread.IsBackground = true;
        m_ClientListenerThread.Start();
        m_Ready = true;
    }
Exemple #21
0
 /// <summary>
 /// Refresh log content using Agent.
 /// </summary>
 protected void RefreshUsingAgent()
 {
     try
     {
         if (FullLogView && AgentClient.ReadLog(logPath, ref logFileAge, out ICollection <string> lines) ||
             !FullLogView && AgentClient.ReadLog(logPath, LogViewSize, ref logFileAge, out lines))
         {
             if (!listBox.IsDisposed)
             {
                 SetLines(lines);
             }
         }
     }
     catch (Exception ex)
     {
         if (!listBox.IsDisposed)
         {
             SetFirstLine(ex.Message);
         }
     }
 }
Exemple #22
0
        /// <summary>
        /// Send an executed WebDriver command to the Agent.
        /// </summary>
        /// <param name="command">The WebDriver command that was executed.</param>
        /// <param name="result">The result of the command execution.</param>
        /// <param name="passed">True if command execution was successful, false otherwise.</param>
        private void SendCommandToAgent(Command command, object result, bool passed)
        {
            if (this.ReportsDisabled || this.CommandReportsDisabled)
            {
                Logger.Trace($"Command '{command.Name}' {(passed ? "passed" : "failed")}");
                return;
            }

            if (!this.RedactionDisabled)
            {
                command = RedactHelper.RedactCommand(this.commandExecutor, command);
            }

            DriverCommandReport driverCommandReport = new DriverCommandReport(command.Name, command.Parameters, result, passed);

            if (!passed)
            {
                driverCommandReport.Screenshot = this.GetScreenshot();
            }

            AgentClient.GetInstance().ReportDriverCommand(driverCommandReport);
        }
        /// <summary>
        /// Report a passed step to TestProject when the SpecFlow step finishes executing.
        /// </summary>
        /// <param name="match">The step definition binding that was executed.</param>
        /// <param name="arguments">The step definitions arguments that were used.</param>
        /// <param name="duration">The duration of the step execution.</param>
        public new void TraceStepDone(BindingMatch match, object[] arguments, TimeSpan duration)
        {
            if (AgentClient.IsInitialized())
            {
                // Create a preliminary test report in the AgentClient (will not be reported until AgentClient is stopped).
                AgentClient.GetInstance().SpecFlowTestReport = new TestReport(TestProjectStepContext.CurrentScenario, true, null);

                string message = $"Step execution time: {duration}";

                StepReport stepReport = new StepReport(TestProjectStepContext.CurrentStep, message, true, null);
                AgentClient.GetInstance().ReportStep(stepReport);
            }
            else
            {
                string errorMessage = "No active Agent development session found.";

                Logger.Error(errorMessage);
                throw new AgentConnectException(errorMessage);
            }

            base.TraceStepDone(match, arguments, duration);
        }
Exemple #24
0
        /// <summary>
        /// Send an executed WebDriver command to the Agent.
        /// </summary>
        /// <param name="command">The WebDriver command that was executed.</param>
        /// <param name="result">The result of the command execution.</param>
        /// <param name="passed">True if command execution was successful, false otherwise.</param>
        private void SendCommandToAgent(Command command, object result, bool passed)
        {
            if (this.ReportsDisabled || this.CommandReportsDisabled.Equals(DriverCommandsFilter.All))
            {
                Logger.Trace($"Command '{command.Name}' {(passed ? "passed" : "failed")}");
                return;
            }

            if (this.CommandReportsDisabled.Equals(DriverCommandsFilter.Passing) && !passed)
            {
                // Report failed driver commands in a user friendly way if explicitly requested by the user
                StepReport stepReport = new StepReport(
                    description: $"Failed to execute driver command '{command.Name}'",
                    message: result.ToJson(),
                    passed: false,
                    screenshot: this.GetScreenshot());

                AgentClient.GetInstance().ReportStep(stepReport);
                return;
            }

            if (this.CommandReportsDisabled.Equals(DriverCommandsFilter.None))
            {
                if (!this.RedactionDisabled)
                {
                    command = RedactHelper.RedactCommand(this.commandExecutor, command);
                }

                DriverCommandReport driverCommandReport = new DriverCommandReport(command.Name, command.Parameters, result, passed);

                if (!passed)
                {
                    driverCommandReport.Screenshot = this.GetScreenshot();
                }

                AgentClient.GetInstance().ReportDriverCommand(driverCommandReport);
            }
        }
Exemple #25
0
        /// <summary>
        /// Overrides the base Execute() method by redirecting the WebDriver command to our own command executor.
        /// </summary>
        /// <param name="driverCommandToExecute">The WebDriver command to execute.</param>
        /// <param name="parameters">Contains the parameters associated with this command.</param>
        /// <returns>The response returned by the Agent upon requesting to execute this command.</returns>
        protected override Response Execute(string driverCommandToExecute, Dictionary <string, object> parameters)
        {
            if (driverCommandToExecute.Equals(DriverCommand.NewSession))
            {
                var resp = new Response();
                resp.Status    = OpenQA.Selenium.WebDriverResult.Success;
                resp.SessionId = this.sessionId;
                resp.Value     = new Dictionary <string, object>();

                return(resp);
            }

            // The Agent does not understand the default way Selenium sends the driver command parameters for SendKeys
            // This means we'll need to patch them so these commands can be executed.
            if (!AgentClient.GetInstance().IsInW3CMode() && driverCommandToExecute.ShouldBePatched())
            {
                parameters = CommandHelper.UpdateSendKeysParameters(parameters);
            }

            Command command = new Command(new SessionId(this.sessionId), driverCommandToExecute, parameters);

            return(this.commandExecutor.Execute(command));
        }
Exemple #26
0
        /// <summary>
        /// Initializes a new instance of the <see cref="BaseDriver"/> class.
        /// </summary>
        /// <param name="remoteAddress">The base address for the Agent API (e.g. http://localhost:8585).</param>
        /// <param name="token">The development token used to communicate with the Agent, see <a href="https://app.testproject.io/#/integrations/sdk">here</a> for more info.</param>
        /// <param name="driverOptions">See <see cref="DriverOptions"/> for more details.</param>
        /// <param name="projectName">The project name to report.</param>
        /// <param name="jobName">The job name to report.</param>
        /// <param name="disableReports">Set to true to disable all reporting (no report will be created on TestProject).</param>
        protected BaseDriver(
            Uri remoteAddress           = null,
            string token                = null,
            DriverOptions driverOptions = null,
            string projectName          = null,
            string jobName              = null,
            bool disableReports         = false)
            : base(
                AgentClient.GetInstance(remoteAddress, token, driverOptions, new ReportSettings(projectName, jobName), disableReports).AgentSession.Capabilities)
        {
            this.sessionId = AgentClient.GetInstance().AgentSession.SessionId;

            // Set the session ID for the base driver object to the session ID returned by the Agent.
            var sessionIdBase = this.GetType()
                                .BaseType
                                .GetField(
                "sessionId",
                System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);

            sessionIdBase.SetValue(this, this.sessionId);

            // Create a new command executor for this driver session and set disable reporting flag
            this.commandExecutor = new CustomHttpCommandExecutor(AgentClient.GetInstance().AgentSession.RemoteAddress, disableReports);

            this.IsRunning = true;

            // Add shutdown hook for gracefully shutting down the driver
            this.driverShutdownThread            = new DriverShutdownThread(this);
            AppDomain.CurrentDomain.ProcessExit += (sender, eventArgs) => this.driverShutdownThread.RunThread();

            if (StackTraceHelper.Instance.TryDetectSpecFlow())
            {
                Logger.Info("SpecFlow detected, applying SpecFlow-specific reporting settings...");
                this.Report().DisableCommandReports(true);
                this.Report().DisableAutoTestReports(true);
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="GenericDriver"/> class.
        /// </summary>
        /// <param name="remoteAddress">The base address for the Agent API (e.g. http://localhost:8585).</param>
        /// <param name="token">The development token used to communicate with the Agent, see <a href="https://app.testproject.io/#/integrations/sdk">here</a> for more info.</param>
        /// <param name="projectName">The project name to report.</param>
        /// <param name="jobName">The job name to report.</param>
        /// <param name="disableReports">Set to true to disable all reporting (no report will be created on TestProject).</param>
        /// <param name="reportType">The report type of the execution, can be local, cloud or both.</param>
        /// <param name="reportName">The name of the local generated report.</param>
        /// <param name="reportPath">The path of the local generated report.</param>
        public GenericDriver(
            Uri remoteAddress     = null,
            string token          = null,
            string projectName    = null,
            string jobName        = null,
            bool disableReports   = false,
            ReportType reportType = ReportType.CLOUD_AND_LOCAL,
            string reportName     = null,
            string reportPath     = null)
        {
            AgentClient agentClient = AgentClient.GetInstance(remoteAddress, token, new GenericOptions(), new ReportSettings(projectName, jobName, reportType, reportName, reportPath), disableReports, this.minGenericDriverSupportedVersion);

            this.commandExecutor = new GenericCommandExecutor(remoteAddress, disableReports);

            this.IsRunning = true;

            if (StackTraceHelper.Instance.TryDetectSpecFlow())
            {
                var report = this.Report();

                if (!StackTraceHelper.Instance.IsSpecFlowPluginInstalled())
                {
                    string message = "TestProject Plugin for SpecFlow is not installed, please install the plugin and run the Test again.";
                    report.Step(description: message, passed: false);
                    Logger.Error(message);
                    this.Stop();
                    throw new SdkException(message);
                }

                report.DisableCommandReports(DriverCommandsFilter.All);
                report.DisableAutoTestReports(true);
                Logger.Info("SpecFlow detected, applying SpecFlow-specific reporting settings...");
            }

            instance = this;
        }
Exemple #28
0
        /// <summary>
        /// Initializes a new instance of the <see cref="IOSDriver{T}"/> class.
        /// </summary>
        /// <param name="remoteAddress">The base address for the Agent API (e.g. http://localhost:8585).</param>
        /// <param name="token">The development token used to communicate with the Agent, see <a href="https://app.testproject.io/#/integrations/sdk">here</a> for more info.</param>
        /// <param name="appiumOptions">See <see cref="AppiumOptions"/> for more details.</param>
        /// <param name="projectName">The project name to report.</param>
        /// <param name="jobName">The job name to report.</param>
        /// <param name="disableReports">Set to true to disable all reporting (no report will be created on TestProject).</param>
        /// <param name="reportType">The report type of the execution, can be local, cloud or both.</param>
        /// <param name="reportName">The name of the local generated report.</param>
        /// <param name="reportPath">The path of the local generated report.</param>
        /// <param name="remoteConnectionTimeout">Timeout for the remote connection to the WebDriver server executing the commands.</param>
        /// <param name="restClientTimeout"> The connection timeout to the agent in milliseconds. Default is 120 seconds.</param>
        public IOSDriver(
            Uri remoteAddress                = null,
            string token                     = null,
            AppiumOptions appiumOptions      = null,
            string projectName               = null,
            string jobName                   = null,
            bool disableReports              = false,
            ReportType reportType            = ReportType.CLOUD_AND_LOCAL,
            string reportName                = null,
            string reportPath                = null,
            TimeSpan?remoteConnectionTimeout = null,
            int restClientTimeout            = AgentClient.DefaultRestClientTimeoutInMilliseconds)
            : base(
                AgentClient.GetInstance(remoteAddress, token, appiumOptions, new ReportSettings(projectName, jobName, reportType, reportName, reportPath), disableReports, restClientTimeout).AgentSession.RemoteAddress,
                AgentClient.GetInstance().AgentSession.Capabilities,
                remoteConnectionTimeout ?? DefaultCommandTimeout)
        {
            this.sessionId = AgentClient.GetInstance().AgentSession.SessionId;

            // Set the session ID for the base driver object to the session ID returned by the Agent.
            FieldInfo sessionIdField = typeof(RemoteWebDriver).GetField("sessionId", BindingFlags.Instance | BindingFlags.NonPublic);

            sessionIdField.SetValue(this, new SessionId(this.sessionId));

            // Create a new command executor for this driver session and set disable reporting flag
            this.commandExecutor = new AppiumCustomHttpCommandExecutor(AgentClient.GetInstance().AgentSession.RemoteAddress, disableReports, remoteConnectionTimeout ?? AgentClient.DefaultConnectionTimeout);

            // If the driver returned by the Agent is in W3C mode, we need to update the command info repository
            // associated with the base RemoteWebDriver to the W3C command info repository (default is OSS).
            if (AgentClient.GetInstance().IsInW3CMode())
            {
                var executorField     = this.GetType().GetInheritedField("executor", BindingFlags.IgnoreCase | BindingFlags.NonPublic | BindingFlags.Instance);
                var executor          = (ICommandExecutor)executorField.GetValue(this);
                var realExecutorField = executor.GetType().GetInheritedField("RealExecutor", BindingFlags.Instance | BindingFlags.NonPublic);
                executor = (ICommandExecutor)realExecutorField.GetValue(executor);
                var commandInfoRepository = executor.GetType().GetField("commandInfoRepository", BindingFlags.Instance | BindingFlags.NonPublic);
                commandInfoRepository.SetValue(executor, typeof(AppiumCommand).CallPrivateStaticMethod("Merge", new object[] { new W3CWireProtocolCommandInfoRepository() }));
            }

            this.IsRunning = true;

            // Add shutdown hook for gracefully shutting down the driver
            this.driverShutdownThread = new DriverShutdownThread(this);

            if (StackTraceHelper.Instance.TryDetectSpecFlow())
            {
                var report = this.Report();

                if (!StackTraceHelper.Instance.IsSpecFlowPluginInstalled())
                {
                    string message = "TestProject Plugin for SpecFlow is not installed, please install the plugin and run the Test again.";
                    report.Step(description: message, passed: false);
                    Logger.Error(message);
                    this.Stop();
                    throw new SdkException(message);
                }

                report.DisableCommandReports(DriverCommandsFilter.All);
                report.DisableAutoTestReports(true);
                Logger.Info("SpecFlow detected, applying SpecFlow-specific reporting settings...");
            }
        }
        public async Task Should_be_able_to_get_clone()
        {
            await AgentClientBuilder.KillClones(client);

            var clone1 = await client.Clone(TestConstants.CLONE_PORT_1);
            var clone2 = await client.Clone(TestConstants.CLONE_PORT_2);
            var clone3 = await client.Clone(TestConstants.CLONE_PORT_3);
            var clone4 = await client.Clone(TestConstants.CLONE_PORT_4);

            Thread.Sleep(TestConstants.CLONE_WAIT_MS);
            
            var client3 = new AgentClient(clone1.ToClientInfo("guest", "guest")).Start();
            var pingResult1 = await client3.Ping();
            Assert.That(pingResult1, Is.Not.Null.Or.Empty);

            var client4 = new AgentClient(clone2.ToClientInfo("guest", "guest")).Start();
            var pingResult2 = await client4.Ping();
            Assert.That(pingResult2, Is.Not.Null.Or.Empty);

            var client5 = new AgentClient(clone3.ToClientInfo("guest", "guest")).Start();
            var pingResult3 = await client5.Ping();
            Assert.That(pingResult3, Is.Not.Null.Or.Empty);

            var client6 = new AgentClient(clone4.ToClientInfo("guest", "guest")).Start();
            var pingResult4 = await client6.Ping();
            Assert.That(pingResult4, Is.Not.Null.Or.Empty);

            Thread.Sleep(TestConstants.CLONE_WAIT_MS);

            client3.Exit();
            client4.Exit();
            client5.Exit();
            client6.Exit();
        }
 void OnClientDisconnect(AgentClient client)
 {
     Debug.Log("Client " + client.ClientSocket.RemoteEndPoint + " disconnected.");
     m_AvailableClientSlot.Release();
 }
        public ActionResult GetAgentPerformance(string startdate, string enddate)
        {
            //try
            //{
            Response.ContentType = "application/json";



            string datestamp = EasternTimeConverter.Convert(DateTime.UtcNow).ToString("yyyyMMdd");
            string cached    = BlobJsonResourceManager.Instance.GetJsonResource("skillcowagentdashboard", datestamp, "range" + startdate + enddate);

            if (cached != null && cached.Trim() != "")
            {
                Response.Write(cached);
                Response.End();
                return(null);
            }


            SkillCowRequestSubmissionClient rsc = new SkillCowRequestSubmissionClient();

            DateTime dstartdate = DateTime.ParseExact(startdate, "yyyyMMdd", CultureInfo.InvariantCulture);
            DateTime denddate   = DateTime.ParseExact(enddate, "yyyyMMdd", CultureInfo.InvariantCulture);


            AgentClient  ac             = new AgentClient();
            List <Agent> agentsprofiles = new List <Agent>(ac.GetAll().Execute());

            //Get agent hours
            List <AgentDailyActivity> tempactivity = AgentDailyActivity.Create(agentsprofiles, dstartdate, denddate, null);
            Dictionary <string, IGrouping <string, AgentDailyActivity> > agenthours = new Dictionary <string, IGrouping <string, AgentDailyActivity> >();

            foreach (IGrouping <string, AgentDailyActivity> ag in tempactivity.GroupBy(x => x.Agent))
            {
                agenthours.Add(ag.Key, ag);
            }

            List <SkillCowRequestSubmission> allrecords = rsc.GetKioskLeads(dstartdate, denddate);


            List <object> agents = new List <object>();

            foreach (KeyValuePair <string, IGrouping <string, AgentDailyActivity> > kv in agenthours)
            {
                Agent agentprofile = agentsprofiles.SingleOrDefault(x => x.LoginName == kv.Key.Replace("cindy", "sydneyc"));

                List <object> dates = new List <object>();

                double totalhours = 0;

                Dictionary <string, List <double> > aggregate = new Dictionary <string, List <double> >();

                aggregate.Add("hours", new List <double>());
                aggregate.Add("billablehours", new List <double>());
                aggregate.Add("hourlyearnings", new List <double>());
                aggregate.Add("validschoolleadsnetwork", new List <double>());
                aggregate.Add("companyvalidschoolleadsnetwork", new List <double>());
                aggregate.Add("invalidschoolleadsnetwork", new List <double>());
                aggregate.Add("companyinvalidschoolleadsnetwork", new List <double>());
                aggregate.Add("commissionsschoolleadsnetwork", new List <double>());
                aggregate.Add("AvgRetentionSchoolLeads", new List <double>());
                aggregate.Add("CompanyAvgRetentionSchoolLeads", new List <double>());
                aggregate.Add("AvgLPH", new List <double>());
                aggregate.Add("Stochastic", new List <double>());
                aggregate.Add("CompanyAverageLPHMean", new List <double>());

                List <object> ProductionChartData = new List <object>();

                ProductionChartData.Add(new string[] { "Date", "Best", "Worst", "Average", kv.Key });

                DateTime cursordate = dstartdate;
                while (cursordate <= denddate)
                {
                    IEnumerable <SkillCowRequestSubmission> companyvalidnetworkschoolleads = allrecords.Where(x =>
                                                                                                              x.PartitionKey == cursordate.ToString("yyyyMMdd") &&
                                                                                                              x.GradYear != "GET THIS" &&
                                                                                                              x.GradYear != "undefined" &&
                                                                                                              (int.Parse(x.GradYear) < DateTime.UtcNow.Year || (int.Parse(x.GradYear) == DateTime.UtcNow.Year && DateTime.UtcNow.Month > 5)) &&
                                                                                                              x.SourceForm == "schoolform");

                    IEnumerable <SkillCowRequestSubmission> companyinvalidnetworkschoolleads = allrecords.Where(x =>
                                                                                                                x.PartitionKey == cursordate.ToString("yyyyMMdd") &&
                                                                                                                !(x.GradYear != "GET THIS" && x.GradYear != "undefined" && (int.Parse(x.GradYear) < DateTime.UtcNow.Year || (int.Parse(x.GradYear) == DateTime.UtcNow.Year && DateTime.UtcNow.Month > 5))) &&
                                                                                                                x.SourceForm == "schoolform");

                    IEnumerable <SkillCowRequestSubmission> validnetworkschoolleads = allrecords.Where(x =>
                                                                                                       x.PartitionKey == cursordate.ToString("yyyyMMdd") &&
                                                                                                       x.GradYear != "GET THIS" &&
                                                                                                       x.GradYear != "undefined" &&
                                                                                                       (int.Parse(x.GradYear) < DateTime.UtcNow.Year || (int.Parse(x.GradYear) == DateTime.UtcNow.Year && DateTime.UtcNow.Month > 5)) &&
                                                                                                       x.SourceForm == "schoolform" &&
                                                                                                       x.UtmContent == kv.Key);

                    IEnumerable <SkillCowRequestSubmission> invalidnetworkschoolleads = allrecords.Where(x =>
                                                                                                         x.PartitionKey == cursordate.ToString("yyyyMMdd") &&
                                                                                                         !(x.GradYear != "GET THIS" && x.GradYear != "undefined" && (int.Parse(x.GradYear) < DateTime.UtcNow.Year || (int.Parse(x.GradYear) == DateTime.UtcNow.Year && DateTime.UtcNow.Month > 5))) &&
                                                                                                         x.SourceForm == "schoolform" &&
                                                                                                         x.UtmContent == kv.Key);

                    AgentDailyActivity locationday = null;
                    if (agenthours.ContainsKey(kv.Key))
                    {
                        locationday = agenthours[kv.Key].SingleOrDefault(x => x.FormattedDate == cursordate.ToString("yyyyMMdd"));
                    }

                    int validnetworkschoolleadcount = validnetworkschoolleads.Count();

#warning TO DO: Replace with hourly pay rate from admin
                    double hoursworked = (locationday != null ? locationday.Hours : 0);

                    double lunch = 0;
                    if (hoursworked > 7)
                    {
                        lunch = 1;
                    }
                    else if (hoursworked > 4)
                    {
                        lunch = 0.5;
                    }

                    double billablehours = hoursworked - lunch;

                    double hourlyrate     = agentprofile.PayPerHour;
                    double hourlyearnings = billablehours * hourlyrate;
                    double CommissionRatePerSchoolLeadNetwork = agentprofile.PayPerLead; //TO DO: Replace with hourly pay rate from admin
                    double CommissionRatePerSchoolLeadDirect  = agentprofile.PayPerLead; //TO DO: Replace with hourly pay rate from admin
                    double CommissionRatePerJobLeadNetwork    = 0.25;                    //TO DO: Replace with hourly pay rate from admin
                    double CommissionRatePerJobLeadDirect     = 0.25;                    //TO DO: Replace with hourly pay rate from admin
                    double CommissionsSchoolLeadsNetwork      = validnetworkschoolleadcount * CommissionRatePerSchoolLeadNetwork;

                    int    uniquestudents          = validnetworkschoolleads.GroupBy(x => x.Email).Count();
                    double AvgRetentionSchoolLeads = uniquestudents > 0 ? (double)validnetworkschoolleadcount / uniquestudents : 0;

                    int    companyuniquestudents          = companyvalidnetworkschoolleads.GroupBy(x => x.Email).Count();
                    double CompanyAvgRetentionSchoolLeads = companyuniquestudents > 0 ? (double)companyvalidnetworkschoolleads.Count() / companyvalidnetworkschoolleads.GroupBy(x => x.Email).Count() : 0;



                    double AvgLPH = locationday != null && locationday.Hours > 0 ? CalculateLPH(validnetworkschoolleadcount, locationday.Hours) : 0;
                    double CompanyAverageLPHMean = GetAvgLPHMean(cursordate, companyvalidnetworkschoolleads, agenthours);
                    double CompanyAverageLPHMax  = GetAvgLPHMax(cursordate, companyvalidnetworkschoolleads, agenthours);
                    double CompanyAverageLPHMin  = GetAvgLPHMin(cursordate, companyvalidnetworkschoolleads, agenthours);

                    double Stochastic = 0;
                    if (CompanyAverageLPHMax - CompanyAverageLPHMin > 0 && AvgLPH > 0)
                    {
                        Stochastic = (AvgLPH - CompanyAverageLPHMin) / (CompanyAverageLPHMax - CompanyAverageLPHMin);
                    }



                    dates.Add(new
                    {
                        Agent = kv.Key,
                        Date  = cursordate.ToString("MMM-d"),

                        ValidSchoolLeadsNetwork        = validnetworkschoolleadcount,
                        CompanyValidSchoolLeadsNetwork = companyvalidnetworkschoolleads.Count(),
                        //ValidSchoolLeadsDirect = GetValidSchoolLeads(allrecords),
                        //ValidJobLeadsNetwork = GetValidSchoolLeads(allrecords),
                        //ValidJobLeadsDirect = GetValidSchoolLeads(allrecords),
                        InvalidSchoolLeadsNetwork        = invalidnetworkschoolleads.Count(),
                        CompanyInvalidSchoolLeadsNetwork = companyinvalidnetworkschoolleads.Count(),
                        //InvalidSchoolLeadsDirect = GetValidSchoolLeads(allrecords),
                        //InvalidJobLeadsNetwork = GetValidSchoolLeads(allrecords),
                        //InvalidJobLeadsDirect = GetValidSchoolLeads(allrecords),
                        //IndeedJobs = GetValidSchoolLeads(allrecords),
                        //UdemyCourses = GetValidSchoolLeads(allrecords),
                        UniqueStudents                 = validnetworkschoolleads.GroupBy(x => x.Email).Count(),
                        AvgRetentionSchoolLeads        = AvgRetentionSchoolLeads,
                        CompanyAvgRetentionSchoolLeads = CompanyAvgRetentionSchoolLeads,

                        CompanyAvgLPHMax  = CompanyAverageLPHMax,
                        CompanyAvgLPHMean = CompanyAverageLPHMean,
                        CompanyAvgLPHMin  = CompanyAverageLPHMin,
                        AvgLPH            = AvgLPH,

                        Hours         = hoursworked,
                        BillableHours = billablehours,
                        Lunch         = lunch,
                        Logon         = locationday != null ? locationday.LogonTime : "",
                        Logoff        = locationday != null ? locationday.LogoffTime : "",

                        HourlyRate     = hourlyrate,
                        HourlyEarnings = hourlyearnings,

                        CommissionRatePerSchoolLeadNetwork = CommissionRatePerSchoolLeadNetwork,
                        CommissionRatePerSchoolLeadDirect  = CommissionRatePerSchoolLeadDirect,
                        CommissionRatePerJobLeadNetwork    = CommissionRatePerJobLeadNetwork,
                        CommissionRatePerJobLeadDirect     = CommissionRatePerJobLeadDirect,

                        CommissionsSchoolLeadsNetwork = CommissionsSchoolLeadsNetwork,

                        TotalEarnings = hourlyearnings + CommissionsSchoolLeadsNetwork,

                        Stochastic = Stochastic,

                        Payments    = 0,
                        Adjustments = 0

                                      //,CumulativeEarnings
                    });


                    //Build production chart data arrays
                    if (hoursworked > 0)
                    {
                        try
                        {
                            ProductionChartData.Add(new object[] {
                                cursordate.ToString("MMM-d"),
                                float.Parse(String.Format("{0:0.0}", CompanyAverageLPHMax)),
                                float.Parse(String.Format("{0:0.0}", CompanyAverageLPHMin)),
                                float.Parse(String.Format("{0:0.0}", CompanyAverageLPHMean)),
                                float.Parse(String.Format("{0:0.0}", AvgLPH))
                            });
                        }
                        catch (Exception ex)
                        {
                            Console.Write(ex.Message);
                        }

                        //running totals
                        totalhours += hoursworked;
                        if (locationday != null)
                        {
                            aggregate["hours"].Add(hoursworked);
                            aggregate["billablehours"].Add(billablehours);
                        }
                        aggregate["hourlyearnings"].Add(hourlyearnings);

                        aggregate["validschoolleadsnetwork"].Add(validnetworkschoolleadcount);
                        aggregate["companyvalidschoolleadsnetwork"].Add(companyvalidnetworkschoolleads.Count());

                        aggregate["invalidschoolleadsnetwork"].Add(invalidnetworkschoolleads.Count());
                        aggregate["companyinvalidschoolleadsnetwork"].Add(companyinvalidnetworkschoolleads.Count());

                        aggregate["commissionsschoolleadsnetwork"].Add(CommissionsSchoolLeadsNetwork);

                        aggregate["AvgRetentionSchoolLeads"].Add(AvgRetentionSchoolLeads);
                        aggregate["CompanyAvgRetentionSchoolLeads"].Add(CompanyAvgRetentionSchoolLeads);
                        aggregate["AvgLPH"].Add(AvgLPH);
                        aggregate["CompanyAverageLPHMean"].Add(CompanyAverageLPHMean);
                        aggregate["Stochastic"].Add(Stochastic);
                    }



                    cursordate = cursordate.AddDays(1);
                }

                double aggregatelph = aggregate["AvgLPH"].Average();


                agents.Add(new
                {
                    Id    = kv.Key,
                    Dates = dates.ToArray(),

                    TotalHours          = totalhours,
                    TotalBillableHours  = aggregate["billablehours"].Sum(),
                    AvgHoursPerDay      = aggregate.ContainsKey("hours") ? aggregate["hours"].Average() : 0,
                    TotalHourlyEarnings = aggregate["hourlyearnings"].Sum(),

                    TotalValidSchoolLeadsNetwork        = aggregate["validschoolleadsnetwork"].Sum(),
                    AvgValidSchoolLeadsNetwork          = aggregate["validschoolleadsnetwork"].Average(),
                    CompanyTotalValidSchoolLeadsNetwork = aggregate["companyvalidschoolleadsnetwork"].Sum(),

                    TotalInvalidSchoolLeadsNetwork        = aggregate["invalidschoolleadsnetwork"].Sum(),
                    AvgInvalidSchoolLeadsNetwork          = aggregate["invalidschoolleadsnetwork"].Average(),
                    CompanyTotalInvalidSchoolLeadsNetwork = aggregate["companyinvalidschoolleadsnetwork"].Sum(),

                    //totalvalidschoolleadsdirect = 0;
                    //totalvalidjobleadsnetwork = 0;
                    //totalvalidjobleadsdirect = 0;

                    TotalCommissionCchoolLeadsNetwork = aggregate["commissionsschoolleadsnetwork"].Sum(),

                    TotalEarnings = aggregate["hourlyearnings"].Sum() + aggregate["commissionsschoolleadsnetwork"].Sum(),

                    //totalcommissionschoolleadsdirect = 0;
                    //totalcommissionjobleadsnetwork = 0;
                    //totalcommissionjobleadsdirect = 0;

                    AvgRetentionSchoolLeads        = aggregate["AvgRetentionSchoolLeads"].Average(),
                    CompanyAvgRetentionSchoolLeads = aggregate["CompanyAvgRetentionSchoolLeads"].Average(),

                    AvgLPH = aggregatelph,
                    CompanyAverageLPHMean = aggregate["CompanyAverageLPHMean"].Average(),

                    Stochastic = aggregate["Stochastic"].Average(),

                    ProductionChartData = ProductionChartData.ToArray()
                });
            }


            string retvalue = (new { result = "ok", agents = agents.ToArray() }).ToJSON();

            //Save cached version
            BlobJsonResourceManager.Instance.SaveJsonResource(retvalue, "range" + startdate + enddate, "skillcowagentdashboard", datestamp);

            Response.Write(retvalue);
            Response.End();
            //}
            //catch (Exception ex)
            //{
            //    Response.ContentType = "application/json";
            //    Response.Write(DefaultErrorResponse(ex.Message));
            //    Response.End();
            //}

            return(null);
        }
Exemple #32
0
 public abstract void Execute(Messsage command, AgentClient client);
Exemple #33
0
        //
        // GET: /_xyz_agents/

        public ActionResult Index()
        {
            AgentClient ac = new AgentClient();

            return(View(ac.GetAll().Execute()));
        }
 public async Task Initialize()
 {
     agentClient = new AgentClient();
 }
        static void Main(string[] args)
        {
            var agent = new AgentClient();

            agent.Run();
        }
 private static async Task KillAllClones(AgentClient client)
 {
     await client.ClonesKill();
     await client.ClonesDelete();
 }
        public async Task Should_be_able_to_recover_clones()
        {
            await AgentClientBuilder.KillClones(client);

            await Should_be_able_to_get_clone();

            Thread.Sleep(TestConstants.CLONE_WAIT_MS);

            var cloneInfos = await client.StartClones();

            Thread.Sleep(TestConstants.CLONE_WAIT_MS);

            var agents = new List<AgentClient>();

            foreach (var cloneInfo in cloneInfos)
            {
                var agent = new AgentClient(cloneInfo.ToClientInfo("guest", "guest"));
                agents.Add(agent.Start());
            }

            Thread.Sleep(TestConstants.CLONE_WAIT_MS);

            foreach (var agent in agents)
            {
                var result = await agent.Ping();
                Assert.That(result, Is.Not.Null.Or.Empty);
            }

            foreach (var agent in agents)
            {
                agent.Exit();
            }
        }