/// <summary>
 /// Bluetooth transport constructor
 /// </summary>
 public BluetoothTransport()
 {
     _showAsConnected = false;
     _lazyReconnect = true;
     _worker = new AsyncWorker(Poll);
     _worker.Name = "Bluetooth Transport";
 }
        public void FindOrganisationList()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Organisation");
            dt.Columns.Add("Description");
            this.ug_organisationlist.DataSource = dt;
            this.lbl_recordCount.Text = this.ug_organisationlist.Rows.Count.ToString();

            using (AsyncWorker<IOrganisationMaintenance> worker = new AsyncWorker<IOrganisationMaintenance>(_presenter, this.ug_organisationlist, new Control[] { btn_search, btn_reset }))
            {
                worker.DoWork += delegate(object oDoWork, DoWorkEventArgs eDoWork)
                {
                    eDoWork.Result = _presenter.FindeOrganisationsByConditions(this.txt_organisationName.Text, this.txt_organisationDescription.Text);
                };
                worker.RunWorkerCompleted += delegate(object oCompleted, RunWorkerCompletedEventArgs eCompleted)
                {
                    List<OrganisationEntity> orgEntities = eCompleted.Result as List<OrganisationEntity>;
                    if (orgEntities != null)
                    {
                        foreach (OrganisationEntity entity in orgEntities)
                        {
                            dt.Rows.Add(entity.OrganisationName, entity.OrganisationDescription);
                        }
                    }
                    this.ug_organisationlist.DataSource = dt;
                    this.lbl_recordCount.Text = this.ug_organisationlist.Rows.Count.ToString();
                };
                worker.Run();
            }
        }
Exemple #3
0
        public void ExceptionViewModelConstructorNewAsyncWorker()
        {
            IAsyncWorker asyncWorker = new AsyncWorker();

            ExceptionViewModel vm = new ExceptionViewModel(asyncWorker);

            Assert.IsNotNull(vm.AsyncWorker);
            Assert.AreSame(asyncWorker, vm.AsyncWorker);
        }
Exemple #4
0
 /// <summary> Gets or sets the current serial port settings. </summary>
 /// <value> The current serial settings. </value>
 public FileTransport()
 {
     _arduino2pc =
         System.IO.File.Open(@"c:\temp\serial2pc.txt", FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite);
     _pc2arduino =
         System.IO.File.Open(@"c:\temp\serial2arduino.txt", FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite);
     _arduino2pc.Seek(0, SeekOrigin.End);
     _worker = new AsyncWorker(Poll);
     _worker.Name = "FileTransport";
 }
 private void LogOperationCompletedWithException(AsyncWorker asyncWorker, DoWorkEventHandler worker, Exception exception)
 {
     this.log.Debug(string.Format(
                        CultureInfo.InvariantCulture,
                        "{0} completes asynchronous operation {1}.{2}() with exception = {3}",
                        asyncWorker,
                        worker.Method.DeclaringType.FullName,
                        worker.Method.Name,
                        exception));
 }
 public void Start(AsyncWorker <T> work)
 {
     try
     {
         _results.Add(work());
     }
     catch (Exception error)
     {
         _results.Add(new AsyncWorkResult <T>(error));
     }
 }
 /// <summary>
 /// Called when an operation is cancelled.
 /// </summary>
 /// <param name="asyncWorker">The async worker.</param>
 /// <param name="worker">The worker.</param>
 public void CancellingExecution(AsyncWorker asyncWorker, DoWorkEventHandler worker)
 {
     if (this.log.IsDebugEnabled)
     {
         this.log.Debug(string.Format(
                            CultureInfo.InvariantCulture,
                            "{0} cancels asynchronous operation {1}.{2}()",
                            asyncWorker,
                            worker.Method.DeclaringType.FullName,
                            worker.Method.Name));
     }
 }
 /// <summary>
 /// Called when an operation reports progress.
 /// </summary>
 /// <param name="asyncWorker">The async worker.</param>
 /// <param name="worker">The worker.</param>
 /// <param name="progress">The progress.</param>
 /// <param name="userState">State of the user.</param>
 public void ReportProgress(AsyncWorker asyncWorker, DoWorkEventHandler worker, ProgressChangedEventHandler progress, object userState)
 {
     if (this.log.IsDebugEnabled)
     {
         this.log.Debug(string.Format(
                            CultureInfo.InvariantCulture,
                            "{0} reports progress for operation {1}.{2}()",
                            asyncWorker,
                            worker.Method.DeclaringType.FullName,
                            worker.Method.Name));
     }
 }
 /// <summary>
 /// Called when an operation is cancelled.
 /// </summary>
 /// <param name="asyncWorker">The async worker.</param>
 /// <param name="worker">The worker.</param>
 public void CancellingExecution(AsyncWorker asyncWorker, DoWorkEventHandler worker)
 {
     if (this.log.IsInfoEnabled)
     {
         this.log.Info(string.Format(
                      CultureInfo.InvariantCulture,
                      "{0} cancels asynchronous operation {1}.{2}()",
                      asyncWorker,
                      worker.Method.DeclaringType.FullName,
                      worker.Method.Name));
     }
 }
Exemple #10
0
        private void btnLogin_Click(object sender, RoutedEventArgs e)
        {
            bool isApplySuccess = false;

            string strpwd         = pbPwd.Password;
            string strPrinterName = ((MainWindow)App.Current.MainWindow).statusPanelPage.m_selectedPrinter;
            string strDrvName     = "";

            if (false == common.GetPrinterDrvName(strPrinterName, ref strDrvName))
            {
                MessageBoxEx_Simple messageBox =
                    new MessageBoxEx_Simple((string)this.TryFindResource("ResStr_can_not_be_carried_out_due_to_software_has_error__please_try__again_after_reinstall_the_Driver_and_Virtual_Operation_Panel_"), (string)this.FindResource("ResStr_Error"));
                messageBox.Owner = App.Current.MainWindow;
                messageBox.ShowDialog();

                return;
            }

            if (strpwd.Length > 0)
            {
                PasswordRecord m_rec  = new PasswordRecord(strPrinterName, strpwd);
                AsyncWorker    worker = new AsyncWorker(this);

                if (worker.InvokeMethod <PasswordRecord>(strPrinterName, ref m_rec, DllMethodType.ConfirmPassword, this))
                {
                    if (null != m_rec && m_rec.CmdResult == EnumCmdResult._ACK)
                    {
                        ((MainWindow)App.Current.MainWindow).m_strPassword = strpwd;
                        isApplySuccess = true;
                    }
                }

                if (!isApplySuccess)
                {
                    ((MainWindow)App.Current.MainWindow).m_strPassword = "";
                    pbPwd.Focus();
                    pbPwd.SelectAll();
                    tbkErrorInfo.Foreground = new SolidColorBrush(Colors.Red);
                    tbkErrorInfo.Text       = (string)this.FindResource("ResStr_Authentication_error__please_enter_the_password_again_");
                }
                else
                {
                    this.DialogResult = true;
                    this.Close();
                }
            }
            else
            {
                tbkErrorInfo.Foreground = new SolidColorBrush(Colors.Red);
                tbkErrorInfo.Text       = (string)this.FindResource("ResStr_The_new_password_can_not_be_empty_");
            }
        }
 /// <summary>
 /// Called when an operation is started.
 /// </summary>
 /// <param name="asyncWorker">The async worker.</param>
 /// <param name="worker">The worker.</param>
 /// <param name="argument">The argument.</param>
 public void StartedExecution(AsyncWorker asyncWorker, DoWorkEventHandler worker, object argument)
 {
     if (this.log.IsDebugEnabled)
     {
         this.log.Debug(string.Format(
                            CultureInfo.InvariantCulture,
                            "{0} executes asynchronous operation {1}.{2}({3})",
                            asyncWorker,
                            worker.Method.DeclaringType.FullName,
                            worker.Method.Name,
                            argument));
     }
 }
