示例#1
0
        private void Init()
        {
            Settings.Default.Upgrade();

            if (!Settings.Default.NeverClickerConfigValid)
            {
                this.SetButtonStateAllDisabled();
                this.ConfigInvalid();
            }
            else
            {
                this.AutomationEngine = new AutomationEngine(this);

                if (Settings.Default.BeginOnStartup)
                {
                    int delaySecs = 10;
                    this.SetButtonStateRunning();
                    this.AutoCycleTask = AutomationEngine.AutoCycle(delaySecs);
                }
                else
                {
                    this.SetButtonStateStopped();
                    WriteLine("Automation engine ready.");
                    WriteLine("Press 'Begin AutoCycle' above to start.");
                }
            }
        }
示例#2
0
 private void ElementSetEditor_Load(object sender, EventArgs e)
 {
     m_AutomationEngine = new AutomationEngine(wbElementSet);
     m_AutomationEngine.SetSequence(m_StepEditContext.Sequence);
     m_AutomationEngine.ExecutionComplete += m_AutomationEngine_ExecutionComplete;
     m_AutomationEngine.ExecuteSequence(m_StepEditContext.GetEditStepPosition());
 }
示例#3
0
 void ElementSetEditor_Disposed(object sender, EventArgs e)
 {
     if (m_AutomationEngine != null)
     {
         m_AutomationEngine.Dispose();
         m_AutomationEngine = null;
     }
 }
示例#4
0
 void GetValueSuggestor_Disposed(object sender, EventArgs e)
 {
     if (m_AutomationEngine != null)
     {
         m_AutomationEngine.Dispose();
         m_AutomationEngine = null;
     }
 }
        private ExecutionContext GetExecutionContext()
        {
            CultureInfo         currentCulture   = CultureInfo.CurrentCulture;
            PSHost              hostInterface    = new DefaultHost(currentCulture, currentCulture);
            InitialSessionState iss              = InitialSessionState.CreateDefault2();
            AutomationEngine    engine           = new AutomationEngine(hostInterface, iss);
            ExecutionContext    executionContext = new ExecutionContext(engine, hostInterface, iss);

            return(executionContext);
        }
示例#6
0
        private void GetValueSuggestor_Load(object sender, EventArgs e)
        {
            m_AutomationEngine = new AutomationEngine(wbPreview);
            m_AutomationEngine.SetSequence(m_StepEditContext.Sequence);
            m_AutomationEngine.ExecutionComplete += m_AutomationEngine_ExecutionComplete;

            int executionScope = m_GroupStepEditContext != null
                ? m_GroupStepEditContext.GetEditStepPosition()
                : m_StepEditContext.GetEditStepPosition();

            m_AutomationEngine.ExecuteSequence(executionScope);
        }
示例#7
0
        public void TestDrives()
        {
            CultureInfo              currentCulture   = CultureInfo.CurrentCulture;
            PSHost                   hostInterface    = new DefaultHost(currentCulture, currentCulture);
            InitialSessionState      iss              = InitialSessionState.CreateDefault2();
            AutomationEngine         engine           = new AutomationEngine(hostInterface, iss);
            ExecutionContext         executionContext = new ExecutionContext(engine, hostInterface, iss);
            SessionStateInternal     sessionState     = new SessionStateInternal(executionContext);
            Collection <PSDriveInfo> drives           = sessionState.Drives(null);

            Assert.NotNull(drives);
        }
