Exemplo n.º 1
0
        public void checkPeriodically(object sender, DoWorkEventArgs e)
        {
            Thread.Sleep(1000);//Wait 10s for Steambot to fully initialize
            while (true)
            {
                double newConversionRate = getConversionRate();
                if (newConversionRate != -1)
                    conversionRate = newConversionRate;

                DataSet verified_adds = returnQuery("SELECT * FROM add_verification a,users u WHERE verified=1 AND a.userID=u.userID");
                if (verified_adds != null)
                {
                    for (int r = 0; r < verified_adds.Tables[0].Rows.Count; r++)
                    {
                        BotManager.mainLog.Success("Add verified: " + verified_adds.Tables[0].Rows[r][2].ToString() + " DOGE to user " + verified_adds.Tables[0].Rows[r][1].ToString());
                        returnQuery("UPDATE users SET balance = balance + " + verified_adds.Tables[0].Rows[r][2].ToString() + " WHERE userID = " + verified_adds.Tables[0].Rows[r][1].ToString());
                        returnQuery("DELETE FROM add_verification WHERE addID = " + verified_adds.Tables[0].Rows[r][0].ToString());

                        SteamID userID = new SteamID();
                        userID.SetFromUInt64(ulong.Parse(verified_adds.Tables[0].Rows[r][6].ToString()));
                        Bot.SteamFriends.SendChatMessage(userID, EChatEntryType.ChatMsg, verified_adds.Tables[0].Rows[r][2].ToString() + " DOGE was successfully added to your tipping balance.");
                        BotManager.mainLog.Success("Registered user successfully added " + verified_adds.Tables[0].Rows[r][2].ToString() + " DOGE to their balance.");
                    }
                }
                Thread.Sleep(30000);
            }
        }
Exemplo n.º 2
0
        private void bgwInit_DoWork(object sender, DoWorkEventArgs e)
        {
            UserAccessLevel accessLvl = UserAccessLevel.None;
            DataRow dtrRow = (DataRow)e.Argument;

            switch ((string)dtrRow["role"])
            {
                case "Admin":
                    accessLvl = UserAccessLevel.Admin;
                    break;
                case "Instructor":
                    accessLvl = UserAccessLevel.Instructor;
                    break;
                case "Counter Staff":
                    accessLvl = UserAccessLevel.CounterStaff;
                    break;
                case "Owner":
                    accessLvl = UserAccessLevel.Owner;
                    break;
                default:
                    MessageBox.Show(this, "Database error.\n Unexpected value in Staff.Role. Notify an administrator.",
                                        "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    Application.Exit();
                    break;
            }
            contentForm = new frmMain(programDatabase, new User((string)dtrRow["name"], (string)dtrRow["username"], (string)dtrRow["password"], accessLvl));
        }
Exemplo n.º 3
0
 public static void CtorTest(object expectedArgument)
 {
     var target = new DoWorkEventArgs(expectedArgument);
     Assert.Equal(expectedArgument, target.Argument);
     Assert.False(target.Cancel);
     Assert.Null(target.Result);
 }
Exemplo n.º 4
0
    private void RTBackground_DoWork(object sender, DoWorkEventArgs e)
    {
        try
        {
            ProcessStartInfo RTStartInfo = new ProcessStartInfo();
            if (Environment.OSVersion.Platform == PlatformID.Win32NT) { RTStartInfo = new ProcessStartInfo("\"" + MySettings.ProgramPath + "\"", e.Argument.ToString()); }
            else if (Environment.OSVersion.Platform == PlatformID.Unix) { RTStartInfo = new ProcessStartInfo("rawtherapee", e.Argument.ToString()); }
            else if (Environment.OSVersion.Platform == PlatformID.MacOSX) { RTStartInfo = new ProcessStartInfo("rawtherapee", e.Argument.ToString()); }
            else { e.Result = InfoType.InvalidOS; return; }

            RTStartInfo.UseShellExecute = false;
            RTStartInfo.CreateNoWindow = true;

            RT.StartInfo = RTStartInfo;
            RT.Start();
            lastTime = DateTime.Now.Ticks;
            RT.WaitForExit();

            e.Result = InfoType.OK;
        }
        catch (Exception ex)
        {
            ThreadException = ex;
            e.Result = InfoType.Error;
        }
    }
Exemplo n.º 5
0
Arquivo: test.cs Projeto: mono/gert
	void bkgndWkr_DoWork (Object sender, DoWorkEventArgs e)
	{
		e.Result = 5566;
		e.Cancel = true;
		m_doWorkException = new RankException ("Rank exception manually created and thrown in _DoWork.");
		throw m_doWorkException;
	}
Exemplo n.º 6
0
        void bg_DoWork(object sender, DoWorkEventArgs e)
        {

            ObservableCollection<WirelessDevice> devices = new ObservableCollection<WirelessDevice>();
            WlanClient client = new WlanClient();
            foreach (WlanClient.WlanInterface wlanIface in client.Interfaces)
            {
                // Lists all networks in the vicinity

                Wlan.WlanAvailableNetwork[] networks = wlanIface.GetAvailableNetworkList(0);
                foreach (Wlan.WlanAvailableNetwork network in networks)
                {

                    string ssid = GetStringForSSID(network.dot11Ssid);
                    string msg = "Found network with SSID " + ssid;
                    log.dispatchLogMessage(msg);
                    msg = "Signal: " + network.wlanSignalQuality;
                    log.dispatchLogMessage(msg);
                    msg = "BSS Type : " + network.dot11BssType;
                    log.dispatchLogMessage(msg);
                    msg = "Profile Name : " + network.profileName;
                    log.dispatchLogMessage(msg);
                    log.dispatchLogMessage("");

                    WirelessDevice d = new WirelessDevice(ssid, network.wlanSignalQuality);
                    devices.Add(d);
                }
            }
            _unsecuredDevices = devices;
            e.Result = _unsecuredDevices;
        }
    /// <summary>
    /// This runs in a different thread and outputs to the javascript log.
    /// </summary>
    /// <param name='sender'>
    /// Sender.
    /// </param>
    /// <param name='e'>
    /// E.
    /// </param>
    void HandleWorkerDoWork(object sender, DoWorkEventArgs e)
    {
        JavascriptLogger jsLogger = new JavascriptLogger("Threaded Logger");

        while(true)
        {
            jsLogger.LogInfo("Ping " + DateTime.Now);
            Thread.Sleep(3000);
        }
    }
Exemplo n.º 8
0
 void bw_DoWork(object sender, DoWorkEventArgs e)
 {
     try
     {
         Start();
     }
     catch (Exception ex)
     {
         WriteError(ex.Message);
     }
 }
 void bwExport_DoWork(object sender, DoWorkEventArgs e)
 {
     try
     {
         mb.ExportToFile(Program.TargetFile);
     }
     catch (Exception ex)
     {
         CloseConnection();
         MessageBox.Show(ex.ToString());
     }
 }
Exemplo n.º 10
0
    static void worker_DoWork(object sender, DoWorkEventArgs e)
    {
        Console.WriteLine("Starting to do some work now...");
        int i;
        for (i = 1; i < 10; i++)
        {
            Thread.Sleep(1000);
            worker.ReportProgress(Convert.ToInt32((100.0 * i) / 10));
        }

        e.Result = i;
    }
Exemplo n.º 11
0
    private void backgroundWorker1_DoWork(
        object sender,
        DoWorkEventArgs e)
    {
        document = new XmlDocument();

        // Uncomment the following line to
        // simulate a noticeable latency.
        //Thread.Sleep(5000);

        // Replace this file name with a valid file name.
        document.Load(@"http://www.tailspintoys.com/sample.xml");
    }
Exemplo n.º 12
0
        private void bgwAuditLogs_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                string[] arg = e.Argument.ToString().Split('|');

                AccessTypes AccessType = (AccessTypes)Enum.Parse(typeof(AccessTypes), arg[0]);
                string Remarks = arg[1];
                
                Methods.InsertAuditLog(mclsTerminalDetails, mCashierName, AccessType, Remarks);
            }
            catch{ }
        }
Exemplo n.º 13
0
        private void bgwTurret_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                string[] arg = e.Argument.ToString().Split('|');

                string szString = arg[0].ToString();
                string strTransactionNo = arg[1].ToString();

                RawPrinterHelper.SendStringToPrinter(mclsTerminalDetails.TurretName, "\f" + szString, "RetailPlus Turret Disp: " + strTransactionNo);
            }
            catch { }
        }
Exemplo n.º 14
0
            private void DoWork(object sender, DoWorkEventArgs e)
            {
                ExternalApp app = new ExternalApp();
                Options opts = sender as Options;

                app.Options = sender as Options;

                if (!app.Run())
                {
                   //MessageBox.Show("HDFExporter tool has failed.", "ATTENTION", MessageBoxButtons.OK, MessageBoxIcon.Error);
                   return;
                }
            }
Exemplo n.º 15
0
 void bgwPrintInvoice_DoWork(object sender, DoWorkEventArgs e)
 {
     //Print Invoice for Currently selected record
     try
     {
         PrintDocument pd = (PrintDocument)e.Argument;
         pd.PrintPage += new PrintPageEventHandler(PrintPage);
         pd.Print();
         ((BackgroundWorker)sender).ReportProgress(100, "Print Completed");
     }
     catch (Exception ae)
     {
         ((BackgroundWorker)sender).ReportProgress(0, "Error");
         MessageBox.Show(ae.Message,"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
     }
 }
Exemplo n.º 16
0
        public static void HandleMailing(Object sender, DoWorkEventArgs e)
        {
            if (EventLog.SourceExists("Billing Mailer"))
                EventLog.WriteEntry("Billing Mailer", "Iniciando fatura de contratos");

            try
            {
                // Processa a lista de envio (mailing) cadastrada no sistema
                ProcessMailingList();
            }
            catch (Exception exc)
            {
                if (EventLog.SourceExists("Billing Mailer"))
                    EventLog.WriteEntry("Billing Mailer", "Exceção encontrada -> " + Environment.NewLine + exc.Message + Environment.NewLine + exc.StackTrace);
            }
        }
Exemplo n.º 17
0
        private void bgwDrawer_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                clsEvent.AddEventLn("Opening cash drawer...", true);

                //Chr$(&H1B) + Chr$(&H70) + Chr$(&H0) + Chr$(&H2F) + Chr$(&H3F) '//drawer open
                //				string command = Convert.ToChar("&H1B").ToString() + Convert.ToChar("&H70").ToString() + Convert.ToChar("&H0").ToString() + Convert.ToChar("&H2F").ToString() + Convert.ToChar("&H3F").ToString();   // cut the paper  Chr$(86)
                string command = Convert.ToChar(27).ToString() + Convert.ToChar(112).ToString() + Convert.ToChar(0).ToString() + Convert.ToChar(47).ToString() + Convert.ToChar(63).ToString();   // cut the paper  Chr$(86)
                RawPrinterHelper.SendStringToPrinter(mclsTerminalDetails.CashDrawerName, command + "\f", "RetailPlus Drawer.");

                // InsertAuditLog(AccessTypes.OpenDrawer, "Open cash drawer." + " @ Branch: " + mclsTerminalDetails.BranchDetails.BranchCode);
                clsEvent.AddEventLn("Done opening cash drawer!", true);
            }
            catch { }
        }
Exemplo n.º 18
0
 void bgwPrintList_DoWork(object sender, DoWorkEventArgs e)
 {
     PrintDocument pd = (PrintDocument)e.Argument;
     //Print list of selected records
     try
     {
         Control.CheckForIllegalCrossThreadCalls = false;
         pd.PrintPage += new PrintPageEventHandler(PrintList);
         pd.Print();
         ((BackgroundWorker)sender).ReportProgress(100, "Print Completed");
         Control.CheckForIllegalCrossThreadCalls = true;
     }
     catch (Exception ae)
     {
         ((BackgroundWorker)sender).ReportProgress(0, ae.Message);
     }
 }
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                switch (origen)
                {
                    case "frmGetDatosCliente1":
                        //   BL.TrendBLL.GrabarDB(dataset);
                        // crear base de datos
                            string path = Application.StartupPath;
                            using (StreamWriter fileWrite = new StreamWriter(path + "\\Backup\\temp.sql"))
                            {
                                using (StreamReader fielRead = new StreamReader(path + "\\Backup\\db_base.sql"))
                                {
                                    String line;

                                    while ((line = fielRead.ReadLine()) != null)
                                    {
                                        if (line.Contains("db_base"))
                                        {
                                            string newLine = line.Replace("db_base", correo);
                                            fileWrite.WriteLine(newLine);
                                        }
                                        else
                                            fileWrite.WriteLine(line);
                                    }
                                }
                            }
                        break;
                }
            }
            catch (MySqlException ex)
            {
                codigoError = ex.Number;
            }
            catch (TimeoutException)
            {
                codigoError = 8888;
            }
            catch (Exception)
            {
                codigoError = 9999;
            }
        }
