Пример #1
2
 public FFRKMySqlInstance()
 {
     mDatabaseThread = new BackgroundWorker();
     mDatabaseThread.DoWork += mDatabaseThread_DoWork;
     mDatabaseThread.RunWorkerAsync();
     mDatabaseQueue = new BlockingCollection<IDbRequest>();
     mCancellationTokenSource = new CancellationTokenSource();
     mConnectionState = ConnectionState.Disconnected;
 }
Пример #2
0
        public void TestCancelAsync()
        {
            BackgroundWorker bw = new BackgroundWorker();

            bw.DoWork += DoWorkExpectCancel;
            bw.WorkerSupportsCancellation = true;

            manualResetEvent3 = new ManualResetEventSlim(false);

            bw.RunWorkerAsync("Message");
            bw.CancelAsync();

            bool ret = manualResetEvent3.Wait(TimeoutLong);
            Assert.True(ret);
            // there could be race condition between worker thread cancellation and completion which will set the CancellationPending to false 
            // if it is completed already, we don't check cancellation
            if (bw.IsBusy) // not complete
            {
                if (!bw.CancellationPending)
                {
                    for (int i = 0; i < 1000; i++)
                    {
                        Wait(TimeoutShort);
                        if (bw.CancellationPending)
                        {
                            break;
                        }
                    }
                }
                // Check again
                if (bw.IsBusy)
                    Assert.True(bw.CancellationPending, "Cancellation in Main thread");
            }
        }
Пример #3
0
        static void Main(string[] args)
        {
            _tweetQueue = new Queue<string>();
            _worker = new BackgroundWorker();
            _worker.DoWork += new DoWorkEventHandler(DBWrite);

            DateTime executionStart = DateTime.Now;
            while (true)
            {
                Console.Write("-");
                try
                {
                    executionStart = DateTime.Now;
                    ConsumeStream();
                }
                catch (Exception e)
                {
                    Output.Print(_name, "Exception from Run:" + Environment.NewLine + e);
                    while (_worker.IsBusy)
                    {
                        Console.WriteLine("Waiting for worker to finish");
                        Thread.Sleep(1000);
                    }
                    if ((DateTime.Now - executionStart).TotalSeconds < 5)
                    {
                        Output.Print(_name, "Previous failure was quick. Waiting 60 seconds.");
                        Thread.Sleep(59000);
                    }
                }
                Console.WriteLine(".");
                Thread.Sleep(1000);
            }

        }
    private void OnTouched()
    {
        if (_backgroundWorker != null) _backgroundWorker.CancelAsync();
        _backgroundWorker = new BackgroundWorker();

        if (string.IsNullOrEmpty(Thread.CurrentThread.Name)) Thread.CurrentThread.Name = "Main";

        Debug.Log("START " + Thread.CurrentThread.Name);
        Plane.InfoStr += "\nS("+Thread.CurrentThread.Name+");";
        _backgroundWorker.DoWork += (o, a) =>
        {
            Debug.Log("INSIDE1 " + Thread.CurrentThread.Name);
            Plane.InfoStr += "IN1("+Thread.CurrentThread.Name+");"+a.Argument+";";
            for (var i = 0; i < 10000000; ++i)
            {
                if (a.IsCanceled) return;

                var n = 67876 + i / 100f;
                var x = Mathf.Pow(n, 3);
            }
            Debug.Log("INSIDE2 " + Thread.CurrentThread.Name);
            Plane.InfoStr += "IN2("+Thread.CurrentThread.Name+");";

            a.Result = a.Argument+"!";
        };
        _backgroundWorker.RunWorkerCompleted += (o, a) =>
        {
            Debug.Log("END " + Thread.CurrentThread.Name);
            Plane.InfoStr += "E("+Thread.CurrentThread.Name+");"+a.Result+";";
        };

        _backgroundWorker.RunWorkerAsync("A1");
    }
Пример #5
0
 /// <summary>
 /// Initialize the manager, should be called in OnNavigatedTo of main page.
 /// </summary>
 public void Initialize()
 {
     socket = new StreamSocket();
     dataReadWorker = new BackgroundWorker();
     dataReadWorker.WorkerSupportsCancellation = true;
     dataReadWorker.DoWork += new DoWorkEventHandler(ReceiveMessages);
 }
    public NativeWorkbench()
    {
        try
        {
          //  KeyDown += OnKeyDown;
            Tick += OnTick;
        }
        catch (Exception e)
        {
            SaveLoad.Log(e.ToString());
           // Debug.WriteLine(e);
        }


        BackgroundWorker myWorker = new BackgroundWorker();
        myWorker.DoWork += (sender, e) =>
        {
            try
            {
                Application.EnableVisualStyles();
                Application.Run(_nativeWorkbenchForm);
            }
            catch (Exception ex)
            {
                SaveLoad.Log(ex.ToString());
            }
        };
        myWorker.RunWorkerAsync();
    }
Пример #7
0
 public void bgworkercounter()
 {
     var backgroundWorker1 = new BackgroundWorker();
     backgroundWorker1.DoWork += backgroundWorker1_DoWork;
     backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;
     backgroundWorker1.RunWorkerAsync();
 }
 // Use this for initialization
 void Start()
 {
     // init a background worker thread
     BackgroundWorker worker = new BackgroundWorker();
     worker.DoWork += HandleWorkerDoWork;
     worker.RunWorkerAsync();
 }
 public void TestCallDoWorkOnBackgroundThreadAndThenCallOnSuccessOnMainThread()
 {
     var strategy = new MockBackgroundWorkerStrategy();
     var operation = new BackgroundWorker<object>(strategy);
     operation.Execute();
     strategy.CheckThatOnDoWorkWasCalled();
 }
Пример #10
0
        internal HidDevice(string devicePath)
        {
            this.devicePath = devicePath;

            try
            {
                var hidHandle = OpenDeviceIO(devicePath, NativeMethods.ACCESS_NONE);

                deviceAttributes = GetDeviceAttributes(hidHandle);
                deviceCapabilities = GetDeviceCapabilities(hidHandle);

                CloseDeviceIO(hidHandle);
            }
            catch (Exception exception)
            {
                throw new Exception(string.Format("Error querying HID device '{0}'.", devicePath), exception);
            }

            deviceEventMonitor = new HidDeviceEventMonitor(this);
            deviceEventMonitor.Inserted += DeviceEventMonitorInserted;
            deviceEventMonitor.Removed += DeviceEventMonitorRemoved;

            readWorker = new BackgroundWorker<HidDeviceData>();
            readWorker.Updated += new EventHandler<EventArgs<HidDeviceData>>(readWorker_Updated);
            readWorker.DoWork += new System.ComponentModel.DoWorkEventHandler(readWorker_DoWork);
        }
Пример #11
0
        public void BackgroundWorker_CancelAsync_ReportsCancelledWhenWorkerSupportsCancellationIsTrue()
        {
            UnitTestContext context = GetContext();

              int numTimesProgressCalled = 0;

              BackgroundWorker target = new BackgroundWorker();
              target.DoWork += (o, e) =>
              {
            // report progress changed 10 times
            for (int i = 1; i < 11; i++)
            {
              Thread.Sleep(100);
              if (target.CancellationPending)
              {
            e.Cancel = true;
            return;
              }
            }
              };
              target.WorkerSupportsCancellation = true;
              target.RunWorkerCompleted += (o, e) =>
              {
            //  target does not support ReportProgress we shold get a System.InvalidOperationException from DoWork
            context.Assert.IsNull(e.Error);
            context.Assert.IsTrue(e.Cancelled);
            context.Assert.Success();
              };
              target.RunWorkerAsync(null);
              target.CancelAsync();
              context.Complete();
        }
Пример #12
0
    // private static SimpleCompileForm _simpleCompileForm;

    private static void Main(string[] args)
    {
        var worker = new BackgroundWorker();
        worker.DoWork += (sender, e) =>
        {
            try
            {
                _nativeWorkbenchForm = new NativeWorkbenchForm();
                _timer = new System.Windows.Forms.Timer();
                _timer.Stop();
                _timer.Interval = 100;
                _timer.Tick += _timer_Tick;
                _timer.Start();
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
            Application.EnableVisualStyles();
            Application.Run(_nativeWorkbenchForm);
        };
        worker.RunWorkerAsync();


        Thread.Sleep(-1);
    }
Пример #13
0
 public void Cancel()
 {
     if (worker != null)
     {
        worker.CancelAsync();
        worker = null;
     }
 }
Пример #14
0
 public void DefaultValues()
 {
     var backgroundWorker = new BackgroundWorker<object, object, object>();
     Assert.IsTrue(backgroundWorker.ThrowExceptionOnCompleted);
     Assert.IsFalse(backgroundWorker.IsBusy);
     Assert.IsFalse(backgroundWorker.WorkerReportsProgress);
     Assert.IsFalse(backgroundWorker.WorkerSupportsCancellation);
 }
Пример #15
0
        public HidDeviceEventMonitor(HidDevice device)
        {
            this.device = device;

            monitor = new BackgroundWorker<bool>();
            monitor.Updated += new EventHandler<EventArgs<bool>>(monitor_Updated);
            monitor.DoWork += new System.ComponentModel.DoWorkEventHandler(monitor_DoWork);
        }
Пример #16
0
 public void ReportProgressNonBusy()
 {
     var b = new BackgroundWorker<object, object, object>
                 {
                     WorkerReportsProgress = true
                 };
     Assert.IsFalse(b.IsBusy);
     b.ReportProgress(0);
 }
Пример #17
0
 public void ThrowExceptionOnCompletedFalse()
 {
     var b = new BackgroundWorker<object, object, object>
                 {
                     ThrowExceptionOnCompleted = false,
                     DoWork = ThrowException
                 };
     b.RunWorkerAsync();
 }
Пример #18
0
 public void CancelAsyncNonBusy()
 {
     var backgroundWorker = new BackgroundWorker<object, object, object>
                 {
                     WorkerSupportsCancellation = true
                 };
     Assert.IsFalse(backgroundWorker.IsBusy);
     backgroundWorker.CancelAsync();
 }
Пример #19
0
 public Fallidas()
 {
     bckWrk = new BackgroundWorker();
     bckWrk.DoWork += new System.ComponentModel.DoWorkEventHandler(this.bckWrk_DoWork);
     bckWrk.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.bckWrk_RunWorkerCompleted);
     aTimer = new System.Timers.Timer(10000);
     aTimer.Elapsed += new ElapsedEventHandler(GrabarFallidas);
     aTimer.Enabled = true;
 }
