예제 #1
0
        private bool UpdateBinary()
        {
            string source, target;
            bool   success = true;

            progressBar1.Value = 0;

            foreach (ListViewItem item in CheckListBox.Items)
            {
                if (item.Checked)
                {
                    // Field 1 has the full source for the item
                    source = item.SubItems[1].Text;
                    target = String.Concat(gBinLocation, "\\", item.Text);

                    FileInfo file = new FileInfo(source);

                    // Main copy loop
CopyFile:

                    try
                    {
                        file.CopyTo(target, true);
                    }
                    catch (Exception e2)
                    {
                        // string message = String.Concat("File ", source, " did not copy!");
                        DialogResult rc = MessageBox.Show(e2.Message, "", MessageBoxButtons.AbortRetryIgnore);

                        switch (rc)
                        {
                        case DialogResult.Abort:
                            success = false;
                            Application.Exit();
                            break;

                        case DialogResult.Retry:
                            goto CopyFile;

                        case DialogResult.Ignore:
                            success = false;
                            continue;
                        }
                    }

                    progressBar1.PerformStep();
                    item.Checked = false;
                }
            }

            progressBar1.Value = 0;

            if (success)
            {
                UpdateRunButton.Enabled = false;
                UpdateButton.Enabled    = false;
            }

            return(success);
        }
예제 #2
0
        public static void Sub_Color(Image[] img, int k1, int k2, int k3, ProgressBar progressBar1, double N1, double N2)
        {
            int w1 = img[k1 - 1].Width;
            int h1 = img[k1 - 1].Height;
            Bitmap bmp1 = new Bitmap(img[k1 - 1], w1, h1);

            int w2 = img[k2 - 1].Width;
            int h2 = img[k2 - 1].Height;
            Bitmap bmp2 = new Bitmap(img[k2 - 1], w2, h2);

            w1 = (int)Math.Min(w1, w2);
            h1 = (int)Math.Min(h1, h2);

            Bitmap bmp3 = new Bitmap(img[k3 - 1], w1, h1);

            Color c1, c2;
            int r1, r2, rs;
            int max=-32000, min=32000;
            progressBar1.Visible = true;
            progressBar1.Minimum = 1;
            progressBar1.Maximum = w1;
            progressBar1.Value = 1;
            progressBar1.Step = 1;

            for (int i = 0; i < w1; i++)
            {
                for (int j = 0; j < h1; j++)
                {
                    c1 = bmp1.GetPixel(i, j);  r1 = (int) (c1.R * N1);
                    c2 = bmp2.GetPixel(i, j);  r2 = (int) (c2.R * N2);
                    rs = (r1 - r2);
                    min = Math.Min(rs, min);
                    max = Math.Max(rs, max);
                }

                progressBar1.PerformStep();
            }
            // ---------------------------------------------------------------------------------------------------
            progressBar1.Value = 1;
            for (int i = 0; i < w1; i++)
            {
                for (int j = 0; j < h1; j++)
                {
                    c1 = bmp1.GetPixel(i, j); r1 = (int) (c1.R * N1);
                    c2 = bmp2.GetPixel(i, j); r2 = (int) (c2.R * N2);
                    rs = (r1 - r2);
                    rs = (rs - min) * 255 / (max - min);
                    bmp3.SetPixel(i, j, Color.FromArgb(rs, rs, rs));
                }

                progressBar1.PerformStep();
            }
            img[k3 - 1] = bmp3;
        }
예제 #3
0
        private void defineProcesses()
        {
            ArrayList processes = m_db.getProcesses();

            progressBar.Maximum = processes.Count;
            progressBar.Minimum = 0;

            int retry = 0;

            //sc.connect("130.100.232.7");
            foreach (Process p in processes)
            {
                Computer comp;
                retry = 0;
                //if(p.getName().StartsWith("ndb") || p.getName().StartsWith("mgm"))
                //{
                textAction.Text = "Defining process " + p.getName();
                textAction.Refresh();
                comp = p.getComputer();
                while (retry < 10)
                {
                    if (!comp.isConnected())
                    {
                        comp.connectToCpcd();
                    }
                    else
                    {
                        if (comp.defineProcess(p) < 0)
                        {
                            ;
                        }
                        else
                        {
                            break;
                        }
                    }
                    if (retry == 9)
                    {
                        if (MessageBox.Show(this, "Failed to define process. Try again?", "Warning!!!", MessageBoxButtons.YesNo) == DialogResult.Yes)
                        {
                            retry = 0;
                        }
                    }
                    retry++;
                    //comp.undefineProcess(p);
                }
                //}
                progressBar.PerformStep();
            }
        }
예제 #4
0
        private void btnStart_Click(object sender, System.EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;

            //Build a new network.
            backend.BuildNetwork();

            //lblHiddenNeurons.Text = "Hidden Neurons: " + backend.HiddenNeuronCount;

            ResetOut();

            int epochs = int.Parse(txtEpochs.Text); //the count of rounds.

            progBar.Maximum = epochs;               //Progressbar Stuff
            progBar.Step    = 1;
            progBar.Value   = 0;

            for (int i = 0; i < epochs; i++)
            {
                backend.TrainEpoche();                 //Train all 4 patterns one time.
                progBar.PerformStep();                 //Update the progress bar.
            }

            double[] output = backend.EvaluateOutputs();
            for (int i = 0; i < 16; i++)
            {
                pattern[i].OutputFF = Math.Round(output[i], 8).ToString();
                pattern[i].OutputFT = Math.Round(output[i + 16], 8).ToString();
                pattern[i].OutputTF = Math.Round(output[i + 32], 8).ToString();
                pattern[i].OutputTT = Math.Round(output[i + 48], 8).ToString();
            }

            Cursor.Current = Cursors.Default;
        }
예제 #5
0
 private void tmrIncrementBar_Tick(object sender, EventArgs e)
 {
     Bar.PerformStep();
     if (Bar.Value == Bar.Maximum)
     {
         Bar.Value = 0;
     }
 }
예제 #6
0
 private void timer1_Tick(object sender, System.EventArgs e)
 {
     ConnectionProgress.PerformStep();
     if (ConnectionProgress.Value == ConnectionProgress.Maximum)
     {
         StriveWindowState = ConnectionWindowState.NotConnected;
     }
 }
예제 #7
0
        public static void ATAN_123(Image[] img, PictureBox pictureBox01, ProgressBar progressBar1, int n, double[] fzz, double Gamma)
        {
            int w1 = img[0].Width;
            int h1 = img[0].Height;

            int n_sdv = n;                                                       // Число фазовых сдвигов

            double[] i_sdv = new double[4];
            double[] v_sdv = new double[4];                                  // Вектор коэффициентов
            double[] k_sin = new double[4];
            double[] k_cos = new double[4];
            double pi = Math.PI;

            for (int i = 0; i < n_sdv; i++) { k_sin[i] = Math.Sin(fzz[i] * pi / 180); k_cos[i] = Math.Cos(fzz[i] * pi / 180); }  //  Сдвиги фаз

            Color c;
            int r;
            double fz, fz1, fz2;
            Bitmap bmp1 = new Bitmap(img[0], w1, h1);
            Bitmap bmp2 = new Bitmap(img[1], w1, h1);
            Bitmap bmp3 = new Bitmap(img[2], w1, h1);
            Bitmap bmp4 = new Bitmap(img[3], w1, h1);
            Bitmap bmp5 = new Bitmap(w1, h1);

            progressBar1.Visible = true;
            progressBar1.Minimum = 1;
            progressBar1.Maximum = w1;
            progressBar1.Value = 1;
            progressBar1.Step = 1;

            for (int i = 0; i < w1; i++)
            {
                for (int j = 0; j < h1; j++)
                {
                    c = bmp1.GetPixel(i, j); r = (c.R + c.G + c.B) / 3; i_sdv[0] = (int)Math.Pow(r, Gamma);
                    c = bmp2.GetPixel(i, j); r = (c.R + c.G + c.B) / 3; i_sdv[1] = (int)Math.Pow(r, Gamma);
                    c = bmp3.GetPixel(i, j); r = (c.R + c.G + c.B) / 3; i_sdv[2] = (int)Math.Pow(r, Gamma);
                    c = bmp4.GetPixel(i, j); r = (c.R + c.G + c.B) / 3; i_sdv[3] = (int)Math.Pow(r, Gamma);

                    // ------                                     Формула расшифровки

                    v_sdv[0] = i_sdv[1] - i_sdv[n_sdv - 1];
                    v_sdv[n_sdv - 1] = i_sdv[0] - i_sdv[n_sdv - 2];
                    for (int ii = 1; ii < n_sdv - 1; ii++) v_sdv[ii] = i_sdv[ii + 1] - i_sdv[ii - 1];
                    fz1 = fz2 = 0; for (int ii = 0; ii < n_sdv; ii++) { fz1 += v_sdv[ii] * k_sin[ii]; fz2 += v_sdv[ii] * k_cos[ii]; }

                    fz = Math.Atan2(fz1, fz2) + Math.PI;
                    r = (int)((fz * 255) / (2 * Math.PI));

                    bmp5.SetPixel(i, j, Color.FromArgb(r, r, r));
                }
                progressBar1.PerformStep();
            }
            pictureBox01.Size = bmp4.Size;
            pictureBox01.Image = bmp5;
        }
예제 #8
0
		private void Prepared()
		{
			if( InvokeRequired )
			{
				this.Invoke( new MethodInvoker(Prepared), new object [] { } );
				return ;
			}

			progress.PerformStep();
		}
예제 #9
0
        private void CalculateAll(System.Windows.Forms.ProgressBar progressBar)
        {
            progressBar1.Maximum = 100000;
            progressBar.Step     = 1;

            for (int i = 0; i < 100000; i++)
            {
                double pow = Math.Pow(i, i);
                progressBar.PerformStep();
            }
        }
예제 #10
0
		void ClearFlags(FdoCache cache, ProgressBar progressBar)
		{
			var paras = cache.ServiceLocator.GetInstance<IStTxtParaRepository>().AllInstances().ToArray();
			progressBar.Minimum = 0;
			progressBar.Maximum = paras.Length;
			progressBar.Step = 1;
			foreach (var para in paras)
			{
				progressBar.PerformStep();
				para.ParseIsCurrent = false;
			}
		}
예제 #11
0
        private void CaluculateAll(System.Windows.Forms.ProgressBar progressBar)
        {
            progressBar1.Visible = true;

            progressBar.Maximum = 100000;
            progressBar.Step    = 1;

            for (int j = 0; j < 100000; j++)
            {
                double pow = Math.Pow(j, j); //Calculation
                progressBar.PerformStep();
            }
        }
예제 #12
0
파일: Form1.cs 프로젝트: Gwee/csharp
 private void Timer1_Tick(object sender, System.EventArgs e)
 {
     t++;
     Label1.Text = t.ToString();
     if (ProgressBar1.Value == ProgressBar1.Maximum)
     {
         ProgressBar1.Value = 0;
     }
     else
     {
         ProgressBar1.PerformStep();
     }
 }