Exemplo n.º 20
0
    private void bw_DoWork(object sender, DoWorkEventArgs e)
    {
        BackgroundWorker worker = sender as BackgroundWorker;

        for (int i = 1; (i <= 10); i++)
        {
            if ((worker.CancellationPending == true))
            {
                e.Cancel = true;
                break;
            }
            else
            {
                // Perform a time consuming operation and report progress.
                System.Threading.Thread.Sleep(500);
                worker.ReportProgress((i * 10));
            }
        }
    }
Exemplo n.º 21
0
        void bw3_DoWork(object sender, DoWorkEventArgs e)
        {
            DateTime viewdate = currentLogDate.Value;
            try
            {
                //get invoices for current day
                MySQL MySQLHandle = new MySQL(GlobalVar.sqlhost, GlobalVar.sqlport, GlobalVar.sqldatabase, GlobalVar.sqlusername, "");
                MySqlConnection sqlReader = MySQLHandle.Connect();
                string selectquery = "SELECT `invoice` FROM shipping_log WHERE `date_delivered` LIKE '" + currentLogDate.Value.ToString("yyyy-MM-dd") + "';";
                MySqlDataReader dataReader = MySQLHandle.Select(selectquery, sqlReader);
                List<int> invoices = new List<int>();
                for (int i = 0; dataReader.Read(); i++)
                {

                    invoices.Add(dataReader.GetInt32(0));
                }
                dataReader.Close();
                sqlReader.Close();
                rrsdatareader = new RRSDataReader(GlobalVar.sqlsettings.RRSHeaderFile, GlobalVar.sqlsettings.RRSLinesFile);
                rrsdatareader.ReadInvoices(viewdate);

                List<Invoice> filteredinvoices = rrsdatareader.FilterInvoices(viewdate, invoices);

                //List<LineItem> filteredlineitems = rrsdatareader.FilterLineItems(filteredinvoices);
                List<Invoice> newfilteredinvoices = new List<Invoice>(filteredinvoices);
                mysql_invoices = new MySQL_Invoices(GlobalVar.sqlhost, GlobalVar.sqlport, GlobalVar.sqldatabase, GlobalVar.sqlusername, "");
                newfilteredinvoices = mysql_invoices.AddInvoices(newfilteredinvoices, false);
                mysql_invoices.UpdateInvoices(filteredinvoices, viewdate, true);
                dataReader.Close();
                sqlReader.Close();
                MySQLHandle.Disconnect();
                for (int i = 0; i < newfilteredinvoices.Count; i++)
                {
                    MySqlConnection sqlWriter = MySQLHandle.Connect();
                    String updatecmd = "UPDATE `shipping_log` SET customer_name='" + newfilteredinvoices[i].customername + "' WHERE `invoice`=" + newfilteredinvoices[i].number + ";";
                    MySQLHandle.Update(updatecmd, sqlWriter);
                    MySQLHandle.Disconnect();
                }
            }
            catch { }
        }
        private void WorkerThreadStart(AsyncOperation asyncOp, object userState, object argument)
        {
            Exception error = null;
            bool cancelled = false;
            DoWorkEventArgs e = new DoWorkEventArgs(userState, argument);

            try
            {
                this.OnDoWork(e);
                if (e.Cancel) cancelled = true;
            }
            catch (Exception ex)
            {
                error = ex;
            }

            lock (userStateToLifetime.SyncRoot)
            {
                userStateToLifetime.Remove(asyncOp.UserSuppliedState);
            }

            WorkerCompletedEventArgs arg = new WorkerCompletedEventArgs(error, cancelled, asyncOp.UserSuppliedState, argument);
            asyncOp.PostOperationCompleted(this.SendOrPostWorkerCompleted, arg);
        }
Exemplo n.º 23
0
 private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
 {
     for (; ; )
     {
         if (backgroundWorker1.CancellationPending == true)
         {
             e.Cancel = true;
             break;
         }
         else
         {
             try
             {
                 backgroundWorker1.ReportProgress(0);
                 System.Threading.Thread.Sleep(100);
             }
             catch (Exception)
             {
                 e.Cancel = true;
                 break;
             }
         }
     }
 }
Exemplo n.º 24
0
 private void IsUpdateAvailableBackground(object sender, DoWorkEventArgs e)
 {
     e.Result = IsUpdateAvailable();
 }
 void m_BackgroundWorker_ANOVA(object sender, DoWorkEventArgs e)
 {
     e.Result = DoAnova((string)e.Argument);
 }
 void m_BackgroundWorker_ShapiroWilks(object sender, DoWorkEventArgs e)
 {
     e.Result = DoShapiroWilkstest((string)e.Argument);
 }
Exemplo n.º 27
0
        private void d_bw_komunikacja_DoWork(object sender, DoWorkEventArgs e)
        {
            BinaryReader czytanie     = new BinaryReader(ns);
            ustawienia   konfiguracja = new ustawienia();

            while (true)
            {
                try
                {
                    komunikat = kk.ConvertOutXML(czytanie.ReadString());
                }
                catch (IOException)
                {
                    return;
                }
                switch (komunikat.komenda)
                {
                case "LISTUSERS":
                    kk.ClearText(d_lb_uzytkownicy);
                    string[] user = komunikat.tresc.Split(new char[] { ':' });
                    for (int i = 0; i < user.Length - 1; i++)
                    {
                        if (login != user[i].Split(';')[1])
                        {
                            kk.SetText(d_lb_uzytkownicy, user[i].Split(';')[0]);
                        }
                        else
                        {
                            this.Invoke((MethodInvoker) delegate()
                            {
                                this.Text = "IM - " + user[i].Split(';')[0];
                            });
                        }
                    }
                    break;

                case "PING":
                    ping = DateTime.Now;
                    break;

                case "SAY":
                    kk.newMessage(this, komunikat);
                    break;

                case "ERROR":
                    kk.newMessage(this, komunikat);
                    this.Invoke((MethodInvoker) delegate()
                    {
                        okna[komunikat.nadawca].f_tb_wiadomosc.Enabled = false;
                        okna[komunikat.nadawca].f_b_wyslij.Enabled     = false;
                    });
                    break;

                case "PASSANS":
                    kk.SetText(d_lb_komunikaty, komunikat.tresc);
                    break;

                case "FILE":
                    kk.newMessage(this, komunikat, "IM", "Użytkownik przesyła plik: <b>" + komunikat.tresc.Split(';')[0] + "</b> o rozmiarze: <b>" + long.Parse(komunikat.tresc.Split(';')[1]) / 1024 + " Kb </b>");
                    plik    = komunikat.tresc.Split(';')[0];
                    rozmiar = long.Parse(komunikat.tresc.Split(';')[1]);
                    this.Invoke((MethodInvoker) delegate()
                    {
                        okna[komunikat.nadawca].d_l_odbierz.Enabled = true;
                        okna[komunikat.nadawca].d_ll_tak.Enabled    = true;
                        okna[komunikat.nadawca].d_ll_nie.Enabled    = true;
                    });
                    break;

                case "FILEYES":
                    kk.newMessage(this, komunikat, "IM", "Użytkownik potwierdził odbiór pliku: <b>" + komunikat.tresc.Split(';')[0] + "</b>");
                    rozmiar = okna[komunikat.nadawca].infoFile.Length;
                    this.Invoke((MethodInvoker) delegate()
                    {
                        d_f_postepPobierania oknoWysylanie = new d_f_postepPobierania(this, komunikat, okna[komunikat.nadawca].infoFile.Name);
                        oknoWysylanie.Parent = okna[komunikat.nadawca].Parent;
                        oknoWysylanie.Show();
                    });
                    break;

                case "FILENO":
                    kk.newMessage(this, komunikat, "IM", "Użytkownik odrzucił transfer pliku: <b>" + plik + "</b>");
                    break;
                }
            }
        }
Exemplo n.º 28
0
        private void WorkerSearch_DoWork(object sender, DoWorkEventArgs e)
        {
            this.Dispatcher.Invoke(() =>
            {
                switch (this.currentMode)
                {
                case 1:
                    if (tbSearch.Text == "")
                    {
                        lstFilterCard = Repository.lstAllCards;
                    }
                    else
                    {
                        lstFilterCard = Repository.lstAllCards.Where(c => (c.CardNumber == tbSearch.Text) || (c.CardSerial.Contains(tbSearch.Text))).ToList();
                    }
                    break;

                case 2:
                    if (tbSearch.Text == "")
                    {
                        lstFilterCardHolder = Repository.lstAllCardHolders;
                    }
                    else
                    {
                        lstFilterCardHolder = Repository.lstAllCardHolders.Where(c => (c.Name.ToLower().Contains(tbSearch.Text.ToLower())) || (c.PhoneNumber == tbSearch.Text)).ToList();
                    }
                    break;

                case 3:
                    if (tbSearch.Text == "")
                    {
                        lstFilterDevice = Repository.lstAllDevices;
                    }
                    else
                    {
                        lstFilterDevice = Repository.lstAllDevices.Where(c => (c.Name.ToLower().Contains(tbSearch.Text.ToLower())) || (c.IP == tbSearch.Text)).ToList();
                    }
                    break;

                case 4:
                    if (tbSearch.Text == "")
                    {
                        lstFilterDoor = Repository.lstAllDoor;
                    }
                    else
                    {
                        lstFilterDoor = Repository.lstAllDoor.Where(c => (c.Name.ToLower().Contains(tbSearch.Text.ToLower()))).ToList();
                    }
                    break;

                case 5:
                    if (tbSearch.Text == "")
                    {
                        lstFilterSchedule = Repository.lstAllSchedules;
                    }
                    else
                    {
                        lstFilterSchedule = Repository.lstAllSchedules.Where(c => (c.Name.ToLower().Contains(tbSearch.Text.ToLower()))).ToList();
                    }
                    break;

                case 6:
                    if (tbSearch.Text == "")
                    {
                        lstFilterRight = Repository.lstAllRIght;
                    }
                    else
                    {
                        lstFilterRight = Repository.lstAllRIght.Where(c => (c.Name.ToLower().Contains(tbSearch.Text.ToLower()))).ToList();
                    }
                    break;

                case 8:
                    if (tbSearch.Text == "")
                    {
                        lstFilterDepartment = Repository.lstAllDepartment;
                    }
                    else
                    {
                        lstFilterDepartment = Repository.lstAllDepartment.Where(c => (c.Name.ToLower().Contains(tbSearch.Text.ToLower()))).ToList();
                    }
                    break;
                }
            });
        }
Exemplo n.º 29
0
        void downloadFileFtp(object sender, DoWorkEventArgs doWorkEventArgs)
        {
            String[] _downloadFIles = label1.Text.Split('^');

            ftpFileDownloadProcess(textBox1.Text, _downloadFIles);
        }
Exemplo n.º 30
0
    private void worker_DoWork(object sender, DoWorkEventArgs e)
    {
      MySqlCommand cmd = new MySqlCommand("", _connection);
      try
      {
        // long command timeout so it spans the full debug session time.
        cmd.CommandTimeout = Int32.MaxValue / 1000;

        // net_xxx are set to avoid EndOfStreamException
        cmd.CommandText = "set net_write_timeout=999998;";
        cmd.ExecuteNonQuery();
        cmd.CommandText = "set net_read_timeout=999998;";
        cmd.ExecuteNonQuery();
        cmd.CommandText = "set session transaction isolation level read uncommitted;";
        cmd.ExecuteNonQuery();
        cmd.CommandText = string.Format( "set {0} = last_insert_id();", VAR_DBG_LAST_INSERT_ID);
        cmd.ExecuteNonQuery();
        cmd.CommandText = string.Format("set {0} = found_rows();", VAR_DBG_FOUND_ROWS);
        cmd.ExecuteNonQuery();
        cmd.CommandText = string.Format("set {0} = row_count();", VAR_DBG_ROW_COUNT);
        cmd.ExecuteNonQuery();
        SetNoDebuggingFlag(0, _connection);
        //cmd.CommandText = string.Format("set {0} = 0;", VAR_DBG_SCOPE_LEVEL);
        //cmd.ExecuteNonQuery();

        // run the command
        cmd.CommandText = _sqlToRun;
        cmd.ExecuteNonQuery();
      }
      catch (ThreadAbortException tae) 
      {
        // nothing
      }
      catch (Exception ex)
      {
        if (!_stopping)
        {
          _asyncError = ex;
          _errorOnAsync = true;
        }
      }
      finally
      {
        // Release debuggee lock
        if (!_completed && !_stopping)
        {
          cmd.CommandText = string.Format("set @@global.net_write_timeout = {0};", NET_WRITE_TIMEOUT_BASE_VALUE);
          cmd.ExecuteNonQuery();
          ReleaseDebuggeeLock();
        }
        _completed = true;
      }
    }