Exemple #12
0
        public void SetEventLoop(bool active)
        {
            if (_active == active)
            {
                return;
            }
            _active = active;

            if (_active)
            {
                AsyncWorker.Run(EventLoop);
            }
        }
        private async Task SomeAsyncFunction()
        {
            Log("Starting async function");

            Log("Waiting for coroutine");
            await AsyncWorker.RunAsync(SomeCoroutine);

            Log("Waiting for deferred");
            await SomeExternalAsyncFunction();

            Log("Woo! All async stuff worked");
            Completed();
        }
Exemple #14
0
        public ApplicationWatcher(Logger logger)
        {
            //ProcessHandlers= new List<ProcessHandler>();
            ApplicationHandlers = new List <ApplicationHandler>();
            _sleepStopwatch     = new Stopwatch();
            var asyncWorkerMonitor = new AsyncWorker(MonitorJob)
            {
                Name = "ApplicationWatcher"
            };

            asyncWorkerMonitor.Start();
            _logger = logger;
        }
        public AsyncTest()
        {
            InitializeComponent();

            var taskId = Guid.NewGuid();

            AsyncWorker.Execute(() => DateTime.Now.ToString(), time => display.Text += time + "\r\n", new TimeSpan(0, 0, 0, 5), processId: taskId);
            AsyncWorker.Execute(() => "Hello! " + Environment.TickCount.ToString(), time => display.Text += time + "\r\n", new TimeSpan(0, 0, 0, 2));

            AsyncWorker.PauseContinuousProcess(taskId);
            AsyncWorker.ResumeContinuousProcess(taskId);
            AsyncWorker.StopContinuousProcess(taskId);
        }
 /// <summary>
 /// Called when an operation is started.
 /// </summary>
 /// <param name="asyncWorker">The async worker.</param>
 /// <param name="worker">The worker.</param>
 /// <param name="argument">The argument.</param>
 public void StartedExecution(AsyncWorker asyncWorker, DoWorkEventHandler worker, object argument)
 {
     if (this.log.IsInfoEnabled)
     {
         this.log.Info(string.Format(
                      CultureInfo.InvariantCulture,
                      "{0} executes asynchronous operation {1}.{2}({3})",
                      asyncWorker,
                      worker.Method.DeclaringType.FullName,
                      worker.Method.Name,
                      argument));
     }
 }
Exemple #17
0
        public bool apply()
        {
            bool isApplySuccess = false;

            // soft ap config
            string str_ssid       = tbSSID.Text;
            string str_pwd        = tbPWD.Text;
            bool   isEnableSoftAp = (chkbtn_wifi_enable.IsChecked == true);

            if (is_InputVailible())
            {
                SoftApRecord m_rec  = new SoftApRecord(((MainWindow)App.Current.MainWindow).statusPanelPage.m_selectedPrinter, str_ssid, str_pwd, isEnableSoftAp);
                AsyncWorker  worker = new AsyncWorker(Application.Current.MainWindow);

                if (worker.InvokeMethod <SoftApRecord>(((MainWindow)App.Current.MainWindow).statusPanelPage.m_selectedPrinter, ref m_rec, DllMethodType.SetSoftAp, this))
                {
                    if (null != m_rec && m_rec.CmdResult == EnumCmdResult._ACK)
                    {
                        softAPSettingInit.m_ssid          = softAPSetting.m_ssid = str_ssid;
                        softAPSettingInit.m_pwd           = softAPSetting.m_pwd = str_pwd;
                        softAPSettingInit.m_bEnableSoftAp = softAPSetting.m_bEnableSoftAp = isEnableSoftAp;
                        isApplySuccess = true;
                    }
                }

                //if (null != event_config_dirty)
                //    event_config_dirty(is_dirty());
            }
            else
            {
                if (str_ssid.Length <= 0)
                {
                    VOP.Controls.MessageBoxEx.Show(VOP.Controls.MessageBoxExStyle.Simple, Application.Current.MainWindow, (string)this.FindResource("ResStr_Msg_10"), (string)this.FindResource("ResStr_Warning"));
                }
                else if (str_pwd.Length < 8 || str_pwd.Length >= 64)
                {
                    VOP.Controls.MessageBoxEx.Show(VOP.Controls.MessageBoxExStyle.Simple, Application.Current.MainWindow, (string)this.FindResource("ResStr_Msg_3"), (string)this.FindResource("ResStr_Warning"));
                }
            }

            if (isApplySuccess)
            {
                ((MainWindow)App.Current.MainWindow).statusPanelPage.ShowMessage((string)this.FindResource("ResStr_Msg_1"), Brushes.Black);
            }
            else
            {
                ((MainWindow)App.Current.MainWindow).statusPanelPage.ShowMessage((string)this.FindResource("ResStr_Setting_Fail"), Brushes.Red);
            }

            return(isApplySuccess);
        }
Exemple #18
0
        public bool apply()
        {
            bool isApplySuccess = false;

            string strPWD   = pbnewPWD.Password;
            string strCfPWD = pbConfirmPWD.Password;

            if (strPWD.Length > 0 && strPWD == strCfPWD)
            {
                if (strPWD.Length > 0)
                {
                    string         strPrinterName = ((MainWindow)App.Current.MainWindow).statusPanelPage.m_selectedPrinter;
                    PasswordRecord m_rec          = new PasswordRecord(strPrinterName, strPWD);
                    AsyncWorker    worker         = new AsyncWorker(Application.Current.MainWindow);

                    if (worker.InvokeMethod <PasswordRecord>(strPrinterName, ref m_rec, DllMethodType.SetPassword, this))
                    {
                        if (null != m_rec && m_rec.CmdResult == EnumCmdResult._ACK)
                        {
                            ((MainWindow)App.Current.MainWindow).m_strPassword = strCfPWD;
                            isApplySuccess = true;
                        }
                    }
                }

                if (isApplySuccess)
                {
                    ((MainWindow)App.Current.MainWindow).statusPanelPage.ShowMessage((string)this.FindResource("ResStr_Setting_Successfully_"), Brushes.Black);
                }
                else
                {
                    ((MainWindow)App.Current.MainWindow).statusPanelPage.ShowMessage((string)this.FindResource("ResStr_Setting_Fail"), Brushes.Red);
                }
            }
            else
            {
                if (strPWD.Length == 0)
                {
                    pbnewPWD.Focus();
                    VOP.Controls.MessageBoxEx.Show(VOP.Controls.MessageBoxExStyle.Simple, Application.Current.MainWindow, (string)this.FindResource("ResStr_The_new_password_can_not_be_empty_"), (string)this.FindResource("ResStr_Error"));
                }
                else if (strPWD != strCfPWD)
                {
                    pbnewPWD.Focus();
                    pbnewPWD.SelectAll();
                    VOP.Controls.MessageBoxEx.Show(VOP.Controls.MessageBoxExStyle.Simple, Application.Current.MainWindow, (string)this.FindResource("ResStr_The_passwords_you_entered__are_different__please_try_again_"), (string)this.FindResource("ResStr_Error"));
                }
            }

            return(isApplySuccess);
        }
        private void OnLoadedIPV6View(object sender, RoutedEventArgs e)
        {
            InitFontSize();

            AsyncWorker worker = new AsyncWorker(this);

            worker.InvokeMethod <IPV6InfoRecord>(((MainWindow)App.Current.MainWindow).statusPanelPage.m_selectedPrinter, ref m_rec, DllMethodType.GetIpv6Info, this);

            if (null != m_rec)
            {
                if (1 == m_rec.DHCPv6)
                {
                    btnDHCP.IsChecked = true;
                }
                else
                {
                    btnDHCP.IsChecked = false;
                }

                if (1 == m_rec.UseManualAddress)
                {
                    btnManual.IsChecked = true;
                }
                else
                {
                    btnManual.IsChecked = false;
                }

                if (1 == m_rec.UseManualAddress)
                {
                    tb_ip.Text         = m_rec.IPManualAddress;
                    tb_PreSubMask.Text = String.Format("{0}", m_rec.ManualMask);
                }
                else
                {
                    tb_ip.Text         = "::";
                    tb_PreSubMask.Text = String.Format("{0}", 1);
                }

                if (1 == m_rec.UseManualAddress)
                {
                    tb_Gateway.Text = m_rec.IPv6ManualGatewayAddress;
                    //  tb_GatewayPreSubMask.Text = String.Format("{0}", m_rec.ManualGatewayAddressMask);
                }
                else
                {
                    tb_Gateway.Text = "::";
                    //  tb_GatewayPreSubMask.Text = String.Format("{0}", 0);
                }
            }
        }