예제 #13
0
파일: Form1.cs 프로젝트: WebDaD/M3UExporter
 private void copyMP3s(ListBox.ObjectCollection files, decimal starting_number, bool auto_pad, decimal padding, string target_folder, ProgressBar pb_progress)
 {
     if (auto_pad) padding = (decimal)Math.Floor(Math.Log10(files.Count) + 1);
     pb_progress.Maximum = files.Count;
     pb_progress.Step = 1;
     int now = (int)starting_number;
     int i;
     for (i = 0; i < files.Count; i++)
     {
         string f = files[i] as string;
         try
         {
             string f_name = Path.GetFileName(f);
             string new_name = target_folder + "\\" + now.ToString().PadLeft((int)padding, '0') + "_" + f_name;
             File.Copy(f, new_name);
             pb_progress.PerformStep();
             now++;
         }
         catch (FileNotFoundException)
         {
             DialogResult d = MessageBox.Show("File " + f + " has not been found...", "Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Error);
             if (d == System.Windows.Forms.DialogResult.Abort)
             {
                 break;
             }
             else if (d == System.Windows.Forms.DialogResult.Retry)
             {
                 i--;
             }
             else //Ignore
             {
                 pb_progress.PerformStep();
                 now++;
             }
         }
     }
     MessageBox.Show(i+" of "+files.Count + " Files have been copied.", "Done", MessageBoxButtons.OK, MessageBoxIcon.Information);
     pb_progress.Value = 0;
 }
예제 #14
0
        void myWorkerThread_OnMethodCompleted(object source, WorkerThreadEventArgs args)
        {
            int    Threadnum   = Convert.ToInt16(args.threadname);
            double dblCallTime = args.MethodCallTime.TotalSeconds;

            CallTimes[Threadnum, args.CallNumber] = dblCallTime;

            decimal decCallTime = Convert.ToDecimal(dblCallTime);

            decCallTime = decimal.Round(decCallTime, 2);
            decimal decAverageTime = Convert.ToDecimal(args.AverageCallTime);

            decAverageTime = decimal.Round(decAverageTime, 2);

            lsvResults.Items[Threadnum].SubItems[(int)ColumnIndex.InCall].Text          = "false";
            lsvResults.Items[Threadnum].SubItems[(int)ColumnIndex.LastCallTime].Text    = decCallTime.ToString();
            lsvResults.Items[Threadnum].SubItems[(int)ColumnIndex.AverageCallTime].Text = decAverageTime.ToString();
            lsvResults.Items[Threadnum].BackColor = System.Drawing.Color.White;
            lsvResults.Items[Threadnum].SubItems[(int)ColumnIndex.ThreadStatus].Text = "Running";

            prgCompletedCalls.PerformStep();
        }
예제 #15
0
        public static void CaluculateAll(System.Windows.Forms.ProgressBar progressBar)
        {
            progressBar.Value   = 1;
            progressBar.Maximum = 1000000;
            progressBar.Minimum = 1;
            progressBar.Step    = 1;

            for (int j = 0; j < 1000000; j++)
            {
                double pow = Math.Pow(j, j); //Calculation
                progressBar.PerformStep();
            }
        }
예제 #16
0
        protected void Frame_Rendered(object sender, EventArgs e)
        {
            // increase the step by one
            pbarProgress.PerformStep();

            // update estimateTime
            int framesRemaining = pbarProgress.Maximum - pbarProgress.Value;

            remainingTime = TimeSpan.FromTicks((currTime.Ticks + TimeSpan.TicksPerSecond) * framesRemaining);



            currTime = TimeSpan.FromTicks(0);
            UpdateTimeLabels();
        }
예제 #17
0
        public void checkOpFinished(Object obj, System.EventArgs arg)
        {
            timer1.Stop();

            progressBar1.PerformStep();
            Invalidate();
            progressBar1.Update();

            if (Finished)
            {
                timer1.Dispose();
                return;
            }
            timer1.Enabled = true;
        }
예제 #18
0
파일: Form1.cs 프로젝트: kargabry/C-Sharp
        private void LoadingBar(System.Windows.Forms.ProgressBar progressBar, int time)
        {
            progressBar.Maximum = time;
            progressBar.Step    = 1;

            for (int j = 0; j < time; j++)
            {
                double pow = Math.Pow(j, j); //Calculation
                progressBar.PerformStep();
            }

            if (progressBar1.Value == time)
            {
                progressBar1.Value = 1;
            }
        }
예제 #19
0
        public static void PerformStep(ProgressBar progressBar)
        {
            MethodInvoker miPerformStep = delegate
            {
                progressBar.PerformStep();
            };

            if (progressBar.InvokeRequired)
            {
                progressBar.Invoke(miPerformStep);
            }
            else
            {
                miPerformStep();
            }
        }
예제 #20
0
        public void checkOpFinished(Object obj, System.EventArgs arg)
        {
            timer1.Stop();

            progressBar1.PerformStep();
            Invalidate();
            progressBar1.Update();

            if (CheckTool.isFinished)
            {
                timer1.Dispose();
                progressBar1.Value   = 0;
                progressBar1.Visible = false;
                //this.Close();
                return;
            }
            timer1.Enabled = true;
        }
예제 #21
0
        public static void MakeProgressBar(int min, int max, int initialvalue, int step)
        {
            //display the progress bar control
            ProgressBar bar = new ProgressBar();

            bar.Visible = true;

            //set minimum to 1 to to represent the first file being copied
            bar.Minimum = min;
            bar.Maximum = max;
            //initial value
            bar.Value = initialvalue;
            bar.Step = step;

            Console.CursorVisible = false;
            Console.ForegroundColor = ConsoleColor.Green;
            bar.PerformStep();
        }
예제 #22
0
        private void runSelectedTestButton_Click(object sender, System.EventArgs e)
        {
            //set the progess bar for a single test
            setupResultsBar(1);
            //test the selected method
            TreeNode selected = testMethodsTree.SelectedNode;

            if (null == selected)
            {
                MessageBox.Show("Please select a test method");
            }
            else
            {
                TestResult result = tr.runSingleTestMethod(selected.Text);
                resultsBar.PerformStep();
                displayTestResults(result);
            }
        }
예제 #23
0
        /********************************************************************************/
        //***Copia todos arquivos de um diretório para outro com progress****************/
        /********************************************************************************/
        public void Copia_Todos_Arquivos_2(System.IO.DirectoryInfo origem, System.IO.DirectoryInfo destino, System.Windows.Forms.ProgressBar prb,
                                           System.Windows.Forms.ProgressBar prb_arquivo)
        {
            if (origem.FullName.ToLower() == destino.FullName.ToLower())
            {
                return;
            }

            if (!System.IO.Directory.Exists(destino.FullName))
            {
                try
                {
                    System.IO.Directory.CreateDirectory(destino.FullName);
                }
                catch (UnauthorizedAccessException e)
                {
                    Console.WriteLine(e.Message);
                    log.Add(e.Message);
                }
            }

            foreach (System.IO.FileInfo fi in origem.GetFiles())
            {
                try
                {
                    CustomFileCopier copia = new CustomFileCopier(fi.FullName, Path.Combine(destino.ToString(), fi.Name));
                    copia.Copy(prb_arquivo);
                    prb.PerformStep();
                    //Console.WriteLine(@"Copiando ... {0}\{1}", destino.FullName, fi.Name);
                    //fi.CopyTo(System.IO.Path.Combine(destino.ToString(), fi.Name), true);
                }
                catch (UnauthorizedAccessException e)
                {
                    Console.WriteLine(e.Message);
                    log.Add(e.Message);
                }
            }

            foreach (System.IO.DirectoryInfo diSourceSubDir in origem.GetDirectories())
            {
                System.IO.DirectoryInfo nextTargetSubDir = destino.CreateSubdirectory(diSourceSubDir.Name);
                Copia_Todos_Arquivos_2(diSourceSubDir, nextTargetSubDir, prb, prb_arquivo);
            }
        }
예제 #24
0
        private void btnStart_Click(object sender, System.EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;

            //Build a new network.
            backend.BuildNetwork();

            //Update the backend's input and training data.
            inputMatrix[0]   = double.Parse(txtX1.Text);
            inputMatrix[1]   = double.Parse(txtY1.Text);
            inputMatrix[2]   = double.Parse(txtX2.Text);
            inputMatrix[3]   = double.Parse(txtY2.Text);
            inputMatrix[4]   = double.Parse(txtX3.Text);
            inputMatrix[5]   = double.Parse(txtY3.Text);
            inputMatrix[6]   = double.Parse(txtX4.Text);
            inputMatrix[7]   = double.Parse(txtY4.Text);
            desiredMatrix[0] = double.Parse(txtT1.Text);
            desiredMatrix[1] = double.Parse(txtT2.Text);
            desiredMatrix[2] = double.Parse(txtT3.Text);
            desiredMatrix[3] = double.Parse(txtT4.Text);
            backend.SetMatrix(inputMatrix, desiredMatrix);

            ResetOut();

            int epochs = int.Parse(txtEpochs.Text); //the count of rounds.

            progBar.Maximum = epochs;               //Progressbar Stuff
            progBar.Step    = 1;
            progBar.Value   = 0;

            for (int i = 0; i < epochs; i++)
            {
                backend.TrainEpoche();                 //Train all 4 patterns one time.
                progBar.PerformStep();                 //Update the progress bar.
            }

            double[] output = backend.EvaluateOutputs();
            txtO1.Text = output[0].ToString();
            txtO2.Text = output[1].ToString();
            txtO3.Text = output[2].ToString();
            txtO4.Text = output[3].ToString();

            Cursor.Current = Cursors.Default;
        }
예제 #25
0
    private void UpdateProgress()
    {
        double completed;
        double number;

        //如果值达到最大,进行重置重新开始
        if (progressBar1.Value == progressBar1.Maximum)
        {
            progressBar1.Value = progressBar1.Minimum;
        }
        else
        {
            progressBar1.PerformStep();
        }
        number    = this.progressBar1.Value;
        completed = (number / 100) * 100.0;
        //改变completedLabel的Text属性,代表进程进度
        completedlabel.Text = Math.Round(completed).ToString() + "%";
    }
예제 #26
0
        public void SetupForward()
        {
            lbMessage.Text = "正在安装程序文件...";

            string setupDir    = PropertySet.GetValue("setupdir").ToString();
            string zipFileName = PropertySet.GetValue("zipfile").ToString();

            ZipFileHandler zipHandler = new ZipFileHandler();

            try
            {
                List <string> tempfiles = new List <string>();
                zipHandler.BeginDecompress(zipFileName, setupDir, ref tempfiles);

                progBar.Value   = 0;
                progBar.Minimum = 0;
                progBar.Maximum = tempfiles.Count;
                progBar.Step    = 1;

                foreach (string file in tempfiles)
                {
                    zipHandler.DecompressSingleFile(zipFileName, setupDir, file);
                    progBar.PerformStep();
                }

                lbMessage.Text = "安装完毕,请单击\"下一步\"结束安装";
                this.Refresh();

                m_form.AddTitleUC("安装完毕");
                SetupCompletedCommand command = new SetupCompletedCommand(m_form);
                m_form.AddBodyUC(command);
                m_form.CurrentCommand = command;

                m_form.SetNextButtonToClose();
            }
            catch (Exception)
            {
                MessageBox.Show("安装包错误,安装程序终止");
                m_form.Abort();
            }
        }
 //functions
 public static ArrayList calcAddressesSE(IPAddress start, IPAddress end, ProgressBar progress)
 {
     ArrayList addresses = new ArrayList();
     addresses.Add(start);
     if (start.Equals(end))return addresses;
     UInt32 h = 0;
     if (progress != null)
     {
         progress.Value = 0;
         progress.Maximum = (int)(convertIPtoUInt32(end) - convertIPtoUInt32(start));
         Log.WriteLog("Progressbar Maximum (clacAddressesSE): " + progress.Maximum);
     }
     while (!(start.Equals(end)))
     {
         h = convertIPtoUInt32(start);
         h++;
         if (progress != null) progress.PerformStep();
         start = IPAddress.Parse(Convert.ToString(h));
         addresses.Add(start);
     }
     return addresses;
 }
예제 #28
0
        } // GenerateFontBitmap

        void GetFontFromBitmap()
        {
            int border = (int)BorderSize.Value;

            ImportProgress.Visible = true;
            ImportProgress.Minimum = MinChar;
            ImportProgress.Maximum = MaxChar;
            ImportProgress.Value   = MinChar;
            ImportProgress.Step    = 1;
            for (int i = MinChar; i <= MaxChar; i++)
            {
                FontChar  c   = (FontChar)Chars[i - MinChar];
                Rectangle rct = new Rectangle(c.X, c.Y, c.Width, c.Height);
                if (rct.Width == 0)
                {
                    continue;
                }
                c.Bmp = Bmp.Clone(rct, PixelFormat.Format32bppArgb);
                ImportProgress.PerformStep();
                ImportProgress.Update();
            }
            ImportProgress.Visible = false;
            Update();
        } // GetFontFromBitmap