Exemplo n.º 31
0
 private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
 {
 }
Exemplo n.º 32
0
        void bgw_DoWork_LocalBlast(object sender, DoWorkEventArgs e)
        {
            //This c# event (function) performs the blast functions from NCBI executeables.
            //It is ran in the background to remove interference with the form

            //Background worker - C# object that runs a function on a separate thread and notifies when ready
            var backgroundWorker = (BackgroundWorker)sender;

            //Gathers all the necessary stringd containing paths
            var filePath = Program.LocalSequenceFilePath;// this.textBoxLBDFP.Text;
            var databasePath = Program.LocalDatabaseDirectory;// this.textBoxLBDWD.Text;
            var exePath = Program.NCBIExecutablesDirectory;// this.textBoxLBEXED.Text;

            //Program.LocalSequenceFilePath = fp;
            //Program. = dbp;
            //Program.NCBIExecutablesDirectory = exp;
            //makeblastdb -in NveProt.fas -dbtype 'prot' -out NveProt -name -NveProt

            //Name for local db
            var outFilePath = databasePath + @"~tempLocalBlastDB";

            //Check for part of db, if exists, remove to force new db creation
            if (File.Exists(outFilePath + ".pin"))
                File.Delete(outFilePath + ".pin");

            //Create new Database through c# command line simulator/wrapper. Wait for completion
            this.AppConsole.CLF.RunCommandLine("makeblastdb -in " + filePath + " -dbtype prot -out " + outFilePath, exePath);
            this._loadingForm.SetProgressPercent(.1);

            if (backgroundWorker.CancellationPending)
                return;
            //Thread.Sleep(500);

            //Get blast fasta sequence from textbox
            /*
            var fasta = "";
            var i = 1;
            if (this.textBoxBlastSeq.Lines[0].Contains('>'))
                fasta = this.textBoxBlastSeq.Lines[0];
            else
                i = 0;
            var seq = "";
            for (i = i; i < this.textBoxBlastSeq.Lines.Length; i++)
            {
                if (this._loadingForm != null)
                    this._loadingForm.SetProgressPercent(.1 + .1 * (i / this.textBoxBlastSeq.Lines.Length));
                seq += this.textBoxBlastSeq.Lines[i];
            }*/

            var fastas = new List<string>();
            var seqs = new List<string>();

            for (int j = 0; j < this.textBoxBlastSeq.Lines.Length; j++)
            {
                var l = this.textBoxBlastSeq.Lines[j];
                if (l.Contains(">"))
                {
                    fastas.Add(l);
                    seqs.Add("");
                }
                else
                    seqs[seqs.Count - 1] += l;

                if (this._loadingForm != null)
                    this._loadingForm.SetProgressPercent(.1 + .1 * (j / this.textBoxBlastSeq.Lines.Length));
            }

            //Verify sequence existd
            if (fastas.Count == 0 || seqs.Count == 0 || fastas.Count != seqs.Count)
                return;

            //Create txt file of blast query
            var outQueryFilePath = databasePath + @"~tempBlastQuery.txt";

            //Get blast type from form
            var t = "";
            if (this.proteinBlastToolStripMenuItem.Checked)
                t = "blastp";
            if (this.nucleotideBlastToolStripMenuItem.Checked)
                t = "blastn";
            if (t == "")
            {
                MessageBox.Show("Invalid blast type.", this.TitleText + " - Error");
                return;
            }

            //Code that checks and waits for the database creation
            var dt = DateTime.Now;
            while ((from x in Directory.GetFiles(databasePath)
                    where x.Contains(outFilePath + ".pin")
                    select x).ToArray<string>().Length == 0)
            {
                if (DateTime.Now.Subtract(dt).TotalSeconds > AppForm.Timeout)
                    return;

                continue;
            }

            for (int i = 0; i < fastas.Count; i++)
            {//////////////
                this._loadingForm.SetProgressPercent(.2);
                //Management.WriteTextToFile(outQueryFilePath, new string[] { fasta, seq }, false);
                Management.WriteTextToFile(outQueryFilePath, new string[] { fastas[i], seqs[i] }, false);
                if (this._loadingForm != null)
                    this._loadingForm.SetProgressPercent(.3);

                //blastn –query text_query.txt –db refseq_rna.00 –out output.txt
                //blastp -db C:\Ryan\ProteinProj\ProjectFiles\~tempLocalBlastDB -query C:\Ryan\ProteinProj\ProjectFiles\tempLocalBlastQuery.txt -out C:\Ryan\ProteinProj\ProjectFiles\~tempLocalBlast.txt
                //  blastp
                //  -db C:\Ryan\ProteinProj\ProjectFiles\~tempLocalBlastDB
                //  -query C:\Ryan\ProteinProj\ProjectFiles\tempLocalBlastQuery.txt
                //  -out C:\Ryan\ProteinProj\ProjectFiles\~tempLocalBlast.txt
                var outBlastFilePath = databasePath + @"~tempBlast.txt";
                //Program.CLF.RunCommandLine(r, NCBIExs);

                if (backgroundWorker.CancellationPending)
                    return;

                if (this._loadingForm != null)
                    this._loadingForm.SetProgressPercent(.5);
                //Thread.Sleep(500);
                if (this._loadingForm != null)
                    this._loadingForm.SetProgressPercent(.7);

                //Run Command line wrapper to perform blast
                this.AppConsole.CLF.RunCommandLine(t +
                    @" -db " + outFilePath + //"C:\Ryan\ProteinProj\ProjectFiles\~tempLocalBlastDB " +
                    @" -query " + outQueryFilePath + //" C:\Ryan\ProteinProj\ProjectFiles\tempLocalBlastQuery.txt " +
                    @" -out " + outBlastFilePath, exePath); //C:\Ryan\ProteinProj\ProjectFiles\~tempLocalBlast.txt", NCBIExs);

                if (this._loadingForm != null)
                    this._loadingForm.SetProgressPercent(.9);
                dt = DateTime.Now;

                //Wait for blast output text file to be created
                while (!File.Exists(outBlastFilePath))
                {
                    if (DateTime.Now.Subtract(dt).TotalSeconds > AppForm.Timeout)
                        return;

                    continue;
                }

                //Leave adequete time (2 secs roughly) for command line to complete and close
                Thread.Sleep(2000);
                if (this._loadingForm != null)
                    this._loadingForm.SetProgressPercent(1);

                //Do Arcog/Multi-Fasta
                if (this.AssignArcogs)
                {
                    if (fastas.Count > 1)
                        this.AssignArcog(fastas[i], Management.GetTextFromFile(outBlastFilePath), true);
                    else
                        this.AssignArcog(fastas[i], Management.GetTextFromFile(outBlastFilePath), false);
                }

            }/////////////

            return;
        }
Exemplo n.º 33
0
    static void ScriptWorker_DoWork(object sender, DoWorkEventArgs e)
    {
        //argument is WorkerData
        WorkerData d = (WorkerData)e.Argument;
        List<int> handled = new List<int>();
        List<byte> outfile = new List<byte>();
        for (int c = 0; c < d.indata.Length; c++)
        {
            if (!(handled.Contains(c)))
            {
                int maxlen = 10;
                if ((d.indata.Length - c) < 10)
                {
                    maxlen = (d.indata.Length - c);
                }

                string[] sc = new string[maxlen];
                for (int p = 0; p < maxlen; p++) //look up to 10 characters ahead
                {
                    if (p > 0)
                    {
                        sc[p] = sc[p - 1];
                    }
                    sc[p] += d.indata[c + p].ToString();
                }

                bool found = false;
                //now check from longest to shortest for a match...
                for (int p = (maxlen - 1); p > -1; p--)
                {
                    if (!found && d.rt.CharMap.ContainsKey(sc[p]))
                    {
                        found = true;
                        for (int b = 0; b < d.rt.CharMap[sc[p]].HexValue.Length; b += 2)
                        {
                            string val = d.rt.CharMap[sc[p]].HexValue.Substring(b, 2);
                            outfile.Add(byte.Parse(val, NumberStyles.HexNumber));
                        }
                    }
                    if (found)
                    {
                        handled.Add(c + p);
                    }
                }

                if (!found)
                {//didn't find a matching value for this character??
                    //write a default byte? experimental...
                    string display = "";
                    for (int h = 0; h < sc.Length; h++)
                    {
                        display += sc[h];
                    }
                    Console.WriteLine("Character match not found in table! (" + display + ")");
                    outfile.Add(0x20);
                    handled.Add(c);
                }
            }
        }
        d.outfile = outfile.ToArray();
        e.Result = d;
    }