Exemple #20
0
        public override void SetUp()
        {
            base.SetUp();

            AsyncWorker worker = new AsyncWorker();

            worker.QueueUserWorkItem = delegate(WaitCallback function)
            {
                function(null);
                return(true);
            };
            tracker = new TrailTracker(persister);
            tracker.Start();
        }
Exemple #21
0
        public ConsumingMessageService(Consumer consumer)
        {
            _consumer        = consumer;
            _logger          = ObjectContainer.Resolve <ILoggerFactory>().Create(GetType().FullName);
            _scheduleService = ObjectContainer.Resolve <IScheduleService>();

            if (_isSequentialConsume)
            {
                _consumeWaitingQueue  = new BlockingCollection <ConsumeResult <Ignore, string> >();
                _consumeMessageWorker = new AsyncWorker("ConsumeMessage", async() => await HandleMessageAsync(_consumeWaitingQueue.Take()));
            }
            _consumingQueues = new ConcurrentDictionary <string, TopicPartitionProcessQueue <Ignore, string> >();
            _retryQueue      = new BlockingCollection <ConsumeResult <Ignore, string> >();
        }
Exemple #22
0
        void analog_AnalogChanged(object sender, AnalogChangeEventArgs e)
        {
            {
                double v = Convert.ToDouble(e.Channels[0]);
                result.Enqueue(v);

                if (result.Count > 22)
                {
                    AsyncWorker.ReportProgress(-1, null);

                    result.Dequeue();
                }
            }
        }
 /// <summary>
 /// Called when an operation was completed.
 /// </summary>
 /// <param name="asyncWorker">The async worker.</param>
 /// <param name="worker">The worker.</param>
 /// <param name="completed">The completed handler.</param>
 /// <param name="runWorkerCompletedEventArgs">The <see cref="System.ComponentModel.RunWorkerCompletedEventArgs"/> instance containing the event data.</param>
 public void CompletedExecution(AsyncWorker asyncWorker, DoWorkEventHandler worker, RunWorkerCompletedEventHandler completed, RunWorkerCompletedEventArgs runWorkerCompletedEventArgs)
 {
     if (this.log.IsDebugEnabled)
     {
         if (runWorkerCompletedEventArgs.Error == null)
         {
             this.LogOperationCompletedWithoutException(asyncWorker, worker);
         }
         else
         {
             this.LogOperationCompletedWithException(asyncWorker, worker, runWorkerCompletedEventArgs.Error);
         }
     }
 }
Exemple #24
0
        static void Main(string[] args)
        {
            Console.WriteLine("App start!");

            IEnumerable <string> m_oEnum = new List <string>()
            {
                "1", "2", "3"
            };

            AsyncWorker.LoopAsync(m_oEnum);

            Console.WriteLine("App completed!");

            Console.Read();
        }
    /// <summary>
    /// Checks if specified process is currently running.
    /// </summary>
    /// <param name="process">Async process to check its status</param>
    private bool ProcessIsRunning(AsyncWorker process)
    {
        switch (process.Status)
        {
        // Process not running statuses
        case AsyncWorkerStatusEnum.Unknown:
        case AsyncWorkerStatusEnum.Stopped:
        case AsyncWorkerStatusEnum.Finished:
        case AsyncWorkerStatusEnum.Error:
            return(false);

        default:
            return(true);
        }
    }
        public ElasticsearchSourceViewModel(IElasticsearchSourceModel elasticsearchSourceModel, IEventAggregator aggregator, IElasticsearchSourceDefinition elasticsearchServiceSource, IAsyncWorker asyncWorker, IExternalProcessExecutor executor, IServer currentEnvironment)
            : this(elasticsearchSourceModel, aggregator, asyncWorker, executor, currentEnvironment)
        {
            VerifyArgument.IsNotNull(nameof(elasticsearchServiceSource), elasticsearchServiceSource);

            AsyncWorker.Start(() => elasticsearchSourceModel.FetchSource(elasticsearchServiceSource.Id), source =>
            {
                _elasticsearchServiceSource      = source;
                _elasticsearchServiceSource.Path = elasticsearchServiceSource.Path;

                FromModel(_elasticsearchServiceSource);
                Item = ToSource();
                SetupHeaderTextFromExisting();
            });
        }
        public ManageWebserviceSourceViewModel(IManageWebServiceSourceModel updateManager, IEventAggregator aggregator, IWebServiceSource webServiceSource, IAsyncWorker asyncWorker, IExternalProcessExecutor executor)
            : this(updateManager, aggregator, asyncWorker, executor)
        {
            VerifyArgument.IsNotNull("webServiceSource", webServiceSource);
            _warewolfserverName = updateManager.ServerName;
            AsyncWorker.Start(() => updateManager.FetchSource(webServiceSource.Id), source =>
            {
                _webServiceSource      = source;
                _webServiceSource.Path = webServiceSource.Path;

                FromModel(_webServiceSource);
                Item = ToSource();
                SetupHeaderTextFromExisting();
            });
        }
        public RedisSourceViewModel(IRedisSourceModel redisSourceModel, IEventAggregator aggregator, IRedisServiceSource redisServiceSource, IAsyncWorker asyncWorker, IExternalProcessExecutor executor)
            : this(redisSourceModel, aggregator, asyncWorker, executor)
        {
            VerifyArgument.IsNotNull(nameof(redisServiceSource), redisServiceSource);
            _warewolfserverName = redisSourceModel.ServerName;
            AsyncWorker.Start(() => redisSourceModel.FetchSource(redisServiceSource.Id), source =>
            {
                _redisServiceSource      = source;
                _redisServiceSource.Path = redisServiceSource.Path;

                FromModel(_redisServiceSource);
                Item = ToSource();
                SetupHeaderTextFromExisting();
            });
        }