示例#8
0
        public SequenceRecorder()
        {
            InitializeComponent();

            m_Lock                             = new object();
            m_BrowserHelper                    = new WebBrowserHelper(wbRecorder);
            m_AutomationEngine                 = new AutomationEngine(wbRecorder);
            m_ElementsWithHandlers             = new HashSet <HtmlElement>();
            m_ElementSelector                  = new ElementSelector(wbRecorder);
            m_ElementSelector.ElementSelected += m_ElementSelector_ElementSelected;
            m_StepIndex                        = new Dictionary <Step, int>();

            tlvSequence.FormatRow      += tlvSequence_FormatRow;
            tlvSequence.CanExpandGetter = zCanExpandGetter;
            tlvSequence.ChildrenGetter  = zChildrenGetter;
            tlvSequence.HotItemStyle    = new BrightIdeasSoftware.HotItemStyle()
            {
                Decoration = new BrightIdeasSoftware.RowBorderDecoration()
                {
                    BorderPen      = new Pen(Color.Transparent, 2),
                    BoundsPadding  = new Size(1, 1),
                    CornerRounding = 4.0f
                }
            };
            BrightIdeasSoftware.SimpleDropSink sink = (BrightIdeasSoftware.SimpleDropSink)tlvSequence.DropSink;
            sink.CanDropBetween = true;

            olvColumnOrder.AspectGetter       = zOrderAspectGetter;
            olvColumnOrder.ImageGetter        = zOrderImageGetter;
            olvColumnHasCondition.ImageGetter = zHasConditionImageGetter;
            olvColumnIsIteration.ImageGetter  = zIsIterationImageGetter;
            olvColumnEdit.AspectGetter        = (obj) => "Edit...";
            olvColumnDelete.AspectGetter      = (obj) => "Remove";
            olvColumnExecute.AspectGetter     = (obj) => "Go!";

            tlvVariables.CanExpandGetter        = zVariableCanExpandGetter;
            tlvVariables.ChildrenGetter         = zVariableChildrenGetter;
            olvColumnVariableValue.AspectGetter = zVariableValueAspectGetter;

            imageListSequence.Images.AddRange(new Image[]
            {
                Resources.GreenArrow,
                Resources.RedArrow,
                Resources.Document,
                Resources.Iteration
            });

            cbAvailableStepList.DataSource = Step.GetAvailableStepList(false)
                                             .OrderBy(s => s.DisplayName)
                                             .ToList();
        }
示例#9
0
 protected override void Dispose(bool disposing)
 {
     try
     {
         if (!this._disposed)
         {
             lock (base.SyncRoot)
             {
                 if (this._disposed)
                 {
                     return;
                 }
                 this._disposed = true;
             }
             if (disposing)
             {
                 this.Close();
                 this._engine             = null;
                 this._history            = null;
                 this._jobManager         = null;
                 this._jobRepository      = null;
                 this._runspaceRepository = null;
                 if (base.RunspaceOpening != null)
                 {
                     base.RunspaceOpening.Dispose();
                     base.RunspaceOpening = null;
                 }
                 if ((base.ExecutionContext != null) && (base.ExecutionContext.Events != null))
                 {
                     try
                     {
                         base.ExecutionContext.Events.Dispose();
                     }
                     catch (ObjectDisposedException)
                     {
                     }
                 }
             }
         }
     }
     finally
     {
         base.Dispose(disposing);
     }
 }
示例#10
0
        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                zDisableRecording();
                if (m_AutomationEngine != null)
                {
                    m_AutomationEngine.StepBegin         -= m_AutomationEngine_StepBegin;
                    m_AutomationEngine.StepComplete      -= m_AutomationEngine_StepComplete;
                    m_AutomationEngine.ExecutionBegin    -= m_AutomationEngine_ExecutionBegin;
                    m_AutomationEngine.ExecutionComplete -= m_AutomationEngine_ExecutionComplete;

                    m_AutomationEngine.Dispose();
                    m_AutomationEngine = null;
                }
                components.Dispose();
            }
            base.Dispose(disposing);
        }
示例#11
0
 private void DoCloseHelper()
 {
     base.StopPipelines();
     this.StopOrDisconnectAllJobs();
     this.CloseOrDisconnectAllRemoteRunspaces(delegate {
         List <RemoteRunspace> list = new List <RemoteRunspace>();
         foreach (PSSession session in this.RunspaceRepository.Runspaces)
         {
             list.Add(session.Runspace as RemoteRunspace);
         }
         return(list);
     });
     this._engine.Context.RunspaceClosingNotification();
     MshLog.LogEngineLifecycleEvent(this._engine.Context, EngineState.Stopped);
     this._engine         = null;
     this._commandFactory = null;
     base.SetRunspaceState(RunspaceState.Closed);
     base.RaiseRunspaceStateEvents();
 }