Пример #20
0
        public TwitterStreamConsumer(string connectionString, bool useForWordStatsOnly)
        {
            _tweetQueue = new Queue<string>();
            _worker = new BackgroundWorker();
            _worker.DoWork += new DoWorkEventHandler(DBWrite);

            _connectionString = connectionString;
            _wordStatsOnly = useForWordStatsOnly;
        }
Пример #21
0
        public SystemService()
        {
            _timer = new Timer (10000);
            _timer.Elapsed += Elapsed;
            _timer.Start ();

            _worker = new BackgroundWorker ();
            _worker.DoWork += DoWork;
        }
Пример #22
0
 void StartBackgroundInitialization()
 {
     Log.Info("PictureOfTheDay: Init!");
     pluginBackgroundWorker = new BackgroundWorker();
     pluginBackgroundWorker.WorkerReportsProgress = true;
     pluginBackgroundWorker.WorkerSupportsCancellation = false;
     pluginBackgroundWorker.DoWork += DoWork;
     pluginBackgroundWorker.RunWorkerAsync();
 }
Пример #23
0
 public Worker(string[] arguments)
 {
     this.worker = new BackgroundWorker();
     worker.WorkerSupportsCancellation = true;
     worker.WorkerReportsProgress = true;
     worker.DoWork += new DoWorkEventHandler(worker_DoWork);
     worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
     worker.RunWorkerAsync(arguments);
 }
 private void StartDownloadEvfInBackGround()
 {
     var backgroundWorker = new BackgroundWorker();
     backgroundWorker.Work(() =>
     {
         while (this.DownloadEvf())
             Thread.Sleep(EosCamera.WaitTimeoutForNextLiveDownload);                
     });
 }
       // private bool m_DansLedgerTableExists = false; 
        #endregion
#region Constructors & Destructors
        public EqualizeProviderPayments(BackgroundWorker bw)
        {
			GC.Collect(); // Found out that the object may not be collected.  If it is not then the finzlizer won't be in the que to call
			GC.WaitForPendingFinalizers(); // Note this can make a serious performance hit.
			
            if (InstanceCounter > 0)
                throw new Exception("Not supposed to make more than one instance of this object! Check it out");
            InstanceCounter++;
        }
Пример #26
0
    public Form1()
    {
        InitializeComponent();

        // Instantiate BackgroundWorker and attach handlers to its
        // DowWork and RunWorkerCompleted events.
        backgroundWorker1 = new System.ComponentModel.BackgroundWorker();
        backgroundWorker1.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorker1_DoWork);
        backgroundWorker1.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorker1_RunWorkerCompleted);
    }
 /// <summary>
 /// Initializes a new instance of the MonitorComPort class 
 /// build connectionString in constructor
 /// </summary>
 public MonitorComPort()
 {
     this.timeCount = 0;
     this.backgroundWorkerMonitorComPort = new BackgroundWorker();
     this.backgroundWorkerMonitorComPort.WorkerReportsProgress = true;
     this.backgroundWorkerMonitorComPort.WorkerSupportsCancellation = true;
     this.backgroundWorkerMonitorComPort.DoWork += new DoWorkEventHandler(this.MonitorComPortDoWork);
     this.backgroundWorkerMonitorComPort.ProgressChanged += new ProgressChangedEventHandler(this.MonitorComPortProgress);
     ////backControlTableUpdate.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bwStationRunWorkerCompleted);
 }
Пример #28
0
 public FileState()
     : base()
 {
     asyncWriter = new BackgroundWorker();
     asyncWriter.DoWork += new DoWorkEventHandler(WriteDataAsync);
     asyncWriter.RunWorkerCompleted +=
             new RunWorkerCompletedEventHandler(
                 (object sender, RunWorkerCompletedEventArgs e) => { if (postponedWrite) { postponedWrite = false; asyncWriter.RunWorkerAsync(); } }
             );
 }
 /// <summary>
 /// Adds a worker method into the processing queue.
 /// </summary>
 /// <param name="callback"></param>
 /// <param name="state"></param>
 public void AddWorker(WaitCallback callback, object state)
 {
     lock (this)
     {
         BackgroundWorker worker = new BackgroundWorker(callback, state);
         queue.Enqueue(worker);
         while (activeWorkerCount < Math.Min(queue.Count, MaxConcurrency))
             LaunchBackgroundWorker();
     }
 }
Пример #30
0
 public FormDatabaseInfo()
 {
     timer1 = new Timer();
     timer1.Interval = 100;
     timer1.Tick += timer1_Tick;
     bw = new BackgroundWorker();
     bw.RunWorkerCompleted += bw_RunWorkerCompleted;
     bw.DoWork += bw_DoWork;
     InitializeComponent();
 }
Пример #31
0
 public override Bitmap processImage(Bitmap SourseImage, BackgroundWorker worker)
 {
     maxColor(SourseImage);
     return(base.processImage(SourseImage, worker));
 }