Exemple #29
0
        private void backgroundEntryWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            BeginInvoke(new MethodInvoker(delegate
            {
                progressBar.Visible   = true;
                progressBar.Value     = 5;
                pageIndex             = 0;
                button_search.Enabled = false;
            }));

            animeEntries = GetAnimes();
            pages        = (int)Math.Ceiling(animeEntries.Count() * 1.0 / entriesPerPage);
            AsyncWorker.ReportProgress(10);

            LoadPage.RunWorkerAsync();
        }
        public override void SetUp()
        {
            base.SetUp();

            var definitions = TestSupport.SetupDefinitions(typeof(PersistableItem), typeof(PersistableItem2), typeof(PersistablePart));

            accessor     = new LuceneAccesor(new ThreadContext(), new DatabaseSection());
            indexer      = new ContentIndexer(new LuceneIndexer(accessor), new TextExtractor(new IndexableDefinitionExtractor(definitions)));
            searcher     = new LuceneContentSearcher(accessor, persister);
            worker       = new AsyncWorker();
            asyncIndexer = new AsyncIndexer(indexer, persister, worker, Rhino.Mocks.MockRepository.GenerateStub <IErrorNotifier>(), new DatabaseSection());
            tracker      = new ContentChangeTracker(asyncIndexer, persister, new N2.Plugin.ConnectionMonitor(), new DatabaseSection());

            accessor.LockTimeout = 1L;
            indexer.Clear();
            root = CreateOneItem <PersistableItem>(1, "The Root Page", null);
        }
        /// <summary>
        /// Starts this EnityPoller.
        /// </summary>
        /// <exception cref="System.InvalidOperationException">Already polling</exception>
        public void Start()
        {
            var worker      = new AsyncWorker(Poll);
            var completed   = new AsyncCallback(PollComplete);
            var onCompleted = new AsyncComplete(OnEntity);

            lock (_sync)
            {
                if (_polling)
                {
                    throw new InvalidOperationException("Already polling");
                }

                var operation = AsyncOperationManager.CreateOperation(onCompleted);
                worker.BeginInvoke(completed, operation);
                _polling = true;
            }
        }
 void GetLoadComputerNamesTask(Action additionalUiAction)
 {
     AsyncWorker.Start(() => _updateManager.GetComputerNames().Select(name => new ComputerName {
         Name = name
     }).ToList(), names =>
     {
         ComputerNames = names;
         additionalUiAction?.Invoke();
     }, exception =>
     {
         FailedTesting();
         if (exception.InnerException != null)
         {
             exception = exception.InnerException;
         }
         TestMessage = exception.Message;
     });
 }