예제 #29
0
 /// <summary>
 /// Reset progress bar.
 /// </summary>
 /// <param name="control"></param>
 public static void ResetProgressBar(ProgressBar control)
 {
     if (control.InvokeRequired)
     {
         control.Invoke((System.Action)(() =>
         {
             control.PerformStep();
         }));
     }
     else
     {
         control.PerformStep();
     }
 }
 /// <summary>
 /// Этот метод производит обработку данных ПС киберплат. На вход подается массив ссылок на киберплат Links. 
 /// Остальные три параметра - граф. эл-ты соответсвующего типа.
 /// </summary>
 /// <param name="Links">Массив ссылок на киберплат</param>
 /// <param name="dataBox">Поле, в которое выводится лог.</param>
 /// <param name="progress">Прогресбар 1</param>
 /// <param name="progress2">Прогресбар 2</param>
 /// <returns>Возвращает сумму за текущий час в строковом формате с запятой.</returns>
 public static string cyberplatProcessing(string[] Links, TextBox dataBox, ProgressBar progress, ProgressBar progress2)//обработка киберплата
 {
     double summa = 0;
     string tmpTime = "";
     string s1 = "";
     string s2 = "";
     string s3 = "";
     string s4 = "";
     for (int i = 0; i < 20; i++)
     {
         Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
         NumberStyles styles;
         styles = NumberStyles.AllowParentheses | NumberStyles.AllowTrailingSign | NumberStyles.Float | NumberStyles.AllowThousands;
         tmpTime = cybertime;
         if (tmpTime != "") { s3 = tmpTime.Remove(3, 2); }
         s1 = Downloader.Download(Links[i]);
         s2 = s1.Substring(s1.IndexOf("Всего") + 228, 100);               //поиск слова "Всего" в документе и сдвиг на 228 символов от него(несколько строк вниз) и выемка 50 символов
         Regex regex = new Regex("([0-9]+.+[0-9])");                       //регулярка для поиска числа в строке
         Match match = regex.Match(s2);
         if (match.Value != "")
         {
             summa = summa + Double.Parse(match.Value, styles);
             dataBox.AppendText(regions[i] + "\n");
             dataBox.AppendText(match.Value + "\n");// вывод в textBox2
             dataBox.AppendText((s1.Substring(s1.IndexOf("Данные отчета актуальны"), 49)).Replace("<b>&nbsp;", " ") + "\n");
             dataBox.AppendText("\n");
             cybertime = ((s1.Substring(s1.IndexOf("Данные отчета актуальны")+44, 5)));
             if (cybertime != "") { s4 = cybertime.Remove(3, 2); }
             if (i >0 & s3 != s4)
             {
                 progress.Value = 0;
                 progress2.Value = 0;
                 return cyberplatProcessing(Links,  dataBox,  progress,  progress2);
             }
         }
         else
         {
             summa = summa + 0;
             dataBox.AppendText(regions[i] + "\n");
             dataBox.AppendText("0.00" + "\n");
             dataBox.AppendText("Отчёт ещё не сформирован" + "\n");
             dataBox.AppendText("\n");
         }
         progress.PerformStep();
         progress2.PerformStep();
     }
     dataBox.AppendText("Данные сняты");
     string result = (summa.ToString()).Replace(".", ",");//замена точки на запятую(для удобства)
     return result;
 }
예제 #31
0
        /// <summary>
        /// Perform a progress step
        /// </summary>
        public void PerformStep()
        {
            CheckDisposed();

            m_ProgressBar.PerformStep();
        }
예제 #32
0
		public void Styles ()
		{
			ProgressBar c = new ProgressBar ();
			//--
			Assert.AreEqual(ProgressBarStyle.Blocks, c.Style, "orig=blocks");
			//--
			c.Style = ProgressBarStyle.Continuous;
			//--
			c.Style = ProgressBarStyle.Marquee;
			// Increment and PerformStep are documented to fail in Marquee style.
			try {
				c.Increment (5);
				Assert.Fail ("should have thrown -- Increment");
			} catch (InvalidOperationException) {
			}
			try {
				c.PerformStep ();
				Assert.Fail ("should have thrown -- PerformStep ");
			} catch (InvalidOperationException) {
			}
			// What about the other value-related properties?  No fail apparently!
			c.Value = 20;
			c.Minimum = 5;
			c.Maximum = 95;
			//--
			// Now undefined style values...
			try {
				c.Style = (ProgressBarStyle)4;
				Assert.Fail("should have thrown -- bad style4");
			} catch (global::System.ComponentModel.InvalidEnumArgumentException ex) {
				//Console.WriteLine(ex.Message);
				Assert.AreEqual(typeof(global::System.ComponentModel.InvalidEnumArgumentException), ex.GetType (), "Typeof bad style4");
				Assert.AreEqual("value", ex.ParamName, "ParamName bad style 4");
			}
			try {
				c.Style = (ProgressBarStyle)99;
				Assert.Fail("should have thrown -- bad style99");
			} catch (global::System.ComponentModel.InvalidEnumArgumentException ex) {
				Assert.AreEqual (typeof(global::System.ComponentModel.InvalidEnumArgumentException), ex.GetType (), "Typeof bad style99");
				Assert.AreEqual ("value", ex.ParamName, "ParamName bad style 99");
			}
		}
