Esempio n. 1
0
 public static void SetClipboard(string result)
 {
     var thread = new Thread(() => Clipboard.SetText(result));
     thread.SetApartmentState(ApartmentState.STA);
     thread.Start();
     thread.Join();
 }
Esempio n. 2
0
        /// <summary>Initializes a new instance of the MTATaskScheduler class with the specified concurrency level.</summary>
        /// <param name="numberOfThreads">The number of threads that should be created and used by this scheduler.</param>
        /// <param name="nameFormat">The template name form to use to name threads.</param>
        public MTATaskScheduler(int numberOfThreads, string nameFormat)
        {
            // Validate arguments
            if (numberOfThreads < 1) throw new ArgumentOutOfRangeException("numberOfThreads");

            // Initialize the tasks collection
            tasks = new BlockingCollection<Task>();

            // Create the threads to be used by this scheduler
            _threads = Enumerable.Range(0, numberOfThreads).Select(i =>
                       {
                           var thread = new Thread(() =>
                           {
                               // Continually get the next task and try to execute it.
                               // This will continue until the scheduler is disposed and no more tasks remain.
                               foreach (var t in tasks.GetConsumingEnumerable())
                               {
                                   TryExecuteTask(t);
                               }
                           });
                           thread.IsBackground = true;
                           thread.SetApartmentState(ApartmentState.MTA);
                           thread.Name = String.Format("{0} - {1}", nameFormat, thread.ManagedThreadId);
                           return thread;
                       }).ToList();

            // Start all of the threads
            _threads.ForEach(t => t.Start());
        }
Esempio n. 3
0
    protected void Capture(object sender, EventArgs e)
    {
        string url = txtUrl.Text.Trim();

        Thread thread = new Thread(delegate()
        {
            using (WebBrowser browser = new WebBrowser())
            {
                browser.ScrollBarsEnabled = false;
                browser.AllowNavigation = false;
                browser.AllowWebBrowserDrop = false;
                browser.ScriptErrorsSuppressed = true;
                browser.Navigate("www.cnn.com");
                //browser.Navigate((url, null, <data>, "Content-Type: application/x-www-form-urlencoded");)
                browser.Width = 1024;
                browser.Height = 768;
                browser.ClientSize = new Size(1024,768);
                browser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(DownloadCompleted);
                while ((browser.IsBusy) |  (browser.ReadyState != WebBrowserReadyState.Complete))
                {
                    System.Windows.Forms.Application.DoEvents();
                }
                //Thread.Sleep(5000);
                //browser.Dispose();
            }
        });
        thread.SetApartmentState(ApartmentState.STA);
        thread.Start();
        thread.Join();
    }
Esempio n. 4
0
 public static void AddWorker(ThreadManager threadManager)
 {
     Interlocked.Increment(ref threadManager.activeThreads);
     var worker = new WorkThread(threadManager);
     var thread = new Thread(worker.Loop);
     thread.SetApartmentState(ApartmentState.STA);
     thread.Start();
 }
Esempio n. 5
0
 public void Connection()
 {
     BTN_Connect.Visible=false;
     T = new Thread(Connect);
     T.IsBackground=true;
     T.SetApartmentState(ApartmentState.STA);
     T.Start();
 }
Esempio n. 6
0
 public Bitmap Generate()
 {
     // Thread
     var m_thread = new Thread(_Generate);
     m_thread.SetApartmentState(ApartmentState.STA);
     m_thread.Start();
     m_thread.Join();
     return m_Bitmap;
 }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="sharepointConnectionId"></param>
 /// <param name="adaptername"></param>
 /// <param name="objectdefinitionId"></param>
 public void StartImport(string sharepointConnectionId, string adaptername, string workflowName, ObjectDefinition objectdefinition)
 {
     ConnectionId = sharepointConnectionId;
     AdapterName = adaptername;
     SharePointObjectDefinition = objectdefinition;
     WorkflowName = workflowName;
     MainThread = new Thread(SharePointClientImportHelper.Start);
     MainThread.Priority = ThreadPriority.Lowest;
     MainThread.SetApartmentState(ApartmentState.STA);//Creating a single threaded apartment.
     MainThread.Start();
     Thread.Sleep(100);
 }
Esempio n. 8
0
 private static void Initialize()
 {
     // Run the message loop on another thread so we're compatible with a console mode app
     var t = new Thread(() => {
         frm = new Form();
         var dummy = frm.Handle;
         frm.BeginInvoke(new MethodInvoker(() => mre.Set()));
         Application.Run();
     });
     t.SetApartmentState(ApartmentState.STA);
     t.IsBackground = true;
     t.Start();
     mre.WaitOne();
 }
Esempio n. 9
0
    public void OpenURLWithData(string wszURL, IntPtr pbPostData, int cbData, IntPtr hwnd)
    {
        Thread InvokeThread;

        // Create POST data and convert it to a byte array.
        m_byteArray = new byte[cbData];
        Marshal.Copy(pbPostData, m_byteArray, 0, cbData);

        m_szUrl = wszURL;
        m_hwnd = hwnd;

        InvokeThread = new Thread(new ThreadStart(InvokeMethod));
        InvokeThread.SetApartmentState(ApartmentState.STA);
        InvokeThread.Start();
    }
    void Run(ThreadStart userDelegate, ApartmentState apartmentState)
    {
        lastException = null;

        var thread = new Thread(() => MultiThreadedWorker(userDelegate));
        thread.SetApartmentState(apartmentState);

        thread.Start();
        thread.Join();

        if (ExceptionWasThrown())
        {
            ThrowExceptionPreservingStack(lastException);
        }
    }
Esempio n. 11
0
 static void SetClipboard()
 {
     var templateClass = @"
     public static class ModuleInitializer
     {
     public static void Initialize()
     {
     //Your code goes here
     }
     }";
     var thread = new Thread(() => Clipboard.SetText(templateClass));
     thread.SetApartmentState(ApartmentState.STA);
     thread.Start();
     thread.Join();
 }
Esempio n. 12
0
    public void RunInSta(Action userDelegate)
    {
        lastException = null;

        var thread = new Thread(() => MultiThreadedWorker(() => userDelegate()));
        thread.SetApartmentState(ApartmentState.STA);

        thread.Start();
        thread.Join();

        if (lastException != null)
        {
            ThrowExceptionPreservingStack(lastException);
        }
    }
Esempio n. 13
0
    /// <summary>
    /// class constructor 
    /// </summary>
    /// <param name="visible">whether or not the form and the WebBrowser control are visiable</param>
    /// <param name="userName">client user name</param>
    /// <param name="password">client password</param>
    /// <param name="resultEvent">functionality to keep the main thread waiting</param>
    public IEBrowser(bool visible, string URL, AutoResetEvent resultEvent)
    {
        //this.userName = userName;
        //this.password = password;
        this.resultEvent = resultEvent;
        htmlResult = null;

        thrd = new Thread(new ThreadStart(
            delegate {
                Init(visible,URL);
                System.Windows.Forms.Application.Run(this);
            }));
        // set thread to STA state before starting
        thrd.SetApartmentState(ApartmentState.STA);
        thrd.Start();
    }
Esempio n. 14
0
    protected void setNorth_Click(object sender, EventArgs e)
    {
        northNetwork = (sender as Button).Text.ToUpper();

        // Do work!
        Thread threadNorth = new Thread( () =>
        {
            using ( System.Windows.Forms.WebBrowser webBrowser1 = new System.Windows.Forms.WebBrowser() )
            {
                webBrowser1.DocumentCompleted += loadPresetsPage;
                webBrowser1.Navigate( NORTH_URL_SET_PRESET );
                System.Windows.Forms.Application.Run();
            }
        } );
        threadNorth.Name = "North";
        threadNorth.SetApartmentState( ApartmentState.STA );
        threadNorth.Start();
        threadNorth.Join();
    }
Esempio n. 15
0
 public Task<RunSummary> RunAsync(IMessageSink diagnosticMessageSink, IMessageBus messageBus, object[] constructorArguments,
     ExceptionAggregator aggregator, CancellationTokenSource cancellationTokenSource)
 {
     var tcs = new TaskCompletionSource<RunSummary>();
     var thread = new Thread(() =>
     {
         try
         {
             var testCaseTask = testCase.RunAsync(diagnosticMessageSink, messageBus, constructorArguments, aggregator,
                 cancellationTokenSource);
             tcs.SetResult(testCaseTask.Result);
         }
         catch (Exception e)
         {
             tcs.SetException(e);
         }
     });
     thread.SetApartmentState(ApartmentState.STA);
     thread.Start();
     return tcs.Task;
 }
Esempio n. 16
0
    protected void Page_Load(object sender, EventArgs e)
    {
        string today = DateTime.Now.ToShortDateString();
        linkSouth.OnClientClick = "window.open('" + "http://epanet.ca.gov/Rooms/dayMtgs.asp?ROOMID=36&BLDGID=15&VW=DAY&DATE=" + today + "&CLONEID=\')";
        linkNorth.OnClientClick = "window.open('" + "http://epanet.ca.gov/Rooms/dayMtgs.asp?ROOMID=35&BLDGID=15&VW=DAY&DATE=" + today + "&CLONEID=\')";
        if ( !IsPostBack )
        {
            // Check North
            Thread threadNorth = new Thread( () =>
            {
                using ( System.Windows.Forms.WebBrowser webBrowser1 = new System.Windows.Forms.WebBrowser() )
                {
                    webBrowser1.DocumentCompleted += loadTRSPage;
                    webBrowser1.Navigate( NORTH_URL );
                    System.Windows.Forms.Application.Run();
                }
            } );

            // Check South
            Thread threadSouth = new Thread( () =>
            {
                using ( System.Windows.Forms.WebBrowser webBrowser1 = new System.Windows.Forms.WebBrowser() )
                {
                    webBrowser1.DocumentCompleted += loadTRSPage;
                    webBrowser1.Navigate( SOUTH_URL );
                    System.Windows.Forms.Application.Run();
                }
            } );

            threadNorth.Name = "North";
            threadSouth.Name = "South";
            threadNorth.SetApartmentState( ApartmentState.STA );
            threadSouth.SetApartmentState( ApartmentState.STA );
            threadNorth.Start();
            threadSouth.Start();
            threadNorth.Join();
            threadSouth.Join();
        }
    }
Esempio n. 17
0
        public void Seek(int ms)
        {
            if (streamType == StreamType.TORRENT && torrent != null && torrent.data.files[fileIndex].FileCreated)
            {
                BufferingDoneClbk?.BeginInvoke(true, null, null); return;
            }
            if (!decoder.isReady)
            {
                return;
            }

            try
            {
                if (vDecoder != null)
                {
                    vDecoder.Abort();
                }
                if (aDecoder != null)
                {
                    aDecoder.Abort();
                }
                if (sDecoder != null)
                {
                    sDecoder.Abort();
                }
                Thread.Sleep(40);
            } catch (Exception) { }

            aDone  = false; vDone = false; sDone = false;
            status = Status.BUFFERING;

            lock (localFocusPoints)
            {
                foreach (KeyValuePair <long, Tuple <long, int> > curLFPKV in localFocusPoints)
                {
                    tsStream.DeleteFocusPoint(curLFPKV.Key);
                }

                localFocusPoints.Clear();
            }

            vDecoder = new Thread(() =>
            {
                decoder.vStatus = Codecs.FFmpeg.Status.RUNNING;
                if (decoder.SeekAccurate2(ms - 100, AVMediaType.AVMEDIA_TYPE_VIDEO) != 0)
                {
                    Log("VIDEO STREAMER] Error Seeking");
                }
                decoder.DecodeSilent2(AVMediaType.AVMEDIA_TYPE_VIDEO, (ms + 5500) * (long)10000);
                decoder.vStatus = Codecs.FFmpeg.Status.STOPPED;
            });
            vDecoder.SetApartmentState(ApartmentState.STA);
            vDecoder.Start();

            if (decoder.hasAudio)
            {
                aDecoder = new Thread(() =>
                {
                    decoder.aStatus = Codecs.FFmpeg.Status.RUNNING;
                    if (decoder.SeekAccurate2((ms - AudioExternalDelay) - 400, AVMediaType.AVMEDIA_TYPE_AUDIO) != 0)
                    {
                        Log("[AUDIO STREAMER] Error Seeking");
                    }
                    decoder.DecodeSilent2(AVMediaType.AVMEDIA_TYPE_AUDIO, ((ms - AudioExternalDelay) + 2000) * (long)10000);
                    decoder.aStatus = Codecs.FFmpeg.Status.STOPPED;
                });
                aDecoder.SetApartmentState(ApartmentState.STA);
                aDecoder.Start();
            }

            if (decoder.hasSubs && !IsSubsExternal)
            {
                sDecoder = new Thread(() =>
                {
                    decoder.sStatus = Codecs.FFmpeg.Status.RUNNING;
                    if (decoder.SeekAccurate2((ms - SubsExternalDelay) - 1000, AVMediaType.AVMEDIA_TYPE_SUBTITLE) != 0)
                    {
                        Log("[SUBS  STREAMER] Error Seeking");
                    }
                    decoder.DecodeSilent2(AVMediaType.AVMEDIA_TYPE_SUBTITLE, ((ms - SubsExternalDelay) + 15000) * (long)10000);
                    decoder.sStatus = Codecs.FFmpeg.Status.STOPPED;
                });
                sDecoder.SetApartmentState(ApartmentState.STA);
                sDecoder.Start();
            }
        }
