Exemplo n.º 1
0
        public byte[] sendBuffer = null;//Send buffer

        public socket(String ipAddress)
        {
            ip = ipAddress;
            sendBuffer = new byte[1024];//Send buffer //c# automatic assigesd to 0     
            try
            {
                //创建一个Socket
                clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                System.Threading.Thread tt = new System.Threading.Thread(delegate()
                {
                    //连接到指定服务器的指定端口
                    //方法参考:http://msdn.microsoft.com/zh-cn/library/system.net.sockets.socket.connect.aspx
                    try
                    {
                        clientSocket.Connect(ip, port);
                    }
                    catch(Exception ee)
                    {
                        MessageBox.Show(ee.Message);
                    }
                });
                tt.Start();
                
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message + "\r\n From:" + this);
            }

        }
Exemplo n.º 2
0
        public static DateTime GetCubeLastSchemaUpdateDate()
        {
            DateTime dtTemp = DateTime.MinValue;
            Exception exDelegate = null;

            string sServerName = Context.CurrentServerID;
            string sDatabaseName = Context.CurrentDatabaseName;
            string sCubeName = GetCurrentCubeName();

            System.Threading.Thread td = new System.Threading.Thread(delegate()
            {
                try {
                    Microsoft.AnalysisServices.Server oServer = new Microsoft.AnalysisServices.Server();
                    oServer.Connect("Data Source=" + sServerName);
                    Database db = oServer.Databases.GetByName(sDatabaseName);
                    Cube cube = db.Cubes.FindByName(sCubeName);

                    dtTemp = cube.LastSchemaUpdate;
                }
                catch (Exception ex)
                {
                    exDelegate = ex;
                }
            }
            );
            td.Start();
            while (!td.Join(1000))
            {
                Context.CheckCancelled();
            }

            if (exDelegate != null) throw exDelegate;

            return dtTemp;
        }
Exemplo n.º 3
0
 private void button1_Click(object sender, EventArgs e)
 {
     try
     {
         System.Threading.ThreadStart ts = delegate
         {
             CLKsFATXLib.Streams.Reader OR = Original.Reader();
             CLKsFATXLib.Streams.Writer D = Destination.Writer();
             OR.BaseStream.Position = 0;
             D.BaseStream.Position = 0;
             for (long i = 0; i < Original.Length; i += 0x6000)
             {
                 D.Write(OR.ReadBytes(0x6000));
                 progressBar1.Invoke((MethodInvoker)delegate
                 {
                     try
                     {
                         progressBar1.Maximum = (int)(Original.Length >> 4);
                         progressBar1.Value = (int)(((i >> 8) < 0) ? 0 : i >> 4);
                     }
                     catch { }
                 });
             }
             OR.Close();
             D.Close();
         };
         System.Threading.Thread t = new System.Threading.Thread(ts);
         t.Start();
     }
     catch (Exception x) { MessageBox.Show(x.Message); }
 }
Exemplo n.º 4
0
        public void reConnect()
        {
            clientSocket.Close();
            clientSocket = null;
            sendBuffer = new byte[1024];//Send buffer //c# automatic assigesd to 0     

            try
            {
                clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                System.Threading.Thread tt = new System.Threading.Thread(delegate()
                {
                    try
                    {
                        clientSocket.Connect(ip, port);
                    }
                    catch (Exception ee)
                    {
                        //MessageBox.Show(ee.Message + "\r\n From:" + this);
                    }
                });
                tt.Start();

            }
            catch (Exception e)
            {
                //MessageBox.Show(e.Message + "\r\n From:" + this);
            }
        }
Exemplo n.º 5
0
        protected override void Dispose(bool disposing)
        {
            if (m_p != null)
            {
                m_basestream.Close();

                if (!m_t.Join(5000))
                    throw new System.Security.Cryptography.CryptographicException(Strings.GPGStreamWrapper.GPGFlushError);

                if (!m_p.WaitForExit(5000))
                    throw new System.Security.Cryptography.CryptographicException(Strings.GPGStreamWrapper.GPGTerminateError);

                if (!m_p.StandardError.EndOfStream)
                {
                    string errmsg = m_p.StandardError.ReadToEnd();
                    if (errmsg.Contains("decryption failed:"))
                        throw new System.Security.Cryptography.CryptographicException(string.Format(Strings.GPGStreamWrapper.DecryptionError, errmsg));
                }

                m_p.Dispose();
                m_p = null;

                m_t = null;
            }

            base.Dispose(disposing);
        }
Exemplo n.º 6
0
        public static void Start()
        {
            lock (StartLock)
            {
                if (isStarted)
                    return;
                isStarted = true;

                if (keyboardHookCheckThread == null)
                {
                    keyboardHookCheckThread = new System.Threading.Thread((System.Threading.ThreadStart)KeyboardHookCheckProc);
                    keyboardHookCheckThread.IsBackground = true;
                    keyboardHookCheckThread.Priority = System.Threading.ThreadPriority.Lowest;
                    keyboardHookCheckThread.Start();
                }

                var modules = System.Reflection.Assembly.GetEntryAssembly().GetModules();
                IntPtr hModule = Marshal.GetHINSTANCE(modules[0]);
                System.Windows.Application.Current.Dispatcher.Invoke((Action)delegate()
                {
                    hHook = WinAPI.WindowHook.SetWindowsHookEx(WinAPI.WindowHook.HookType.WH_KEYBOARD_LL, hookProcPtr, hModule, 0);
                    if (hHook == IntPtr.Zero)
                    {
                        // failed
                        isStarted = false;
                        ("KBHOOK: Hook Failed 0x" + Marshal.GetLastWin32Error().ToString("X")).Log();
                    }
                });
            }
        }
        private void BUT_connect_Click(object sender, EventArgs e)
        {
            if (comPort.IsOpen)
            {
                threadrun = false;
                comPort.Close();
                BUT_connect.Text = Strings.Connect;
            }
            else
            {
                try
                {
                    comPort.PortName = CMB_serialport.Text;
                }
                catch { CustomMessageBox.Show(Strings.InvalidPortName); return; }
                try {
                comPort.BaudRate = int.Parse(CMB_baudrate.Text);
                } catch {CustomMessageBox.Show(Strings.InvalidBaudRate); return;}
                try {
                comPort.Open();
                } catch {CustomMessageBox.Show("Error Connecting\nif using com0com please rename the ports to COM??"); return;}

                t12 = new System.Threading.Thread(new System.Threading.ThreadStart(mainloop))
                {
                    IsBackground = true,
                    Name = "Nmea output"
                };
                t12.Start();
            }
        }
 public static String ModelDownloaded(ContentObject co)
 {
     System.Threading.ParameterizedThreadStart t = new System.Threading.ParameterizedThreadStart(ModelDownloaded_thread);
     System.Threading.Thread th = new System.Threading.Thread(t);
     th.Start(co);
     return "Thread fired";
 }
Exemplo n.º 9
0
        public void Start(Action run)
        {
            Debug.Assert(!isRunning);

            thread = new System.Threading.Thread(new System.Threading.ThreadStart(run));
            thread.Start();
        }
Exemplo n.º 10
0
        private void BUT_connect_Click(object sender, EventArgs e)
        {
            if (comPort.IsOpen)
            {
                threadrun = false;
                comPort.Close();
                BUT_connect.Text = Strings.Connect;
                MainV2.comPort.MAV.cs.MovingBase = null;
            }
            else
            {
                try
                {
                    comPort.PortName = CMB_serialport.Text;
                }
                catch { CustomMessageBox.Show(Strings.InvalidPortName, Strings.ERROR); return; }
                try {
                comPort.BaudRate = int.Parse(CMB_baudrate.Text);
                }
                catch { CustomMessageBox.Show(Strings.InvalidBaudRate, Strings.ERROR); return; }
                try {
                comPort.Open();
                }
                catch (Exception ex) { CustomMessageBox.Show("Error Connecting\nif using com0com please rename the ports to COM??\n" + ex.ToString(), Strings.ERROR); return; }

                t12 = new System.Threading.Thread(new System.Threading.ThreadStart(mainloop))
                {
                    IsBackground = true,
                    Name = "Nmea base Input"
                };
                t12.Start();

                BUT_connect.Text = Strings.Stop;
            }
        }
        public async void StartHostAndClient_SimpleSyncMethodSyncCallWithAsync_Success()
        {
            bool @continue = false;
            var thread = new System.Threading.Thread(() =>
            {
                using (var host = new WcfExampleServiceHost("localhost:10000"))
                {
                    host.Start();
                    @continue = true;
                    while (@continue)
                    {
                        System.Threading.Thread.Sleep(10);
                    }
                    host.Close();
                }
            });
            thread.Start();

            while (!@continue)
            {
                System.Threading.Thread.Sleep(10);
            }

            var client = new WcfExampleServiceAsyncClient("localhost:10000");
            SimpleSyncMethodResponseModel responseSimpleSyncMethod = client.SimpleSyncMethod(new SimpleSyncMethodRequestModel { Message = "Hello World" });
            Assert.IsNotNull(responseSimpleSyncMethod);
            Assert.AreEqual("SimpleSyncMethod: Hello World", responseSimpleSyncMethod.Message);

            @continue = false;

            thread.Join();
        }
Exemplo n.º 12
0
		public static IAsyncOperation Package (MonoMacProject project, ConfigurationSelector configSel,
			MonoMacPackagingSettings settings, FilePath target)
		{
			IProgressMonitor mon = IdeApp.Workbench.ProgressMonitors.GetOutputProgressMonitor (
				GettextCatalog.GetString ("Packaging Output"),
				MonoDevelop.Ide.Gui.Stock.RunProgramIcon, true, true);
			
			 var t = new System.Threading.Thread (() => {
				try {
					using (mon) {
						BuildPackage (mon, project, configSel, settings, target);
					}	
				} catch (Exception ex) {
					mon.ReportError ("Unhandled error in packaging", null);
					LoggingService.LogError ("Unhandled exception in packaging", ex);
				} finally {
					mon.Dispose ();
				}
			}) {
				IsBackground = true,
				Name = "Mac Packaging",
			};
			t.Start ();
			
			return mon.AsyncOperation;
		}
