Пример #1
0
 public static void Test()
 {
     Console.WriteLine("++++++++++++++++ProgrammeTest++++++++++++++++++");
     using (WaitHandle = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.AutoReset))
     {
         DateTime triggerTime = DateTime.Now.AddSeconds(2);
         using (Programme prog = new Programme())
         {
             prog.Reminding += new EventHandler <ProgrammeRemindingEventArgs>(prog_Reminding);
             prog.Items.Add("1", new PlanTime(triggerTime.Hour, triggerTime.Minute, triggerTime.Second), "新闻联播");
             prog.Items.Add(new ProgrammeItem("2", new PlanTime(triggerTime.AddSeconds(2)), "二人转 001"));
             prog.Items.Add("3", new PlanTime(triggerTime.AddDays(1)), "二人转 002");
             DateTime date = DateTime.Now.Date;
             ReadOnlyCollection <ProgrammeItem> collection = prog.GetDateProgrammeItems(date);
             Console.WriteLine("Today's Programme");
             foreach (var item in collection)
             {
                 Console.WriteLine("{0} {1}", item.Content, item.PlannedTime.ToDateTime(date));
             }
             Console.WriteLine("====================================");
             Console.WriteLine("Waiting for {0}", prog.Items["1"].Content);
             WaitHandle.WaitOne();
             Console.WriteLine("Waiting for {0}", prog.Items["2"].Content);
             WaitHandle.WaitOne();
             Console.WriteLine("Press enter to continue.");
             Console.ReadKey();
         }
     }
 }
Пример #2
0
        public static void Test()
        {
            Console.WriteLine("++++++++++++++++WeeklyWorkSheetTest++++++++++++++++++");
            using (WaitHandle = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.AutoReset))
            {
                DateTime beginTime = DateTime.Now.AddSeconds(-2);
                DateTime endTime   = DateTime.Now.AddSeconds(3);
                using (WeeklyWorkSheet ws = new WeeklyWorkSheet())
                {
                    ws.DayOfWeekWorkSheetItemBeginning += new EventHandler <DayOfWeekWorkSheetItemBeginningEventArgs>(ws_DayOfWeekWorkSheetItemBeginning);
                    ws.DayOfWeekWorkSheetItemEnding    += new EventHandler <DayOfWeekWorkSheetItemEndingEventArgs>(ws_DayOfWeekWorkSheetItemEnding);

                    ws.Monday.Items.Add(beginTime, endTime);
                    ws.Monday.Items.Add(beginTime.AddSeconds(10), endTime.AddSeconds(10));
                    ws.CopyToAll(DayOfWeek.Monday);
                    int i = 0;
                    while (i < ws.Monday.Items.Count)
                    {
                        i++;
                        Console.WriteLine("====================================");
                        Console.WriteLine("Waiting for Beginning");
                        WaitHandle.WaitOne();
                        Console.WriteLine("Waiting for Ending");
                        WaitHandle.WaitOne();
                    }
                    Console.WriteLine("Press enter to continue.");
                    Console.ReadKey();
                }
            }
        }
Пример #3
0
        private static void Plan_Test()
        {
            Console.WriteLine("++++++++++++++++PlanTest++++++++++++++++++");
            Int32    times = 3;
            DateTime time  = DateTime.Now.AddSeconds(1);

            using (Plan plan = new Plan(time.Hour, time.Minute, time.Second))
            {
                plan.RepeatInterval = TimeSpan.FromSeconds(5);
                plan.RepeatTimes    = 3;
                plan.Enabled        = false;
                plan.Reminding     += new EventHandler <EventArgs>(plan_Reminding);
                while (times-- > 0)
                {
                    plan.Enabled = true;
                    WaitHandle.WaitOne();
                }
                Console.WriteLine("Press enter to continue.");
                Console.ReadKey();
                foreach (var item in plan.RemindedRecords)
                {
                    Console.WriteLine("Reminded at {0}.{0:ffff}", item);
                }
            }
        }