Esempio n. 18
0
        private static void Main(string[] args)
        {
            var eventHookFactory = new EventHookFactory();

            //Provide text that needs to be dynamically added to the clipboard
            var text = "wait-time 2 secs music goto step 15 service-hours not-in V2 goto step 9 staffed-agents 2298 > 0 goto step 12 staffed-agents 2299 > 0 goto step 9 staffed-agents 1st = 0 route-to number V1 n unconditionally stop announcement 2840102 disconnect 2840107 stop announcement 2840103 VECTOR disconnect 2840107 stop announcement 2840104 disconnect 2840107 stop";
            var lst  = text.Split(' ');

            //Prints first word in text to Console
            Console.WriteLine(lst[0]);
            var i = 0;

            //Initialises MouseWatcher
            var mouseWatcher = eventHookFactory.GetMouseWatcher();

            mouseWatcher.Start();
            mouseWatcher.OnMouseInput += (s, e) =>
            {
                if (e.Message.ToString() != "WM_MOUSEMOVE")
                {
                    Console.WriteLine("Mouse event {0} at point {1},{2}", e.Message.ToString(), e.Point.x, e.Point.y);
                }
            };

            //Initialises Clipboard Watcher to check for clipboard update events
            var clipboardWatcher = eventHookFactory.GetClipboardWatcher();

            clipboardWatcher.Start();
            clipboardWatcher.OnClipboardModified += (s, e) =>
            {
                Console.WriteLine("Clipboard updated with data '{0}' of format {1}", e.Data,
                                  e.DataFormat.ToString());
            };

            //var applicationWatcher = eventHookFactory.GetApplicationWatcher();
            //applicationWatcher.Start();
            //applicationWatcher.OnApplicationWindowChange += (s, e) =>
            //{
            //    Console.WriteLine("Application window of '{0}' with the title '{1}' was {2}",
            //        e.ApplicationData.AppName, e.ApplicationData.AppTitle, e.Event);
            //};

            //Initialises Keyboard Watcher to check key press events
            var keyboardWatcher = eventHookFactory.GetKeyboardWatcher();

            keyboardWatcher.Start();
            keyboardWatcher.OnKeyInput += (s, e) =>
            {
                //Updates Clipboard with the next word in the list when "TAB" is pressed
                if (e.KeyData.Keyname == "Tab" && e.KeyData.EventType.ToString() == "down")
                {
                    Console.WriteLine("Key {0} event of key {1}", e.KeyData.EventType, e.KeyData.Keyname);

                    //Creates new thread to handle the clipboard update
                    Thread thread = new Thread(() => Clipboard.SetText(lst[i]));
                    thread.SetApartmentState(ApartmentState.STA); //Set the thread to STA
                    thread.Start();
                    thread.Join();
                    i++;
                    i = i % (lst.Length);
                    //Console.WriteLine(lst[i]);
                }

                //Console.WriteLine("Key {0} event of key {1}", e.KeyData.EventType, e.KeyData.Keyname);
            };

            Console.Read();
            //mouseWatcher.Stop();
            clipboardWatcher.Stop();
            //applicationWatcher.Stop();
            keyboardWatcher.Stop();


            eventHookFactory.Dispose();
        }
    /*Parametrelerin Elde edilmesi*/
    /*Rapor*/

    
   
    
  
      protected void Capture(object sender, EventArgs e)
    {

        Thread thread = new Thread(delegate()
        {
            using (WebBrowser browser = new WebBrowser())
            {
                string url = "http://localhost:11127/EkranListesi/Tvlistreport.aspx";
                browser.ScrollBarsEnabled = false;
                browser.Navigate(url);

                browser.Width = 1024;
                browser.Height = 768;
                browser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(DocumentCompleted);
                while (browser.ReadyState != WebBrowserReadyState.Complete)
                {
                    System.Windows.Forms.Application.DoEvents();
                }
            }
        });
        thread.SetApartmentState(ApartmentState.STA);
        thread.Start();
        thread.Join();
    }
Esempio n. 20
0
        /// <summary>
        /// Handle the DocumentComplete event.
        /// </summary>
        /// <param name="pDisp">
        /// The pDisp is an an object implemented the interface InternetExplorer.
        /// By default, this object is the same as the ieInstance, but if the page
        /// contains many frames, each frame has its own document.
        /// </param>
        void IeInstance_DocumentComplete(object pDisp, ref object URL)
        {
            if (ieInstance == null)
            {
                return;
            }

            // get the url
            string url = URL as string;

            if (string.IsNullOrEmpty(url) || url.Equals(@"about:Tabs", StringComparison.OrdinalIgnoreCase) || url.Equals("about:blank", StringComparison.OrdinalIgnoreCase))
            {
                return;
            }


            // http://borderstylo.com/posts/115-browser-wars-2-dot-0-the-plug-in
            SHDocVw.WebBrowser browser = (SHDocVw.WebBrowser)ieInstance;
            if (browser.ReadyState != SHDocVw.tagREADYSTATE.READYSTATE_COMPLETE)
            {
                return;
            }


            // Set the handler of the document in InternetExplorer.
            NativeMethods.ICustomDoc customDoc = (NativeMethods.ICustomDoc)ieInstance.Document;
            customDoc.SetUIHandler(openImageDocHostUIHandler);


            // sets the document
            this.document = (HTMLDocument)ieInstance.Document;


            try
            {
                if (this.document.url.Contains(@"thousandpass") || this.document.url.Contains(@"1000pass.com"))
                {
                    // Mark the add_on as installed!
                    IHTMLElement div1000pass_add_on = this.document.getElementById("1000pass_add_on");
                    div1000pass_add_on.className = @"installed";
                    IHTMLElement div1000pass_add_on_version = this.document.getElementById("1000pass_add_on_version");
                    div1000pass_add_on_version.innerText = VERSION;


                    // Try to save the token
                    string token = div1000pass_add_on.getAttribute("token").ToString();
                    if (!String.IsNullOrEmpty(token))
                    {
                        Utils.WriteToFile(Utils.TokenFileName, token);
                    }


                    foreach (IHTMLElement htmlElement in document.getElementsByTagName("IMG"))
                    {
                        if (htmlElement.className == "remote_site_logo")
                        {
                            IHTMLStyle htmlStyle = (IHTMLStyle)htmlElement.style;
                            htmlStyle.cursor = "pointer";


                            DHTMLEventHandler Handler = new DHTMLEventHandler((IHTMLDocument2)ieInstance.Document);
                            Handler.Handler    += new DHTMLEvent(Logo_OnClick);
                            htmlElement.onclick = Handler;

                            htmlElement.setAttribute("alreadyopened", "false", 0);
                        }
                    }
                }
                else
                {
                    // Must run on a thread to guaranty the page has finished loading (js loading)
                    // http://stackoverflow.com/questions/3514945/running-a-javascript-function-in-an-instance-of-internetexplorer
                    System.Threading.ThreadPool.QueueUserWorkItem((o) =>
                    {
                        System.Threading.Thread.Sleep(500);
                        try
                        {
                            Thread aThread = new Thread(bind);
                            aThread.SetApartmentState(ApartmentState.STA);
                            aThread.Start();
                        }
                        catch (Exception ee)
                        {
                            Utils.l(ee);
                        }
                    }, browser);
                }
            }
            catch (Exception e)
            {
                Utils.l(e);
            }
        }
Esempio n. 21
0
        private static void Pause()
        {
            while (true)
            {
                var  useModifier = (ActiveConfig.Controls_KB_Detach_MOD != (int)Key.None);
                bool detachKey   = (useModifier ?
                                    Keyboard.IsKeyDown((Key)ActiveConfig.Controls_KB_Detach_MOD) &&
                                    Keyboard.IsKeyDown((Key)ActiveConfig.Controls_KB_Detach_KEY) :
                                    Keyboard.IsKeyDown((Key)ActiveConfig.Controls_KB_Detach_KEY));

                if (detachKey || ToggleStatusState)
                {
                    if (ToggleStatusState)
                    {
                        ToggleStatusState = false;
                    }

                    bool inputDead  = !Activate.tKMInput.IsAlive;
                    bool streamDead = !Activate.tXboxStream.IsAlive;

                    #if (DEBUG)
                    Logger.appendLogLine("Threads", $"Threads Status: Input - {!inputDead}, Stream - {!streamDead}",
                                         Logger.Type.Debug);
                    #endif

                    if (!inputDead && !streamDead)
                    {
                        #if (DEBUG)
                        Logger.appendLogLine("Threads", "Aborting all threads!", Logger.Type.Info);
                        #endif

                        try { Activate.tXboxStream.Abort(); }       catch (Exception) { }
                        try { Activate.tKMInput.Abort(); }          catch (Exception) { }
                        try { XboxStream.tMouseMovement.Abort(); }  catch (Exception) { }

                        CursorView.CursorShow();

                        /*
                         * if (Activate.tKMInput.IsAlive == true && Activate.tXboxStream.IsAlive == true) {
                         *  // TODO: Handle failed threads
                         *  MessageBox.Show("Error:  Threads failed to abort");
                         * }  //*/

                        // Reset the controller
                        Activate.ResetController();

                        MainForm.StatusStopped();
                    }
                    else
                    {
                        // && Activate.tXboxStream.IsAlive == false
                        if (inputDead || streamDead)
                        {
                            // Start the required threads
                            Thread tActivateKM = new Thread(() => {
                                Activate.ActivateKeyboardAndMouse(streamDead, inputDead);
                            });
                            tActivateKM.SetApartmentState(ApartmentState.STA);
                            tActivateKM.IsBackground = true;
                            tActivateKM.Start();
                        }
                    }
                }

                Thread.Sleep(100);
            }
        }
Esempio n. 22
0
            /// <summary>
            /// 清空回收站,这个方法同SHEmptyRecycleBin函数一样调用
            /// </summary>
            /// <param name="hwnd">在调用SHEmptyRecycleBin期间,指向用来显示的对话框的父窗体的句柄
            /// 可为NULL值
            /// </param>
            /// <param name="rootpath">最大长度为260个字符的字符串,指定磁盘根目录或文件夹目录,可为null,则清空整个回收站的内容</param>
            /// <param name="dwFlags">SHERB枚举,可组合使用</param>
            /// <returns>成功返回0,否则为OLE定义的错误值</returns>
            public uint EmptyRecycleBin(IntPtr hwnd, string rootpath, SHERB dwFlags)
            {
                _rbState rvs = new _rbState(hwnd, rootpath, dwFlags);
                rvs.Revalue = 0x8000FFFF;

                long size, items;

                this.QuerySizeRecycleBin(out size, out items);
                if (size == 0)
                    return rvs.Revalue;

                lock (rvs)
                {
                    Thread t = new Thread(
                        new ParameterizedThreadStart(this.wrokThread));
                    t.SetApartmentState(ApartmentState.STA);
                    t.Start(rvs);
                }
                /* Console.WriteLine("aaa");测试了,同一个对象实例,依次调用EmptyRecycleBin
                的任何一个重载,其顺序总是:先被调用的,总是先运行,后面的--排队等待
                 * 这样的原因是ewh是AUTO的,set之后,同样命名的对象就不会wait了
                 */
                this.ewh.WaitOne();
                this.ewh.Reset();
                return rvs.Revalue;
            }