Exemplo n.º 13
0
 public static void runUpload( )
 {
     if (Properties.Settings.Default.firstrun)
         return;
     NameValueCollection postdata = new NameValueCollection();
     postdata.Add("u", Properties.Settings.Default.username);
     postdata.Add("p", Properties.Settings.Default.password);
     if (!Clipboard.ContainsImage() && !Clipboard.ContainsText()) {
         nscrot.balloonText("No image or URL in clipboard!", 2);
         return;
     }
     if (!Clipboard.ContainsText()) {
         Image scrt = Clipboard.GetImage();
         System.Threading.Thread upld = new System.Threading.Thread(( ) =>
         {
             nscrot.uploadScreenshot(postdata, scrt);
         });
         upld.SetApartmentState(System.Threading.ApartmentState.STA);
         upld.Start();
     } else {
         string lURL = Clipboard.GetText();
         System.Threading.Thread shrt = new System.Threading.Thread(( ) =>
         {
             nscrot.shorten(lURL);
         });
         shrt.SetApartmentState(System.Threading.ApartmentState.STA);
         shrt.Start();
     }
 }
Exemplo n.º 14
0
 /// <summary>
 /// Plays the specified wav path.
 /// </summary>
 /// <param name="wavPath">The wav path.</param>
 public static void Play(string wavPath)
 {
     var thPlay = new System.Threading.Thread(THPlay);
     thPlay.IsBackground = true;
     threadWavPath = wavPath;
     thPlay.Start();
 }
Exemplo n.º 15
0
        public override int DiscoverDynamicCategories()
        {
            _thread = new System.Threading.Thread(new System.Threading.ThreadStart(ReadEPG));
            _thread.Start();
 
            Settings.Categories.Clear();
            RssLink cat = null;

            cat = new RssLink()
            {
                Name = "Channels",
                Other = "channels",
                Thumb = "http://arenavision.in/sites/default/files/FAVICON_AV2015.png",
                HasSubCategories = false
            };
            Settings.Categories.Add(cat);

            cat = new RssLink()
            {
                Name = "Agenda",
                Other = "agenda",
                Thumb = "http://arenavision.in/sites/default/files/FAVICON_AV2015.png",
                HasSubCategories = false
            };
            Settings.Categories.Add(cat);

            Settings.DynamicCategoriesDiscovered = true;
            return Settings.Categories.Count;
        }
Exemplo n.º 16
0
        public TravelModule()
        {
            load_RGS_table();

               thOneMinCalTask = new System.Threading.Thread(section_data_1min_task);
               thOneMinCalTask.Start();
        }
        public void Start(string portName, int baudRate, Parity parity, int dataBits, StopBits stopBits)
        {
            if (!GetAvailablePorts().Contains(portName))
            {
                throw new Exception(string.Format("Unknown serial port: {0}", portName));
            }

            // Start the timer to empty the receive buffer (in case data smaller than MAX_RECEIVE_BUFFER is received)
            _bufferTimer = new Timer();
            _bufferTimer.Interval = BUFFER_TIMER_INTERVAL;
            _bufferTimer.Elapsed += _bufferTimer_Elapsed;
            _bufferTimer.Start();

            // Instantiate new serial port communication
            _serialPort = new SerialPort(portName, baudRate, parity, dataBits, stopBits);

            // Open serial port communication
            _serialPort.Open();

            // Check that it is actually open
            if (!_serialPort.IsOpen)
            {
                throw new Exception(string.Format("Could not open serial port: {0}", portName));
            }

            _serialPort.ReadTimeout = 100; // Milliseconds

            _readThread = new System.Threading.Thread(ReadThread);
            _readThreadRunning = true;
            _readThread.Start();
        }
Exemplo n.º 18
0
 static ContainerVideoAudio()
 {
     _aqEvents = new ThreadBufferQueue<Tuple<EventDelegate, Effect, Effect>>(false, true);
     _cThreadEvents = new System.Threading.Thread(WorkerEvents);
     _cThreadEvents.IsBackground = true;
     _cThreadEvents.Start();
 }
Exemplo n.º 19
0
        public EventNotifyClient(string strIP,int port,bool bAutoRetry)
        {
            this.bAutoRetry = bAutoRetry;
            this.port = port;
            string[]ips=strIP.Split(new char[]{'.'});

            for(int i=0;i<4;i++)
                ipByte[i]=System.Convert.ToByte(ips[i]);

            //if (bAutoRetry)
            //{
                System.Threading.Thread th = new System.Threading.Thread(Connect_Task);
                th.Start();

            //}
            //else
            //{
            //    tcp = new System.Net.Sockets.TcpClient();

            //    tcp.Connect(new System.Net.IPAddress(ipByte), port);

            //    bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            //    connected = true;
            //    Console.WriteLine("NotifySerevr connected!");
            //    new System.Threading.Thread(ClientWork).Start();
            //}
        }
Exemplo n.º 20
0
        private Socket SOCKET; //receive socket

        #endregion Fields

        #region Methods

        public void Begin()
        {
            connect:
            SOCKET = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            SOCKET.Connect(IPAddress.Parse("127.0.0.1"), 2404);
            Console.WriteLine("S104 establish a link successfully, try to receive...");

            RCV_THREAD = new System.Threading.Thread(BeginReceive);
            RCV_THREAD.Start(SOCKET);

            while (true)
            {
                System.Threading.Thread.Sleep(4000);
                this.Send_UFram(Uflag.testfr_active);
                if (RCVD_NUM >= 20000)
                {
                    SOCKET.Shutdown(SocketShutdown.Receive);
                    RCV_THREAD.Abort();
                    System.Threading.Thread.Sleep(4000);
                    SOCKET.Shutdown(SocketShutdown.Send);
                    SOCKET.Dispose();

                    RCVD_NUM = 0;
                    goto connect;
                }
                if (DateTime.Now - lastTime > new TimeSpan(0, 0, 4))
                {
                    this.Send_SFram(RCVD_NUM);
                    Console.WriteLine("overtime send S fram...");
                }
            }
        }
Exemplo n.º 21
0
		public void StartTheApplication()
		{
			this.console = new FakeConsole();
			var taskList = new TaskList(console);
			this.applicationThread = new System.Threading.Thread(() => taskList.Run());
			applicationThread.Start();
		}
Exemplo n.º 22
0
        private void startPreview()
        {
            #region Create capture object if it is not already created

            if (_capture == null)
            {
                try
                {
                    _capture = new Capture();
                }
                catch (NullReferenceException excpt)
                {
                    MessageBox.Show(excpt.Message);
                }
            }

            #endregion

            #region Start the capture process and display in the preview window

            if (_capture != null)
            {
                //start the capture
                
                //Application.Idle += ProcessFrame;
                captureEnabled = true;
                System.Threading.Thread capThread = new System.Threading.Thread(new System.Threading.ThreadStart(captureThread));
                capThread.Start();

            }

            #endregion
        }
Exemplo n.º 23
0
 public watch()
 {
     t = new System.Threading.Thread(new System.Threading.ThreadStart(loop));
     s = new udpstate();
     s.e = new IPEndPoint(IPAddress.IPv6Any, 9887);
     s.u = new UdpClient(s.e);
 }
Exemplo n.º 24
0
 private void Ajouter_Click(object sender, EventArgs e)
 {
     System.Threading.Thread monthread = new System.Threading.Thread(new System.Threading.ThreadStart(Ajout));
     monthread.Start();
     this.Close();
     LoadPerso();
 }
Exemplo n.º 25
0
        public void Run()
        {
            if ((Site == null) || (Site.ID < 1))
            {
                return;
            }

            if ((MailTo == "") || (Subject == "") || (Body == ""))
            {
                new Log("System").Write("Send Email: MailTo, Subject or Body parameters error.");

                return;
            }

            EmailServer_From = Site.SiteOptions["Opt_EmailServer_From"].Value.ToString();
            EmailServer_EmailServer = Site.SiteOptions["Opt_EmailServer_EmailServer"].Value.ToString();
            EmailServer_User = Site.SiteOptions["Opt_EmailServer_UserName"].Value.ToString();
            EmailServer_Password = Site.SiteOptions["Opt_EmailServer_Password"].Value.ToString();

            if ((EmailServer_From == "") || (EmailServer_EmailServer == "") || (EmailServer_User == ""))
            {
                new Log("System").Write("Send Email: Read EmailServer configure fail.");

                return;
            }

            lock (this) // 确保临界区被一个 Thread 所占用
            {
                thread = new System.Threading.Thread(new System.Threading.ThreadStart(Do));
                thread.IsBackground = true;

                thread.Start();
            }
        }
Exemplo n.º 26
0
 protected void SendNonQuery(string stmt)
 {
     var pts = new System.Threading.ParameterizedThreadStart(_SendNonQuery);
     System.Threading.Thread t = new System.Threading.Thread(pts);
     t.Start(stmt);
     t.Join();
 }