Пример #4
0
        public async Task Process()
        {
            while (!Error)
            {
                if (msgQueue.Count == 0)
                {
                    waitHandle.WaitOne();
                }

                try
                {
                    var folderList = StorageApplicationPermissions.FutureAccessList;
                    if (LogFile == null && Config.GetBoolean(Config.EnableLogs) && folderList.ContainsItem(Config.LogsFolder))
                    {
                        var parent = await StorageApplicationPermissions.FutureAccessList.GetFolderAsync(Config.LogsFolder);

                        serverFolder = await parent.CreateFolderAsync(server, CreationCollisionOption.OpenIfExists);

                        currentDate = DateTime.Now.ToString("yyyy-MM-dd");
                        await OpenFile();
                    }
                    else if (LogFile != null)
                    {
                        var newDate = DateTime.Now.ToString("yyyy-MM-dd");

                        if (newDate != currentDate)
                        {
                            currentDate = newDate;
                            await OpenFile();
                        }

                        Message msg;
                        msgQueue.TryDequeue(out msg);

                        if (msg != null)
                        {
                            await WriteLine(MessageToString(msg));
                        }
                    }
                    else
                    {
                        Error = true;
                        break;
                    }
                }
                catch (Exception e)
                {
                    Error = true;
                    Message error = new Message()
                    {
                        User = "******",
                        Type = MessageType.Info,
                        Text = e.Message + "\r\n Logging disabled for this channel"
                    };
                    msgs.Add(error);
                }

                waitHandle.Reset();
            }
        }
Пример #5
0
        public override void RunInGuiThread(System.Action d)
        {
            if (alreadyInGuiThread)
            {
                Console.WriteLine();
                Console.WriteLine("WARNING: You called RunInGuiThread nestedly.");
                d();
                return;
            }
            alreadyInGuiThread = true;

            try {
                System.Threading.EventWaitHandle h = guiThread.CallDelegInMainLoop(d);
                h.WaitOne();
                h.Close();
                if (guiThread.ExceptionHappened != null)
                {
                    throw guiThread.ExceptionHappened;
                }
            }
            finally {
                alreadyInGuiThread = false;
            }
            System.Threading.Thread.Sleep(2000);
        }
Пример #6
0
        private void NavigateDownRequestWorker(object state)
        {
            // bool waitForEvent = false;

            System.Threading.Thread.Sleep(20);

            //Dispatcher.Invoke(new Action(() => {
            //    if (_currentListBox.SelectedItem == null)
            //    {
            //        waitForEvent = true;
            //    }
            //}));



            if (ongoingSearches > 0)
            {
                searchFinishedEvent.WaitOne(5000);
            }

            Dispatcher.Invoke(new Action(() =>
            {
                if (_currentListBox.SelectedItem != null)
                {
                    object selectedItem = _currentListBox.SelectedItem;
                    TryNavigateDown(selectedItem);
                }
            }));

            ongoingSearches            = 0;
            pendingNavigateDownRequest = false;
        }
Пример #7
0
 public void Work(BackgroundWorker report)
 {
     while (true)
     {
         IBrowserItem task = null;
         lock (tasks)
             if (tasks.Count > 0)
             {
                 task = tasks.Dequeue();
                 if (task == null)
                 {
                     return;
                 }
             }
         if (task != null)
         {
             System.Threading.Thread.Sleep(15);
             Icon icon = ShellApi.Win32.getIcon(task.FullPath);
             task.Icon = icon;
             report.ReportProgress(0, task);
         }
         else
         {
             wh.WaitOne();         // No more tasks - wait for a signal
         }
     }
 }
Пример #8
0
        static void start(System.Threading.EventWaitHandle quit)
        {
            var appSettings = ConfigurationManager.AppSettings;

            try
            {
                Uri            baseAddress = new Uri(string.Format("http://localhost:{0}/", appSettings["port"]));
                WebServiceHost svcHost     = new WebServiceHost(typeof(Program), baseAddress);
                WebHttpBinding b           = new WebHttpBinding();
                b.Name = NAME;
                b.HostNameComparisonMode = HostNameComparisonMode.Exact;
                svcHost.AddServiceEndpoint(typeof(IModelLookupWebService), b, "");
                logIt("WebService is running");
                svcHost.Open();
                download_imei2model();
                loadDB();
                quit.WaitOne();
                //System.Console.WriteLine("Press any key to stop.");
                //System.Console.ReadKey();
                svcHost.Close();
            }
            catch (Exception ex)
            {
                logIt(ex.Message);
            }
        }