Exemplo n.º 34
0
        private void MFTScannerWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                var usnRecord    = default(USN_RECORD);
                var mft          = default(MFT_ENUM_DATA);
                var dwRetBytes   = 0;
                var cb           = 0;
                var dicFRNLookup = new Dictionary <long, FSNode>();
                var bIsFile      = false;

                // This shouldn't be called more than once.
                if (m_Buffer.ToInt32() != 0)
                {
                    throw new Exception("invalid buffer");
                }

                // Assign buffer size
                m_BufferSize = 65536;
                //64KB

                // Allocate a buffer to use for reading records.
                m_Buffer = Marshal.AllocHGlobal(m_BufferSize);

                // correct path
                path = path.TrimEnd('\\');

                // Open the volume handle
                m_hCJ = OpenVolume(path);

                // Check if the volume handle is valid.
                if (m_hCJ == INVALID_HANDLE_VALUE)
                {
                    string errorMsg = "Couldn't open handle to the volume.";
                    if (!PermissionHelper.IsAdministrator())
                    {
                        errorMsg += "Current user is not administrator";
                    }

                    throw new Exception(errorMsg);
                }
                mft.StartFileReferenceNumber = 0;
                mft.LowUsn  = 0;
                mft.HighUsn = long.MaxValue;
                string    fileName = "";
                Stopwatch sw       = new Stopwatch();
                sw.Start();
                do
                {
                    if (DeviceIoControl(m_hCJ, FSCTL_ENUM_USN_DATA, ref mft, Marshal.SizeOf(mft), m_Buffer, m_BufferSize, ref dwRetBytes, IntPtr.Zero))
                    {
                        cb = dwRetBytes;
                        // Pointer to the first record
                        IntPtr pUsnRecord = Environment.Is64BitOperatingSystem ? new IntPtr(m_Buffer.ToInt64() + 8) : new IntPtr(m_Buffer.ToInt32() + 8);

                        FSNode fs = null;
                        while ((dwRetBytes > 8) && !e.Cancel)
                        {
                            // Copy pointer to USN_RECORD structure.
                            usnRecord = (USN_RECORD)Marshal.PtrToStructure(pUsnRecord, usnRecord.GetType());
                            long intPUsnRecord = Environment.Is64BitOperatingSystem ? pUsnRecord.ToInt64() : pUsnRecord.ToInt32();
                            // The filename within the USN_RECORD.
                            fileName = Marshal.PtrToStringUni(new IntPtr(intPUsnRecord + usnRecord.FileNameOffset), usnRecord.FileNameLength / 2);
                            bIsFile  = !usnRecord.FileAttributes.HasFlag(FileAttributes.Directory);
                            //ReportProgress((int)(usnRecord.RecordLength / (double)dwRetBytes) * 100, FileName);
                            fs = new FSNode(usnRecord.FileReferenceNumber, usnRecord.ParentFileReferenceNumber, fileName, bIsFile);
                            dicFRNLookup.Add(usnRecord.FileReferenceNumber, fs);
                            pUsnRecord  = new IntPtr(intPUsnRecord + usnRecord.RecordLength);
                            dwRetBytes -= usnRecord.RecordLength;
                        }
                        mft.StartFileReferenceNumber = Marshal.ReadInt64(m_Buffer, 0);
                        if (sw.ElapsedMilliseconds > 100)
                        {
                            string sFullPath     = "";
                            FSNode oParentFSNode = fs;
                            while (dicFRNLookup.TryGetValue(oParentFSNode.ParentFRN, out oParentFSNode))
                            {
                                sFullPath = string.Concat(oParentFSNode.FileName, @"\", sFullPath);
                            }
                            sFullPath = string.Concat(path, @"\", sFullPath);
                            ReportProgress(0, sFullPath);
                            sw.Restart();
                        }
                    }
                    else
                    {
                        break;
                    }
                } while (!(cb <= 8) && !e.Cancel);
                List <string> result = new List <string>();
                foreach (FSNode oFSNode in dicFRNLookup.Values.Where(o => (o.IsFile && o.FileName.Contains(keyWord))))
                {
                    string sFullPath     = oFSNode.FileName;
                    FSNode oParentFSNode = oFSNode;

                    while (dicFRNLookup.TryGetValue(oParentFSNode.ParentFRN, out oParentFSNode))
                    {
                        sFullPath = string.Concat(oParentFSNode.FileName, @"\", sFullPath);
                    }
                    sFullPath = string.Concat(path, @"\", sFullPath);

                    result.Add(sFullPath);
                }
                e.Result = result;
            }
            finally
            {
                Cleanup();
            }
        }
 private void worker_DoWork(object sender, DoWorkEventArgs e)
 {
     temp_loadtime_Categorylst = CategoryServices.GetAllCategory(0);
 }
Exemplo n.º 36
0
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                btn_index_delete.Invoke((MethodInvoker) delegate { btn_index_delete.Enabled = false; });
                btn_update.Invoke((MethodInvoker) delegate { btn_update.Enabled = false; });

                var files = Directory.GetFiles(_rootPath, "*.pdf", SearchOption.AllDirectories);

                progressBar1.Invoke((MethodInvoker) delegate
                {
                    progressBar1.Maximum = 5;
                    progressBar1.Minimum = 0;
                    progressBar1.Value   = 1;
                    Console.WriteLine($"1 / 5 = Read {files.Length} files");
                });

                var scraper = new TextSharpPdfScraper {
                    Strategy = TextSharpPdfScraper.TextSharpPdfScraperStrategy.Location
                };
                scraper.Input.Enqueue(files);
                scraper.Execute();

                progressBar1.Invoke((MethodInvoker) delegate
                {
                    progressBar1.Maximum = 5;
                    progressBar1.Minimum = 0;
                    progressBar1.Value   = 2;
                    Console.WriteLine($"2 / 5 = Cleaning");
                });

                // no cleanup

                progressBar1.Invoke((MethodInvoker) delegate
                {
                    progressBar1.Maximum = 5;
                    progressBar1.Minimum = 0;
                    progressBar1.Value   = 3;
                    Console.WriteLine($"3 / 5 = Tagging");
                });

                var tagger = new RawTextTagger();
                tagger.Input = scraper.Output;
                tagger.Execute();
                var corpus = tagger.Output.First();
                corpus.Save(_corpusPath, false);
                _dict = corpus.DocumentMetadata.ToDictionary(x => x.Key, x => (string)x.Value["Datei"]);
                Serializer.Serialize(_dict, "corpus/data.bin", false);

                progressBar1.Invoke((MethodInvoker) delegate
                {
                    progressBar1.Maximum = 5;
                    progressBar1.Minimum = 0;
                    progressBar1.Value   = 4;
                    Console.WriteLine($"4 / 5 = Build QuickIndex");
                });

                _quickIndex = new QuickIndex(_corpusPath);

                btn_index_delete.Invoke((MethodInvoker) delegate { btn_index_delete.Enabled = true; });
                btn_update.Invoke((MethodInvoker) delegate { btn_index_delete.Enabled = true; });

                progressBar1.Invoke((MethodInvoker) delegate
                {
                    progressBar1.Maximum = 5;
                    progressBar1.Minimum = 0;
                    progressBar1.Value   = 4;
                    Console.WriteLine($"5 / 5 = COMPLETE!");
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine("########--------########");
                Console.WriteLine(ex.Message);
                Console.WriteLine("--------########--------");
                Console.WriteLine(ex.StackTrace);
                Console.WriteLine("########--------########");
                Console.WriteLine();
            }
        }
Exemplo n.º 37
0
 private void worker_DoWork(object sender, DoWorkEventArgs e)
 {
     var printers = PrinterSettings.InstalledPrinters.Cast<string>().ToArray();
     comboBox1.Invoke((MethodInvoker)delegate { comboBox1.Items.AddRange(printers); });
     comboBox1.Invoke((MethodInvoker)delegate { comboBox1.Text = printDocument.PrinterSettings.PrinterName; });
 }
        private void Worker_DoWork_Download(object sender, DoWorkEventArgs e)
        {
            try
            {
                // background
                QuanTriHeThongProcess process          = new QuanTriHeThongProcess();
                ApplicationConstant.ResponseStatus ret = ApplicationConstant.ResponseStatus.KHONG_THANH_CONG;
                FileBase    fileResponse    = new FileBase();
                string      responseMessage = "";
                PhienBanDTO phienBanDTO     = new PhienBanDTO();
                ret       = process.DownloadClientVersion(ClientInformation.Version, LastestClientVersion, HtPban, ref phienBanDTO, ref responseMessage);
                ResStatus = ret;
                if (ret == ApplicationConstant.ResponseStatus.THANH_CONG)
                {
                    string phuongThucCapNhat = HtPban.PTHUC_CNHAT;
                    string maPhienBanTruoc   = HtPban.MA_PBAN_TRUOC;
                    // Nếu cập nhật toàn bộ ứng dụng
                    if (phuongThucCapNhat.Equals("FULL") ||
                        (phuongThucCapNhat.Equals("CHANGE") && !maPhienBanTruoc.Equals(ClientInformation.Version)))
                    {
                        LLogging.WriteLog(System.Reflection.MethodInfo.GetCurrentMethod().ToString(), LLogging.LogType.SYS, "FULL_UPDATE");
                        string tenFile    = phienBanDTO.ListPhienBanItemDTO.FirstOrDefault().HtPbanFile.TEN_FILE;
                        string folderPath = ClientInformation.OtaVersionDir + "\\" + HtPban.MA_PBAN;
                        string filePath   = ClientInformation.OtaVersionDir + "\\" + HtPban.MA_PBAN + "\\" + tenFile;
                        PathFile = filePath;

                        if (Directory.Exists(folderPath))
                        {
                            LLogging.WriteLog(System.Reflection.MethodInfo.GetCurrentMethod().ToString(), LLogging.LogType.SYS, "DeleteDirectory: " + folderPath);
                            Directory.Delete(folderPath, true);
                        }
                        LLogging.WriteLog(System.Reflection.MethodInfo.GetCurrentMethod().ToString(), LLogging.LogType.SYS, "CreateDirectory: " + folderPath);

                        try
                        {
                            DirectoryInfo dirInfo = Directory.CreateDirectory(folderPath);
                            LLogging.WriteLog(System.Reflection.MethodInfo.GetCurrentMethod().ToString(), LLogging.LogType.SYS, "CreateDirectory result: " + dirInfo.ToString());
                        }
                        catch (System.Exception ex)
                        {
                            LLogging.WriteLog(System.Reflection.MethodInfo.GetCurrentMethod().ToString(), LLogging.LogType.SYS, "CreateDirectory result failed: " + ex);
                            ResContent             = LLanguage.SearchResourceByKey("M.ResponseMessage.QuanTriHeThong.PhienBan.TaiVeKhongThanhCong");
                            lblContent.Content     = ResContent;
                            prbProcess.Visibility  = Visibility.Collapsed;
                            btnDownload.Visibility = Visibility.Collapsed;
                            btnUpdate.Visibility   = Visibility.Collapsed;
                        }
                        LLogging.WriteLog(System.Reflection.MethodInfo.GetCurrentMethod().ToString(), LLogging.LogType.SYS, "WriteFileFromByteArray: " + filePath);
                        bool retWriteFile = LFile.WriteFileFromByteArray(phienBanDTO.ListPhienBanItemDTO.FirstOrDefault().HtPbanData.FileData, filePath);
                        LLogging.WriteLog(System.Reflection.MethodInfo.GetCurrentMethod().ToString(), LLogging.LogType.SYS, "WriteFileFromByteArray result: " + retWriteFile.ToString());
                        if (!retWriteFile)
                        {
                            ResStatus  = ApplicationConstant.ResponseStatus.KHONG_THANH_CONG;
                            ResContent = LLanguage.SearchResourceByKey("M.ResponseMessage.QuanTriHeThong.PhienBan.TaiVeKhongThanhCong");
                            Worker_Download.CancelAsync();
                        }
                        HtPban.PTHUC_CNHAT = "FULL";
                    }
                    // Nếu cập nhật phần thay đổi của ứng dụng
                    else if (phuongThucCapNhat.Equals("CHANGE"))
                    {
                        LLogging.WriteLog(System.Reflection.MethodInfo.GetCurrentMethod().ToString(), LLogging.LogType.SYS, "CHANGED_UPDATE");
                        List <PhienBanItemDTO> listPhienBanItemDTO = phienBanDTO.ListPhienBanItemDTO.ToList();
                        string folderPath = ClientInformation.OtaVersionDir + "\\" + HtPban.MA_PBAN;
                        PathFile = folderPath;

                        if (Directory.Exists(folderPath))
                        {
                            LLogging.WriteLog(System.Reflection.MethodInfo.GetCurrentMethod().ToString(), LLogging.LogType.SYS, "DeleteDirectory: " + folderPath);
                            Directory.Delete(folderPath, true);
                        }
                        LLogging.WriteLog(System.Reflection.MethodInfo.GetCurrentMethod().ToString(), LLogging.LogType.SYS, "CreateDirectory: " + folderPath);

                        try
                        {
                            DirectoryInfo dirInfo = Directory.CreateDirectory(folderPath);
                            LLogging.WriteLog(System.Reflection.MethodInfo.GetCurrentMethod().ToString(), LLogging.LogType.SYS, "CreateDirectory result: " + dirInfo.ToString());
                        }
                        catch (System.Exception ex)
                        {
                            LLogging.WriteLog(System.Reflection.MethodInfo.GetCurrentMethod().ToString(), LLogging.LogType.SYS, "CreateDirectory result failed: " + ex);
                            ResContent             = LLanguage.SearchResourceByKey("M.ResponseMessage.QuanTriHeThong.PhienBan.TaiVeKhongThanhCong");
                            lblContent.Content     = ResContent;
                            prbProcess.Visibility  = Visibility.Collapsed;
                            btnDownload.Visibility = Visibility.Collapsed;
                            btnUpdate.Visibility   = Visibility.Collapsed;
                        }

                        foreach (PhienBanItemDTO item in listPhienBanItemDTO)
                        {
                            string tenFile  = item.HtPbanFile.TEN_FILE;
                            string filePath = ClientInformation.OtaVersionDir + "\\" + HtPban.MA_PBAN + "\\" + ((item.HtPbanFile.DUONG_DAN != null && !item.HtPbanFile.DUONG_DAN.Equals("")) ? item.HtPbanFile.DUONG_DAN + "\\" : "") + tenFile;
                            LLogging.WriteLog(System.Reflection.MethodInfo.GetCurrentMethod().ToString(), LLogging.LogType.SYS, "WriteAbsFileFromByteArray: " + filePath);
                            bool retWriteFile = LFile.WriteAbsFileFromByteArray(item.HtPbanData.FileData, filePath);
                            LLogging.WriteLog(System.Reflection.MethodInfo.GetCurrentMethod().ToString(), LLogging.LogType.SYS, "WriteAbsFileFromByteArray result: " + retWriteFile.ToString());
                            if (!retWriteFile)
                            {
                                ResStatus  = ApplicationConstant.ResponseStatus.KHONG_THANH_CONG;
                                ResContent = LLanguage.SearchResourceByKey("M.ResponseMessage.QuanTriHeThong.PhienBan.TaiVeKhongThanhCong");
                                Worker_Download.CancelAsync();
                            }
                        }
                        HtPban.PTHUC_CNHAT = "CHANGE";
                    }
                    // Còn lại
                    else
                    {
                    }
                    ResContent = LLanguage.SearchResourceByKey("M.ResponseMessage.QuanTriHeThong.PhienBan.CaiDat");
                }
                else if (ret == ApplicationConstant.ResponseStatus.KHONG_THANH_CONG)
                {
                    ResContent = LLanguage.SearchResourceByKey(responseMessage);
                }
                else
                {
                    ResContent = "";
                }

                Thread.Sleep(3000);
            }
            catch (Exception ex)
            {
                ResStatus  = ApplicationConstant.ResponseStatus.KHONG_THANH_CONG;
                ResContent = LLanguage.SearchResourceByKey("M.ResponseMessage.QuanTriHeThong.PhienBan.TaiVeKhongThanhCong");
                LLogging.WriteLog(System.Reflection.MethodInfo.GetCurrentMethod().ToString(), LLogging.LogType.SYS, ex);
                Worker_Download.CancelAsync();
                // Vẫn xử lý tại client cho logout
                //Application.Current.Shutdown();
            }
        }
Exemplo n.º 39
0
        protected override void AnimatedThreadWorkerDoWork(object sender, DoWorkEventArgs e)
        {
            _initialDirectiveArray.Clear();
            _resultDirectiveArray.Clear();

            if (!string.IsNullOrEmpty(TextBoxFilter.Text))
            {
                #region Загрузка элементов

                AnimatedThreadWorker.ReportProgress(0, "load directives");

                var maintenanceDirectives = new List <MaintenanceDirective>();
                try
                {
                    var temp =
                        GlobalObjects.MaintenanceCore.GetMaintenanceDirectives(TextBoxFilter.Text);

                    foreach (var directive in temp)
                    {
                        directive.ParentAircraft = GlobalObjects.AircraftsCore.GetAircraftById(directive.ParentBaseComponent?.ParentAircraftId ?? -1);
                        if (directive.ParentAircraft != null)
                        {
                            maintenanceDirectives.Add(directive);
                        }
                    }

                    AnimatedThreadWorker.ReportProgress(20, "calculation directives");


                    foreach (var g in maintenanceDirectives.GroupBy(i => i.ParentAircraft.ItemId))
                    {
                        var bindedItemsDict = GlobalObjects.BindedItemsCore.GetBindedItemsFor(g.Key,
                                                                                              maintenanceDirectives
                                                                                              .Where(m => m.WorkItemsRelationType == WorkItemsRelationType.CalculationDepend)
                                                                                              .Cast <IBindedItem>());

                        CalculateMaintenanceDirectives(maintenanceDirectives.Where(i => i.ParentAircraft.ItemId == g.Key).ToList(), bindedItemsDict);
                    }
                }
                catch (Exception ex)
                {
                    Program.Provider.Logger.Log("Error while loading directives", ex);
                }

                if (AnimatedThreadWorker.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }

                #endregion

                #region Фильтрация директив

                AnimatedThreadWorker.ReportProgress(70, "filter directives");

                FilterItems(_initialDirectiveArray, _resultDirectiveArray);

                if (AnimatedThreadWorker.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }

                #endregion

                AnimatedThreadWorker.ReportProgress(100, "Complete");
            }
        }
Exemplo n.º 40
0
        private void ExportWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            exportWorker.ReportProgress(0, "");

            var exportSettings = (ExportSettings)e.Argument;

            // clear filesystem directories
            CcbApi.InitializeExport();



            // export individuals
            if (exportSettings.ExportIndividuals)
            {
                exportWorker.ReportProgress(1, "Exporting Individuals...");
                CcbApi.ExportIndividuals(exportSettings.ModifiedSince);

                if (CcbApi.ErrorMessage.IsNotNullOrWhitespace())
                {
                    this.Dispatcher.Invoke(() =>
                    {
                        exportWorker.ReportProgress(2, $"Error exporting individuals: {CcbApi.ErrorMessage}");
                    });
                }
            }

            // export contributions
            if (exportSettings.ExportContributions)
            {
                exportWorker.ReportProgress(30, "Exporting Financial Accounts...");

                CcbApi.ExportFinancialAccounts();
                if (CcbApi.ErrorMessage.IsNotNullOrWhitespace())
                {
                    exportWorker.ReportProgress(31, $"Error exporting financial accounts: {CcbApi.ErrorMessage}");
                }

                exportWorker.ReportProgress(35, "Exporting Contribution Information...");

                CcbApi.ExportContributions(exportSettings.ModifiedSince);
                if (CcbApi.ErrorMessage.IsNotNullOrWhitespace())
                {
                    exportWorker.ReportProgress(36, $"Error exporting financial batches: {CcbApi.ErrorMessage}");
                }
            }

            // export group types
            if (ExportGroupTypes.Count > 0)
            {
                exportWorker.ReportProgress(54, $"Exporting Groups...");

                CcbApi.ExportGroups(ExportGroupTypes.Select(t => t.Id).ToList(), exportSettings.ModifiedSince);

                if (CcbApi.ErrorMessage.IsNotNullOrWhitespace())
                {
                    exportWorker.ReportProgress(54, $"Error exporting groups: {CcbApi.ErrorMessage}");
                }
            }

            // export attendance
            if (exportSettings.ExportAttendance)
            {
                exportWorker.ReportProgress(75, $"Exporting Attendance...");

                CcbApi.ExportAttendance(exportSettings.ModifiedSince);


                if (CcbApi.ErrorMessage.IsNotNullOrWhitespace())
                {
                    exportWorker.ReportProgress(75, $"Error exporting attendance: {CcbApi.ErrorMessage}");
                }
            }

            // finalize the package
            ImportPackage.FinalizePackage("ccb-export.slingshot");

            // schedule the API status to update (the status takes a few mins to update)
            _apiUpdateTimer.Start();
        }
Exemplo n.º 41
0
        private void WokerLoadAllData_DoWork(object sender, DoWorkEventArgs e)
        {
            switch (this.currentMode)
            {
            //Card
            case 1:
                Repository.lstAllCards = bus_Card.GetAllCard();
                lstFilterCard          = Repository.lstAllCards;
                this.Dispatcher.Invoke(() =>
                {
                    LoadCard();
                });
                break;

            //Card Holder
            case 2:
                Repository.lstAllCardHolders = bus_CardHolder.GetAllCardHolder();
                lstFilterCardHolder          = Repository.lstAllCardHolders;
                this.Dispatcher.Invoke(() =>
                {
                    LoadHolder();
                });
                break;

            //Device
            case 3:
                Repository.lstAllDevices = bus_Device.GetAllDevice();
                lstFilterDevice          = Repository.lstAllDevices;
                this.Dispatcher.Invoke(() =>
                {
                    LoadDevice();
                });
                break;

            //Door
            case 4:
                Repository.lstAllDoor = bUS_Door.GetAllDoor();
                lstFilterDoor         = Repository.lstAllDoor;
                this.Dispatcher.Invoke(() =>
                {
                    LoadDoor();
                });
                break;

            //Schedule
            case 5:
                Repository.lstAllSchedules = bUS_Schedule.GetAllSchedule();
                lstFilterSchedule          = Repository.lstAllSchedules;
                this.Dispatcher.Invoke(() =>
                {
                    LoadSchedule();
                });
                break;

            //Schedule
            case 6:
                Repository.lstAllRIght = bus_Right.GetAllUserRight();
                lstFilterRight         = Repository.lstAllRIght;
                this.Dispatcher.Invoke(() =>
                {
                    LoadRight();
                });
                break;
            }
        }
Exemplo n.º 42
0
 protected abstract void Process(object sender, DoWorkEventArgs e);
 private void limpaFilaImpressora_DoWork(object sender, DoWorkEventArgs e)
 {
     Thread.Sleep(1500);
     Lib.Impressora.Impressora.LimparFila();
 }
Exemplo n.º 44
0
 private void threadDetail_DoWork(object sender, DoWorkEventArgs e)
 {
     detail = orderService.findDetailByOrder(Convert.ToInt64(e.Argument));
 }
Exemplo n.º 45
0
        private void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            while (true)
            {
                if (worker.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }

                string folder = null;
                int    count  = 0;
                lock (CollectionToEnumerate)
                {
                    if (CollectionToEnumerate.Count > 0)
                    {
                        folder = CollectionToEnumerate[0].Path;
                        count += CollectionToEnumerate[0].NumberOfLinks();
                        count += CollectionToEnumerate[0].NumberOfDistantReferences();
                        CollectionToEnumerate.RemoveAt(0);
                    }
                }

                if (folder == null)
                {
                    System.Threading.Thread.Sleep(500);
                    continue;
                }

                /*string[] csvFiles = Directory.GetFiles(folder, "*.csv");
                 * foreach ( string csv in csvFiles )
                 * {
                 *  string xml = Path.ChangeExtension(csv, ".xml");
                 *  if (File.Exists(xml))
                 *  {
                 *      if (File.GetLastWriteTime(xml).CompareTo(File.GetLastWriteTime(csv)) >= 0)
                 *          continue;
                 *      File.Delete(xml);
                 *  }
                 *  ConvertCsvToXml(csv);
                 * }*/

                //int count = 0;

                /*string[] xmlFiles = Directory.GetFiles(folder, "*.xml");
                 * foreach( string xml in xmlFiles )
                 * {
                 *  if (xml.ToLower().StartsWith("_infos"))
                 *      continue;
                 *
                 *  XmlSerializer deserializer = new XmlSerializer(typeof(ImagesLinks));
                 *  TextReader reader = new StreamReader(xml);
                 *  try
                 *  {
                 *      object obj = deserializer.Deserialize(reader);
                 *      reader.Close();
                 *      ImagesLinks list = obj as ImagesLinks;
                 *      count += list.Count;
                 *  }
                 *  catch { }
                 *
                 *  if (worker.CancellationPending)
                 *  {
                 *      e.Cancel = true;
                 *      return;
                 *  }
                 * }
                 */

                IEnumerable <string> files = Directory.EnumerateFiles(folder, "*.jpg");
                foreach (string file in files)
                {
                    count++;
                    if (worker.CancellationPending)
                    {
                        e.Cancel = true;
                        return;
                    }
                }



                lock (dataGridViewImages.Rows)
                {
                    foreach (DataGridViewRow row in dataGridViewImages.Rows)
                    {
                        if (row == null || row.Tag == null)
                        {
                            continue;
                        }
                        if (!(row.Tag is ImageCollection))
                        {
                            continue;
                        }
                        if ((row.Tag as ImageCollection).Path != folder)
                        {
                            continue;
                        }
                        row.Cells[1].Value = count.ToString();
                        break;
                    }
                }
            }
        }