Esempio n. 23
0
        private static void BackgroundWorkerOnRunWorkerCompleted(object sender,
            RunWorkerCompletedEventArgs runWorkerCompletedEventArgs)
        {
            if (!runWorkerCompletedEventArgs.Cancelled)
            {
                if (runWorkerCompletedEventArgs.Result is DateTime)
                {
                    SetTimer((DateTime) runWorkerCompletedEventArgs.Result);
                }
                else
                {
                    var args = runWorkerCompletedEventArgs.Result as UpdateInfoEventArgs;
                    if (CheckForUpdateEvent != null)
                    {
                        CheckForUpdateEvent(args);
                    }
                    else
                    {
                        if (args != null)
                        {
                            if (args.IsUpdateAvailable)
                            {
                                if (!IsWinFormsApplication)
                                {
                                    Application.EnableVisualStyles();
                                }

                                if (Mandatory && UpdateMode == Mode.ForcedDownload)
                                {
                                    DownloadUpdate();
                                    Exit();
                                }
                                else
                                {
                                    if (Thread.CurrentThread.GetApartmentState().Equals(ApartmentState.STA))
                                    {
                                        ShowUpdateForm();
                                    }
                                    else
                                    {
                                        Thread thread = new Thread(ShowUpdateForm);
                                        thread.CurrentCulture = thread.CurrentUICulture = CultureInfo.CurrentCulture;
                                        thread.SetApartmentState(ApartmentState.STA);
                                        thread.Start();
                                        thread.Join();
                                    }
                                }

                                return;
                            }
                            else
                            {
                                if (ReportErrors)
                                {
                                    MessageBox.Show(Resources.UpdateUnavailableMessage,
                                        Resources.UpdateUnavailableCaption,
                                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                                }
                            }
                        }
                        else
                        {
                            if (ReportErrors)
                            {
                                MessageBox.Show(
                                    Resources.UpdateCheckFailedMessage,
                                    Resources.UpdateCheckFailedCaption, MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                    }
                }
            }

            Running = false;
        }
Esempio n. 24
0
        public static void RunBotWithParameters(Action <ISession, StatisticsAggregator> onBotStarted, string[] args)
        {
            var ioc = TinyIoC.TinyIoCContainer.Current;

            //Setup Logger for API
            APIConfiguration.Logger = new APILogListener();

            //Application.EnableVisualStyles();
            var strCulture = Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;

            var culture = CultureInfo.CreateSpecificCulture("en");

            CultureInfo.DefaultThreadCurrentCulture = culture;
            Thread.CurrentThread.CurrentCulture     = culture;

            AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionEventHandler;

            Console.Title           = @"NecroBot2";
            Console.CancelKeyPress += (sender, eArgs) =>
            {
                QuitEvent.Set();
                eArgs.Cancel = true;
            };

            // Command line parsing
            var commandLine = new Arguments(args);

            // Look for specific arguments values
            if (commandLine["subpath"] != null && commandLine["subpath"].Length > 0)
            {
                _subPath = commandLine["subpath"];
            }
            if (commandLine["jsonvalid"] != null && commandLine["jsonvalid"].Length > 0)
            {
                switch (commandLine["jsonvalid"])
                {
                case "true":
                    _enableJsonValidation = true;
                    break;

                case "false":
                    _enableJsonValidation = false;
                    break;
                }
            }
            if (commandLine["killswitch"] != null && commandLine["killswitch"].Length > 0)
            {
                switch (commandLine["killswitch"])
                {
                case "true":
                    _ignoreKillSwitch = false;
                    break;

                case "false":
                    _ignoreKillSwitch = true;
                    break;
                }
            }

            bool excelConfigAllow = false;

            if (commandLine["provider"] != null && commandLine["provider"] == "excel")
            {
                excelConfigAllow = true;
            }

            //
            Logger.AddLogger(new ConsoleLogger(LogLevel.Service), _subPath);
            Logger.AddLogger(new FileLogger(LogLevel.Service), _subPath);
            Logger.AddLogger(new WebSocketLogger(LogLevel.Service), _subPath);

            var profilePath       = Path.Combine(Directory.GetCurrentDirectory(), _subPath);
            var profileConfigPath = Path.Combine(profilePath, "config");
            var configFile        = Path.Combine(profileConfigPath, "config.json");
            var excelConfigFile   = Path.Combine(profileConfigPath, "config.xlsm");

            GlobalSettings settings;
            var            boolNeedsSetup = false;

            if (File.Exists(configFile))
            {
                // Load the settings from the config file
                settings = GlobalSettings.Load(_subPath, _enableJsonValidation);
                if (excelConfigAllow)
                {
                    if (!File.Exists(excelConfigFile))
                    {
                        Logger.Write(
                            "Migrating existing json confix to excel config, please check the config.xlsm in your config folder"
                            );

                        ExcelConfigHelper.MigrateFromObject(settings, excelConfigFile);
                    }
                    else
                    {
                        settings = ExcelConfigHelper.ReadExcel(settings, excelConfigFile);
                    }

                    Logger.Write("Bot will run with your excel config, loading excel config");
                }
            }
            else
            {
                settings = new GlobalSettings
                {
                    ProfilePath       = profilePath,
                    ProfileConfigPath = profileConfigPath,
                    GeneralConfigPath = Path.Combine(Directory.GetCurrentDirectory(), "config"),
                    ConsoleConfig     = { TranslationLanguageCode = strCulture }
                };

                boolNeedsSetup = true;
            }
            if (commandLine["latlng"] != null && commandLine["latlng"].Length > 0)
            {
                var crds = commandLine["latlng"].Split(',');
                try
                {
                    var lat = double.Parse(crds[0]);
                    var lng = double.Parse(crds[1]);
                    settings.LocationConfig.DefaultLatitude  = lat;
                    settings.LocationConfig.DefaultLongitude = lng;
                }
                catch (Exception)
                {
                    // ignored
                }
            }

            var options = new Options();

            if (CommandLine.Parser.Default.ParseArguments(args, options))
            {
                // Values are available here
                if (options.Init)
                {
                    settings.GenerateAccount(options.IsGoogle, options.Template, options.Start, options.End, options.Password);
                }
            }
            var lastPosFile = Path.Combine(profileConfigPath, "LastPos.ini");

            if (File.Exists(lastPosFile) && settings.LocationConfig.StartFromLastPosition)
            {
                var text = File.ReadAllText(lastPosFile);
                var crds = text.Split(':');
                try
                {
                    var lat = double.Parse(crds[0]);
                    var lng = double.Parse(crds[1]);
                    //If lastcoord is snipe coord, bot start from default location

                    if (LocationUtils.CalculateDistanceInMeters(lat, lng, settings.LocationConfig.DefaultLatitude, settings.LocationConfig.DefaultLongitude) < 2000)
                    {
                        settings.LocationConfig.DefaultLatitude  = lat;
                        settings.LocationConfig.DefaultLongitude = lng;
                    }
                }
                catch (Exception)
                {
                    // ignored
                }
            }

            if (!_ignoreKillSwitch)
            {
                if (CheckMKillSwitch() || CheckKillSwitch())
                {
                    return;
                }
            }

            var logicSettings = new LogicSettings(settings);
            var translation   = Translation.Load(logicSettings);

            TinyIoC.TinyIoCContainer.Current.Register <ITranslation>(translation);

            if (settings.GPXConfig.UseGpxPathing)
            {
                var xmlString = File.ReadAllText(settings.GPXConfig.GpxFile);
                var readgpx   = new GpxReader(xmlString, translation);
                var nearestPt = readgpx.Tracks.SelectMany(
                    (trk, trkindex) =>
                    trk.Segments.SelectMany(
                        (seg, segindex) =>
                        seg.TrackPoints.Select(
                            (pt, ptindex) =>
                            new
                {
                    TrackPoint = pt,
                    TrackIndex = trkindex,
                    SegIndex   = segindex,
                    PtIndex    = ptindex,
                    Latitude   = Convert.ToDouble(pt.Lat, CultureInfo.InvariantCulture),
                    Longitude  = Convert.ToDouble(pt.Lon, CultureInfo.InvariantCulture),
                    Distance   = LocationUtils.CalculateDistanceInMeters(
                        settings.LocationConfig.DefaultLatitude,
                        settings.LocationConfig.DefaultLongitude,
                        Convert.ToDouble(pt.Lat, CultureInfo.InvariantCulture),
                        Convert.ToDouble(pt.Lon, CultureInfo.InvariantCulture)
                        )
                }
                            )
                        )
                    )
                                .OrderBy(pt => pt.Distance)
                                .FirstOrDefault(pt => pt.Distance <= 5000);

                if (nearestPt != null)
                {
                    settings.LocationConfig.DefaultLatitude  = nearestPt.Latitude;
                    settings.LocationConfig.DefaultLongitude = nearestPt.Longitude;
                    settings.LocationConfig.ResumeTrack      = nearestPt.TrackIndex;
                    settings.LocationConfig.ResumeTrackSeg   = nearestPt.SegIndex;
                    settings.LocationConfig.ResumeTrackPt    = nearestPt.PtIndex;
                }
            }
            IElevationService elevationService = new ElevationService(settings);

            //validation auth.config
            if (boolNeedsSetup)
            {
                AuthAPIForm form = new AuthAPIForm(true);
                if (form.ShowDialog() == DialogResult.OK)
                {
                    settings.Auth.APIConfig = form.Config;
                }
            }
            else
            {
                var apiCfg = settings.Auth.APIConfig;

                if (apiCfg.UsePogoDevAPI)
                {
                    if (string.IsNullOrEmpty(apiCfg.AuthAPIKey))
                    {
                        Logger.Write(
                            "You select pogodev API but not provide API Key, please press any key to exit and correct you auth.json, \r\n The Pogodev API key call be purchased at - https://talk.pogodev.org/d/51-api-hashing-service-by-pokefarmer",
                            LogLevel.Error
                            );

                        Console.ReadKey();
                        Environment.Exit(0);
                    }
                    //TODO - test api call to valida auth key
                }
                else if (apiCfg.UseLegacyAPI)
                {
                    Logger.Write(
                        "You bot will start after 15 second, You are running bot with  Legacy API (0.45) it will increase your risk to be banned and trigger captcha. Config captcha in config.json to auto resolve them",
                        LogLevel.Warning
                        );

#if RELEASE
                    Thread.Sleep(15000);
#endif
                }
                else
                {
                    Logger.Write(
                        "At least 1 authentication method is selected, please correct your auth.json, ",
                        LogLevel.Error
                        );
                    Console.ReadKey();
                    Environment.Exit(0);
                }
            }

            _session = new Session(settings,
                                   new ClientSettings(settings, elevationService), logicSettings, elevationService,
                                   translation
                                   );
            ioc.Register <ISession>(_session);

            Logger.SetLoggerContext(_session);

            MultiAccountManager accountManager = new MultiAccountManager(logicSettings.Bots);
            ioc.Register <MultiAccountManager>(accountManager);

            if (boolNeedsSetup)
            {
                StarterConfigForm configForm = new StarterConfigForm(_session, settings, elevationService, configFile);
                if (configForm.ShowDialog() == DialogResult.OK)
                {
                    var fileName = Assembly.GetEntryAssembly().Location;

                    Process.Start(fileName);
                    Environment.Exit(0);
                }

                //if (GlobalSettings.PromptForSetup(_session.Translation))
                //{
                //    _session = GlobalSettings.SetupSettings(_session, settings, elevationService, configFile);

                //    var fileName = Assembly.GetExecutingAssembly().Location;
                //    Process.Start(fileName);
                //    Environment.Exit(0);
                //}
                else
                {
                    GlobalSettings.Load(_subPath, _enableJsonValidation);

                    Logger.Write("Press a Key to continue...",
                                 LogLevel.Warning);
                    Console.ReadKey();
                    return;
                }

                if (excelConfigAllow)
                {
                    ExcelConfigHelper.MigrateFromObject(settings, excelConfigFile);
                }
            }

            ProgressBar.Start("NecroBot2 is starting up", 10);

            ProgressBar.Fill(20);

            var machine = new StateMachine();
            var stats   = _session.RuntimeStatistics;

            ProgressBar.Fill(30);
            var strVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString(4);
            stats.DirtyEvent +=
                () =>
                Console.Title = $"[Necrobot2 v{strVersion}] " +
                                stats.GetTemplatedStats(
                    _session.Translation.GetTranslation(TranslationString.StatsTemplateString),
                    _session.Translation.GetTranslation(TranslationString.StatsXpTemplateString));
            ProgressBar.Fill(40);

            var aggregator = new StatisticsAggregator(stats);
            if (onBotStarted != null)
            {
                onBotStarted(_session, aggregator);
            }

            ProgressBar.Fill(50);
            var listener = new ConsoleEventListener();
            ProgressBar.Fill(60);
            var snipeEventListener = new SniperEventListener();

            _session.EventDispatcher.EventReceived += evt => listener.Listen(evt, _session);
            _session.EventDispatcher.EventReceived += evt => aggregator.Listen(evt, _session);
            _session.EventDispatcher.EventReceived += evt => snipeEventListener.Listen(evt, _session);

            ProgressBar.Fill(70);

            machine.SetFailureState(new LoginState());
            ProgressBar.Fill(80);

            ProgressBar.Fill(90);

            _session.Navigation.WalkStrategy.UpdatePositionEvent +=
                (session, lat, lng, speed) => _session.EventDispatcher.Send(new UpdatePositionEvent {
                Latitude = lat, Longitude = lng, Speed = speed
            });
            _session.Navigation.WalkStrategy.UpdatePositionEvent += LoadSaveState.SaveLocationToDisk;

            ProgressBar.Fill(100);

            //TODO: temporary
            if (settings.Auth.APIConfig.UseLegacyAPI)
            {
                Logger.Write("The PoGoDev Community Has Updated The Hashing Service To Be Compatible With 0.57.4 So We Have Updated Our Code To Be Compliant. Unfortunately During This Update Niantic Has Also Attempted To Block The Legacy .45 Service Again So At The Moment Only Hashing Service Users Are Able To Login Successfully. Please Be Patient As Always We Will Attempt To Keep The Bot 100% Free But Please Realize We Have Already Done Quite A Few Workarounds To Keep .45 Alive For You Guys.  Even If We Are Able To Get Access Again To The .45 API Again It Is Over 3 Months Old So Is Going To Be More Detectable And Cause Captchas. Please Consider Upgrading To A Paid API Key To Avoid Captchas And You Will  Be Connecting Using Latest Version So Less Detectable So More Safe For You In The End.", LogLevel.Warning);
                Logger.Write("The bot will now close", LogLevel.Error);
                Console.ReadLine();
                Environment.Exit(0);
                return;
            }
            //

            if (settings.WebsocketsConfig.UseWebsocket)
            {
                var websocket = new WebSocketInterface(settings.WebsocketsConfig.WebSocketPort, _session);
                _session.EventDispatcher.EventReceived += evt => websocket.Listen(evt, _session);
            }

            var bot = accountManager.GetStartUpAccount();

            _session.ReInitSessionWithNextBot(bot);

            machine.AsyncStart(new VersionCheckState(), _session, _subPath, excelConfigAllow);

            try
            {
                Console.Clear();
            }
            catch (IOException)
            {
            }

            if (settings.TelegramConfig.UseTelegramAPI)
            {
                _session.Telegram = new TelegramService(settings.TelegramConfig.TelegramAPIKey, _session);
            }

            if (_session.LogicSettings.EnableHumanWalkingSnipe &&
                _session.LogicSettings.HumanWalkingSnipeUseFastPokemap)
            {
                // jjskuld - Ignore CS4014 warning for now.
                //#pragma warning disable 4014
                HumanWalkSnipeTask.StartFastPokemapAsync(_session,
                                                         _session.CancellationTokenSource.Token).ConfigureAwait(false); // that need to keep data live
                //#pragma warning restore 4014
            }

            if (_session.LogicSettings.UseSnipeLocationServer ||
                _session.LogicSettings.HumanWalkingSnipeUsePogoLocationFeeder)
            {
                SnipePokemonTask.AsyncStart(_session);
            }


            if (_session.LogicSettings.DataSharingConfig.EnableSyncData)
            {
                BotDataSocketClient.StartAsync(_session);
                _session.EventDispatcher.EventReceived += evt => BotDataSocketClient.Listen(evt, _session);
            }
            settings.CheckProxy(_session.Translation);

            if (_session.LogicSettings.ActivateMSniper)
            {
                ServicePointManager.ServerCertificateValidationCallback +=
                    (sender, certificate, chain, sslPolicyErrors) => true;
                //temporary disable MSniper connection because site under attacking.
                //MSniperServiceTask.ConnectToService();
                //_session.EventDispatcher.EventReceived += evt => MSniperServiceTask.AddToList(evt);
            }
            var trackFile = Path.GetTempPath() + "\\necrobot2.io";

            if (!File.Exists(trackFile) || File.GetLastWriteTime(trackFile) < DateTime.Now.AddDays(-1))
            {
                Thread.Sleep(10000);
                Thread mThread = new Thread(delegate()
                {
                    var infoForm = new InfoForm();
                    infoForm.ShowDialog();
                });
                File.WriteAllText(trackFile, DateTime.Now.Ticks.ToString());
                mThread.SetApartmentState(ApartmentState.STA);

                mThread.Start();
            }

            QuitEvent.WaitOne();
        }
Esempio n. 25
0
 /// <summary>
 /// 连接SocketServer-多个Server-包括监测掉线后重试等
 /// </summary>
 private void ConnectSocketServerNew()
 {
     try
     {
         //遍历配置文件,连接
         foreach (var item in Config.SocketServerAdresses)
         {
             string       curAdressAndPort = string.Format("{0}:{1}", item.Key, item.Value);
             SocketClient curSocketClient  = null;
             ///是否首次增加
             bool isFirAdd = false;
             List <SocketClient> findClients = clients.Where(c => c.socketAdress == curAdressAndPort).ToList();
             if (findClients == null || findClients.Count == 0)
             {
                 isFirAdd = true;
                 //设定服务器IP地址并连接
                 curSocketClient = new SocketClient();
                 curSocketClient.socketAdress = curAdressAndPort;
                 IPAddress ipAdress = IPAddress.Parse(item.Key);
                 curSocketClient.client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
             }
             else
             {
                 curSocketClient = findClients.FirstOrDefault();
             }
             //开始准备连接
             try
             {
                 if (curSocketClient.isConnected == false)
                 {
                     //关闭,并重新初始化
                     curSocketClient.client.Close();
                     curSocketClient.client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                     //连接
                     curSocketClient.client.Connect(item.Key, item.Value);
                     LogInfo(String.Format("连接{0}成功~", curAdressAndPort));
                     curSocketClient.isConnected = true;
                     //启动监听请求
                     Thread clientReceiveThread = new Thread(ReceiveMessageNew);
                     clientReceiveThread.SetApartmentState(ApartmentState.STA);//这句是关键
                     clientReceiveThread.Start(curSocketClient);
                 }
             }
             catch (Exception ex)
             {
                 curSocketClient.isConnected = false;
                 LogInfo(String.Format("{0}连接异常:{1}", curAdressAndPort, ex.Message));
             }
             if (isFirAdd)
             {
                 clients.Add(curSocketClient);
             }
             if (curSocketClient.isConnected)
             {
                 //如果渠道正常,则发送消息
                 SendToServerNew(curSocketClient, "hello~");
             }
         }
     }
     catch (Exception ex)
     {
         LogInfo(String.Format("执行ConnectSocketServerNew连接异常:{0}", ex.Message));
     }
 }
Esempio n. 26
0
        private static DataSeriesBox show(String title, double[] x, double[][] series,
                                          bool time = false)
        {
            DataSeriesBox form       = null;
            Thread        formThread = null;

            if (title == null)
            {
                title = "Time series";
            }

            x = (double[])x.Clone();
            var idx = Vector.Range(0, x.Length);

            Array.Sort(x, idx);

            for (int i = 0; i < series.Length; i++)
            {
                series[i] = series[i].Get(idx);
            }

            AutoResetEvent stopWaitHandle = new AutoResetEvent(false);

            formThread = new Thread(() =>
            {
                Accord.Controls.Tools.ConfigureWindowsFormsApplication();

                // Show control in a form
                form            = new DataSeriesBox();
                form.Text       = title;
                form.formThread = formThread;

                var pane = form.zedGraphControl.GraphPane;

                if (time)
                {
                    pane.XAxis.Type            = AxisType.Date;
                    pane.XAxis.Scale.MajorUnit = DateUnit.Hour;
                    pane.XAxis.Scale.Format    = "T";
                }

                var sequence = new ColorSequenceCollection(series.Length);

                for (int i = 0; i < series.Length; i++)
                {
                    if (x == null)
                    {
                        x = Vector.Range(0, series[i].Length).ToDouble();
                    }

                    var lineItem = new LineItem(i.ToString(), x,
                                                series[i], sequence.GetColor(i), SymbolType.None);

                    form.series.Add(lineItem);
                }

                pane.Title.Text = title;
                pane.AxisChange();

                stopWaitHandle.Set();

                Application.Run(form);
            });

            formThread.SetApartmentState(ApartmentState.STA);

            formThread.Start();

            stopWaitHandle.WaitOne();

            return(form);
        }
Esempio n. 27
0
        public static string GetInputText(string oldString)
        {
            if (!Main.hasFocus)
            {
                return(oldString);
            }
            inputTextEnter  = false;
            inputTextEscape = false;
            string text    = oldString;
            string newKeys = "";

            if (text == null)
            {
                text = "";
            }
            bool flag = false;

            if (inputText.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.LeftControl) || inputText.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.RightControl))
            {
                if (inputText.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Z) && !oldInputText.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Z))
                {
                    text = "";
                }
                else if (inputText.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.X) && !oldInputText.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.X))
                {
                    PlatformUtilities.SetClipboard(oldString);
                    text = "";
                }
                else if ((inputText.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.C) && !oldInputText.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.C)) || (inputText.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Insert) && !oldInputText.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Insert)))
                {
                    PlatformUtilities.SetClipboard(oldString);
                }
                else if (inputText.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.V) && !oldInputText.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.V))
                {
                    newKeys += PlatformUtilities.GetClipboard();
                }
            }
            else
            {
                if (inputText.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.LeftShift) || inputText.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.RightShift))
                {
                    if (inputText.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Delete) && !oldInputText.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Delete))
                    {
                        Thread thread = new Thread((ThreadStart) delegate
                        {
                            if (oldString.Length > 0)
                            {
                                Clipboard.SetText(oldString);
                            }
                        });
                        thread.SetApartmentState(ApartmentState.STA);
                        thread.Start();
                        while (thread.IsAlive)
                        {
                        }
                        text = "";
                    }
                    if (inputText.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Insert) && !oldInputText.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Insert))
                    {
                        Thread thread2 = new Thread((ThreadStart) delegate
                        {
                            string text2 = Clipboard.GetText();
                            for (int l = 0; l < text2.Length; l++)
                            {
                                if (text2[l] < ' ' || text2[l] == '\u007f')
                                {
                                    text2 = text2.Replace(string.Concat(text2[l--]), "");
                                }
                            }
                            newKeys += text2;
                        });
                        thread2.SetApartmentState(ApartmentState.STA);
                        thread2.Start();
                        while (thread2.IsAlive)
                        {
                        }
                    }
                }
                for (int i = 0; i < Main.keyCount; i++)
                {
                    int    num = Main.keyInt[i];
                    string str = Main.keyString[i];
                    if (num == 13)
                    {
                        inputTextEnter = true;
                    }
                    else if (num == 27)
                    {
                        inputTextEscape = true;
                    }
                    else if (num >= 32 && num != 127)
                    {
                        newKeys += str;
                    }
                }
            }
            Main.keyCount = 0;
            text         += newKeys;
            oldInputText  = inputText;
            inputText     = Keyboard.GetState();
            Microsoft.Xna.Framework.Input.Keys[] pressedKeys  = inputText.GetPressedKeys();
            Microsoft.Xna.Framework.Input.Keys[] pressedKeys2 = oldInputText.GetPressedKeys();
            if (inputText.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Back) && oldInputText.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Back))
            {
                if (backSpaceCount == 0)
                {
                    backSpaceCount = 7;
                    flag           = true;
                }
                backSpaceCount--;
            }
            else
            {
                backSpaceCount = 15;
            }
            for (int j = 0; j < pressedKeys.Length; j++)
            {
                bool flag2 = true;
                for (int k = 0; k < pressedKeys2.Length; k++)
                {
                    if (pressedKeys[j] == pressedKeys2[k])
                    {
                        flag2 = false;
                    }
                }
                string a = string.Concat(pressedKeys[j]);
                if (a == "Back" && (flag2 || flag) && text.Length > 0)
                {
                    TextSnippet[] array = ChatManager.ParseMessage(text, Microsoft.Xna.Framework.Color.White);
                    if (array[array.Length - 1].DeleteWhole)
                    {
                        text = text.Substring(0, text.Length - array[array.Length - 1].TextOriginal.Length);
                    }
                    else
                    {
                        text = text.Substring(0, text.Length - 1);
                    }
                }
            }
            return(text);
        }