Пример #32
0
        /// <summary>
        /// Updates the NetworkSystem to
        /// 1) Create and maintain the network session
        /// 2) update all networked element's components and
        /// 3) send local element's component's updates to remote systems
        /// </summary>
        /// <param name="elapsedTime">
        /// The time elapsed between this and the previous frame
        /// </param>
        public void Update(float elapsedTime)
        {
            if (searchingForAvailableSessions)
            {
                searchingtimer += elapsedTime;
                searchingtimer %= 1;
                return;
            }

            if (game.GameState == GameState.NetworkSetup)
            {
                switch (menuState)
                {
                case NetworkMenuState.SelectMode:
                    if (menuSessionState == 1)
                    {
                        if (Keyboard.GetState().IsKeyDown(Keys.Left) ||
                            GamePad.GetState(PlayerIndex.One).ThumbSticks.Left.X <= -1 ||
                            GamePad.GetState(PlayerIndex.Two).ThumbSticks.Left.X <= -1 ||
                            GamePad.GetState(PlayerIndex.Three).ThumbSticks.Left.X <= -1 ||
                            GamePad.GetState(PlayerIndex.Four).ThumbSticks.Left.X <= -1)
                        {
                            if (!pressedKeys.left)
                            {
                                menuSessionState--;
                                menuSpriteLocation = TextLocations[1] - new Vector2(10, 0);
                                pressedKeys.left   = true;


                                menuSelectSound.Play();
                                break;
                            }
                        }
                        else
                        {
                            pressedKeys.left = false;
                        }

                        if (Keyboard.GetState().IsKeyDown(Keys.Space) ||
                            GamePad.GetState(PlayerIndex.One).IsButtonDown(Buttons.A) ||
                            GamePad.GetState(PlayerIndex.Two).IsButtonDown(Buttons.A) ||
                            GamePad.GetState(PlayerIndex.Three).IsButtonDown(Buttons.A) ||
                            GamePad.GetState(PlayerIndex.Four).IsButtonDown(Buttons.A))
                        {
                            if (!pressedKeys.space)
                            {
                                try
                                {
                                    menuSelectSound.Play();

                                    backgroundWorker = new BackgroundWorker();

                                    backgroundWorker.DoWork +=
                                        new DoWorkEventHandler(findAvailableSessions);
                                    backgroundWorker.RunWorkerCompleted +=
                                        new RunWorkerCompletedEventHandler(foundAvailableSessions);

                                    backgroundWorker.RunWorkerAsync();

                                    searchingForAvailableSessions = true;

                                    pressedKeys.space = true;
                                }
                                catch (Exception e)
                                {
                                    //Throw error
                                }
                                break;
                            }
                        }
                        else
                        {
                            pressedKeys.space = false;
                        }
                    }

                    if (menuSessionState == 0)
                    {
                        if (Keyboard.GetState().IsKeyDown(Keys.Right) ||
                            GamePad.GetState(PlayerIndex.One).ThumbSticks.Left.X >= 1 ||
                            GamePad.GetState(PlayerIndex.Two).ThumbSticks.Left.X >= 1 ||
                            GamePad.GetState(PlayerIndex.Three).ThumbSticks.Left.X >= 1 ||
                            GamePad.GetState(PlayerIndex.Four).ThumbSticks.Left.X >= 1)
                        {
                            if (!pressedKeys.right)
                            {
                                menuSessionState++;
                                menuSpriteLocation = TextLocations[2] - new Vector2(10, 0);
                                pressedKeys.right  = true;

                                menuSelectSound.Play();

                                break;
                            }
                        }
                        else
                        {
                            pressedKeys.right = false;
                        }

                        if (Keyboard.GetState().IsKeyDown(Keys.Space) ||
                            GamePad.GetState(PlayerIndex.One).IsButtonDown(Buttons.A) ||
                            GamePad.GetState(PlayerIndex.Two).IsButtonDown(Buttons.A) ||
                            GamePad.GetState(PlayerIndex.Three).IsButtonDown(Buttons.A) ||
                            GamePad.GetState(PlayerIndex.Four).IsButtonDown(Buttons.A))
                        {
                            if (!pressedKeys.space)
                            {
                                menuSelectSound.Play();

                                menuState          = NetworkMenuState.CreateSession;
                                menuSpriteLocation = TextLocations[3] - new Vector2(10, 0);
                                pressedKeys.space  = true;

                                break;
                            }
                        }
                        else
                        {
                            pressedKeys.space = false;
                        }
                    }

                    break;

                case NetworkMenuState.JoinSession:

                    if (menuSessionState == 0)     //select game
                    {
                        if (Keyboard.GetState().IsKeyDown(Keys.Down) ||
                            GamePad.GetState(PlayerIndex.One).ThumbSticks.Left.Y >= 1 ||
                            GamePad.GetState(PlayerIndex.Two).ThumbSticks.Left.Y >= 1 ||
                            GamePad.GetState(PlayerIndex.Three).ThumbSticks.Left.Y >= 1 ||
                            GamePad.GetState(PlayerIndex.Four).ThumbSticks.Left.Y >= 1)
                        {
                            if (!pressedKeys.down)
                            {
                                menuSessionState++;
                                menuSpriteLocation = TextLocations[5] - new Vector2(10, 0);
                                pressedKeys.down   = true;


                                menuSelectSound.Play();
                                break;
                            }
                        }
                        else
                        {
                            pressedKeys.down = false;
                        }

                        if (Keyboard.GetState().IsKeyDown(Keys.Left) ||
                            GamePad.GetState(PlayerIndex.One).ThumbSticks.Left.X <= -1 ||
                            GamePad.GetState(PlayerIndex.Two).ThumbSticks.Left.X <= -1 ||
                            GamePad.GetState(PlayerIndex.Three).ThumbSticks.Left.X <= -1 ||
                            GamePad.GetState(PlayerIndex.Four).ThumbSticks.Left.X <= -1)
                        {
                            if (!pressedKeys.left)
                            {
                                if (availableSessions.Count > 0)
                                {
                                    selectedSession--;
                                    selectedSession   %= availableSessions.Count;
                                    currentSessionName = string.Format("Session %s : %d / %d",
                                                                       availableSessions[selectedSession].HostGamertag,
                                                                       availableSessions[selectedSession].CurrentGamerCount,
                                                                       availableSessions[selectedSession].CurrentGamerCount
                                                                       + availableSessions[selectedSession].OpenPublicGamerSlots);

                                    menuSelectSound.Play();
                                }
                                pressedKeys.left = true;

                                break;
                            }
                        }
                        else
                        {
                            pressedKeys.left = false;
                        }

                        if (Keyboard.GetState().IsKeyDown(Keys.Right) ||
                            GamePad.GetState(PlayerIndex.One).ThumbSticks.Left.X >= 1 ||
                            GamePad.GetState(PlayerIndex.Two).ThumbSticks.Left.X >= 1 ||
                            GamePad.GetState(PlayerIndex.Three).ThumbSticks.Left.X >= 1 ||
                            GamePad.GetState(PlayerIndex.Four).ThumbSticks.Left.X >= 1)
                        {
                            if (!pressedKeys.right)
                            {
                                if (availableSessions.Count > 0)
                                {
                                    selectedSession++;
                                    selectedSession   %= availableSessions.Count;
                                    currentSessionName = string.Format("Session %s : %d / %d",
                                                                       availableSessions[selectedSession].HostGamertag,
                                                                       availableSessions[selectedSession].CurrentGamerCount,
                                                                       availableSessions[selectedSession].CurrentGamerCount
                                                                       + availableSessions[selectedSession].OpenPublicGamerSlots);

                                    menuSelectSound.Play();
                                }
                                pressedKeys.right = true;

                                break;
                            }
                        }
                        else
                        {
                            pressedKeys.right = false;
                        }
                    }
                    else if (menuSessionState == 1)     //go
                    {
                        if (Keyboard.GetState().IsKeyDown(Keys.Up) ||
                            GamePad.GetState(PlayerIndex.One).ThumbSticks.Left.Y <= -1 ||
                            GamePad.GetState(PlayerIndex.Two).ThumbSticks.Left.Y <= -1 ||
                            GamePad.GetState(PlayerIndex.Three).ThumbSticks.Left.Y <= -1 ||
                            GamePad.GetState(PlayerIndex.Four).ThumbSticks.Left.Y <= -1)
                        {
                            if (!pressedKeys.up)
                            {
                                menuSessionState--;
                                menuSpriteLocation = TextLocations[4] - new Vector2(10, 0);
                                pressedKeys.up     = true;

                                menuSelectSound.Play();
                                break;
                            }
                        }
                        else
                        {
                            pressedKeys.up = false;
                        }

                        if (Keyboard.GetState().IsKeyDown(Keys.Space) ||
                            GamePad.GetState(PlayerIndex.One).IsButtonDown(Buttons.A) ||
                            GamePad.GetState(PlayerIndex.Two).IsButtonDown(Buttons.A) ||
                            GamePad.GetState(PlayerIndex.Three).IsButtonDown(Buttons.A) ||
                            GamePad.GetState(PlayerIndex.Four).IsButtonDown(Buttons.A))
                        {
                            if (!pressedKeys.space)
                            {
                                menuSelectSound.Play();

                                JoinSession();

                                break;
                            }
                        }
                        else
                        {
                            pressedKeys.space = false;
                        }
                    }


                    if (Keyboard.GetState().IsKeyDown(Keys.B) ||
                        GamePad.GetState(PlayerIndex.One).IsButtonDown(Buttons.B) ||
                        GamePad.GetState(PlayerIndex.Two).IsButtonDown(Buttons.B) ||
                        GamePad.GetState(PlayerIndex.Three).IsButtonDown(Buttons.B) ||
                        GamePad.GetState(PlayerIndex.Four).IsButtonDown(Buttons.B))
                    {
                        if (!pressedKeys.b)
                        {
                            menuSessionState   = 1;
                            menuState          = NetworkMenuState.SelectMode;
                            menuSpriteLocation = TextLocations[2] - new Vector2(10, 0);
                            pressedKeys.b      = true;

                            menuSelectSound.Play();

                            break;
                        }
                    }
                    else
                    {
                        pressedKeys.b = false;
                    }

                    break;

                case NetworkMenuState.CreateSession:
                    if (Keyboard.GetState().IsKeyDown(Keys.Space) ||
                        GamePad.GetState(PlayerIndex.One).IsButtonDown(Buttons.A) ||
                        GamePad.GetState(PlayerIndex.Two).IsButtonDown(Buttons.A) ||
                        GamePad.GetState(PlayerIndex.Three).IsButtonDown(Buttons.A) ||
                        GamePad.GetState(PlayerIndex.Four).IsButtonDown(Buttons.A))
                    {
                        if (!pressedKeys.space)
                        {
                            menuSelectSound.Play();
                            CreateSession();

                            break;
                        }
                    }
                    else
                    {
                        pressedKeys.space = false;
                    }

                    if (Keyboard.GetState().IsKeyDown(Keys.B) ||
                        GamePad.GetState(PlayerIndex.One).IsButtonDown(Buttons.B) ||
                        GamePad.GetState(PlayerIndex.Two).IsButtonDown(Buttons.B) ||
                        GamePad.GetState(PlayerIndex.Three).IsButtonDown(Buttons.B) ||
                        GamePad.GetState(PlayerIndex.Four).IsButtonDown(Buttons.B))
                    {
                        if (!pressedKeys.b)
                        {
                            menuSessionState   = 0;
                            menuState          = NetworkMenuState.SelectMode;
                            menuSpriteLocation = TextLocations[1] - new Vector2(10, 0);
                            pressedKeys.b      = true;

                            menuSelectSound.Play();

                            break;
                        }
                    }
                    else
                    {
                        pressedKeys.b = false;
                    }
                    break;
                }
            }
            else
            {
                // send local object updates
                SendLocalEntityUpdates();

                // Pump the session
                session.Update();

                // Check for session ending
                if (session == null)
                {
                    game.GameState = GameState.NetworkSetup;
                }

                // Read packets for remote updates
                RecieveRemoteEntityUpdates();
            }
        }
Пример #33
0
        public static void GenerateLog(BackgroundWorker backgroundWorker, string inputPath, string outputPath)
        {
            var pdfPath = outputPath + ".pdf";
            var csvPath = outputPath + ".csv";

            var sheetToProcess = Properties.CommonSettings.Default.Sheet;

            try
            {
                var excelApp = new ExcelToCSVService(inputPath, sheetToProcess);
                excelApp.GetOutput(csvPath);
            }
            catch (Exception ex)
            {
                throw new ApplicationException("Error processing the Excel worksheet.", ex);
            }

            backgroundWorker.ReportProgress(40);

            var columns          = Properties.ColumnSettings.Default;
            var csvToCallService = new CSVToCallsService(columns.SessionIDColumn,
                                                         columns.FromNameColumn,
                                                         columns.FromNumberColumn,
                                                         columns.ToNameColumn,
                                                         columns.ToNumberColumn,
                                                         columns.CallResultColumn,
                                                         columns.CallLengthColumn,
                                                         columns.HandleTimeColumn,
                                                         columns.StartTimeColumn,
                                                         columns.CallDirectionColumn,
                                                         columns.CallQueueColumn);

            List <Call> calls;

            try
            {
                calls = csvToCallService.ParseCSV(csvPath);
            }
            catch (Exception ex)
            {
                throw new ApplicationException("Error reading data from file.", ex);
            }

            backgroundWorker.ReportProgress(60);

            var callProcessing = new CallProcessingService(calls);

            var employees = Properties.CommonSettings.Default.Employees.Cast <string>().ToList();

            Dictionary <string, CallLog>   processedCalls;
            Dictionary <string, CallStats> totalStats;

            try
            {
                processedCalls = callProcessing.GetCallsPerPerson(employees);
                totalStats     = callProcessing.GetTotalStats(employees);
            }
            catch (Exception ex)
            {
                throw new ApplicationException("Error performing queries on phone call logs.", ex);
            }

            backgroundWorker.ReportProgress(80);

            try
            {
                var pdfService = new PDFService(pdfPath);
                pdfService.GenerateOutput(processedCalls, totalStats);
            }
            catch (Exception ex)
            {
                throw new ApplicationException("Error generating PDF file from data.", ex);
            }

            backgroundWorker.ReportProgress(100);
        }
        private static void UpdateTranslationFiles(TranslationProject project, BackgroundWorker worker)
        {
            var containers = project.Game.GetContainers(project.InstallationPath);

            foreach (var container in containers)
            {
                if (worker.CancellationPending)
                {
                    worker.ReportProgress(0, "CANCELADO");
                    throw new UserCancelException();
                }

                var translationContainer =
                    project.FileContainers.FirstOrDefault(x => x.Path == container.Path && x.Type == container.Type);

                var addNewContainer = false;
                var addedFiles      = 0;

                if (translationContainer == null)
                {
                    translationContainer = new TranslationFileContainer(container.Path, container.Type);
                    addNewContainer      = true;
                }

                var extractionContainerPath = Path.Combine(project.ContainersFolder, translationContainer.Id);
                Directory.CreateDirectory(extractionContainerPath);

                var containerPath = Path.GetFullPath(Path.Combine(project.InstallationPath, container.Path));

                worker.ReportProgress(0, $"Procesando {container.Path}...");
                if (container.Type == ContainerType.CompressedFile)
                {
                    if (File.Exists(containerPath))
                    {
                        if (addNewContainer)
                        {
                            project.Game.PreprocessContainer(translationContainer, containerPath, extractionContainerPath);
                            project.Game.ExtractFile(containerPath, extractionContainerPath);
                        }

                        foreach (var fileSearch in container.FileSearches)
                        {
                            worker.ReportProgress(0, $"Buscando {fileSearch.RelativePath}\\{fileSearch.SearchPattern}...");
                            var foundFiles = fileSearch.GetFiles(extractionContainerPath);

                            foreach (var f in foundFiles)
                            {
                                var relativePath = PathHelper.GetRelativePath(extractionContainerPath, Path.GetFullPath(f));
                                var type         = fileSearch.FileType;

                                var translationFile = translationContainer.Files.FirstOrDefault(x => x.RelativePath == relativePath);

                                if (translationFile == null)
                                {
                                    try
                                    {
                                        translationFile = (TranslationFile)Activator.CreateInstance(type, f,
                                                                                                    project.ChangesFolder, project.Game.FileEncoding);
                                    }
                                    catch (MissingMethodException e)
                                    {
                                        translationFile =
                                            (TranslationFile)Activator.CreateInstance(type, f, project.ChangesFolder);
                                    }
                                    catch (Exception e)
                                    {
                                        translationFile = new TranslationFile(f, project.ChangesFolder);
                                    }

                                    translationFile.RelativePath = relativePath;

                                    if (translationFile.Type == FileType.TextFile)
                                    {
                                        if (translationFile.SubtitleCount > 0)
                                        {
                                            translationContainer.AddFile(translationFile);
                                            addedFiles++;
                                        }
                                    }
                                    else
                                    {
                                        translationContainer.AddFile(translationFile);
                                        addedFiles++;
                                    }
                                }
                            }
                        }

                        project.Game.PostprocessContainer(translationContainer, containerPath, extractionContainerPath);

                        worker.ReportProgress(0, $"{addedFiles} ficheros encontrados y añadidos");
                    }
                    else
                    {
                        worker.ReportProgress(0, $"ERROR: No existe el fichero comprimido {containerPath}");
                        continue;
                    }
                }
                else
                {
                    project.Game.PreprocessContainer(translationContainer, containerPath, extractionContainerPath);
                    foreach (var fileSearch in container.FileSearches)
                    {
                        worker.ReportProgress(0, $"Buscando {fileSearch.RelativePath}\\{fileSearch.SearchPattern}...");
                        var foundFiles = fileSearch.GetFiles(containerPath);

                        foreach (var f in foundFiles)
                        {
                            var relativePath = PathHelper.GetRelativePath(containerPath, Path.GetFullPath(f));

                            var destinationFileName = Path.GetFullPath(Path.Combine(extractionContainerPath, relativePath));
                            var destPath            = Path.GetDirectoryName(destinationFileName);
                            Directory.CreateDirectory(destPath);

                            if (!File.Exists(destinationFileName))
                            {
                                File.Copy(f, destinationFileName);
                            }

                            var type = fileSearch.FileType;

                            var translationFile = translationContainer.Files.FirstOrDefault(x => x.RelativePath == relativePath);

                            if (translationFile == null)
                            {
                                try
                                {
                                    translationFile = (TranslationFile)Activator.CreateInstance(type,
                                                                                                destinationFileName, project.ChangesFolder, project.Game.FileEncoding);
                                }
                                catch (MissingMethodException e)
                                {
                                    translationFile =
                                        (TranslationFile)Activator.CreateInstance(type, destinationFileName,
                                                                                  project.ChangesFolder);
                                }
                                catch (Exception e)
                                {
                                    translationFile = new TranslationFile(destinationFileName, project.ChangesFolder);
                                }

                                translationFile.RelativePath = relativePath;

                                if (translationFile.Type == FileType.TextFile)
                                {
                                    if (translationFile.SubtitleCount > 0)
                                    {
                                        translationContainer.AddFile(translationFile);
                                        addedFiles++;
                                    }
                                }
                                else
                                {
                                    translationContainer.AddFile(translationFile);
                                    addedFiles++;
                                }
                            }
                        }

                        project.Game.PostprocessContainer(translationContainer, containerPath, extractionContainerPath);
                        worker.ReportProgress(0, $"{addedFiles} ficheros encontrados y añadidos");
                    }
                }

                if (addNewContainer && translationContainer.Files.Count > 0)
                {
                    project.FileContainers.Add(translationContainer);
                }
            }
        }
 public void ReadTranslationFiles(BackgroundWorker worker)
 {
     UpdateTranslationFiles(this, worker);
 }