Exemple #33
0
        static void Main(string[] args)
        {

            intList = Enumerable.Range(0, N);
            int[] arr = new int[N];
            Console.WriteLine("Starting with {0} items", N);
            Stopwatch sw = new Stopwatch();
            sw.Start();

            AsyncWorker<int> worker = new AsyncWorker<int>(Method2, arr, TC);

            worker.Wait();
            sw.Stop();
            Console.WriteLine("Worker finished in {0}s", sw.Elapsed.TotalSeconds);
            Console.ReadLine();


        }
 void TestConnection()
 {
     _token = new CancellationTokenSource();
     AsyncWorker.Start(SetupProgressSpinner, () =>
     {
         TestMessage = "Passed";
         TestFailed  = false;
         TestPassed  = true;
         Testing     = false;
     },
                       _token, exception =>
     {
         TestFailed  = true;
         TestPassed  = false;
         Testing     = false;
         TestMessage = GetExceptionMessage(exception);
     });
 }
        private void OnLoadedIPV6View(object sender, RoutedEventArgs e)
        {
            InitFontSize();

            AsyncWorker worker = new AsyncWorker(this);

            worker.InvokeMethod <IPV6InfoRecord>(((MainWindow)App.Current.MainWindow).statusPanelPage.m_selectedPrinter, ref m_rec, DllMethodType.GetIpv6Info, this);

            if (null != m_rec)
            {
                tbStatelessAddress1.Text           = m_rec.StatelessAddress1;
                tbStatelessAddress2.Text           = m_rec.StatelessAddress2;
                tbStatelessAddress3.Text           = m_rec.StatelessAddress3;
                tbAutoStatefullAddress.Text        = m_rec.AutoStatefulAddress;
                tbLinkLocalAddress.Text            = m_rec.IPLinkLocalAddress;
                tbAutoConfigureGatewayAddress.Text = m_rec.AutoGatewayAddress;
            }
        }
 protected DatabaseSourceViewModelBase(IManageDatabaseSourceModel updateManager, IEventAggregator aggregator, IDbSource dbSource, IAsyncWorker asyncWorker, string dbSourceImage)
     : this(asyncWorker, dbSourceImage)
 {
     VerifyArgument.IsNotNull("dbSource", dbSource);
     PerformInitialise(updateManager, aggregator);
     _warewolfserverName = updateManager.ServerName ?? "";
     AsyncWorker.Start(() => updateManager.FetchDbSource(dbSource.Id), source =>
     {
         DbSource      = source;
         DbSource.Path = dbSource.Path;
         Item          = ToSourceDefinition();
         GetLoadComputerNamesTask(() =>
         {
             FromModel(DbSource);
             SetupHeaderTextFromExisting();
         });
     });
 }
        public void FindRoleList()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Role Name");
            dt.Columns.Add("Description");
            dt.Columns.Add("Status");
            this.ug_rolelist.DataSource = dt;
            this.lbl_rolecount.Text = this.ug_rolelist.Rows.Count.ToString();
            this.ug_rolelist.Focus();

            var argus = new object[] { this.txt_rolename.Text, this.txt_description.Text };
            using (AsyncWorker<IRoleMaintenance> worker = new AsyncWorker<IRoleMaintenance>(_presenter, this.ug_rolelist, new Control[] { btn_search, btn_reset }))
            {
                worker.DoWork += delegate(object oDoWork, DoWorkEventArgs eDoWork)
                {
                    var tempArgus = eDoWork.Argument as object[];
                    if (tempArgus == null || tempArgus.Length <= 1)
                    {
                        return;
                    }
                    eDoWork.Result = _presenter.FindRoleListByConditions(tempArgus[0] as string,tempArgus[1] as string);
                };
                worker.RunWorkerCompleted += delegate(object oCompleted, RunWorkerCompletedEventArgs eCompleted)
                {
                    RoleEntity[] roleEntitys = eCompleted.Result as RoleEntity[];
                    if (roleEntitys != null)
                    {
                        if (roleEntitys.Length > 0)
                        {
                            foreach (RoleEntity entity in roleEntitys)
                            {
                                dt.Rows.Add(entity.RoleName, entity.Description, entity.Status);
                            }
                        }
                        this.ug_rolelist.DataSource = dt;
                        this.lbl_rolecount.Text = this.ug_rolelist.Rows.Count.ToString();
                    }
                };
                worker.Run(argus);
            }
        }
    private void wzdExport_NextButtonClick(object sender, WizardNavigationEventArgs e)
    {
        switch (e.CurrentStepIndex)
        {
            case 0:
                // Apply settings
                if (!configExport.ApplySettings())
                {
                    e.Cancel = true;
                    return;
                }

                // Update settings
                ExportSettings = configExport.Settings;

                if (!configExport.ExportHistory)
                {
                    ltlScriptAfter.Text = ScriptHelper.GetScript(
                        "var actDiv = document.getElementById('actDiv'); \n" +
                        "if (actDiv != null) { actDiv.style.display='block'; } \n" +
                        "var buttonsDiv = document.getElementById('buttonsDiv'); if (buttonsDiv != null) { buttonsDiv.disabled=true; } \n" +
                        "BTN_Disable('" + NextButton.ClientID + "'); \n" +
                        "StartSelectionTimer();"
                        );

                    // Select objects asynchronously
                    ctrlAsync.RunAsync(SelectObjects, WindowsIdentity.GetCurrent());
                    e.Cancel = true;
                }
                else
                {
                    pnlExport.Settings = ExportSettings;
                    pnlExport.ReloadData();
                }
                break;

            case 1:
                // Apply settings
                if (!pnlExport.ApplySettings())
                {
                    e.Cancel = true;
                    return;
                }
                ExportSettings = pnlExport.Settings;

                // Delete temporary files
                try
                {
                    ExportProvider.DeleteTemporaryFiles(ExportSettings, true);
                }
                catch (Exception ex)
                {
                    lblError.Text = ex.Message;
                    e.Cancel = true;
                    return;
                }

                try
                {
                    // Save export history
                    ExportHistoryInfo history = new ExportHistoryInfo();
                    history.ExportDateTime = DateTime.Now;
                    history.ExportFileName = ExportSettings.TargetFileName;
                    history.ExportSettings = ExportSettings.GetXML();
                    history.ExportSiteID = ExportSettings.SiteId;
                    history.ExportUserID = CMSContext.CurrentUser.UserID;

                    ExportHistoryInfoProvider.SetExportHistoryInfo(history);
                }
                catch (Exception ex)
                {
                    lblError.Text = ex.Message;
                    lblError.ToolTip = EventLogProvider.GetExceptionLogMessage(ex);
                    e.Cancel = true;
                    return;
                }

                // Init the Mimetype helper (required for the export)
                MimeTypeHelper.LoadMimeTypes();

                if (ExportSettings.SiteId > 0)
                {
                    ExportSettings.EventLogSource = string.Format(ExportSettings.GetAPIString("ExportSite.EventLogSiteSource", "Export '{0}' site"), ResHelper.LocalizeString(ExportSettings.SiteInfo.DisplayName));
                }

                // Start asynchronnous export
                ExportManager.Settings = ExportSettings;

                AsyncWorker worker = new AsyncWorker();
                worker.OnFinished += worker_OnFinished;
                worker.OnError += worker_OnError;
                worker.RunAsync(ExportManager.Export, WindowsIdentity.GetCurrent());

                lblProgress.Text = GetString("SiteExport.PreparingExport");
                break;
        }

        ReloadSteps();
        wzdExport.ActiveStepIndex = e.NextStepIndex;
    }
        private SerialPort _serialPort; // The serial port

        #endregion Fields

        #region Constructors

        public SerialTransport()
        {
            _worker = new AsyncWorker(Poll, "SerialTransport");
        }
        public void ShowSessionList(SessionCriteria sessionCriteria)
        {
            this.ug_sessionlist.Focus();

            using (AsyncWorker<ISessionManagementView> worker = new AsyncWorker<ISessionManagementView>(_presenter, this.ug_sessionlist, new Control[] { refreshButton }))
            {
                worker.DoWork += delegate(object oDoWork, DoWorkEventArgs eDoWork)
                {
                    eDoWork.Result = _presenter.GetActiveSessions(sessionCriteria);
                };
                worker.RunWorkerCompleted += delegate(object oCompleted, RunWorkerCompletedEventArgs eCompleted)
                {
                    SessionInfo[] sessions = eCompleted.Result as SessionInfo[];
                    if (sessions == null)
                    {
                        return;
                    }
                    this._sessionList.Clear();
                    foreach (SessionInfo sessionInfo in sessions)
                    {
                        this._sessionList.Add(sessionInfo.SessionID, sessionInfo);
                    }

                    this.ug_sessionlist.DataSource = sessions;
                    this.ug_sessionlist.DataBind();
                    this.lbl_totalsessionnumber.Text = this.ug_sessionlist.Rows.Count.ToString();
                };
                worker.Run();
            }
        }
 private void LogOperationCompletedWithException(AsyncWorker asyncWorker, DoWorkEventHandler worker, Exception exception)
 {
     this.log.Info(string.Format(
         CultureInfo.InvariantCulture,
         "{0} completes asynchronous operation {1}.{2}() with exception = {3}",
         asyncWorker,
         worker.Method.DeclaringType.FullName,
         worker.Method.Name,
         exception));
 }
    /// <summary>
    /// Starts import process with given settings. Returns true if import was started successfully, false otherwise (error label is set in this case).
    /// </summary>
    /// <param name="importSettings">Import settings</param>
    /// <returns>Returns true if import was started successfully, false otherwise.</returns>
    private bool StartImport(SiteImportSettings importSettings)
    {
        // Check licences
        string error = ImportExportControl.CheckLicenses(importSettings);
        if (!string.IsNullOrEmpty(error))
        {
            SetErrorLabel(error);

            return false;
        }

        // Init the Mimetype helper (required for the Import)
        MimeTypeHelper.LoadMimeTypes();

        // Start asynchronnous Import
        if (importSettings.SiteIsIncluded)
        {
            importSettings.EventLogSource = string.Format(importSettings.GetAPIString("ImportSite.EventLogSiteSource", "Import '{0}' site"), ResHelper.LocalizeString(importSettings.SiteDisplayName));
        }
        ImportManager.Settings = importSettings;

        AsyncWorker worker = new AsyncWorker();
        worker.OnFinished += worker_OnFinished;
        worker.OnError += worker_OnError;
        worker.RunAsync(ImportManager.Import, WindowsIdentity.GetCurrent());

        return true;
    }
    protected void wzdImport_NextButtonClick(object sender, WizardNavigationEventArgs e)
    {
        switch (e.CurrentStepIndex)
        {
            case 0:
                // Apply settings
                if (!stpConfigImport.ApplySettings())
                {
                    e.Cancel = true;
                    return;
                }

                // Update settings
                ImportSettings = stpConfigImport.Settings;

                ltlScriptAfter.Text = ScriptHelper.GetScript(
                    "var actDiv = document.getElementById('actDiv'); \n" +
                    "if (actDiv != null) { actDiv.style.display='block'; } \n" +
                    "var buttonsDiv = document.getElementById('buttonsDiv'); if (buttonsDiv != null) { buttonsDiv.disabled=true; } \n" +
                    "BTN_Disable('" + NextButton.ClientID + "'); \n" +
                    "StartUnzipTimer();"
                    );

                // Create temporary files asynchronously
                ctrlAsync.RunAsync(CreateTemporaryFiles, WindowsIdentity.GetCurrent());

                e.Cancel = true;
                break;

            case 1:
                // Apply settings
                if (!stpSiteDetails.ApplySettings())
                {
                    e.Cancel = true;
                    return;
                }

                // Update settings
                ImportSettings = stpSiteDetails.Settings;
                //stpImport.SelectedNodeValue = CMSObjectHelper.GROUP_OBJECTS;
                stpImport.ReloadData(true);

                wzdImport.ActiveStepIndex++;
                break;

            case 2:
                // Apply settings
                if (!stpImport.ApplySettings())
                {
                    e.Cancel = true;
                    return;
                }

                // Check licences
                string error = ImportExportControl.CheckLicenses(ImportSettings);
                if (!string.IsNullOrEmpty(error))
                {
                    SetErrorLabel(error);

                    e.Cancel = true;
                    return;
                }

                ImportSettings = stpImport.Settings;

                // Init the Mimetype helper (required for the Import)
                MimeTypeHelper.LoadMimeTypes();

                // Start asynchronnous Import
                ImportSettings.DefaultProcessObjectType = ProcessObjectEnum.Selected;
                if (ImportSettings.SiteIsIncluded)
                {
                    ImportSettings.EventLogSource = string.Format(ImportSettings.GetAPIString("ImportSite.EventLogSiteSource", "Import '{0}' site"), ResHelper.LocalizeString(ImportSettings.SiteDisplayName));
                }
                ImportManager.Settings = ImportSettings;

                AsyncWorker worker = new AsyncWorker();
                worker.OnFinished += worker_OnFinished;
                worker.OnError += worker_OnError;
                worker.RunAsync(ImportManager.Import, WindowsIdentity.GetCurrent());

                wzdImport.ActiveStepIndex++;
                break;
        }

        ReloadSteps();
    }
Exemple #44
0
 protected CommandQueue()
 {
     _worker = new AsyncWorker(ProcessQueue);
     _worker.Name = "CommandQueue";
 }
        private void LoadOrganisationList()
        {
            this.ultraGridOrganisational.Focus();

            var argus = txt_Orgenisation.Text ;
             using (AsyncWorker<IMaintainOrganisationName> worker = new AsyncWorker<IMaintainOrganisationName>(_presenter, this.ultraGridOrganisational, new Control[] { ultraBtnSearch, ultraBtnReset }))
             {
                 worker.DoWork += delegate(object oDoWork, DoWorkEventArgs eDoWork)
                 {
                     var lookup = _presenter.GetOrganisationLookup();

                     var tempArgu = eDoWork.Argument as string;
                     eDoWork.Result = RetriveOrgData(lookup,
                         tempArgu);
                 };
                 worker.RunWorkerCompleted += delegate(object oCompleted, RunWorkerCompletedEventArgs eCompleted)
                 {

                     this.ultraGridOrganisational.DataSource = eCompleted.Result;
                     ultraLabTotalNum.Text = HiiP.Framework.Messaging.Messages.General.GEI001.Format(this.ultraGridOrganisational.Rows.Count.ToString());

                 };
                 worker.Run(argus);

             }
        }