示例#12
0
        protected override void OnStart(string[] args)
        {
            Container container = new Container();

            IoC.Configure(container);
            InitializeAutoMapper.Initialize();

            #region Logging Configuration
            ExceptionHandler.Current.AddDefaultLogAndRethrowPolicy();
            ExceptionHandler.Current.AddDefaultLogOnlyPolicy();
            Logger.Current.CreateRollingFlatFileListener(EventLevel.Verbose, ConfigurationManager.AppSettings["AUTOMATION_ENGINE_LOG_FILE_PATH"], 2048);
            #endregion

            var cachingService        = IoC.Container.GetInstance <ICachingService>();
            var indexingService       = IoC.Container.GetInstance <IIndexingService>();
            var advancedSearchService = IoC.Container.GetInstance <IAdvancedSearchService>();
            var contactService        = IoC.Container.GetInstance <IContactService>();
            var workflowService       = IoC.Container.GetInstance <IWorkflowService>();
            var accountService        = IoC.Container.GetInstance <IAccountService>();
            var tagService            = IoC.Container.GetInstance <ITagService>();
            var campaignService       = IoC.Container.GetInstance <ICampaignService>();
            var leadScoreService      = IoC.Container.GetInstance <ILeadScoreService>();
            var pubSubService         = IoC.Container.GetInstance <IPublishSubscribeService>();
            var opportunityServcie    = IoC.Container.GetInstance <IOpportunitiesService>();
            var communicationService  = IoC.Container.GetInstance <ICommunicationService>();

            #region Schedule Messaging Job
            //Quartz.Net Job Scheduler
            //use http://www.cronmaker.com/ to build cron expression
            Logger.Current.Informational("Scheduling Job : Message Scheduler");
            IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler();
            scheduler.Start();

            scheduler.ScheduleJob(CreateJob <MessagingScheduler>(),
                                  CreateTrigger(ConfigurationManager.AppSettings["MESSAGESCHEDULE_CRON"].ToString(), "Message Scheduler"));
            #endregion

            AutomationEngine engine = new AutomationEngine(cachingService, indexingService, advancedSearchService,
                                                           contactService, workflowService, accountService, tagService, campaignService, leadScoreService, pubSubService, opportunityServcie, communicationService);
            engine.Start();
            Logger.Current.Informational("Engine started successfully.");
        }
示例#13
0
		private void Init() {
			Settings.Default.Upgrade();

			if (!Settings.Default.NeverClickerConfigValid) {
				this.SetButtonStateAllDisabled();
				this.ConfigInvalid();
			} else {
				this.AutomationEngine = new AutomationEngine(this);

				if (Settings.Default.BeginOnStartup) {
					int delaySecs = 10;
					this.SetButtonStateRunning();
					this.AutoCycleTask = AutomationEngine.AutoCycle(delaySecs);
				} else {
					this.SetButtonStateStopped();
					WriteLine("Automation engine ready.");
					WriteLine("Press 'Begin AutoCycle' above to start.");
				}
			}
		}