Esempio n. 28
0
        static void InitializeSensor()
        {
            var sensor = Sensor;

            if (sensor != null)
            {
                return;
            }

            try
            {
                sensor = KinectSensor.GetDefault();
                if (sensor == null)
                {
                    return;
                }

                var reader = sensor.OpenMultiSourceFrameReader(FrameSourceTypes.Depth | FrameSourceTypes.Color | FrameSourceTypes.BodyIndex);
                reader.MultiSourceFrameArrived += Reader_MultiSourceFrameArrived;

                coordinateMapper = sensor.CoordinateMapper;

                FrameDescription depthFrameDescription = sensor.DepthFrameSource.FrameDescription;

                int depthWidth  = depthFrameDescription.Width;
                int depthHeight = depthFrameDescription.Height;

                FrameDescription colorFrameDescription = sensor.ColorFrameSource.FrameDescription;

                int colorWidth  = colorFrameDescription.Width;
                int colorHeight = colorFrameDescription.Height;

                colorMappedToDepthPoints = new DepthSpacePoint[colorWidth * colorHeight];

                sensor.Open();

                Sensor = sensor;

                if (context == null)
                {
                    contexThread = new Thread(() =>
                    {
                        context = new KinectCamApplicationContext();
                        Application.Run(context);
                    });
                    refreshThread = new Thread(() =>
                    {
                        while (true)
                        {
                            Thread.Sleep(250);
                            Application.DoEvents();
                        }
                    });
                    contexThread.IsBackground  = true;
                    refreshThread.IsBackground = true;
                    contexThread.SetApartmentState(ApartmentState.STA);
                    refreshThread.SetApartmentState(ApartmentState.STA);
                    contexThread.Start();
                    refreshThread.Start();
                }
            }
            catch
            {
                Trace.WriteLine("Error of enable the Kinect sensor!");
            }
        }
Esempio n. 29
0
        private PageTitleFixture GoToWebSite()
        {
            /*     var thread = new Thread(new ThreadStart(StartWindows));
             *
             *  thread.SetApartmentState(ApartmentState.STA);
             *  thread.Start();
             *  thread.Join();
             */



            var thread = new Thread(new ThreadStart(StartWindows));

            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
            thread.Join();


            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);

            request.MaximumAutomaticRedirections = 4;
            request.MaximumResponseHeadersLength = 4;
            // Set credentials to use for this request.
            request.Credentials = CredentialCache.DefaultCredentials;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            Console.WriteLine("Content length is {0}", response.ContentLength);
            Console.WriteLine("Content type is {0}", response.ContentType);
            // Get the stream associated with the response.
            Stream receiveStream = response.GetResponseStream();

            // Pipes the stream to a higher level stream reader with the required encoding format.
            StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);

            Console.WriteLine("Response stream received.");


            string responseValue = readStream.ReadToEnd();

            doc = NSoup.NSoupClient.ParseBodyFragment(responseValue);

            Elements element = doc.GetElementsByTag("Title");



            response.Close();
            readStream.Close();


            HttpStatusCode = response.StatusCode.GetHashCode().ToString();

            Console.WriteLine(response.StatusCode);



            PageTitle = element.Text;

//            Console.WriteLine("Response stream received.\n {0}",responseValue);

            Elements links = doc.GetElementsByTag("a");
            int      count = 0;

            foreach (var _link in links)
            {
                Element linkByLink = _link.TagName("a href");

                if (!linkByLink.Text().ToString().Equals(""))
                {
                    //var linkText = _link.TagName("a href").Text;
                    //Console.WriteLine("Link ={0}", linkByLink.Text());
                    //listOfLinks.Add(linkByLink.Text());

                    String absHref = linkByLink.Attr("abs:href");
                    Console.WriteLine("Link ={0}", absHref);

                    LinkNameAndLink.Add(count + "_" + linkByLink.Text(), absHref);

                    count++;
                }
            }

            _noOfLinks = count.ToString();

            return(null);
        }
Esempio n. 30
0
        public Result SettingsWindow()
        {
            Result newSetting = new Result(); // Opretter resultat til listen

            newSetting.Title    = "Settings";
            newSetting.SubTitle = DateTime.Now.ToString();
            newSetting.Action   = context => // sætter action på hver story
            {
                var thread = new Thread(() =>
                {
                    bw        = new Window();
                    bw.Height = 800;
                    bw.Width  = 500;

                    StackPanel stackPanel = new StackPanel();
                    Label label           = new Label();
                    label.Content         = "Settings";
                    label.Height          = 100;
                    label.Width           = 100;
                    stackPanel.Children.Add(label);

                    Grid grid = new Grid();
                    grid.ColumnDefinitions.Add(new ColumnDefinition()
                    {
                        Width = new GridLength(250)
                    });
                    grid.ColumnDefinitions.Add(new ColumnDefinition()
                    {
                        Width = new GridLength(250)
                    });
                    grid.RowDefinitions.Add(new RowDefinition());
                    grid.RowDefinitions.Add(new RowDefinition());
                    grid.RowDefinitions.Add(new RowDefinition());
                    grid.RowDefinitions.Add(new RowDefinition());
                    grid.RowDefinitions.Add(new RowDefinition());
                    grid.RowDefinitions.Add(new RowDefinition());
                    grid.RowDefinitions.Add(new RowDefinition());
                    grid.RowDefinitions.Add(new RowDefinition());
                    grid.RowDefinitions.Add(new RowDefinition());
                    stackPanel.Children.Add(grid);

                    checkboxList         = new List <CheckBox>();
                    int rowDefinition    = 0;
                    int columnDefinition = 0;

                    foreach (Feeds feed in Feeds.FeedsList)
                    {
                        CheckBox checkbox            = new CheckBox();
                        checkbox.Content             = feed.Name;
                        checkbox.IsChecked           = feed.ToBeSeen;
                        checkbox.Width               = 200;
                        checkbox.Height              = 50;
                        checkbox.HorizontalAlignment = HorizontalAlignment.Left;
                        checkbox.Margin              = new Thickness(10, 0, 0, 0);
                        grid.Children.Add(checkbox);
                        Grid.SetColumn(checkbox, columnDefinition);
                        Grid.SetRow(checkbox, rowDefinition);
                        checkboxList.Add(checkbox);

                        rowDefinition++;
                        if (rowDefinition == 8)
                        {
                            rowDefinition    = 0;
                            columnDefinition = 1;
                        }
                    }

                    Button saveSettings   = new Button();
                    saveSettings.FontSize = 16;
                    saveSettings.Content  = "Save settings";
                    saveSettings.Height   = 100;
                    saveSettings.Width    = 500;
                    saveSettings.Click   += SaveSettings_Click;
                    stackPanel.Children.Add(saveSettings);

                    bw.Content = stackPanel;
                    bw.Show();
                    bw.Closed += (s, e) => bw.Dispatcher.InvokeShutdown();
                    Dispatcher.Run();
                });
                thread.SetApartmentState(ApartmentState.STA);
                //thread.IsBackground = true;
                thread.Start();

                return(false);// True bestemmer at wox skal lukke, når man trykker på story
            };

            return(newSetting);
        }