Exemple #46
0
        private void ButtonSearchForCount_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                DisableValidationProvider();
                this.validationProvider7.Enabled = true;
                if (this.ValidateChildren())
                {
                    DateTimeCompare timeEntity = new DateTimeCompare(
                        DateTimeStartDateForCount.DateTime.Date, DateTimeEndDateForCount.DateTime.Date);

                    using (AsyncWorker<IUsageLogView> worker = new AsyncWorker<IUsageLogView>(_presenter, this.ultraChart7, new Control[] { ButtonSearchForCount }))
                    {
                        #region worker defini
                        worker.DoWork += delegate(object oDoWork, DoWorkEventArgs eDoWork)
                        {
                            var tempEntity = eDoWork.Argument as DateTimeCompare;
                            if (tempEntity == null)
                            {
                                return;
                            }
                            eDoWork.Result = _presenter.GetAllCountOfUsers(tempEntity);
                        };
                        worker.RunWorkerCompleted += delegate(object oCompleted, RunWorkerCompletedEventArgs eCompleted)
                        {
                            LoggingUsageDataSet dataset = eCompleted.Result as LoggingUsageDataSet;
                            if (dataset != null && dataset.T_IC_LOGGING_USAGE.Rows.Count > 0)
                            {
                                int rowCount = dataset.T_IC_LOGGING_USAGE.Rows.Count - 1;
                                this.ultraChart7.Height = CHART_BASE_HEIGHT + rowCount * INCREMENT_FEED;
                                this.usageByUserCountExpandableGroupBox.Height = EXPANDABLE_GROUP_BOX_BASE_HEIGHT + rowCount * INCREMENT_FEED;
                                SetChartStype(this.ultraChart7, "USER_COUNT", dataset);
                                this.ultraChart7.DataSource = dataset.T_IC_LOGGING_USAGE.Select(
                                    data => new
                                    {
                                        emptyname = String.Empty,
                                        usercount = Convert.ToInt32(data["USER_COUNT"])
                                    }
                                    ).ToList();
                                this.ultraChart7.Visible = true;
                            }
                            else
                            {
                                this.ultraChart7.Visible = false;
                                this.usageByUserCountExpandableGroupBox.Height = EXPANDABLE_GROUP_BOX_BASE_HEIGHT - CHART_BASE_HEIGHT;
                            }
                        };
                        #endregion
                        worker.Run(timeEntity);
                    }
                }
            }
            catch (Exception ex)
            {
                if (ExceptionManager.Handle(ex))
                {
                    throw;
                }
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }
Exemple #47
0
        private void ButtonSearchForUser_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                DisableValidationProvider();
                this.validationProvider1.Enabled = true;
                if (this.ValidateChildren())
                {
                    DateTimeCompare timeEntity = new DateTimeCompare(DateTimeStartDateForUser.DateTime.Date,
                        DateTimeEndDateForUser.DateTime.Date);
                    var argus = new object[] {timeEntity, TextBoxUserName.Text};

                    using (AsyncWorker<IUsageLogView> worker = new AsyncWorker<IUsageLogView>(_presenter, this.ultraChart1, new Control[] { ButtonSearchForUser }))
                    {
                        #region worker definition
                        worker.DoWork += delegate(object oDoWork, DoWorkEventArgs eDoWork)
                        {
                            var tempArgus = eDoWork.Argument as object[];

                            if (tempArgus==null || tempArgus.Length<=1)
                            {
                                return;
                            }
                            eDoWork.Result = _presenter.GetUsageForUserData(
                                tempArgus[0] as DateTimeCompare,tempArgus[1] as string );
                        };
                        worker.RunWorkerCompleted += delegate(object oCompleted, RunWorkerCompletedEventArgs eCompleted)
                        {
                            LoggingUsageDataSet dataset = eCompleted.Result as LoggingUsageDataSet;
                            if (dataset != null && dataset.T_IC_LOGGING_USAGE.Rows.Count > 0)
                            {
                                int rowCount = dataset.T_IC_LOGGING_USAGE.Rows.Count - 1;
                                this.ultraChart1.Height = CHART_BASE_HEIGHT + rowCount * INCREMENT_FEED;
                                this.usageByUserExpandableGroupBox.Height = EXPANDABLE_GROUP_BOX_BASE_HEIGHT + rowCount * INCREMENT_FEED;
                                SetChartStype(this.ultraChart1, "FREQUENCY", dataset);
                                this.ultraChart1.DataSource = dataset.T_IC_LOGGING_USAGE.Select(
                                    data => new
                                    {
                                        username = data["USER_NAME"].ToString(),
                                        logintimes = Convert.ToInt32(data["FREQUENCY"])
                                    }
                                    ).ToList();
                                this.ultraChart1.Visible = true;
                            }
                            else
                            {
                                this.ultraChart1.Visible = false;
                                this.usageByUserExpandableGroupBox.Height = EXPANDABLE_GROUP_BOX_BASE_HEIGHT - CHART_BASE_HEIGHT;
                            }
                        };
                        #endregion
                        worker.Run(argus);
                    }
                }
            }
            catch (Exception ex)
            {
                if (ExceptionManager.Handle(ex)) throw;
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }
        public void Test()
        {
            Parallel.For(0, 100, i =>
            {
                DateTime dt = SysTimeRecord.Get(i.ToString());
                SysTimeRecord.Set(i.ToString(), dt == DateTime.MinValue ? DateTime.Now.AddDays(-i) : dt.AddHours(1));
            });

            for (int i = 0; i < 100; i++)
            {
                DateTime dt = SysTimeRecord.Get(i.ToString());
                SysTimeRecord.Set(i.ToString(), dt == DateTime.MinValue ? DateTime.Now.AddDays(i) : dt.AddHours(-1));
            }
            RedisTest.Test();


            AsyncWorker<int> aw = new AsyncWorker<int>(3, Console.WriteLine);
            for (int i = 0; i < 100; i++)
            {
                aw.AddItem(i);
            }
            aw.StopAndWait();


            Thread.Sleep(10000000);

            Parallel.Invoke(
                () => ExecCrawler(1),
                () => ExecCrawler(2),
                () => ExecCrawler(3),
                () => ExecCrawler(4),
                () => ExecCrawler(5)
                );



            HttpCore hc = new HttpCore();
            hc.SetUrl("http://ac168.info/bt/thread.php?fid=16&page={0}", 2);
            var res = hc.GetHtml();
            var tres = res.SelectNodes("//*[@id='ajaxtable']/tbody[1]/tr[@class='tr3 t_one']");

            HtmlNode node = tres[10];
            var an = node.SelectSingleNode("/td[2]/h3/a");

            string aHref = "http://ac168.info/bt/" + an.Attributes["href"].Value;
            string aText = an.InnerHtml;


            hc.SetUrl(aHref);
            res = hc.GetHtml();
            tres = res.SelectNodes("//*[@id='read_tpc']/img");

            string imgUrl = tres[0].Attributes["src"].Value;

            HttpCore hcImg = new HttpCore();
            hcImg.SetUrl(imgUrl);
            hcImg.CurrentHttpItem.ResultType = ResultType.Byte;
            //得到HTML代码
            HttpResult result = hcImg.CurrentHttpHelper.GetHtml(hcImg.CurrentHttpItem);
            if (result.StatusCode == System.Net.HttpStatusCode.OK)
            {
                //表示访问成功,具体的大家就参考HttpStatusCode类
            }
            //表示StatusCode的文字说明与描述
            string statusCodeDescription = result.StatusDescription;
            //把得到的Byte转成图片
            Image img = result.ResultByte.ByteArrayToImage();
            img.Save("f://imgs/" + imgUrl.Split('/').Last());
            Console.WriteLine(tres);
            Console.ReadLine();
            RequestBase rb = new RequestBase();
            rb.BindLocalCache("intc", s => GetSourceCacheInt(s[0].TryChangeType(0)), 3);
            rb.BindLocalCache("person", s => GetSourceCachePerson(), null);

            Stopwatch st0 = new Stopwatch();
            st0.Start();
            rb.BindLocalCache("ps", s => GetSourceCacheListPerson(), null);
            st0.Stop();
            Console.WriteLine("实例化1千万个对象,耗时【{0}】毫秒", st0.ElapsedMilliseconds);

            Stopwatch st1 = new Stopwatch();
            st1.Start();
            for (int i = 0; i < 10000000; i++)
            {
                rb.BindLocalCache("ps", s => GetSourceCacheListPerson(), null);
            }
            st1.Stop();
            Console.WriteLine("绑定1千万次本地缓存,耗时【{0}】毫秒", st1.ElapsedMilliseconds);

            var t1 = rb.GetLocalCache("intc");
            var t2 = rb.GetLocalCache("person");
            var t3 = rb.GetLocalCache<Person>("person");
            var t4 = rb.LocalCache.person;
            var t5 = rb.LocalCache.intc;

            Stopwatch st = new Stopwatch();
            st.Start();
            for (int i = 0; i < 10000000; i++)
            {
                var t = rb.LocalCache.ps;
                var tt = rb.GetLocalCache<List<Person>>("ps");
            }
            st.Stop();
            Console.WriteLine("读取2千万次本地缓存,耗时【{0}】毫秒", st.ElapsedMilliseconds);
        }
    /// <summary>
    /// Checks if specified process is currently running.
    /// </summary>
    /// <param name="process">Async process to check its status</param>
    private bool ProcessIsRunning(AsyncWorker process)
    {
        switch (process.Status)
        {
            // Process not running statuses
            case AsyncWorkerStatusEnum.Unknown:
            case AsyncWorkerStatusEnum.Stopped:
            case AsyncWorkerStatusEnum.Finished:
            case AsyncWorkerStatusEnum.Error:
                return false;

            default:
                return true;
        }
    }
        public void ShowUserList()
        {
            this.btn_disable.Enabled = false;
            this.btn_assignroles.Enabled = false;

            DataTable dt = new DataTable();
            dt.Columns.Add("User ID", Type.GetType("System.String"));
            dt.Columns.Add("Status", Type.GetType("System.String"));
            dt.Columns.Add("Created On", Type.GetType("System.DateTime"));
            dt.Columns.Add("User Name", Type.GetType("System.String"));
            dt.Columns.Add("Gender", Type.GetType("System.String"));
            dt.Columns.Add("Title", Type.GetType("System.String"));
            dt.Columns.Add("Email", Type.GetType("System.String"));
            dt.Columns.Add("Telephone No", Type.GetType("System.String"));
            //dt.Columns.Add("Organisation", Type.GetType("System.String"));
            dt.Columns.Add("Master Office", Type.GetType("System.String"));
            dt.Columns.Add("Office", Type.GetType("System.String"));
            dt.Columns.Add("AllOffices", Type.GetType("System.String"));
            dt.Columns.Add("First Name", Type.GetType("System.String"));
            dt.Columns.Add("Last Name", Type.GetType("System.String"));
            dt.Columns.Add("Mobile", Type.GetType("System.String"));
            this.ug_userlist.DataSource = dt;
            this.ug_userlist.Focus();
            this.lbl_recordCount.Text = "0";

            var criteria = GetSearchCriteria();
            using (AsyncWorker<IUserMaintenance> worker = new AsyncWorker<IUserMaintenance>(_presenter, this.ug_userlist, new Control[] { btn_search }))
            {
                worker.DoWork += delegate(object oDoWork, DoWorkEventArgs eDoWork)
                {
                    var tempCriteria = eDoWork.Argument as UserInfoSearchCriteria;
                    if (tempCriteria == null)
                    {
                        return;
                    }
                    eDoWork.Result = _presenter.GetUserInfoArrayEntity(tempCriteria);
                };
                worker.RunWorkerCompleted += delegate(object oCompleted, RunWorkerCompletedEventArgs eCompleted)
                {
                    UserInfoEntity[] userInfoEntitys = eCompleted.Result as UserInfoEntity[];
                    if (userInfoEntitys != null && userInfoEntitys.Length > 0)
                    {
                        foreach (UserInfoEntity entity in userInfoEntitys)
                        {
                            dt.Rows.Add(
                                entity.UserName,
                                entity.UserStatus,
                                entity.CreatedOn,
                                entity.Display,
                                entity.Gender,
                                entity.Title,
                                entity.Email,
                                entity.TelephoneNo,
                                //entity.Organisation,
                                entity.IsMaster,
                                entity.Office,
                                entity.AllOffices,
                                entity.FirstName,
                                entity.LastName,
                                entity.MobileNo
                                );
                        }
                    }
                    this.ug_userlist.DataSource = dt;
                    this.lbl_recordCount.Text = this.ug_userlist.Rows.Count.ToString();
                };
                worker.Run(criteria);
            }
        }
    void btnYes_Click(object sender, EventArgs e)
    {
        pnlConfirmation.Visible = false;
        pnlDeleteSite.Visible = true;

        // Start the timer for the callbacks
        ltlScript.Text = ScriptHelper.GetScript("StartStateTimer();");

        // Initilaize web root path
        AttachmentHelper.WebRootFullPath = HttpContext.Current.Server.MapPath("~/");

        // Deletion info initialization
        DeletionInfo.DeleteAttachments = chkDeleteDocumentAttachments.Checked;
        DeletionInfo.DeleteMediaFiles = chkDeleteMediaFiles.Checked;
        DeletionInfo.DeleteMetaFiles = chkDeleteMetaFiles.Checked;
        DeletionInfo.SiteName = siteName;
        DeletionInfo.SiteDisplayName = siteDisplayName;
        DeletionManager.CurrentUser = CMSContext.CurrentUser;
        DeletionManager.DeletionInfo = DeletionInfo;

        AsyncWorker worker = new AsyncWorker();
        worker.RunAsync(DeletionManager.DeleteSite, WindowsIdentity.GetCurrent());
    }