Exemplo n.º 27
0
        public void Run()
        {
            //if ((ElectronTicket_HPCQ_Getway == "") || (ElectronTicket_HPCQ_UserName == "") || (ElectronTicket_HPCQ_UserPassword == ""))
            //{
            //    log.Write("ElectronTicket_XGCQ Task 参数配置不完整.");

            //    return;
            //}

            // 已经启动
            if (State == 1)
            {
                return;
            }

            lock (this) // 确保临界区被一个 Thread 所占用
            {
                State = 1;

                gCount1 = 0;

                thread = new System.Threading.Thread(new System.Threading.ThreadStart(Do));
                thread.IsBackground = true;

                thread.Start();

                log.Write("ElectronTicket_XGCQ Task Start.");
            }
        }
 public webclient(Stream netstream, string path)
 {
     Path = path;
     clientStream = netstream;
     System.Threading.Thread mythread = new System.Threading.Thread(new System.Threading.ThreadStart(thetar));
     mythread.Start();
 }
        private async void ActionWindowLoaded(object sender, RoutedEventArgs e)
        {
            if (count == 0)
            {
                id = Properties.Settings.Default.UserID;
                //ClientNameTextBox.Text = id;
                Active = true;
                Thread = new System.Threading.Thread(() =>
                {
                    Connection = new HubConnection(Host);
                    Proxy = Connection.CreateHubProxy("SignalRMainHub");

                    Proxy.On<string, string>("addmessage", (name, message) => OnSendData(DateTime.Now.ToShortTimeString()+"    ["+ name + "]\t " + message));
                    Proxy.On("heartbeat", () => OnSendData("Recieved heartbeat <3"));
                    Proxy.On<HelloModel>("sendHelloObject", hello => OnSendData("Recieved sendHelloObject " + hello.Molly + " " + hello.Age));

                    Connection.Start();

                    while (Active)
                    {
                        System.Threading.Thread.Sleep(10);
                    }
                }) { IsBackground = true };
                
                Thread.Start();
                
                count++;
            }

        }
Exemplo n.º 30
0
 // Insert / remove threads must be executed on a different thread as they are called within WndProc().
 // System.Windows.Forms.Invoke also wont work as we are within WndProc at the time.
 // QueryRemove does not use the thread as it requires an immediate response for the application to allow removal, just
 // dont call any COM stuff when responding to a QueryRemove
 public DriveDetector( Control control )
 {
     mControl = control;
     mControlHandle = mControl.Handle;
     mEventHandlerThread = new System.Threading.Thread( new System.Threading.ThreadStart( OnEventHandlerThreadStart ) );
     mEventHandlerThread.Start();
 }
Exemplo n.º 31
0
 public void StartRemoveWorkdir()
 {
     System.Threading.Thread workThread =
         new System.Threading.Thread(RemoveWorkdir);
     workThread.Start();
 }
Exemplo n.º 32
0
        private void Log_Load(object sender, EventArgs e)
        {
            if (MainV2.config["log_isarducopter"] != null)
            {
                CHK_arducopter.Checked = bool.Parse(MainV2.config["log_isarducopter"].ToString());
                CHK_arduplane.Checked  = bool.Parse(MainV2.config["log_isarduplane"].ToString());
                CHK_ardurover.Checked  = bool.Parse(MainV2.config["log_isardurover"].ToString());
            }

            status = serialstatus.Connecting;

            MainV2.comPort.giveComport = true;

            comPort = MainV2.comPort.BaseStream;

            comPort.DtrEnable = false;
            comPort.RtsEnable = false;

            try
            {
                Console.WriteLine("Log_load " + comPort.IsOpen);

                if (!comPort.IsOpen)
                {
                    comPort.Open();
                }

                Console.WriteLine("Log dtr");

                comPort.toggleDTR();

                Console.WriteLine("Log discard");

                comPort.DiscardInBuffer();

                Console.WriteLine("Log w&sleep");

                try
                {
                    // try provoke a responce
                    comPort.Write("\n\n?\r\n\n");
                }
                catch
                {
                }

                // 10 sec
                waitandsleep(10000);
            }
            catch (Exception ex)
            {
                log.Error("Error opening comport", ex);
                CustomMessageBox.Show("Error opening comport");
            }

            var t11 = new System.Threading.Thread(delegate()
            {
                var start = DateTime.Now;

                threadrun = true;

                readandsleep(100);

                try
                {
                    comPort.Write("\n\n\n\nexit\r\nlogs\r\n"); // more in "connecting"
                }
                catch
                {
                }

                while (threadrun)
                {
                    try
                    {
                        updateDisplay();

                        System.Threading.Thread.Sleep(10);
                        if (!comPort.IsOpen)
                        {
                            break;
                        }
                        while (comPort.BytesToRead >= 4)
                        {
                            comPort_DataReceived((object)null, (SerialDataReceivedEventArgs)null);
                        }
                    }
                    catch (Exception ex)
                    {
                        log.Error("crash in comport reader " + ex);
                    } // cant exit unless told to
                }
                log.Info("Comport thread close");
            })
            {
                Name = "comport reader"
            };

            t11.Start();

            // doesnt seem to work on mac
            //comPort.DataReceived += new SerialDataReceivedEventHandler(comPort_DataReceived);
        }
Exemplo n.º 33
0
 public void Down(string url, string savePath, string fileName, string type = "MV")
 {
     this.label18.Text = "正在下载" + type + "( " + fileName + " ) ";
     System.Threading.Thread th = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(Down_ThreadFun));
     th.Start(new string[] { url, savePath, fileName, type });
 }
Exemplo n.º 34
0
 public void start()
 {
     r = test;
     System.Threading.Thread t = new System.Threading.Thread(threadStart);
     t.Start(this);
 }
Exemplo n.º 35
0
        public Aja(DeviceScanner.NTV2DeviceInfo cDeviceInfo, uint nDeviceIndex)
            : base("Aja-" + nDeviceIndex + "_")
        {
            try
            {
                _nDeviceIndex      = nDeviceIndex;
                _nAudioQueueLength = 0;
                _bDoMultichannel   = true; // separate channels (if false, all channels provides one signal)
                string sMessage = "aja card [devid=" + cDeviceInfo.stWrapper.deviceID + "][device_id=" + cDeviceInfo.deviceIdentifier + "][multiformat=" + cDeviceInfo.stWrapper.multiFormat + "][ins=" + cDeviceInfo.stWrapper.numVidInputs + "][outs=" + cDeviceInfo.stWrapper.numVidOutputs + "]";
                if (bInput)
                {
                    throw new Exception("aja input mode has not relized yet");
                }
                else
                {
                    _eChannel = (AjaInterop.NTV2Channel)Preferences.nTargetChannel;

                    sMessage += "<br>\tsupported video formats:<br>\t\t" + cDeviceInfo.videoFormatsList.ToEnumerationString("<br>\t\t", "", null, null, true);
                    sMessage += "<br>\tsupported audio Bits Per Sample:<br>\t\t" + cDeviceInfo.audioBitsPerSampleList.ToEnumerationString("<br>\t\t", "", null, null, true);
                    sMessage += "<br>\tsupported audio in sources:<br>\t\t" + cDeviceInfo.audioInSourceList.ToEnumerationString("<br>\t\t", "", null, null, true);
                    sMessage += "<br>\tsupported audio out sources:<br>\t\t" + cDeviceInfo.audioOutSourceList.ToEnumerationString("<br>\t\t", "", null, null, true);
                    sMessage += "<br>\tsupported audio sample rates:<br>\t\t" + cDeviceInfo.audioSampleRateList.ToEnumerationString("<br>\t\t", "", null, null, true);
                    (new Logger("Aja", sName)).WriteNotice(sMessage);

                    if (Preferences.bAudio)
                    {
                        _nAudioChannelsQty = Preferences.nAudioChannelsQty;  // can be only 6, 8, 16
                        if (_nAudioChannelsQty != 6 && _nAudioChannelsQty != 8 && _nAudioChannelsQty != 16)
                        {
                            throw new Exception("unsupported audio channels qty (only 6, 8, 16) [" + _nAudioChannelsQty + "]");
                        }

                        switch (Preferences.nAudioSamplesRate)
                        {
                        case 48000:
                            _eAudioSampleRate = AjaInterop.NTV2AudioRate.NTV2_AUDIO_48K;
                            break;

                        case 96000:
                            _eAudioSampleRate = AjaInterop.NTV2AudioRate.NTV2_AUDIO_96K;
                            throw new Exception("96000 audio sample rate has not realised yet");

                        default:
                            throw new Exception("unsupported audio sample rate [" + Preferences.nAudioSamplesRate + "]");
                        }
                        //for (int nIndx = 0; _nAudioFrameSize_InBytes > nIndx; nIndx++)
                        //    Marshal.WriteByte(_pAudioSamplesBuffer, nIndx, 0);
                    }

                    _cCard = new NTV2Card(_nDeviceIndex, Preferences.bAudio, _eChannel, ePixelFormat, AjaTools.NTV2ChannelToOutputDestination(_eChannel), eVideoFormat, _eAudioSampleRate, _bDoMultichannel, _nAudioChannelsQty, false, false);
                    _cCard.SetVideoFormat();
                    ushort nW, nH;
                    _cCard.GetActiveFrameDimensions(out nW, out nH);
                    stArea          = new Area(0, 0, nW, nH);
                    _nVideoBytesQty = stArea.nWidth * stArea.nHeight * 4;

                    AjaInterop.NTV2FrameRate eFR;
                    switch (eFR = _cCard.GetCurrentFramrRate())
                    {
                    case AjaInterop.NTV2FrameRate.NTV2_FRAMERATE_2500:
                        Preferences.nFPS = 25;
                        break;

                    default:
                        throw new Exception("unsupported frame rate [" + eFR + "][video_format=" + _eVideoFormat + "]");
                    }
                    if (Preferences.bAudio)
                    {
                        _nAudioBufferCapacity_InSamples = Preferences.nAudioSamplesPerFrame * Preferences.nQueueDeviceLength;
                        _nChannelBytesQty = Preferences.nAudioSamplesPerFrame * Preferences.nAudioByteDepth;
                        _nAudioBytesQty   = _nAudioChannelsQty * _nChannelBytesQty;
                    }
                    _AjaFramesBufferMaxCount = 3;
                    _AjaFramesVideoBuffer    = new ThreadBufferQueue <Frame.Video>(_AjaFramesBufferMaxCount, true, true);
                    _AjaFramesVideoToDispose = new ThreadBufferQueue <Frame.Video>(false, false);
                    if (Preferences.bAudio)
                    {
                        _AjaFramesAudioBuffer    = new ThreadBufferQueue <Frame.Audio>(_AjaFramesBufferMaxCount, true, true);
                        _AjaFramesAudioToDispose = new ThreadBufferQueue <Frame.Audio>(false, false);
                    }
                    _bDoWritingFrames = false;
#if DEBUG
                    _aqWritingFrames            = new Queue <byte[]>();
                    _cThreadWritingFramesWorker = new System.Threading.Thread(WritingFramesWorker);
                    _cThreadWritingFramesWorker.IsBackground = true;
                    _cThreadWritingFramesWorker.Priority     = System.Threading.ThreadPriority.Normal;
                    _cThreadWritingFramesWorker.Start();
#endif

                    if (null != Preferences.cDownStreamKeyer)
                    {
                        throw new Exception("aja keyer has not realised yet");
                    }
                }
            }
            catch (Exception ex)
            {
                (new Logger("Aja", sName)).WriteError(ex);
                throw;
            }
        }