示例#14
0
        /// <summary>
        /// Helper function used for opening a runspace
        /// </summary>
        private void DoOpenHelper()
        {
            // NTRAID#Windows Out Of Band Releases-915851-2005/09/13
            if (_disposed)
            {
                throw PSTraceSource.NewObjectDisposedException("runspace");
            }

            bool startLifeCycleEventWritten = false;
            s_runspaceInitTracer.WriteLine("begin open runspace");
            try
            {
                _transcriptionData = new TranscriptionData();

                if (InitialSessionState != null)
                {
                    // All ISS-based configuration of the engine itself is done by AutomationEngine,
                    // which calls InitialSessionState.Bind(). Anything that doesn't
                    // require an active and open runspace should be done in ISS.Bind()
                    _engine = new AutomationEngine(Host, null, InitialSessionState);
                }
                else
                {
                    _engine = new AutomationEngine(Host, RunspaceConfiguration, null);
                }
                _engine.Context.CurrentRunspace = this;

                //Log engine for start of engine life
                MshLog.LogEngineLifecycleEvent(_engine.Context, EngineState.Available);
                startLifeCycleEventWritten = true;

                _commandFactory = new CommandFactory(_engine.Context);
                _history = new History(_engine.Context);
                _jobRepository = new JobRepository();
                _jobManager = new JobManager();
                _runspaceRepository = new RunspaceRepository();

                s_runspaceInitTracer.WriteLine("initializing built-in aliases and variable information");
                InitializeDefaults();
            }
            catch (Exception exception)
            {
                CommandProcessorBase.CheckForSevereException(exception);
                s_runspaceInitTracer.WriteLine("Runspace open failed");

                //Log engine health event
                LogEngineHealthEvent(exception);

                //Log engine for end of engine life
                if (startLifeCycleEventWritten)
                {
                    Dbg.Assert(_engine.Context != null, "if startLifeCycleEventWritten is true, ExecutionContext must be present");
                    MshLog.LogEngineLifecycleEvent(_engine.Context, EngineState.Stopped);
                }

                //Open failed. Set the RunspaceState to Broken.
                SetRunspaceState(RunspaceState.Broken, exception);

                //Raise the event
                RaiseRunspaceStateEvents();

                //Rethrow the exception. For asynchronous execution, 
                //OpenThreadProc will catch it. For synchronous execution
                //caller of open will catch it.
                throw;
            }

            SetRunspaceState(RunspaceState.Opened);
            RunspaceOpening.Set();

            //Raise the event
            RaiseRunspaceStateEvents();
            s_runspaceInitTracer.WriteLine("runspace opened successfully");

            // Now do initial state configuration that requires an active runspace
            if (InitialSessionState != null)
            {
                Exception initError = InitialSessionState.BindRunspace(this, s_runspaceInitTracer);
                if (initError != null)
                {
                    // Log engine health event
                    LogEngineHealthEvent(initError);

                    // Log engine for end of engine life
                    Debug.Assert(_engine.Context != null,
                                "if startLifeCycleEventWritten is true, ExecutionContext must be present");
                    MshLog.LogEngineLifecycleEvent(_engine.Context, EngineState.Stopped);

                    // Open failed. Set the RunspaceState to Broken.
                    SetRunspaceState(RunspaceState.Broken, initError);

                    // Raise the event
                    RaiseRunspaceStateEvents();

                    // Throw the exception. For asynchronous execution, 
                    // OpenThreadProc will catch it. For synchronous execution
                    // caller of open will catch it.
                    throw initError;
                }
            }

            TelemetryAPI.ReportLocalSessionCreated(InitialSessionState, TranscriptionData);
        }