Пример #9
0
        private void btnSearchKey_Click(object sender, EventArgs e)
        {
            if (RedisClient == null)
            {
                DoConnection();
            }
            try
            {
                this.treeKeys.Nodes.Clear();
                System.Threading.EventWaitHandle waitHandle = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.AutoReset);
                List <string> keys = null;
                new Task(() =>
                {
                    keys = RedisClient.SearchKeys(txtPattern.Text);
                    waitHandle.Set();
                }).Start();
                if (!waitHandle.WaitOne(RedisClient.SendTimeout))
                {
                    RedisClient.Dispose();
                    RedisClient = null;
                    throw new Exception("search keys timeout!");
                }
                NestedHash keysTree = new NestedHash();
                foreach (string key in keys)
                {
                    string[]   keySegments = key.Split(':');
                    NestedHash pHash       = keysTree;   // 指针
                    string     pKeySegment = "";         // 指针
                    for (int i = 0; i < keySegments.Length; i++)
                    {
                        string keySegment = keySegments[i];
                        if (i > 0)
                        {
                            if (pHash[pKeySegment] == null)
                            {
                                NestedHash hash = new NestedHash();
                                pHash[pKeySegment] = hash;
                                pHash = hash;
                            }
                            else
                            {
                                pHash = pHash[pKeySegment] as NestedHash;
                            }
                        }

                        if (!pHash.ContainsKey(keySegment))
                        {
                            pHash.Add(keySegment, null);
                        }

                        pKeySegment = keySegment;
                    }
                }
                BuildTree(this.treeKeys.Nodes, keysTree);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Пример #10
0
 private void _execute()
 {
     System.Threading.Thread t = new System.Threading.Thread(executeThread);
     executeEvent.Reset();
     t.Start();
     executeEvent.WaitOne(System.Threading.Timeout.Infinite);
 }
Пример #11
0
        public static void OE_App_3_0_2_0(System.Threading.EventWaitHandle evt)
        {
            Program.logIt("OE_App_3_0_2_0: ++");
            Process app = start_app();

            if (app != null)
            {
                Program.logIt($"OE_App_3_0_2_0: App started, {app.MainWindowTitle}");
                // to start the process post message WM_COMMAND, 0x3C(0x3D), 0
                System.Threading.Thread.Sleep(5000);
                app.Refresh();
                SetForegroundWindow(app.MainWindowHandle);
                IntPtr mainWnd = app.MainWindowHandle;
                Program.logIt($"OE_App_3_0_2_0: send message to {app.MainWindowTitle}({app.MainWindowHandle}), 0x111,0x3c,0");
                PostMessage(app.MainWindowHandle, WM_COMMAND, 0x3c, 0);
                IntPtr topWnd = GetDesktopWindow();
                Program.logIt($"OE_App_3_0_2_0: desktop Wnd: {topWnd}");
                evt.WaitOne();
                Program.logIt($"OE_App_3_0_2_0: recv terminate event.");
                app.Refresh();
                Program.logIt($"OE_App_3_0_2_0: send message to {app.MainWindowTitle}({app.MainWindowHandle}), 0x111,0x3d,0");
                PostMessage(app.MainWindowHandle, WM_COMMAND, 0x3d, 0);
                System.Threading.Thread.Sleep(5000);
                app.CloseMainWindow();
                app.WaitForExit(3000);
                if (!app.HasExited)
                {
                    app.Kill();
                }
            }
            Program.logIt("OE_App_3_0_2_0: --");
        }
Пример #12
0
        private void check_button_Click(object sender, EventArgs e)
        {
            if (IdPwcheck()) // id , pw  모두 입력 됐으면
            {
                userId = user_id_textbox.Text;
                string   userpw      = user_pw_textbox.Text;
                string[] client_info = new string[2];
                client_info[0] = userId;
                client_info[1] = userpw;
                clientSocket.OnSendData("login" + "|" + client_info[0] + "/" + client_info[1] + "|", null);
                waitHandle.WaitOne(); //로그인 결과가 올때까지 대기 상태가 되어야 한다.
                if (loginstate)
                {
                    clientSocket.Disconnect();
                    MessageBox.Show("로그인 성공!", "확인", MessageBoxButtons.OK, MessageBoxIcon.None);
                    Main_form main_form = new Main_form(userId);
                    this.Invoke(new MethodInvoker(this.Hide)); // 크로스 스레드 해결

                    main_form.ShowDialog();
                    if (main_form.DialogResult != DialogResult.OK)
                    {
                        this.Invoke(new MethodInvoker(this.Dispose));  // 크로스 스레드 해결
                    }
                }
                else
                {
                    MessageBox.Show("로그인 실패!", "오류", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }
Пример #13
0
        private void DbListener()
        {
            bool isConnected               = TryConnectSocket();
            bool isNeedSendEventsAgain     = false;
            bool isNeedSendExceptionsAgain = false;

            while (true)
            {
                ewh.WaitOne();
                System.Threading.Thread.Sleep(1500);
                if (_isEventsRecord)
                {
                    ewh.Reset();
                    continue;
                }
                if (isConnected)
                {
                    isNeedSendEventsAgain     = _context.SendTrackerEvents(socket, ref isConnected);
                    isNeedSendExceptionsAgain = _context.SendExceptions(socket, ref isConnected);
                    if (!isNeedSendEventsAgain && !isNeedSendExceptionsAgain)
                    {
                        ewh.Reset();
                    }
                }
                else
                {
                    isConnected = TryConnectSocket();
                    if (!isConnected)
                    {
                        System.Threading.Thread.Sleep(1000);
                    }
                }
            }
        }
Пример #14
0
 public BackgroundTaskManager()
 {
     _OwnerDispatcher           = System.Windows.Threading.Dispatcher.CurrentDispatcher;
     _WorkerThread              = new System.Threading.Thread(new System.Threading.ThreadStart(WorkerStart));
     _WorkerThread.Name         = "BackgroundTaskManager:" + DateTime.Now.Ticks.ToString();
     _WorkerThread.IsBackground = true;
     _WorkerThread.Start();
     _WorkerStarted.WaitOne();
 }
Пример #15
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            bool createdNew;

            mutex = new System.Threading.Mutex(true, Res.Resources.GetRes().GetSoftServicePCName(), out createdNew);
            System.Threading.EventWaitHandle eventWaitHandle = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.AutoReset, Res.Resources.GetRes().GetSoftServicePCName() + Res.Resources.GetRes().GetSoftServicePCName());



            if (createdNew)
            {
                // Spawn a thread which will be waiting for our event
                var thread = new System.Threading.Thread(
                    () =>
                {
                    while (eventWaitHandle.WaitOne())
                    {
                        lock (TheLock)
                        {
                            Form defaultForm = Application.OpenForms.Cast <Form>().Where(x => null != x.Tag && x.Tag.ToString() == "Main").FirstOrDefault();

                            if (null != defaultForm)
                            {
                                defaultForm.BeginInvoke((Action)(() => BringToForeground(defaultForm)));
                            }
                        }
                    }
                });

                // It is important mark it as background otherwise it will prevent app from exiting.
                thread.IsBackground = true;

                thread.Start();

                //注册错误
                Application.ThreadException += Application_ThreadException;
                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
                //加载日志
                Resources.GetRes().LoadLog();
                //字体效果(为XP开启)
                FontSmoothing.OpenFontEffect();

                Resources.GetRes().SetDeviceType((long)1);
                Application.Run(new LoginWindow());
                mutex.ReleaseMutex();
            }
            // Notify other instance so it could bring itself to foreground.
            eventWaitHandle.Set();

            // Terminate this instance.
            Environment.Exit(0);
        }
Пример #16
0
 public static Task <T> ToTaskAsync <T>(this IPushObservable <T> observable)
 {
     return(Task.Run(() =>
     {
         T latestValue = default(T);
         var mtx = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.AutoReset);
         var disp = observable.Subscribe((v) => latestValue = v, () => mtx.Set());
         mtx.WaitOne();
         disp.Dispose();
         return latestValue;
     }));
 }
Пример #17
0
 private void commitPendingChanges(Lynx.PropertySets.Workspace workspace)
 {
     sessionLogger.Log("commit pending changes.");
     using (var eventWaitHandle = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.ManualReset))
     {
         workspace.commit(System.DateTime.Now.ToString(), (error, commitNode) => { if (error != null)
                                                                                   {
                                                                                       System.Windows.Forms.MessageBox.Show(error.what()); sessionLogger.Log("error: " + error.what());
                                                                                   }
                                                                                   eventWaitHandle.Set(); });
         eventWaitHandle.WaitOne();
     }
 }