Exemplo n.º 36
0
        public void StartWorkerThread()
        {
            var thread = new System.Threading.Thread(RunWorker);

            thread.Start(this);
        }
Exemplo n.º 37
0
 public void StartRemoveAllProviderData()
 {
     System.Threading.Thread workThread =
         new System.Threading.Thread(RemoveAllProviderData);
     workThread.Start();
 }
Exemplo n.º 38
0
        public void ReadGameDirectory(string path)
        {
            DataPath      = path;
            IsInitialized = false;

            System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
            stopwatch.Start();

            System.Threading.Thread workerThread = null;

            loadWaitWorker = new BackgroundWorker {
                WorkerReportsProgress = true
            };
            loadWaitWorker.DoWork += ((s, e) =>
            {
                try
                {
                    System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture;
                    workerThread = System.Threading.Thread.CurrentThread;

                    loadWaitWorker.ReportProgress(-1, "Reading game directory...");
                    ReadHeaderIdentify();

                    PrepareDirectoryUnpack();

                    loadWaitWorker.ReportProgress(-1, "Generating character map...");
                    EtrianString.GameVersion = Version;

                    loadWaitWorker.ReportProgress(-1, "Initializing font renderers...");
                    ushort characterCount = (ushort)((SmallFontInfoOffset - MainFontInfoOffset) / 2);
                    MainFontRenderer = new FontRenderer(this, Path.Combine(path, MainFontFilename + ".ntft"), MainFontInfoOffset, characterCount);
                    SmallFontRenderer = new FontRenderer(this, Path.Combine(path, SmallFontFilename + ".ntft"), SmallFontInfoOffset, characterCount);

                    MessageFiles = ReadDataTablesByExtension(new string[] { ".mbb", ".tbb" }, messageDirs);
                    dataTableFiles = ReadDataTablesByExtension(new string[] { ".tbb" }, dataDirs);

                    archives = ReadArchiveFiles(archiveDirs);

                    EnsureMessageTableIntegrity();
                    GenerateDictionariesLists();

                    changedMessageFiles = new List <TableFile>();

                    ParsedData = ParseDataTables();
                    changedParsedData = new List <BaseParser>();

                    MapDataFiles = ReadMapDataFiles(mapDataDirs);
                    MapTileData = ParseMapData();
                    changedMapTileData = new List <BaseTile>();

                    TextureFilePaths = FindTextureFiles(textureDataDirs);

                    CleanStringDictionaries();
                    GenerateOtherDictionaries();

                    loadWaitWorker.ReportProgress(-1, "Finished loading.");
                    IsInitialized = true;
                }
                catch (System.Threading.ThreadAbortException) { }
                catch (GameDataManagerException gameException)
                {
                    GUIHelpers.ShowErrorMessage(
                        "Application Error", "An error occured while loading the game data.", "Please ensure you've selected a valid game data directory.",
                        gameException.Message, gameException.ToString(), (IntPtr)Program.MainForm.Invoke(new Func <IntPtr>(() => { return(Program.MainForm.Handle); })));
                }
#if !DEBUG
                catch (Exception exception)
                {
                    GUIHelpers.ShowErrorMessage(
                        "Application Error", "The application performed an illegal operation.", "Please contact a developer with the details of this message.",
                        exception.Message, exception.ToString(), (IntPtr)Program.MainForm.Invoke(new Func <IntPtr>(() => { return(Program.MainForm.Handle); })));
                }
#endif
            });
            loadWaitWorker.ProgressChanged += ((s, e) =>
            {
                string message = (e.UserState as string);
                if (loadWaitDialog.Cancel)
                {
                    workerThread.Abort();
                    Program.Logger.LogMessage("Loading aborted.");
                    Program.MainForm.StatusText = "Ready";
                    return;
                }

                loadWaitDialog.Details = message;
                Program.Logger.LogMessage(true, message);
            });
            loadWaitWorker.RunWorkerCompleted += ((s, e) =>
            {
                loadWaitDialog.Close();
                stopwatch.Stop();
                Program.Logger.LogMessage("Game directory read in {0:0.000} sec...", stopwatch.Elapsed.TotalSeconds);
            });
            loadWaitWorker.RunWorkerAsync();

            loadWaitDialog = new ProgressDialog()
            {
                Title = "Loading", InstructionText = "Loading game data.", Text = "Please wait while the game data is being loaded...", ParentForm = Program.MainForm
            };
            loadWaitDialog.Show(Program.MainForm);
        }
Exemplo n.º 39
0
        private void WaitAndFinishDatabaseUpdate()
        {
            if (m_PendingStatuses == null)
            {
                return;
            }

            if (DoTraceLogs)
            {
                Debug.Log($"Finished Update Database at {EditorApplication.timeSinceStartup:0.00}");
            }

            EditorApplication.update -= WaitAndFinishDatabaseUpdate;
            m_WorkerThread            = null;

            var statuses = m_PendingStatuses;

            m_PendingStatuses = null;
            StatusDatas.Clear();

            // Mark update as finished.
            PendingUpdate = false;

            // If preferences were changed while waiting.
            if (!IsActive)
            {
                return;
            }

            // Process the gathered statuses in the main thread, since Unity API is not thread-safe.
            foreach (var foundStatusData in statuses)
            {
                // Because structs can't be modified in foreach.
                var statusData = foundStatusData;

                // Meta statuses are also considered. They are shown as the asset status.
                if (statusData.Path.EndsWith(".meta", StringComparison.OrdinalIgnoreCase))
                {
                    statusData.Path = statusData.Path.Substring(0, statusData.Path.LastIndexOf(".meta"));
                }

                // Conflicted is with priority.
                if (statusData.IsConflicted)
                {
                    statusData.Status = VCFileStatus.Conflicted;
                }

                var guid = AssetDatabase.AssetPathToGUID(statusData.Path);
                if (string.IsNullOrEmpty(guid))
                {
                    // Files were added in the background without Unity noticing.
                    // When the user focuses on Unity, it will refresh them as well.
                    continue;
                }

                // File was added to the repository but is missing in the working copy.
                // The proper way to check this is to parse the working revision from the svn output (when used with -u)
                if (statusData.RemoteStatus == VCRemoteFileStatus.Modified &&
                    statusData.Status == VCFileStatus.Normal &&
                    string.IsNullOrEmpty(guid)
                    )
                {
                    continue;
                }

                // TODO: Test tree conflicts.
                SetStatusData(guid, statusData, false);

                AddModifiedFolders(statusData);
            }

            DatabaseChanged?.Invoke();
        }
Exemplo n.º 40
0
 public void StartGetUserKey()
 {
     System.Threading.Thread workThread =
         new System.Threading.Thread(GetUserKey);
     workThread.Start();
 }
Exemplo n.º 41
0
        private void Terminal_Load(object sender, EventArgs e)
        {
            try
            {
                MainV2.giveComport = true;

                if (comPort.IsOpen)
                {
                    comPort.Close();
                }

                comPort.ReadBufferSize = 1024 * 1024;

                comPort.PortName = MainV2.comPortName;

                comPort.Open();

                comPort.toggleDTR();

                System.Threading.Thread t11 = new System.Threading.Thread(delegate()
                {
                    threadrun = true;

                    DateTime start = DateTime.Now;

                    while ((DateTime.Now - start).TotalMilliseconds < 2000)
                    {
                        try
                        {
                            if (comPort.BytesToRead > 0)
                            {
                                comPort_DataReceived((object)null, (SerialDataReceivedEventArgs)null);
                            }
                        }
                        catch { return; }
                    }
                    try
                    {
                        comPort.Write("\n\n\n");

                        System.Threading.Thread.Sleep(500);

                        comPort.Write("\r\r\r?\r");
                    }
                    catch { return; }

                    while (threadrun)
                    {
                        try
                        {
                            System.Threading.Thread.Sleep(10);
                            if (inlogview)
                            {
                                continue;
                            }
                            if (!comPort.IsOpen)
                            {
                                break;
                            }
                            if (comPort.BytesToRead > 0)
                            {
                                comPort_DataReceived((object)null, (SerialDataReceivedEventArgs)null);
                            }
                        }
                        catch { }
                    }

                    comPort.DtrEnable = false;

                    if (threadrun == false)
                    {
                        comPort.Close();
                    }
                    Console.WriteLine("Comport thread close");
                });
                t11.IsBackground = true;
                t11.Name         = "Terminal serial thread";
                t11.Start();

                // doesnt seem to work on mac
                //comPort.DataReceived += new SerialDataReceivedEventHandler(comPort_DataReceived);

                TXT_terminal.AppendText("Opened com port\r\n");
                inputStartPos = TXT_terminal.SelectionStart;
            }
            catch (Exception) { TXT_terminal.AppendText("Cant open serial port\r\n"); return; }

            TXT_terminal.Focus();
        }