Пример #36
0
        public static Color[,] ComputeAlgorithmVersion1(Color[,] currentImage, int Kr, int Kg, int Kb, Random random, BackgroundWorker backgroundWorker)
        {
            Color[,] image = (Color[, ])currentImage.Clone();
            int nR = OrderedHelper.GetClosestN(Kr);
            int nG = OrderedHelper.GetClosestN(Kg);
            int nB = OrderedHelper.GetClosestN(Kb);

            for (int i = 0; i < CONST.bitmapWidth; i++)
            {
                for (int j = 0; j < CONST.bitmapHeight; j++)
                {
                    int r = Values.Round255(OrderedHelper.GetColorForOrdered(currentImage[i, j].R, nR, random, -1, -1));
                    int g = Values.Round255(OrderedHelper.GetColorForOrdered(currentImage[i, j].G, nG, random, -1, -1));
                    int b = Values.Round255(OrderedHelper.GetColorForOrdered(currentImage[i, j].B, nB, random, -1, -1));
                    image[i, j] = Color.FromArgb(r, g, b);
                }
                backgroundWorker.ReportProgress((int)((double)(i * 100) / CONST.bitmapWidth));
            }

            return(image);
        }
Пример #37
0
        /// <summary>
        /// Initializes a new instance of the <see cref="StringTableEditorViewModel"/> class.
        /// </summary>
        public StringTableEditorViewModel()
        {
            TemplateMaster.Instance.Load("templates.xml");

            this.violationsBackgroundWorker = new BackgroundWorker
            {
                WorkerSupportsCancellation = true,
                WorkerReportsProgress      = true
            };

            this.violationsBackgroundWorker.DoWork             += this.violationsBackgroundWorker_DoWork;
            this.violationsBackgroundWorker.RunWorkerCompleted += this.violationsBackgroundWorker_RunWorkerCompleted;

            this.searchBackgroundWorker = new BackgroundWorker
            {
                WorkerSupportsCancellation = true,
                WorkerReportsProgress      = true
            };

            this.searchBackgroundWorker.DoWork             += this.searchBackgroundWorker_DoWork;
            this.searchBackgroundWorker.RunWorkerCompleted += this.searchBackgroundWorker_RunWorkerCompleted;

            this.replaceBackgroundWorker = new BackgroundWorker
            {
                WorkerSupportsCancellation = true,
                WorkerReportsProgress      = true
            };

            this.replaceBackgroundWorker.DoWork             += this.replaceBackgroundWorker_DoWork;
            this.replaceBackgroundWorker.RunWorkerCompleted += this.replaceBackgroundWorker_RunWorkerCompleted;

            this.Violations = new ObservableCollection <IViolation>();

            this.AboutCommand = ReactiveCommand.Create();
            this.AboutCommand.Subscribe(_ =>
            {
                var aboutV = new AboutView();
                aboutV.ShowDialog();
            });

            this.UnloadProjectCommand = ReactiveCommand.Create();
            this.UnloadProjectCommand.Subscribe(_ => this.UnloadProjectCommandExecute());

            this.OpenCommand = ReactiveCommand.Create();
            this.OpenCommand.Subscribe(_ => this.OpenCommandExecute());
            this.OpenFolderCommand = ReactiveCommand.Create();
            this.OpenFolderCommand.Subscribe(_ => this.OpenFolderCommandExecute());

            var canSave = this.WhenAny(x => x.Projects, x => x.Value.Count >= 1);

            this.SaveCommand = ReactiveCommand.Create(canSave);
            this.SaveCommand.Subscribe(_ => this.QuickSaveCommandExecute());

            var canSaveAs = this.WhenAny(x => x.Projects, x => x.Value.Count == 1);

            this.SaveAsCommand = ReactiveCommand.Create(canSaveAs);
            this.SaveAsCommand.Subscribe(_ => this.SaveAsCommandExecute());

            this.StringTableConvertCommand = ReactiveCommand.Create();
            this.StringTableConvertCommand.Subscribe(_ => this.StringTableConvertCommandExecute());

            var canFill = this.WhenAny(x => x.Keys, x => x.Value.Count > 0);

            this.FillMissingCommand = ReactiveCommand.Create(canFill);
            this.FillMissingCommand.Subscribe(_ => this.FillMissingInSelectionCommandExecute());

            this.WipeCommand = ReactiveCommand.Create(canFill);
            this.WipeCommand.Subscribe(_ => this.WipeCommandExecute());

            var canFindInTree = this.WhenAny(x => x.SelectedKey, x => x.Value != null);

            this.FindInTreeCommand = ReactiveCommand.Create(canFindInTree);
            this.FindInTreeCommand.Subscribe(_ =>
            {
                this.SelectedNode = this.SelectedKey;
            });

            this.WhenAny(vm => vm.SelectedNode, vm => vm.Value != null).Subscribe(async _ =>
            {
                await Task.Run(() => this.RecomputeGridKeys());
                this.RunViolationsCheck();
            });

            // display the violation keys
            this.WhenAny(vm => vm.SelectedViolation, vm => vm.Value != null).Subscribe(_ =>
            {
                if (this.SelectedViolation != null)
                {
                    this.Keys = this.SelectedViolation.Keys;
                }
            });

            this.EditProjectCommand = ReactiveCommand.Create();
            this.EditProjectCommand.Subscribe(_ => this.ExecuteEditProjectCommand());

            this.AddPackageCommand = ReactiveCommand.Create();
            this.AddPackageCommand.Subscribe(_ => this.ExecuteAddPackageCommand());

            this.EditPackageCommand = ReactiveCommand.Create();
            this.EditPackageCommand.Subscribe(_ => this.ExecuteEditPackageCommand());

            this.RemovePackageCommand = ReactiveCommand.Create();
            this.RemovePackageCommand.Subscribe(_ => this.ExecuteRemovePackageCommand());

            this.AddContainerCommand = ReactiveCommand.Create();
            this.AddContainerCommand.Subscribe(_ => this.ExecuteAddContainerCommand());

            this.EditContainerCommand = ReactiveCommand.Create();
            this.EditContainerCommand.Subscribe(_ => this.ExecuteEditContainerCommand());

            this.RemoveContainerCommand = ReactiveCommand.Create();
            this.RemoveContainerCommand.Subscribe(_ => this.ExecuteRemoveContainerCommand());

            this.AddKeyCommand = ReactiveCommand.Create();
            this.AddKeyCommand.Subscribe(_ => this.ExecuteAddKeyCommand());

            this.DuplicateKeyCommand = ReactiveCommand.Create();
            this.DuplicateKeyCommand.Subscribe(_ => this.ExecuteDuplicateKeyCommand());

            this.RemoveKeyCommand = ReactiveCommand.Create();
            this.RemoveKeyCommand.Subscribe(_ => this.ExecuteRemoveKeyCommand());

            this.TemplatesCommand = ReactiveCommand.Create();
            this.TemplatesCommand.Subscribe(_ => this.ExecuteTemplatesCommand());

            var canSearch = this.WhenAny(x => x.SearchString, x => !string.IsNullOrEmpty(x.Value));

            this.SearchCommand = ReactiveCommand.Create(canSearch);
            this.SearchCommand.Subscribe(_ => this.ExecuteSearchCommand());

            this.ReplaceCommand = ReactiveCommand.Create(canSearch);
            this.ReplaceCommand.Subscribe(_ => this.ExecuteReplaceCommand());

            this.ConfigScannerVm = new ConfigScannerViewModel {
                ParentViewModel = this
            };

            this.SetPropertis();
        }
 private void Window_Loaded(object sender, RoutedEventArgs e)
 {
     worker         = new BackgroundWorker();
     worker.DoWork += worker_DoWork;
     worker.RunWorkerAsync();
 }