Пример #18
0
 public void PlayAsync(string url)
 {
     System.Threading.EventWaitHandle wait = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.AutoReset);
     Task.Factory.StartNew(() =>
     {
         System.Media.SoundPlayer player = new System.Media.SoundPlayer(url);
         player.PlaySync();
         wait.Set();
     }).ContinueWith(x =>
     {
         wait.WaitOne();
     });
 }
Пример #19
0
 public void PlayAsync(string url)
 {
     System.Threading.EventWaitHandle wait = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.AutoReset);
     Task.Factory.StartNew(() =>
     {
         System.Media.SoundPlayer player = new System.Media.SoundPlayer(url);
         player.PlaySync();
         wait.Set();
     }).ContinueWith(x =>
     {
         wait.WaitOne();
     });
 }
Пример #20
0
 public static void Test()
 {
     Console.WriteLine("++++++++++++++++WorkSheetTest++++++++++++++++++");
     using (WaitHandle = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.AutoReset))
     {
         DateTime beginTime = DateTime.Now.AddSeconds(2);
         DateTime endTime   = DateTime.Now.AddSeconds(3);
         using (WorkSheet ws = new WorkSheet())
         {
             ws.WorkSheetItemBeginning += new EventHandler <WorkSheetItemBeginningEventArgs>(ws_WorkSheetItemBeginning);
             ws.WorkSheetItemEnding    += new EventHandler <WorkSheetItemEndingEventArgs>(ws_WorkSheetItemEnding);
             ws.Items.Add(new WorkSheetItem(new PlanTime(beginTime.Hour, beginTime.Minute, beginTime.Second), new PlanTime(endTime.Hour, endTime.Minute, endTime.Second), "放风", true));
             Console.WriteLine("====================================");
             Console.WriteLine("Waiting for {0} Beginning", ws.Items[0].Content);
             WaitHandle.WaitOne();
             Console.WriteLine("Waiting for {0} Ending", ws.Items[0].Content);
             WaitHandle.WaitOne();
             Console.WriteLine("Press enter to continue.");
             Console.ReadKey();
         }
     }
 }