Exemplo n.º 46
0
        private void Worker_DoWork(object sender, DoWorkEventArgs e)
        {
            DoCheckApplicationFolders();

            SetNote("startup.label.loadingdb");
            StartServerDatabase();
            Worker.ReportProgress(10);

            // SetNote("startup.label.checkingdb");
            //if( EnsureServerIsRunning() == false)
            // {
            //     SetError("Server Off!");
            //     return;
            // }


            SetNote("startup.label.loadingmodule");
            LoadModulesDll();
            Worker.ReportProgress(20);

            SetNote("startup.label.logging");
            StartLogger();


            SetNote("startup.label.data");
            LoadTypesToDatahelper();

            SetNote("startup.label.initdb");
            InstallDefaultDatabase();
            Worker.ReportProgress(30);

            SetNote("startup.label.cultures");
            SetDefaultCultureOnThread();
            Worker.ReportProgress(40);

            SetNote("startup.label.lang");
            CheckDefaultLang();
            Worker.ReportProgress(55);

            SetNote("startup.label.checkmodules");
            ReloadAllModules();



            var setting = ElvaSettings.getInstance();

            if (setting.IsRestheatUsed)
            {
                StartServerApi();
            }

            if (setting.AppInitialized == false)
            {
                Mode = StartupMode.ALL;
            }
            else
            {
                Mode = StartupMode.LAUNCH;
            }

            if (Mode == StartupMode.ALL)
            {
                SetNote("startup.label.init");
                RestoreDatabaseDump();
                Worker.ReportProgress(50);

                SetNote("startup.label.data");
                FrameworkManager.UpdateModules();
                Worker.ReportProgress(60);

                SetNote("startup.label.series");
                InitSeries();
                Worker.ReportProgress(70);

                // SetNote("Lancement assistant");
                //Execute.PostToUIThread(() => OpenAppAssistant());
                // Worker.ReportProgress(80);

                //Execute.OnUIThread(() => { _windowManager.ShowMessageBox("Vous devez relancer l'application aprés cette configuration");  });
            }
            else
            {
                SetNote("startup.label.lang");
                SetDefaultLang();
                Worker.ReportProgress(50);
            }

            Worker.ReportProgress(60);
            SetNote("startup.label.checkadmin");
            InstallDefaultUser();

            SetNote("startup.label.data");
            ReloadAllModules();
            Worker.ReportProgress(60);

            SetNote("startup.label.temp");
            CleanTempFiles();
            Worker.ReportProgress(70);

            SetNote("startup.label.loadingmodule");
            CheckForNewModules();
            Worker.ReportProgress(80);

            LoadSettingsInDatahelpers();
            Worker.ReportProgress(90);

            SetNote("startup.label.updates");
            CheckForUpdates();
            Worker.ReportProgress(95);
        }
 void m_BackgroundWorker_Ttest(object sender, DoWorkEventArgs e)
 {
     e.Result = DoOneSampleTtest((string)e.Argument);
 }