Esempio n. 31
0
 private void DisplayReleaseNotesIfNecessary()
 {
     var thread = new Thread(DisplayReleaseNotesIfNecessaryProc);
     thread.SetApartmentState(ApartmentState.STA);
     thread.Start();
 }
        public PythonConsole(PythonTextEditor textEditor, CommandLine commandLine)
        {
            waitHandles = new WaitHandle[] { lineReceivedEvent, disposedEvent };

            this.commandLine = commandLine;
            this.textEditor  = textEditor;
            textEditor.CompletionProvider = new PythonConsoleCompletionDataProvider(commandLine)
            {
                ExcludeCallables = disableAutocompletionForCallables
            };
            textEditor.PreviewKeyDown += textEditor_PreviewKeyDown;
            textEditor.TextEntering   += textEditor_TextEntering;
            dispatcherThread           = new Thread(new ThreadStart(DispatcherThreadStartingPoint));
            dispatcherThread.SetApartmentState(ApartmentState.STA);
            dispatcherThread.IsBackground = true;
            dispatcherThread.Start();

            // Only required when running outside REP loop.
            prompt = ">>> ";

            // Set commands:
            this.textEditor.textArea.Dispatcher.Invoke(new Action(delegate()
            {
                CommandBinding pasteBinding  = null;
                CommandBinding copyBinding   = null;
                CommandBinding cutBinding    = null;
                CommandBinding undoBinding   = null;
                CommandBinding deleteBinding = null;
                foreach (CommandBinding commandBinding in (this.textEditor.textArea.CommandBindings))
                {
                    if (commandBinding.Command == ApplicationCommands.Paste)
                    {
                        pasteBinding = commandBinding;
                    }
                    if (commandBinding.Command == ApplicationCommands.Copy)
                    {
                        copyBinding = commandBinding;
                    }
                    if (commandBinding.Command == ApplicationCommands.Cut)
                    {
                        cutBinding = commandBinding;
                    }
                    if (commandBinding.Command == ApplicationCommands.Undo)
                    {
                        undoBinding = commandBinding;
                    }
                    if (commandBinding.Command == ApplicationCommands.Delete)
                    {
                        deleteBinding = commandBinding;
                    }
                }
                // Remove current bindings completely from control. These are static so modifying them will cause other
                // controls' behaviour to change too.
                if (pasteBinding != null)
                {
                    this.textEditor.textArea.CommandBindings.Remove(pasteBinding);
                }
                if (copyBinding != null)
                {
                    this.textEditor.textArea.CommandBindings.Remove(copyBinding);
                }
                if (cutBinding != null)
                {
                    this.textEditor.textArea.CommandBindings.Remove(cutBinding);
                }
                if (undoBinding != null)
                {
                    this.textEditor.textArea.CommandBindings.Remove(undoBinding);
                }
                if (deleteBinding != null)
                {
                    this.textEditor.textArea.CommandBindings.Remove(deleteBinding);
                }
                this.textEditor.textArea.CommandBindings.Add(new CommandBinding(ApplicationCommands.Paste, OnPaste, CanPaste));
                this.textEditor.textArea.CommandBindings.Add(new CommandBinding(ApplicationCommands.Copy, OnCopy, PythonEditingCommandHandler.CanCutOrCopy));
                this.textEditor.textArea.CommandBindings.Add(new CommandBinding(ApplicationCommands.Cut, PythonEditingCommandHandler.OnCut, CanCut));
                this.textEditor.textArea.CommandBindings.Add(new CommandBinding(ApplicationCommands.Undo, OnUndo, CanUndo));
                this.textEditor.textArea.CommandBindings.Add(new CommandBinding(ApplicationCommands.Delete, PythonEditingCommandHandler.OnDelete(ApplicationCommands.NotACommand), CanDeleteCommand));
            }));
            CodeContext codeContext = DefaultContext.Default;

            //Set dispatcher to run on a UI thread independent of both the Control UI thread and thread running the REPL.
            ClrModule.SetCommandDispatcher(codeContext, DispatchCommand);
        }
        private void btnDescargaPdf_Click(object sender, EventArgs e)
        {
            PdfDocument         pdf = new PdfDocument();
            PdfHtmlLayoutFormat htmlLayoutFormat = new PdfHtmlLayoutFormat();

            htmlLayoutFormat.IsWaiting = false;
            PdfPageSettings setting = new PdfPageSettings();

            setting.Size = PdfPageSize.A4;
            Dictionary <string, string> datosFrm = new Dictionary <string, string>();
            UsuarioBLL negocioUsuario            = new UsuarioBLL();

            DAL.VS_Login.VHWServiceClient VHWS = new DAL.VS_Login.VHWServiceClient();

            var resp = VHWS.lstCantidadPermisoEstado().ToList();
            //datosFrm = negocioUsuario.frmPermisoUsuario(1061);
            //string idSolicitud = (new System.Collections.Generic.Mscorlib_DictionaryDebugView<string, string>(datosFrm)).Items[0].Value;
            //string rutFuncionario = (new System.Collections.Generic.Mscorlib_DictionaryDebugView<string, string>(datosFrm)).Items[3].Value;
            //string htmlCode = File.ReadAllText("..\\..\\2.html");
            string htmlCode = @"<h1 style='text-align: center;'><span style='text-decoration: underline;'>Resumen de permisos por unidad interna</span></h1><p>&nbsp;</p>";

            foreach (var item in resp)
            {
                htmlCode = htmlCode + @"<p style='text-align: center;'><em><strong>ID UNIDAD INTERNA: {0}</strong></em></p>
<p style='text-align: center;'>&nbsp;</p>
<p style='text-align: center;'><em><strong>CANTIDAD: {1}</strong></em></p>
<p style='text-align: center;'>&nbsp;</p>
<p style='text-align: center;'><em><strong>RECURSO LEGAL: {2}</strong></em></p>
<p>&nbsp;</p>
<p>&nbsp;</p>";
                htmlCode = string.Format(htmlCode, item.unidadInterna, item.cantidad, item.recursoLegal);
            }

            htmlCode = htmlCode.Replace(System.Environment.NewLine, string.Empty);

            Thread thread = new Thread(() =>
                                       { pdf.LoadFromHTML(htmlCode, false, setting, htmlLayoutFormat); });

            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
            thread.Join();

            SaveFileDialog MyFiles = new SaveFileDialog();

            MyFiles.Filter     = "PDF Files|*.pdf";
            MyFiles.Title      = "GUARDAR COMPROBANTE PERMISO";
            MyFiles.DefaultExt = "*.pdf";
            MyFiles.FileName   = "resumenPermisoUnidadInterna";
            if (MyFiles.ShowDialog() == DialogResult.OK)
            {
                if (File.Exists(MyFiles.FileName))
                {
                    File.Delete(MyFiles.FileName);
                }

                //File.Copy(path, MyFiles.FileName);
                pdf.SaveToFile(MyFiles.FileName);
            }


            //System.Diagnostics.Process.Start("output.pdf");
        }
Esempio n. 34
0
            public static void SaveConnectionsBG()
            {
                _saveUpdate = true;

                var t = new Thread(SaveConnectionsBGd);
                t.SetApartmentState(ApartmentState.STA);
                t.Start();
            }
Esempio n. 35
0
            private static void LoadConnectionsBG(bool WithDialog = false, bool Update = false)
            {
                _withDialog = false;
                _loadUpdate = true;

                Thread t = new Thread(LoadConnectionsBGd);
                t.SetApartmentState(ApartmentState.STA);
                t.Start();
            }
Esempio n. 36
0
        private void CopyToClipBoardCmd() // Copies content of window to clipboard
        {
            try
            {
                ForceGetInfo();

                StringBuilder sb = new StringBuilder();

                sb.AppendLine(String.Format("Keppy's Synthesizer version {0}", Driver.FileVersion));
                sb.AppendLine("========= Debug information =========");
                sb.AppendLine(String.Format("Driver version: {0}", Driver.FileVersion));
                sb.AppendLine(String.Format("{0} {1}", CMALabel.Text, CMA.Text));
                sb.AppendLine(String.Format("{0} {1}", AVLabel.Text, AV.Text));
                sb.AppendLine(String.Format("{0} {1}", AvVLabel.Text, AvV.Text));
                sb.AppendLine(String.Format("{0} {1}", RTLabel.Text, RT.Text));
                if ((int)Settings.GetValue("xaudiodisabled", "0") == 2 || (int)Settings.GetValue("xaudiodisabled", "0") == 3)
                {
                    sb.AppendLine(String.Format("{0} {1}", AERTLabel.Text, AERT.Text));
                }
                else
                {
                    sb.AppendLine(String.Format("{0} {1}", DDSLabel.Text, DDS.Text));
                }
                sb.AppendLine(String.Format("{0} {1}", RAMUsageVLabel.Text, RAMUsageV.Text));
                sb.AppendLine(String.Format("{0} {1}", HCountVLabel.Text, HCountV.Text));
                sb.AppendLine("======= Channels  information =======");
                sb.AppendLine(String.Format("{0} {1}", CHV1L.Text, CHV1.Text));
                sb.AppendLine(String.Format("{0} {1}", CHV2L.Text, CHV2.Text));
                sb.AppendLine(String.Format("{0} {1}", CHV3L.Text, CHV3.Text));
                sb.AppendLine(String.Format("{0} {1}", CHV4L.Text, CHV4.Text));
                sb.AppendLine(String.Format("{0} {1}", CHV5L.Text, CHV5.Text));
                sb.AppendLine(String.Format("{0} {1}", CHV6L.Text, CHV6.Text));
                sb.AppendLine(String.Format("{0} {1}", CHV7L.Text, CHV7.Text));
                sb.AppendLine(String.Format("{0} {1}", CHV8L.Text, CHV8.Text));
                sb.AppendLine(String.Format("{0} {1}", CHV9L.Text, CHV9.Text));
                sb.AppendLine(String.Format("{0} {1}", CHV10L.Text, CHV10.Text));
                sb.AppendLine(String.Format("{0} {1}", CHV11L.Text, CHV11.Text));
                sb.AppendLine(String.Format("{0} {1}", CHV12L.Text, CHV12.Text));
                sb.AppendLine(String.Format("{0} {1}", CHV13L.Text, CHV13.Text));
                sb.AppendLine(String.Format("{0} {1}", CHV14L.Text, CHV14.Text));
                sb.AppendLine(String.Format("{0} {1}", CHV15L.Text, CHV15.Text));
                sb.AppendLine(String.Format("{0} {1}", CHV16L.Text, CHV16.Text));
                sb.AppendLine("======== System  information ========");
                sb.AppendLine(String.Format("Driver version: {0}", Driver.FileVersion));
                sb.AppendLine(String.Format("{0} {1}", COSLabel.Text, COS.Text));
                sb.AppendLine(String.Format("{0} {1}", CPULabel.Text, CPU.Text));
                sb.AppendLine(String.Format("{0} {1}", CPUInfoLabel.Text, CPUInfo.Text));
                sb.AppendLine(String.Format("{0} {1}", GPULabel.Text, GPU.Text));
                sb.AppendLine(String.Format("{0} {1}", GPUInternalChipLabel.Text, GPUInternalChip.Text));
                sb.AppendLine(String.Format("{0} {1}", GPUInfoLabel.Text, GPUInfo.Text));
                sb.AppendLine(String.Format("{0} {1}", TMLabel.Text, TM.Text));
                sb.AppendLine(String.Format("{0} {1}", AMLabel.Text, AM.Text));
                sb.AppendLine(String.Format("{0} {1}", MTLabel.Text, MT.Text));

                Thread thread = new Thread(() => Clipboard.SetText(sb.ToString())); // Creates another thread, otherwise the form locks up while copying the richtextbox
                thread.SetApartmentState(ApartmentState.STA);
                thread.Start();
                thread.Join();
            }
            catch {
                // lel
            }
            finally
            {
                MessageBox.Show("Info copied to clipboard.", "Notification", MessageBoxButtons.OK, MessageBoxIcon.Information); // Done, now get out
            }
        }
Esempio n. 37
0
        private static void InvokeConfiguration(ref dynamic vaProxy)
        {
            string config = (string)vaProxy.Context;

            if (configWindow == null && config != "configuration")
            {
                vaProxy.WriteToLog("The EDDI configuration window is not open.", "orange");
                return;
            }

            switch (config)
            {
            case "configuration":
                // Ensure there's only one instance of the configuration UI
                if (configWindow == null)
                {
                    Thread configThread = new Thread(() =>
                    {
                        try
                        {
                            configWindow          = new MainWindow(true);
                            configWindow.Closing += new CancelEventHandler(eddiClosing);
                            configWindow.ShowDialog();

                            // Bind Cargo monitor inventory, Material Monitor inventory, & Ship monitor shipyard collections to the EDDI config Window
                            ((CargoMonitor)EDDI.Instance.ObtainMonitor("Cargo monitor")).EnableConfigBinding(configWindow);
                            ((MaterialMonitor)EDDI.Instance.ObtainMonitor("Material monitor")).EnableConfigBinding(configWindow);
                            ((MissionMonitor)EDDI.Instance.ObtainMonitor("Mission monitor")).EnableConfigBinding(configWindow);
                            ((ShipMonitor)EDDI.Instance.ObtainMonitor("Ship monitor")).EnableConfigBinding(configWindow);

                            configWindow = null;
                        }
                        catch (ThreadAbortException)
                        {
                            Logging.Debug("Thread aborted");
                        }
                        catch (Exception ex)
                        {
                            Logging.Warn("Show configuration window failed", ex);
                        }
                    });
                    configThread.SetApartmentState(ApartmentState.STA);
                    configThread.Start();
                }
                else
                {
                    // Tell the configuration UI to restore its window if minimized
                    setWindowState(ref vaProxy, WindowState.Minimized, true, false);
                    vaProxy.WriteToLog("The EDDI configuration window is already open.", "orange");
                }
                break;

            case "configurationminimize":
                setWindowState(ref vaProxy, WindowState.Minimized);
                break;

            case "configurationmaximize":
                setWindowState(ref vaProxy, WindowState.Maximized);
                break;

            case "configurationrestore":
                setWindowState(ref vaProxy, WindowState.Normal);
                break;

            case "configurationclose":
                // Unbind the Cargo Monitor inventory, Material Monitor inventory, & Ship Monitor shipyard collections from the EDDI config window
                ((CargoMonitor)EDDI.Instance.ObtainMonitor("Cargo monitor")).DisableConfigBinding(configWindow);
                ((MaterialMonitor)EDDI.Instance.ObtainMonitor("Material monitor")).DisableConfigBinding(configWindow);
                ((MissionMonitor)EDDI.Instance.ObtainMonitor("Mission monitor")).DisableConfigBinding(configWindow);
                ((ShipMonitor)EDDI.Instance.ObtainMonitor("Ship monitor")).DisableConfigBinding(configWindow);

                configWindow.Dispatcher.Invoke(configWindow.Close);

                if (eddiCloseCancelled)
                {
                    vaProxy.WriteToLog("The EDDI window cannot be closed at this time.", "orange");
                }
                else
                {
                    configWindow = null;
                }
                break;

            default:
                vaProxy.WriteToLog("Plugin context \"" + (string)vaProxy.Context + "\" not recognized.", "orange");
                break;
            }
        }