Пример #21
0
        public static void DoIt(
            string sourceProject = "XFTestPlatformes",
            string sourcePath    = @"D:\SoftWare2\MyProjects\XFTestPlatformes",

            string targetProject = "MSBuildSdkExtrasTest",
            string targetPath    = @"D:\SoftWare2\MyProjects\MSBuildSdkExtrasTest")
        {
            Task task = Task.Run(() => DoIt_sub(sourceProject, sourcePath, targetProject, targetPath));

            waitHandle.WaitOne();

            //ToDo: Progressbar or other feedback on progress ...
            MessageBox.Show("Copy and rename solution terminated.", "Info", MessageBoxButton.OK, MessageBoxImage.Information);
        }
Пример #22
0
 private void BackgroundProcess()
 {
     while (!_isStopped)
     {
         lock (_lock)
         {
             while (_actionQueue.Count > 0)
             {
                 _actionQueue.Dequeue()();
             }
         }
         _mtxWaitNewProcess.WaitOne();
     }
 }
        public async Task AsteroidsDAL_CSV_ReadCSV()
        {
            // 1. Stufe: Einlesen der Asteroiden aus der CSV- Datei
            //    und erfassen im Sammler
            AsteroidsBL.IAsteroidsCollector collector = new AsteroidsCollector();
            try
            {
                var reader = new AsteroidsCSVReader("Asteroids.csv", 2);
                while (!reader.EOF)
                {
                    var asteroid = reader.Read();
                    collector.Add(asteroid);
                }

                Assert.IsTrue(collector.Count > 0);

                // 2. Stufe: Aus gesammelten Asteroiden ein
                //           Repository formen.
                var repository = collector.CreateRepository();

                // 3. Abfragen auf dem Repository formulieren und ausführen
                var qbld = repository.GetNewQueryBuilder();

                qbld.MinDiameterInKm = 10.0;
                qbld.MaxDiameterInKm = 50.0;

                // 4. Definition der Sortierreihenfolgen
                var SortBld = qbld.GetSortOrderBuilder();

                SortBld.OrderByDiameterAsc = true;

                // Gefilterte und Sortierte Menge als IFilteredSortedSet Objekte abrufen
                var fsSet = SortBld.GetFilteredSortedSet();
                Assert.IsTrue(fsSet.Any());

                // Zugrif auf die einzelnen Elemente
                var elems = fsSet.Get();
                Assert.IsTrue(elems.First().DiameterInKm > elems.Last().DiameterInKm);


                await qbld.EnqueueFilteredInAsync(queue);

                Ampel.WaitOne();
            }
            catch (Exception ex)
            {
                Assert.Fail();
            }
        }