Exemplo n.º 48
0
 private void LoadSupplierBackground(object sender, DoWorkEventArgs e)
 {
     RefreshData();
 }
 void m_BackgroundWorker_Wilcox(object sender, DoWorkEventArgs e)
 {
     e.Result = DoWilcoxtest((string)e.Argument);
 }
Exemplo n.º 50
0
        private void CustomersDownloader_DoWork(object sender, DoWorkEventArgs e)
        {
            var db = new Entities();

            e.Result = db.Customers.ToList();
        }
Exemplo n.º 51
0
        public bool Encrypt(object sender, DoWorkEventArgs e,
                            string[] FilePaths, string OutFilePath, string Password, byte[] PasswordBinary, string NewArchiveName)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            byte[] bufferKey = new byte[32];

            e.Result = ENCRYPTING;

            _FileList = new List <string>();

            //----------------------------------------------------------------------
            // Check the disk space
            //----------------------------------------------------------------------
            string RootDriveLetter = Path.GetPathRoot(Path.GetDirectoryName(OutFilePath)).Substring(0, 1);

            if (RootDriveLetter == "\\")
            {
                // Network
            }
            else
            {
                DriveInfo drive = new DriveInfo(RootDriveLetter);

                DriveType driveType = drive.DriveType;
                switch (driveType)
                {
                case DriveType.CDRom:
                case DriveType.NoRootDirectory:
                case DriveType.Unknown:
                    break;

                case DriveType.Fixed:     // Local Drive
                case DriveType.Network:   // Mapped Drive
                case DriveType.Ram:       // Ram Drive
                case DriveType.Removable: // Usually a USB Drive

                    // The drive is not available, or not enough free space.
                    if (drive.IsReady == false || drive.AvailableFreeSpace < _TotalFileSize)
                    {
                        // The drive is not available, or not enough free space.
                        if (drive.IsReady == false || drive.AvailableFreeSpace < _TotalFileSize)
                        {
                            // not available free space
                            _ReturnCode = NO_DISK_SPACE;
                            _DriveName  = drive.ToString();
                            //_TotalFileSize = _TotalFileSize;
                            _AvailableFreeSpace = drive.AvailableFreeSpace;
                            return(false);
                        }
                    }
                    break;
                }
            }

            try
            {
                //----------------------------------------------------------------------
                // Start to create zip file
                //----------------------------------------------------------------------
                using (FileStream outfs = File.Open(OutFilePath, FileMode.Create, FileAccess.ReadWrite))
                {
                    using (var zip = new ZipOutputStream(outfs))
                    {
                        zip.AlternateEncoding = System.Text.Encoding.GetEncoding("shift_jis");
                        //zip.AlternateEncoding = System.Text.Encoding.UTF8;
                        zip.AlternateEncodingUsage = Ionic.Zip.ZipOption.Always;

                        // Password
                        zip.Password = Password;

                        // Encryption Algorithm
                        switch (AppSettings.Instance.ZipEncryptionAlgorithm)
                        {
                        case ENCRYPTION_ALGORITHM_PKZIPWEAK:
                            zip.Encryption = EncryptionAlgorithm.PkzipWeak;
                            break;

                        case ENCRYPTION_ALGORITHM_WINZIPAES128:
                            zip.Encryption = EncryptionAlgorithm.WinZipAes128;
                            break;

                        case ENCRYPTION_ALGORITHM_WINZIPAES256:
                            zip.Encryption = EncryptionAlgorithm.WinZipAes256;
                            break;
                        }

                        // Compression level
                        switch (AppSettings.Instance.CompressRate)
                        {
                        case 0:
                            zip.CompressionLevel = Ionic.Zlib.CompressionLevel.None;
                            break;

                        case 1:
                            zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestSpeed;
                            break;

                        case 2:
                            zip.CompressionLevel = Ionic.Zlib.CompressionLevel.Level2;
                            break;

                        case 3:
                            zip.CompressionLevel = Ionic.Zlib.CompressionLevel.Level3;
                            break;

                        case 4:
                            zip.CompressionLevel = Ionic.Zlib.CompressionLevel.Level4;
                            break;

                        case 5:
                            zip.CompressionLevel = Ionic.Zlib.CompressionLevel.Level5;
                            break;

                        case 6:
                            zip.CompressionLevel = Ionic.Zlib.CompressionLevel.Default;
                            break;

                        case 7:
                            zip.CompressionLevel = Ionic.Zlib.CompressionLevel.Level7;
                            break;

                        case 8:
                            zip.CompressionLevel = Ionic.Zlib.CompressionLevel.Level8;
                            break;

                        case 9:
                            zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;
                            break;

                        default:
                            break;
                        }

                        string    ParentPath;
                        ArrayList FileInfoList = new ArrayList();

                        //----------------------------------------------------------------------
                        // Put together files in one ( Save as the name ).
                        // 複数ファイルを一つにまとめる(ファイルに名前をつけて保存)
                        if (NewArchiveName != "")
                        {
                            ParentPath = NewArchiveName + "\\";
                        }

                        //----------------------------------------------------------------------
                        // When encrypt multiple files
                        // 複数のファイルを暗号化する場合
                        foreach (string FilePath in FilePaths)
                        {
                            ParentPath = Path.GetDirectoryName(FilePath) + "\\";

                            if ((worker.CancellationPending == true))
                            {
                                e.Cancel = true;
                                return(false);
                            }

                            //----------------------------------------------------------------------
                            // 暗号化リストを生成(ファイル)
                            // Create file to encrypt list ( File )
                            //----------------------------------------------------------------------
                            if (File.Exists(FilePath) == true)
                            {
                                ArrayList Item = GetFileInfo(ParentPath, FilePath);
                                FileInfoList.Add(Item);
                                //Item[0]       // TypeFlag ( Directory: 0, file: 1 )
                                //Item[1]       // Absolute file path
                                //Item[2]       // Relative file path
                                //Item[3]       // File size

                                // files only
                                if ((int)Item[0] == 1)
                                {
                                    _TotalFileSize += Convert.ToInt64(Item[3]);
                                    _FileList.Add((string)Item[1]);
                                }
                            }
                            //----------------------------------------------------------------------
                            // 暗号化リストを生成(ディレクトリ)
                            // Create file to encrypt list ( Directory )
                            //----------------------------------------------------------------------
                            else
                            {
                                // Directory
                                foreach (ArrayList Item in GetFileList(ParentPath, FilePath))
                                {
                                    if ((worker.CancellationPending == true))
                                    {
                                        e.Cancel = true;
                                        return(false);
                                    }

                                    if (NewArchiveName != "")
                                    {
                                        Item[2] = NewArchiveName + "\\" + Item[2] + "\\";
                                    }

                                    FileInfoList.Add(Item);

                                    if (Convert.ToInt32(Item[0]) == 1)
                                    {                                               // files only
                                        _TotalFileSize += Convert.ToInt64(Item[3]); // File size
                                    }

                                    _FileList.Add((string)Item[1]);
                                } // end foreach (ArrayList Item in GetFilesList(ParentPath, FilePath));
                            }     // if (File.Exists(FilePath) == true);
                        }         // end foreach (string FilePath in FilePaths);

#if (DEBUG)
                        string DeskTopPath  = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
                        string TempFilePath = Path.Combine(DeskTopPath, "zip_encrypt.txt");
                        using (StreamWriter sw = new StreamWriter(TempFilePath, false, System.Text.Encoding.UTF8))
                        {
                            foreach (ArrayList Item in FileInfoList)
                            {
                                string OneLine = Item[0] + "\t" + Item[1] + "\t" + Item[2] + "\t" + Item[3] + "\n";
                                sw.Write(OneLine);
                            }
                        }
#endif
                        _NumberOfFiles      = 0;
                        _TotalNumberOfFiles = FileInfoList.Count;
                        string    MessageText = "";
                        ArrayList MessageList = new ArrayList();
                        float     percent;

                        foreach (ArrayList Item in FileInfoList)
                        {
                            //Item[0]       // TypeFlag ( Directory: 0, file: 1 )
                            //Item[1]       // Absolute file path
                            //Item[2]       // Relative file path
                            //Item[3]       // File size
                            zip.PutNextEntry((string)Item[2]);
                            _NumberOfFiles++;

                            //-----------------------------------
                            // Directory
                            if ((int)Item[0] == 0)
                            {
                                if (_TotalNumberOfFiles > 1)
                                {
                                    MessageText = (string)Item[1] + " ( " + _NumberOfFiles.ToString() + " / " + _TotalNumberOfFiles.ToString() + " )";
                                }
                                else
                                {
                                    MessageText = (string)Item[1];
                                }

                                percent     = ((float)_TotalSize / _TotalFileSize);
                                MessageList = new ArrayList();
                                MessageList.Add(ENCRYPTING);
                                MessageList.Add(MessageText);
                                worker.ReportProgress((int)(percent * 10000), MessageList);

                                if (worker.CancellationPending == true)
                                {
                                    e.Cancel = true;
                                    return(false);
                                }
                            }
                            else
                            {
                                //-----------------------------------
                                // File
                                using (FileStream fs = File.Open((string)Item[1], FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Write))
                                {
                                    byte[] buffer = new byte[BUFFER_SIZE];
                                    int    len;

                                    while ((len = fs.Read(buffer, 0, buffer.Length)) > 0)
                                    {
                                        zip.Write(buffer, 0, len);

                                        if (_TotalNumberOfFiles > 1)
                                        {
                                            MessageText = (string)Item[1] + " ( " + _NumberOfFiles.ToString() + " / " + _TotalNumberOfFiles.ToString() + " )";
                                        }
                                        else
                                        {
                                            MessageText = (string)Item[1];
                                        }

                                        _TotalSize += len;
                                        percent     = ((float)_TotalSize / _TotalFileSize);
                                        MessageList = new ArrayList();
                                        MessageList.Add(ENCRYPTING);
                                        MessageList.Add(MessageText);
                                        System.Random r = new System.Random();
                                        if (r.Next(0, 20) == 4)
                                        {
                                            worker.ReportProgress((int)(percent * 10000), MessageList);
                                        }

                                        if (worker.CancellationPending == true)
                                        {
                                            e.Cancel = true;
                                            return(false);
                                        }
                                    } // end while ((len = fs.Read(buffer, 0, buffer.Length)) > 0);
                                }     // end using (FileStream fs = File.Open((string)Item[1], FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Write));
                            }         // end if ((int)Item[0] == 0);
                        }             // end foreach (ArrayList Item in FileInfoList);
                    }                 // using (var zip = new ZipOutputStream(outfs));
                }                     // end using (FileStream outfs = File.Open(OutFilePath, FileMode.Create, FileAccess.ReadWrite));

                //Encryption succeed.
                _ReturnCode = ENCRYPT_SUCCEEDED;
                return(true);
            }
            catch (UnauthorizedAccessException)
            {
                //オペレーティング システムが I/O エラーまたは特定の種類のセキュリティエラーのためにアクセスを拒否する場合、スローされる例外
                //The exception that is thrown when the operating system denies access
                //because of an I/O error or a specific type of security error.
                _ReturnCode    = OS_DENIES_ACCESS;
                _ErrorFilePath = OutFilePath;
                return(false);
            }
            catch (DirectoryNotFoundException ex)
            {
                //ファイルまたはディレクトリの一部が見つからない場合にスローされる例外
                //The exception that is thrown when part of a file or directory cannot be found
                _ReturnCode   = DIRECTORY_NOT_FOUND;
                _ErrorMessage = ex.Message;
                return(false);
            }
            catch (DriveNotFoundException ex)
            {
                //使用できないドライブまたは共有にアクセスしようとするとスローされる例外
                //The exception that is thrown when trying to access a drive or share that is not available
                _ReturnCode   = DRIVE_NOT_FOUND;
                _ErrorMessage = ex.Message;
                return(false);
            }
            catch (FileLoadException ex)
            {
                //マネージド アセンブリが見つかったが、読み込むことができない場合にスローされる例外
                //The exception that is thrown when a managed assembly is found but cannot be loaded
                _ReturnCode    = FILE_NOT_LOADED;
                _ErrorFilePath = ex.FileName;
                return(false);
            }
            catch (FileNotFoundException ex)
            {
                //ディスク上に存在しないファイルにアクセスしようとして失敗したときにスローされる例外
                //The exception that is thrown when an attempt to access a file that does not exist on disk fails
                _ReturnCode    = FILE_NOT_FOUND;
                _ErrorFilePath = ex.FileName;
                return(false);
            }
            catch (PathTooLongException)
            {
                //パス名または完全修飾ファイル名がシステム定義の最大長を超えている場合にスローされる例外
                //The exception that is thrown when a path or fully qualified file name is longer than the system-defined maximum length
                _ReturnCode = PATH_TOO_LONG;
                return(false);
            }
            catch (IOException ex)
            {
                //I/Oエラーが発生したときにスローされる例外。現在の例外を説明するメッセージを取得します。
                //The exception that is thrown when an I/O error occurs. Gets a message that describes the current exception.
                _ReturnCode   = IO_EXCEPTION;
                _ErrorMessage = ex.Message;
                return(false);
            }
            catch (Exception ex)
            {
                _ReturnCode   = ERROR_UNEXPECTED;
                _ErrorMessage = ex.Message;
                return(false);
            }
        }
 private void _backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
 {
     OnDoWork(e);
 }