Exemplo n.º 42
0
 private void buttonProcessGPX_Click(object sender, EventArgs e)
 {
     System.Threading.Thread th = new System.Threading.Thread(GPXProcessingThread);
     th.Start();
 }
Exemplo n.º 43
0
 /// <summary>
 /// Initializes a new instance of the Thread class.
 /// </summary>
 /// <param name="start">A ThreadStart delegate that references the methods to be invoked when this thread begins executing</param>
 /// <param name="name">The name of the thread</param>
 public ThreadClass(System.Threading.ThreadStart start, String name)
 {
     threadField = new System.Threading.Thread(start);
     Name        = name;
 }
Exemplo n.º 44
0
        private void BUT_connect_Click(object sender, EventArgs e)
        {
            if (comPort.IsOpen)
            {
                threadrun = false;
                comPort.Close();
                BUT_connect.Text = Strings.Connect;
            }
            else
            {
                try
                {
                    comPort.PortName = CMB_serialport.Text;
                }
                catch { CustomMessageBox.Show(Strings.InvalidPortName, Strings.ERROR); return; }
                try {
                    comPort.BaudRate = int.Parse(CMB_baudrate.Text);
                }
                catch { CustomMessageBox.Show(Strings.InvalidBaudRate, Strings.ERROR); return; }
                try {
                    comPort.Open();
                }
                catch (Exception ex)
                {
                    CustomMessageBox.Show(Strings.ErrorConnecting + "\n" + ex.ToString(), Strings.ERROR); return;
                }


                string alt = "100";

                if (MainV2.comPort.MAV.cs.firmware == MainV2.Firmwares.ArduCopter2)
                {
                    alt = (10 * CurrentState.multiplierdist).ToString("0");
                }
                else
                {
                    alt = (100 * CurrentState.multiplierdist).ToString("0");
                }
                if (DialogResult.Cancel == InputBox.Show("Enter Alt", "Enter Alt (relative to home alt)", ref alt))
                {
                    return;
                }

                intalt = (int)(100 * CurrentState.multiplierdist);
                if (!int.TryParse(alt, out intalt))
                {
                    CustomMessageBox.Show(Strings.InvalidAlt, Strings.ERROR);
                    return;
                }

                intalt = (int)(intalt / CurrentState.multiplierdist);

                t12 = new System.Threading.Thread(new System.Threading.ThreadStart(mainloop))
                {
                    IsBackground = true,
                    Name         = "Nmea Input"
                };
                t12.Start();

                BUT_connect.Text = Strings.Stop;
            }
        }
Exemplo n.º 45
0
 /// <summary>
 /// Initializes a new instance of the Thread class.
 /// </summary>
 /// <param name="name">The name of the thread</param>
 public ThreadClass(String name)
 {
     threadField = new System.Threading.Thread(Run);
     Name        = name;
 }
Exemplo n.º 46
0
        private void BUT_connect_Click(object sender, EventArgs e)
        {
            if (comPort.IsOpen)
            {
                threadrun = false;
                comPort.Close();
                BUT_connect.Text = Strings.Connect;
            }
            else
            {
                try
                {
                    switch (CMB_serialport.Text)
                    {
                    case "TCP Host - 14551":
                    case "TCP Host":
                        comPort = new TcpSerial();
                        CMB_baudrate.SelectedIndex = 0;
                        listener = new TcpListener(System.Net.IPAddress.Any, 14551);
                        listener.Start(0);
                        listener.BeginAcceptTcpClient(new AsyncCallback(DoAcceptTcpClientCallback), listener);
                        BUT_connect.Text = Strings.Stop;
                        break;

                    case "TCP Client":
                        comPort = new TcpSerial()
                        {
                            retrys = 999999, autoReconnect = true
                        };
                        CMB_baudrate.SelectedIndex = 0;
                        break;

                    case "UDP Host - 14551":
                        comPort = new UdpSerial();
                        CMB_baudrate.SelectedIndex = 0;
                        break;

                    case "UDP Client":
                        comPort = new UdpSerialConnect();
                        CMB_baudrate.SelectedIndex = 0;
                        break;

                    default:
                        comPort          = new SerialPort();
                        comPort.PortName = CMB_serialport.Text;
                        break;
                    }
                }
                catch
                {
                    CustomMessageBox.Show(Strings.InvalidPortName);
                    return;
                }
                try
                {
                    comPort.BaudRate = int.Parse(CMB_baudrate.Text);
                }
                catch
                {
                    CustomMessageBox.Show(Strings.InvalidBaudRate, Strings.ERROR);
                    return;
                }
                try
                {
                    if (listener == null)
                    {
                        comPort.Open();
                    }
                }
                catch (Exception ex)
                {
                    CustomMessageBox.Show(Strings.ErrorConnecting + "\n" + ex.ToString(), Strings.ERROR);
                    return;
                }

                t12 = new System.Threading.Thread(new System.Threading.ThreadStart(mainloop))
                {
                    IsBackground = true,
                    Name         = "movingbase Input"
                };
                t12.Start();

                BUT_connect.Text = Strings.Stop;
            }
        }
Exemplo n.º 47
0
        private void AddFilesThread(object arg)
        {
            try
            {
                string[] files = (string[])arg;
                this.BeginUpdateControl(this.listView待处理文件);
                this.SetPropertyValue(this.toolStripProgressBar1, "Maximum", files.Length);
                for (int i = 0; i < files.Length && this.请求中止全部任务 == false; i++)
                {
                    string file = files[i];
                    this.SetPropertyValue(this.toolStripProgressBar1, "Value", i);
                    this.正在处理的文件 = file;
                    if (this.ContainsListViewItem(this.listView待处理文件, file))
                    {
                        continue;
                    }
                    string ext = System.IO.Path.GetExtension(file);
                    foreach (var tmp in this.ImageFormats)
                    {
                        if (tmp.Extension == ext.ToLower())
                        {
                            if (!this.LargeImageList.Images.ContainsKey(file))
                            {
                                System.Drawing.Image img = Thinksea.Image.GetThumbnailImage(file, this.LargeImageList.ImageSize.Width, this.LargeImageList.ImageSize.Height, true, true, Thinksea.eImageQuality.Low, false, System.Drawing.Color.Transparent);
                                //System.Drawing.Image img = System.Drawing.Bitmap.FromFile(file);
                                this.AddFileToImageList(this.LargeImageList, file, img);
                            }

                            System.IO.FileInfo fileInfo = new System.IO.FileInfo(file);
                            ListViewItem       item     = new ListViewItem();
                            item.Name = file;
                            item.Text = file;
                            item.SubItems.Add(fileInfo.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss"));
                            item.SubItems.Add(string.Format("{0:N0} KB", System.Math.Ceiling(fileInfo.Length / 1024D)));
                            Size imgSize = Thinksea.Image.GetImageSize(file);
                            item.SubItems.Add(string.Format("{0} x {1}", imgSize.Width, imgSize.Height));
                            //item.ImageKey = file;
                            item.ImageIndex = this.LargeImageList.Images.IndexOfKey(file);
                            item.Tag        = file;
                            this.AddListViewItem(this.listView待处理文件, item);
                            break;
                        }
                    }
                    this.SetPropertyValue(this.toolStripStatusLabel文件总数, "Text", string.Format((string)this.toolStripStatusLabel文件总数.Tag, this.listView待处理文件.Items.Count));
                }
                if (this.请求中止全部任务)
                {
                    //this.SetPropertyValue(this.toolStripStatusLabel正在处理的文件, "Text", "用户中止任务。");
                    this.正在处理的文件 = "用户中止任务。";
                }
                else
                {
                    this.SetPropertyValue(this.toolStripProgressBar1, "Value", files.Length);
                    //this.SetPropertyValue(this.toolStripStatusLabel正在处理的文件, "Text", "任务已完成。");
                    this.正在处理的文件 = "任务已完成。";
                }
            }
            finally
            {
                this.EndUpdateControl(this.listView待处理文件);
                this.SetPropertyValue(this.toolStripButton添加文件, "Enabled", true);
                this.SetPropertyValue(this.toolStripButton添加文件夹, "Enabled", true);
                this.SetPropertyValue(this.toolStripButton开始, "Enabled", (this.listView待处理文件.Items.Count > 0));
                //this.timer1.Stop();
                this.thread添加文件 = null;
            }
        }
Exemplo n.º 48
0
 /// <summary>
 /// Initializes a new instance of the Thread class.
 /// </summary>
 /// <param name="start">A ThreadStart delegate that references the methods to be invoked when this thread begins executing</param>
 public ThreadClass(System.Threading.ThreadStart start)
 {
     threadField = new System.Threading.Thread(start);
 }
Exemplo n.º 49
0
        // --------------------- //

        // Basculer sur RCV - Borication //
        private void RcvBorication_Click(object sender, EventArgs e)
        {
            System.Threading.Thread rcvboricationThread = new System.Threading.Thread(new System.Threading.ThreadStart(OuvrirRcvBorication));
            rcvboricationThread.Start();
            this.Close();
        }
Exemplo n.º 50
0
 /// <summary>
 /// Initializes a new instance of the ThreadClass class
 /// </summary>
 public ThreadClass()
 {
     threadField = new System.Threading.Thread(Run);
 }
Exemplo n.º 51
0
        // ------------------------ //

        // Basculer sur RCV - Réglage platine //
        private void RcvReglagePlatine_Click(object sender, EventArgs e)
        {
            System.Threading.Thread rcvreglageplatineThread = new System.Threading.Thread(new System.Threading.ThreadStart(OuvrirRcvReglagePlatine));
            rcvreglageplatineThread.Start();
            this.Close();
        }
Exemplo n.º 52
0
        void dicks()
        {
            Logger.pcm.a("prism thread");
            long bufSize = settings.samplerate * 10;

            byte[] buffer          = new byte[bufSize * 4];
            System.IO.FileStream w = null;
            if (settings.recPCM)
            {
                Logger.pcm.a("open dump target");
                w = new System.IO.FileStream(string.Format("Loopstream-{0}.pcm", DateTime.Now.ToString("yyyy-MM-dd_HH.mm.ss")), System.IO.FileMode.Create);
            }

            // Create encoders first, but do not feed data
            if (settings.mp3.enabled)
            {
                encoders.Add(new LSLame(settings, this));
            }
            if (settings.ogg.enabled)
            {
                encoders.Add(new LSVorbis(settings, this));
            }
            // Note that encoders handle creation of and connecting to shouters

            // start the thread watching encoders/shouters and restarting the crashed ones
            System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(medic));
            t.Name = "LSPcm_Medic";
            t.Start();

            // Finally, reposition PCM pointer to minimize latency
            // (and chance of lost packets because icecast a bitch)
            outlet.setReadPtr(0.2);

            // PCM reader loop, passing on to encoders/shouters
            //List<string> toclip = new List<string>();
            try
            {
                while (true)
                {
                    if (qt())
                    {
                        break;
                    }
                    int avail = outlet.avail();
                    if (avail > 1024)
                    {
                        //Console.Write('.');
                        Logger.pcm.a("reading pcm data");
                        int i = wp16.Read(buffer, 0, (outlet.avail() / 4) * 4);
                        //toclip.Add((DateTime.UtcNow.Ticks / 10000) + ", " + i);
                        Logger.pcm.a("locking for write");
                        lock (locker)
                        {
                            int _soffMono   = soffMono;
                            int _soffStereo = soffStereo;
                            for (int a = 0; a < encoders.Count; a++)
                            {
                                LSEncoder enc = encoders[a];
                                if (!enc.crashed && enc.stdin != null)
                                {
                                    bool silence = false;
                                    if (enc.GetType() == typeof(LSVorbis))
                                    {
                                        silence = true;
                                        for (int ofs = 1; ofs < i; ofs += 16)
                                        {
                                            int v = buffer[ofs];
                                            if (v > 0x80)
                                            {
                                                v = 255 - v;
                                            }
                                            if (v > 1)
                                            {
                                                silence = false;
                                                break;
                                            }
                                        }
                                        if (silence)
                                        {
                                            Logger.pcm.a("SILENCE to " + enc.enc.ext);
                                            soffMono   = _soffMono;
                                            soffStereo = _soffStereo;
                                            bool stereo = enc.enc.channels == LSSettings.LSChannels.stereo;
                                            enc.eat(barf(i, stereo), i);
                                        }
                                    }
                                    if (!silence)
                                    {
                                        Logger.pcm.a("writing to " + enc.enc.ext);
                                        enc.eat(buffer, i);
                                    }
                                }
                            }
                        }
                        if (w != null)
                        {
                            Logger.pcm.a("writing to dump");
                            w.Write(buffer, 0, i);
                        }
                    }
                    Logger.pcm.a("waiting for pcm data");
                    System.Threading.Thread.Sleep(70); // value selected by fair dice roll

                    //if (toclip.Count > 1000) break;
                }
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show("pcm reader / enc prism just died\n\nthought you might want to know\n\n===========================\n" + ex.Message + "\n" + ex.StackTrace);
            }
            //StringBuilder sb = new StringBuilder();
            //foreach (string str in toclip) sb.AppendLine(str);
            //System.IO.File.WriteAllText("asdf", sb.ToString());

            Console.WriteLine("shutting down encoder prism");
            if (w != null)
            {
                w.Close();
            }
        }