Esempio n. 38
0
        public static void RunBotWithParameters(Action <ISession, StatisticsAggregator> onBotStarted, string[] args)
        {
            var ioc = TinyIoC.TinyIoCContainer.Current;

            //Setup Logger for API
            APIConfiguration.Logger = new APILogListener();

            //Application.EnableVisualStyles();
            var strCulture = Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;

            var culture = CultureInfo.CreateSpecificCulture("en");

            CultureInfo.DefaultThreadCurrentCulture = culture;
            Thread.CurrentThread.CurrentCulture     = culture;

            AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionEventHandler;

            Console.Title           = @"NecroBot2 Loading";
            Console.CancelKeyPress += (sender, eArgs) =>
            {
                QuitEvent.Set();
                eArgs.Cancel = true;
            };

            // Command line parsing
            var commandLine = new Arguments(args);

            // Look for specific arguments values
            if (commandLine["subpath"] != null && commandLine["subpath"].Length > 0)
            {
                _subPath = commandLine["subpath"];
            }
            if (commandLine["jsonvalid"] != null && commandLine["jsonvalid"].Length > 0)
            {
                switch (commandLine["jsonvalid"])
                {
                case "true":
                    _enableJsonValidation = true;
                    break;

                case "false":
                    _enableJsonValidation = false;
                    break;
                }
            }
            if (commandLine["killswitch"] != null && commandLine["killswitch"].Length > 0)
            {
                switch (commandLine["killswitch"])
                {
                case "true":
                    _ignoreKillSwitch = false;
                    break;

                case "false":
                    _ignoreKillSwitch = true;
                    break;
                }
            }

            bool excelConfigAllow = false;

            if (commandLine["provider"] != null && commandLine["provider"] == "excel")
            {
                excelConfigAllow = true;
            }

            //
            Logger.AddLogger(new ConsoleLogger(LogLevel.Service), _subPath);
            Logger.AddLogger(new FileLogger(LogLevel.Service), _subPath);
            Logger.AddLogger(new WebSocketLogger(LogLevel.Service), _subPath);

            var profilePath       = Path.Combine(Directory.GetCurrentDirectory(), _subPath);
            var profileConfigPath = Path.Combine(profilePath, "config");
            var configFile        = Path.Combine(profileConfigPath, "config.json");
            var excelConfigFile   = Path.Combine(profileConfigPath, "config.xlsm");

            GlobalSettings settings;
            var            boolNeedsSetup = false;

            if (File.Exists(configFile))
            {
                // Load the settings from the config file
                settings = GlobalSettings.Load(_subPath, _enableJsonValidation);
                if (excelConfigAllow)
                {
                    if (!File.Exists(excelConfigFile))
                    {
                        Logger.Write(
                            "Migrating existing json confix to excel config, please check the config.xlsm in your config folder"
                            );

                        ExcelConfigHelper.MigrateFromObject(settings, excelConfigFile);
                    }
                    else
                    {
                        settings = ExcelConfigHelper.ReadExcel(settings, excelConfigFile);
                    }

                    Logger.Write("Bot will run with your excel config, loading excel config");
                }
            }
            else
            {
                settings = new GlobalSettings
                {
                    ProfilePath       = profilePath,
                    ProfileConfigPath = profileConfigPath,
                    GeneralConfigPath = Path.Combine(Directory.GetCurrentDirectory(), "config"),
                    ConsoleConfig     = { TranslationLanguageCode = strCulture }
                };

                boolNeedsSetup = true;
            }
            if (commandLine["latlng"] != null && commandLine["latlng"].Length > 0)
            {
                var crds = commandLine["latlng"].Split(',');
                try
                {
                    var lat = double.Parse(crds[0]);
                    var lng = double.Parse(crds[1]);
                    settings.LocationConfig.DefaultLatitude  = lat;
                    settings.LocationConfig.DefaultLongitude = lng;
                }
                catch (Exception)
                {
                    // ignored
                }
            }

            var options = new Options();

            if (CommandLine.Parser.Default.ParseArguments(args, options))
            {
                // Values are available here
                if (options.Init)
                {
                    settings.GenerateAccount(options.IsGoogle, options.Template, options.Start, options.End, options.Password);
                }
            }
            var lastPosFile = Path.Combine(profileConfigPath, "LastPos.ini");

            if (File.Exists(lastPosFile) && settings.LocationConfig.StartFromLastPosition)
            {
                var text = File.ReadAllText(lastPosFile);
                var crds = text.Split(':');
                try
                {
                    var lat = double.Parse(crds[0]);
                    var lng = double.Parse(crds[1]);
                    //If lastcoord is snipe coord, bot start from default location

                    if (LocationUtils.CalculateDistanceInMeters(lat, lng, settings.LocationConfig.DefaultLatitude, settings.LocationConfig.DefaultLongitude) < 2000)
                    {
                        settings.LocationConfig.DefaultLatitude  = lat;
                        settings.LocationConfig.DefaultLongitude = lng;
                    }
                }
                catch (Exception)
                {
                    // ignored
                }
            }

            if (!_ignoreKillSwitch)
            {
                if (CheckMKillSwitch() || CheckKillSwitch())
                {
                    return;
                }
            }

            var logicSettings = new LogicSettings(settings);
            var translation   = Translation.Load(logicSettings);

            TinyIoC.TinyIoCContainer.Current.Register <ITranslation>(translation);

            if (settings.GPXConfig.UseGpxPathing)
            {
                var xmlString = File.ReadAllText(settings.GPXConfig.GpxFile);
                var readgpx   = new GpxReader(xmlString, translation);
                var nearestPt = readgpx.Tracks.SelectMany(
                    (trk, trkindex) =>
                    trk.Segments.SelectMany(
                        (seg, segindex) =>
                        seg.TrackPoints.Select(
                            (pt, ptindex) =>
                            new
                {
                    TrackPoint = pt,
                    TrackIndex = trkindex,
                    SegIndex   = segindex,
                    PtIndex    = ptindex,
                    Latitude   = Convert.ToDouble(pt.Lat, CultureInfo.InvariantCulture),
                    Longitude  = Convert.ToDouble(pt.Lon, CultureInfo.InvariantCulture),
                    Distance   = LocationUtils.CalculateDistanceInMeters(
                        settings.LocationConfig.DefaultLatitude,
                        settings.LocationConfig.DefaultLongitude,
                        Convert.ToDouble(pt.Lat, CultureInfo.InvariantCulture),
                        Convert.ToDouble(pt.Lon, CultureInfo.InvariantCulture)
                        )
                }
                            )
                        )
                    )
                                .OrderBy(pt => pt.Distance)
                                .FirstOrDefault(pt => pt.Distance <= 5000);

                if (nearestPt != null)
                {
                    settings.LocationConfig.DefaultLatitude  = nearestPt.Latitude;
                    settings.LocationConfig.DefaultLongitude = nearestPt.Longitude;
                    settings.LocationConfig.ResumeTrack      = nearestPt.TrackIndex;
                    settings.LocationConfig.ResumeTrackSeg   = nearestPt.SegIndex;
                    settings.LocationConfig.ResumeTrackPt    = nearestPt.PtIndex;
                }
            }
            IElevationService elevationService = new ElevationService(settings);

            //validation auth.config
            if (boolNeedsSetup)
            {
                AuthAPIForm form = new AuthAPIForm(true);
                if (form.ShowDialog() == DialogResult.OK)
                {
                    settings.Auth.APIConfig = form.Config;
                }
            }
            else
            {
                var apiCfg = settings.Auth.APIConfig;

                if (apiCfg.UsePogoDevAPI)
                {
                    if (string.IsNullOrEmpty(apiCfg.AuthAPIKey))
                    {
                        Logger.Write(
                            "You have selected PogoDev API but you have not provided an API Key, please press any key to exit and correct you auth.json, \r\n The Pogodev API key can be purchased at - https://talk.pogodev.org/d/51-api-hashing-service-by-pokefarmer",
                            LogLevel.Error
                            );

                        Console.ReadKey();
                        Environment.Exit(0);
                    }
                    try
                    {
                        HttpClient client = new HttpClient();
                        client.DefaultRequestHeaders.Add("X-AuthToken", apiCfg.AuthAPIKey);
                        var maskedKey = apiCfg.AuthAPIKey.Substring(0, 4) + "".PadLeft(apiCfg.AuthAPIKey.Length - 8, 'X') + apiCfg.AuthAPIKey.Substring(apiCfg.AuthAPIKey.Length - 4, 4);
                        HttpResponseMessage response = client.PostAsync("https://pokehash.buddyauth.com/api/v133_1/hash", null).Result;

                        string   AuthKey             = response.Headers.GetValues("X-AuthToken").FirstOrDefault();
                        string   MaxRequestCount     = response.Headers.GetValues("X-MaxRequestCount").FirstOrDefault();
                        DateTime AuthTokenExpiration = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Local).AddSeconds(Convert.ToDouble(response.Headers.GetValues("X-AuthTokenExpiration").FirstOrDefault())).ToLocalTime();
                        TimeSpan Expiration          = AuthTokenExpiration - DateTime.Now;
                        string   Result = $"Key: {maskedKey} RPM: {MaxRequestCount} Expiration Date: {AuthTokenExpiration.Month}/{AuthTokenExpiration.Day}/{AuthTokenExpiration.Year} ({Expiration.Days} Days {Expiration.Hours} Hours {Expiration.Minutes} Minutes)";
                        Logger.Write(Result, LogLevel.Info, ConsoleColor.Green);
                    }
                    catch
                    {
                        Logger.Write("The HashKey is invalid or has expired, please press any key to exit and correct you auth.json, \r\n The Pogodev API key can be purchased at - https://talk.pogodev.org/d/51-api-hashing-service-by-pokefarmer", LogLevel.Error);
                        Console.ReadKey();
                        Environment.Exit(0);
                    }
                }
                else if (apiCfg.UseLegacyAPI)
                {
                    Logger.Write(
                        "You bot will start after 15 seconds, You are running bot with Legacy API (0.45), but it will increase your risk of being banned and triggering captchas. Config Captchas in config.json to auto-resolve them",
                        LogLevel.Warning
                        );

#if RELEASE
                    Thread.Sleep(15000);
#endif
                }
                else
                {
                    Logger.Write(
                        "At least 1 authentication method must be selected, please correct your auth.json.",
                        LogLevel.Error
                        );
                    Console.ReadKey();
                    Environment.Exit(0);
                }
            }

            _session = new Session(settings,
                                   new ClientSettings(settings, elevationService), logicSettings, elevationService,
                                   translation
                                   );
            ioc.Register <ISession>(_session);

            Logger.SetLoggerContext(_session);

            MultiAccountManager accountManager = new MultiAccountManager(settings, logicSettings.Bots);
            ioc.Register(accountManager);

            if (boolNeedsSetup)
            {
                StarterConfigForm configForm = new StarterConfigForm(_session, settings, elevationService, configFile);
                if (configForm.ShowDialog() == DialogResult.OK)
                {
                    var fileName = Assembly.GetEntryAssembly().Location;

                    Process.Start(fileName);
                    Environment.Exit(0);
                }

                //if (GlobalSettings.PromptForSetup(_session.Translation))
                //{
                //    _session = GlobalSettings.SetupSettings(_session, settings, elevationService, configFile);

                //    var fileName = Assembly.GetExecutingAssembly().Location;
                //    Process.Start(fileName);
                //    Environment.Exit(0);
                //}
                else
                {
                    GlobalSettings.Load(_subPath, _enableJsonValidation);

                    Logger.Write("Press a Key to continue...",
                                 LogLevel.Warning);
                    Console.ReadKey();
                    return;
                }

                if (excelConfigAllow)
                {
                    ExcelConfigHelper.MigrateFromObject(settings, excelConfigFile);
                }
            }

            ProgressBar.Start("NecroBot2 is starting up", 10);

            ProgressBar.Fill(20);

            var machine = new StateMachine();
            var stats   = _session.RuntimeStatistics;

            ProgressBar.Fill(30);
            var strVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString(4);
            stats.DirtyEvent +=
                () =>
                Console.Title = $"[Necrobot2 v{strVersion}] " +
                                stats.GetTemplatedStats(
                    _session.Translation.GetTranslation(TranslationString.StatsTemplateString),
                    _session.Translation.GetTranslation(TranslationString.StatsXpTemplateString));
            ProgressBar.Fill(40);

            var aggregator = new StatisticsAggregator(stats);
            onBotStarted?.Invoke(_session, aggregator);

            ProgressBar.Fill(50);
            var listener = new ConsoleEventListener();
            ProgressBar.Fill(60);
            var snipeEventListener = new SniperEventListener();

            _session.EventDispatcher.EventReceived += evt => listener.Listen(evt, _session);
            _session.EventDispatcher.EventReceived += evt => aggregator.Listen(evt, _session);
            _session.EventDispatcher.EventReceived += evt => snipeEventListener.Listen(evt, _session);

            ProgressBar.Fill(70);

            machine.SetFailureState(new LoginState());
            ProgressBar.Fill(80);

            ProgressBar.Fill(90);

            _session.Navigation.WalkStrategy.UpdatePositionEvent +=
                (session, lat, lng, speed) => _session.EventDispatcher.Send(new UpdatePositionEvent {
                Latitude = lat, Longitude = lng, Speed = speed
            });
            _session.Navigation.WalkStrategy.UpdatePositionEvent += LoadSaveState.SaveLocationToDisk;

            ProgressBar.Fill(100);

            if (settings.WebsocketsConfig.UseWebsocket)
            {
                var websocket = new WebSocketInterface(settings.WebsocketsConfig.WebSocketPort, _session);
                _session.EventDispatcher.EventReceived += evt => websocket.Listen(evt, _session);
            }

            var bot = accountManager.GetStartUpAccount();

            _session.ReInitSessionWithNextBot(bot);

            machine.AsyncStart(new VersionCheckState(), _session, _subPath, excelConfigAllow);

            try
            {
                Console.Clear();
            }
            catch (IOException)
            {
            }

            var TotXP = 0;

            for (int i = 0; i < bot.Level + 1; i++)
            {
                TotXP = TotXP + Statistics.GetXpDiff(i);
            }
            var user = !string.IsNullOrEmpty(bot.Nickname) ? bot.Nickname : bot.Username;
            Logger.Write($"User: {user} | XP: {bot.CurrentXp - TotXP} | SD: {bot.Stardust}", LogLevel.BotStats);

            if (settings.TelegramConfig.UseTelegramAPI)
            {
                _session.Telegram = new TelegramService(settings.TelegramConfig.TelegramAPIKey, _session);
            }

            if (_session.LogicSettings.EnableHumanWalkingSnipe &&
                _session.LogicSettings.HumanWalkingSnipeUseFastPokemap)
            {
                HumanWalkSnipeTask.StartFastPokemapAsync(_session,
                                                         _session.CancellationTokenSource.Token).ConfigureAwait(false); // that need to keep data live
            }

            if (_session.LogicSettings.UseSnipeLocationServer ||
                _session.LogicSettings.HumanWalkingSnipeUsePogoLocationFeeder)
            {
                SnipePokemonTask.AsyncStart(_session);
            }


            if (_session.LogicSettings.DataSharingConfig.EnableSyncData)
            {
                BotDataSocketClient.StartAsync(_session, Properties.Resources.EncryptKey);
                _session.EventDispatcher.EventReceived += evt => BotDataSocketClient.Listen(evt, _session);
            }
            settings.CheckProxy(_session.Translation);

            if (_session.LogicSettings.ActivateMSniper)
            {
                ServicePointManager.ServerCertificateValidationCallback +=
                    (sender, certificate, chain, sslPolicyErrors) => true;
                //temporary disable MSniper connection because site under attacking.
                //MSniperServiceTask.ConnectToService();
                //_session.EventDispatcher.EventReceived += evt => MSniperServiceTask.AddToList(evt);
            }

            // jjskuld - Don't await the analytics service since it starts a worker thread that never returns.