Пример #39
0
        public static void UpdateDat(object sender, DoWorkEventArgs e)
        {
            try
            {
                _bgw = sender as BackgroundWorker;
                if (_bgw == null)
                {
                    return;
                }

                Program.SyncCont = e.Argument as SynchronizationContext;
                if (Program.SyncCont == null)
                {
                    _bgw = null;
                    return;
                }


                _bgw.ReportProgress(0, new bgwText("Clearing DB Status"));
                RepairStatus.ReportStatusReset(DB.DirTree);

                _datCount = 0;

                _bgw.ReportProgress(0, new bgwText("Finding Dats"));
                RvDir datRoot = new RvDir(FileType.Dir)
                {
                    Name = "RomVault", DatStatus = DatStatus.InDatCollect
                };

                // build a datRoot tree of the DAT's in DatRoot, and count how many dats are found
                if (!RecursiveDatTree(datRoot, out _datCount))
                {
                    _bgw.ReportProgress(0, new bgwText("Dat Update Complete"));
                    _bgw             = null;
                    Program.SyncCont = null;
                    return;
                }

                _bgw.ReportProgress(0, new bgwText("Scanning Dats"));
                _datsProcessed = 0;

                // now compare the database DAT's with datRoot removing any old DAT's
                RemoveOldDats(DB.DirTree.Child(0), datRoot);

                // next clean up the File status removing any old DAT's
                RemoveOldDatsCleanUpFiles(DB.DirTree.Child(0));

                _bgw.ReportProgress(0, new bgwSetRange(_datCount - 1));

                // next add in new DAT and update the files
                UpdateDatList((RvDir)DB.DirTree.Child(0), datRoot);

                // finally remove any unneeded DIR's from the TreeView
                RemoveOldTree(DB.DirTree.Child(0));

                _bgw.ReportProgress(0, new bgwText("Updating Cache"));
                DB.Write();

                _bgw.ReportProgress(0, new bgwText("Dat Update Complete"));
                _bgw             = null;
                Program.SyncCont = null;
            }
            catch (Exception exc)
            {
                ReportError.UnhandledExceptionHandler(exc);

                if (_bgw != null)
                {
                    _bgw.ReportProgress(0, new bgwText("Updating Cache"));
                }
                DB.Write();
                if (_bgw != null)
                {
                    _bgw.ReportProgress(0, new bgwText("Complete"));
                }

                _bgw             = null;
                Program.SyncCont = null;
            }
        }
Пример #40
0
        public bool SendAsych(Action <XNetResult> cb)
        {
            if (ow || civ || dn != null)
            {
                return(false);
            }
            or = ow = true;

            string dstr = "";

            try
            {
                r = this.PreSend(out dstr);
                if (r == null)
                {
                    throw new Exception("Error: " + dstr);
                }
                byte[] bdata = Encoding.UTF8.GetBytes(dstr);

                string           strs = "";
                BackgroundWorker bgw  = new BackgroundWorker();
                bgw.DoWork += (a, b) =>
                {
                    Stream          strm     = null;
                    HttpWebResponse res      = null;
                    bool            syncDone = false;

                    r.ReadWriteTimeout = (int)_opt["ReadWriteTimeout", new JSON(1000 * 60 * 15)].NumberValue;
                    r.Timeout          = (int)_opt["Timeout", new JSON(1000 * 60 * 15)].NumberValue;

                    if (dstr.Length > 0)
                    {
                        // getting stream
                        syncDone = false;
                        try
                        {
                            var ssync = r.BeginGetRequestStream(new AsyncCallback((c) =>
                            {
                                try
                                {
                                    strm = r.EndGetRequestStream(c);
                                }
                                catch (Exception ex) { b.Result = ex.Message; }
                                finally { syncDone = true; }
                            }), r);
                        }
                        catch (Exception ex) { b.Result = ex.Message; }
                        if (b.Result != null)
                        {
                            throw new Exception("Cannot get request stream, details: " + b.Result);
                        }

                        // wait until done with checking
                        while (!syncDone)
                        {
                            if (civ)
                            {
                                b.Cancel = true;
                                r.Abort();
                                return;
                            }
                        }
                        if (b.Result != null)
                        {
                            throw new Exception("Cannot get request stream, details: " + b.Result);
                        }

                        // writing stream
                        syncDone = false;
                        var wsync = strm.BeginWrite(bdata, 0, bdata.Length, new AsyncCallback((c) =>
                        {
                            try
                            {
                                strm.EndWrite(c);
                            }
                            catch (Exception ex) { b.Result = ex.Message; }
                            finally { syncDone = true; }
                        }), strm);
                        if (b.Result != null)
                        {
                            throw new Exception("Cannot sending data, details: " + b.Result);
                        }

                        // wait until done with checking
                        while (!syncDone)
                        {
                            if (civ)
                            {
                                b.Cancel = true;
                                r.Abort();
                                return;
                            }
                        }
                        if (b.Result != null)
                        {
                            throw new Exception("Cannot sending data, details: " + b.Result);
                        }
                        strm.Close();
                    }

                    // get response
                    syncDone = false;
                    var rsync = r.BeginGetResponse(new AsyncCallback((c) =>
                    {
                        try
                        {
                            res = (HttpWebResponse)r.EndGetResponse(c);
                        }
                        catch (Exception ex) { b.Result = ex.Message; }
                        finally { syncDone = true; }
                    }), r);
                    if (b.Result != null)
                    {
                        throw new Exception("Cannot getting data, details: " + b.Result);
                    }

                    // wait until done with checking
                    while (!syncDone)
                    {
                        if (civ)
                        {
                            b.Cancel = true;
                            r.Abort();
                            return;
                        }
                    }
                    if (b.Result != null)
                    {
                        throw new Exception("Cannot getting data, details: " + b.Result);
                    }

                    // reading stream
                    using (var ssr = new StreamReader(res.GetResponseStream()))
                    {
                        strs = ssr.ReadToEnd();
                    }
                    b.Result = res;
                };

                bgw.RunWorkerCompleted += (a, b) =>
                {
                    or = false;
                    if (b.Error != null)
                    {
                        dn = new XNetResult(b.Error);
                    }
                    else if (b.Result == null || b.Cancelled)
                    {
                        dn = new XNetResult(false);
                    }
                    else if (b.Result.Equals(true))
                    {
                        dn = new XNetResult(true, "No output", "");
                    }
                    else if (b.Result.GetType() == typeof(HttpWebResponse))
                    {
                        if (strs.Length > 0)
                        {
                            dn = new XNetResult(true, (HttpWebResponse)b.Result, "", strs);
                        }
                        else
                        {
                            dn = new XNetResult(true, (HttpWebResponse)b.Result);
                        }
                    }
                    else
                    {
                        dn = new XNetResult(false);
                    }

                    cb(dn);
                    ow = false;
                };

                bgw.RunWorkerAsync();
            }
            catch (Exception ex)
            {
                dn = new XNetResult(ex);
                cb(dn);
            }
            return(true);
        }