Exemplo n.º 53
0
 // Basculer sur PTR K - Dilution //
 private void PtrKDilution_Click(object sender, EventArgs e)
 {
     System.Threading.Thread ptrkdilutionThread = new System.Threading.Thread(new System.Threading.ThreadStart(OuvrirPtrKDilution));
     ptrkdilutionThread.Start();
     this.Close();
 }
Exemplo n.º 54
0
        // ------------------------ //

        // Basculer sur Calcul Cb //
        private void CalculCb_Click(object sender, EventArgs e)
        {
            System.Threading.Thread CalculCbThread = new System.Threading.Thread(new System.Threading.ThreadStart(OuvrirCalculCb));
            CalculCbThread.Start();
            this.Close();
        }
Exemplo n.º 55
0
        public void TestsThreading()
        {
            System.Threading.ManualResetEvent mre = new System.Threading.ManualResetEvent(false);

            int countIn = 0;

            //In a thread populate
            System.Threading.Thread enqueueThread = new System.Threading.Thread(() =>
            {
                while (countIn < Amount)
                {
                    ++LastInputOutput;

                    if (LinkedStack.TryPush(ref LastInputOutput))
                    {
                        System.Console.WriteLine("pushThread: " + LastInputOutput);

                        ++countIn;

                        mre.Set();

                        System.Threading.Thread.Sleep(1);
                    }
                }

                if (LinkedStack.IsEmpty)
                {
                    System.Console.WriteLine("pushThread Empty");
                }

                System.Console.WriteLine("pushThread Exit");
            });

            int countOut = 0;

            //In another thread write
            System.Threading.Thread dequeueThread = new System.Threading.Thread(() =>
            {
                while (countOut < Amount)
                {
                    long dequeue;

                    if (LinkedStack.TryPop(out dequeue))
                    {
                        ++countOut;

                        System.Console.WriteLine("popThread: " + dequeue);

                        mre.Set();

                        System.Threading.Thread.Sleep(2);
                    }
                }

                //if (false == LinkedStack.IsEmpty) throw new System.Exception("popThread");

                System.Console.WriteLine("popThread Exit");
            });

            enqueueThread.Start();

            dequeueThread.Start();

            while (countOut == 0 && countIn == 0)
            {
                mre.WaitOne(0);
            }

            while (countOut < Amount)
            {
                mre.Reset();

                System.Console.WriteLine("Count: " + LinkedStack.Count + "," + "CountIn: " + countIn + "," + "CountOut: " + countOut);

                new System.Threading.Thread(() =>
                {
                    try
                    {
                        System.Console.WriteLine("Enumerate Count: " + LinkedStack.Count);

                        long peek = 0;

                        if (LinkedStack.TryPeek(ref peek))
                        {
                            System.Console.WriteLine("Enumerate TryPeek: " + peek);
                        }

                        if (false == LinkedStack.IsEmpty)
                        {
                            System.Console.WriteLine("Enumerate Last: " + LinkedStack.Last.Value);

                            //Increases test time by 10 and keeps the main thread busy
                            ////foreach (long value in LinkedStack)
                            ////{
                            ////    System.Console.WriteLine("Enumerate Value: " + value);
                            ////}
                        }
                    }
                    catch { }
                })
                {
                    Priority = System.Threading.ThreadPriority.Highest
                }.Start();

                mre.WaitOne(0);
            }

            if (countIn != countOut)
            {
                throw new System.Exception("count");
            }

            if (false == LinkedStack.IsEmpty)
            {
                throw new System.Exception("IsEmpty");
            }

            System.Console.WriteLine("Count: " + LinkedStack.Count);
        }
Exemplo n.º 56
0
        // --------------------- //

        // Basculer sur PTR K - Appoint SED //
        private void PtrKAppointSED_Click(object sender, EventArgs e)
        {
            System.Threading.Thread ptrkappointThread = new System.Threading.Thread(new System.Threading.ThreadStart(OuvrirPtrKAppointSED));
            ptrkappointThread.Start();
            this.Close();
        }