#pragma warning disable 4014
            _session.AnalyticsService.StartAsync(_session, _session.CancellationTokenSource.Token);
#pragma warning restore 4014
            _session.EventDispatcher.EventReceived += evt => AnalyticsService.Listen(evt, _session);

            var trackFile = Path.GetTempPath() + "\\necrobot2.io";

            if (!File.Exists(trackFile) || File.GetLastWriteTime(trackFile) < DateTime.Now.AddDays(-1))
            {
                Thread.Sleep(10000);
                Thread mThread = new Thread(delegate()
                {
                    var infoForm = new InfoForm();
                    infoForm.ShowDialog();
                });
                File.WriteAllText(trackFile, DateTime.Now.Ticks.ToString());
                mThread.SetApartmentState(ApartmentState.STA);

                mThread.Start();
            }

            QuitEvent.WaitOne();
        }
Esempio n. 39
0
                public void CheckForAnnouncement()
                {
                    try
                    {
                        uT = new Thread(new System.Threading.ThreadStart(CheckForAnnouncementBG));
                        uT.SetApartmentState(ApartmentState.STA);
                        uT.IsBackground = true;

                        if (this.IsAnnouncementCheckHandlerDeclared == false)
                        {
                            AnnouncementCheckCompleted +=
                                new Announcement.AnnouncementCheckCompletedEventHandler(AnnouncementCheckComplete);
                            this.IsAnnouncementCheckHandlerDeclared = true;
                        }

                        uT.Start();
                    }
                    catch (Exception ex)
                    {
                        Runtime.MessageCollector.AddMessage(Messages.MessageClass.ErrorMsg,
                                                            (string)
                                                            ("CheckForAnnouncement (UI.Window.Announcement) failed" +
                                                             Constants.vbNewLine + ex.Message), true);
                    }
                }
Esempio n. 40
0
    /// <summary>
    /// Displays the mail message dialog asynchronously.
    /// </summary>
    public void ShowDialog()
    {
        // Create the mail message in an STA thread
        Thread t = new Thread(new ThreadStart(_ShowMail));
        t.IsBackground = true;
        t.SetApartmentState(ApartmentState.STA);
        t.Start();

        // only return when the new thread has built it's interop representation
        _manualResetEvent.WaitOne();
        _manualResetEvent.Reset();
    }
Esempio n. 41
0
            /// <summary>
            /// 清空整个回收站的内容
            /// </summary>
            /// <returns>成功返回0,否则为OLE定义的错误值</returns>
            public uint EmptyRecycleBin()
            {
                _rbState rvs = new _rbState();
                rvs.Revalue = 0x8000FFFF;

                long size, items;

                this.QuerySizeRecycleBin(out size, out items);
                if (size == 0)
                    return rvs.Revalue;

                lock (rvs)
                {
                    Thread t = new Thread(
                       new ParameterizedThreadStart(this.wrokThread));
                    t.SetApartmentState(ApartmentState.STA);//将线程设置为STA
                    t.Start(rvs);

                }
                this.ewh.WaitOne();
                this.ewh.Reset();
                return rvs.Revalue;
            }
Esempio n. 42
0
 public void SetApartmentState(ApartmentState aptState)
 {
     _thread.SetApartmentState(aptState);
 }
Esempio n. 43
0
        public static void VA_Init1(dynamic vaProxy)
        {
            // Initialize and launch an EDDI instance without opening the main window
            // VoiceAttack commands will be used to manipulate the window state.
            App.vaProxy = vaProxy;
            if (App.AlreadyRunning())
            {
                return;
            }

            Thread appThread = new Thread(App.Main);

            appThread.SetApartmentState(ApartmentState.STA);
            appThread.Start();

            try
            {
                int timeout = 0;
                while (Application.Current == null)
                {
                    if (timeout < 200)
                    {
                        Thread.Sleep(50);
                        timeout++;
                    }
                    else
                    {
                        throw new TimeoutException("EDDI VoiceAttack plugin initialisation has timed out");
                    }
                }

                Logging.Info("Initialising EDDI VoiceAttack plugin");

                // Set up our event responders
                VoiceAttackResponder.RaiseEvent += (s, theEvent) =>
                {
                    try
                    {
                        eventQueue.Enqueue(theEvent);
                        Thread eventHandler = new Thread(() => dequeueEvent(ref vaProxy))
                        {
                            Name         = "VoiceAttackEventHandler",
                            IsBackground = true
                        };
                        eventHandler.Start();
                        eventHandler.Join();
                    }
                    catch (ThreadAbortException tax)
                    {
                        Thread.ResetAbort();
                        Logging.Debug("Thread aborted", tax);
                    }
                    catch (Exception ex)
                    {
                        Dictionary <string, object> data = new Dictionary <string, object>
                        {
                            { "event", JsonConvert.SerializeObject(theEvent) },
                            { "exception", ex.Message },
                            { "stacktrace", ex.StackTrace }
                        };
                        Logging.Error("VoiceAttack failed to handle event.", data);
                    }
                };

                // Add notifiers for changes in variables we want to react to
                // (we can only use event handlers with classes which are always constructed - nullable objects will be updated via responder events)
                EDDI.Instance.State.CollectionChanged  += (s, e) => setDictionaryValues(EDDI.Instance.State, "state", ref vaProxy);
                SpeechService.Instance.PropertyChanged += (s, e) => setSpeaking(SpeechService.Instance.eddiSpeaking, ref vaProxy);

                CargoMonitor cargoMonitor = (CargoMonitor)EDDI.Instance.ObtainMonitor("Cargo monitor");
                cargoMonitor.InventoryUpdatedEvent += (s, e) =>
                {
                    lock (vaProxyLock)
                    {
                        setCargo(cargoMonitor, ref vaProxy);
                    }
                };

                ShipMonitor shipMonitor = (ShipMonitor)EDDI.Instance.ObtainMonitor("Ship monitor");
                if (shipMonitor != null)
                {
                    shipMonitor.ShipyardUpdatedEvent += (s, e) =>
                    {
                        lock (vaProxyLock)
                        {
                            setShipValues(shipMonitor.GetCurrentShip(), "Ship", ref vaProxy);
                            Task.Run(() => setShipyardValues(shipMonitor.shipyard?.ToList(), ref vaProxy));
                        }
                    };
                }

                StatusMonitor statusMonitor = (StatusMonitor)EDDI.Instance.ObtainMonitor("Status monitor");
                if (statusMonitor != null)
                {
                    statusMonitor.StatusUpdatedEvent += (s, e) =>
                    {
                        lock (vaProxyLock)
                        {
                            setStatusValues(statusMonitor.currentStatus, "Status", ref vaProxy);
                        }
                    };
                }

                // Display instance information if available
                if (EddiUpgrader.UpgradeRequired)
                {
                    vaProxy.WriteToLog("Please shut down VoiceAttack and run EDDI standalone to upgrade", "red");
                    string msg = Properties.VoiceAttack.run_eddi_standalone;
                    SpeechService.Instance.Say(((ShipMonitor)EDDI.Instance.ObtainMonitor("Ship monitor")).GetCurrentShip(), msg, 0);
                }
                else if (EddiUpgrader.UpgradeAvailable)
                {
                    vaProxy.WriteToLog("Please shut down VoiceAttack and run EDDI standalone to upgrade", "orange");
                    string msg = Properties.VoiceAttack.run_eddi_standalone;
                    SpeechService.Instance.Say(((ShipMonitor)EDDI.Instance.ObtainMonitor("Ship monitor")).GetCurrentShip(), msg, 0);
                }

                if (EddiUpgrader.Motd != null)
                {
                    vaProxy.WriteToLog("Message from EDDI: " + EddiUpgrader.Motd, "black");
                    string msg = String.Format(Eddi.Properties.EddiResources.msg_from_eddi, EddiUpgrader.Motd);
                    SpeechService.Instance.Say(((ShipMonitor)EDDI.Instance.ObtainMonitor("Ship monitor")).GetCurrentShip(), msg, 0);
                }

                // Set the initial values from the main EDDI objects
                setStandardValues(ref vaProxy);

                vaProxy.WriteToLog("The EDDI plugin is fully operational.", "green");
                setStatus(ref vaProxy, "Operational");

                // Fire an event once the VA plugin is initialized
                Event @event = new VAInitializedEvent(DateTime.UtcNow);

                if (initEventEnabled(@event.type))
                {
                    EDDI.Instance.enqueueEvent(@event);
                }

                // Set a variable indicating the version of VoiceAttack in use
                System.Version v = vaProxy.VAVersion;
                EDDI.Instance.vaVersion = v.ToString();

                // Set a variable indicating whether EDDI is speaking
                try
                {
                    setSpeaking(SpeechService.Instance.eddiSpeaking, ref vaProxy);
                }
                catch (Exception ex)
                {
                    Logging.Error("Failed to set initial speaking status", ex);
                }
                Logging.Info("EDDI VoiceAttack plugin initialization complete");
            }
            catch (Exception e)
            {
                Logging.Error("Failed to initialize VoiceAttack plugin", e);
                vaProxy.WriteToLog("Unable to fully initialize EDDI. Some functions may not work.", "red");
            }
        }