Пример #41
0
        public static void ReadLogs(string[] summonerNames, string groupName, string gamePath, int minimumGames, BackgroundWorker bw)
        {
            Directory.CreateDirectory(@"Groups\" + groupName);

            errorLogPath = Path.Combine(@"Logs\" + DateTime.Now.ToString().Replace(" ", "_").Replace(":", "-") + @".txt");
            string logPath          = gamePath + @"Logs\Game - R3d Logs\";
            string tempPath         = @"Groups\Temp.txt";
            string summonerInfoPath = @"Groups\" + groupName + @"\Summoners.txt";
            string dirPath          = @"Groups";

            hadError = false;
            bool  inGame           = false;
            float readLogsProgress = 0;

            if (!Directory.Exists(logPath) || Directory.GetFiles(logPath) == null)
            {
                //WriteError("Couldnt find any logs in the specified folder!", "FileNotFoundException\n" + logPath);
                return;
            }

            string[] logs = Directory.GetFiles(logPath, "*_r3dlog.txt");             // Get all r3dlogs in logPath's directory.

            if (logs.Length == 1)
            {
                WriteLog("Found " + logs.Length + " log!");
            }
            else if (logs.Length > 1)
            {
                WriteLog("Found " + logs.Length + " logs!");
            }
            else if (logs.Length == 0)
            {
                WriteError("Couldn't find any logs!\nPlease check if the installation path is correct!", "");
            }


            File.WriteAllText(tempPath, String.Empty);             // Empty old files / Create temp file.
            File.WriteAllText(errorLogPath, "------ Starting analyze at " + DateTime.Now.TimeOfDay.ToString().Remove(8, 8) + " ------\n\n");

            Dictionary <string, int> summonersPlayed = new Dictionary <string, int>();
            List <string>            champions       = new List <string>();
            float totalLogs = logs.Length * summonerNames.Length;

            // Creating directory to store info in
            Directory.CreateDirectory(dirPath);

            WriteLog("Working. Please wait...");
            WriteLog("Reading through logs...");
            sw.Start();

            try
            {
                float logsAnalyzed = 0;                                   // Counting logs

                foreach (string log in logs)                              // For each log-file (x_r3dlog.txt)
                {
                    string[] lines             = File.ReadAllLines(@log); // Get all the text in the file
                    string   champion          = " created for ";         // Declare what string means that there is a champion loaded in
                    bool     isSummonerPlaying = false;

                    // For each line in the log-file
                    foreach (string line in lines)
                    {
                        // If a string has both a champion loading in and it is controlled by the specified Summoner
                        if (line.Contains(champion))
                        {
                            foreach (string summonerName in summonerNames)
                            {
                                if (line.Contains(summonerName))
                                {
                                    isSummonerPlaying = true;

                                    // Lots of trimming of the raw text
                                    string tempLine = line.Remove(0, 62);
                                    int    index    = tempLine.IndexOf("(");
                                    tempLine = tempLine.Remove(index, 16 + summonerName.Length);

                                    champions.Add(tempLine);
                                }
                            }
                        }
                    }

                    // Don't know if this is the best way to do this, but it's the easiest way I can come up with.
                    // Since we need to know if the log file contains the summonerName first we read through it again.
                    foreach (string line in lines)
                    {
                        // If a champion is being loaded in and if one of the summoners is in the match
                        if (line.Contains(champion) && isSummonerPlaying)
                        {
                            if (!line.Contains(" Bot") || Settings.GetIncludeBots())
                            {
                                string tempStr = line;
                                tempStr = tempStr.Substring(tempStr.LastIndexOf("created for"));
                                string otherSummoner = tempStr.Remove(0, 12);

                                if (!summonerNames.Contains(otherSummoner))
                                {
                                    if (summonersPlayed.ContainsKey(otherSummoner))
                                    {
                                        summonersPlayed[otherSummoner] += 1;
                                    }
                                    else if (!summonersPlayed.ContainsKey(otherSummoner))
                                    {
                                        summonersPlayed.Add(otherSummoner, 1);
                                    }
                                    else
                                    {
                                        WriteError("bullshit", "this-should-not-be-able-to-happen-exception");                                         // impossibru
                                    }
                                }
                            }
                        }
                    }

                    logsAnalyzed++;
                    readLogsProgress += (1f / (totalLogs / 100f)) * summonerNames.Length;

                    bw.ReportProgress((int)Math.Ceiling(readLogsProgress));
                }
            }
            catch (FileNotFoundException e)
            {
                WriteError("Couldn't find any log files in the specified folder!", "FileNotFoundException\n" + e.Message);
            }
            catch (IOException e)             // Most likely access denied error
            {
                if (e.Message.Contains("cannot access"))
                {
                    WriteError("Couldn't access a specific log file! Oh no!\nMake sure to not be in-game when running this program!", e.ToString());
                    inGame = true;
                }
                hadError = true;
            }
            catch (Exception e)             // Any other error?
            {
                WriteError("Error!", e.ToString());
                inGame   = true;
                hadError = true;
            }


            if (!hadError)
            {
                WriteLog("Done analyzing! Starting counting!");
            }
            else
            {
                return;
            }


            List <KeyValuePair <string, int> > myList = summonersPlayed.ToList();

            myList.Sort(
                delegate(KeyValuePair <string, int> firstPair,
                         KeyValuePair <string, int> nextPair)
            {
                return(nextPair.Value.CompareTo(firstPair.Value));
            }
                );

            using (var tw2 = new StreamWriter(summonerInfoPath))
            {
                int summonersCounted = 0;
                tw2.AutoFlush = true;

                foreach (KeyValuePair <string, int> entry in myList)
                {
                    if (entry.Value > minimumGames)
                    {
                        string tempStr = entry.ToString();
                        tempStr = tempStr.Substring(1, tempStr.Length - 2);

                        tw2.WriteLine(tempStr);
                    }

                    summonersCounted++;
                    int percent = (int)Math.Floor(75f + (((summonersCounted / (float)myList.Count) * 100f) * 0.5f));
                    bw.ReportProgress(percent);
                }
            }

            using (var tw = new StreamWriter(tempPath, false, Encoding.ASCII, 0x10000))
            {
                foreach (string str in champions)
                {
                    // Writing the text into the file located at infoPath (\Summoners\summonerNameTemp.txt)
                    tw.WriteLine(str);
                }
            }

            if (!inGame)
            {
            }
            else
            {
                WriteError("\nAn error occurred and the program\nwill not be able to compile the data.", "Make sure you're not in-game while running the program!");
            }
        }
Пример #42
0
        public static void Count(string groupName, BackgroundWorker bw)
        {
            try
            {
                string tempPath = @"Groups\Temp.txt";
                string dirPath  = @"Groups\" + groupName + @"\Champions.txt";

                File.WriteAllText(dirPath, String.Empty);
                Dictionary <string, int> dic = new Dictionary <string, int>();

                string[] analyzeResult = File.ReadAllLines(tempPath);
                Array.Sort(analyzeResult);

                // Fill in the Dictionary
                foreach (string champ in analyzeResult)
                {
                    if (dic.ContainsKey(champ))
                    {
                        dic[champ] += 1;
                    }
                    else if (!dic.ContainsKey(champ))
                    {
                        dic.Add(champ, 1);
                    }
                    else
                    {
                        Console.WriteLine("bullshit");                         // impossibru
                    }
                }

                // Time to start using Champions.txt
                string[] champions = File.ReadAllLines(@"Champions.txt");

                using (var tw = new StreamWriter(dirPath))
                {
                    tw.AutoFlush = true;

                    foreach (string champion in champions)
                    {
                        try
                        {
                            //Console.WriteLine(champion + ": " + dic[champion]);
                            tw.WriteLine(champion + ": " + dic[champion]);
                        }
                        catch (KeyNotFoundException)
                        {
                            Debug.WriteLine(champion + " hasn't been played.");
                        }
                    }
                }

                // Remove temporary file
                File.Delete(tempPath);
            }
            catch (Exception e)
            {
                if (e.Message.Contains("cannot access"))
                {
                    WriteError("Couldn't access a specific log file!", "Make sure to not be in-game when running this program!");
                    Debug.WriteLine(e.ToString());
                }
                else
                {
                    WriteError("Error!", e.ToString());
                    Debug.WriteLine(e.ToString());
                }
                hadError = true;
            }

            sw.Stop();

            WriteLog("Done! You can now view your stats in the tab!");
            try
            {
                WriteLog("Time elapsed: " + sw.Elapsed.ToString().Remove(8, 8));
            }
            catch (ArgumentOutOfRangeException)
            {
                hadError = true;
                return;
            }
        }
Пример #43
0
        public static List <string> GetDirectoriesFromRootPath(string rootPath, string directorySearchPatterns = "", BackgroundWorker worker = null)
        {
            if (!Directory.Exists(rootPath))
            {
                return(null);
            }

            var searchPatterns = directorySearchPatterns?.Split('|') ?? new string[] { "" };

            List <string> directories = getDirectoriesFromPath(rootPath, worker) ?? new List <string>();

            directories = directories.Where(dir => StringServices.IsTextIncludingPatterns(dir, searchPatterns)).ToList();

            foreach (var directory in directories)
            {
                var recursiveYield = GetDirectoriesFromRootPath(directory, directorySearchPatterns, worker);
                directories = recursiveYield != null
                    ? directories.Concat(recursiveYield).ToList()
                    : null;
            }

            return(directories != null?directories.ToList() : null);
        }
        public static TranslationProject Load(string path, PluginManager pluginManager, BackgroundWorker worker)
        {
            var types = new Dictionary <string, Type>();

            var searchNewFiles = false;

            using (var fs = new FileStream(path, FileMode.Open))
                using (var input = new ExtendedBinaryReader(fs, Encoding.UTF8))
                {
                    var result = new TranslationProject();

                    var gameId = input.ReadString();
                    var game   = pluginManager.GetGame(gameId);
                    result.Game = game ?? throw new Exception("No existe un plugin para cargar este fichero.");

                    var pluginVersion = input.ReadInt32();
                    if (pluginVersion > game.Version)
                    {
                        throw new Exception("No coincide la versión del plugin instalado con la versión del que creó esta traducción.");
                    }

                    if (pluginVersion < game.Version)
                    {
                        searchNewFiles = true;
                    }

                    var installPath = input.ReadString();
                    if (!Directory.Exists(installPath))
                    {
                        throw new Exception($"No se encuentra la carpeta de instalación: {installPath}");
                    }

                    result.InstallationPath = installPath;
                    result.WorkPath         = Path.GetDirectoryName(path);

                    var containersCount = input.ReadInt32();
                    for (var i = 0; i < containersCount; i++)
                    {
                        var containerId   = input.ReadString();
                        var containerPath = input.ReadString();
                        var containerType = (ContainerType)input.ReadInt32();
                        var container     = new TranslationFileContainer(containerId, containerPath, containerType);

                        var fileCount = input.ReadInt32();
                        for (var j = 0; j < fileCount; j++)
                        {
                            var fileId           = input.ReadString();
                            var filePath         = input.ReadString();
                            var fileRelativePath = input.ReadString();
                            var fileName         = input.ReadString();
                            var typeString       = input.ReadString();

                            var             type = GetType(typeString, types);
                            TranslationFile file;
                            try
                            {
                                file = (TranslationFile)Activator.CreateInstance(type, filePath, result.ChangesFolder, result.Game.FileEncoding);
                            }
                            catch (MissingMethodException e)
                            {
                                file = (TranslationFile)Activator.CreateInstance(type, filePath, result.ChangesFolder);
                            }
                            catch (Exception e)
                            {
                                file = new TranslationFile(filePath, result.ChangesFolder);
                            }

                            file.Id           = fileId;
                            file.Name         = fileName;
                            file.RelativePath = fileRelativePath;
                            container.AddFile(file);
                        }

                        result.FileContainers.Add(container);
                    }

                    if (searchNewFiles)
                    {
                        UpdateTranslationFiles(result, worker);
                    }

                    return(result);
                }
        }
	private void InitializeComponents(){
		_button1 = new Button();
		_button2 = new Button();
		_button3 = new Button();
		_label1 = new Label();
		_label2 = new Label();
		_label3 = new Label();
		_pb1 = new ProgressBar();
		_pb2 = new ProgressBar();
		_pb3 = new ProgressBar();
		_bw1 = new BackgroundWorker();
		_bw2 = new BackgroundWorker();
		_bw3 = new BackgroundWorker();

		_button1.Text = "Do Something";
		_button1.AutoSize = true;
		_button1.Click += ButtonOneClickHandler;
		_button1.Dock = DockStyle.Fill;
		_label1.BackColor = Color.Green;
		_label1.Dock = DockStyle.Fill;
		_pb1.Minimum = 0;
		_pb1.Maximum = 3000;
		_pb1.Dock = DockStyle.Fill;
		_bw1.DoWork += DoWorkOne;
		_bw1.WorkerReportsProgress = true;
		_bw1.ProgressChanged += ReportProgressOne;
		_bw1.RunWorkerCompleted += ResetLabelOne;

		_button2.Text = "Do Something Else";
		_button2.AutoSize = true;
		_button2.Click += ButtonTwoClickHandler;
		_button2.Dock = DockStyle.Fill;
		_label2.BackColor = Color.Green;
		_label2.Dock = DockStyle.Fill;
		_pb2.Minimum = MINIMUM;
		_pb2.Maximum = MAXIMUM;
		_pb2.Dock = DockStyle.Fill;
		_bw2.DoWork += DoWorkTwo;
		_bw2.WorkerReportsProgress = true;
		_bw2.ProgressChanged += ReportProgressTwo;
		_bw2.RunWorkerCompleted += ResetLabelTwo;

		_button3.Text = "Do Something Different";
		_button3.AutoSize = true;
		_button3.Click += ButtonThreeClickHandler;
		_button3.Dock = DockStyle.Fill;
		_label3.BackColor = Color.Green;
		_label3.Dock = DockStyle.Fill;
		_pb3.Minimum = MINIMUM;
		_pb3.Maximum = MAXIMUM;
		_pb3.Dock = DockStyle.Fill;
		_bw3.DoWork += DoWorkThree;
		_bw3.WorkerReportsProgress = true;
		_bw3.ProgressChanged += ReportProgressThree;
		_bw3.RunWorkerCompleted += ResetLabelThree;
	 
		TableLayoutPanel tlp1 = new TableLayoutPanel();
		tlp1.RowCount = 3;
		tlp1.ColumnCount = 3;
		this.SuspendLayout();
		tlp1.SuspendLayout();
		tlp1.AutoSize = true;
		tlp1.Dock = DockStyle.Fill;
		tlp1.Controls.Add(_button1);
		tlp1.Controls.Add(_button2);
		tlp1.Controls.Add(_button3);
		tlp1.Controls.Add(_label1);
		tlp1.Controls.Add(_label2);
		tlp1.Controls.Add(_label3);
		tlp1.Controls.Add(_pb1);
		tlp1.Controls.Add(_pb2);
		tlp1.Controls.Add(_pb3);
		this.Controls.Add(tlp1);
		this.AutoSize = true;
		this.AutoSizeMode = AutoSizeMode.GrowAndShrink;
		this.Height = tlp1.Height + 20;
		this.Width = tlp1.Width;
		tlp1.ResumeLayout();
		this.ResumeLayout();
	}
Пример #46
0
 protected override void ProcessLineValues(double[] rowValues, string line, int lineNumber, BackgroundWorker worker, DoWorkEventArgs e)
 {
     if (staticFileReady)
     {
         container.ForceAddVoxel(new Voxel_Habitat(rowValues));
     }
     base.ProcessLineValues(rowValues, line, lineNumber, worker, e); // This is an empty function of the base class.
 }
        public IList <Tuple <TranslationFileContainer, TranslationFile> > SearchInFiles(string searchString, BackgroundWorker worker)
        {
            var result = new List <Tuple <TranslationFileContainer, TranslationFile> >();

            foreach (var container in FileContainers)
            {
                if (worker.CancellationPending)
                {
                    worker.ReportProgress(0, "CANCELADO");
                    throw new UserCancelException();
                }

                worker.ReportProgress(0, $"Procesando {container.Path}...");

                foreach (var file in container.Files)
                {
                    var found = file.Search(searchString);

                    if (found)
                    {
                        result.Add(new Tuple <TranslationFileContainer, TranslationFile>(container, file));
                    }
                }
            }

            return(result);
        }
        public IEnumerable <Auction> GetAllAuctions(bool includeImages, bool includeEnded, BackgroundWorker bw)
        {
            List <Auction> auctions    = new List <Auction>();
            var            auctionData = Helpers.GetDataFromUrl("https://www.minnbid.org/Mobile/GetLotsDataJs", "POST");

            auctionData = WebUtility.HtmlDecode(auctionData);

            //Clean up the JSON
            auctionData = auctionData.Replace(@"\r\n", "");
            auctionData = auctionData.Replace(@"\""", @"""");
            auctionData = auctionData.Replace(@"\\""", @"\""");
            auctionData = auctionData.Substring(1, auctionData.Length - 2);

            dynamic auctionItemJSON = JObject.Parse(auctionData);

            if (!String.IsNullOrEmpty(auctionData))
            {
                Auction mainAuction = new Auction();

                List <AuctionItem> items = new List <AuctionItem>();

                foreach (var item in auctionItemJSON.Table)
                {
                    AuctionItem itemToAdd = new AuctionItem();

                    itemToAdd.ID               = item.LotID;
                    itemToAdd.CurrentPrice     = item.CurrentPrice;
                    itemToAdd.EndDateTime      = item.ClosingDateTime;
                    itemToAdd.FullDescription  = Helpers.StripHTMLTags(item.LotDescription.ToString());
                    itemToAdd.AuctionItemURL   = "https://www.minnbid.org/Mobile/AuctionLot/" + item.LotID;
                    itemToAdd.ShortDescription = item.ItemName;
                    itemToAdd.Auction          = mainAuction;

                    //The bidding increment is only stored on the item's page, so load the data from that page then parse out the increment
                    var itemWebData = Helpers.GetDataFromUrl(itemToAdd.AuctionItemURL);
                    var doc         = new HAP.HtmlDocument();
                    doc.LoadHtml(itemWebData);
                    var root      = doc.DocumentNode;
                    var increment = root.SelectNodes("//span").Where(x => x.GetAttributeValue("id", "") == "spnIncrement").FirstOrDefault().InnerText;
                    //add the increment to the current price to determine the next bid required
                    itemToAdd.NextBidRequired = itemToAdd.CurrentPrice + double.Parse(increment.Replace("$", ""));

                    items.Add(itemToAdd);
                }

                mainAuction.AuctionItems  = items;
                mainAuction.AuctionName   = "Minnesota Online Auction";
                mainAuction.AuctionSource = "Minnesota";

                auctions.Add(mainAuction);
            }

            return(auctions);
        }
Пример #49
0
        private void btnConnect_Click(object sender, EventArgs e)
        {
            string connString = cboConnectionString.Text;

            Exception exception = null;

            DataTable schema   = null;
            string    database = string.Empty;

            var worker = new BackgroundWorker();

            worker.DoWork += delegate(object sender2, DoWorkEventArgs e2)
            {
                try
                {
                    using (var conn = new SqlConnection(connString))
                    {
                        conn.Open();
                        schema   = conn.GetSchema("Databases");
                        database = conn.Database;
                        conn.Close();
                        SqlConnection.ClearPool(conn);
                    }
                }
                catch (Exception ex)
                {
                    exception = new Exception("Error opening source connection: " + ex.Message);
                    return;
                }

                // TODO:
                _generatorHelper         = new GeneratorHelper(typeof(SqlConnection), connString, worker);
                _generatorHelper.Prompt += delegate(object s3, PromptEventArgs e3)
                {
                    e3.Result = ScrollableMessageBox.ShowDialog(e3.Message, "Error", ScrollableMessageBoxButtons.Yes, ScrollableMessageBoxButtons.No);
                };
            };

            WinControls.WinProgressBox.ShowProgress(worker, progressBarStyle: ProgressBarStyle.Marquee);
            if (exception != null)
            {
                MessageBox.Show(exception.Message);
            }
            else
            {
                refreshPage(false);

                var           settings    = PaJaMa.Common.SettingsHelper.GetUserSettings <DatabaseStudioSettings>();
                List <string> connStrings = settings.ConnectionStrings.Split('|').ToList();
                if (!connStrings.Any(s => s == cboConnectionString.Text))
                {
                    connStrings.Add(cboConnectionString.Text);
                }

                settings.ConnectionStrings         = string.Join("|", connStrings.ToArray());
                settings.LastQueryConnectionString = cboConnectionString.Text;
                PaJaMa.Common.SettingsHelper.SaveUserSettings <DatabaseStudioSettings>(settings);

                _lockDbChange = true;
                cboDatabase.Items.Clear();
                foreach (var dr in schema.Rows.OfType <DataRow>())
                {
                    cboDatabase.Items.Add(dr["database_name"].ToString());
                }
                cboDatabase.Text = database;

                _lockDbChange = false;

                btnConnect.Visible    = btnRemoveConnString.Visible = false;
                btnDisconnect.Visible = true;
                cboConnectionString.SelectionLength = 0;
                cboConnectionString.Enabled         = false;
                cboDatabase.Visible = true;
                btnGo.Enabled       = btnRefresh.Enabled = btnViewMissingDependencies.Enabled = btnAdd10.Enabled = btnAddNRows.Enabled = btnQuery.Enabled = true;
            }
        }
        public void Export(IList <TranslationFileContainer> containers, ExportOptions options, BackgroundWorker worker)
        {
            PathHelper.DeleteDirectory(TempFolder);

            foreach (var container in containers)
            {
                if (worker.CancellationPending)
                {
                    worker.ReportProgress(0, "CANCELADO");
                    throw new UserCancelException();
                }

                worker.ReportProgress(0, $"Procesando {container.Path}...");

                if (container.Type == ContainerType.Folder)
                {
                    var outputFolder = Path.GetFullPath(Path.Combine(ExportFolder, container.Path));

                    foreach (var translationFile in container.Files)
                    {
                        if (translationFile.HasChanges || options.ForceRebuild)
                        {
                            translationFile.Rebuild(outputFolder);
                        }
                        else
                        {
                            var outputFile = Path.Combine(outputFolder, translationFile.RelativePath);
                            var dir        = Path.GetDirectoryName(outputFile);
                            Directory.CreateDirectory(dir);

                            File.Copy(translationFile.Path, outputFile, true);
                        }
                    }
                }
                else
                {
                    var outputFile = Path.GetFullPath(Path.Combine(ExportFolder, container.Path));
                    if (File.Exists(outputFile))
                    {
                        File.Delete(outputFile);
                    }

                    worker.ReportProgress(0, "Preparando para empaquetar...");
                    // 1. Copiar todos los ficheros del contenedor a una carpeta temporal
                    var source = Path.Combine(ContainersFolder, container.Id);
                    var dest   = Path.Combine(TempFolder, container.Id);
                    Directory.CreateDirectory(dest);

                    PathHelper.CloneDirectory(source, dest);

                    // 2. Crear los ficheros traducidos en esa carpeta temporal
                    worker.ReportProgress(0, "Generando ficheros traducidos...");
                    Parallel.ForEach(container.Files, translationFile =>
                    {
                        if (translationFile.HasChanges || options.ForceRebuild)
                        {
                            translationFile.Rebuild(dest);
                        }
                    });

                    // 3. Empaquetar
                    worker.ReportProgress(0, "Empaquetando fichero...");
                    Game.RepackFile(dest, outputFile, options.UseCompression);

                    // 4. Eliminar la carpeta temporal
                    if (!options.SaveTempFiles)
                    {
                        try
                        {
                            Directory.Delete(dest, true);
                        }
                        catch (IOException)
                        {
                            Thread.Sleep(0);
                            Directory.Delete(dest, true);
                        }
                    }
                }
            }
        }
 private void UserControl_Loaded(object sender, RoutedEventArgs e)
 {
     worker         = new BackgroundWorker();
     worker.DoWork += Worker_DoWork;
     worker.RunWorkerAsync();
 }
Пример #52
0
        private void butApply_Click(object sender, EventArgs e)
        {
            string errorMessage = this.ValidateForm();

            if (errorMessage != null)
            {
                MessageBox.Show("Error on validating form: " + errorMessage, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                this.UseWaitCursor = true;
                this.EnableAllControls(false, null);

                //SET TARGET RATINGS KEYS
                List <string> targetRatingsKeys = new List <string>();
                foreach (object o in this.chkRatings.CheckedItems)
                {
                    DataRowView drv = o as DataRowView;
                    if (drv != null)
                    {
                        targetRatingsKeys.Add(drv["key"] as string);
                    }
                }

                this.mRMod.SetTargetRatings(targetRatingsKeys);

                //SET TARGET RATINGS TYPE
                if (this.rbRatingsMin.Checked)
                {
                    this.mRMod.SetTargetRatingsType(RatingsModifier.RatingsTypeToModify.Min);
                }
                else if (this.rbRatingsMax.Checked)
                {
                    this.mRMod.SetTargetRatingsType(RatingsModifier.RatingsTypeToModify.Max);
                }
                else if (this.rbRatingsBoth.Checked)
                {
                    this.mRMod.SetTargetRatingsType(RatingsModifier.RatingsTypeToModify.Both);
                }

                //SET TARGET CARS
                if (this.rbCurrentCar.Checked)
                {
                    this.mRMod.SetTargetCars(RatingsModifier.CarsToModify.Current);
                }
                else if (this.rbSelectedCars.Checked)
                {
                    this.mRMod.SetTargetCars(RatingsModifier.CarsToModify.Selected);
                }
                else if (this.rbAllCars.Checked)
                {
                    this.mRMod.SetTargetCars(RatingsModifier.CarsToModify.All);
                }

                //SET TARGET ACTION
                if (this.rbActionRandomize.Checked)
                {
                    this.mRMod.SetTargetAction(RatingsModifier.ActionToPerform.Randomize);
                }
                else if (this.rbActionAdd.Checked)
                {
                    this.mRMod.SetTargetAction(RatingsModifier.ActionToPerform.Add);
                }
                else if (this.rbActionMultiply.Checked)
                {
                    this.mRMod.SetTargetAction(RatingsModifier.ActionToPerform.Multiply);
                }
                else if (this.rbActionSet.Checked)
                {
                    this.mRMod.SetTargetAction(RatingsModifier.ActionToPerform.Set);
                }

                //SET GROUPING OPTIONS
                this.mRMod.SetGroupingOptions(this.chkGroupByNumber.Checked, this.chkGroupByName.Checked);

                //SET VARIABLES
                int?    minValue = null;
                int?    maxValue = null;
                decimal?value    = null;

                string decsep = NumberFormatInfo.CurrentInfo.NumberDecimalSeparator;

                try { minValue = Int32.Parse(this.txtRandomizeFrom.Text.Replace(".", decsep).Replace(",", decsep)); }
                catch { }

                try { maxValue = Int32.Parse(this.txtRandomizeTo.Text.Replace(".", decsep).Replace(",", decsep)); }
                catch { }

                try { value = Decimal.Parse(this.txtActionValue.Text.Replace(".", decsep).Replace(",", decsep)); }
                catch { }

                this.mRMod.SetVariables(minValue, maxValue, value);

                //FINALLY, APPLY THE ACTION IN A SEPARATE THREAD
                BackgroundWorker backWorker = new BackgroundWorker();
                backWorker.DoWork             += new DoWorkEventHandler(backWorker_DoWork);
                backWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backWorker_RunWorkerCompleted);
                backWorker.RunWorkerAsync();


                this.mIsDirty = false;
            }
        }
Пример #53
0
 // THIS METHOD IS MAINTAINED BY THE FORM DESIGNER
 // DO NOT EDIT IT MANUALLY! YOUR CHANGES ARE LIKELY TO BE LOST
 void InitializeComponent()
 {
     this.components        = new System.ComponentModel.Container();
     this.textBox           = new System.Windows.Forms.TextBox();
     this.buttonStop        = new System.Windows.Forms.Button();
     this.buttonStart       = new System.Windows.Forms.Button();
     this.backgroundWorker1 = new System.ComponentModel.BackgroundWorker();
     this.timer1            = new System.Windows.Forms.Timer(this.components);
     this.backgroundWorker2 = new System.ComponentModel.BackgroundWorker();
     this.SuspendLayout();
     //
     // textBox
     //
     this.textBox.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                                                                  | System.Windows.Forms.AnchorStyles.Left)
                                                                 | System.Windows.Forms.AnchorStyles.Right)));
     this.textBox.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
     this.textBox.Font        = new System.Drawing.Font("Courier New", 11F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.World);
     this.textBox.Location    = new System.Drawing.Point(4, 32);
     this.textBox.Multiline   = true;
     this.textBox.Name        = "textBox";
     this.textBox.ScrollBars  = System.Windows.Forms.ScrollBars.Vertical;
     this.textBox.Size        = new System.Drawing.Size(328, 30);
     this.textBox.TabIndex    = 3;
     //
     // buttonStop
     //
     this.buttonStop.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
     this.buttonStop.Location  = new System.Drawing.Point(85, 3);
     this.buttonStop.Name      = "buttonStop";
     this.buttonStop.Size      = new System.Drawing.Size(75, 23);
     this.buttonStop.TabIndex  = 1;
     this.buttonStop.Text      = "Stop";
     this.buttonStop.Click    += new System.EventHandler(this.ButtonStopClick);
     //
     // buttonStart
     //
     this.buttonStart.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
     this.buttonStart.Location  = new System.Drawing.Point(4, 3);
     this.buttonStart.Name      = "buttonStart";
     this.buttonStart.Size      = new System.Drawing.Size(75, 23);
     this.buttonStart.TabIndex  = 0;
     this.buttonStart.Text      = "Start";
     this.buttonStart.Click    += new System.EventHandler(this.ButtonStartClick);
     //
     // backgroundWorker1
     //
     this.backgroundWorker1.DoWork             += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorker1_DoWork);
     this.backgroundWorker1.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorker1_RunWorkerCompleted);
     //
     // timer1
     //
     this.timer1.Enabled  = true;
     this.timer1.Interval = 10;
     this.timer1.Tick    += new System.EventHandler(this.timer1_Tick);
     //
     // backgroundWorker2
     //
     this.backgroundWorker2.DoWork             += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorker2_DoWork);
     this.backgroundWorker2.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorker2_RunWorkerCompleted);
     //
     // MainForm
     //
     this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
     this.ClientSize        = new System.Drawing.Size(334, 74);
     this.Controls.Add(this.textBox);
     this.Controls.Add(this.buttonStop);
     this.Controls.Add(this.buttonStart);
     this.Name        = "MainForm";
     this.Text        = "Kltest";
     this.Load       += new System.EventHandler(this.MainFormLoad);
     this.Shown      += new System.EventHandler(this.MainForm_Shown);
     this.MouseClick += new System.Windows.Forms.MouseEventHandler(this.MainForm_MouseClick);
     this.ResumeLayout(false);
     this.PerformLayout();
 }
 public override void PostApply(BackgroundWorker worker, DoWorkEventArgs e)
 {
     base.PostApply(worker, e);
 }