Exemplo n.º 57
0
        static void Main(string[] args)
        {
            Console.WriteLine("====**************** PDF.NET SOD 控制台测试程序 **************====");
            Assembly coreAss = Assembly.GetAssembly(typeof(AdoHelper));//获得引用程序集

            Console.WriteLine("框架核心程序集 PWMIS.Core Version:{0}", coreAss.GetName().Version.ToString());
            Console.WriteLine();
            Console.WriteLine("  应用程序配置文件默认的数据库配置信息:\r\n  当前使用的数据库类型是:{0}\r\n  连接字符串为:{1}\r\n  请确保数据库服务器和数据库是否有效且已经初始化过建表脚本(项目下的2个sql脚本文件),\r\n继续请回车,退出请输入字母 Q ."
                              , MyDB.Instance.CurrentDBMSType.ToString(), MyDB.Instance.ConnectionString);
            Console.WriteLine("=====Power by Bluedoctor,2015.2.8 http://www.pwmis.com/sqlmap ====");
            string read = Console.ReadLine();

            if (read.ToUpper() == "Q")
            {
                return;
            }

            IDataParameter[] paraArr = new IDataParameter[] {
                MyDB.Instance.GetParameter("P1", 111),
                MyDB.Instance.GetParameter("P2", "abc'ee<edde/>e"),
            };

            string str = DbParameterSerialize.Serialize(paraArr);

            Console.WriteLine("测试参数序列化:{0}", str);
            IDataParameter[] paraArr2 = DbParameterSerialize.DeSerialize(str, MyDB.Instance);
            Console.WriteLine("测试反序列化成功!");

            LocalDbContext localDb = new LocalDbContext();
            var            entitys = localDb.ResolveAllEntitys();

            localDb.CurrentDataBase.RegisterCommandHandle(new TransactionLogHandle());
            Table_User user = new Table_User();

            user.Name     = "zhang san";
            user.Height   = 1.8f;
            user.Birthday = new DateTime(1980, 1, 1);
            user.Sex      = true;
            localDb.Add(user);

            user.Name     = "lisi";
            user.Height   = 1.6f;
            user.Birthday = new DateTime(1982, 3, 1);
            user.Sex      = false;
            localDb.Add(user);
            Console.WriteLine("测试 生成事务日志 成功!(此操作将写入事务日志信息到数据库中。)");

            //var logList = localDb.QueryList<MyCommandLogEntity>(OQL.From(new MyCommandLogEntity()).Select().END);
            AdoHelper db      = MyDB.GetDBHelperByConnectionName("local");
            var       logList = OQL.From <MyCommandLogEntity>().Select().END.ToList(db);

            foreach (MyCommandLogEntity log in logList)
            {
                var paras = DbParameterSerialize.DeSerialize(log.ParameterInfo, db);
                int count = db.ExecuteNonQuery(log.CommandText, log.CommandType, paras);
                Console.WriteLine("执行语句:{0} \r\n 受影响行数:{1}", log.CommandText, count);
            }
            Console.WriteLine("测试 运行事务日志 成功!(此操作将事务日志的操作信息回放执行。)");

            //写入10000条日志,有缓存,可能不会写完
            Console.WriteLine("测试日志写入10000 条信息...");
            CommandLog loger = new CommandLog();

            for (int t = 0; t <= 1; t++)
            {
                System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(WriteLog));
                thread.Name = "thread" + t;
                thread.Start(loger);
            }

            loger.Flush();
            Console.WriteLine("按任意键继续");
            Console.ReadLine();

            EntityUser  etu = new EntityUser();
            ITable_User itu = etu.AsEntity();
            DateTime    dtt = itu.Birthday;



            //测试 AdoHelper的并发能力
            //for (int i = 0; i < 100; i++)
            //{
            //    System.Threading.Thread t = new System.Threading.Thread(
            //        new System.Threading.ParameterizedThreadStart(TestDataSetAndOQL));
            //    t.Name = "thread "+i;
            //    t.Start();

            //}

            //测试生成列的脚本
            EntityCommand ecmd         = new EntityCommand(new Table_User(), new SqlServer());
            string        table_script = ecmd.CreateTableCommand;

            Console.Write("1,测试 OpenSession 长连接数据库访问...");
            TestDataSetAndOQL(null);
            Console.WriteLine("OK");
            //
            Console.WriteLine("2,测试OQL 转SQL...");
            RoadTeam.Model.CS.TbCsEvent CsEvent = new RoadTeam.Model.CS.TbCsEvent();
            CsEvent.EventID = 1;
            OQL oql = OQL.From(CsEvent)
                      .Select(CsEvent.EventCheck, CsEvent.EventCheckInfo, CsEvent.EventCheckor, CsEvent.EventCheckTime)
                      .Where(CsEvent.EventID)
                      .END;

            Console.WriteLine(oql.ToString());
            Console.WriteLine("-----------------------");

            RoadTeam.Model.CS.TbCsEvent CsEvent2 = new RoadTeam.Model.CS.TbCsEvent();
            CsEvent.EventID = 1;
            OQL oql2 = OQL.From(CsEvent2)
                       .Select(true, CsEvent2.EventCheck, CsEvent2.EventCheckInfo, CsEvent2.EventCheckor, CsEvent2.EventCheckTime)
                       .Where(CsEvent2.EventID)
                       .END;

            Console.WriteLine(oql2.ToString());
            Console.WriteLine("-----------------------");
            Console.WriteLine("OK");
            //
            Console.Write("3,测试实体类动态增加虚拟属性...");
            UserModels um1 = new UserModels();

            um1.AddPropertyName("TestName");
            um1["TestName"] = 123;
            int testi = (int)um1["TestName"];

            um1["TestName"] = "abc";
            string teststr = (string)um1["TestName"];

            Console.WriteLine("OK");
            //
            Console.Write("4,测试缓存...");
            var cache = PWMIS.Core.MemoryCache <EntityBase> .Default;

            cache.Add("UserModels", um1);
            var cacheData = cache.Get("UserModels");

            cache.Remove("UserModels");
            Console.WriteLine("OK");
            //
            Console.Write("5,测试自动创建实体类数据库表...");
            AutoCreateEntityTable <LT_Users>();
            AutoCreateEntityTable <LT_UserRoles>();
            Console.WriteLine("OK");

            Console.WriteLine("------------测试暂时停止,回车继续运行------");
            Console.ReadLine();
            //return;

            Console.Write("6,测试实体类的外键查询...");
            TestEntityFK();
            Console.WriteLine("OK");
            Console.Write("7,测试实体类批量插入...");
            OqlInTest();
            Console.WriteLine("OK");

            Console.WriteLine("8,测试SOD POCO实体类性能...");
            Console.WriteLine("SELECT top 100000 UID,Sex,Height,Birthday,Name FROM Table_User");
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine("-------------Testt No.{0}----------------", i + 1);
                TestPocoQuery();
            }
            Console.WriteLine("--------OK---------------");

            Console.Write("9,测试OQL IN 子查询...");
            TestInChild();
            Console.WriteLine("OK");
            //TestFun(1, 2, 3);

            Console.WriteLine("10,测试泛型 OQL --GOQL");
            TestGOQL();
            Console.WriteLine("OK");

            Console.WriteLine("11,测试OQL 批量更新(带条件更新)...");
            UpdateTest();
            Console.WriteLine("OK");

            Console.WriteLine("12,测试批量数据插入性能....");
            //InsertTest();



            Console.WriteLine("13,OQL 自连接...");
            OqlJoinTest();
            //
            Console.Write("14,根据接口类型,自动创建实体类测试...");
            TestDynamicEntity();
            Console.WriteLine("OK");

            //
            Console.WriteLine("15,Sql 格式化查询测试( SOD 微型ORM功能)...");
            AdoHelper dbLocal = new SqlServer();

            dbLocal.ConnectionString = MyDB.Instance.ConnectionString;
            //DataSet ds = dbLocal.ExecuteDataSet("SELECT * FROM Table_User WHERE UID={0} AND Height>={1:5.2}", 1, 1.80M);

            /*
             * 下面的写法过时
             * var dataList = dbLocal.GetList(reader =>
             * {
             *  return new
             *  {
             *      UID=reader.GetInt32(0),
             *      Name=reader.GetString(1)
             *  };
             * }, "SELECT UID,Name FROM Table_User WHERE Sex={0} And Height>={0:5.2}",1, 1.60);
             */
            var dataList = dbLocal.ExecuteMapper("SELECT UID,Name FROM Table_User WHERE Sex={0} And Height>={1:5.2}", 1, 1.60)
                           .MapToList(reader => new
            {
                UID  = reader.GetInt32(0),
                Name = reader.GetString(1)
            });

            Console.WriteLine("OK");

            //
            Console.Write("16,测试属性拷贝...");
            V_UserModels vum = new V_UserModels();

            vum.BIGTEAM_ID   = 123;//可空属性,如果目标对象不是的话,无法拷贝
            vum.REGION_ID    = 456;
            vum.SMALLTEAM_ID = 789;

            UserModels um = vum.CopyTo <UserModels>();

            Console.WriteLine("OK");

            //
            Console.Write("17,测试【自定义查询】的实体类...");
            UserPropertyView up = new UserPropertyView();
            OQL      q11        = new OQL(up);
            OQLOrder order      = new OQLOrder(q11);

            q11.Select()
            .Where(q11.Condition.AND(up.PropertyName, "=", "总成绩").AND(up.PropertyValue, ">", 1000))
            .OrderBy(order.Asc(up.UID));
            AdoHelper db11   = MyDB.GetDBHelperByConnectionName("local");
            var       result = EntityQuery <UserPropertyView> .QueryList(q11, db11);

            //下面2行不是必须
            q11.Dispose();
            Console.WriteLine("OK");

            //EntityContainer ec = new EntityContainer(q11);
            //var ecResult = ec.MapToList(() => {
            //    return new { AAA = ec.GetItemValue<int>(0), BBB = ec.GetItemValue<string>(1) };
            //});

            /////////////////////////////////////////////////////
            Console.WriteLine("18,测试实体类【自动保存】数据...");

            TestAutoSave();

            /////////////////测试事务////////////////////////////////////
            Console.WriteLine("19,测试测试事务...");
            TestTransaction();
            TestTransaction2();
            Console.WriteLine("事务测试完成!");
            Console.WriteLine("-------PDF.NET SOD 测试全部完成-------");

            Console.ReadLine();
        }