Пример #24
0
        public void Execute(Action action)
        {
            var mtxInit = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.AutoReset);

            lock (_lock)
            {
                _actionQueue.Enqueue(() =>
                {
                    action();
                    mtxInit.Set();
                });
            }
            _mtxWaitNewProcess.Set();
            mtxInit.WaitOne();
        }
Пример #25
0
 /// <summary>
 /// Constructor for initialization and acquireing locks
 /// </summary>
 /// <param name="key"></param>
 public KeyLock(string key)
 {
     this.key = key;
     lock (globalLock)
     {
         if (!Locks.ContainsKey(key))
         {
             Locks.Add(key, new LockItem());
         }
         var item = Locks[key];
         item.count++;
         ev = item.ev;
     }
     ev.WaitOne();
 }
Пример #26
0
 public UuidLock(string uuid)
 {
     this.uuid = uuid;
     lock (globalLock)
     {
         if (!Locks.ContainsKey(uuid))
         {
             Locks.Add(uuid, new LockItem());
         }
         var item = Locks[uuid];
         item.count++;
         ev = item.ev;
     }
     ev.WaitOne();
 }
Пример #27
0
        public int Execute()
        {
            try
            {
                Action <string> log = text => { if (!settings.Quiet)
                                                {
                                                    Console.Out.WriteLine(text);
                                                }
                };

                var wait = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.AutoReset);

                using (var client = new WebClientWithInfo())
                {
                    client.Headers[HttpRequestHeader.UserAgent] = settings.Http.UserAgent;
                    client.Headers[HttpRequestHeader.Accept]    = "*/*";

                    client.GotResponse += (object _, WebClientWithInfo.ResponseEventArgs e) => {
                        log("Got response...");
                        log("Length: {0}".With(e.Response.ContentLength > -1 ? e.Response.ContentLength.ToString() : "unspecfied"));
                        log("Saving to: '{0}'\n".With(settings.Download.OutputDocument));
                    };

                    client.DownloadProgressChanged += (object _, DownloadProgressChangedEventArgs e) => {
                        log("progress: {0}/{1} ({2}%)".With(e.BytesReceived, e.TotalBytesToReceive, e.ProgressPercentage));
                    };

                    client.DownloadDataCompleted += (_, e) => wait.Set();

                    settings.Urls.Each(url => {
                        client.DownloadDataAsync(new Uri(url));
                        // update progressbar etc
                        wait.WaitOne();
                    });
                }

                return(0);
            }
            catch (Exception ex)
            {
                if (!settings.Quiet)
                {
                    Console.Error.WriteLine(ex.Message);
                }
                return(1);
            }
        }
Пример #28
0
        public override bool Execute()
        {
            System.Threading.EventWaitHandle handle = new System.Threading.EventWaitHandle(
                true, System.Threading.EventResetMode.AutoReset, m_Name);

            if (m_Lock)
            {
                handle.WaitOne();
                handle.Reset();
            }
            else
            {
                handle.Set();
            }

            return(true);
        }