Esempio n. 44
0
        static int Main(string[] args)
        {
            ParseOptions(args);

            if (!_nologo)
            {
                Console.WriteLine(
                    "Chiron - Silverlight Development Utility. Version {0}",
                    typeof(Chiron).Assembly.GetName().Version
                    );
            }

            if (_help)
            {
                Console.WriteLine(
                    @"Usage: Chiron [<options>]

Common usages:

  Chiron.exe /b
    Starts the web-server on port 2060, and opens the default browser
    to the root of the web-server. This is used for developing an
    application, as Chiron will rexap you application's directory for
    every request.
    
  Chiron.exe /d:app /z:app.xap
    Takes the contents of the app directory and generates an app.xap 
    from it, which embeds the DLR and language assemblies according to
    the settings in Chiron.exe.config. This is used for deployment,
    so you can take the generated app.xap, along with any other files,
    and host them on any web-server.

Options:

  Note: forward-slashes (/) in option names can be substituted for dashes (-).
        For example ""Chiron.exe -w"" instead of ""Chiron.exe /w"".

  /w[ebserver][:<port number>]
    Launches a development web server that automatically creates
    XAP files for dynamic language applications (runs /z for every
    request of a XAP file, but generates it in memory).
    Optionally specifies server port number (default: 2060)

  /b[rowser][:<start url>]
    Launches the default browser and starts the web server
    Implies /w, cannot be combined with /x or /z

  /z[ipdlr]:<file>
    Generates a XAP file, including dynamic language dependencies, and
    auto-generates AppManifest.xaml (equivalent of /m in memory), 
    if it does not exist.
    Does not start the web server, cannot be combined with /w or /b

  /m[anifest]
    Saves the generated AppManifest.xaml file to disk
    Use /d to set the directory containing the sources
    Can only be combined with /d, /n and /s

  /d[ir[ectory]]:<path>
    Specifies directory on disk (default: the current directory).
    Implies /w.

  /r[efpath]:<path>
    Path where assemblies are located. Defaults to the same directory
    where Chiron.exe exists.
    Overrides appSettings.localAssemblyPath in Chiron.exe.config.

  /p[ath]:<path1;path2;..;pathn>
    Semi-colon-separated directories to be included in the XAP file,
    in addition to what is specified by /d
    
  /u[rlprefix]:<relative or absolute uri>
    Appends a relative or absolute Uri to each language assembly or extension
    added to the AppManifest.xaml. If a relative Uri is provided, Chiron 
    will serve all files located in the /refpath at this Uri, relative to the
    root of the web-server.
    Overrides appSettings.urlPrefix in Chiron.exe.config.
  
  /l /detectLanguages:true|false (default true)
    Scans the current application directory for files with a valid language's
    file extension, and only makes those languages available to the XAP file.
    See /useExtensions for whether the languages assemblies or extension files
    are used.
    If false, no language-specific assemblies/extensions are added to the XAP,
    so the Silverlight application is responsible for parsing the languages.config
    file in the XAP and downloading the languages it needs.
    Overrides appSettings.detectLanguages in Chiron.exe.config.
  
  /e /useExtensions:true|false (default false)
    Toggles whether or not language and DLR assemblies are embedded in
    the XAP file, or whether their equivalent extension files are used.

  /x[ap[file]]:<file>
    Specifies XAP file to generate. Only XAPs a directory; does not
    generate a manifest or add dynamic language DLLs; see /z for that
    functionality.
    Does not start the web server, cannot be combined with /w or /b

  /notification
    Display notification icon
  
  /n[ologo]
    Suppresses display of the logo banner

  /s[ilent]
    Suppresses display of all output
");
            }
            else if (_error != null)
            {
                return(Error(1000, "options", _error));
            }
            else if (!string.IsNullOrEmpty(_xapfile))
            {
                try {
                    if (!_silent)
                    {
                        Console.WriteLine("Generating XAP {0} from {1}", _xapfile, _dir);
                    }

                    if (_zipdlr)
                    {
                        XapBuilder.XapToDisk(_dir, _xapfile);
                    }
                    else
                    {
                        ZipArchive xap = new ZipArchive(_xapfile, FileAccess.Write);
                        XapBuilder.AddPathDirectories(xap);
                        xap.CopyFromDirectory(_dir, "");
                        xap.Close();
                    }
                }
                catch (Exception ex) {
                    return(Error(1001, "xap", ex.Message));
                }
            }
            else if (_saveManifest)
            {
                try {
                    string manifest = Path.Combine(_dir, "AppManifest.xaml");
                    if (File.Exists(manifest))
                    {
                        return(Error(3002, "manifest", "AppManifest.xaml already exists at path " + manifest));
                    }

                    // Generate the AppManifest.xaml file to disk, as we would if we were
                    // generating it in the XAP
                    XapBuilder.GenerateManifest(_dir).Save(manifest);
                } catch (Exception ex) {
                    return(Error(3001, "manifest", ex.Message));
                }
            }
            else
            {
                string uri = string.Format("http://localhost:{0}/", _port);

                if (!_silent)
                {
                    Console.WriteLine("Chiron serving '{0}' as {1}", _dir, uri);
                }

                try {
                    HttpServer server = new HttpServer(_port, _dir);
                    server.Start();

                    if (_browser)
                    {
                        if (_startPage != null)
                        {
                            uri += _startPage;
                        }

                        ProcessStartInfo startInfo = new ProcessStartInfo(uri);
                        startInfo.UseShellExecute  = true;
                        startInfo.WorkingDirectory = _dir;

                        Process p = new Process();
                        p.StartInfo = startInfo;
                        p.Start();
                    }

                    if (_notifyIcon)
                    {
                        Thread notify = new Thread(
                            () => {
                            Application.EnableVisualStyles();
                            Application.SetCompatibleTextRenderingDefault(false);

                            var notification = new Notification(_dir, _port);
                            Application.Run();
                        }
                            );
                        notify.SetApartmentState(ApartmentState.STA);
                        notify.IsBackground = true;
                        notify.Start();
                    }

                    while (server.IsRunning)
                    {
                        Thread.Sleep(500);
                    }
                } catch (Exception ex) {
                    return(Error(2001, "server", ex.Message));
                }
            }

            return(0);
        }
Esempio n. 45
0
        /// <summary>
        /// Loads the current application.
        /// </summary>
        /// <param name="password"></param>
        /// <exception cref="ApplicationLoaderException">An error occurred during the decryption or while starting the application.</exception>
        public static void Load(string password)
        {
            if (string.IsNullOrEmpty(password))
            {
                throw new ArgumentNullException(nameof(password));
            }

            var exePath          = Assembly.GetExecutingAssembly().Location;
            var mainAssemblyPath = Path.ChangeExtension(exePath, SharedConstants.EncryptedExeFileExtension);

            if (false == File.Exists(mainAssemblyPath))
            {
                throw new ApplicationLoaderException("The main assembly was not found.");
            }

            #region Decrypt files

            byte[] mainAssembly;
            try
            {
                mainAssembly = DecryptFile(mainAssemblyPath, password);
            }
            catch (Exception exc)
            {
                throw new ApplicationLoaderException("Error loading the main assembly.", exc);
            }

            var applicationPath = Path.GetDirectoryName(exePath);

            var libFileList = Directory.GetFiles(applicationPath, "*" + SharedConstants.EncryptedLibFileExtension);

            var assemblyDict = new Dictionary <string, byte[]>(StringComparer.InvariantCultureIgnoreCase);

            var mainAssemblyName = Path.GetFileNameWithoutExtension(exePath);

            assemblyDict.Add(mainAssemblyName, mainAssembly);

            foreach (var filePath in libFileList)
            {
                var assemblyName = Path.GetFileNameWithoutExtension(filePath);

                try
                {
                    var binaryAssembly = DecryptFile(filePath, password);
                    assemblyDict[assemblyName] = binaryAssembly;
                }
                catch (Exception exc)
                {
                    throw new ApplicationLoaderException($"Error loading assembly '{assemblyName}'.", exc);
                }
            }

            #endregion

            #region Load application

            {
                var decryptedAppDomain = AppDomain.CreateDomain(mainAssemblyName, AppDomain.CurrentDomain.Evidence, AppDomain.CurrentDomain.SetupInformation);

                var assemblyResolver = new AssemblyResolver(assemblyDict, decryptedAppDomain);

                var thread = new Thread(() =>
                {
                    // Start the application
                    decryptedAppDomain.ExecuteAssemblyByName(mainAssemblyName);
                });
                thread.SetApartmentState(ApartmentState.STA); // Required by WPF applications
                thread.Start();
            }

#if DEPRECATED
            {
                AppDomain decryptedAppDomain;
                Assembly  mainAssembly;

                try
                {
                    var applcationName = Path.GetFileNameWithoutExtension(exePath);
                    decryptedAppDomain = AppDomain.CreateDomain(applcationName, AppDomain.CurrentDomain.Evidence, AppDomain.CurrentDomain.SetupInformation);

                    mainAssembly = decryptedAppDomain.Load(mainAssemblyStream.ToArray());
                    foreach (var item in libStreamDict.Values)
                    {
                        decryptedAppDomain.Load(item.ToArray());
                    }
                }
                catch (Exception exc)
                {
                    throw new ApplicationLoaderException("An error occurred while loading assemblies in the new AppDomain.", exc);
                }

                try
                {
                    decryptedAppDomain.ExecuteAssemblyByName(mainAssembly.GetName());
                }
                catch (Exception exc)
                {
                    throw new ApplicationLoaderException("An error occurred while starting the application in the new AppDomain.", exc);
                }
            }
#endif

            #endregion
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                mCaptureManager = Program.mCaptureManager;

                App.mHotKeyHost = new HotKeyHost((HwndSource)HwndSource.FromVisual(App.Current.MainWindow));

                App.mHotKeyHost.AddHotKey(new CustomHotKey("Record",
                                                           new Action(() =>
                {
                    App.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, (ThreadStart) delegate()
                    {
                        mStartStop_Click(null, null);
                    });
                }
                                                                      ), Key.P, ModifierKeys.Control | ModifierKeys.Shift, true));
            }
            catch (System.Exception)
            {
                try
                {
                    mCaptureManager = new CaptureManager();
                }
                catch (System.Exception)
                {
                }
            }

            LogManager.getInstance().WriteDelegateEvent += MainWindow_WriteDelegateEvent;

            if (mCaptureManager == null)
            {
                return;
            }


            var t = new Thread(

                delegate()
            {
                try
                {
                    mSourceControl = mCaptureManager.createSourceControl();

                    if (mSourceControl == null)
                    {
                        return;
                    }

                    mEncoderControl = mCaptureManager.createEncoderControl();

                    if (mEncoderControl == null)
                    {
                        return;
                    }

                    mSinkControl = mCaptureManager.createSinkControl();

                    if (mSinkControl == null)
                    {
                        return;
                    }

                    mISessionControl = mCaptureManager.createSessionControl();

                    if (mISessionControl == null)
                    {
                        return;
                    }

                    mStreamControl = mCaptureManager.createStreamControl();

                    if (mStreamControl == null)
                    {
                        return;
                    }

                    mStreamControl.createStreamControlNodeFactory(ref mSpreaderNodeFactory);

                    if (mSpreaderNodeFactory == null)
                    {
                        return;
                    }

                    mSinkControl.createSinkFactory(Guid.Empty, out mEVRMultiSinkFactory);

                    if (mEVRMultiSinkFactory == null)
                    {
                        return;
                    }


                    XmlDataProvider lXmlDataProvider = (XmlDataProvider)this.Resources["XmlSources"];

                    if (lXmlDataProvider == null)
                    {
                        return;
                    }

                    XmlDocument doc = new XmlDocument();

                    string lxmldoc = "";

                    mCaptureManager.getCollectionOfSources(ref lxmldoc);

                    doc.LoadXml(lxmldoc);

                    lXmlDataProvider.Document = doc;

                    lXmlDataProvider = (XmlDataProvider)this.Resources["XmlEncoders"];

                    if (lXmlDataProvider == null)
                    {
                        return;
                    }

                    doc = new XmlDocument();

                    mCaptureManager.getCollectionOfEncoders(ref lxmldoc);

                    doc.LoadXml(lxmldoc);

                    lXmlDataProvider.Document = doc;



                    mCaptureManager.getCollectionOfSinks(ref lxmldoc);


                    lXmlDataProvider = (XmlDataProvider)this.Resources["XmlContainerTypeProvider"];

                    if (lXmlDataProvider == null)
                    {
                        return;
                    }

                    doc = new XmlDocument();

                    doc.LoadXml(lxmldoc);

                    lXmlDataProvider.Document = doc;
                }
                catch (Exception)
                {
                }
                finally
                {
                }
            });

            t.SetApartmentState(ApartmentState.MTA);

            t.Start();
        }
    /// <summary>
    /// Starts the test passed.  The test should already be loaded into an app domain.
    /// </summary>
    /// <param name="test">The test to run.</param>
    private void StartTest(ReliabilityTest test)
    {
#if PROJECTK_BUILD
        Interlocked.Increment(ref _testsRunningCount);
        test.TestStarted();

        StartTestWorker(test);
#else     
        try
        {
            if (curTestSet.AppDomainLoaderMode == AppDomainLoaderMode.Lazy)
            {
                Console.WriteLine("Test Loading: {0} run #{1}", test.RefOrID, test.RunCount);
                TestPreLoader(test, curTestSet.DiscoveryPaths);
            }

            // Any test failed to load during the preload step should be removed. Need to take a closer look.
            // This is to fix Dev10 Bug 552621.
            if (test.TestLoadFailed)
            {
                logger.WriteToInstrumentationLog(curTestSet, LoggingLevels.Tests, "Test failed to load.");
                return;
            }

            Thread newThread = new Thread(new ParameterizedThreadStart(this.StartTestWorker));

            // check the thread requirements and set appropriately.
            switch ((test.TestAttrs & TestAttributes.RequiresThread))
            {
                case TestAttributes.RequiresSTAThread:
                    newThread.SetApartmentState(ApartmentState.STA);
                    break;
                case TestAttributes.RequiresMTAThread:
                    newThread.SetApartmentState(ApartmentState.MTA);
                    break;
                case TestAttributes.RequiresUnknownThread:
                    // no attribute specified... ignore.
                    break;
            }

            newThread.Name = test.RefOrID;
            
            Interlocked.Increment(ref testsRunningCount);
            test.TestStarted();
            logger.WriteToInstrumentationLog(curTestSet, LoggingLevels.TestStarter, String.Format("RF.StartTest, RTs({0}) - Instances of this test: {1} - New Test:{2}", testsRunningCount, test.RunningCount, test.RefOrID));

            newThread.Start(test);
        }
        catch (OutOfMemoryException e)
        {
            HandleOom(e, "StartTest");
        }
#endif      
    }
    public void HandlePlayerCommand(PlayerTextPacket playerText)
    {
        //Discarded unreachable code: IL_00b1, IL_00c4, IL_015b
        if (!Settings.Default.EnableGotoCommand)
        {
            goto IL_000f;
        }
        goto IL_01d2;
IL_01d2:
        int num;
        int num2;

        if (playerText._Message.StartsWith("/"))
        {
            num  = -184337631;
            num2 = num;
        }
        else
        {
            num  = -1517235003;
            num2 = num;
        }
        goto IL_0014;
IL_0014:
        string[] array = default(string[]);
        while (true)
        {
            uint num3;
            switch ((num3 = (uint)num ^ 0xE1B2BB24u) % 15u)
            {
            case 13u:
                break;

            default:
                return;

            case 10u:
            {
                int num6;
                int num7;
                if (array[0] == "/ip")
                {
                    num6 = 1792502034;
                    num7 = num6;
                }
                else
                {
                    num6 = 698822585;
                    num7 = num6;
                }
                num = num6 ^ ((int)num3 * -985111412);
                continue;
            }

            case 4u:
                goto IL_008d;

            case 3u:
                return;

            case 6u:
                return;

            case 2u:
            {
                _50w8wVuv8bL5nhKaR2EHxjrTamB._TVcgSr7bcouFhNfw8PyT9bbBIM0("Server IP: " + _ServerHostname);
                Thread thread = new Thread((ThreadStart) delegate
                    {
                        Clipboard.SetText(_ServerHostname);
                    });
                thread.SetApartmentState(ApartmentState.STA);
                thread.Start();
                num = (int)(num3 * 1103150964) ^ -1716114833;
                continue;
            }

            case 8u:
                playerText._Send = false;
                num = ((int)num3 * -685168380) ^ -671761443;
                continue;

            case 0u:
                array = playerText._Message.Split(' ');
                num   = -500983293;
                continue;

            case 7u:
                return;

            case 12u:
            {
                int num8;
                int num9;
                if (array.Length >= 2)
                {
                    num8 = -1632455468;
                    num9 = num8;
                }
                else
                {
                    num8 = -2097540126;
                    num9 = num8;
                }
                num = num8 ^ ((int)num3 * -265559845);
                continue;
            }

            case 5u:
            {
                string ip = new string(array[1].Where(delegate(char c)
                    {
                        //Discarded unreachable code: IL_0052
                        if (!char.IsLetterOrDigit(c))
                        {
                            while (true)
                            {
                                int num11 = 212579801;
                                while (true)
                                {
                                    uint num12;
                                    switch ((num12 = (uint)num11 ^ 0xDE26FE2u) % 4u)
                                    {
                                    case 2u:
                                        break;

                                    case 3u:
                                        {
                                            int num13;
                                            int num14;
                                            if (c == '.')
                                            {
                                                num13 = -158807755;
                                                num14 = num13;
                                            }
                                            else
                                            {
                                                num13 = -694170600;
                                                num14 = num13;
                                            }
                                            num11 = num13 ^ (int)(num12 * 1129387666);
                                            continue;
                                        }

                                    case 0u:
                                        return(c == '-');

                                    default:
                                        goto IL_0061;
                                    }
                                    break;
                                }
                            }
                        }
                        goto IL_0061;
                        IL_0061:
                        return(true);
                    }).ToArray());
                ConnectToHostname(ip);
                num = -828669762;
                continue;
            }

            case 14u:
                goto IL_01d2;

            case 9u:
                playerText._Send = false;
                num = (int)(num3 * 4425787) ^ -440414735;
                continue;

            case 11u:
            {
                int num4;
                int num5;
                if (string.IsNullOrEmpty(array[1]))
                {
                    num4 = 2079224214;
                    num5 = num4;
                }
                else
                {
                    num4 = 1662400866;
                    num5 = num4;
                }
                num = num4 ^ ((int)num3 * -1900441634);
                continue;
            }

            case 1u:
                return;
            }
            break;
IL_008d:
            int num10;
            if (!(array[0] == "/goto"))
            {
                num   = -828669762;
                num10 = num;
            }
            else
            {
                num   = -181681680;
                num10 = num;
            }
        }
        goto IL_000f;
IL_000f:
        num = -513758749;
        goto IL_0014;
    }