Exemplo n.º 53
0
        //=======================================

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            //var worker = sender as BackgroundWorker;
            CollectClass collectClass = new CollectClass();

            _countsLoaded = false;
            _countLastIndex = 0;

            _countYears.Clear();
            _countDefectsYears.Clear();
            _countMonths.Clear();
            _countDefectsMonths.Clear();
            _countDays.Clear();
            _countDefectsDays.Clear();
            _countSmens.Clear();
            _countDefectsSmens.Clear();
            _countParts.Clear();
            _countDefectsParts.Clear();

            Connection connection = null;
            MySqlCommand myCommand = null;
            MySqlDataReader dataReader = null;

            try
            {
                Console.WriteLine("Begin load Statistic " + DateTime.Now.ToString());
                #region last index
                try
                {
                    connection = new Connection();
                    connection.Open();
                }
                catch
                { throw (new Exception("Open Error")); }

                try
                {
                    myCommand = new MySqlCommand(@"
SELECT IndexData
FROM defectsdata
ORDER BY IndexData DESC
LIMIT 1", connection.mySqlConnection);
                }
                catch
                { throw (new Exception("Open Error")); }

                try
                {
                    dataReader = (MySqlDataReader)myCommand.ExecuteReader();
                    dataReader.Read();
                    _countLastIndex = dataReader.GetInt64(0);
                }
                catch
                { throw (new Exception("Read Error")); }

                try
                {
                    dataReader.Close();
                    connection.Close();
                }
                catch
                { throw (new Exception("Close Error")); }
                #endregion

                collectClass.Cyears(_countYears);
                collectClass.Cdyears(_countDefectsYears);
                collectClass.Cmonths(_countMonths);
                collectClass.Cdmonths(_countDefectsMonths);
                collectClass.Cdays(_countDays);
                collectClass.Cddays(_countDefectsDays);
                collectClass.Csmens(_countSmens);
                collectClass.Cdsmens(_countDefectsSmens);
                collectClass.Cparts(_countParts);
                collectClass.cdparts(_countDefectsParts);
                Console.WriteLine("End load Statistic " + DateTime.Now.ToString());
            }
            catch (Exception ex)
            {
                /*Console.WriteLine("========================================");
                Console.WriteLine("ArchiveControl.cs");
                Console.WriteLine("backgroundWorker1_DoWork()  :  " + DateTime.Now.ToString());
                Console.WriteLine(ex.Message);*/
                MessageBox.Show("Ошибка загрузки статистики");
                if (MainWindow.mainWindow.myThrArchive != null)
                {
                    archiveWindow.buttonReload.IsEnabled = true;
                }
            }
        }
Exemplo n.º 54
0
        void antminerStatusBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            var ant = e.Argument as Antminer;

            if (ant == null)
            {
                return;
            }

            _inProgressCount++;

            var status = new AntminerStatus
            {
                Id        = ant.Id,
                IpAddress = ant.IpAddress,
                Name      = ant.Name
            };

            var updatingRow = grdAntminers.Rows.SingleOrDefault(x => x.Tag.Equals(status.Id));

            if (updatingRow != null)
            {
                grdAntminers.Invoke(new MethodInvoker(() =>
                {
                    updatingRow.Cells[2].Value = "-------------";
                }));
            }

            try
            {
                var summary = AntminerConnector.GetSummary(IPAddress.Parse(ant.IpAddress));
                var stats   = AntminerConnector.GetStats(IPAddress.Parse(ant.IpAddress));

                var hwError = Convert.ToInt32(summary["Hardware Errors"].ToString());
                var diffA   = Convert.ToDouble(summary["Difficulty Accepted"].ToString());
                var diffR   = Convert.ToDouble(summary["Difficulty Rejected"].ToString());

                var rejects  = Convert.ToDouble(summary["Rejected"].ToString());
                var accepted = Convert.ToDouble(summary["Accepted"].ToString());
                var stale    = Convert.ToDouble(summary["Stale"].ToString());

                status.Status = "Alive";
                status.Ghs5S  = Convert.ToDouble(summary["GHS 5s"].ToString());
                status.GhsAv  = Convert.ToDouble(summary["GHS av"].ToString());
                status.Blocks = summary["Found Blocks"].ToString();
                status.HardwareErrorPercentage = Math.Round(hwError / (diffA + diffR) * 100, 2);
                status.RejectPercentage        = (Math.Round(rejects / accepted) * 100);
                status.StalePercentage         = (Math.Round(stale / accepted) * 100);
                status.BestShare   = Convert.ToDouble(summary["Best Share"].ToString());
                status.Fans        = string.Format("{0}, {1}", stats["fan1"], stats["fan2"]);
                status.FanSpeed    = Convert.ToInt32(stats["fan1"]);
                status.Temps       = string.Format("{0}, {1}", stats["temp1"], stats["temp2"]);
                status.Freq        = stats["frequency"].ToString();
                status.AsicStatus  = string.Format("{0} - {1}", stats["chain_acs1"], stats["chain_acs2"]);
                status.WorkUtility = Convert.ToDouble(summary["Work Utility"]);
            }
            catch (Exception)
            {
                status.Status = "Dead";
                status.Ghs5S  = 0;
                status.GhsAv  = 0;
                status.Blocks = "-";
                status.HardwareErrorPercentage = 0;
                status.RejectPercentage        = 0;
                status.StalePercentage         = 0;
                status.Fans       = "-";
                status.Temps      = "-";
                status.Freq       = "-";
                status.AsicStatus = "-";
            }

            e.Result = status;
        }
Exemplo n.º 55
0
        private void bgw_DoWork_SQLBlast(object sender, DoWorkEventArgs e)
        {
            var filePath = Program.LocalSequenceFilePath;
            var dbName = Program.SelectedDatabase;
            var tblName = Program.SelectedTable;

            var rows = this.AppSQL.GetRowsInTable(dbName, tblName, this._loadingForm);
            var dbp = Program.LocalDatabaseDirectory;// this.textBoxLBDWD.Text;
            var tempSQLFasta = dbp + @"~tempSQLDB" + "_" + dbName + "_" + tblName + ".fa";

            if (rows != null && rows.Count > 1 && rows[0][0].Contains('>'))
            {
                if (File.Exists(tempSQLFasta))
                    File.Delete(tempSQLFasta);

                var f = new List<string>();
                foreach (var s in rows)
                    f.AddRange(s);

                Management.WriteTextToFile(tempSQLFasta, f.ToArray<string>(), false);
            }

            Program.LocalSequenceFilePath = tempSQLFasta;

            if (Program.LocalSequenceFilePath != tempSQLFasta)
            {
                MessageBox.Show("Temporary SQL file unable to be constructed.", this.TitleText + " - Error");
                return;
            }

            return;
        }
Exemplo n.º 56
0
 void btcBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
 {
     e.Result = BtcPriceService.GetBtcPrice();
 }
Exemplo n.º 57
0
        void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                conn.Open();
                /*MySqlCommand cmd = new MySqlCommand("select * from `customer`", conn);
                MySqlDataAdapter adp = new MySqlDataAdapter(cmd);
                adp.Fill(ds, "customer");*/

                MySqlCommand cmd = new MySqlCommand("select * from `catagory`", conn);
                MySqlDataAdapter adp = new MySqlDataAdapter(cmd);
                adp.Fill(ds, "catagory");
            }
            catch (MySqlException ex)
            {
                logger.Trace("Exception string: {0}", conn.ConnectionString);
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                conn.Close();
            }
        }