Exemple #52
0
		public ScanResult Execute(object markerAsynchrone)
		{
			_log.Info("======================================= SCAN COMMAND ========================================");
			_log.Info(string.Format("Start execute with scan params: " +
			                        "source={0}, sourceFeed={1}, dpi={2}, colorMode={3}, compressionFormat={4}, format={5}, " +
			                        "isPackage={6}, saveAs={7}", 
				_command.Source, 
				_command.DocumentHandlingCap, 
				_command.DPI,
				_command.ColorMode,
				_command.CompressionFormat.ImgFormat,
				_command.Format.Name,
				_command.IsPackage,
				_command.SaveAs));

			ScanResult scanResult;
			try
			{
				var scannedImages = new List<Image>();
				lock (markerAsynchrone)
				{
					if (_scannerManager.CurrentSourceIndex != _command.Source)
					{
						new AsyncWorker<int>().RunWorkAsync(_command.Source, _scannerManager.ChangeSource,
							WaitTimeForChangeSource);

						if (_scannerManager.CurrentSourceIndex != _command.Source)
						{
							return new SingleScanResult("Не удается изменить источник данных");
						}
					}

					var settingAcquire = new SettingsAcquire
					{
						Format = _command.Format,
						Resolution = _command.DPI,
						PixelType = _command.ColorMode,
						ScanSource =  _command.DocumentHandlingCap
					};

					var images = new AsyncWorker<SettingsAcquire, List<Image>>().RunWorkAsync(settingAcquire, _scannerManager.CurrentSource.Scan, WaitTimaeForScan);

					if (images != null)
					{
						foreach (var image in images)
						{
							var clonedImage = (Image) image.Clone();
							image.Dispose();

							((Bitmap) clonedImage).SetResolution(_command.DPI, _command.DPI);
							scannedImages.Add(clonedImage);
						}

					}
				}
				if (scannedImages.Count == 0)
				{
					return new SingleScanResult(
							"Сканирование завершилось неудачей! Попробуйте переподключить сканер либо повторить сканирование с помощью другого устройства.");
				}
				
				if (scannedImages.Count == 1)
				{
					var image = scannedImages[0];
					var downloadFile = SaveImage(image);
					var singleScanResult = new SingleScanResult();
					singleScanResult.FillContent(downloadFile);

					scanResult = singleScanResult;

					image.Dispose();
				}
				else
				{
					var downloadFiles = new List<DownloadFile>();
					int counter;
					try
					{
						counter = int.Parse(_command.FileCounter);
					}
					catch (Exception)
					{
						counter = 1;
					}
					foreach (var scannedImage in scannedImages)
					{
						var downloadFile = SaveImage(scannedImage, counter++);
						downloadFiles.Add(downloadFile);
						scannedImage.Dispose();
					}
				
					var multipleScanResult = new MultipleScanResult();
					multipleScanResult.FillContent(downloadFiles);
					scanResult = multipleScanResult;
				}
			}
			catch (TwainException ex)
			{
				return new SingleScanResult(ex.Message);
			}

			_log.Info("Scan command executed");
			return scanResult;
		}
        private void ultraBtnSearch_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;

                this.ultraGridDelegation.Focus();
                var criteria = GetDelegationSearchCriteria();
                using (AsyncWorker<IMaintainDelegation> worker = new AsyncWorker<IMaintainDelegation>(_presenter, this.ultraGridDelegation,true))
                {
                    worker.DoWork += delegate(object senderobj, DoWorkEventArgs ev)
                    {
                        var tempCriteria = ev.Argument as DelegationSearchCriteria;
                        if (tempCriteria == null)
                        {
                            return;
                        }
                        ev.Result = _presenter.FindDelegationDetailEntity(tempCriteria);
                    };

                    worker.RunWorkerCompleted += delegate(object senderobj, RunWorkerCompletedEventArgs ev)
                    {
                        List<DelegationValueEntity> lstResults = ev.Result as List<DelegationValueEntity>;
                        ultraGridDelegation.DataSource = lstResults;
                        ultraGridDelegation.DataBind();
                        ultraLabTotalNum.Text = string.Format("Total record(s) : {0}", ultraGridDelegation.Rows.Count.ToString());

                    };
                    worker.Run(criteria);
                }

            }
            catch (Exception ex)
            {
                if (ExceptionManager.Handle(ex)) throw;
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }
        private SerialPort _serialPort; // The serial port

        #endregion Fields

        #region Constructors

        public SerialTransport()
        {
            _worker = new AsyncWorker(Poll);
            _worker.Name = "SerialTransport";
        }
 /// <summary>
 /// Called when an operation was completed.
 /// </summary>
 /// <param name="asyncWorker">The async worker.</param>
 /// <param name="worker">The worker.</param>
 /// <param name="completed">The completed handler.</param>
 /// <param name="runWorkerCompletedEventArgs">The <see cref="System.ComponentModel.RunWorkerCompletedEventArgs"/> instance containing the event data.</param>
 public void CompletedExecution(AsyncWorker asyncWorker, DoWorkEventHandler worker, RunWorkerCompletedEventHandler completed, RunWorkerCompletedEventArgs runWorkerCompletedEventArgs)
 {
     if (this.log.IsInfoEnabled)
     {
         if (runWorkerCompletedEventArgs.Error == null)
         {
             this.LogOperationCompletedWithoutException(asyncWorker, worker);
         }
         else
         {
             this.LogOperationCompletedWithException(asyncWorker, worker, runWorkerCompletedEventArgs.Error);
         }
     }
 }
 protected CommandQueue()
 {
     _worker = new AsyncWorker(ProcessQueue, "CommandQueue");
 }
		private ScannerSettings GetScannerSettings(int sourceIndex)
		{
			_logger.Debug("Searching scanner settings in cache...");
			var searchSetting = _cacheSettings.Search(_scannerManager, sourceIndex);

			if (searchSetting != null)
			{
				_logger.Debug("Scanner settings was found");
				return searchSetting;
			}
			else
			{
				_logger.Debug("Scanner settings was not found");
			}

			var needOfChangeSource = _sourceIndex.HasValue && _sourceIndex != _scannerManager.CurrentSourceIndex;

			if (needOfChangeSource)
				new AsyncWorker<int>().RunWorkAsync(sourceIndex, _scannerManager.ChangeSource, ChangeSourceWaitTime);

			if (_scannerManager.CurrentSource == null)
				throw new Exception("Не удалось выбрать источник");

			if (sourceIndex == _scannerManager.CurrentSource.Index)
				searchSetting = new AsyncWorker<IScannerManager, ScannerSettings>()
					.RunWorkAsync(_scannerManager, _cacheSettings.PushCurrentSource, PushSettingsWaitTime);

			return searchSetting;
		}
    private void btnYes_Click(object sender, EventArgs e)
    {
        pnlConfirmation.Visible = false;
        pnlDeleteSite.Visible = true;

        // Start the timer for the callbacks
        ltlScript.Text = ScriptHelper.GetScript("StartStateTimer();");

        // Deletion info initialization
        DeletionInfo.DeleteAttachments = chkDeleteDocumentAttachments.Checked;
        DeletionInfo.DeleteMediaFiles = chkDeleteMediaFiles.Checked;
        DeletionInfo.DeleteMetaFiles = chkDeleteMetaFiles.Checked;
        DeletionInfo.SiteName = siteName;
        DeletionInfo.SiteDisplayName = siteDisplayName;
        DeletionManager.CurrentUser = MembershipContext.AuthenticatedUser;
        DeletionManager.DeletionInfo = DeletionInfo;

        AsyncWorker worker = new AsyncWorker();
        worker.RunAsync(DeletionManager.DeleteSite, WindowsIdentity.GetCurrent());
    }
 /// <summary>
 /// Called when an operation reports progress.
 /// </summary>
 /// <param name="asyncWorker">The async worker.</param>
 /// <param name="worker">The worker.</param>
 /// <param name="progress">The progress.</param>
 /// <param name="userState">State of the user.</param>
 public void ReportProgress(AsyncWorker asyncWorker, DoWorkEventHandler worker, ProgressChangedEventHandler progress, object userState)
 {
     if (this.log.IsInfoEnabled)
     {
         this.log.Info(string.Format(
                      CultureInfo.InvariantCulture,
                      "{0} reports progress for operation {1}.{2}()",
                      asyncWorker,
                      worker.Method.DeclaringType.FullName,
                      worker.Method.Name));
     }
 }
 /// <summary>
 /// Next button click.
 /// </summary>
 /// <param name="sender">Sender</param>
 /// <param name="e">Arguments</param>
 void wzdImport_NextButtonClick(object sender, WizardNavigationEventArgs e)
 {
     switch (wzdImport.ActiveStepIndex)
     {
         case 0:
             if (!string.IsNullOrEmpty(lstImports.SelectedValue))
             {
                 // Create asynchronous process
                 worker = new AsyncWorker();
                 worker.OnError += new EventHandler(worker_OnError);
                 worker.RunAsync(ImportLicenses, WindowsIdentity.GetCurrent());
                 wzdImport.ActiveStepIndex++;
                 PrepareSteps();
             }
             else
             {
                 e.Cancel = true;
                 lblErrorFirstStep.Visible = true;
             }
             break;
     }
 }