Пример #29
0
 public string GetAuthorizationCode()
 {
     using (var host = new Nancy.Hosting.Self.NancyHost(new Nancy.Hosting.Self.HostConfiguration()
     {
         UrlReservations = { CreateAutomatically = true }
     }, new System.Uri(redirectUrl)))
     {
         host.Start();
         eventWaitHandler = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.ManualReset);
         Log("launch operating system default web browser: " + url);
         System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(url));
         eventWaitHandler.WaitOne();
         Log("authorization code: " + authorizationCode);
         System.Threading.Thread.Sleep(1000);
     }
     return(authorizationCode);
 }
Пример #30
0
        public override bool Execute()
        {
            System.Threading.EventWaitHandle handle = new System.Threading.EventWaitHandle(
                true, System.Threading.EventResetMode.AutoReset, m_Name);

            if (m_Lock)
            {
                handle.WaitOne();
                handle.Reset();
            }
            else
            {
                handle.Set();
            }

            return true;
        }
Пример #31
0
        private static void DoTheJob()
        {
            while (true)
            {
                EV.WaitOne();

                if (C.CanSendFile)
                {
                    C.RunProgram();
                }
                else if (C.CanResumeHold)
                {
                    C.CycleStartResume(false);
                }

                System.Threading.Thread.Sleep(1000);                 //do not test the flag for 1 sec
            }
        }
Пример #32
0
 public void DanglingWindowMessage()
 {
     using (OuterTest nuf = new OuterTest())
     {
         Form f = new Form();
         f.Show();
         System.Threading.EventWaitHandle w = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.AutoReset);
         System.Threading.ThreadPool.QueueUserWorkItem(delegate(object o)
         {
             f.BeginInvoke(new MethodInvoker(delegate()
             {
                 MessageBox.Show("", "Blah");
             }));
             w.Set();
         });
         w.WaitOne();
     }
 }
Пример #33
0
 public void DanglingWindowMessage()
 {
     using (OuterTest nuf = new OuterTest())
     {
         Form f = new Form();
         f.Show();
         System.Threading.EventWaitHandle w = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.AutoReset);
         System.Threading.ThreadPool.QueueUserWorkItem(delegate(object o)
         {
             f.BeginInvoke(new MethodInvoker(delegate()
             {
                 MessageBox.Show("", "Blah");
             }));
             w.Set();
         });
         w.WaitOne();
         Assert.Throws<FormsTestAssertionException>(() => nuf.Verify());
     }
 }
Пример #34
0
        public int Execute()
        {
            try
            {
                Action<string> log = text => { if(!settings.Quiet) Console.Out.WriteLine(text); };

                var wait = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.AutoReset);

                using(var client = new WebClientWithInfo())
                {
                    client.Headers[HttpRequestHeader.UserAgent] = settings.Http.UserAgent;
                    client.Headers[HttpRequestHeader.Accept] = "*/*";

                    client.GotResponse += (object _, WebClientWithInfo.ResponseEventArgs e) => {
                        log("Got response...");
                        log("Length: {0}".With(e.Response.ContentLength > -1 ? e.Response.ContentLength.ToString() : "unspecfied"));
                        log("Saving to: '{0}'\n".With(settings.Download.OutputDocument));
                    };

                    client.DownloadProgressChanged += (object _, DownloadProgressChangedEventArgs e) => {
                        log("progress: {0}/{1} ({2}%)".With(e.BytesReceived, e.TotalBytesToReceive, e.ProgressPercentage));
                    };

                    client.DownloadDataCompleted += (_, e) => wait.Set();

                    settings.Urls.Each(url => {
                        client.DownloadDataAsync(new Uri(url));
                        // update progressbar etc
                        wait.WaitOne();
                    });
                }

                return 0;
            }
            catch (Exception ex)
            {
                if(!settings.Quiet)
                    Console.Error.WriteLine(ex.Message);
                return 1;
            }
        }