Exemplo n.º 58
0
        public void TestsMultiThreading()
        {
            int MultiThreadAmount = Amount * 10;

            System.Threading.ManualResetEvent sharedResetEvent = new System.Threading.ManualResetEvent(false);

            int statLevelCountIn = 0;

            int stackLevelCountOut = 0;

            int product = ThreadCount * MultiThreadAmount;

            int enumerateCount = 0;

            //In these threads populate
            System.Threading.Thread[] pushThreads = new System.Threading.Thread[ThreadCount];

            System.Threading.Thread[] popThreads = new System.Threading.Thread[ThreadCount];

            System.Threading.Thread[] enumerateThreads = new System.Threading.Thread[ThreadCount];

            Func <System.Threading.Thread> createEnumerateThread = () =>
            {
                if (enumerateCount >= ThreadCount)
                {
                    enumerateCount = 0;
                }

                return(enumerateThreads[enumerateCount] = new System.Threading.Thread(() =>
                {
                    try
                    {
                        long peek = 0;

                        if (LinkedStack.TryPeek(ref peek))
                        {
                            System.Console.WriteLine(System.Threading.Thread.CurrentThread.Name + "=> TryPeek: " + peek);

                            System.Console.WriteLine(System.Threading.Thread.CurrentThread.Name + "=> Count" + LinkedStack.Count);
                        }
                        else if (false == LinkedStack.IsEmpty)
                        {
                            if (LinkedStack.TryPeek(ref peek))
                            {
                                System.Console.WriteLine(System.Threading.Thread.CurrentThread.Name + "=> First = " + System.Threading.Thread.VolatileRead(ref LinkedStack.Last.Value));
                            }

                            System.Console.WriteLine(System.Threading.Thread.CurrentThread.Name + "=> Last = " + System.Threading.Thread.VolatileRead(ref LinkedStack.Last.Value));
                        }
                    }
                    catch (Exception)
                    {
                        System.Console.WriteLine(System.Threading.Thread.CurrentThread.Name + " => Exception");
                    }
                })
                {
                    Name = "enumerateThreads" + enumerateCount++,

                    ApartmentState = System.Threading.ApartmentState.MTA,

                    Priority = System.Threading.ThreadPriority.AboveNormal
                });
            };

            for (int t = ThreadCount - 1; t >= 0; --t)
            {
                pushThreads[t] = new System.Threading.Thread(() =>
                {
                    int threadLocalCountIn = 0;

                    while (threadLocalCountIn < MultiThreadAmount)
                    {
                        ++LastInputOutput;

                        if (Common.Binary.IsEven(ref LastInputOutput) && LinkedStack.TryPush(ref LastInputOutput))
                        {
                            System.Console.WriteLine(System.Threading.Thread.CurrentThread.Name + " @ TryPush => " + LastInputOutput);

                            ++threadLocalCountIn;

                            System.Threading.Interlocked.Increment(ref statLevelCountIn);

                            sharedResetEvent.Set();

                            System.Threading.Thread.Yield();
                        }
                        else
                        {
                            LinkedStack.Push(LastInputOutput);

                            System.Console.WriteLine(System.Threading.Thread.CurrentThread.Name + " @ Push => " + LastInputOutput);

                            ++threadLocalCountIn;

                            System.Threading.Interlocked.Increment(ref statLevelCountIn);

                            sharedResetEvent.Set();

                            System.Threading.Thread.Yield();
                        }
                    }

                    if (LinkedStack.IsEmpty)
                    {
                        System.Console.WriteLine("pushThread Empty");
                    }

                    System.Console.WriteLine("pushThread Exit");
                })
                {
                    ApartmentState = System.Threading.ApartmentState.MTA,

                    Priority = System.Threading.ThreadPriority.Normal,

                    Name = "pushThreads_" + t
                };

                popThreads[t] = new System.Threading.Thread(() =>
                {
                    int threadLocalCountOut = 0;

                    while (threadLocalCountOut < MultiThreadAmount)
                    {
                        long pop;

                        if (LinkedStack.TryPop(out pop))
                        {
                            ++threadLocalCountOut;

                            System.Threading.Interlocked.Increment(ref stackLevelCountOut);

                            System.Console.WriteLine(System.Threading.Thread.CurrentThread.Name + ": " + pop);

                            //if(dequeue <= dequeueLast) throw new System.Exception("Unexpected value");

                            sharedResetEvent.Set();

                            System.Threading.Thread.Yield();
                        }
                    }

                    //if (false == LinkedStack.IsEmpty) throw new System.Exception("dequeueThread");

                    System.Console.WriteLine("popThread Exit");
                })
                {
                    Priority = System.Threading.ThreadPriority.BelowNormal,

                    ApartmentState = System.Threading.ApartmentState.MTA,

                    Name = "popThreads_" + t
                };

                enumerateThreads[t] = createEnumerateThread();
            }

            System.Linq.ParallelEnumerable.ForAll(pushThreads.AsParallel(), t => t.Start());

            System.Linq.ParallelEnumerable.ForAll(popThreads.AsParallel(), t => t.Start());

            while (stackLevelCountOut == 0 && statLevelCountIn == 0)
            {
                sharedResetEvent.WaitOne(0);
            }

            while (stackLevelCountOut < product)
            {
                sharedResetEvent.Reset();

                System.Console.WriteLine(System.Threading.Thread.CurrentThread.Name + "=> Count: " + LinkedStack.Count + "," + "CountIn: " + statLevelCountIn + "," + "CountOut: " + stackLevelCountOut);

                (enumerateThreads.FirstOrDefault(t => t.ThreadState == System.Threading.ThreadState.Unstarted) ?? createEnumerateThread()).Start();

                sharedResetEvent.WaitOne(ThreadCount);
            }

            if (statLevelCountIn != stackLevelCountOut)
            {
                throw new System.Exception("count");
            }

            if (false == LinkedStack.IsEmpty)
            {
                throw new System.Exception("IsEmpty");
            }

            System.Console.WriteLine("Count: " + LinkedStack.Count);
        }
        /// <returns>True if the user has upgraded</returns>
        private async Task <Boolean> githubCheck()
        {
            log.Debug("Checking for Squirrel update...");
            UpdateManager updateManager = null;

            isBusy = true;
            try {
                String installRootDir = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
                if (string.IsNullOrEmpty(nonGitHubReleaseUri))
                {
                    updateManager = await Squirrel.UpdateManager.GitHubUpdateManager("https://github.com/phw198/OutlookGoogleCalendarSync", "OutlookGoogleCalendarSync", installRootDir,
                                                                                     prerelease : Settings.Instance.AlphaReleases);
                }
                else
                {
                    updateManager = new Squirrel.UpdateManager(nonGitHubReleaseUri, "OutlookGoogleCalendarSync", installRootDir);
                }

                UpdateInfo updates = await updateManager.CheckForUpdate();

                if (updates.ReleasesToApply.Any())
                {
                    if (updates.CurrentlyInstalledVersion != null)
                    {
                        log.Info("Currently installed version: " + updates.CurrentlyInstalledVersion.Version.ToString());
                    }
                    log.Info("Found " + updates.ReleasesToApply.Count() + " newer releases available.");

                    foreach (ReleaseEntry update in updates.ReleasesToApply.OrderBy(x => x.Version).Reverse())
                    {
                        log.Info("Found a new " + update.Version.SpecialVersion + " version: " + update.Version.Version.ToString());

                        if (!this.isManualCheck && update.Version.Version.ToString() == Settings.Instance.SkipVersion)
                        {
                            log.Info("The user has previously requested to skip this version.");
                            break;
                        }

                        String releaseNotes = "";
                        if (nonGitHubReleaseUri != null)
                        {
                            releaseNotes = update.GetReleaseNotes(nonGitHubReleaseUri);
                        }
                        else
                        {
                            //Somewhat annoyingly we have to download the release in order to get the release notes, as they are embedded in the .nupkg upgrade file(s)
                            try {
                                updateManager.DownloadReleases(new[] { update }).Wait(30 * 1000);
                                System.Collections.Generic.Dictionary <ReleaseEntry, String> allReleaseNotes = updates.FetchReleaseNotes();
                                releaseNotes = allReleaseNotes[update];
                            } catch (System.Exception ex) {
                                log.Error("Failed pre-fetching release notes. " + ex.Message);
                                releaseNotes = null;
                            }
                        }

                        DialogResult dr = DialogResult.Cancel;
                        if (!string.IsNullOrEmpty(releaseNotes))
                        {
                            log.Debug("Release notes retrieved.");
                        }
                        var t = new System.Threading.Thread(() => new Forms.UpdateInfo(update.Version.Version.ToString(), update.Version.SpecialVersion, releaseNotes, out dr));
                        t.SetApartmentState(System.Threading.ApartmentState.STA);
                        t.Start();
                        t.Join();

                        if (dr == DialogResult.OK || dr == DialogResult.Yes)
                        {
                            log.Debug("Download started...");
                            if (!updateManager.DownloadReleases(new[] { update }).Wait(60 * 1000))
                            {
                                log.Warn("The download failed to completed within 60 seconds.");
                                if (MessageBox.Show("The update failed to download.", "Download timed out", MessageBoxButtons.RetryCancel, MessageBoxIcon.Exclamation) == DialogResult.Retry)
                                {
                                    if (!updateManager.DownloadReleases(new[] { update }).Wait(60 * 1000))
                                    {
                                        if (MessageBox.Show("The update failed to download again.\nTo download from the project website, click Yes.", "Download timed out", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
                                        {
                                            System.Diagnostics.Process.Start("https://phw198.github.io/OutlookGoogleCalendarSync/");
                                        }
                                        break;
                                    }
                                }
                                else
                                {
                                    if (MessageBox.Show("Would you like to download directly from the project website?", "Go to OGCS website", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
                                    {
                                        System.Diagnostics.Process.Start("https://phw198.github.io/OutlookGoogleCalendarSync/");
                                    }
                                    break;
                                }
                            }

                            try {
                                log.Debug("Download complete.");
                                log.Info("Applying the updated release...");
                                updateManager.ApplyReleases(updates).Wait();

                                log.Info("The application has been successfully updated.");
                                MessageBox.Show("The application has been updated and will now restart.",
                                                "OGCS successfully updated!", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                restartUpdateExe = updateManager.RootAppDirectory + "\\Update.exe";
                                return(true);
                            } catch (System.AggregateException ae) {
                                foreach (System.Exception ex in ae.InnerExceptions)
                                {
                                    OGCSexception.Analyse(ex, true);
                                    throw new ApplicationException("Failed upgrading OGCS.", ex);
                                }
                            } catch (System.Exception ex) {
                                OGCSexception.Analyse(ex, true);
                                throw new ApplicationException("Failed upgrading OGCS.", ex);
                            }
                        }
                        else
                        {
                            log.Info("User chose not to upgrade.");
                        }
                        break;
                    }
                }
                else
                {
                    log.Info("Already running the latest version of OGCS.");
                    if (this.isManualCheck)   //Was a manual check, so give feedback
                    {
                        MessageBox.Show("You are already running the latest version of OGCS.", "Latest Version", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            } catch (ApplicationException ex) {
                throw ex;
            } catch (System.AggregateException ae) {
                log.Error("Failed checking for update.");
                foreach (System.Exception ex in ae.InnerExceptions)
                {
                    OGCSexception.Analyse(ex, true);
                    throw ex;
                }
            } catch (System.Exception ex) {
                log.Error("Failed checking for update.");
                OGCSexception.Analyse(ex, true);
                throw ex;
            } finally {
                isBusy = false;
                updateManager.Dispose();
            }
            return(false);
        }
Exemplo n.º 60
0
 public virtual void Start()
 {
     m_Thread = new System.Threading.Thread(Run);
     m_Thread.Start();
 }