Exemplo n.º 58
0
        public void bckWrk_DoWork(object sender, DoWorkEventArgs e)
        {
            if (BL.Utilitarios.HayInternet()) // si hay conexión a internet
            {
                #region ventas
                //
                //borrar ventas
                //
                DataTable tbl = BL.FallidasBLL.VentasGetByAccion("Deleted");
                if (tbl.Rows.Count > 0)
                {
                    //borro las ventas que no se borraron en el servidor remoto por falta de internet
                    BL.VentasBLL.BorrarByPK(tbl, ref codigoError);
                }
                //
                // agregar ventas
                //
                tbl = BL.FallidasBLL.VentasGetByAccion("Added");
                if (tbl.Rows.Count > 0)
                {
                    ds                         = BL.VentasBLL.CrearDatasetVentas(0);
                    dsVentas                   = ds.Clone(); // obtengo la estructura de las tablas ventas y ventasDetalle
                    tblVentas                  = dsVentas.Tables[0];
                    tblVentasDetalle           = dsVentas.Tables[1];
                    tblVentas.TableName        = "Ventas";
                    tblVentasDetalle.TableName = "VentasDetalle";
                    foreach (DataRow row in tbl.Rows) // obtengo las ventas que no se insertaron en el remote server para luego insert remoto
                    {
                        idVenta = Convert.ToInt32(row[0].ToString());
                        ds      = BL.VentasBLL.CrearDatasetVentas(idVenta);
                        if (ds.Tables[0].Rows.Count != 0)
                        {
                            tblVentasFallidas        = ds.Tables[0];
                            tblVentasDetalleFallidas = ds.Tables[1];
                            DataRow rwVentasFallidas = tblVentasFallidas.Rows[0];
                            tblVentas.ImportRow(rwVentasFallidas);
                            foreach (DataRow rwVentasDetalleFallidas in tblVentasDetalleFallidas.Rows)
                            {
                                tblVentasDetalle.ImportRow(rwVentasDetalleFallidas);
                            }
                        }
                    }
                    dsVentas.AcceptChanges();
                    foreach (DataRow rowVentas in tblVentas.Rows)
                    {
                        rowVentas.SetAdded();
                    }
                    foreach (DataRow rowDetalle in tblVentasDetalle.Rows)
                    {
                        rowDetalle.SetAdded();
                    }
                    if (tblVentas.GetChanges() != null || tblVentasDetalle.GetChanges() != null)
                    {
                        bool grabarFallidas = true;
                        BL.TransaccionesBLL.GrabarVentas(dsVentas, ref codigoError, grabarFallidas);
                    }
                }

                #endregion

                #region ventasDetalle

                //
                // borrar
                //
                tbl = BL.FallidasBLL.VentasDetalleGetByAccion("Deleted");
                if (tbl.Rows.Count > 0)
                {
                    BL.VentasDetalleBLL.BorrarByPK(tbl, ref codigoError);
                }
                //
                // agregar
                //
                tbl = BL.FallidasBLL.VentasDetalleGetByAccion("Added");
                if (tbl.Rows.Count > 0)
                {
                    ds                         = BL.VentasDetalleBLL.GetSchema(0);
                    dsVentas                   = ds.Clone(); // obtengo la estructura de las tablas ventasDetalle
                    tblVentasDetalle           = dsVentas.Tables[1];
                    tblVentasDetalle.TableName = "VentasDetalle";
                    foreach (DataRow row in tbl.Rows) // obtengo las ventas que no se insertaron en el remote server para luego insert remoto
                    {
                        idVenta = Convert.ToInt32(row[0].ToString());
                        // obtengo las ventasDetalle que no se insertaron en el remote server para luego insert remoto
                        ds = BL.VentasDetalleBLL.GetFallidas(idVenta);
                        if (ds.Tables[0].Rows.Count != 0)
                        {
                            foreach (DataRow rwVentasDetalleFallidas in ds.Tables[0].Rows)
                            {
                                tblVentasDetalle.ImportRow(rwVentasDetalleFallidas);
                            }
                        }
                    }
                    foreach (DataRow rowDetalle in tblVentasDetalle.Rows)
                    {
                        rowDetalle.SetAdded();
                    }
                    if (dsVentas.HasChanges())
                    {
                        BL.VentasDetalleBLL.InsertFallidasRemoteServer(dsVentas, ref codigoError);
                    }
                }
                //
                // editar
                //
                tbl = BL.FallidasBLL.VentasDetalleGetByAccion("Modified");
                if (tbl.Rows.Count > 0)
                {
                    ds                         = BL.VentasDetalleBLL.GetSchema(0);
                    dsVentas                   = ds.Clone(); // obtengo la estructura de las tablas ventasDetalle
                    tblVentasDetalle           = dsVentas.Tables[1];
                    tblVentasDetalle.TableName = "VentasDetalle";
                    foreach (DataRow row in tbl.Rows) // obtengo las ventas que no se insertaron en el remote server para luego insert remoto
                    {
                        idVenta = Convert.ToInt32(row[0].ToString());
                        // obtengo las ventasDetalle que no se insertaron en el remote server para luego insert remoto
                        ds = BL.VentasDetalleBLL.GetFallidas(idVenta);
                        if (ds.Tables[0].Rows.Count != 0)
                        {
                            foreach (DataRow rwVentasDetalleFallidas in ds.Tables[0].Rows)
                            {
                                tblVentasDetalle.ImportRow(rwVentasDetalleFallidas);
                            }
                        }
                    }
                    foreach (DataRow rowDetalle in tblVentasDetalle.Rows)
                    {
                        rowDetalle.SetModified();
                    }
                    if (dsVentas.HasChanges())
                    {
                        BL.VentasDetalleBLL.EditFallidasRemoteServer(dsVentas, ref codigoError);
                    }
                }

                #endregion

                #region TesoreriaMovimientos
                //
                //borrar TesoreriaMovimientos
                //
                tbl = BL.FallidasBLL.TesoreriaGetByAccion("Deleted");
                if (tbl.Rows.Count > 0)
                {
                    //borro las movimientos de tesoreria que no se borraron en el servidor remoto por falta de internet
                    BL.TesoreriaMovimientosBLL.BorrarByPK(tbl, ref codigoError);
                }
                //
                // agregar TesoreriaMovimientos
                //
                tbl = BL.FallidasBLL.TesoreriaGetByAccion("Added");
                if (tbl.Rows.Count > 0)
                {
                    ds = BL.TesoreriaMovimientosBLL.CrearDataset();
                    DataSet   dsTesoreria  = ds.Clone(); // obtengo la estructura de la tabla TesoreriaMovimientos
                    DataTable tblTesoreria = dsTesoreria.Tables[0];
                    tblTesoreria.TableName = "TesoreriaMovimientos";
                    foreach (DataRow row in tbl.Rows) // obtengo las ventas que no se insertaron en el remote server para luego insert remoto
                    {
                        int idMov = Convert.ToInt32(row[0].ToString());
                        ds = BL.TesoreriaMovimientosBLL.CrearDatasetMovimiento(idMov);
                        if (ds.Tables[0].Rows.Count != 0)
                        {
                            tblTesoreriaFallidas = ds.Tables[0];
                            DataRow rwTesoreriaFallidas = tblTesoreriaFallidas.Rows[0];
                            tblTesoreria.ImportRow(rwTesoreriaFallidas);
                        }
                    }
                    dsTesoreria.AcceptChanges();
                    foreach (DataRow rowTesoreria in tblTesoreria.Rows)
                    {
                        rowTesoreria.SetAdded();
                    }
                    if (tblTesoreria.GetChanges() != null)
                    {
                        bool grabarFallidas = true;
                        BL.TesoreriaMovimientosBLL.InsertFallidasRemoteServer(dsTesoreria, ref codigoError, grabarFallidas);
                    }
                }
                //
                // editar TesoreriaMovimientos
                //
                tbl = BL.FallidasBLL.TesoreriaGetByAccion("Modified");
                if (tbl.Rows.Count > 0)
                {
                    ds = BL.TesoreriaMovimientosBLL.CrearDataset();
                    DataSet   dsTesoreria  = ds.Clone(); // obtengo la estructura de la tabla TesoreriaMovimientos
                    DataTable tblTesoreria = dsTesoreria.Tables[0];
                    tblTesoreria.TableName = "TesoreriaMovimientos";
                    foreach (DataRow row in tbl.Rows) // obtengo las ventas que no se insertaron en el remote server para luego insert remoto
                    {
                        int idMov = Convert.ToInt32(row[0].ToString());
                        ds = BL.TesoreriaMovimientosBLL.CrearDatasetMovimiento(idMov);
                        if (ds.Tables[0].Rows.Count != 0)
                        {
                            tblTesoreriaFallidas = ds.Tables[0];
                            DataRow rwTesoreriaFallidas = tblTesoreriaFallidas.Rows[0];
                            tblTesoreria.ImportRow(rwTesoreriaFallidas);
                        }
                    }
                    dsTesoreria.AcceptChanges();
                    foreach (DataRow rowTesoreria in tblTesoreria.Rows)
                    {
                        rowTesoreria.SetModified();
                    }
                    if (tblTesoreria.GetChanges() != null)
                    {
                        bool grabarFallidas = true;
                        BL.TesoreriaMovimientosBLL.EditFallidasRemoteServer(dsTesoreria, ref codigoError, grabarFallidas);
                    }
                }
                #endregion

                #region FondoCaja
                //
                // agregar FondoCaja
                //
                tbl = BL.FallidasBLL.FondoCajaGetByAccion("Added");
                if (tbl.Rows.Count > 0)
                {
                    ds = BL.FondoCajaBLL.CrearDataset();
                    DataSet   dsFondoCaja  = ds.Clone(); // obtengo la estructura de la tabla
                    DataTable tblFondoCaja = dsFondoCaja.Tables[0];
                    tblFondoCaja.TableName = "FondoCaja";
                    foreach (DataRow row in tbl.Rows) // obtengo las ventas que no se insertaron en el remote server para luego insert remoto
                    {
                        int idMov = Convert.ToInt32(row[0].ToString());
                        ds = BL.FondoCajaBLL.GetByPk(idMov);
                        if (ds.Tables[0].Rows.Count != 0)
                        {
                            tblFondoFallidas = ds.Tables[0];
                            DataRow rwFondoFallidas = tblFondoFallidas.Rows[0];
                            tblFondoCaja.ImportRow(rwFondoFallidas);
                        }
                    }
                    dsFondoCaja.AcceptChanges();
                    foreach (DataRow rowFondo in tblFondoCaja.Rows)
                    {
                        rowFondo.SetAdded();
                    }
                    if (tblFondoCaja.GetChanges() != null)
                    {
                        bool grabarFallidas = true;
                        BL.FondoCajaBLL.InsertFallidasRemoteServer(dsFondoCaja, ref codigoError, grabarFallidas);
                    }
                }
                //
                // editar FondoCaja
                //
                tbl = BL.FallidasBLL.FondoCajaGetByAccion("Modified");
                if (tbl.Rows.Count > 0)
                {
                    ds = BL.FondoCajaBLL.CrearDataset();
                    DataSet   dsFondoCaja  = ds.Clone(); // obtengo la estructura de la tabla TesoreriaMovimientos
                    DataTable tblFondoCaja = dsFondoCaja.Tables[0];
                    tblFondoCaja.TableName = "FondoCaja";
                    foreach (DataRow row in tbl.Rows) // obtengo las ventas que no se insertaron en el remote server para luego insert remoto
                    {
                        int idMov = Convert.ToInt32(row[0].ToString());
                        ds = BL.FondoCajaBLL.GetByPk(idMov);
                        if (ds.Tables[0].Rows.Count != 0)
                        {
                            tblFondoFallidas = ds.Tables[0];
                            DataRow rwFondoFallidas = tblFondoFallidas.Rows[0];
                            tblFondoCaja.ImportRow(rwFondoFallidas);
                        }
                    }
                    dsFondoCaja.AcceptChanges();
                    foreach (DataRow rowFondo in tblFondoCaja.Rows)
                    {
                        rowFondo.SetModified();
                    }
                    if (tblFondoCaja.GetChanges() != null)
                    {
                        bool grabarFallidas = true;
                        BL.FondoCajaBLL.EditFallidasRemoteServer(dsFondoCaja, ref codigoError, grabarFallidas);
                    }
                }
                #endregion

                #region Clientes
                // la inserción de registros fallidos en el remote server y el borrado de registros de la tabla local "clientesfallidas",
                // se hace toda através de ClientesBLL y ClientesDAL no se usa
                // como en ventas, ventasDetalle, TesoreriaMovimientos y FondoCaja las clases FallidasBLL y FallidasDAL
                //
                //borrar Clientes
                //
                tbl = BL.ClientesBLL.ClienteGetByAccion("Delete"); // OJO !!! que las otras tablas locales fallidas guardan 'Modified', 'Deleted', 'Added'
                if (tbl.Rows.Count > 0)
                {
                    //borro los clientes que no se borraron en el servidor remoto por falta de internet
                    BL.ClientesBLL.BorrarByPK(tbl, ref codigoError);
                }
                //
                // agregar Clientes
                //
                tbl = BL.ClientesBLL.ClienteGetByAccion("Add");// OJO !!! que las otras tablas locales fallidas guardan 'Modified', 'Deleted', 'Added'
                if (tbl.Rows.Count > 0)
                {
                    ds = BL.ClientesBLL.GetClientes(0);
                    DataSet   dsCliente  = ds.Clone(); // obtengo la estructura de la tabla Clientes
                    DataTable tblCliente = dsCliente.Tables[0];
                    tblCliente.TableName = "Clientes";
                    foreach (DataRow row in tbl.Rows) // obtengo los clientes que no se insertaron en el remote server para luego insert remoto
                    {
                        int idCliente = Convert.ToInt32(row[0].ToString());
                        ds = BL.ClientesBLL.GetRegistroFallido(idCliente);
                        if (ds.Tables[0].Rows.Count != 0)
                        {
                            tblClienteFallidas = ds.Tables[0];
                            DataRow rwClienteFallidas = tblClienteFallidas.Rows[0];
                            tblCliente.ImportRow(rwClienteFallidas);
                        }
                    }
                    dsCliente.AcceptChanges();
                    foreach (DataRow rowCliente in tblCliente.Rows)
                    {
                        rowCliente.SetAdded();
                    }
                    if (tblCliente.GetChanges() != null)
                    {
                        bool grabarFallidas = true;
                        BL.ClientesBLL.GrabarFallidasRemoteServer(dsCliente, ref codigoError, grabarFallidas, "Add");
                    }
                }
                //
                // editar Clientes
                //
                tbl = BL.ClientesBLL.ClienteGetByAccion("Change");// OJO !!! que las otras tablas locales fallidas guardan 'Modified', 'Deleted', 'Added'
                if (tbl.Rows.Count > 0)
                {
                    ds = BL.ClientesBLL.GetClientes(0);
                    DataSet   dsCliente  = ds.Clone(); // obtengo la estructura de la tabla Clientes
                    DataTable tblCliente = dsCliente.Tables[0];
                    tblCliente.TableName = "Clientes";
                    foreach (DataRow row in tbl.Rows) // obtengo los clientes que no se insertaron en el remote server para luego insert remoto
                    {
                        int idCliente = Convert.ToInt32(row[0].ToString());
                        ds = BL.ClientesBLL.GetRegistroFallido(idCliente);
                        if (ds.Tables[0].Rows.Count != 0)
                        {
                            tblClienteFallidas = ds.Tables[0];
                            DataRow rwClienteFallidas = tblClienteFallidas.Rows[0];
                            tblCliente.ImportRow(rwClienteFallidas);
                        }
                    }
                    dsCliente.AcceptChanges();
                    foreach (DataRow rowCliente in tblCliente.Rows)
                    {
                        rowCliente.SetModified();
                    }
                    if (tblCliente.GetChanges() != null)
                    {
                        bool grabarFallidas = true;
                        BL.ClientesBLL.GrabarFallidasRemoteServer(dsCliente, ref codigoError, grabarFallidas, "Change");
                    }
                }
                #endregion
            }
        }
      void invalidatorWatch(object sender, DoWorkEventArgs e)
      {
         var w = sender as BackgroundWorker;

         TimeSpan span = TimeSpan.FromMilliseconds(111);
         int spanMs = (int)span.TotalMilliseconds;
         bool skiped = false;
         TimeSpan delta;
         DateTime now = DateTime.Now;

         while(Refresh != null && (!skiped && Refresh.WaitOne() || (Refresh.WaitOne(spanMs, false) || true)))
         {
            if(w.CancellationPending)
               break;

            now = DateTime.Now;
            lock(invalidationLock)
            {
               delta = now - lastInvalidation;
            }

            if(delta > span)
            {
               lock(invalidationLock)
               {
                  lastInvalidation = now;
               }
               skiped = false;

               w.ReportProgress(1);
               Debug.WriteLine("Invalidate delta: " + (int)delta.TotalMilliseconds + "ms");
            }
            else
            {
               skiped = true;
            }
         }
      }
Exemplo n.º 60
0
 private void _curBgWork_DoWork(object sender, DoWorkEventArgs e)
 {
 }