Пример #35
0
		/// <summary>Starts the installer program, when all presumtions are fullfilled.</summary>
		/// <param name="isAltaxoCurrentlyStarting">If set to <c>true</c>, Altaxo will be restarted after the installation is done.</param>
		/// <param name="commandLineArgs">Original command line arguments. Can be <c>null</c> when calling this function on shutdown.</param>
		/// <returns>True if the installer program was started. Then Altaxo have to be shut down immediately. Returns <c>false</c> if the installer program was not started.</returns>
		public static bool Run(bool isAltaxoCurrentlyStarting, string[] commandLineArgs)
		{
			var updateSettings = Current.PropertyService.GetValue(Altaxo.Settings.AutoUpdateSettings.PropertyKeyAutoUpdate, Main.Services.RuntimePropertyKind.UserAndApplicationAndBuiltin, () => new Altaxo.Settings.AutoUpdateSettings());

			var installationRequested = (isAltaxoCurrentlyStarting && updateSettings.InstallAtStartup) || (!isAltaxoCurrentlyStarting && updateSettings.InstallAtShutdown);
			if (!installationRequested)
				return false;

			bool loadUnstable = updateSettings.DownloadUnstableVersion;

			FileStream versionFileStream = null;
			FileStream packageStream = null;

			// try to lock the version file in the download directory, thus no other process can modify it
			try
			{
				var downloadFolder = PackageInfo.GetDownloadDirectory(loadUnstable);
				var versionFileName = Path.Combine(downloadFolder, PackageInfo.VersionFileName);

				versionFileStream = new FileStream(versionFileName, FileMode.Open, FileAccess.Read, FileShare.Read);

				var info = PackageInfo.GetPresentDownloadedPackage(versionFileStream, downloadFolder, out packageStream);

				if (null == info || null == packageStream)
					return false;

				var entryAssembly = System.Reflection.Assembly.GetEntryAssembly();
				var entryAssemblyVersion = entryAssembly.GetName().Version;

				if (info.Version <= entryAssemblyVersion)
					return false; // no need to update

				if (updateSettings.ConfirmInstallation)
				{
					var question = string.Format(
						"A new Altaxo update is available (from current version {0} to new {1} version {2}).\r\n\r\n" +
						"If you don't want to have auto updates, please deactivate them by choosing 'Tools'->'Options' menu in Altaxo.\r\n" +
						"\r\n" +
					"Do you want to update to {1} version {2} now?", entryAssemblyVersion, PackageInfo.GetStableIdentifier(info.IsUnstableVersion).ToLower(), info.Version);

					if (false == Current.Gui.YesNoMessageBox(question, "Altaxo update available", true))
						return false; // user don't want to update
				}

				// copy the Updater executable to the download folder
				var entryAssemblyFolder = Path.GetDirectoryName(entryAssembly.Location);
				var installerFullSrcName = Path.Combine(entryAssemblyFolder, UpdateInstallerFileName);
				var installerFullDestName = Path.Combine(downloadFolder, UpdateInstallerFileName);
				File.Copy(installerFullSrcName, installerFullDestName, true);

				// both the version file and the package stream are locked now
				// so we can start the updater program

				var eventName = System.Guid.NewGuid().ToString();
				var waitForRemoteStartSignal = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.ManualReset, eventName);

				var processInfo = new System.Diagnostics.ProcessStartInfo();
				processInfo.FileName = installerFullDestName;
				StringBuilder stb = new StringBuilder();
				stb.AppendFormat(System.Globalization.CultureInfo.InvariantCulture,
					"\"{0}\"\t\"{1}\"\t{2}\t{3}\t{4}\t\"{5}\"",
					eventName,
					packageStream.Name,
					updateSettings.ShowInstallationWindow ? 1 : 0,
					updateSettings.InstallationWindowClosingTime,
					isAltaxoCurrentlyStarting ? 1 : 0,
					entryAssembly.Location);
				if (isAltaxoCurrentlyStarting && commandLineArgs != null && commandLineArgs.Length > 0)
				{
					foreach (var s in commandLineArgs)
						stb.AppendFormat("\t\"{0}\"", s);
				}
				processInfo.Arguments = stb.ToString();
				processInfo.CreateNoWindow = false;
				processInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;

				// Start the updater program
				var process = System.Diagnostics.Process.Start(processInfo);

				for (; ; )
				{
					// we wait until the update program signals that it has now taken the VersionInfo file
					if (waitForRemoteStartSignal.WaitOne(100))
						break;
					if (process.HasExited)
						return false; // then something has gone wrong or the user has closed the window
				}

				return true;
			}
			catch (Exception)
			{
				return false;
			}
			finally
			{
				if (null != packageStream)
					packageStream.Close();
				if (null != versionFileStream)
					versionFileStream.Close();
			}
		}