Пример #55
0
 public Form1()
 {
     InitializeComponent();
     this.bw         = new BackgroundWorker();
     this.bw.DoWork += this.bw_DoWork;
 }
Пример #56
0
 public ProgressDialog1(BackgroundWorker bgWorker, System.Threading.ManualResetEvent manualResult)
 {
     this.InitializeComponent();
     this._bgWorker     = bgWorker;
     this._manualResult = manualResult;
 }
Пример #57
0
 public QueueItem(BackgroundWorker backgroundWorker, Tin argument)
 {
     this.BackgroundWorker = backgroundWorker;
     this.Argument         = argument;
 }
Пример #58
0
        private void InitializePresetScriptCombobox()
        {
            LoadingOverlay.Visibility = Visibility.Visible;
            presetScriptItems = new List<PresetScript>();

            Progressbar.Value = 0;
            worker = new BackgroundWorker();
            worker.WorkerReportsProgress = true;
            worker.DoWork += (obj, e) =>
            {
                try
                {
                    //string baseDir = AppDomain.CurrentDomain.BaseDirectory;
                    Directory.CreateDirectory("presets");
                    string[] fileList = Directory.GetFiles("presets");
                    int count = fileList.Length;

                    string filename;
                    for (int i = 0; i < count; i++)
                    {
                        filename = Path.GetFileNameWithoutExtension(fileList[i]);
                        presetScriptItems.Add(
                            new PresetScript(
                                filename,
                                GetContent(fileList[i])));

                        double percent = ((i + 1) * 100) / count;
                        worker.ReportProgress((int)percent);
                        Thread.Sleep(500);
                    }
                }
                catch
                {
                    throw new Exception();
                }
            };
            worker.ProgressChanged += (obj, e) =>
            {
                //Progressbar.Value = e.ProgressPercentage;
                DoubleAnimation animation = new DoubleAnimation(e.ProgressPercentage, TimeSpan.FromMilliseconds(500));
                Progressbar.BeginAnimation(ProgressBar.ValueProperty, animation);
            };
            worker.RunWorkerCompleted += (obj, e) =>
            {
                PresetScriptCombobox.ItemsSource = presetScriptItems;
                PresetScriptCombobox.DisplayMemberPath = "Name";
                PresetScriptCombobox.SelectedValuePath = "Script";
                PresetScriptCombobox.SelectionChanged += PresetScriptCombobox_SelectionChanged;

                if (savingNewScript)
                {
                    PresetScriptCombobox.SelectedItem = presetScriptItems.FirstOrDefault(x => x.Name == savingNewScriptName);
                    savingNewScript = false;
                }
                else
                {
                    PresetScriptCombobox.SelectedIndex = -1;
                }

                LoadingOverlay.Visibility = Visibility.Collapsed;
            };
            worker.RunWorkerAsync();
        }
 private void InitializeComponent()
 {
     this.backgroundWorker                     = new BackgroundWorker();
     this.backgroundWorker.DoWork             += new DoWorkEventHandler(this.BackgroundWorkerDoWork);
     this.backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(this.BackgroundWorkerRunWorkerCompleted);
 }
Пример #60
0
 /// <summary>
 /// Ejecuta un plan de ejecución
 /// </summary>
 /// <param name="sticky">Plan de ejecución</param>
 /// <param name="work">Proceso en segundo plano</param>
 /// <returns>Datos devueltos por el plan de ejecución</returns>
 public static object ExecuteSticky(object sticky, BackgroundWorker work = null)
 {
     return sticky.GetType().GetMethod("ExecutePlan",
         new[] { typeof(BackgroundWorker) }).Invoke(sticky,
             new object[] { work });
 }