示例#15
0
        private void DoOpenHelper()
        {
            if (this._disposed)
            {
                throw PSTraceSource.NewObjectDisposedException("runspace");
            }
            bool startLifeCycleEventWritten = false;

            runspaceInitTracer.WriteLine("begin open runspace", new object[0]);
            try
            {
                if (this.InitialSessionState != null)
                {
                    this._engine = new AutomationEngine(base.Host, null, this.InitialSessionState);
                }
                else
                {
                    this._engine = new AutomationEngine(base.Host, this.RunspaceConfiguration, null);
                }
                this._engine.Context.CurrentRunspace = this;
                MshLog.LogEngineLifecycleEvent(this._engine.Context, EngineState.Available);
                startLifeCycleEventWritten = true;
                this._commandFactory       = new System.Management.Automation.CommandFactory(this._engine.Context);
                this._history            = new Microsoft.PowerShell.Commands.History(this._engine.Context);
                this._jobRepository      = new System.Management.Automation.JobRepository();
                this._jobManager         = new System.Management.Automation.JobManager();
                this._runspaceRepository = new System.Management.Automation.RunspaceRepository();
                runspaceInitTracer.WriteLine("initializing built-in aliases and variable information", new object[0]);
                this.InitializeDefaults();
            }
            catch (Exception exception)
            {
                CommandProcessorBase.CheckForSevereException(exception);
                runspaceInitTracer.WriteLine("Runspace open failed", new object[0]);
                this.LogEngineHealthEvent(exception);
                if (startLifeCycleEventWritten)
                {
                    MshLog.LogEngineLifecycleEvent(this._engine.Context, EngineState.Stopped);
                }
                base.SetRunspaceState(RunspaceState.Broken, exception);
                base.RaiseRunspaceStateEvents();
                throw;
            }
            base.SetRunspaceState(RunspaceState.Opened);
            base.RunspaceOpening.Set();
            base.RaiseRunspaceStateEvents();
            runspaceInitTracer.WriteLine("runspace opened successfully", new object[0]);
            string environmentVariable = Environment.GetEnvironmentVariable("PSMODULEPATH");

            if (this.InitialSessionState != null)
            {
                try
                {
                    Environment.SetEnvironmentVariable("PSMODULEPATH", ModuleIntrinsics.GetSystemwideModulePath());
                    this.ProcessImportModule(this.InitialSessionState.CoreModulesToImport, startLifeCycleEventWritten);
                    this._engine.Context.EngineSessionState.Module = null;
                }
                finally
                {
                    Environment.SetEnvironmentVariable("PSMODULEPATH", environmentVariable);
                }
                this.ProcessImportModule(this.InitialSessionState.ModuleSpecificationsToImport, startLifeCycleEventWritten);
                InitialSessionState.SetSessionStateDrive(this._engine.Context, true);
                if (this.InitialSessionState.WarmUpTabCompletionOnIdle)
                {
                    ScriptBlock action = ScriptBlock.Create("$null = [System.Management.Automation.CommandCompletion]::CompleteInput('Set-Location', 12, $null)");
                    this._engine.Context.Events.SubscribeEvent(null, null, "PowerShell.OnIdle", null, action, true, false, 1);
                }
            }
        }
示例#16
0
        public void Execute(IJobExecutionContext context)
        {
            ThreadSynchronizer threadSynchronizer = null;
            frmAutomation      frmAutomation      = null;

            try
            {
                m_JobKey = context.JobDetail.Key;
                m_Logger.InfoFormat("ExecuteSequenceJob {0} executing at {1}.", m_JobKey, DateTime.Now.ToString("r"));

                string connectionString = (string)context.MergedJobDataMap["connectionString"];
                AutomationController automationController = new AutomationController(connectionString);
                SchedulingController schedulingController = new SchedulingController(connectionString);

                long           scheduledTaskId = (long)context.MergedJobDataMap["scheduledTaskId"];
                ScheduledTask  scheduledTask   = schedulingController.GetScheduledTask(scheduledTaskId, DeletedInclusion.All);
                SequenceDetail sequenceDetail  = automationController.GetSequenceDetail(scheduledTask.TaskSequence.SequenceId);

                threadSynchronizer = (ThreadSynchronizer)context.MergedJobDataMap["threadSynchronizer"];
                threadSynchronizer.RunOnSynchronizedThread(() => frmAutomation = new frmAutomation(), true);

                using (AutomationEngine automationEngine = new AutomationEngine(frmAutomation.Browser))
                {
                    automationEngine.SetSequence(sequenceDetail.SequenceSteps);
                    Dictionary <string, IStateVariable> persistedData = automationController.GetSequencePersistedData(sequenceDetail.Sequence.SequenceId);
                    automationEngine.DataContext.LoadPersistedVariables(persistedData);

                    automationEngine.ExecutionComplete += automationEngine_ExecutionComplete;
                    using (m_ExecutionWaitHandle = new AutoResetEvent(false))
                    {
                        automationEngine.ExecuteSequence();

                        if (!m_ExecutionWaitHandle.WaitOne(scheduledTask.RunDurationLimit.HasValue
                            ? scheduledTask.RunDurationLimit.Value
                            : TimeSpan.FromMilliseconds(-1)))
                        {
                            throw new TimeoutException(
                                      String.Format("Scheduled sequence execution timed out because it reached the specified Run Duration Limit of {0}.",
                                                    scheduledTask.RunDurationLimit));
                        }
                    }
                    automationEngine.ExecutionComplete -= automationEngine_ExecutionComplete;

                    persistedData = automationEngine.DataContext.GetPersistedVariables();
                    automationController.SetSequencePersistedData(sequenceDetail.Sequence.SequenceId, persistedData);
                }

                ExecuteSequenceJobResult result = new ExecuteSequenceJobResult(
                    zGetScheduledTaskStatusFromExecutionState(m_ExecutionCompleteEventArgs.RunResult),
                    "");     //TODO: get error from ExecutionCompleteEventArgs
                context.Result = result;
            }
            catch (Exception ex)
            {
                JobExecutionException jobEx = new JobExecutionException(ex, false);
                throw jobEx;
            }
            finally
            {
                //Clean up
                try
                {
                    if (frmAutomation != null)
                    {
                        threadSynchronizer.RunOnSynchronizedThread(() => frmAutomation.Dispose(), true);
                    }
                }
                catch (Exception ex)
                {
                    if (m_Logger != null)
                    {
                        m_Logger.ErrorFormat("Cleanup failed for ExecuteSequenceJob {0}: {1}", m_JobKey, ex.Message);
                    }
                }

                //Dereference global variables
                m_Logger = null;
                m_JobKey = null;
                m_ExecutionCompleteEventArgs = null;
                m_ExecutionWaitHandle        = null;
            }
        }