예제 #33
0
 public static int ExtractMessage(Bitmap bitmap, out MemoryStream messageStream, ProgressBar progressBar)
 {
     //Read the length of the file
     Color pixel = bitmap.GetPixel(0, 0);
     int fileLength = (pixel.R << 16) + (pixel.G << 8) + pixel.B;
     //Check if file length is within the allowed range
     if (fileLength >= (16777216)/8)
     {
         MessageBox.Show("You've chosen the wrong image, it does not contain file gidden with this software",
             "Warning", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
         messageStream = new MemoryStream();
         return 0;
     }
     //Check if file length is not bigger than the number of pixels
     if (fileLength >= 3 * (bitmap.Size.Height * bitmap.Size.Width - 1))
     {
         MessageBox.Show("Your image can not contain file encrypted with this application",
             "Warning", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
         messageStream = new MemoryStream();
         return 0;
     }
     //Set maximum value of progress bar
     progressBar.Maximum = fileLength;
     //Initialize memory stream
     messageStream = new MemoryStream(fileLength);
     //initialize x and y coordinates of pixel
     int x = 1;
     int y = 0;
     int val = 0; //0 - R, 1 - G, 2 - B
     byte message = (byte)0; //bits will be stored in this variable
     //initialize mask to get the value of the last bit in the pixel
     byte mask = (byte)Convert.ToInt32("00000001", 2);
     pixel = bitmap.GetPixel(x, y); //get next pixel in the image
     for (int i = 0; i < fileLength; i++) //loop through the image until all bytes are read
     {
         for (int j = 0; j < 8; j++) //get the next byte
         {
             switch (val)//read R - 0, G - 1, or B - 2 channel of a pixel
             {
                 case 0:
                     message = (byte)(message | ((pixel.R & mask) << j));
                     val++;
                     break;
                 case 1:
                     message = (byte)(message | ((pixel.G & mask) << j));
                     val++;
                     break;
                 case 2:
                     message = (byte)(message | ((pixel.B & mask) << j));
                     updateXY(ref x, ref y, bitmap);
                     pixel = bitmap.GetPixel(x, y);
                     val = 0;
                     break;
             }
         }
         //Write byte to the stream
         messageStream.WriteByte(message);
         //reset byte
         message = (byte)0;
         //update progress bar
         progressBar.PerformStep();
     }
     return 1;
 }
예제 #34
0
        // ------------------------------------------------------------------------------------------------------------------------------------------------------------------ Построение таблицы
        private static void Graph_China(Image[] img, PictureBox pictureBox01,  ProgressBar progressBar1, int Diag, Point p, int x0_end, int x1_end, int y0_end, int y1_end, int rb, int pr_obr)
        {
            int max_x = (n1+n2)*scale, max_y = 800;
            int w1 = n2, hh = n1;

            f_sin = new Form();
            f_sin.Size = new Size(max_x + 8, max_y + 8);
            f_sin.StartPosition = FormStartPosition.Manual;
            f_sin.Location = p;

            pc1 = new PictureBox();
            pc1.BackColor = Color.White;
            pc1.Location = new System.Drawing.Point(0, 8);
            pc1.Size = new Size(max_x, max_y);
            pc1.SizeMode = PictureBoxSizeMode.StretchImage;
            pc1.BorderStyle = BorderStyle.Fixed3D;

            Bitmap btmBack = new Bitmap(max_x + 8, max_y + 8);      //изображение
            Graphics grBack = Graphics.FromImage(btmBack);

            pc1.BackgroundImage = btmBack;

            f_sin.Controls.Add(pc1);

            Pen p1 = new Pen(Color.Black, 1);
            Pen p2 = new Pen(Color.Red, 1);
            Pen p3 = new Pen(Color.Blue, 1);
            Pen p4 = new Pen(Color.Gold, 1);
            Pen p5 = new Pen(Color.Yellow, 1);
            Font font = new Font("Arial", 16, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);
            //Font font = new Font(FontFamily.GenericSansSerif, 12.0F, FontStyle.Regular);
            //Font font = new Font("Verdana", 14, FontStyle.Regular);

            grBack.DrawLine(p1, x0, y0, x0, hh * scale + y0);
            grBack.DrawLine(p1, x0, hh * scale + y0, 2 * w1 * scale + x0, hh * scale + y0);

            grBack.DrawLine(p1, w1 * scale + x0, hh * scale + y0, w1 * scale + x0, y0);
            grBack.DrawLine(p1, w1 * scale + x0, y0, x0, y0);

            StringFormat drawFormat = new StringFormat(StringFormatFlags.NoClip);
            //drawFormat.LineAlignment = StringAlignment.Near ;  //   .Center;
               // drawFormat.FormatFlags = StringFormatFlags.DirectionVertical;

            string s = n2.ToString(); grBack.DrawString("b2 " + s, font, new SolidBrush(Color.Black), w1 * scale + x0 + 8, y0 - 8, drawFormat);
            s = n1.ToString(); grBack.DrawString("b1 " + s, font, new SolidBrush(Color.Black), x0, hh * scale + 20 + 10 * scale, drawFormat);
            // ----------------------------------------------------------------------------------------------------------------
            for (int i = 0; i < n1 + n2; i++) { glbl_faze[i] = -1; glbl_faze1[i] = -1; }                                              // Массив для расшифровки

            Int32 A = Diag * Math.Max(n1, n2);
            Int32 pf;
            for (int b2 = 0; b2 < n2; b2++)                                                                    // Диагонали
            {
                pf = M2 * N2 * b2 % (n1 * n2);
                if (pf < A) { grBack.DrawLine(p2, x0 + b2 * scale, y0, x0 + b2 * scale + n1 * scale, hh * scale + y0);
                              pf = pf / n1;
                              glbl_faze[n1 + b2] = pf;
                              s = pf.ToString();    grBack.DrawString(s, font, new SolidBrush(Color.Black), x0 + b2 * scale, y0 - 4 * scale, drawFormat);
                            }
            }
            for (int b1 = 0; b1 < n1; b1++)
            {
                pf = M1 * N1 * b1 % (n1 * n2);
                if (pf < A) { grBack.DrawLine(p3, x0, y0 + b1 * scale, x0 + n1 * scale - b1 * scale, hh * scale + y0);
                              pf = pf / n1;
                              glbl_faze[n1 - b1] = pf;
                              s = pf.ToString();    grBack.DrawString(s, font, new SolidBrush(Color.Black), x0 - 10 * scale, y0 + b1 * scale, drawFormat);
                            }
            }

            for (int i = 0; i < n1 + n2; i++)
            {
                int bb = glbl_faze[i];
                if (bb >= 0) { s = bb.ToString(); grBack.DrawString(s, font, new SolidBrush(Color.Black), x0 + i * scale, y0 + n1*scale + 8 * scale, drawFormat); }
            }

            int mxx = 0, mxx_x = 0, mnx = 0, mnx_x = 0, cntr = 0;
            for (;;)
            {
                for (int i = mnx_x; i < n1 + n2; i++)
                {
                    cntr = i;
                    int bb = glbl_faze[i]; if (bb >= 0 && bb != mnx) { mxx = bb; mxx_x = i; break; }
                }
                if (cntr >= n1 + n2 - 1) break;
                //MessageBox.Show(" mnx =  " + mnx.ToString() + " mxx =  " + mxx.ToString());
               int m = (mxx_x - mnx_x) /2;
               for (int j = mnx_x; j < mnx_x + m; j++) glbl_faze1[j] = mnx;
               for (int j = mnx_x + m; j < mxx_x; j++) glbl_faze1[j] = mxx;
               mnx_x = mxx_x;
               mnx = mxx;

            }

            mnx = glbl_faze1[0];
            for (int i = 0; i < n1 + n2; i++)
            {
                int bb = glbl_faze1[i];
                if (bb != mnx)
                   { mnx = bb;
                     grBack.DrawLine(p4, x0 + i * scale, y0 + hh * scale, x0, y0 + hh * scale - i * scale);
                     //grBack.DrawLine(p4, x0 + i * scale, y0 + hh * scale, x0 + i * scale, y0 );
                   }
            }

            //---------------------------------------------------------------------------------------------------------------
            int r, g, b;
            int w = img[0].Width;
            int h = img[0].Height;
            Bitmap bmp1 = new Bitmap(img[0], w, h);
            Bitmap bmp2 = new Bitmap(img[1], w, h);
            Bitmap bmp3 = new Bitmap(img[2], w, h);
            Bitmap bmp  = new Bitmap(pictureBox01.Image, w, h);

            int[,] bmp_r = new int[n2+3, n1+3];
            int[,] bmp_line = new int[n2 + 3, n1 + 3];
            int[] ims1 = new int[h];
            int[] ims2 = new int[h];
            int[] ims3 = new int[h];

            Color c, c1;

            progressBar1.Visible = true;
            progressBar1.Minimum = 1;
            progressBar1.Maximum = w1;

            progressBar1.Step = 1;

            int xx0 = 0,  yy0 = 0;
            int xx1 = w,  yy1 = h;

            if ((x0_end < x1_end) && (y0_end < y1_end)) { xx0 = x0_end; xx1 = x1_end; yy0 = y0_end; yy1 = y1_end; }

            Int32 count = 0;
            progressBar1.Value = 1;
            if (rb == 1)                                             // ------------- По фигуре из 3 квадрата
                for (int i = xx0; i < xx1; i++)
                {

                    for (int j = yy0; j < yy1; j++)
                    {
                            c1 = bmp3.GetPixel(i, j);
                            if (c1.R == 0) ims3[j] = 0;
                            else
                            {
                                ims3[j] = 1;
                                c = bmp1.GetPixel(i, j); r = c.R; ims1[j] = (int)((double)(r * (n1 - 1)) / 255);  //(b2)
                                c = bmp2.GetPixel(i, j); r = c.R; ims2[j] = (int)((double)(r * (n2 - 1)) / 255);  //(b1)
                            }

                    }

                    for (int j = yy0; j < yy1; j++)
                    {
                        if (ims3[j] != 0) { r = ims1[j]; g = ims2[j]; bmp_r[g, r]++; count++; }
                    }
                    progressBar1.PerformStep();
                }
            if (rb == 0)                                               // --------- По квадратной области
                for (int i = xx0; i < xx1; i++)
                {

                    for (int j = yy0; j < yy1; j++)
                    {
                            c = bmp1.GetPixel(i, j); r = c.R; ims1[j] = (int)((double)(r * (n1 - 1)) / 255);  //(b2)
                            c = bmp2.GetPixel(i, j); r = c.R; ims2[j] = (int)((double)(r * (n2 - 1)) / 255);  //(b1)
                    }

                    for (int j = yy0; j < yy1; j++)
                    {
                         r = ims1[j]; g = ims2[j]; bmp_r[g, r]++; count++;
                    }
                    progressBar1.PerformStep();
                }

            Int32 ib2=0, ib1=0, max_count = 0;
            progressBar1.Value = 1;
             for (ib2 = 0; ib2 < n2-1; ib2++)
              {
                 for (ib1 = 0; ib1 < n1 - 1; ib1++) { b = bmp_r[ib2, ib1]; if (b > max_count) max_count = b; }
                 progressBar1.PerformStep();
              }
            progressBar1.Value = 1;   // Рисование точек по диагоналям

            int mn1 = pr_obr;         // pr_obr - это уровень обрезания. Ниже этих значений не отображается

               // int mn = (max_count-mn1)/20;
               // int mn2 = mn1 + mn;
               // int mn3 = mn2 + mn;
            MessageBox.Show(" count =  " + count.ToString() + " max =  " + max_count.ToString()  );

            for (ib2 = 0; ib2 < n2-1; ib2++)
            {
              for ( ib1 = 0; ib1 < n1-1; ib1++)
                    { b = bmp_r[ib2, ib1];
                      if (b > mn1)
                           {
                                //if (b > mn3 )            grBack.DrawRectangle(new Pen(Color.FromArgb(255, 255, 255)), x0 + ib2 * scale /*+ 2 * scale*/, y0 + ib1 * scale, 1, 1);
                                //if (b > mn2 && b <=mn3)  grBack.DrawRectangle(new Pen(Color.FromArgb(0, 0, 255)), x0 + ib2 * scale /*+ 2 * scale*/, y0 + ib1 * scale, 1, 1);
                                //if (b <= mn2) grBack.DrawRectangle(new Pen(Color.FromArgb(255, 0, 0)), x0 + ib2 * scale /*+ 2 * scale*/, y0 + ib1 * scale, 1, 1);
                                grBack.DrawRectangle(new Pen(Color.FromArgb(255, 0, 0)), x0 + ib2 * scale /*+ 2 * scale*/, y0 + ib1 * scale, 1, 1);
                           }
                    }
                  progressBar1.PerformStep();
              }

            pc1.Refresh();
            f_sin.Show();

            /*
                        if (MessageBox.Show("Закончить нумерацию?", "Нумерация полос", MessageBoxButtons.OKCancel) == DialogResult.OK) {  return; }

                        int ii_max = Num_Line(bmp_r, bmp_line, grBack);                  // -------------------------------------------- Нумерация полос

                        // -------------------------------------------------------------------------------------------------------------------------------

                                                                     // Рисование точек по диагоналям
                        for (ib2 = 0; ib2 < n2; ib2++)
                        {
                            for (ib1 = 0; ib1 < n1; ib1++)
                            {
                                b = bmp_line[ib2, ib1];
                                if (b != 0) grBack.DrawRectangle(new Pen(Color.FromArgb(255, 0, 0)), x0 + ib2 * scale , y0 + ib1 * scale, 2, 2);
                            }

                        }

                        Pen p6 = new Pen(Color.Green, 1);
                        Pen p7 = new Pen(Color.Green, 2);

                        for (int i = 1; i <= ii_max; i++)  // ----------------------------------------------------------------------- Рисование наклонных границ и внизу границ glbl_faze[n1+n2]
                        {
                            int max = 0;   int min = n2 + n1; for (int j = 0; j < n2 + n1; j++) { b = glbl_faze[j]; if (b == i) { if (j > max) max = j; if (j < min) min = j; } }
                            for (int j = min; j <= max; j++) glbl_faze[j] = i;
                            grBack.DrawLine(p6, x0 + min * scale, y0 + n1 * scale, x0 + min * scale - n1 * scale, y0);
                            grBack.DrawLine(p6, x0 + max * scale, y0 + n1 * scale, x0 + max * scale - n1 * scale, y0);
                            grBack.DrawLine(p7, x0 + min * scale, y0 + n1 * scale + 2 * scale, x0 + max * scale, y0 + n1 * scale + 2 * scale);

                            int b1 = number_2pi[i];
                            s = i.ToString() + " ( " + b1.ToString() + " )";
                            int min2 = (max - min) / 2;
                            grBack.DrawString(s, font, new SolidBrush(Color.Black), x0 + (min+min2) * scale, y0 + n1 * scale + 2 * scale, drawFormat);
                        }

                        Rash_glbl_faze();  // ----------------------------------------------------------------------------------------- Расширение полос

                        Pen p8 = new Pen(Color.Blue, 2);

                        //s = "glbl_faze - ";
                        //for (int k = 0; k < n2 + n1; k++) { b = glbl_faze[k]; s = s + " " + b.ToString(); if (k % 10 == 0) s = s + "\n"; }
                        //MessageBox.Show(s);
                        //string s1  = "glbl_faze1 - ";
                        for (int i = 0 ;  i<n2+n1 ; )
                        {
                            int b1 = glbl_faze[i];
                            int max = i; int min = i;
                            for (int j = i; j < n2 + n1; j++) { b = glbl_faze[j]; if (j > max) max = j; if (b != b1) break; }

                            grBack.DrawLine(p8, x0 + min * scale, y0 + n1 * scale + 7 * scale, x0 + max * scale, y0 + n1 * scale + 7 * scale);
                            s = b1.ToString(); // +" ( " + b1.ToString() + " )";
                            int min2 = (max - min) / 2;
                            grBack.DrawString(s, font, new SolidBrush(Color.Black), x0 + (min + min2) * scale, y0 + n1 * scale + 7 * scale, drawFormat);
                            i =  max+1;

                        }
                      MessageBox.Show(" Всего " + ii_max.ToString() + " полос ");

                        pc1.Refresh();
                        f_sin.Show();
             */
        }
예제 #35
0
        public void CreateTileMap(ProgressBar _progressbarProcess)
        {
            CTile _Tile = null;

            for (int i = 0; i < this.m_BitMap.Height / CTile.HEIGHT_TILE; ++i)
            {
                for (int j = 0; j < this.m_BitMap.Width / CTile.WIDTH_TILE; ++j)
                {
                    _Tile = new CTile(GetTile(j, i), CTile.CountID);

                    if (this.m_TileMap.Count == 0)
                    {
                        this.m_TileMap.Add(_Tile);
                        this.m_ArrMap[i, j] = CTile.CountID;
                        Bitmap a = new Bitmap(CTile.WIDTH_TILE, CTile.HEIGHT_TILE);
                        for (int y = 0; y < CTile.HEIGHT_TILE; y++)
                        {
                            for (int x = 0; x < CTile.WIDTH_TILE; x++)
                            {
                                a.SetPixel(x, y, _Tile.ArrPixel[y, x]);
                            }
                        }
                        a.Save(CTile.CountID.ToString() + ".png");
                        ++CTile.CountID;
                    }
                    else
                    {
                        for (int k = 0; k < this.m_TileMap.Count; ++k)
                        {
                            if (CTile.CompareTile(_Tile, this.m_TileMap[k]) == true)
                            {
                                this.m_ArrMap[i, j] = this.m_TileMap[k].ID;
                                break;
                            }

                            if (k == this.m_TileMap.Count - 1)
                            {
                                this.m_TileMap.Add(_Tile);
                                this.m_ArrMap[i, j] = CTile.CountID;
                                Bitmap a = new Bitmap(CTile.WIDTH_TILE, CTile.HEIGHT_TILE);
                                for (int y = 0; y < CTile.HEIGHT_TILE; y++)
                                {
                                    for (int x = 0; x < CTile.WIDTH_TILE; x++)
                                    {
                                        a.SetPixel(x, y, _Tile.ArrPixel[y, x]);
                                    }
                                }
                                a.Save(CTile.CountID.ToString() + ".png");
                                ++CTile.CountID;
                            }
                        }
                    }

                    _progressbarProcess.PerformStep();
                }

            }
        }
예제 #36
0
 void Button5Click(object sender, System.EventArgs e)
 {
     progressBar.PerformStep();
 }
예제 #37
0
 private void CrearProgressBars(int sX, int sY, int sAltura, int sAncho)
 {
     pb= new System.Windows.Forms.ProgressBar();
     pb.SetBounds(sX, sY, sAncho, sAltura);
        // pb.Parent = this;
     pb.Visible = true;
     pb.CreateControl();
     pb.Maximum = 100;
     pb.Minimum = 0;
     pb.Name = "progressBar";
     pb.Step = 1;
     pb.Value = 1;
     pb.PerformStep();
 }
        private void LoadMenuElements(ToolStripDropDownItem tools, DelegGetAll d, string text, ProgressBar bar)
        {
            Status.Text = text;
            Application.DoEvents();
            tools.DropDownItems.Clear();
            Array t = d();
            if (t.GetType() == typeof(FacultyInfo[]))
            {
                var temp = t as FacultyInfo[];
                Array.Sort(temp, new Model.MyComparerName().Compare);
                t = temp;
            }
            if (t.GetType() == typeof(TeacherInfo[]))
            {
                var temp = t as TeacherInfo[];
                Array.Sort(temp, new Model.MyComparerName().Compare);
                t = temp;
            }
            if (t.GetType() == typeof(LocationInfo[]))
            {
                var temp = t as LocationInfo[];
                Array.Sort(temp, new Model.MyComparerName().Compare);
                t = temp;
            }

            foreach (var fac in t)
            {
                if (bar != null)
               		bar.PerformStep();
                var tool = new ToolStripMenuItem(fac.ToString());
                tool.Click += MenuItem_Click;
                tool.Tag = fac;
                tools.DropDownItems.Add(tool);
            }
        }
        //Scan all Clients in current System Inevntory for Details
        private void scanDetails(ProgressBar progress)
        {
            //Prepare known license types
            Dictionary<string, int> licenses = new Dictionary<string, int>();
            foreach (License l in list_allAvailableLicenses)
            {
                if (!licenses.ContainsKey(l.Name))
                {
                    licenses.Add(l.Name, l.LicenseNumber);
                }
            }
            Log.WriteLog("Scanning Details");
            //Get IP of local Host because the wmi conection differs
            IPAddress[] localhost = Dns.GetHostAddresses("");
            ArrayList localadrresses = new ArrayList();
            foreach (IPAddress ip in localhost)
            {   //only IPv4
                if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                {
                    localadrresses.Add(ip.ToString());
                    Log.WriteLog(string.Format("Local Adresses: {0}", ip.ToString()));
                }
            }
            if (progress != null)
            {
                progress.Value = 0;
                progress.Maximum = currentSystemInventory.List_Systems.Count;
            }

            foreach (ClientSystem c in currentSystemInventory.List_Systems)
            {
                //Connect via WMI
                string host = c.ClientIP.ToString();
                Log.WriteLog(string.Format("Connecting to {0}", host));
                ConnectionOptions options = new ConnectionOptions();
                options.Username = username;
                options.Password = password;
                ManagementScope scope;
                //Localhost don't need credentials
                if (localadrresses.Contains(host))
                {
                    scope = new ManagementScope("\\\\" + host + "\\root\\cimv2");
                }
                else
                {
                    scope = new ManagementScope("\\\\" + host + "\\root\\cimv2", options);
                }
                try
                {
                    scope.Connect();
                    //Query Operating System Informations
                    ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_OperatingSystem");
                    ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
                    ManagementObjectCollection queryCollection = searcher.Get();
                    foreach (ManagementObject m in queryCollection)
                    {
                        //Computername
                        Log.WriteLog(string.Format("Computer Name : {0}", m["csname"]));
                        c.Computername = (string)m["csname"];
                        //Operatingsystem
                        Log.WriteLog(string.Format("Operating System: {0}", m["Caption"]));
                        c.Type = (string)m["Caption"];
                        //OperatingSystemSerial
                        Log.WriteLog(string.Format("SerialNumber : {0}", m["SerialNumber"]));
                        c.Serial = (string)m["SerialNumber"];
                    }
                    //Check if it is an unknow license type
                    if (!licenses.ContainsKey(c.Type))
                    {
                        //licensetype unknown, learn it
                        License newlicense = new License(list_allAvailableLicenses.Count, c.Type);
                        list_allAvailableLicenses.Add(newlicense);
                        db.SaveLicense(newlicense);
                        licenses.Add(newlicense.Name, newlicense.LicenseNumber);
                        Log.WriteLog("Neue Lizenz gelernt: " + newlicense.Name);
                    }
                }
                catch (System.Runtime.InteropServices.COMException e)
                {
                    //Der RPC-Server ist nicht verfügbar. (Ausnahme von HRESULT: 0x800706BA)
                    Log.WriteLog(string.Format("COM-Fehler bei der WMI Abfrage: {0}", e.Message));
                }
                catch (ManagementException e)
                {
                    //Fehler beim der WMI Abfrage: Zugriff verweigert. 
                    Log.WriteLog(string.Format("Zugriffs-Fehler bei der WMI Abfrage: {0}", e.Message));
                }
                catch (Exception e)
                {
                    Log.WriteLog(string.Format("AllgemeinerFehler bei der WMI Abfrage: {0}", e.Message));
                }
                if (c.Type != null)
                {
                    db.UpdateClientSystem(c);
                }
                if (progress != null) progress.PerformStep();
            }
        }
예제 #40
0
        public static void Sum_Color(Image[] img, int k1, int k2, int k3, ProgressBar progressBar1)
        {
            int w1 = img[k1-1].Width;
            int h1 = img[k1-1].Height;
            Bitmap bmp1 = new Bitmap(img[k1-1], w1, h1);

            int w2 = img[k2 - 1].Width;
            int h2 = img[k2 - 1].Height;
            Bitmap bmp2 = new Bitmap(img[k2 - 1], w2, h2);

            w1 = (int)Math.Min(w1, w2);
            h1 = (int)Math.Min(h1, h2);

            Bitmap bmp3 = new Bitmap(img[k3 - 1], w1, h1);

            Color c1,c2;
            int r1, r2, rs , rg, rb;

            progressBar1.Visible = true;
            progressBar1.Minimum = 1;
            progressBar1.Maximum = w1;
            progressBar1.Value = 1;
            progressBar1.Step = 1;

            for (int i = 0; i < w1; i++)
            {
                for (int j = 0; j < h1; j++)
                {
                    c1 = bmp1.GetPixel(i, j);
                    c2 = bmp2.GetPixel(i, j);
                    r1 = c1.R; r2 = c2.R; rs = r1 + r2; if (rs > 255) rs = 255;
                    r1 = c1.G; r2 = c2.G; rg = r1 + r2; if (rg > 255) rg = 255;
                    r1 = c1.B; r2 = c2.B; rb = r1 + r2; if (rb > 255) rb = 255;
                    bmp3.SetPixel(i, j, Color.FromArgb(rs, rg, rb));
                }
                //pictureBox1.Image = bmp3;
                progressBar1.PerformStep();
            }
            img[k3 - 1] = bmp3;
        }
 //scan Network for Clients
 private void scanNetwork(ProgressBar progress)
 {
     //Create a new system Inventory
     currentSystemInventory = CreateSystemInventroy(currentCustomer.Cnumber);
     Log.WriteLog("New SystemInventory created");
     //Get the latest systemnumber
     int latestsystemnumber;
     //only if there is no data, set it manually
     if (list_systems.Count <= 0)
     {
         latestsystemnumber = 0;
     }
     else
     {
         currentSystem = (ClientSystem)list_systems[list_systems.Count - 1];
         latestsystemnumber = currentSystem.ClientSystemNumber;
     }
     //Get number adresses
     int i = 0;
     foreach (Network n in selectedNetworks)
     {
         foreach (IPAddress ip in n.IpAddresses) i++;
     }
     if (progress != null)
     {
         progress.Value = 0;
         progress.Maximum = i;
     }
     //scan Networks
     Dictionary<String, IPAddress> unique = new Dictionary<string, IPAddress>();
     foreach (Network n in selectedNetworks)
     {
         // Ping each ip address of the network with timeout of 100ms
         foreach (IPAddress ip in n.IpAddresses)
         {
             try
             {
                 if (progress != null) progress.PerformStep();
                 unique.Add(ip.ToString(), ip);
                 Ping pingSender = new Ping();
                 PingReply reply = pingSender.Send(ip, 100);
                 Log.WriteLog(string.Format("Ping: {0}", ip.ToString()));
                 if (reply.Status == IPStatus.Success)
                 {
                     currentSystem = new ClientSystem(++latestsystemnumber, ip, n.NetworkNumber);
                     list_systems.Add(currentSystem);
                     db.SaveClientSystem(currentSystem, currentSystemInventory);
                     currentSystemInventory.AddSystemToInventory(currentSystem);
                     Log.WriteLog(string.Format("System {0} added to Systeminventory",
                         currentSystem.ClientIP.ToString()));
                 }
             }
             //If dictionary contains key already
             catch (ArgumentException e)
             {
                 Log.WriteLog(string.Format("IP-Addresse already in list: {0}", ip.ToString()));
                 Log.WriteLog(e.Message);
             }
         }
     }
 }
예제 #42
0
        /*
         * Methods
         */

        public void PerformStep()
        {
            progressBar1.PerformStep();
        }
 public void PerformStep()
 {
     Bar.PerformStep();
     UpdateLabel();
 }
예제 #44
0
        public string BuscaRetorno(tcIdentificacaoPrestador Prestador, KryptonLabel lblStatus, ProgressBar ProgresStatus)
        {

            bool parar = false;
            Globais glob = new Globais();
            string sMensagemErro = "";
            int iCountBuscaRet = 0;

            ProgresStatus.Step = 1;
            ProgresStatus.Minimum = 0;
            ProgresStatus.Maximum = 20;
            ProgresStatus.MarqueeAnimationSpeed = 20;
            ProgresStatus.Value = 0;

            try
            {
                for (; ; )
                {
                    ProgresStatus.PerformStep();
                    ProgresStatus.Refresh();
                    lblStatus.Text = "Sistema tentando buscar retorno!!" + Environment.NewLine + "Tentativas: " + iCountBuscaRet.ToString() + " de 21";
                    lblStatus.Refresh();
                    string sRetConsulta = BuscaRetornoWebService(Prestador);
                    XmlDocument xmlRet = new XmlDocument();
                    xmlRet.LoadXml(sRetConsulta);

                    XmlNodeList xNodeList = xmlRet.GetElementsByTagName("ns4:MensagemRetorno");

                    if (xNodeList.Count > 0)
                    {
                        sMensagemErro = "{3}Lote: " + NumeroLote + "{3}{3}Código: {0}{3}{3}Mensagem: {1}{3}{3}Correção: {2}{3}{3}Protocolo: " + Protocolo;

                        foreach (XmlNode node in xNodeList)
                        {
                            sCodigoRetorno = node["ns4:Codigo"].InnerText;

                            if (sCodigoRetorno.Equals("E4") && iCountBuscaRet <= 20)
                            {
                                iCountBuscaRet++;
                            }
                            else
                            {
                                sMensagemErro = string.Format(sMensagemErro, node["ns4:Codigo"].InnerText,
                                                      "Esse RPS ainda não se encontra em nossa base de dados.",
                                                      node["ns4:Correcao"].InnerText, Environment.NewLine);
                                parar = true;
                            }
                        }
                    }
                    else if (xmlRet.GetElementsByTagName("ns3:CompNfse").Count > 0)
                    {
                        this.sCodigoRetorno = "";
                        sMensagemErro = "";
                        Globais objGlobais = new Globais();
                        bool bAlteraDupl = Convert.ToBoolean(objGlobais.LeRegConfig("GravaNumNFseDupl"));


                        for (int i = 0; i < xmlRet.GetElementsByTagName("ns3:CompNfse").Count; i++)
                        {
                            #region Salva Arquivo por arquivo
                            string sPasta = Convert.ToDateTime(xmlRet.GetElementsByTagName("ns4:InfNfse")[i]["ns4:DataEmissao"].InnerText).ToString("MM/yy").Replace("/", "");
                            //Numero da nota no sefaz + numero da sequencia no sistema
                            string sNomeArquivo = sPasta + (xmlRet.GetElementsByTagName("ns4:InfNfse")[i]["ns4:Numero"].InnerText.PadLeft(6, '0'))
                                                 + (xmlRet.GetElementsByTagName("ns4:IdentificacaoRps")[i]["ns4:Numero"].InnerText.PadLeft(6, '0'));

                            XmlDocument xmlSaveNfes = new XmlDocument();
                            xmlSaveNfes.LoadXml(xmlRet.GetElementsByTagName("ns4:Nfse")[i].InnerXml);
                            DirectoryInfo dPastaData = new DirectoryInfo(belStaticPastas.ENVIADOS + "\\Servicos\\" + sPasta);
                            if (!dPastaData.Exists) { dPastaData.Create(); }
                            xmlSaveNfes.Save(belStaticPastas.ENVIADOS + "\\Servicos\\" + sPasta + "\\" + sNomeArquivo + "-nfes.xml");
                            #endregion

                            objNfseRetorno = new TcInfNfse();
                            objNfseRetorno.Numero = xmlRet.GetElementsByTagName("ns4:InfNfse")[i]["ns4:Numero"].InnerText;
                            objNfseRetorno.CodigoVerificacao = xmlRet.GetElementsByTagName("ns4:InfNfse")[i]["ns4:CodigoVerificacao"].InnerText;

                            tcIdentificacaoRps objIdentRps = BuscatcIdentificacaoRps(xmlRet.GetElementsByTagName("ns4:IdentificacaoRps")[i]["ns4:Numero"].InnerText.PadLeft(6, '0'));
                            belGerarXML objBelGeraXml = new belGerarXML();


                            if (belStatic.sNomeEmpresa == "LORENZON")
                            {
                                AlteraDuplicataNumNFse(objIdentRps, xmlRet.GetElementsByTagName("ns4:InfNfse")[i]["ns4:Numero"].InnerText);
                            }

                            if (xmlRet.GetElementsByTagName("ns4:SubstituicaoNfse")[i] != null)
                            {
                                objNfseRetorno.NfseSubstituida = xmlRet.GetElementsByTagName("ns4:SubstituicaoNfse")[i]["ns4:NfseSubstituidora"].InnerText;
                            }
                            objNfseRetorno.IdentificacaoRps = objIdentRps;
                            objListaNfseRetorno.Add(objNfseRetorno);

                        }
                        parar = true;
                    }

                    if (parar) break;
                }
                return sMensagemErro;

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
예제 #45
0
        // ------------------------------------------------------------------------------------------------------ 8 bit Cуммирование
        public static void bit8sin(int k_8bit, Image[] img, PictureBox pictureBox01, ProgressBar progressBar1)
        {
            int k0 = 8 - k_8bit;

            Bitmap[] bmp_r = new Bitmap[8];
            for (int i = k0; i < 8; i++) { bmp_r[i] = new Bitmap(img[i], img[i].Width, img[i].Height); }
            int w1 = img[7].Width;
            int h1 = img[7].Height;
            Bitmap bmp2 = new Bitmap(w1, h1);

            Color  c;

            int[] cr = new int[h1];
            int[] cb = new int[h1];
            int[] cg = new int[h1];

            int[] cr1 = new int[h1];
            int[] cb1 = new int[h1];
            int[] cg1 = new int[h1];

            progressBar1.Visible = true;
            progressBar1.Minimum = 1;
            progressBar1.Maximum = w1;
            progressBar1.Value = 1;
            progressBar1.Step = 1;

            int kk;

            progressBar1.Value = 1;
            for (int i = 0; i < w1; i++)
            {
                for (int j = 0; j < h1; j++) { c = bmp2.GetPixel(i, j); cr[j] = c.R; cg[j] = c.G; cb[j] = c.B; }
                kk = k_8bit;
                for (int k = k0; k < 8; k++, kk--)
                {
                    for (int j = 0; j < h1; j++) { c = bmp_r[k].GetPixel(i, j); cr1[j] = c.R; cg1[j] = c.G; cb1[j] = c.B; }
                    for (int j = 0; j < h1; j++) { cr[j] += cr1[j] >> kk; cg[j] += cg1[j] >> kk; cb[j] += cb1[j] >> kk;   }
                 }
              for (int j = 0; j < h1; j++)
              { if (cr[j] > 255) cr[j] = 255; if (cg[j] > 255) cg[j] = 255; if (cb[j] > 255) cb[j] = 255;
                bmp2.SetPixel(i, j, Color.FromArgb(cr[j], cb[j], cg[j]));
              }
                progressBar1.PerformStep();
            }
            //Razmer(w1, h1);

            pictureBox01.Size = new System.Drawing.Size(w1, h1);
            pictureBox01.Image = bmp2;
        }
예제 #46
0
        // -------------------------- Z -> BMP
        // -----------------------------------------------------------------------------------------------------------------------------------
        static void Z_bmp(ProgressBar progressBar1, Bitmap bmp, Int32[,] Z, int w, int h)
        {
            Int32 b2_min = Z[ 1,  1], b2_max = Z[ 1,  1];
            int b2;
            for (int i = 0; i < w; i++) for (int j = 0; j < h; j++) { b2_max = Math.Max(b2_max, Z[i, j]); b2_min = Math.Min(b2_min, Z[i, j]); }

            MessageBox.Show(" Max = " + b2_max.ToString() + " Min =  " + b2_min.ToString());
            b2_max = b2_max - b2_min;             if (b2_max == 0) return;
            progressBar1.Minimum = 1;
            progressBar1.Maximum = w;
            progressBar1.Value = 1;

            for (int i = 0; i < w; i++)                                                                   //  Отображение точек на pictureBox01
            {
                for (int j = 0; j < h; j++)
                {
                    b2 = (Z[i, j] - b2_min) * 255 / b2_max;
                    if (b2 < 0 || b2 > 255) b2 = 0;
                    bmp.SetPixel(i, j, Color.FromArgb(b2, b2, b2));

                }
             progressBar1.PerformStep();
            }
        }
예제 #47
0
		/// <summary>
		/// Saves a wz file to the disk, AKA repacking.
		/// </summary>
		/// <param name="path">Path to the output wz file</param>
        /// <param name="progressBar">Progressbar, optional. (Set to null if not in use)</param>
		public void SaveToDisk(string path, ProgressBar progressBar)
		{
            WzIv = WzTool.GetIvByMapleVersion(mapleVersion);
			CreateVersionHash();
			wzDir.SetHash(versionHash);
            if (progressBar != null) { progressBar.PerformStep(); progressBar.Refresh(); } //30%
			string tempFile = Path.GetFileNameWithoutExtension(path) + ".TEMP";
			File.Create(tempFile).Close();
			wzDir.GenerateDataFile(tempFile);
			WzTool.StringCache.Clear();
            if (progressBar != null) { progressBar.PerformStep(); progressBar.Refresh(); } //40%
			uint totalLen = wzDir.GetImgOffsets(wzDir.GetOffsets(Header.FStart + 2));
			WzBinaryWriter wzWriter = new WzBinaryWriter(File.Create(path), WzIv);
			wzWriter.Hash = (uint)versionHash;
			Header.FSize = totalLen - Header.FStart;
			for (int i = 0; i < 4; i++)
				wzWriter.Write((byte)Header.Ident[i]);
            if (progressBar != null) { progressBar.PerformStep(); progressBar.Refresh(); } //50%
			wzWriter.Write((long)Header.FSize);
			wzWriter.Write(Header.FStart);
			wzWriter.WriteNullTerminatedString(Header.Copyright);
            if (progressBar != null) { progressBar.PerformStep(); progressBar.Refresh(); } //60%
			long extraHeaderLength = Header.FStart - wzWriter.BaseStream.Position;
			if (extraHeaderLength > 0)
			{
				wzWriter.Write(new byte[(int)extraHeaderLength]);
			}
            if (progressBar != null) { progressBar.PerformStep(); progressBar.Refresh(); } //70%
			wzWriter.Write(version);
			wzWriter.Header = Header;
			wzDir.SaveDirectory(wzWriter);
			wzWriter.StringCache.Clear();
			FileStream fs = File.OpenRead(tempFile);
			wzDir.SaveImages(wzWriter, fs);
			fs.Close();
            if (progressBar != null) { progressBar.PerformStep(); progressBar.Refresh(); } //80%
			File.Delete(tempFile);
			wzWriter.StringCache.Clear();
			wzWriter.Close();
            if (progressBar != null) { progressBar.PerformStep(); progressBar.Refresh(); } //90%
            GC.Collect();
            GC.WaitForPendingFinalizers();
		}
예제 #48
0
        private void FileUpdate()
        {
            string iniFile = Application.StartupPath + "\\UpdateFile.ini";

            try
            {
                this.btnOk.Enabled = false;
                FileStream fw = null;
                pbTotal.Maximum = systemUpdateTB.Rows.Count;
                pbTotal.Value   = 0;
                this.Refresh();
                for (int i = 0; i < systemUpdateTB.Rows.Count; i++)
                {
                    try
                    {
                        int    id            = Convert.ToInt32(systemUpdateTB.Rows[i]["ID"]);
                        string fileName      = systemUpdateTB.Rows[i]["name"].ToString();
                        string localVersion  = ApiFunction.GetIniString("FILEINFO", fileName, iniFile);
                        string serverVersion = systemUpdateTB.Rows[i]["Version"].ToString();
                        string fullFileName  = Application.StartupPath + "\\" + fileName;
                        string exName        = fileName.Substring(fileName.Length - 3, 3);
                        #region ...
                        //增加判断 Modify By Tany 2010-03-24
                        if ((File.Exists(Application.StartupPath + "\\SysUpdate.exe") && fileName.ToUpper() == "SYSUPDATE.EXE") ||
                            (File.Exists(Application.StartupPath + "\\SysUpdateEx.exe") && fileName.ToUpper() == "SYSUPDATEEX.EXE"))
                        {
                            //如果升级文件是自身,跳过
                            continue;
                        }
                        if (exName.Trim().ToUpper() == "RPT")
                        {
                            fullFileName = Application.StartupPath + "\\report\\" + fileName; //当前路径下的报表文件夹
                        }
                        int flag = Convert.IsDBNull(systemUpdateTB.Rows[i]["DelLocalReport"]) ? 0 : Convert.ToInt32(systemUpdateTB.Rows[i]["DelLocalReport"]);
                        #endregion
                        if (localVersion.Trim().ToUpper() != serverVersion.Trim().ToUpper())
                        {
                            lblUpdate.Text = "从旧版本(" + localVersion + ")升级到新版本(" + serverVersion + ")";
                            //DataRow dr = this.GetFileValue(id);
                            Object obj = this.GetFileValue(id);// dr["file_value"];
                            if (obj != null && !Convert.IsDBNull(obj))
                            {
                                if (File.Exists(fullFileName))
                                {
                                    File.Delete(fullFileName);
                                }
                                #region ...
                                fw = new FileStream(fullFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);

                                sttbplFiles.Text = fileName;

                                byte[] buffer     = (byte[])obj;
                                int    fileLength = (int)buffer.Length / BUFFER_LENGTH;
                                if (fileLength * BUFFER_LENGTH < buffer.Length)
                                {
                                    fileLength++;
                                }
                                pbCurrent.Maximum = fileLength;
                                pbCurrent.Value   = 0;
                                for (int j = 0; j < fileLength; j++)    //以长度为BUFFER_LENGTH字节的块进行传送
                                {
                                    if (buffer.Length - j * BUFFER_LENGTH >= BUFFER_LENGTH)
                                    {
                                        fw.Write(buffer, j * BUFFER_LENGTH, BUFFER_LENGTH);
                                    }
                                    else
                                    {
                                        fw.Write(buffer, j * BUFFER_LENGTH, buffer.Length - j * BUFFER_LENGTH);
                                    }
                                    fw.Seek(0, SeekOrigin.End);
                                    pbCurrent.Value++;
                                    this.Refresh();
                                }

                                #endregion
                                if (flag == 1)
                                {
                                    //删除指定目录下的报表文件
                                    if (File.Exists(this.CustomDirectory + "\\report\\" + fileName))
                                    {
                                        File.Delete(this.CustomDirectory + "\\report\\" + fileName);
                                    }
                                }
                                ApiFunction.WriteIniString("FILEINFO", fileName, serverVersion, iniFile);
                            }
                        }
                    }
                    catch (Exception err)
                    {
                        this.lstInfo.Items.Add(err.Message.ToString());
                        continue;
                    }
                    finally
                    {
                        pbTotal.PerformStep();
                    }
                }

                this.sttbDesc.Text = "升级成功!";
                this.btnOk.Enabled = true;

                //btnOk_Click(null, null);
            }
            catch (Exception err)
            {
                MessageBox.Show("升级失败:\n" + err.Message, "错误");
                //Process.Start(Application.StartupPath+ "\\"+mainExeName);
                this.Close();
            }
            finally
            {
                if (pConn != null && pConn.State == ConnectionState.Open)
                {
                    pConn.Close();
                }
                if (pConn != null)
                {
                    pConn.Dispose();
                }
            }
        }
예제 #49
0
        public void DownloadSpoiler(XmlDocument xSet, XmlDocument xSetLang, ListView list, ProgressBar progressBar)
        {
            mList = list;

              ListViewItem item;

              if(Directory.Exists("cards"))
            Directory.Delete("cards", true);
              Directory.CreateDirectory("cards");
              foreach(XmlNode nodeSet in xSet.DocumentElement.SelectNodes("card_sets/item"))
              {
            string setCode = nodeSet.Attributes["code"].Value;
            string setName = xSetLang.DocumentElement.SelectSingleNode("card_sets_lang/item[@code='" + setCode + "' and @language='ENG']/@name").InnerText;

            if(setCode != "M12")
              continue;

            string cardsPath = "cards\\" + setCode + ".xml";
            string cardsLangPath = "cards\\" + setCode + ".eng.xml";
            if(File.Exists(cardsPath))
              File.Delete(cardsPath);
            if(File.Exists(cardsLangPath))
              File.Delete(cardsLangPath);
            XmlDocument xCards = new XmlDocument();
            xCards.LoadXml("<cards />");
            XmlDocument xCardsLang = new XmlDocument();
            xCardsLang.LoadXml("<cards />");

            DateTime setDate = XmlConvert.ToDateTime(nodeSet.Attributes["releaseDate"].Value, "yyyy-MM-ddTHH:mm:ss");
            xCards.DocumentElement.Attributes.Append(xCards.CreateAttribute("releaseDate")).Value = setDate.ToString("yyyy-MM-ddTHH:mm:ss");
            xCards.DocumentElement.Attributes.Append(xCards.CreateAttribute("code")).Value = setCode;

            xCardsLang.DocumentElement.Attributes.Append(xCardsLang.CreateAttribute("name")).Value = setName;

            string contentTextPath = Path.Combine(Path.Combine(CARDS_DIRPATH, setCode), "CONTENT.txt");
            string contentXmlPath = Path.Combine(Path.Combine(CARDS_DIRPATH, setCode), "CONTENT.xml");
            string listPath = Path.Combine(Path.Combine(CARDS_DIRPATH, setCode), "list.xml");

            item = new ListViewItem(setCode);
            ListViewItem.ListViewSubItem subItem = item.SubItems.Add("Working...");
            mList.Items.Add(item);
            mList.EnsureVisible(mList.Items.Count - 1);
            Application.DoEvents();

            progressBar.Minimum = 0;
            progressBar.Step = 1;
            progressBar.Value = 0;

            XmlDocument xCardList = new XmlDocument();
            xCardList.Load(listPath);
            XmlDocument xContent = new XmlDocument();
            string allContent;
            if(!File.Exists(contentTextPath))
            {
              // download page content
              subItem.Text = "Downloading...";
              mList.FindForm().Refresh();
              Application.DoEvents();

              allContent = string.Empty;

              xContent.LoadXml("<content />");
              progressBar.Maximum = xCardList.SelectNodes("//card").Count;
              foreach(XmlNode cardNode in xCardList.SelectNodes("//card"))
              {
            string id = cardNode.SelectSingleNode("@id").InnerText;
            string content = Download(URL_SPOILER + id);
            allContent += content;
            XmlNode nodeContent = xContent.ImportNode(GetDocument(content).DocumentElement, true);
            xContent.DocumentElement.AppendChild(nodeContent);
            progressBar.PerformStep();
            mList.FindForm().Refresh();
            Application.DoEvents();
              }

              File.WriteAllText(contentTextPath, allContent);
              xContent.Save(contentXmlPath);
              subItem.Text = "OK!";
              mList.FindForm().Refresh();
              Application.DoEvents();
            }

            subItem.Text = "Creating...";
            mList.FindForm().Refresh();
            Application.DoEvents();

            xContent.Load(contentXmlPath);
            progressBar.Value = 0;
            progressBar.Maximum = xContent.DocumentElement.SelectNodes("td").Count;
            XmlNodeList cardListNodes = xCardList.DocumentElement.SelectNodes("card");
            XmlNodeList contentNodes = xContent.DocumentElement.SelectNodes("td");
            for(int i = 0; i < cardListNodes.Count; i++)
            {
              SpoilerReader spoilerReader = new SpoilerReader(cardListNodes[i].SelectSingleNode("@name").InnerText,
            cardListNodes[i].SelectSingleNode("@color").InnerText);
              spoilerReader.CreateCardNode(contentNodes[i], xCards, xCardsLang, setCode, setDate, i + 1);
              progressBar.PerformStep();
              mList.FindForm().Refresh();
              Application.DoEvents();
            }
            subItem.Text = "OK!";
            mList.FindForm().Refresh();
            Application.DoEvents();

            xCards.Save(cardsPath);
            xCardsLang.Save(cardsLangPath);
              }
        }
예제 #50
0
 private void ProgressBarPerformStep(ProgressBar pb)
 {
     // InvokeRequired required compares the thread ID of the
     // calling thread to the thread ID of the creating thread.
     // If these threads are different, it returns true.
     if (pb.InvokeRequired)
     {
         ProgressBarPerformStepCallback d = new ProgressBarPerformStepCallback(ProgressBarPerformStep);
         pb.BeginInvoke(d, new object[] { pb });
     }
     else
     {
         if (pb.Value >= pb.Maximum)
         {
             pb.Value = pb.Minimum;
         }
         pb.PerformStep();
     }
 }
예제 #51
0
        public void insertToStockDataByBatch(List<string> sqlArray,ProgressBar pb)
        {
            try
            {
                OleDbConnection aConnection = new OleDbConnection(connString);
               aConnection.Open();
                OleDbTransaction transaction = aConnection.BeginTransaction();

                OleDbCommand aCommand = new OleDbCommand();
                aCommand.Connection = aConnection;
                aCommand.Transaction = transaction;
                pb.Maximum = sqlArray.Count;
                pb.Step = 1;
                for (int i = 0; i < sqlArray.Count; i++)
                {
                    pb.PerformStep();
                    aCommand.CommandText = sqlArray[i].ToString();
                    aCommand.ExecuteNonQuery();

                }

                transaction.Commit();
                aConnection.Close();

            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());

            }
        }
예제 #52
0
        private static void rash_2pi(ProgressBar progressBar1,  Bitmap bmp, Bitmap bmp1, Bitmap bmp2, int w, int h, int Diag)
        {
            GLBL_FAZE(Diag);                         // Заполнение массива glbl_faze[] для расшифровки
            int b,  ib1, ib2;

            Color c;
            progressBar1.Minimum = 1;
            progressBar1.Maximum =  w;
            progressBar1.Value = 1;
            for (int i = 0; i < w; i++)
            {
                for (int j = 0; j < h; j++)
                {
                    c = bmp1.GetPixel(i, j); b = c.R; ib1 = (int)((double)(b * (n1 - 1)) / 255); // --------------------- (b2)
                    c = bmp2.GetPixel(i, j); b = c.R; ib2 = (int)((double)(b * (n2 - 1)) / 255); // --------------------- (b1)
                    b = glbl_faze1[ib2 + (n1 - ib1)];
                    Z[i, j] = b  * n1 - (n1 - ib1);
                }
                progressBar1.PerformStep();
            }
        }
예제 #53
0
        public static int HideMessage(MemoryStream messageStream, Bitmap bitmap, ProgressBar progressBar)
        {
            //get bytes of teh file
            byte[] bytes = messageStream.ToArray();
            //check if file is too big
            if (bytes.Length >= (16777216)/8)
            {
                MessageBox.Show("Your file is too long, a maximum size of 2MB is allowed",
                    "Warning", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return 0;
            }
            //check if image has enough number of pixels to hide image
            if (bytes.Length >= (3 * (bitmap.Size.Height * bitmap.Size.Width - 1))/8)
            {
                MessageBox.Show("Your image is too small(not enough pixels) to hide message",
                    "Warning", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return 0;
            }
            //Write Length of the file into the first pixel
            int colorValue = bytes.Length;

            int redMask = 0xff0000;
            int red = (colorValue & redMask) >> 16;

            int greenMask = 0x00ff00;
            int green = (colorValue & greenMask) >> 8;

            int blueMask = 0x0000ff;
            int blue = colorValue & blueMask;

            bitmap.SetPixel(0, 0, Color.FromArgb(red, green, blue));
            //initialize x and y coordinates of image
            int x = 1;
            int y = 0;
            //pixel to be used
            Color pixel = bitmap.GetPixel(x, y);
            int val = 0; //0 - R, 1 - G, 2 - B
            byte R = pixel.R;
            byte G = pixel.G;
            byte B = pixel.B;
            //Loop through each file byte an hide it in the image
            for (int i = 0; i < bytes.Length; i++)
            {
                byte cur = bytes[i]; //get byte value
                byte mask = (byte)Convert.ToInt32("00000001", 2); //initialize mask
                for (int j = 0; j < 8; j++) //for each bit in the byte
                {

                    //get bit to set
                    byte result = (byte)(cur & mask);
                    //shift bit to the LSB position
                    result = (byte)(result >> j);
                    //Set pixel's value in the image
                    switch (val)
                    {
                        case 0: //just set R channel and update val
                            R = (byte)(((pixel.R>>1)<<1) | result);
                            val++;
                            break;
                        case 1: //just set G channel and update val
                            G = (byte)(((pixel.G >> 1) << 1) | result);
                            val++;
                            break;
                        case 2: //set B channel, and write pixel to bitmap
                            B = (byte)(((pixel.B >> 1) << 1) | result);
                            byte mask5 = (byte)Convert.ToInt32("00000001", 2);
                            Color toSet = Color.FromArgb(R, G, B);
                            bitmap.SetPixel(x, y, toSet);
                            byte mask1 = (byte)Convert.ToInt32("00000001", 2);
                            //Update pixel coordinate and reset variables
                            updateXY(ref x, ref y, bitmap);
                            //get next pixel
                            pixel = bitmap.GetPixel(x, y);
                            R = pixel.R;
                            G = pixel.G;
                            B = pixel.B;
                            val = 0;
                            break;
                    }
                    //update mask for reading teh next bit
                    mask =(byte)(mask << 1);

                }
                progressBar.PerformStep(); //update progress bar
            }
            //Check if need to set the last pixel
            if (val != 0)
            {
                Color toSet = Color.FromArgb(R, G, B);
                bitmap.SetPixel(x, y, toSet);

            }
            return 1;
        }
예제 #54
0
 public void PerformStep()
 {
     ProgressBar.PerformStep();
 }
예제 #55
0
 public void BarPerformStep()
 {
     bar.PerformStep();
 }
예제 #56
0
        internal static void MakeRomFSData(RomfsFile[] RomFiles, MemoryStream metadata, RichTextBox TB_Progress = null, ProgressBar PB_Show = null)
        {
            updateTB(TB_Progress, "Computing IVFC Header Data...");
            IVFCInfo ivfc = new IVFCInfo { Levels = new IVFCLevel[3] };
            for (int i = 0; i < ivfc.Levels.Length; i++)
            {
                ivfc.Levels[i] = new IVFCLevel { BlockSize = 0x1000 };
            }
            ivfc.Levels[2].DataLength = RomfsFile.GetDataBlockLength(RomFiles, (ulong)metadata.Length);
            ivfc.Levels[1].DataLength = (Align(ivfc.Levels[2].DataLength, ivfc.Levels[2].BlockSize) / ivfc.Levels[2].BlockSize) * 0x20; //0x20 per SHA256 hash
            ivfc.Levels[0].DataLength = (Align(ivfc.Levels[1].DataLength, ivfc.Levels[1].BlockSize) / ivfc.Levels[1].BlockSize) * 0x20; //0x20 per SHA256 hash
            ulong MasterHashLen = (Align(ivfc.Levels[0].DataLength, ivfc.Levels[0].BlockSize) / ivfc.Levels[0].BlockSize) * 0x20;
            ulong lofs = 0;
            foreach (IVFCLevel t in ivfc.Levels)
            {
                t.HashOffset = lofs;
                lofs += Align(t.DataLength, t.BlockSize);
            }
            const uint IVFC_MAGIC = 0x43465649; //IVFC
            const uint RESERVED = 0x0;
            const uint HeaderLen = 0x5C;
            FileStream OutFileStream = new FileStream(TempFile, FileMode.Create, FileAccess.ReadWrite);
            try
            {
                OutFileStream.Seek(0, SeekOrigin.Begin);
                OutFileStream.Write(BitConverter.GetBytes(IVFC_MAGIC), 0, 0x4);
                OutFileStream.Write(BitConverter.GetBytes(0x10000), 0, 0x4);
                OutFileStream.Write(BitConverter.GetBytes(MasterHashLen), 0, 0x4);
                foreach (IVFCLevel t in ivfc.Levels)
                {
                    OutFileStream.Write(BitConverter.GetBytes(t.HashOffset), 0, 0x8);
                    OutFileStream.Write(BitConverter.GetBytes(t.DataLength), 0, 0x8);
                    OutFileStream.Write(BitConverter.GetBytes((int)(Math.Log(t.BlockSize, 2))), 0, 0x4);
                    OutFileStream.Write(BitConverter.GetBytes(RESERVED), 0, 0x4);
                }
                OutFileStream.Write(BitConverter.GetBytes(HeaderLen), 0, 0x4);
                //IVFC Header is Written.
                OutFileStream.Seek((long)Align(MasterHashLen + 0x60, ivfc.Levels[0].BlockSize), SeekOrigin.Begin);
                byte[] metadataArray = metadata.ToArray();
                OutFileStream.Write(metadataArray, 0, metadataArray.Length);
                long baseOfs = OutFileStream.Position;
                updateTB(TB_Progress, "Writing Level 2 Data...");
                if (PB_Show.InvokeRequired)
                    PB_Show.Invoke((MethodInvoker)delegate { PB_Show.Minimum = 0; PB_Show.Step = 1; PB_Show.Value = 0; PB_Show.Maximum = RomFiles.Length; });
                else { PB_Show.Minimum = 0; PB_Show.Step = 1; PB_Show.Value = 0; PB_Show.Maximum = RomFiles.Length; }

                foreach (RomfsFile t in RomFiles)
                {
                    OutFileStream.Seek(baseOfs + (long)t.Offset, SeekOrigin.Begin);
                    using (FileStream inStream = new FileStream(t.FullName, FileMode.Open, FileAccess.Read))
                    {
                        while (inStream.Position < inStream.Length)
                        {
                            byte[] buffer = new byte[inStream.Length - inStream.Position > 0x100000 ? 0x100000 : inStream.Length - inStream.Position];
                            inStream.Read(buffer, 0, buffer.Length);
                            OutFileStream.Write(buffer, 0, buffer.Length);
                        }
                    }
                    if (PB_Show.InvokeRequired)
                        PB_Show.Invoke((MethodInvoker)delegate { PB_Show.PerformStep(); });
                    else { PB_Show.PerformStep(); }
                }
                long hashBaseOfs = (long)Align((ulong)OutFileStream.Position, ivfc.Levels[2].BlockSize);
                long hOfs = (long)Align(MasterHashLen, ivfc.Levels[0].BlockSize);
                long cOfs = hashBaseOfs + (long)ivfc.Levels[1].HashOffset;
                SHA256Managed sha = new SHA256Managed();
                for (int i = ivfc.Levels.Length - 1; i >= 0; i--)
                {
                    updateTB(TB_Progress, "Computing Level " + i + " Hashes...");
                    byte[] buffer = new byte[(int)ivfc.Levels[i].BlockSize];

                    if (PB_Show.InvokeRequired)
                        PB_Show.Invoke((MethodInvoker)delegate { PB_Show.Minimum = 0; PB_Show.Step = 1; PB_Show.Value = 0; PB_Show.Maximum = (int)(ivfc.Levels[i].DataLength / ivfc.Levels[i].BlockSize); });
                    else { PB_Show.Minimum = 0; PB_Show.Step = 1; PB_Show.Value = 0; PB_Show.Maximum = (int)(ivfc.Levels[i].DataLength / ivfc.Levels[i].BlockSize); }

                    for (long ofs = 0; ofs < (long)ivfc.Levels[i].DataLength; ofs += ivfc.Levels[i].BlockSize)
                    {
                        OutFileStream.Seek(hOfs, SeekOrigin.Begin);
                        OutFileStream.Read(buffer, 0, (int)ivfc.Levels[i].BlockSize);
                        hOfs = OutFileStream.Position;
                        byte[] hash = sha.ComputeHash(buffer);
                        OutFileStream.Seek(cOfs, SeekOrigin.Begin);
                        OutFileStream.Write(hash, 0, hash.Length);
                        cOfs = OutFileStream.Position;
                        if (PB_Show.InvokeRequired)
                            PB_Show.Invoke((MethodInvoker)delegate { PB_Show.PerformStep(); });
                        else { PB_Show.PerformStep(); }
                    }
                    if (i == 2)
                    {
                        long len = OutFileStream.Position;
                        if (len % 0x1000 != 0)
                        {
                            len = (long)Align((ulong)len, 0x1000);
                            byte[] buf = new byte[len - OutFileStream.Position];
                            OutFileStream.Write(buf, 0, buf.Length);
                        }
                    }
                    if (i <= 0) continue;
                    hOfs = hashBaseOfs + (long)ivfc.Levels[i - 1].HashOffset;
                    if (i > 1)
                        cOfs = hashBaseOfs + (long)ivfc.Levels[i - 2].HashOffset;
                    else
                        cOfs = (long)Align(HeaderLen, PADDING_ALIGN);
                }
            }
            finally
            {
                if (OutFileStream != null)
                    OutFileStream.Dispose();
            }
            if (OutFile != TempFile)
            {
                if (File.Exists(OutFile)) File.Delete(OutFile);
                File.Move(TempFile, OutFile);
            }
        }
        /// <summary>
        /// Этот метод выполняет обработку файла золотой короны.
        /// </summary>
        /// <param name="workbookPath">Путь к файлу.</param>
        /// <param name="progress">Прогресбар.</param>
        /// <returns>Возвращает сумму за текущий час в строковом формате с запятой.</returns>
        public static double GoldenCrown(string workbookPath, ProgressBar progress)
        {
            double sum = 0;
            progress.Value = 0;
            progress.Step = 30;
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
            NumberStyles styles;
            styles = NumberStyles.AllowParentheses | NumberStyles.AllowTrailingSign | NumberStyles.Float | NumberStyles.AllowThousands;
            progress.PerformStep();

            Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(workbookPath, 0, false, 5, "", "", false,
                Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
            progress.PerformStep();
            Excel.Sheets excelSheets = excelWorkbook.Worksheets;
            try {
                Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelSheets.get_Item("pcards");
                progress.PerformStep();
                Array myvalues1;
                Array myvalues2;
                Array myvalues3;
                Excel.Range rng = excelWorksheet.Range["A3:AA25000", Type.Missing];
                progress.PerformStep();
                object cols = new object[] { 15 };
                rng.RemoveDuplicates(cols, Excel.XlYesNoGuess.xlYes);
                Excel.Range rangeNom = excelWorksheet.get_Range("S3", "S25000".ToString());
                Excel.Range rangeStat = excelWorksheet.get_Range("W3", "W25000".ToString());
                Excel.Range rangeProd = excelWorksheet.get_Range("AA3", "AA25000".ToString());
                progress.PerformStep();
                myvalues1 = (Array)rangeNom.Cells.Value;
                myvalues2 = (Array)rangeStat.Cells.Value;
                myvalues3 = (Array)rangeProd.Cells.Value;
                double total = 0;
                progress.PerformStep();
                for (int i = 1; i <= myvalues1.Length; i++)
                {
                    if (myvalues1.GetValue(i, 1) != null) {

                        if ((myvalues2.GetValue(i, 1).ToString() == "Готов к выдаче" | myvalues2.GetValue(i, 1).ToString() == "Выдан"
                            | myvalues2.GetValue(i, 1).ToString() == "Запрошен для выдачи") & (myvalues3.GetValue(i,1).ToString() != "Погашение"))
                        {
                            total += Double.Parse((myvalues1.GetValue(i, 1).ToString()).Replace(" ", ""), styles);
                        }
                    }
                }
                sum = (Math.Round(total, 2));
                excelWorkbook.Close(false);
                progress.PerformStep();
                return sum;
            }
            catch
            {
                excelWorkbook.Close(false);
                progress.Value = 0;
                return sum;
            }
        }
예제 #58
0
        internal static void WriteBinary(string tempFile, string outFile, RichTextBox TB_Progress = null, ProgressBar PB_Show = null)
        {
            using (FileStream fs = new FileStream(outFile, FileMode.Create))
            {
                using (BinaryWriter writer = new BinaryWriter(fs))
                {
                    using (FileStream fileStream = new FileStream(tempFile, FileMode.Open, FileAccess.Read))
                    {
                        const uint BUFFER_SIZE = 0x400000; // 4MB Buffer

                        if (PB_Show.InvokeRequired)
                            PB_Show.Invoke((MethodInvoker)delegate { PB_Show.Minimum = 0; PB_Show.Step = 1; PB_Show.Value = 0; PB_Show.Maximum = (int)(fileStream.Length / BUFFER_SIZE); });
                        else { PB_Show.Minimum = 0; PB_Show.Step = 1; PB_Show.Value = 0; PB_Show.Maximum = (int)(fileStream.Length / BUFFER_SIZE); }

                        byte[] buffer = new byte[BUFFER_SIZE];
                        while (true)
                        {
                            int count = fileStream.Read(buffer, 0, buffer.Length);
                            if (count != 0)
                            {
                                writer.Write(buffer, 0, count);
                                if (PB_Show.InvokeRequired)
                                    PB_Show.Invoke((MethodInvoker)delegate { PB_Show.PerformStep(); });
                                else { PB_Show.PerformStep(); }
                            }
                            else
                                break;
                        }
                    }
                    writer.Flush();
                }
            }
            File.Delete(TempFile);
            updateTB(TB_Progress, "Wrote RomFS to path:" + Environment.NewLine + outFile);
        }
예제 #59
0
 public void updateSplash(string str, int sleepTime)
 {
     //SplashLabel.Text = str;
     SplashProgressBar.PerformStep();
     Thread.Sleep(sleepTime);
 }
예제 #60
0
        private int DownloadFile(String remoteFilename,
                                 String localFilename)
        {
            // Function will return the number of bytes processed
            // to the caller. Initialize to 0 here.
            int bytesProcessed = 0;

            // Assign values to these objects here so that they can
            // be referenced in the finally block
            Stream      remoteStream = null;
            Stream      localStream  = null;
            WebResponse response     = null;

            // Use a try/catch/finally block as both the WebRequest and Stream
            // classes throw exceptions upon error
            try
            {
                // Create a request for the specified remote file name
                WebRequest request = WebRequest.Create(remoteFilename);
                if (request != null)
                {
                    // Send the request to the server and retrieve the
                    // WebResponse object
                    response = request.GetResponse();
                    if (response != null)
                    {
                        // Once the WebResponse object has been retrieved,
                        // get the stream object associated with the response's data
                        remoteStream = response.GetResponseStream();

                        // Create the local file
                        localStream       = File.Create(localFilename);
                        progressBar1.Step = (int)response.ContentLength / 100;

                        // Allocate a 1k buffer
                        byte[] buffer = new byte[1024];
                        int    bytesRead;

                        // Simple do/while loop to read from stream until
                        // no bytes are returned
                        do
                        {
                            // Read data (up to 1k) from the stream
                            bytesRead = remoteStream.Read(buffer, 0, buffer.Length);
                            progressBar1.PerformStep();


                            // Write the data to the local file
                            localStream.Write(buffer, 0, bytesRead);

                            // Increment total bytes processed
                            bytesProcessed += bytesRead;
                        } while (bytesRead > 0);
                        progressBar1.Step = 100;
                        progressBar1.PerformStep();
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            finally
            {
                // Close the response and streams objects here
                // to make sure they're closed even if an exception
                // is thrown at some point
                if (response != null)
                {
                    response.Close();
                }
                if (remoteStream != null)
                {
                    remoteStream.Close();
                }
                if (localStream != null)
                {
                    localStream.Close();
                }
            }

            button2.Enabled = true;
            // Return total bytes processed to caller.
            return(bytesProcessed);
        }