示例#17
0
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
            bool env = Environment.UserInteractive;

            if (env)
            {
                Logger.Current.Informational("Starting the engine in CommandLine mode.");

                Container container = new Container();
                IoC.Configure(container);
                InitializeAutoMapper.Initialize();

                #region Logging Configuration
                ExceptionHandler.Current.AddDefaultLogAndRethrowPolicy();
                ExceptionHandler.Current.AddDefaultLogOnlyPolicy();
                Logger.Current.CreateRollingFlatFileListener(EventLevel.Verbose,
                                                             ConfigurationManager.AppSettings["AUTOMATION_ENGINE_LOG_FILE_PATH"], 2048);
                #endregion

                //engine = new ScoringEngine();
                //engine.Start();
                var cachingService        = IoC.Container.GetInstance <ICachingService>();
                var indexingService       = IoC.Container.GetInstance <IIndexingService>();
                var advancedSearchService = IoC.Container.GetInstance <IAdvancedSearchService>();
                var contactService        = IoC.Container.GetInstance <IContactService>();
                var workflowService       = IoC.Container.GetInstance <IWorkflowService>();
                var accountService        = IoC.Container.GetInstance <IAccountService>();
                var tagService            = IoC.Container.GetInstance <ITagService>();
                var campaignService       = IoC.Container.GetInstance <ICampaignService>();
                var leadScoreService      = IoC.Container.GetInstance <ILeadScoreService>();
                var pubSubService         = IoC.Container.GetInstance <IPublishSubscribeService>();
                var opportunityServcie    = IoC.Container.GetInstance <IOpportunitiesService>();
                var communicationService  = IoC.Container.GetInstance <ICommunicationService>();

                #region Schedule Messaging Job
                //Quartz.Net Job Scheduler
                //use http://www.cronmaker.com/ to build cron expression

                IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler();
                scheduler.Start();

                scheduler.ScheduleJob(CreateJob <MessagingScheduler>(),
                                      CreateTrigger(ConfigurationManager.AppSettings["MESSAGESCHEDULE_CRON"].ToString(), "Message Scheduler"));
                #endregion

                AutomationEngine engine = new AutomationEngine(cachingService, indexingService, advancedSearchService,
                                                               contactService, workflowService, accountService, tagService, campaignService, leadScoreService, pubSubService, opportunityServcie, communicationService);
                engine.Start();
                Logger.Current.Informational("Engine started successfully.");
            }
            else
            {
                Logger.Current.Informational("Starting the engine in Windows Service mode.");
                ServiceBase[] ServicesToRun;
                ServicesToRun = new ServiceBase[]
                {
                    new SmartCRMAutomationEngine()
                };
                ServiceBase.Run(ServicesToRun);
            }

            Console.ReadLine();
        }