private void Initialize()
 {
     _updatePbDelegate += new UpdateProgressBarDelegate(pbMeters.SetValue);
     _showMeterProcess += new Action <double>(this.ShowMeterProgress);
     _enableControls   += new Action(this.EnableControls);
     _bindGrid         += new Action <DataSet>(this.BindGrid);
 }
        private void CopyFiles()
        {
            //StringBuilder SB = new StringBuilder();
            UpdateProgressBarDelegate updProgress = new UpdateProgressBarDelegate(progressBar1.SetValue);
            double value = 0;

            /*
             * foreach (OFP_forList ofp in ((App)Application.Current).OFPLIST)
             * {
             *  SB.AppendLine(ofp.IFPS_Validate());
             *  Dispatcher.Invoke(updProgress, new object[] { ProgressBar.ValueProperty, ++value });
             * }
             */

            Parallel.ForEach(((App)Application.Current).OFPLIST, ofp => {
                //SB.AppendLine(ofp.IFPS_Validate());
                resultList.Add(ofp.IFPS_Validate());

                Dispatcher.Invoke(updProgress, new object[] { ProgressBar.ValueProperty, ++value });
            });

            Dispatcher.BeginInvoke(new ThreadStart(delegate
            {
                //newTB.AppendText(SB.ToString());
                outputList.DataContext = resultList;
            }));
        }
        /// <summary>
        /// Добавление картинок в listBox из выбранной папки.
        /// </summary>
        /// <param name="selectedPath">Путь выбранной папки</param>
        private void AddToTheListFoundFilesImages(string selectedPath)
        {
            this.listBox.SelectedIndex = -1;
            this.listBox.Items.Clear();
            this.progressBar.Value = 0;

            UpdateProgressBarDelegate updProgress = new UpdateProgressBarDelegate(progressBar.SetValue);

            DirectoryInfo directoryInfo = new DirectoryInfo(selectedPath);

            this.progressBar.Maximum = directoryInfo.GetFiles().Count();


            foreach (FileInfo fileInfo in directoryInfo.GetFiles())
            {
                if (IsImageExtensions(fileInfo.Extension) == true)
                {
                    this.AddToListBoxImage(fileInfo);

                    Dispatcher.Invoke(updProgress,
                                      System.Windows.Threading.DispatcherPriority.Background,
                                      new object[] { Wpf.ProgressBar.ValueProperty, ++this.progressBar.Value });
                }
            }
        }
 public afgeleide_functies()
 {
     InitializeComponent();
     // bvfta.Connection.ConnectionString = zeebregtsCs.Global.ConnectionString_fileserver;
     updatePbDelegate = new UpdateProgressBarDelegate(pro_bar.SetValue);
     updateLDelegate  = new UpdateLayoutDelegate(dg_nieuw.SetValue);
 }
Beispiel #5
0
        private void Sum(object obj)
        {
            result = 0;
            long num = Convert.ToInt64(obj);

            UpdateProgressBarDelegate upd = new UpdateProgressBarDelegate(UpdateProgressBar);

            for (long i = 0; i <= num; i++)
            {
                result += i;
                if (i % 10000 == 0)
                {
                    if (progressBar1.InvokeRequired)
                    {
                        progressBar1.Invoke(upd, new object[] { progressBar1, Convert.ToInt32((100 * i) / num) });
                    }
                    else
                    {
                        progressBar1.Value = Convert.ToInt32(i / num * 100);
                    }
                }
            }

            if (lblResult.InvokeRequired)
            {
                UpdateLabelDelegate uld = new UpdateLabelDelegate(UpdateLabel);
                lblResult.Invoke(uld, new object[] { lblResult, result.ToString() });
            }
        }
Beispiel #6
0
        private void BeginDownLoad()
        {
            _progressBar.Maximum = 4;
            _progressBar.Value   = 0;
            OperateLog log = new OperateLog();

            log.Guid        = CO_IA.Client.Utility.NewGuid();
            log.Operater    = RiasPortal.Current.UserSetting.UserName;
            log.OperateDate = DateTime.Now;
            log.OperateType = OperateTypeEnum.DownLoad;
            UpdateProgressBarDelegate updatePbDelegate = new UpdateProgressBarDelegate(_progressBar.SetValue);

            SQLiteDataService.Transaction = SQLiteConnect.GetSQLiteTransaction(SystemLoginService.CurrentActivity.Name);
            try
            {
                SQLiteDataService.DeleteStationBase(SystemLoginService.CurrentActivity.Guid, SystemLoginService.CurrentActivityPlace.Guid);
                SQLiteDataService.DeleteFreqPlan(SystemLoginService.CurrentActivity.Guid, SystemLoginService.CurrentActivityPlace.Guid);
                SQLiteDataService.DeletePlace(SystemLoginService.CurrentActivity.Guid);
                for (int i = 0; i < 4; i++)
                {
                    if (i == 0 && _statDownLoad.IsChecked == true)
                    {
                        _downLoadInfo.Text = "正在下载周围台站数据";
                        DownLoadStationBase();
                        log.OperateTables += "ACTIVITY_PLACE_STATION,";
                    }
                    //else if (i == 1 && _emitDownLoad.IsChecked == true)
                    //{
                    //    _downLoadInfo.Text = "正在下载设备信息数据";
                    //    DownLoadEquipInfo();
                    //    log.OperateTables += "ACTIVITY_STATION_EMIT,";
                    //}

                    else if (i == 2 && _areaDownLoad.IsChecked == true)
                    {
                        _downLoadInfo.Text = "正在下载活动区域数据";
                        DownLoadActivityPlace();
                        log.OperateTables += "ACTIVITY_PLACE,ACTIVITY_PLACE_LOCATION,";
                    }
                    else if (i == 3 && _freqRangeDownLoad.IsChecked == true)
                    {
                        _downLoadInfo.Text = "正在下载频率预案数据";
                        DownLoadFreqPlan();
                        log.OperateTables += "activity_place_freq_plan, rias_equipment_freqplanning,";
                    }
                    Dispatcher.Invoke(updatePbDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { System.Windows.Controls.ProgressBar.ValueProperty, Convert.ToDouble(i + 1) });
                }
                SQLiteDataService.SaveOperaterLog(log);

                SQLiteDataService.Transaction.Commit();
                _downLoadInfo.Text = "下载完成";
            }
            catch (Exception ex)
            {
                SQLiteDataService.Transaction.Rollback();
                Console.WriteLine(ex.Message);
                _downLoadInfo.Text = "下载失败";
                MessageBox.Show("失败原因:\r\n" + ex.Message);
            }
        }
        private void Process()
        {
            //Configure the ProgressBar
            ProgressBar1.Minimum = 0;
            ProgressBar1.Maximum = short.MaxValue;
            ProgressBar1.Value   = 0;

            //Stores the value of the ProgressBar
            double value = 0;

            //Create a new instance of our ProgressBar Delegate that points
            //  to the ProgressBar's SetValue method.
            UpdateProgressBarDelegate updatePbDelegate = new UpdateProgressBarDelegate(ProgressBar1.SetValue);

            //Tight Loop:  Loop until the ProgressBar.Value reaches the max
            do
            {
                value += 1;

                /*Update the Value of the ProgressBar:
                 * 1)  Pass the "updatePbDelegate" delegate that points to the ProgressBar1.SetValue method
                 * 2)  Set the DispatcherPriority to "Background"
                 * 3)  Pass an Object() Array containing the property to update (ProgressBar.ValueProperty) and the new value */
                Dispatcher.Invoke(updatePbDelegate,
                                  System.Windows.Threading.DispatcherPriority.Background,
                                  new object[] { ProgressBar.ValueProperty, value });
            }while (ProgressBar1.Value != ProgressBar1.Maximum);
        }
        /// <summary>
        /// Displays progress bar for downloading binaries
        /// </summary>
        private void ProgressBarDisplay()
        {
            ProgressBar1.Visibility = System.Windows.Visibility.Visible;
            //Configure the ProgressBar
            ProgressBar1.Foreground = new SolidColorBrush(AppearanceManager.Current.AccentColor);
            ProgressBar1.Minimum    = 0;
            ProgressBar1.Maximum    = 150;
            ProgressBar1.Value      = 0;
            waitText.Visibility     = System.Windows.Visibility.Visible;
            //Stores the value of the ProgressBar
            double value = 0;

            //Create a new instance of our ProgressBar Delegate that points
            //  to the ProgressBar's SetValue method.
            UpdateProgressBarDelegate updatePbDelegate = new UpdateProgressBarDelegate(ProgressBar1.SetValue);

            //Tight Loop:  Loop until the ProgressBar.Value reaches the max
            do
            {
                value += 1;

                /*Update the Value of the ProgressBar:
                 * 1)  Pass the "updatePbDelegate" delegate that points to the ProgressBar1.SetValue method
                 * 2)  Set the DispatcherPriority to "Background"
                 * 3)  Pass an Object() Array containing the property to update (ProgressBar.ValueProperty) and the new value */
                Dispatcher.Invoke(updatePbDelegate,
                                  System.Windows.Threading.DispatcherPriority.Background,
                                  new object[] { ProgressBar.ValueProperty, value });
            }while (ProgressBar1.Value != ProgressBar1.Maximum);
        }
        private void Dispose(bool disposing)
        {
            if (!disposed)
            {
                if (disposing)
                {
                    this.CleanupWPFObjectTopControls((i) =>
                    {
                        // events
                        this.MeterLife.Loaded -= (this.MeterLife_Loaded);
                        this.lstView.Loaded   -= (this.lstView_Loaded);
                        this.btnRefresh.Click -= (this.btnRefresh_Click);
                        this.btnPrint.Click   -= (this.btnPrint_Click);

                        _updatePbDelegate -= (pbMeters.SetValue);
                        _showMeterProcess -= (this.ShowMeterProgress);
                        _enableControls   -= (this.EnableControls);
                        _bindGrid         -= (this.BindGrid);
                    },
                                                     (c) =>
                    {
                    });
                    LogManager.WriteLog("|=> CMeterLife objects are released successfully.", LogManager.enumLogLevel.Info);
                }
                disposed = true;
            }
        }
Beispiel #10
0
        public void ProgressUpdate(int Step)
        {
            System.Windows.Controls.ProgressBar pb = ProgressBar1;
            //Create a new instance of our ProgressBar Delegate that points
            //  to the ProgressBar's SetValue method.
            UpdateProgressBarDelegate updatePbDelegate = new UpdateProgressBarDelegate(ProgressBar1.SetValue);

            //解决主线程控件无法被子线程控制的问题,调用线程无法访问此对象,因为另一个线程拥有该对象
            this.Dispatcher.Invoke(new Action(() =>
            {
                Notice.Text = "正在测量第" +
                              ((pb.Value - pb.Minimum) / Step + 1) + "/" +
                              ((pb.Maximum - pb.Minimum) / Step + 1) + "层";

                /*Update the Value of the ProgressBar:
                 * 1)  Pass the "updatePbDelegate" delegate that points to the ProgressBar1.SetValue method
                 * 2)  Set the DispatcherPriority to "Background"
                 * 3)  Pass an Object() Array containing the property to update (ProgressBar.ValueProperty) and the new value */

                Dispatcher.Invoke(updatePbDelegate,
                                  System.Windows.Threading.DispatcherPriority.Background,
                                  new object[] { System.Windows.Controls.ProgressBar.ValueProperty, (double)pb.Value });

                pb.Value += Step;
            }));
        }
Beispiel #11
0
        public static void InitializeProgress(string statusText, int maximum, bool indeterminate = false)
        {
            if (null == ProgressBar || null == StatusLabel)
            {
                return;
            }

            ProgressBar.Visibility = Visibility.Visible;
            ProgressValue          = 0;

            _updateLabelDelegate = StatusLabel.SetValue;
            Dispatcher.CurrentDispatcher.Invoke(_updateLabelDelegate, DispatcherPriority.Background, TextBlock.TextProperty, statusText);

            _updatePbDelegate   = ProgressBar.SetValue;
            ProgressBar.Value   = ProgressValue;
            ProgressBar.Maximum = maximum;

            Logs = new List <string>();
            LogButton.Visibility = Visibility.Hidden;

            if (indeterminate)
            {
                ProgressBar.IsIndeterminate = true;
            }
        }
Beispiel #12
0
 // update progress bar thread safe
 private void UpdateProgressBar(object o, TaskProgressedEventArgs e)
 {
     // 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 (statusStrip1.InvokeRequired)
     {
         //create new delegate
         UpdateProgressBarDelegate d = new UpdateProgressBarDelegate(UpdateProgressBar);// use the very same function to call it again in correct and save thread
         this.Invoke(d, new object[] { o, e });
     }
     else
     {
         if (e.ProgressIncrement != 0)
         {
             toolStripProgressBar1.Increment(1);
         }
         else
         {
             toolStripProgressBar1.Minimum = (int)e.Start;
             toolStripProgressBar1.Maximum = (int)e.End;
             toolStripProgressBar1.Value   = (int)e.Val;
             toolStripStatusLabel1.Text    = string.IsNullOrEmpty(e.Text) ? CertFolderStatusStrip: e.Text;
         }
     }
 }
        //private UpdateProgressBarDelegate UpdatePbDelegate { get; set; }

        public AddFromListofURLs()
        {
            InitializeComponent();

            _updatePbDelegate      = progressBar.SetValue;
            progressBar.Visibility = Visibility.Hidden;
        }
Beispiel #14
0
 public Form1()
 {
     UpdateProgressBar = new UpdateProgressBarDelegate(UpdateProgressBarMethod);
     InitializeComponent();
     DrawArea          = new Bitmap(pictureBox1.Size.Width, pictureBox1.Size.Height);
     pictureBox1.Image = DrawArea;
 }
Beispiel #15
0
        public ImageResource(HtmlParser parser, UpdateProgressBarDelegate updateProgressBarDelegate)
        {
            this.updateProgressBarDelegate = updateProgressBarDelegate;
            Uri docPath = parser.GetPageUri();

            this.LoadImages(parser.GetImageSrcUrls(), docPath.AbsoluteUri);
        }
        //private UpdateProgressBarDelegate UpdatePbDelegate { get; set; }
        public AddFromList()
        {
            InitializeComponent();

            _updatePbDelegate = progressBar.SetValue;
            progressBar.Visibility = Visibility.Hidden;
        }
        private void DownloadFiles()
        {
            UpdateProgressBarDelegate updProgress = new UpdateProgressBarDelegate(progressBar.SetValue);
            double value        = 0;
            var    sw           = new Stopwatch();
            int    downloadsize = 0;

            foreach (var item in fileLIstforDownload)
            {
                if (!listMD5Hash.Contains(item.md5))
                {
                    sw.Start();
                    DownloadFile(item);
                    TimeSpan ts = sw.Elapsed;
                    listMD5Hash.Add(item.md5);
                    downloadsize += item.size;
                    var    newTime     = new TimeSpan(0, 0, (int)((ts.TotalSeconds * size / downloadsize) - ts.TotalSeconds));
                    string elapsedTime = String.Format("Прошло - {0:00}:{1:00}:{2:00}", ts.Hours, ts.Minutes, ts.Seconds);
                    elapsedTime += String.Format("; Осталось примерно - {0:00}:{1:00}:{2:00}", newTime.Hours, newTime.Minutes, newTime.Seconds);
                    value       += item.size;
                    Dispatcher.Invoke(DispatcherPriority.Background, new Action(() => this.timeBlock.Text = elapsedTime));
                    Dispatcher.Invoke(updProgress, new object[] { ProgressBar.ValueProperty, value });
                }
            }
            WriteMD5List();
            value = 0;
            Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => this.downloadButton.IsEnabled   = true));
            Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => this.typeFileComboBox.IsEnabled = true));
            Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => this.loadButton.IsEnabled       = true));
            Dispatcher.Invoke(updProgress, new object[] { ProgressBar.ValueProperty, value });
            Dispatcher.Invoke(DispatcherPriority.Background, new Action(() => this.timeBlock.Text = ""));
        }
Beispiel #18
0
        private void Process()
        {
            //Configure the ProgressBar
            ProgressBar1.Minimum = 0;
            ProgressBar1.Maximum = short.MaxValue;
            ProgressBar1.Value = 0;

            //Stores the value of the ProgressBar
            double value = 0;

            //Create a new instance of our ProgressBar Delegate that points
            //  to the ProgressBar's SetValue method.
            UpdateProgressBarDelegate updatePbDelegate = new UpdateProgressBarDelegate(ProgressBar1.SetValue);

            //Tight Loop:  Loop until the ProgressBar.Value reaches the max
            do
            {
                value += 1;

                /*Update the Value of the ProgressBar:
                  1)  Pass the "updatePbDelegate" delegate that points to the ProgressBar1.SetValue method
                  2)  Set the DispatcherPriority to "Background"
                  3)  Pass an Object() Array containing the property to update (ProgressBar.ValueProperty) and the new value */
                Dispatcher.Invoke(updatePbDelegate,
                    System.Windows.Threading.DispatcherPriority.Background,
                    new object[] { ProgressBar.ValueProperty, value });

            }
            while (ProgressBar1.Value != ProgressBar1.Maximum);
        }
 private void Initialize()
 {
     _updatePbDelegate += new UpdateProgressBarDelegate(pbMeters.SetValue);
     _showMeterProcess += new Action<double>(this.ShowMeterProgress);
     _enableControls += new Action(this.EnableControls);
     _bindGrid += new Action<DataSet>(this.BindGrid);
 }
Beispiel #20
0
        void client_Progress(object sender, SvnProgressEventArgs e)
        {
            // Convert the total progress into a value on the progress bar
            // The event args has two values - Progress and TotalProgres.
            // Progress is the numerator and TotalProgress is the denominator

            if (e.Progress == e.TotalProgress)
            {
                // This means that we have completed the operation.
                this.client.Progress -= new EventHandler <SvnProgressEventArgs>(client_Progress);
                this.Close();
                return;
            }

            double value = (e.Progress / (double)(e.TotalProgress));

            value *= 100;

            // Count of the latest number of bytes received.
            this.last_count = e.Progress;

            UpdateProgressBarDelegate updatedel = new UpdateProgressBarDelegate(this._progress_bar.SetValue);

            Dispatcher.Invoke(
                updatedel,
                System.Windows.Threading.DispatcherPriority.Background,
                new object[] { ProgressBar.ValueProperty, value }
                );
        }
Beispiel #21
0
        private void StartEncryption()
        {
            try
            {
                string inFile   = filenameBox.Text;
                string outFile  = filenameBox.Text + ".fcfe";
                string password = passwordBox.Text;
                progressBar.Visibility = System.Windows.Visibility.Visible;
                progressBar.Minimum    = 0;
                progressBar.Maximum    = 100;

                updatePbDelegate = new UpdateProgressBarDelegate(progressBar.SetValue);

                CryptoProgressCallBack cb = new CryptoProgressCallBack(this.ProgressCallBackEncrypt);
                CryptoHelp.EncryptFile(inFile, outFile, password, cb);

                progressBar.Value      = 0;
                filenameBox.Text       = "";
                passwordBox.Text       = "";
                progressBar.Visibility = System.Windows.Visibility.Collapsed;
            }
            catch (Exception ex)
            {
                encryptButton.IsEnabled = true;
                MessageBoxResult result = MessageBox.Show(ex.Message);
            }
        }
        private void btnGenerate_Click(object sender, RoutedEventArgs e)
        {
            if (this.listRightTables.Items.Count == 0)
            {
                MessageBox.Show("Please select object(s)");
                return;
            }
            if (this.txtNameSpaceRoot.Text.Trim().Length == 0)
            {
                MessageBox.Show("Please input root Namespace");
                this.txtNameSpaceRoot.Focus();
                return;
            }
            if (this.tvTemplates.SelectedItem == null)
            {
                MessageBox.Show("Please select template package or template.");
                return;
            }
            if (!Directory.Exists(this.txtExportPath.Text + @"\" + this.cboxDatabases.Text))
            {
                Directory.CreateDirectory(this.txtExportPath.Text + @"\" + this.cboxDatabases.Text);
            }

            PropertyNodeItem sn = (PropertyNodeItem)this.tvTemplates.SelectedItem;

            this.proCount = 0;
            this.pbarBatchGenerate.Maximum = totalCount;
            this.pbarBatchGenerate.Minimum = 0;
            this.pbarBatchGenerate.Value   = 0;
            updatePbDelegate = new UpdateProgressBarDelegate(pbarBatchGenerate.SetValue);
            //Start to Generate Codes
            GenerateByTreeNode(sn);

            Process.Start("explorer.exe", this.txtExportPath.Text);
        }
        void client_Progress(object sender, SvnProgressEventArgs e)
        {
            // Convert the total progress into a value on the progress bar 
            // The event args has two values - Progress and TotalProgres. 
            // Progress is the numerator and TotalProgress is the denominator 

            if (e.Progress == e.TotalProgress)
            {
                // This means that we have completed the operation. 
                this.client.Progress -= new EventHandler<SvnProgressEventArgs>(client_Progress);
                this.Close();
                return; 
            }
            
            double value = (e.Progress / (double)(e.TotalProgress));             
            value *= 100;

            // Count of the latest number of bytes received. 
            this.last_count = e.Progress; 

            UpdateProgressBarDelegate updatedel = new UpdateProgressBarDelegate(this._progress_bar.SetValue);            
            Dispatcher.Invoke(
                updatedel, 
                System.Windows.Threading.DispatcherPriority.Background,
                new object[] { ProgressBar.ValueProperty, value }
                ); 
        }
Beispiel #24
0
        public void UpdateProgressBar(Control ctrl, string prop, int value)
        {
            if (ctrl.InvokeRequired)
            {
                UpdateProgressBarDelegate del = new UpdateProgressBarDelegate(UpdateProgressBar);
                ctrl.Invoke(del, ctrl, prop, value);
            }
            else
            {
                switch (prop)
                {
                case "max":
                    ((ProgressBar)ctrl).Maximum = value;
                    break;

                case "min":
                    ((ProgressBar)ctrl).Minimum = value;
                    break;

                case "value":
                    ((ProgressBar)ctrl).Value = value;
                    break;
                }
            }
        }
Beispiel #25
0
        private void buttonCreate_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var checkedItems = from item in selectedItems where item.IsSelected select item;
                if (checkedItems.Count() > 0)
                {
                    List <View> createdViews = new List <View>();
                    bool        create3dView = (bool)radioButton3D.IsChecked;
                    bool        overwrite    = (bool)checkBoxOverwrite.IsChecked;
                    statusLable.Text       = "Creating Views..";
                    progressBar.Visibility = System.Windows.Visibility.Visible;
                    UpdateProgressBarDelegate updatePbDelegate = new UpdateProgressBarDelegate(progressBar.SetValue);

                    progressBar.Minimum = 0;
                    progressBar.Maximum = checkedItems.Count();
                    progressBar.Value   = 0;

                    double value = 0;

                    foreach (ItemInfo item in checkedItems)
                    {
                        if (create3dView)
                        {
                            View3D viewCreated = ViewCreator.Create3DView(m_doc, item, view3dFamilyType, overwrite);
                            if (null != viewCreated)
                            {
                                createdViews.Add(viewCreated);
                            }
                        }
                        else
                        {
                            if (null != comboBoxLevel.SelectedItem)
                            {
                                ViewPlan viewCreated = ViewCreator.CreateFloorPlan(m_doc, item, viewPlanFamilyType, (Level)comboBoxLevel.SelectedItem, overwrite);
                                if (null != viewCreated)
                                {
                                    createdViews.Add(viewCreated);
                                }
                            }
                        }
                        value++;
                        Dispatcher.Invoke(updatePbDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { ProgressBar.ValueProperty, value });
                    }

                    if (createdViews.Count > 0)
                    {
                        MessageBox.Show(createdViews.Count + " views are created.", "Views Created", MessageBoxButton.OK, MessageBoxImage.Information);
                    }

                    statusLable.Text       = "Ready";
                    progressBar.Visibility = System.Windows.Visibility.Hidden;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to create views.\n" + ex.Message, "Create Views", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }
        public formSyncDatabase()
        {
            InitializeComponent();
            this.builder = new StringBuilder();

            UpdateProgressBar = new UpdateProgressBarDelegate(this.UpdateProgressBarMethod);
            UpdateTextLabel   = new UpdateTextLabelDelegate(this.UpdateTextLabelMethod);
        }
Beispiel #27
0
 /// <summary>
 /// Конструктор
 /// </summary>
 /// <param name="mWindow"></param>
 public Service(System.Windows.Window mWindow)
 {
     if (mWindow.GetType() == typeof(MainWindow))
     {
         WinMainWindow = (MainWindow)mWindow;
     }
     updatePbDelegate = new UpdateProgressBarDelegate(WinMainWindow.pb1.SetValue);
 }
        public void setProgressValue(double value)
        {
            if (value >= 0 && value <= 100)
            {
                UpdateProgressBarDelegate updatePbDelegate = new UpdateProgressBarDelegate(this.pbTask.SetValue);

                Dispatcher.Invoke(updatePbDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { System.Windows.Controls.ProgressBar.ValueProperty, value });
            }
        }
Beispiel #29
0
        public AnalisisSensibilidadSimulacionPopUp(string simulationPath, List <string> vicPaths, AnalisisSensibilidadPopUp analisisSensibilidadPopUp)
        {
            InitializeComponent();
            this.simulationPath            = simulationPath;
            this.simulationStoped          = false;
            this.vicPaths                  = vicPaths;
            this.analisisSensibilidadPopUp = analisisSensibilidadPopUp;
            this.mustPrint                 = false;
            this.stagesFinished            = new List <string>();
            double totalValue = 0;

            this.stages = new ObservableCollection <StageViewModelBase>();
            this.simulationStartedTime = DateTime.Now;
            this.conTiempoFinal        = false;

            foreach (string vicPath in vicPaths)
            {
                string simulationFile = File.ReadAllText(vicPath);
                var    simulation     = XMLParser.GetSimulation(simulationFile);
                if (simulation.Stages.Any())
                {
                    var            s     = simulation.Stages.First();
                    StageViewModel stage = new StageViewModel(simulation, s)
                    {
                        Name = s.Name
                    };
                    this.stages.Add(stage);
                    Variable tiempoFinal = stage.Simulation.GetVariables().First(v => v.Name == "TF");
                    if (tiempoFinal != null && tiempoFinal.InitialValue > 0)
                    {
                        this.conTiempoFinal = true;
                        totalValue          = totalValue + stage.Simulation.GetVariables().First(v => v.Name == "TF").InitialValue;
                        stage.Variables.First(v => v.Name == "T").PropertyChanged += VariableTChanged;
                    }
                    stage.Simulation.SimulationStatusChanged += OnSimulationStatusChanged;
                    //stage.ExecuteStageCommand.Execute(null);
                }
            }
            if (this.conTiempoFinal)
            {
                barraProgreso.Minimum   = 0;
                barraProgreso.Maximum   = totalValue;
                barraProgreso.Value     = 0;
                this.barraProgresoValue = 0;
                this.updatePbDelegate   = new UpdateProgressBarDelegate(barraProgreso.SetValue);
            }
            else
            {
                barraProgreso.IsIndeterminate = true;
            }
            // Despues que quedó configurada la barra y eso, mando a ejecutar
            foreach (StageViewModel stage in this.stages)
            {
                stage.ExecuteStageCommand.Execute(null);
            }
        }
Beispiel #30
0
        private void ImageToText()
        {
            #region проверка символов

            int    countY = image.Height / 40;
            int    countX = image.Width / 40;
            string answer = "";

            double value;
            UpdateProgressBarDelegate updProgress = new UpdateProgressBarDelegate(Bar.SetValue);

            for (int p = 0; p < countY; p++)
            {
                for (int k = 0; k < countX; k++)
                {
                    Bitmap   symbol = new Bitmap(35, 35);
                    Graphics g      = Graphics.FromImage(symbol);
                    g.DrawImage(image, 0, 0, new Rectangle(k * 40, p * 40, 35, 35), GraphicsUnit.Pixel);

                    //symbol = image.Clone(new Rectangle(k*40, p*40, 35, 35), PixelFormat.Format32bppArgb);

                    FileInfo[] dd = new DirectoryInfo(@"symbols").GetFiles();
                    bool       ok = false;
                    foreach (FileInfo f in dd)
                    {
                        Bitmap frame = LoadBitmap(@"symbols/" + f.Name);
                        bool   upper;
                        if (CheckSymbol(symbol, frame, out upper))
                        {
                            ok = true;
                            string s = f.Name.Remove(f.Name.IndexOf("."));
                            if (upper)
                            {
                                s = s.ToUpper();
                            }
                            answer += s == "BLANK" ? " " : s;
                            break;
                        }
                    }
                    if (!ok)
                    {
                        MessageBox.Show("Произошла ошибка в распознавании символа " + (p * countY + k + 1));
                        return;
                    }
                    value = k + countX * p + 1;
                    Dispatcher.Invoke(updProgress, ProgressBar.ValueProperty, value);
                }
            }

            MessageBox.Show("Ваше сообщение расшифровано", "Готово");
            image = null;

            Dispatcher.Invoke(ll, TextBox.TextProperty, answer.Trim());
            #endregion проверка символов
        }
        public formLoadData()
        {
            InitializeComponent();
            this.builder = new StringBuilder();

            this.txtLog.Text = this.builder.ToString();

            UpdateProgressBar = new UpdateProgressBarDelegate(this.UpdateProgressBarMethod);
            UpdateTextLabel   = new UpdateTextLabelDelegate(this.UpdateTextLabelMethod);
            UpdateTextLog     = new UpdateTextLogDelegate(this.UpdateTextLogMethod);
        }
 private void StandardInitialization()
 {
     InitializeComponent();
     updateMainLabel     = new UpdateLabelDelegate(UpdateMainLabel);
     updateProgressBar   = new UpdateProgressBarDelegate(UpdateProgressBar);
     updateBottomBar     = new UpdateLabelDelegate(UpdateBottomBar);
     uploadFiles         = new EmptyDelegate(StartFileUploadThreadSafe);
     CloseOnComplete     = true;
     formTimer.AutoReset = false;
     formTimer.Elapsed  += formTimer_Elapsed;
 }
Beispiel #33
0
        public MainWindow()
        {
            api = new VkApi();
            InitializeComponent();

            updatePbDelegate = new UpdateProgressBarDelegate(pbProgress.SetValue);

            TimeTo         = DateTime.Now;
            tbDataTo.Text  = TimeTo.Day + "." + TimeTo.Month + "." + TimeTo.Year;
            TimeTo2        = DateTime.Now;
            tbDataTo2.Text = TimeTo2.Day + "." + TimeTo2.Month + "." + TimeTo2.Year;
            try {
                LoadOptions();
                UserPassword = pbPassword.Password;
            }
            catch {
                LoadCommplite   = true;
                lErrors.Content = "Не удалось загрузить параметры. Будут использованы параметры по умолчанию.";
            }

            try {
                LoadMessage();
            }
            catch {
                lErrors2.Document.Blocks.Clear();
                lErrors2.Document.Blocks.Add(new Paragraph(new Run("Не удалось загрузить сохранённые сообщения. Возможно файл с сообщиниями не существует.")));
                //lErrors2.Content = "Не удалось загрузить сохранённые сообщения. Возможно файл с сообщиниями не существует.";
            }

            try {
                api.Authorize(new ApiAuthParams {
                    ApplicationId = 5539924,
                    Login         = ULogin,
                    Password      = UserPassword,
                    Settings      = Settings.All
                });

                uint countAlbums = (uint)api.Photo.GetAlbumsCount(groupId: groupId);
                AllAlbums = api.Photo.GetAlbums(new PhotoGetAlbumsParams {
                    Count = countAlbums, OwnerId = -groupId
                }, skipAuthorization: true);
                for (int i = 0; i < countAlbums; i++)
                {
                    cbAlbum.Items.Add("Альбом № " + (i + 1) + " имя: " + AllAlbums[i].Title + ". Количество фотографий: " + AllAlbums[i].Size);
                    cbAlbum2.Items.Add("Альбом № " + (i + 1) + " имя: " + AllAlbums[i].Title + ". Количество фотографий: " + AllAlbums[i].Size);
                }
                cbAlbum.Items.Add("Все альбомы");
                cbAlbum.SelectedIndex  = cbAlbum.Items.Count - 1;
                cbAlbum2.SelectedIndex = 0;
            }
            catch (Exception) {
                lErrors.Content = "Не удалось загрузить альбомы. Возможно нет подключения к интернету.";
            }
        }
        public MainWindow()
        {
            InitializeComponent();
            //MessageBox.Show(FSystem.ListDirContent("D:\\"));

            //thatSocketRecv.ReceiveFrom();

            UpdateProgressBarDelegate updatePbDelegate = new UpdateProgressBarDelegate(thatSocketRecv.ReceiveFrom);

            //Application.Current.Dispatcher.Invoke(updatePbDelegate, System.Windows.Threading.DispatcherPriority.Background);
        }
Beispiel #35
0
        private void btnStart_Click(object sender, RoutedEventArgs e)
        {
            UpdateProgressBarDelegate updatePbDelegate = new UpdateProgressBarDelegate(pbProgress.SetValue);

            List<string> l = new List<string>();
            foreach (var item in lbDirectories.Items)
            {
                l.Add((string)item);
            }
            string[] s = { ".mp3", ".ogg", ".wma" };
            DirectoryHelper.SuperDirectoryCollection coll = DirectoryHelper.ScanDirectories(l.ToArray());

            coll.ApplyExtensionFilter(s);


            tbStatus.Text = "Directories: " + coll.DirectoryCount.ToString() + "  |  Files: " + coll.FileCount.ToString();

            pbProgress.Minimum = 0;
            pbProgress.Maximum = coll.FileCount;

            double i = pbProgress.Value;


            MainWindow w = this.Owner as MainWindow;
            Database sta = w.AudioEngine.Datastore;

            foreach (DirectoryHelper.SuperDirectory sd in coll.Items)
            {
                List<string> filelist = sd.GetFileList();
                foreach (string file in filelist)
                {
                    FileInfo f = new FileInfo(file);
                    DirectoryInfo d = f.Directory;
                    if (!sta.Songs.Contains(f))
                    {
                        sta.Songs.AddFile(f);
                        i++;
                        Dispatcher.Invoke(updatePbDelegate,
                            System.Windows.Threading.DispatcherPriority.Background,
                            new object[] { ProgressBar.ValueProperty, i });
                    }

                }
            }
        }
Beispiel #36
0
        private void UpdateProgresBar(string data)
        {
            if (progressBar1.InvokeRequired)
            {
                UpdateProgressBarDelegate d = new UpdateProgressBarDelegate(UpdateProgresBar);
                Invoke(d, data);
            }
            else
            {
                progressBar1.Value += 1;
                label1.Text = String.Format("Finished downloading file: {0}", data);

                if (progressBar1.Value == progressBar1.Maximum)
                {
                    label1.Text = "Building local database...";
                    progressBar1.Style = ProgressBarStyle.Marquee;
                }
            }
        }
Beispiel #37
0
        public void StartTagging()
        {
            wndMainWindow = this.Owner as MainWindow;

            UpdateProgressBarDelegate updatePbDelegate = new UpdateProgressBarDelegate(pbProgress.SetValue);
            UpdateProgressTextDelegate updatePtDelegate = new UpdateProgressTextDelegate(txtResults.SetValue);
            double i = 0.0;
            int total = wndMainWindow.AudioEngine.Playlist.Count;
            pbProgress.Minimum = i;
            pbProgress.Maximum = total;
            string t = "Initializing...";
            int idx = 0;

            int c = wndMainWindow.AudioEngine.Playlist.Count();
            Database.Song[] temp = new Database.Song[c];
            wndMainWindow.AudioEngine.Playlist.CopyTo(temp, 0);
            // can't modify the playlist if its the subject of the foreach, so we have to make a copy.


            foreach (Database.Song row in temp)
            {
                i++;
                t += "\n" + "Processing file " + i.ToString() + " of " + total.ToString() + " | " + row.Filename;

                Dispatcher.Invoke(updatePtDelegate,
                    System.Windows.Threading.DispatcherPriority.Background,
                    new object[] { TextBox.TextProperty, t });

                AudioEngine.Fingerprint(row);

                wndMainWindow.AudioEngine.Playlist.RemoveAt(idx);
                wndMainWindow.AudioEngine.Playlist.Insert(idx, row);

                Dispatcher.Invoke(updatePbDelegate,
                    System.Windows.Threading.DispatcherPriority.Background,
                    new object[] { ProgressBar.ValueProperty, i });

                idx++;
            }

            this.btnClose.IsEnabled = true;
        }
        private void FindFilesClick(object sender, RoutedEventArgs e)
        {
            ClearVars();
            stopBtn.IsEnabled = true;
            clearBtn.IsEnabled = false;
            if(!Directory.Exists(searchDir.Text)){
                var msg = "Directory " + searchDir.Text + " does not exists.";
                MessageBox.Show(msg, "No Such Directory");
                return;
            }

            if(string.IsNullOrEmpty(searchPattern.Text))
                searchPattern.Text = "*";
            var di = new DirectoryInfo(searchDir.Text);
            var files = di.GetFiles(searchPattern.Text, _dirChoice);

            double value = 0;
            progressBar1.Minimum = 0;
            progressBar1.Maximum = files.Length;
            progressBar1.Value = 0;

            var updatePbDelegate = new UpdateProgressBarDelegate(progressBar1.SetValue);
            var updateCurFile = new UpdateLabelDelegate(curFileLabel.SetValue);

            foreach (var file in files)
            {
                if (_stop)
                {
                    _stop = false;
                    break;
                }
                value += 1;
                Dispatcher.Invoke(updatePbDelegate,
                    System.Windows.Threading.DispatcherPriority.Background,
                    new object[] { ProgressBar.ValueProperty, value });

                var progressMessage = "Scanning: " + file.FullName;
                Dispatcher.Invoke(updateCurFile,
                    System.Windows.Threading.DispatcherPriority.Background,
                    new object[] { TextBox.TextProperty, progressMessage });

                var md5 = "";
                if (!_nameOnly)
                {
                    var findHash = new findMD5();
                    md5 = findHash.getFilesMD5Hash(file.FullName);
                }

                var fStruct = new fileStruct{ checksum = md5, fileName = file.Name, fullPath = file.FullName, creationDate=file.CreationTime };
                _listOfFiles.Add(fStruct);
            }

            curFileLabel.Text = "";
            ArrayList duplicates = new ArrayList();

            if (_nameOnly)
            {
                _listOfFiles.Sort(_compareByFileName);
                duplicates = _duplicateFiles.findDuplicatesByFileName(_listOfFiles);
            }
            else
            {
                _listOfFiles.Sort(_compareByCheckSum);
                duplicates = _duplicateFiles.findDuplicatesByCheckSum(_listOfFiles);
            }

            foreach(fileStruct file in duplicates){
                fileStructListView.Items.Add(file);
            }
            stopBtn.IsEnabled = false;
            clearBtn.IsEnabled = true;
            selectOldestBtn.IsEnabled = true;
            selectNewestBtn.IsEnabled = true;
            progressBar1.Value = 0;
        }
        /// <summary>
        /// Lanzamiento del update
        /// </summary>
        private void lanzarUpdate()
        {
            try
            {
                actualProces = 0;
                actualProces++;
                // Create a new instance of our ProgressBar Delegate that points
                // to the ProgressBar's SetValue method.
                updatePbDelegate =
                    new UpdateProgressBarDelegate(pBar.SetValue);
                Dispatcher.Invoke(updatePbDelegate,
                System.Windows.Threading.DispatcherPriority.Background, new object[] { ProgressBar.ValueProperty, Convert.ToDouble(actualProces) });
                if (this.validacionBD() )
                if( this.checkSMS() != 0)
                {
                    this.addText("Comprobando la conectividad de la red\n");
                    if (NetworkInterface.GetIsNetworkAvailable())
                   {
                        this.addText("Conectividad de la red comprobada\n");
                        int numIntentos = 1;
                        int numIntentosMax = 1;
                        int tiempoEspera = 1 ;
                        //Obteniendo num maximo de intentos
                        try
                        {
                            numIntentosMax = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["NumReintentos"]);
                        }
                        catch(Exception ex)
                        {
                            this.addText("Formato de número de intentos invalido - " + ex.Message );
                             numIntentos = 1;
                        }
                        //Obteniendo tiempo de espera entre intentos
                        try
                        {
                            tiempoEspera = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SegsTiempoReintento"]);
                        }
                        catch(Exception ex2)
                        {
                            this.addText("Formato de tiempo de espera invalido - " + ex2.Message);
                             numIntentos = 1;
                        }
                        //Intentos de conexion
                        while (numIntentos <= numIntentosMax)
                        {
                            this.addText("Comprobando la conectividad de la carpeta de datos - intento "+numIntentos+" / "+numIntentosMax+"\n");
                            if (this.getStatusConn())
                            {
                                this.addText("Conectividad de la carpeta de datos comprobada\n");
                                this.addText("Iniciando sincronización de KPIs\n");

                                //--------- INI BZG - Elimina Carpeta temporal -------------
                                EliminaArchivosTemporales();
                                //--------- FIN BZG - Elimina Carpeta temporal -------------

                                //Sincronizando
                                //--------------   INI BZG ----------------
                                territorio = this.ValidaCambioTerritorio();
                                //--------------   FIN BZG ----------------
                                this.sincroniceKPIs();
                                this.sincroniceCatalogos();
                                DateTime stopTime = DateTime.Now;
                                double totalSeconds = (double)stopTime.Ticks / TimeSpan.TicksPerSecond;
                                string dateFormat = stopTime.ToString("yyyyMMddHHmmssffff");
                                long fecha_sin_int = Convert.ToInt64(dateFormat);
                                int duracion = 0;
                                Consultas c = new Consultas();
                                c.InsertVitacora(usuario, WindowsIdentity.GetCurrent().Name, DateTime.Now, versionCliente, duracion, null, territorio, fecha_sin_int, true);

                                if (this.getText().ToLower().Contains("error"))
                                {
                                    MessageBox.Show("El proceso de sincronización terminó con al menos un error. Favor de contactar a Help Desk.");
                                    //MessageBox.Show("El proceso de actualización terminó, pero se registró un problema, verifique el detalle de la ejecución.");
                                }
                                else
                                    MessageBox.Show("El proceso de sincronización de KPIs terminó exitosamente.");
                                    //MessageBox.Show("El proceso de actualización terminó, por favor verifique el log para constatar la ejecución del proceso");
                                string delay = System.Configuration.ConfigurationManager.AppSettings["SegsTiempoComprobacionConexion"];
                                try
                                {
                                    int delayNew = Convert.ToInt32(delay);
                                    delayNew = delayNew + 5;
                                    System.Threading.Thread.Sleep(delayNew * 1000);
                                }
                                catch (Exception)
                                {
                                }
                                this.reinitPrincipal();
                                break;
                            }
                            else
                            {
                                this.addText("No se encontró conexión con la carpeta de datos de aplicación " + System.Configuration.ConfigurationManager.AppSettings["CarpetaCompartida"] + "\n");
                                numIntentos++;
                                System.Threading.Thread.Sleep(tiempoEspera);
                            }
                        }
                        //Comprobando maximo de intentos
                        if (numIntentos > numIntentosMax)
                        {
                            this.addText("Los intentos de conectividad superaron el máximo de intentos "+numIntentos+"/"+numIntentosMax+"\n");
                        }
                   }
                    else
                    {
                        MessageBox.Show("No se encontró conexión de red disponible");
                    }
                }
                actualProces++;
                Dispatcher.Invoke(updatePbDelegate,
                System.Windows.Threading.DispatcherPriority.Background, new object[] { ProgressBar.ValueProperty, Convert.ToDouble(actualProces) });

            this.btnEjecutarEnabled(true);
            }
            catch (Exception ex3)
            {
                this.btnEjecutarEnabled(true);
                this.addText("Error en la ejecución de la actualización : " + ex3.Message);
                MessageBox.Show("Ocurrió un error en la ejecución de la actualización - " + ex3.Message);
            }
        }
        //private void LoadInitConfig()
        //{
        //    //加载ini文件内容
        //    try
        //    {
        //        if (App.reportSettingModel == null)
        //        {
        //            App.reportSettingModel = new ReportSettingModel();
        //            App.reportSettingModel.MeikBase = OperateIniFile.ReadIniData("Base", "MEIK base", "C:\\MEIKData", System.AppDomain.CurrentDomain.BaseDirectory + "Config.ini");
        //            App.reportSettingModel.Version = OperateIniFile.ReadIniData("Base", "Version", "1.0.0", System.AppDomain.CurrentDomain.BaseDirectory + "Config.ini");
        //            App.reportSettingModel.HasNewer = Convert.ToBoolean(OperateIniFile.ReadIniData("Base", "Newer", "false", System.AppDomain.CurrentDomain.BaseDirectory + "Config.ini"));
        //            App.reportSettingModel.MailSsl = Convert.ToBoolean(OperateIniFile.ReadIniData("Report", "Use Default Signature", "false", System.AppDomain.CurrentDomain.BaseDirectory + "Config.ini"));
        //            string doctorNames = OperateIniFile.ReadIniData("Report", "Doctor Names List", "", System.AppDomain.CurrentDomain.BaseDirectory + "Config.ini");                    
        //            if (!string.IsNullOrEmpty(doctorNames))
        //            {                        
        //                var doctorList = doctorNames.Split(';').ToList<string>();
        //                //doctorList.ForEach(item => App.reportSettingModel.DoctorNames.Add(item));
        //                foreach (var item in doctorList)
        //                {
        //                    User doctorUser=new User();
        //                    string[] arr = item.Split('|');
        //                    doctorUser.Name = arr[0];
        //                    doctorUser.License = arr[1];
        //                    App.reportSettingModel.DoctorNames.Add(doctorUser);
        //                }                        
        //            }
        //            string techNames = OperateIniFile.ReadIniData("Report", "Technician Names List", "", System.AppDomain.CurrentDomain.BaseDirectory + "Config.ini");                    
        //            if (!string.IsNullOrEmpty(techNames))
        //            {
        //                var techList = techNames.Split(';').ToList<string>();
        //                //techList.ForEach(item => App.reportSettingModel.TechNames.Add(item));
        //                foreach (var item in techList)
        //                {
        //                    User techUser = new User();
        //                    string[] arr = item.Split('|');
        //                    techUser.Name = arr[0];
        //                    techUser.License = arr[1];
        //                    App.reportSettingModel.TechNames.Add(techUser);
        //                }
        //            }

        //            App.reportSettingModel.NoShowDoctorSignature = Convert.ToBoolean(OperateIniFile.ReadIniData("Report", "Hide Doctor Signature", "false", System.AppDomain.CurrentDomain.BaseDirectory + "Config.ini"));
        //            App.reportSettingModel.NoShowTechSignature = Convert.ToBoolean(OperateIniFile.ReadIniData("Report", "Hide Technician Signature", "false", System.AppDomain.CurrentDomain.BaseDirectory + "Config.ini"));
        //            App.reportSettingModel.FtpPath = OperateIniFile.ReadIniData("FTP", "FTP Path", "", System.AppDomain.CurrentDomain.BaseDirectory + "Config.ini");
        //            App.reportSettingModel.FtpUser = OperateIniFile.ReadIniData("FTP", "FTP User", "", System.AppDomain.CurrentDomain.BaseDirectory + "Config.ini");
        //            string ftpPwd = OperateIniFile.ReadIniData("FTP", "FTP Password", "", System.AppDomain.CurrentDomain.BaseDirectory + "Config.ini");
        //            if (!string.IsNullOrEmpty(ftpPwd))
        //            {
        //                App.reportSettingModel.FtpPwd = SecurityTools.DecryptText(ftpPwd);
        //            }
                    
        //            App.reportSettingModel.PrintPaper = (PageSize)Enum.Parse(typeof(PageSize),OperateIniFile.ReadIniData("Report", "Print Paper", "Letter", System.AppDomain.CurrentDomain.BaseDirectory + "Config.ini"),true);
        //            App.reportSettingModel.MailAddress = OperateIniFile.ReadIniData("Mail", "My Mail Address", "", System.AppDomain.CurrentDomain.BaseDirectory + "Config.ini");
        //            App.reportSettingModel.ToMailAddress = OperateIniFile.ReadIniData("Mail", "To Mail Address", "", System.AppDomain.CurrentDomain.BaseDirectory + "Config.ini");
        //            App.reportSettingModel.MailSubject = OperateIniFile.ReadIniData("Mail", "Mail Subject", "", System.AppDomain.CurrentDomain.BaseDirectory + "Config.ini");
        //            App.reportSettingModel.MailBody = OperateIniFile.ReadIniData("Mail", "Mail Content", "", System.AppDomain.CurrentDomain.BaseDirectory + "Config.ini");
        //            App.reportSettingModel.MailHost = OperateIniFile.ReadIniData("Mail", "Mail Host", "", System.AppDomain.CurrentDomain.BaseDirectory + "Config.ini");
        //            App.reportSettingModel.MailPort = Convert.ToInt32(OperateIniFile.ReadIniData("Mail", "Mail Port", "25", System.AppDomain.CurrentDomain.BaseDirectory + "Config.ini"));
        //            App.reportSettingModel.MailUsername = OperateIniFile.ReadIniData("Mail", "Mail Username", "", System.AppDomain.CurrentDomain.BaseDirectory + "Config.ini");
        //            string mailPwd=OperateIniFile.ReadIniData("Mail", "Mail Password", "", System.AppDomain.CurrentDomain.BaseDirectory + "Config.ini");
        //            if(!string.IsNullOrEmpty(mailPwd)){
        //                App.reportSettingModel.MailPwd = SecurityTools.DecryptText(mailPwd);
        //            }                    
        //            App.reportSettingModel.MailSsl = Convert.ToBoolean(OperateIniFile.ReadIniData("Mail", "Mail SSL", "false", System.AppDomain.CurrentDomain.BaseDirectory + "Config.ini"));
        //            App.reportSettingModel.DeviceNo = OperateIniFile.ReadIniData("Device", "Device No", "000", System.AppDomain.CurrentDomain.BaseDirectory + "Config.ini");
        //            App.reportSettingModel.DeviceType = Convert.ToInt32(OperateIniFile.ReadIniData("Device", "Device Type", "1", System.AppDomain.CurrentDomain.BaseDirectory + "Config.ini"));
        //        }                
        //    }
        //    catch (Exception ex)
        //    {
        //        MessageBox.Show(this, App.Current.FindResource("Message_9").ToString() + " " + ex.Message);
        //    }
                        
        //}
        

        /// <summary>
        /// 立即进行版本更新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnUpdateNow_Click(object sender, RoutedEventArgs e)
        {
            MessageBoxResult result = MessageBox.Show(this, App.Current.FindResource("Message_46").ToString(), "Update Now", MessageBoxButton.YesNo, MessageBoxImage.Information);
            if (result == MessageBoxResult.Yes)
            {
                //定义委托代理
                ProgressBarGridDelegate progressBarGridDelegate = new ProgressBarGridDelegate(progressBarGrid.SetValue);
                UpdateProgressBarDelegate updatePbDelegate = new UpdateProgressBarDelegate(uploadProgressBar.SetValue);
                //使用系统代理方式显示进度条面板
                Dispatcher.Invoke(updatePbDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { System.Windows.Controls.ProgressBar.ValueProperty, Convert.ToDouble(5) });
                Dispatcher.Invoke(progressBarGridDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { System.Windows.Controls.Grid.VisibilityProperty, Visibility.Visible });
                
                try
                {
                    string ftpPath = App.reportSettingModel.FtpPath.Replace("home", "MeikUpdate");
                    //查询FTP上所有版本文件列表要下载的文件列表
                    var fileList = FtpHelper.Instance.GetFileList(App.reportSettingModel.FtpUser, App.reportSettingModel.FtpPwd, ftpPath);                    
                    fileList.Reverse();
                    foreach (var setupFileName in fileList)
                    {
                        if (setupFileName.EndsWith(".exe", StringComparison.OrdinalIgnoreCase))
                        {
                            var verStr = setupFileName.ToLower().Replace(".exe", "").Replace("meiksetup.", "");
                            string currentVer=App.reportSettingModel.Version;
                            if (string.Compare(verStr, currentVer,StringComparison.OrdinalIgnoreCase) > 0)
                            {
                                //下載新的升級安裝包
                                FtpWebRequest reqFTP;
                                try
                                {
                                    FileStream outputStream = new FileStream(App.reportSettingModel.DataBaseFolder + System.IO.Path.DirectorySeparatorChar + setupFileName, FileMode.Create);
                                    reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath + setupFileName));
                                    reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                                    reqFTP.UseBinary = true;
                                    reqFTP.Credentials = new NetworkCredential(App.reportSettingModel.FtpUser, App.reportSettingModel.FtpPwd);
                                    reqFTP.UsePassive = false;
                                    FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                                    Stream ftpStream = response.GetResponseStream();
                                    long cl = response.ContentLength;
                                    int bufferSize = 2048;
                                    double moveSize = 100d / (cl / 2048);
                                    int x = 1;
                                    int readCount;
                                    byte[] buffer = new byte[bufferSize];
                                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                                    while (readCount > 0)
                                    {
                                        outputStream.Write(buffer, 0, readCount);
                                        readCount = ftpStream.Read(buffer, 0, bufferSize);
                                        Dispatcher.Invoke(updatePbDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { System.Windows.Controls.ProgressBar.ValueProperty, Convert.ToDouble(moveSize * x) });
                                        x++;
                                    }
                                    ftpStream.Close();
                                    outputStream.Close();
                                    response.Close();
                                }
                                catch (Exception ex2)
                                {
                                    throw ex2;
                                }

                                //FtpHelper.Instance.Download(App.reportSettingModel.FtpUser, App.reportSettingModel.FtpPwd, ftpPath, App.reportSettingModel.DataBaseFolder, setupFileName);
                                Dispatcher.Invoke(updatePbDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { System.Windows.Controls.ProgressBar.ValueProperty, Convert.ToDouble(100) });
                                Dispatcher.Invoke(progressBarGridDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { System.Windows.Controls.Grid.VisibilityProperty, Visibility.Collapsed });
                                MessageBox.Show(this, App.Current.FindResource("Message_48").ToString());

                                try
                                {
                                    //启动外部程序
                                    Process setupProc = Process.Start(App.reportSettingModel.DataBaseFolder + System.IO.Path.DirectorySeparatorChar + setupFileName);
                                    if (setupProc != null)
                                    {                                       
                                        //proc.WaitForExit();//等待外部程序退出后才能往下执行
                                        setupProc.WaitForInputIdle();                                        
                                        File.Copy(System.AppDomain.CurrentDomain.BaseDirectory + "Config.ini", System.AppDomain.CurrentDomain.BaseDirectory + "Config_bak.ini", true);                                        
                                        OperateIniFile.WriteIniData("Base", "Version", verStr, System.AppDomain.CurrentDomain.BaseDirectory + "Config_bak.ini");                                                                       
                                        //关闭当前程序
                                        App.Current.Shutdown();
                                    }
                                }
                                catch (Exception ex)
                                {
                                    MessageBox.Show(App.Current.FindResource("Message_51").ToString() + " " + ex.Message);
                                }


                            }
                            break;
                        }
                        else
                        {
                            continue;
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this, App.Current.FindResource("Message_47").ToString() + " " + ex.Message);
                }
                finally
                {
                    Dispatcher.Invoke(progressBarGridDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { System.Windows.Controls.Grid.VisibilityProperty, Visibility.Collapsed });
                }
            }
        }
        public void PrintTickets()
        {
            try
            {
                App application = App.Current as App;
                Thread.CurrentThread.CurrentUICulture = application.CurrentUICulture;
                Thread.CurrentThread.CurrentCulture = application.CurrentCulture;

                this.Dispatcher.Invoke(new Action(() =>
                {
                    pbPrint.Value = _NoOfPrintedTickets;
                    this.lblErrorMsg.Content = string.Empty;
                    this.lblPrintedTicket.Content = _NoOfPrintedTickets;
                    this.lblTotalTicket.Content = _NoOfTickets;
                    pbPrint.Minimum = _NoOfPrintedTickets;
                    pbPrint.Maximum = _NoOfTickets;
                }), System.Windows.Threading.DispatcherPriority.Normal);


                long lValue = 0;
                if (strValue != null && strValue != string.Empty)
                    lValue = Convert.ToInt64(strValue.GetSingleFromString() * 100);
                else
                    lValue = 0;

                this.Dispatcher.Invoke(new Action(() =>
                {
                    pbPrint.Value = _NoOfPrintedTickets;
                }), System.Windows.Threading.DispatcherPriority.Normal);

                Promotional objPromotional = new Promotional();

                try
                {
                    while ((_NoOfPrintedTickets < _NoOfTickets) && !_mreShutdown.WaitOne(1))
                    {
                        if (_mreResume.WaitOne())
                        {
                            if (_mreShutdown.WaitOne(10))
                            {
                                LogManager.WriteLog("Print screen was closed. So exiting now.", LogManager.enumLogLevel.Info);
                                return;
                            }
                        }

                        this.Dispatcher.Invoke(new Action(() =>
                        {

                            lblPrintedTicket.Content = _NoOfPrintedTickets.ToString();
                            lblTotalTicket.Content = _NoOfTickets.ToString();
                        }), System.Windows.Threading.DispatcherPriority.Normal);


                        if (true)
                        {

                            string strBarcode;
                            this.Dispatcher.Invoke(new Action(() =>
                            {
                                pbPrint.Value = _NoOfPrintedTickets;
                            }), System.Windows.Threading.DispatcherPriority.Normal);
                            
                            IssueTicketEntity issueTicketEntity = new IssueTicketEntity();
                            issueTicketEntity.Type = UIIssueTicketConstants.STANDARDTICKET;
                            if (PromoTicketType == 1)
                                issueTicketEntity.TicketHeader = "PLAYABLE VOUCHER";
                            else if (PromoTicketType == 0)
                                issueTicketEntity.TicketHeader = "CASHABLE PROMO VOUCHER";
                            else
                                issueTicketEntity.TicketHeader = "CASH DESK VOUCHER";

                            LogManager.WriteLog("Ticket Header : " + issueTicketEntity.TicketHeader, LogManager.enumLogLevel.Info);

                         //   issueTicketEntity.VoidDate = DateTime.Now.ToString();// (Convert.ToDateTime(this.ExpiryDate, new CultureInfo(ExtensionMethods.CurrentDateCulture))).ToString();
                            issueTicketEntity.VoidDate = (Convert.ToDateTime(this.ExpiryDate, new CultureInfo(ExtensionMethods.CurrentDateCulture))).ToString();
                            issueTicketEntity.dblValue = Convert.ToDouble(this.PromotionTicketAmount, new CultureInfo(ExtensionMethods.CurrentCurrenyCulture)); ;
                            issueTicketEntity.lnglValue = long.Parse((this.PromotionTicketAmount * 100).ToString());
                            System.TimeSpan ts = (ExpiryDate).Subtract(DateTime.Now);
                            issueTicketEntity.NumberOfDays = ts.Days;
                            // issueTicketEntity.Date = DateTime.Now;

                            string PrintedDateTime = string.Empty;
                            //PrintedDateTime = (Convert.ToDateTime(System.DateTime.Now, new CultureInfo(ExtensionMethods.CurrentDateCulture))).ToString();

                            issueTicketEntity.Date = DateTime.Now;//Convert.ToDateTime(PrintedDateTime);
                            PrintTicketErrorCodes PrintResult = objCashDeskOperator.IssueTicket(issueTicketEntity);
                            strBarcode = issueTicketEntity.BarCode;
                            this.Dispatcher.Invoke(new Action(() =>
                            {
                                this.lblErrorMsg.Visibility = Visibility.Visible;
                                this.pbPrint.Visibility = Visibility.Visible;
                                this.lblPrintedTicket.Visibility = Visibility.Visible;
                                this.lblTotalTicket.Visibility = Visibility.Visible;
                                this.btnCancel.Visibility = Visibility.Visible;
                                this.btnPause.Visibility = Visibility.Visible;


                                switch (PrintResult)
                                {
                                    case PrintTicketErrorCodes.OpenCOMPortFailure:
                                        {
                                            _FailureTickets++;
                                            //    MessageBox.ShowBox("MessageID295", BMC_Icon.Warning); //Unable to open COM Port. Please check connectivity.
                                            lblErrorMsg.Content = "Unable to open COM Port. Please check connectivity";
                                            return;
                                        }
                                    case PrintTicketErrorCodes.OutofPaper:
                                        {
                                            _FailureTickets++;
                                            //  MessageBox.ShowBox("MessageID294", BMC_Icon.Warning); //out of Paper
                                            lblErrorMsg.Content = "Out of Paper";
                                            return;
                                        }
                                    case PrintTicketErrorCodes.Success:
                                        {

                                            lblErrorMsg.Content = string.Empty;
                                            _SucceededTickets++;
                                            pbPrint.Value = _NoOfPrintedTickets;


                                            if (!String.IsNullOrEmpty(DisplayTicketPrintedSuccessMsg))
                                            {
                                                if (DisplayTicketPrintedSuccessMsg.ToUpper().Trim() == "TRUE")
                                                {
                                                    lblErrorMsg.Content = " Voucher printed successfully";
                                                }
                                            }
                                            _NoOfPrintedTickets += 1;


                                            pbPrint.Value = _NoOfPrintedTickets;
                                            lblPrintedTicket.Content = _NoOfPrintedTickets.ToString();
                                            int UpdateVoucherPromotionID = objPromotional.BUpdateVoucherPromotion(this.PromotionID, strBarcode);//Update PromotionalID in Voucher Table

                                            break;
                                        }
                                    case PrintTicketErrorCodes.eVoltErr:
                                        {
                                            _FailureTickets++;
                                            // MessageBox.ShowBox("MsgPromErr1", BMC_Icon.Error);
                                            lblErrorMsg.Content = "Voltage Error";

                                            return;
                                        }
                                    case PrintTicketErrorCodes.eHeadErr:
                                        {
                                            _FailureTickets++;
                                            //  MessageBox.ShowBox("MsgPromErr2", BMC_Icon.Error);
                                            lblErrorMsg.Content = " Printer Head Error";
                                            return;
                                        }
                                    case PrintTicketErrorCodes.ePaperOut:
                                        {
                                            _FailureTickets++;
                                            // MessageBox.ShowBox("MsgPromErr3", BMC_Icon.Error);
                                            lblErrorMsg.Content = "Out of Paper";
                                            return;
                                        }
                                    case PrintTicketErrorCodes.ePlatenUP:
                                        {
                                            _FailureTickets++;
                                            //  MessageBox.ShowBox("MsgPromErr4", BMC_Icon.Error);
                                            lblErrorMsg.Content = "Platen Up";
                                            return;
                                        }
                                    case PrintTicketErrorCodes.eSysErr:
                                        {
                                            _FailureTickets++;
                                            // MessageBox.ShowBox("MsgPromErr5", BMC_Icon.Error);
                                            lblErrorMsg.Content = "System Error";
                                            return;
                                        }
                                    case PrintTicketErrorCodes.eBusy:
                                        {
                                            _FailureTickets++;
                                            //   MessageBox.ShowBox("MsgPromErr6", BMC_Icon.Error);
                                            lblErrorMsg.Content = "Printer is Busy";
                                            return;
                                        }
                                    case PrintTicketErrorCodes.eJobMemOF:
                                        {
                                            _FailureTickets++;
                                            //  MessageBox.ShowBox("MsgPromErr7", BMC_Icon.Error);
                                            lblErrorMsg.Content = "Job Memory off";
                                            return;
                                        }
                                    case PrintTicketErrorCodes.eBufOF:
                                        {
                                            _FailureTickets++;
                                            // MessageBox.ShowBox("MsgPromErr8", BMC_Icon.Error);
                                            lblErrorMsg.Content = "Buffer off";
                                            return;
                                        }
                                    case PrintTicketErrorCodes.eLibLoadErr:
                                        {
                                            _FailureTickets++;
                                            //  MessageBox.ShowBox("MsgPromErr9", BMC_Icon.Error);
                                            lblErrorMsg.Content = "Library Load Error";
                                            return;
                                        }
                                    case PrintTicketErrorCodes.ePRDataErr:
                                        {
                                            _FailureTickets++;
                                            //   MessageBox.ShowBox("MsgPromErr10", BMC_Icon.Error);
                                            lblErrorMsg.Content = "Printer Data Error";
                                            return;
                                        }
                                    case PrintTicketErrorCodes.eLibRefErr:
                                        {
                                            _FailureTickets++;
                                            //  MessageBox.ShowBox("MsgPromErr11", BMC_Icon.Error);
                                            lblErrorMsg.Content = "Library Reference Error";
                                            return;
                                        }
                                    case PrintTicketErrorCodes.eTempErr:
                                        {
                                            _FailureTickets++;
                                            //   MessageBox.ShowBox("MsgPromErr12", BMC_Icon.Error);
                                            lblErrorMsg.Content = "Temp Error";
                                            return;
                                        }
                                    case PrintTicketErrorCodes.eMissingSupplyIndex:
                                        {
                                            _FailureTickets++;
                                            //   MessageBox.ShowBox("MsgPromErr13", BMC_Icon.Error);
                                            lblErrorMsg.Content = "Supply Index is Missing";
                                            return;
                                        }
                                    case PrintTicketErrorCodes.eFlashProgErr:
                                        {
                                            _FailureTickets++;
                                            //   MessageBox.ShowBox("MsgPromErr14", BMC_Icon.Error);
                                            lblErrorMsg.Content = "Flash Program Error";
                                            return;
                                        }
                                    case PrintTicketErrorCodes.ePaperInChute:
                                        {
                                            _FailureTickets++;
                                            //   MessageBox.ShowBox("MsgPromErr15", BMC_Icon.Error);
                                            lblErrorMsg.Content = "Paper in Chute";
                                            return;
                                        }
                                    case PrintTicketErrorCodes.ePrintLibCorr:
                                        {
                                            _FailureTickets++;
                                            //   MessageBox.ShowBox("MsgPromErr16", BMC_Icon.Error);
                                            lblErrorMsg.Content = "Print library is corrupted.";
                                            return;
                                        }
                                    case PrintTicketErrorCodes.eCmdErr:
                                        {
                                            _FailureTickets++;
                                            // MessageBox.ShowBox("MsgPromErr17", BMC_Icon.Error);
                                            lblErrorMsg.Content = "Command Error";
                                            return;
                                        }
                                    case PrintTicketErrorCodes.ePaperLow:
                                        {
                                            _FailureTickets++;
                                            //  MessageBox.ShowBox("MsgPromErr18", BMC_Icon.Error);
                                            lblErrorMsg.Content = "Paper low.";
                                            return;
                                        }
                                    case PrintTicketErrorCodes.ePaperJam:
                                        {
                                            _FailureTickets++;
                                            //   MessageBox.ShowBox("MsgPromErr19", BMC_Icon.Error);
                                            lblErrorMsg.Content = "Paper jammed.";
                                            return;
                                        }
                                    case PrintTicketErrorCodes.eCurrentErr:
                                        {
                                            _FailureTickets++;
                                            // MessageBox.ShowBox("MsgPromErr20", BMC_Icon.Error);
                                            lblErrorMsg.Content = "Current Error";
                                            return;
                                        }
                                    case PrintTicketErrorCodes.eJournalPrint:
                                        {
                                            _FailureTickets++;
                                            //  MessageBox.ShowBox("MsgPromErr21", BMC_Icon.Error);
                                            lblErrorMsg.Content = "Journal Print Error";
                                            return;
                                        }
                                    default:
                                        {
                                            _FailureTickets++;
                                            //   MessageBox.ShowBox("MessageID102", BMC_Icon.Warning);
                                            lblErrorMsg.Content = "Unable to Print Voucher";
                                            return;
                                        }
                                }



                            }), System.Windows.Threading.DispatcherPriority.Normal);


                            this.Dispatcher.Invoke(new Action(() =>
                            {
                                this.lblPrintedTicket.Content = _NoOfPrintedTickets.ToString();
                                this.lblTotalTicket.Content = _NoOfTickets.ToString();
                                UpdateProgressBarDelegate updatePbDelegate = new UpdateProgressBarDelegate(pbPrint.SetValue);
                            }), System.Windows.Threading.DispatcherPriority.Normal);


                            this.Dispatcher.Invoke(new Action(() =>
                            {
                                btnCancel.IsEnabled = true;

                            }), System.Windows.Threading.DispatcherPriority.Normal);
                            System.Threading.Thread.Sleep(1000);
                        }
                        PromoTickAmt = Convert.ToDouble(_PromotionTicketAmount);
                        PromCount = Convert.ToInt32(_NoOfTickets);

                        double TotalAmoount = PromCount * PromoTickAmt;
                        if (_NoOfPrintedTickets == _NoOfTickets)
                        {
                            int UpdateVoucherPrintSuccess = objPromotional.MarkPromotionalTicketsAsValid(this.PromotionID, 1);
                            this.Dispatcher.Invoke(new Action(() =>
                            {
                                this.lblErrorMsg.Content = string.Empty;
                                pbPrint.Value = _NoOfPrintedTickets;
                                MessageBox.ShowBox("MessageID435", BMC_Icon.Information);

                            }), System.Windows.Threading.DispatcherPriority.Normal);

                            AuditViewerBusiness.InsertAuditData(new Audit.Transport.Audit_History
                            {
                                AuditModuleName = ModuleName.Promotion,
                                Audit_Screen_Name = "Promo Print",
                                Audit_Desc = "Promo Name: " + PromoName + "; TicketAmount: " + _PromotionTicketAmount.ToString() + "; Number of Tickets: " + PromCount.ToString() + "; Total Promotion Amount: " + TotalAmoount.ToString() + "; Expiry Date: " + ExpiryDate,
                                AuditOperationType = OperationType.ADD,
                                Audit_New_Vl = PromoName
                            });


                            this.Dispatcher.Invoke(new Action(() =>
                                                   {
                                                       IsPrintedCompleted = true;
                                                   }), System.Windows.Threading.DispatcherPriority.Normal);
                        }

                    }

                }
                catch (Exception ex)
                {
                    ExceptionManager.Publish(ex);
                    LogManager.WriteLog("Promotional Print Tickets : " + ex.Message, LogManager.enumLogLevel.Error);

                }
                finally
                {

                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Publish(ex);
            }
        }
Beispiel #42
0
 private void start_measuring(object sender, RoutedEventArgs e)
 {
     if (plotter_cntrl.FLAG_MEASURING_MODE == 1)
     {
         updProgress = new UpdateProgressBarDelegate(progress_bar.SetValue);
     }
     pattern.create_template();
     plotter_cntrl.StartGettingData();
 }
Beispiel #43
0
        private void buttonImportujFajl_Click(object sender, RoutedEventArgs e)
        {
            if (textBoxFajl.Text.Equals("") || !File.Exists(textBoxFajl.Text))
            {
                MessageBox.Show("Odaberi fajl.", "Upozorenje", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            //listBoxRezultat.Items.Clear();

            if (MessageBox.Show(String.Format("Potvrdi import {0} iz fajla {1}", (bool)radioButtonKorisnikPrograma.IsChecked ? "cenovnika Korisnika programa" : "cenovnika Poslovnih partnera", textBoxFajl.Text), "Import", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
            {
                int _ukupanBrojRedova = 0;
                int _brojUnetih = 0;
                int _brojGresaka = 0;
                int _brojNeNadjenih = 0;

                char _karakter;

                int _kolona = 1;

                string _poslovniPartner = "";//_kolona = 1
                string _proizvodjac = "";//_kolona = 2
                string _brojProizvodjaca = "";//_kolona = 3
                string _cenaBezPoreza = "";//_kolona = 4
                string _kolicinaNaStanju = "";//_kolona = 5

                this.Cursor = Cursors.Wait;

                DateTime _pocetak = DateTime.Now;
                TimeSpan _vremeTrajanja;

                string _cenovnikFilePath = textBoxFajl.Text;
                string _cenovnikGreskaFilePath = _cenovnikFilePath.Insert(_cenovnikFilePath.Length - 4, "_Greska");
                string _cenovnikNijeNadjenoFilePath = _cenovnikFilePath.Insert(_cenovnikFilePath.Length - 4, "_NijeNadjeno");

                StreamReader _brojacRedovaStreamReader = new StreamReader(_cenovnikFilePath);
                StreamReader _cenovnikStreamReader = new StreamReader(_cenovnikFilePath);
                StreamWriter _greskaStreamWriter = new StreamWriter(_cenovnikGreskaFilePath);
                StreamWriter _nijeNadjenoStreamWriter = new StreamWriter(_cenovnikNijeNadjenoFilePath);

                bool _resetujBrojac = true;

                try
                {

                    int _ubr = 0;
                    while (_brojacRedovaStreamReader.ReadLine() != null)
                    {
                        _ubr++;
                    }
                    _brojacRedovaStreamReader.Close();

                    progressBarStatus.Minimum = 0;
                    progressBarStatus.Maximum = _ubr;
                    progressBarStatus.Value = 0;

                    progressBarStatus.Visibility = System.Windows.Visibility.Visible;
                    textBlockStatus.Visibility = System.Windows.Visibility.Visible;
                    textBlockStatusUkupnoRedova.Visibility = System.Windows.Visibility.Visible;


                    textBlockStatusUkupnoRedova.Text = String.Format("Od ukupno: {0}", _ubr.ToString());

                    //Create a new instance of our ProgressBar Delegate that points to the ProgressBar's SetValue method.
                    UpdateProgressBarDelegate updatePbDelegate =
                        new UpdateProgressBarDelegate(progressBarStatus.SetValue);




                    while (_cenovnikStreamReader.Peek() >= 0)
                    {
                        _karakter = (char)_cenovnikStreamReader.Read();

                        if (_karakter.Equals('\t'))
                        {
                            _kolona++;
                        }
                        else
                        {
                            if (_karakter.Equals('\r') || _karakter.Equals('\n'))
                            {
                                //zato sto posle \r dolazi \n pa vec prazne stringove prazni ponovo 
                                //proverava se kolona preko koje se vrsi update
                                if (_poslovniPartner != "")
                                {
                                    string _c = _poslovniPartner + "\t" + _proizvodjac + "\t" + _brojProizvodjaca + "\t" + _cenaBezPoreza + "\t" + _kolicinaNaStanju;

                                    _ukupanBrojRedova++;

                                    textBlockStatus.Text = _ukupanBrojRedova.ToString();

                                    Dispatcher.Invoke(updatePbDelegate,
                                                        System.Windows.Threading.DispatcherPriority.Background,
                                                            new object[] { ProgressBar.ValueProperty, Convert.ToDouble(_ukupanBrojRedova) });
                                    try
                                    {
                                        int _i = (bool)radioButtonPoslovniPartner.IsChecked
                                            ? dBProksi.UnesiCenuDobavljacaTD(_poslovniPartner, _proizvodjac, _brojProizvodjaca, Convert.ToDecimal(_cenaBezPoreza, decimalFormatProvider), Convert.ToDecimal(_kolicinaNaStanju, decimalFormatProvider), _resetujBrojac)
                                            : dBProksi.UnesiCenuKorisnikaProgramaTD(_poslovniPartner, _proizvodjac, _brojProizvodjaca, Convert.ToDecimal(_cenaBezPoreza, decimalFormatProvider), Convert.ToDecimal(_kolicinaNaStanju, decimalFormatProvider), _resetujBrojac);

                                        //da samo jednom resetuje brojac, na pocetku
                                        if (_resetujBrojac)
                                        {
                                            _resetujBrojac = false;
                                        }

                                        if (_i == -1)
                                        {
                                            _nijeNadjenoStreamWriter.WriteLine(_c.ToCharArray());
                                            _brojNeNadjenih++;
                                        }
                                        else
                                        {
                                            _brojUnetih++;
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        //Zato sto ako se uvek desi greska nikad nece podesiti na false gore
                                        _resetujBrojac = false;

                                        _brojGresaka++;

                                        _c = _c + "\t" + ex.Message;

                                        _greskaStreamWriter.WriteLine(_c.ToCharArray());
                                    }
                                }
                                _poslovniPartner = "";//_kolona = 1
                                _proizvodjac = "";//_kolona = 2
                                _brojProizvodjaca = "";//_kolona = 3
                                _cenaBezPoreza = "";//_kolona = 4
                                _kolicinaNaStanju = "";//_kolona = 5

                                _kolona = 1;

                            }
                            else
                            {
                                switch (_kolona)
                                {
                                    case 1:
                                        _poslovniPartner = _poslovniPartner + _karakter.ToString();
                                        break;
                                    case 2:
                                        _proizvodjac = _proizvodjac + _karakter.ToString();
                                        break;
                                    case 3:
                                        _brojProizvodjaca = _brojProizvodjaca + _karakter.ToString();
                                        break;
                                    case 4:
                                        _cenaBezPoreza = _cenaBezPoreza + _karakter.ToString();
                                        break;
                                    case 5:
                                        _kolicinaNaStanju = _kolicinaNaStanju + _karakter.ToString();
                                        break;
                                }
                            }
                        }

                    }
                    _vremeTrajanja = (DateTime.Now - _pocetak);


                    listBoxRezultat.Items.Add("Rezultat za import fajla: " + _cenovnikFilePath);
                    listBoxRezultat.Items.Add("Ukupan broj redova = " + _ukupanBrojRedova);
                    listBoxRezultat.Items.Add("Broj unetih = " + _brojUnetih);
                    listBoxRezultat.Items.Add("Broj ne nađenih = " + _brojNeNadjenih + (_brojNeNadjenih != 0 ? ". Redovi koji sadrže nepoznate artikle nalaze se u fajlu: " + _cenovnikNijeNadjenoFilePath : ""));
                    listBoxRezultat.Items.Add("Broj grešaka = " + _brojGresaka + (_brojGresaka != 0 ? ". Artikli koji nisu importovani zbog greške nalaze se u fajlu: " + _cenovnikGreskaFilePath : ""));
                    listBoxRezultat.Items.Add("Vreme importa cenovnika = " + _vremeTrajanja);
                    listBoxRezultat.Items.Add("-------------------------------------------------------");

                    _greskaStreamWriter.Close();
                    _nijeNadjenoStreamWriter.Close();

                    if (_brojNeNadjenih.Equals(0))
                    {
                        File.Delete(_cenovnikNijeNadjenoFilePath);
                    }
                    if (_brojGresaka.Equals(0))
                    {
                        File.Delete(_cenovnikGreskaFilePath);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Greška", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                finally
                {
                    _brojacRedovaStreamReader.Close();
                    _cenovnikStreamReader.Close();
                    _greskaStreamWriter.Close();
                    _nijeNadjenoStreamWriter.Close();

                    textBlockStatus.Text = "";
                    textBlockStatusUkupnoRedova.Text = "";
                    progressBarStatus.Visibility = System.Windows.Visibility.Collapsed;
                    textBlockStatus.Visibility = System.Windows.Visibility.Collapsed;
                    textBlockStatusUkupnoRedova.Visibility = System.Windows.Visibility.Collapsed;


                    this.Cursor = Cursors.Arrow;
                }
            }
        }
 private void UserControl_Loaded(object sender, RoutedEventArgs e)
 {
     updatePbDelegate =
         new UpdateProgressBarDelegate(TesisProgress.SetValue);
 }
        private void FillVocabulary(string sourceText, Vocabulary vocabulary, string languageCode = null)
        {
            UpdateProgressBarDelegate updatePbDelegate = new UpdateProgressBarDelegate(pbProgress.SetValue);
            Dispatcher.Invoke(updatePbDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { ProgressBar.ValueProperty, 0.0 });

            StringBuilder text = new StringBuilder(sourceText);
            text.Replace("-\r\n", "");

            string result = text.ToString();
            string tempResult = Regex.Replace(result, "-", "");
            tempResult = tempResult.Replace("?", "?.");
            tempResult = tempResult.Replace("!", "!.");
            tempResult = Regex.Replace(tempResult, @"\s+\n+", " \n");
            tempResult = Regex.Replace(tempResult, @"[ ]+", " ");
            HashSet<string> sentences = new HashSet<string>(tempResult.Split('.'));

            result = Regex.Replace(result, @"[’']\w+", " ");
            result = Regex.Replace(result, @"[^\w\-]", " ");
            result = result.Replace("\r\n", " ");
            result = Regex.Replace(result, @"\s+", " ");
            result = result.ToLower();

            List<string> wordsList = new List<string>(result.Split(' '));
            Debug.Print("Total words count: " + wordsList.Count.ToString());

            HashSet<string> distinctWords = new HashSet<string>(wordsList);
            Debug.Print("Distinct words count: " + distinctWords.Count.ToString());

            HashSet<string> tempDistinctWordsList = new HashSet<string>(distinctWords);

            Debug.Print("Start creating phrases");
            HashSet<string> distinct2WordsComb = new HashSet<string>();
            HashSet<string> distinct3WordsComb = new HashSet<string>();
            HashSet<string> distinct4WordsComb = new HashSet<string>();
            HashSet<string> distinct5WordsComb = new HashSet<string>();
            string firstWord = " ";
            string secondWord = " ";
            string thirdWord = " ";
            string fourthWord = " ";

            foreach (string word in wordsList)
            {
                StringBuilder combination1 = new StringBuilder(fourthWord);
                combination1.Append(" ").Append(word);
                distinct2WordsComb.Add(combination1.ToString());

                StringBuilder combination2 = new StringBuilder(thirdWord);
                combination2.Append(" ").Append(combination1);
                distinct3WordsComb.Add(combination2.ToString());

                StringBuilder combination3 = new StringBuilder(secondWord);
                combination3.Append(" ").Append(combination2);
                distinct4WordsComb.Add(combination3.ToString());

                StringBuilder combination4 = new StringBuilder(firstWord);
                combination4.Append(" ").Append(combination3);
                distinct5WordsComb.Add(combination4.ToString());

                firstWord = secondWord;
                secondWord = thirdWord;
                thirdWord = fourthWord;
                fourthWord = word;
            }

            Debug.Print("2 words phrases count: {0}", distinct2WordsComb.Count);
            Debug.Print("3 words phrases count: {0}", distinct3WordsComb.Count);
            Debug.Print("4 words phrases count: {0}", distinct4WordsComb.Count);

            List<Term> termsFromDic = DB.Dictionary.GetListOfTerms(vocabulary.BaseDictionaryId);

            distinctWords.UnionWith(distinct2WordsComb);
            distinctWords.UnionWith(distinct3WordsComb);
            distinctWords.UnionWith(distinct4WordsComb);
            distinctWords.UnionWith(distinct5WordsComb);

            Debug.Print("Creating words dictionary");
            List<LearnedWord> learnedWords = new List<LearnedWord>();


            List<TermToAdd> termsToAdd = new List<TermToAdd>();

            var newResult = from term in termsFromDic join word in distinctWords on term.Content equals word select term;
            List<Term> wordsToAdd = newResult.ToList();

            foreach (Term term in wordsToAdd)
            {
                termsToAdd.Add(new TermToAdd(term.Id, term.Content));
            }

            Dispatcher.Invoke((Action)(() => pbProgress.Maximum = wordsToAdd.Count() + sentences.Count()));
            int counter = 0; 
            Regex regex = new Regex(@"\w+", RegexOptions.IgnoreCase);
            int sentCount = 0;

            Parallel.ForEach(sentences, sentence =>
            {
                Debug.Print("strict search for example. Sentence {0}/{1}", sentCount++, sentences.Count());
                foreach (Match match in regex.Matches(sentence))
                {
                    TermToAdd t = (from term in termsToAdd where term.Term == match.ToString() && term.Examples.Count() < 3 select term).FirstOrDefault();
                    if (t != null)
                        t.Examples.Add(sentence.Trim());
                }
                Interlocked.Increment(ref counter);
                Dispatcher.Invoke(updatePbDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { ProgressBar.ValueProperty, (double)counter });
            });

            int debugCounter = 0;
            Parallel.ForEach(termsToAdd, term =>
            {
                StringBuilder realExamples = new StringBuilder();

                if (term.Examples.Count() != 0)
                {
                    foreach (string example in term.Examples)
                    {
                        realExamples.Append(FormatExample(example));
                    }
                }
                else
                {
                    Regex weakRegex = new Regex("\\W" + term.Term + "\\W", RegexOptions.IgnoreCase);
                    List<string> examplesList = (from sentence in sentences where weakRegex.IsMatch(sentence) select sentence).Take(3).ToList();

                    foreach (string example in examplesList)
                    {
                        realExamples.Append(FormatExample(example));
                    }

                    if (realExamples.Length == 0)
                    {
                        weakRegex = new Regex("\\W" + term.Term, RegexOptions.IgnoreCase);
                        examplesList = (from sentence in sentences where weakRegex.IsMatch(sentence) select sentence).Take(3).ToList();

                        foreach (string example in examplesList)
                        {
                            realExamples.Append(FormatExample(example));
                        }
                    }
                }

                lock (learnedWords)
                {
                    learnedWords.Add(new LearnedWord(vocabulary.Id, term.TermId, realExamples.ToString().Trim()));
                    Interlocked.Increment(ref counter);
                    Dispatcher.Invoke(updatePbDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { ProgressBar.ValueProperty, (double)counter });
                    if (learnedWords.Count > 100)
                    {
                        DB.LearnedWords.AddContent(learnedWords);
                        learnedWords.Clear();
                    }
                }

                Debug.Print("{0}/{1}", debugCounter++, wordsToAdd.Count());
            });

            if (learnedWords.Count > 0)
            {
                DB.LearnedWords.AddContent(learnedWords);
                learnedWords.Clear();
                Dispatcher.Invoke(updatePbDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { ProgressBar.ValueProperty, (double)counter });
            }

            Debug.Print("Vocabulary has been created");
        }
        private void renamebtn_Click(object sender, RoutedEventArgs e)
        {
            if (pth == "")
            {
                MessageBox.Show("‫ئاۋۋال «ھۆججەت ئېچىش» كۇنۇپكىسىنى بېسىپ Encoding Errors.txt ھۆججىتىنى ئېچىڭ، ئاندىن «ئىسمىنى ئۆزگەرتىش» كۇنۇپكىسىنى بېسىڭ");
                return;
            }
            //Configure the ProgressBar
            ProgressBar1.Minimum = 0;
            ProgressBar1.Maximum = filenam.Count;
            ProgressBar1.Value = 0;

            //Stores the value of the ProgressBar
            double value = 0;

            //Create a new instance of our ProgressBar Delegate that points
            // to the ProgressBar's SetValue method.
            UpdateProgressBarDelegate updatePbDelegate =
                new UpdateProgressBarDelegate(ProgressBar1.SetValue);
            if (ProgressBar1.Value != ProgressBar1.Maximum)
            {
                //Tight Loop: Loop until the ProgressBar.Value reaches the max
                foreach (string key in filenam.Keys)
                {
                    progresslabel.Content = System.IO.Path.Combine(pth, key);
                    string newName=System.IO.Path.Combine(pth, key);
                    string oldName=System.IO.Path.Combine(pth, filenam[key].ToString());
                    if (File.Exists(oldName))
                    {
                        //Check the destiantion folder is exist
                        string dirPath=new FileInfo(newName).Directory.FullName;
                        if (!Directory.Exists(dirPath))
                        {
                            Directory.CreateDirectory(dirPath);
                        }
                        File.Move(@oldName, @newName);
                    }
                    value += 1;
                    /*Update the Value of the ProgressBar:
                        1) Pass the "updatePbDelegate" delegate
                           that points to the ProgressBar1.SetValue method
                        2) Set the DispatcherPriority to "Background"
                        3) Pass an Object() Array containing the property
                           to update (ProgressBar.ValueProperty) and the new value */
                    Dispatcher.Invoke(updatePbDelegate,
                        System.Windows.Threading.DispatcherPriority.Background,
                        new object[] { ProgressBar.ValueProperty, value });
                }
            }
            progresslabel.Content = "ھەممىنى تۈگەتتىم!";
        }
        private void save()
        {
            #region enable statusbar
            this.IsEnabled = false;
            //Create a new instance of our ProgressBar Delegate that points
            //  to the ProgressBar's SetValue method.
            UpdateProgressBarDelegate updatePbDelegate = new UpdateProgressBarDelegate(ProgressBarStatus.SetValue);
            bool usePGB = false;
            //Stores the value of the ProgressBar
            double value = 0;
            #endregion
            try
            {
                #region enable statusbar

                usePGB = true;
                //Configure the ProgressBar
                StatusGrid.Visibility = System.Windows.Visibility.Visible;
                ProgressBarStatus.Minimum = 0;
                ProgressBarStatus.Maximum = RepositoryLibrary.Repositorys.Count + 1;// add 1 for cleaning operation
                ProgressBarStatus.Value = 0;



                #endregion

                foreach (CommandRepository repo in RepositoryLibrary.Repositorys)
                {

                    repo.Save();
                    #region Step statusbar
                    if (usePGB)
                    {
                        value += 1;
                        ProgressbarLabel.Text = "Saving repositorys, please wait...";
                        //Update the Value of the ProgressBar:

                        Dispatcher.Invoke(updatePbDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { ProgressBar.ValueProperty, value });

                    }

                    #endregion
                }

            }
            catch (Exception ex)
            {

                sendMessage(ex.Message, "Unhandled error");

            }
            finally
            {
                #region Cleanup
                ProgressbarLabel.Text = "Cleaning up icondsfolder...";
                MyImageWorker.CleanIconFolder();
                value += 1;
                Dispatcher.Invoke(updatePbDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { ProgressBar.ValueProperty, value });
                #endregion

                ProgressbarLabel.Text = string.Empty;
                StatusGrid.Visibility = System.Windows.Visibility.Collapsed;
                commandRepositoryViewSource = null;
                runCommandViewSource = null;
                callReload();
                currentCmd = null;
                GC.Collect();
            }

        }
        // create list to hold extra files
        private void DoDrop(object sender, DragEventArgs e)
        {
            if (draging)
            {
                e.Handled = true;
                return;
            }
            draging = true;
            List<string> errors = new List<string>();
            bool usePGB = false;

            //only one image can be added at a time
            bool oneImageadded = false;

            if (commandRepositoryViewSource.View.CurrentItem == null)
            {
                e.Handled = true;
                return;
            }

            #region enable statusbar

            togleEnable(false);
            //Create a new instance of our ProgressBar Delegate that points
            //  to the ProgressBar's SetValue method.
            UpdateProgressBarDelegate updatePbDelegate = new UpdateProgressBarDelegate(ProgressBarStatus.SetValue);

            //Stores the value of the ProgressBar
            double value = 0;
            #endregion

            try
            {


                // Handle FileDrop data.
                if (e.Data.GetDataPresent(DataFormats.FileDrop))
                {
                    // Check if we have been given only one file, if not kill the user with error message!
                    string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
                    List<string> newList = cleanUpListAndFindDirectories(files);

                    if (files.Count() > 1) oneImageadded = true;


                    #region enable statusbar


                    if (newList.Count() > 2)
                    {
                        usePGB = true;
                        //Configure the ProgressBar
                        StatusGrid.Visibility = System.Windows.Visibility.Visible;
                        ProgressBarStatus.Minimum = 0;
                        ProgressBarStatus.Maximum = newList.Count();
                        ProgressbarLabel.Text = "Gettering information of files...";

                        ProgressBarStatus.Value = 0;

                    }

                    #endregion


                    foreach (string s in newList)
                    {
                        ProgressbarLabel.Text = "Processing file: " + s;

                        System.Windows.Forms.Application.DoEvents();
                        try
                        {
                            if (System.IO.Path.GetExtension(s).Equals(".lnk", StringComparison.CurrentCultureIgnoreCase))
                            {
                                try
                                {
                                    RunCommand newCmd = RunCommand.CreateCommandFromLnk(s);

                                    if (newCmd != null && newCmd.Error.Length == 0)
                                    {
                                        (commandRepositoryViewSource.View.CurrentItem as CommandRepository).Commands.Add(newCmd);
                                        runCommandViewSource.View.MoveCurrentToLast();

                                        runCommandDataGrid.ScrollIntoView(runCommandDataGrid.SelectedItem);
                                        DataGridRow dgrow = (DataGridRow)runCommandDataGrid.ItemContainerGenerator.ContainerFromItem(runCommandDataGrid.SelectedItem);
                                        dgrow.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));

                                        oneImageadded = true;
                                    }
                                }
                                catch (Exception ex)
                                {

                                    errors.Add("error in file: " + s + " " + ex.Message + Environment.NewLine);
                                }
        #endregion

                            }
                            else
                            {
                                #region check if its image
                                //file is not an ink object, check if its an image
                                bool isSuportedExtension = false;
                                string fileExstension = System.IO.Path.GetExtension(s);
                                foreach (string item in RunCommand.imageExt)
                                {
                                    if (fileExstension.ToLower().Equals(item, StringComparison.CurrentCultureIgnoreCase))
                                    {
                                        isSuportedExtension = true;
                                        break;
                                    }
                                }
                                #endregion

                                if (!isSuportedExtension)// it is not a supported image, check if we want to make a shortcut out of is --> extensions properties
                                {
                                    bool isValidExtension = false;
                                    foreach (string sr in Properties.Settings.Default.MakeShortCutExtensions)
                                    {
                                        if (System.IO.Path.GetExtension(s).Equals(sr, StringComparison.CurrentCultureIgnoreCase))
                                        {
                                            isValidExtension = true;
                                            break;
                                        }
                                    }

                                    if (isValidExtension)
                                    {
                                        #region Make it into a shortcut
                                        try
                                        {
                                            // Start fetching new runcommand.
                                            RunCommand newCmd = RunCommand.CreateCommandFromstring(s);

                                            if (newCmd != null && newCmd.Error.Length == 0)
                                            {
                                                (commandRepositoryViewSource.View.CurrentItem as CommandRepository).Commands.Add(newCmd);
                                                runCommandViewSource.View.MoveCurrentToLast();

                                                runCommandDataGrid.ScrollIntoView(runCommandDataGrid.SelectedItem);
                                                DataGridRow dgrow = (DataGridRow)runCommandDataGrid.ItemContainerGenerator.ContainerFromItem(runCommandDataGrid.SelectedItem);
                                                dgrow.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));

                                                oneImageadded = true;
                                            }
                                        }
                                        catch (Exception ex)
                                        {

                                            errors.Add(s + "  failed for shortcut creation: " + ex.Message + Environment.NewLine);
                                        }
                                        #endregion
                                    }

                                }
                                else
                                {
                                    #region Add maximum one image
                                    if (!oneImageadded)//if more items were provided, only add one image
                                    {

                                        HitTestResult result = VisualTreeHelper.HitTest(this, e.GetPosition(this));
                                        DependencyObject obj = result.VisualHit;


                                        while (VisualTreeHelper.GetParent(obj) != null && !(obj is DataGrid))
                                        {
                                            obj = VisualTreeHelper.GetParent(obj);
                                            if (obj is DataGridRow)
                                            {
                                                runCommandDataGrid.SelectedItem = (obj as DataGridRow).Item;
                                                break;
                                            }
                                        }

                                        if (runCommandViewSource.View.CurrentItem != null)
                                        {
                                            (runCommandViewSource.View.CurrentItem as RunCommand).IconLocation = s;

                                        }

                                        oneImageadded = true;
                                    }
                                }
                                    #endregion
                            }
                        }
                        catch (Exception ex)
                        {

                            errors.Add("Unhandled error" + ex.Message + Environment.NewLine);
                        }
                        finally
                        {
                            #region Step statusbar
                            if (usePGB)
                            {
                                value += 1;

                                Dispatcher.Invoke(updatePbDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { ProgressBar.ValueProperty, value });

                            }


                            #endregion
                        }
                    }
                }

                #region textdrop = only for images
                // Handle TextDrop data. Texstdrops are only for icons!
                if (e.Data.GetDataPresent(DataFormats.Text))
                {

                    if (runCommandViewSource.View.CurrentItem == null)
                    {

                        HitTestResult result = VisualTreeHelper.HitTest(this, e.GetPosition(this));
                        DependencyObject obj = result.VisualHit;


                        while (VisualTreeHelper.GetParent(obj) != null && !(obj is DataGrid))
                        {
                            obj = VisualTreeHelper.GetParent(obj);
                            if (obj is DataGridRow)
                            {
                                runCommandDataGrid.SelectedItem = (obj as DataGridRow).Item;
                                oneImageadded = true;
                            }
                        }
                    }

                    string file = (string)e.Data.GetData(DataFormats.Text);

                    (runCommandDataGrid.SelectedItem as RunCommand).IconLocation = file;


                }
                #endregion


            }
            catch (Exception ex)
            {
                errors.Add(ex.Message + Environment.NewLine + Environment.NewLine);
            }

            finally
            {

                #region reporting errors
                if (errors.Count >= 1 && errors.Count < 50)
                {
                    StringBuilder sb = new StringBuilder();
                    foreach (string x in errors)
                        sb.Append(x);


                    sendMessage("Drop failer for the item(s): " + Environment.NewLine + Environment.NewLine + sb.ToString(), "Drop error(s)");

                }
                else if (errors.Count > 50)
                {
                    sendMessage("a large number of files were logged, they will be displayed in a txt file...", "Drop error(s)");
                    StringBuilder sb = new StringBuilder();
                    foreach (string x in errors)
                        sb.Append(x);

                    try
                    {
                        string tempPath = System.IO.Path.GetTempPath() + DateTime.Now.ToFileTime() + ".txt";

                        File.WriteAllText(tempPath, sb.ToString());
                        RunCommand x = new RunCommand();
                        x.Type = CommandType.SimpleRunCommand;
                        x.Command = tempPath;
                        x.ExecuteCommandSync();
                    }
                    catch (Exception ex)
                    {

                        sendMessage("Fatal error!" + Environment.NewLine + ex.Message, "Writing to textfile failed.");
                    }


                }
                #endregion

                #region Step statusbar
                StatusGrid.Visibility = System.Windows.Visibility.Collapsed;
                ProgressbarLabel.Text = string.Empty;
                if (usePGB)
                {

                    value = 0;

                    /*Update the Value of the ProgressBar:
                      1)  Pass the "updatePbDelegate" delegate that points to the ProgressBar1.SetValue method
                      2)  Set the DispatcherPriority to "Background"
                      3)  Pass an Object() Array containing the property to update (ProgressBar.ValueProperty) and the new value */
                    Dispatcher.Invoke(updatePbDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { ProgressBar.ValueProperty, value });

                }
                togleEnable(true);

                #endregion
                draging = false;
                e.Handled = true;
            }

        }
Beispiel #49
0
        public LearningResult Calc(DateTime fromDate, DateTime toDate)
        {
            UpdateProgressBarDelegate updProgress = new UpdateProgressBarDelegate(progressBar.SetValue);

            double[] Ks = { 0.5, 1, 2 }; //массив коэффициентов для интерполирования
            LearningResult result = new LearningResult();
            result.GPResults = new List<GPLearningResult>();
            var datesRange = db.wells_measurements.Where(x => (x.measure_date >= fromDate) && (x.measure_date <= toDate)).Select(y => new { Date = y.measure_date }).Distinct().ToList();

            var dates = (from date in datesRange
                         join meas in db.final_gather_point_measurements on date.Date equals meas.measure_date
                         select new { Date = date.Date }).ToList();
            if (!dates.Any())
            {
                return result;
            }
            progressBar.Maximum = dates.Count;
            progressBar.Minimum = 0;
            progressBar.Value = 0;
            double value = 0;
            foreach (var date in dates)
            {
                value++;
                Dispatcher.CurrentDispatcher.Invoke(updProgress, DispatcherPriority.Background, new object[] { ProgressBar.ValueProperty, value });

                double[,] _PTk = new double[Ks.Length, 2];
                //foreach (var wellMeasurement in db.wells_measurements.Where(x => x.measure_date == date.Date).ToList()) //заполнение данных о скважинах за данный день
                //{

                //	var well = _graph.wells.First(x => x.Data.well_id == wellMeasurement.well_id);
                //	well.Data = wellMeasurement;
                //	well.a = new double[] { -4f / 5, -1f / 5, 1f };
                //	well.b = new double[] { -12f / 5, 11f / 5, 1f / 5 };
                //}

                List<GPResult> gpResults = new List<GPResult>();

                for (int i = 0; i < Ks.Length; i++) //расчет P и T для каждого из значений коэффициентов
                {
                    K_p = Ks[i];
                    K_t = Ks[i];
                    CalcGraph(date.Date);
                    //CalcNode(_graph.endNode);
                    _PTk[i, 0] = _graph.endNode.P;
                    _PTk[i, 1] = _graph.endNode.T;

                    if (K_p == 1)
                    {
                        foreach (var n in _graph.nodes)
                        {
                            gpResults.Add(new GPResult()
                            {
                                G = n.G,
                                Id = n.Id,
                                Name = n.Name,
                                NextNodeName = n.NextNode != null ? n.NextNode.Name : "",
                                Pf = n.P,
                                Tf = n.T
                            });
                        }
                    }

                    _graph.Clear();

                    //foreach (var wellMeasurement in db.wells_measurements.Where(x => x.measure_date == date.Date).ToList()) //заполнение данных о скважинах за данный день
                    //{
                    //	var well = _graph.wells.First(x => x.Data.well_id == wellMeasurement.well_id);
                    //	well.Data = wellMeasurement;
                    //	well.a = new double[] { -4f / 5, -1f / 5, 1f };
                    //	well.b = new double[] { -12f / 5, 11f / 5, 1f / 5 };
                    //}
                }

                var realResults = db.final_gather_point_measurements.FirstOrDefault(x => x.measure_date == date.Date);
                double _Kt = GetInterpolatedValue(realResults.Texper, new [] {_PTk[0, 1], _PTk[1, 1], _PTk[2, 1]}, Ks);
                double _Kp = GetInterpolatedValue(realResults.Pexper, new [] {_PTk[0, 0], _PTk[1, 0], _PTk[2, 0]}, Ks);
                K_p = _Kp;
                K_t = _Kt;
                CalcNode(_graph.endNode);

                foreach (var n in _graph.nodes)
                {
                    var r = gpResults.First(x => x.Id == n.Id);
                    r.Pcoef = n.P;
                    r.Tcoef = n.T;
                }

                result.GPResults.Add(new GPLearningResult()
                {
                    Date = date.Date,
                    Pexpr = realResults.Pexper,
                    Texpr = realResults.Texper,
                    Pf = _PTk[1, 0],
                    Tf = _PTk[1, 1],
                    Coef_T = _Kt,
                    Coef_P = _Kp,
                    Pcoef = _graph.endNode.P,
                    Tcoef = _graph.endNode.T,
                    G = _graph.endNode.G,
                    WellMeasurements = db.wells_measurements.Where(x => EntityFunctions.TruncateTime(x.measure_date) == date.Date).ToList(),
                    GPMeasurements = gpResults
                });

                _graph.Clear();
                //break;
            }
            result.Coef_P = result.GPResults.Average(x => x.Coef_P);
            result.Coef_T = result.GPResults.Average(x => x.Coef_T);
            //progressBar.IsIndeterminate = false;
            return result;
        }
        private bool ParseDictionaryToSql(Dictionary dictionary, string sourceTextPath )
        {
            if (string.IsNullOrWhiteSpace(dictionary.Title) || dictionary.TermLanguageId<1 || dictionary.DefinitionLanguageId<1)
                return false;

            int dictionaryId = DB.Dictionary.CreateDictionary(dictionary);
            if (dictionaryId == 0)
                return false;

            //Create a new instance of ProgressBar Delegate that points
            //  to the ProgressBar's SetValue method.
            UpdateProgressBarDelegate updatePbDelegate = new UpdateProgressBarDelegate(pbProgress.SetValue);
            Dispatcher.Invoke(updatePbDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { ProgressBar.ValueProperty, 0.0 });

            String source = File.ReadAllText(sourceTextPath, Encoding.UTF8);
            string[] chunks = source.Split(new string[] { "<k>" }, StringSplitOptions.None);
            List<Article> articles = new List<Article>();

            Dispatcher.Invoke((Action)(() => pbProgress.Maximum = chunks.Count()));
            int counter = 0;

            Parallel.ForEach(chunks, chunk =>
            {
                Interlocked.Increment(ref counter);

                StringBuilder text = new StringBuilder(chunk);
                text.Replace("<opt>", "[");
                text.Replace("</opt>", "]");
                text.Replace("<nu />", "");
                text = new StringBuilder(Regex.Replace(text.ToString(), @"<rref>.*</rref>", " "));
                text = new StringBuilder(Regex.Replace(text.ToString(), @"<iref>.*</iref>", " "));
                text = new StringBuilder(Regex.Replace(text.ToString(), @"•\s+<kref>", "- <kref>"));
                text = new StringBuilder(Regex.Replace(text.ToString(), @"\- <kref>.*</kref>", ""));

                string output = text.ToString();

                output = Regex.Replace(output, @"\)\s*\n", ") ");
                output = Regex.Replace(output, @"•", " ");

                output = output.Replace("<k>", "\n<k>");
                output = output.Replace("<tr>", "\n<tr>");
                output = output.Replace("<ex>", "\n<ex>");
                output = Regex.Replace(output, @"\s+\n+", " \n");

                StringWriter myWriter = new StringWriter();
                // Decode the encoded string.
                HttpUtility.HtmlDecode(output, myWriter);
                output = myWriter.ToString();


                StringBuilder article = new StringBuilder(output);
                Regex tagsRegex = new Regex(@"<((\w+)|(/\w+)|( /\w+)|\w+ /)>");
                string addedWord = Regex.Match(output, @".*</k>").ToString();
                if (!string.IsNullOrWhiteSpace(addedWord))
                    article.Replace(addedWord, "");

                if (string.IsNullOrWhiteSpace(addedWord) || addedWord.Contains("#ICON_FILE"))
                    return;

                addedWord = tagsRegex.Replace(addedWord, "");


                HashSet<string> uniqueTranscriptions = new HashSet<string>();
                foreach (Match m in Regex.Matches(output, @"<tr>.*</tr>"))
                {
                    uniqueTranscriptions.Add(tagsRegex.Replace(m.ToString(), ""));
                    article.Replace(m.ToString(), "");
                }
                StringBuilder transcription = new StringBuilder();
                foreach (string tr in uniqueTranscriptions)
                {
                    transcription.Append(tr).Append("  ");
                }

                string example = null;
                foreach (Match m in Regex.Matches(article.ToString(), @"<ex>.*</ex>"))
                {
                    example = tagsRegex.Replace(m.ToString(), "");
                    example = Regex.Replace(example, " ; ", " ");
                    article.Replace(m.ToString(), "");
                }
                if (example != null)
                    example = example.Trim();

                string transl = tagsRegex.Replace(article.ToString(), "");
                transl = Regex.Replace(transl, @"\s+\n+", " \n");

                lock(articles)
                {
                    articles.Add(new Article(0, dictionaryId, addedWord.Trim(), transcription.ToString().Trim(), transl.Trim(), example));
                    Debug.Print("{0}/{1}", counter, chunks.Count());

                    if (articles.Count > 50) // "|| counter==end" can lead to data loss
                    {
                        DB.Dictionaries.AddDictionariesContent(articles);
                        articles.Clear();

                        Dispatcher.Invoke(updatePbDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { ProgressBar.ValueProperty, (double)counter });
                    }
                }
            });

            //if previous condition didn't work
            //do not remove!
            if (articles.Count > 0)
            {
                DB.Dictionaries.AddDictionariesContent(articles);
                articles.Clear();
                Dispatcher.Invoke(updatePbDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { ProgressBar.ValueProperty, (double)counter });
                Debug.Print("Safety net");
            }

            return true;
        }
Beispiel #51
0
        private void UpdateProgressBar(int progress)
        {
            if (this.ssMain.InvokeRequired)
            {
                m_updateProgressBarDelegate = new UpdateProgressBarDelegate(UpdateProgressBar);

                this.ssMain.Invoke(m_updateProgressBarDelegate, progress);
            }
            else
            {
                if (this.ProgressBar.Value + progress <= this.ProgressBar.Maximum)
                {
                    this.ProgressBar.Value += progress;
                }
            }
        }
Beispiel #52
0
        private void btnImport_Click(object sender, RoutedEventArgs e)
        {
            dgAthlete.ItemsSource = null;
            tbAllCount.Text = "";
            tbSuccessCount.Text = "";
            tbFaildCount.Text = "";

            if (tbFilePath.Text == ""||excelContentList.Count==0) {
                MessageBox.Show("请选择受测者名单!", "系统信息");
                return;
            }
            if (cbTestItems.SelectedIndex < 0) {
                MessageBox.Show("请选择测试项目!", "系统信息");
                return;
            }

            double value = 0;
            UpdateProgressBarDelegate updatePbDelegate = new UpdateProgressBarDelegate(importProgress.SetValue);

            List<Model.TB_AthleteInfo> existsAthNameList = new List<Model.TB_AthleteInfo>();
            int errorCount = 0;
            int successCount = 0;
            bool cancleImport = false;
            for (int i = 0; i < excelContentList.Count; i++) {
                 List<string> columnList = excelContentList[i];

                    tbProgress.Text = (i + 1) + "/" + excelContentList.Count;

                    try
                    {
                        Model.TB_AthleteInfo newAthInfo = new Model.TB_AthleteInfo();
                        newAthInfo.Ath_TestDate = columnList[0] == "" ? DateTime.Now : DateTime.Parse(columnList[0]);
                        newAthInfo.Ath_Name = columnList[1];
                        newAthInfo.Ath_PinYin = DataUtil.PersonNamePinYinUtil.GetNamePinyin(newAthInfo.Ath_Name);
                        newAthInfo.Ath_Sex = DataUtil.AthleteSexUtil.GetSex(columnList[2]);
                        newAthInfo.Ath_Birthday = columnList[3] == "" ? DateTime.Now : DateTime.Parse(columnList[3]);
                        newAthInfo.Ath_Height = columnList[4];
                        newAthInfo.Ath_Weight = columnList[5];
                        newAthInfo.Ath_Project = columnList[6];
                        newAthInfo.Ath_MainProject = columnList[7];
                        newAthInfo.Ath_TrainYears = columnList[8];
                        newAthInfo.Ath_Level = columnList[9];
                        newAthInfo.Ath_Team = columnList[10];
                        newAthInfo.Ath_TestAddress = columnList[11];
                        newAthInfo.Ath_TestMachine = columnList[12];
                        newAthInfo.Ath_TestState = columnList[13];
                        newAthInfo.Ath_Remark = columnList[14];
                        newAthInfo.Ath_TestID = testList[cbTestItems.SelectedIndex].ID;
                        string existID = "";
                        int result = athInfoBLL.Add(newAthInfo, out existID);
                        if (result == BLL.TB_AthleteInfo.RepeatAdd)
                        {
                            existsAthNameList.Add(newAthInfo);
                        }
                        else {
                            successCount++;
                        }
                    }
                    catch
                    {
                        errorCount++;
                        if (MessageBox.Show("第" + (i + 2) + "行 " + columnList[0] + "的信息导入错误,请检查!\r\n是否继续导入?", "系统信息", MessageBoxButton.YesNo) == MessageBoxResult.No)
                        {
                            value = 0;
                            Dispatcher.Invoke(updatePbDelegate,
                     System.Windows.Threading.DispatcherPriority.Background,
                     new object[] { ProgressBar.ValueProperty, value });
                            cancleImport = true;
                            break;
                        }
                    }
                    value += 1;
                    Dispatcher.Invoke(updatePbDelegate,
                        System.Windows.Threading.DispatcherPriority.Background,
                        new object[] { ProgressBar.ValueProperty, value });

            }

            for (int i = 0; i < existsAthNameList.Count; i++) {
                existsAthNameList[i].Index = i + 1;
            }

            dgAthlete.ItemsSource = existsAthNameList;
            tbAllCount.Text = "总共" + excelContentList.Count + "条信息";
            tbSuccessCount.Text = "成功导入" + successCount + "条信息";
            tbFaildCount.Text = "未导入" + (existsAthNameList.Count + errorCount) + "条信息";
            if (!cancleImport)
            {
                MessageBox.Show("导入完成!", "系统信息");
            }

            tbFilePath.Text = "";
        }
Beispiel #53
0
        private void Progress(int min, int selectedValue, int current)
        {
            progress.Minimum = min;
            progress.Maximum = selectedValue;
            progress.Value = current;

            double value = current;

            UpdateProgressBarDelegate updatePbDelegate = new UpdateProgressBarDelegate(progress.SetValue);
            Dispatcher.Invoke(updatePbDelegate,
                    System.Windows.Threading.DispatcherPriority.Background,
                    new object[] { ProgressBar.ValueProperty, value });
        }
Beispiel #54
0
        /// <summary>
        /// Technician模式接收PDF報告
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnReceivePdf_Click(object sender, RoutedEventArgs e)
        {
            ProgressBarGridDelegate progressBarGridDelegate = new ProgressBarGridDelegate(progressBarGrid.SetValue);
            UpdateProgressBarDelegate updatePbDelegate = new UpdateProgressBarDelegate(uploadProgressBar.SetValue);
            //使用系统代理方式显示进度条面板
            Dispatcher.Invoke(updatePbDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { System.Windows.Controls.ProgressBar.ValueProperty, Convert.ToDouble(0) });
            Dispatcher.Invoke(progressBarGridDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { System.Windows.Controls.Grid.VisibilityProperty, Visibility.Visible });
            
            List<string> errMsg = new List<string>();
            try
            {
                //查询FTP上要下载的文件列表
                var fileArr = FtpHelper.Instance.GetFileList(App.reportSettingModel.FtpUser, App.reportSettingModel.FtpPwd, App.reportSettingModel.FtpPath + "Receive/");
                //判断是否存在已下载的目录IsDownloaded
                if (!FtpHelper.Instance.FolderExist(App.reportSettingModel.FtpUser, App.reportSettingModel.FtpPwd, App.reportSettingModel.FtpPath, "IsDownloaded"))
                {
                    FtpHelper.Instance.MakeDir(App.reportSettingModel.FtpUser, App.reportSettingModel.FtpPwd, App.reportSettingModel.FtpPath, "IsDownloaded");
                }

                int n = 0;
                double groupValue = 100 / (fileArr.Count + 1);                

                foreach (var file in fileArr)
                {
                    if (file.EndsWith(".pdf", StringComparison.OrdinalIgnoreCase))
                    {
                        Dispatcher.Invoke(updatePbDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { System.Windows.Controls.ProgressBar.ValueProperty, Convert.ToDouble(groupValue * n) });
                        n++;
                        //创建下载目录路径
                        string folderpath = "";
                        try
                        {
                            string monthfolder = file.Substring(2, 2) + "_20" + file.Substring(0, 2);
                            //folderpath = App.reportSettingModel.DataBaseFolder + System.IO.Path.DirectorySeparatorChar + monthfolder + System.IO.Path.DirectorySeparatorChar + file.Substring(4, 2);
                            folderpath = App.reportSettingModel.DataBaseFolder + System.IO.Path.DirectorySeparatorChar + monthfolder;
                            if (!Directory.Exists(folderpath))
                            {
                                Directory.CreateDirectory(folderpath);
                            }
                        }
                        catch (Exception e1)
                        {
                            //MessageBox.Show(this, e1.Message);
                            errMsg.Add(file + " :: " + App.Current.FindResource("Message_39").ToString() + e1.Message);
                            continue;
                        }
                        //从FTP下载PDF文件
                        try
                        {
                            FtpHelper.Instance.Download(App.reportSettingModel.FtpUser, App.reportSettingModel.FtpPwd, App.reportSettingModel.FtpPath + "Receive/", folderpath, file);
                            Dispatcher.Invoke(updatePbDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { System.Windows.Controls.ProgressBar.ValueProperty, Convert.ToDouble(groupValue * n + groupValue/2) });
                            FtpHelper.Instance.MovieFile(App.reportSettingModel.FtpUser, App.reportSettingModel.FtpPwd, App.reportSettingModel.FtpPath + "Receive/", file, "/home/IsDownloaded/" + file);
                        }
                        catch (Exception e2)
                        {
                            //MessageBox.Show(this, e2.Message);
                            errMsg.Add(file + " :: " + App.Current.FindResource("Message_40").ToString() + e2.Message);
                            continue;
                        }                        
                        
                    }
                }
                Dispatcher.Invoke(updatePbDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { System.Windows.Controls.ProgressBar.ValueProperty, Convert.ToDouble(100) });
                Dispatcher.Invoke(progressBarGridDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { System.Windows.Controls.Grid.VisibilityProperty, Visibility.Collapsed });
                if (errMsg.Count == 0)
                {
                    if (n == 0)
                    {
                        MessageBox.Show(this, App.Current.FindResource("Message_43").ToString());
                    }
                    else
                    {
                        MessageBox.Show(this, App.Current.FindResource("Message_37").ToString());
                    }
                }
                else
                {
                    StringBuilder sb = new StringBuilder();
                    sb.Append(App.Current.FindResource("Message_38").ToString());
                    foreach (var err in errMsg)
                    {
                        sb.Append("\r\n" + err);
                    }
                    MessageBox.Show(this, sb.ToString());
                }
            }
            catch (Exception exe)
            {
                Dispatcher.Invoke(updatePbDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { System.Windows.Controls.ProgressBar.ValueProperty, Convert.ToDouble(100) });
                Dispatcher.Invoke(progressBarGridDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { System.Windows.Controls.Grid.VisibilityProperty, Visibility.Collapsed });
                MessageBox.Show(this, App.Current.FindResource("Message_45").ToString() + exe.Message);
            }
        }
 private void tabSetting_SelectionChanged(object sender, SelectionChangedEventArgs e)
 {
     if (e.AddedItems!=null&&e.AddedItems.Count > 0)
     {
         var tabItem=e.AddedItems[0] as TabItem;
         if (tabItem!=null&&"tabVersion".Equals(tabItem.Name))
         {
             if (this.radradDeviceType1.DataContext.Equals(App.reportSettingModel.DeviceType.ToString()))
             {
                 this.radradDeviceType1.IsChecked = true;
             }
             else if (this.radradDeviceType2.DataContext.Equals(App.reportSettingModel.DeviceType.ToString()))
             {
                 this.radradDeviceType2.IsChecked = true;
             }
             else
             {
                 this.radradDeviceType3.IsChecked = true;
             }
     
             //定义委托代理
             ProgressBarGridDelegate progressBarGridDelegate = new ProgressBarGridDelegate(progressBarGrid.SetValue);
             UpdateProgressBarDelegate updatePbDelegate = new UpdateProgressBarDelegate(uploadProgressBar.SetValue);
             //使用系统代理方式显示进度条面板
             Dispatcher.Invoke(updatePbDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { System.Windows.Controls.ProgressBar.ValueProperty, Convert.ToDouble(10) });
             Dispatcher.Invoke(progressBarGridDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { System.Windows.Controls.Grid.VisibilityProperty, Visibility.Visible });
             Dispatcher.Invoke(updatePbDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { System.Windows.Controls.ProgressBar.ValueProperty, Convert.ToDouble(20) });
             List<string> fileList = new List<string>();
             try
             {
                 string ftpPath = App.reportSettingModel.FtpPath.Replace("home", "MeikUpdate");
                 //查询FTP上所有版本文件列表要下载的文件列表
                 fileList = FtpHelper.Instance.GetFileList(App.reportSettingModel.FtpUser, App.reportSettingModel.FtpPwd, ftpPath);
                 Dispatcher.Invoke(updatePbDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { System.Windows.Controls.ProgressBar.ValueProperty, Convert.ToDouble(90) });
             }
             catch (Exception ex)
             {
                 MessageBox.Show(this, App.Current.FindResource("Message_47").ToString() + " " + ex.Message);
                 Dispatcher.Invoke(progressBarGridDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { System.Windows.Controls.Grid.VisibilityProperty, Visibility.Collapsed });
                 return;
             }
             try
             {
                 fileList.Reverse();
                 foreach (var setupFileName in fileList)
                 {
                     if (setupFileName.EndsWith(".exe", StringComparison.OrdinalIgnoreCase))
                     {
                         var verStr = setupFileName.ToLower().Replace(".exe", "").Replace("meiksetup.", "");
                         string currentVer = App.reportSettingModel.Version;
                         if (string.Compare(verStr, currentVer,StringComparison.OrdinalIgnoreCase) > 0)
                         {                                                                
                             labVerCheckInfo.Content = App.Current.FindResource("SettingVersionCheckInfo2").ToString();
                             btnUpdateNow.IsEnabled = true;                            
                         }
                         break;
                     }
                     else
                     {
                         continue;
                     }
                 }
             }
             catch (Exception ex1)
             {
                 MessageBox.Show(this, ex1.Message);
             }
             Dispatcher.Invoke(updatePbDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { System.Windows.Controls.ProgressBar.ValueProperty, Convert.ToDouble(100) });
             Dispatcher.Invoke(progressBarGridDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { System.Windows.Controls.Grid.VisibilityProperty, Visibility.Collapsed });
     
         }
     }
 }
Beispiel #56
0
        /// <summary>
        /// Technician发送数据事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SendDataButton_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(App.reportSettingModel.MailAddress) || string.IsNullOrEmpty(App.reportSettingModel.MailHost)
                || string.IsNullOrEmpty(App.reportSettingModel.MailUsername) || string.IsNullOrEmpty(App.reportSettingModel.MailPwd)
                || string.IsNullOrEmpty(App.reportSettingModel.ToMailAddress))
            {
                MessageBox.Show(this, App.Current.FindResource("Message_15").ToString());
                return;
            }
            string deviceNo = App.reportSettingModel.DeviceNo;
            int deviceType = App.reportSettingModel.DeviceType;
            var selectedUserList = this.CodeListBox.SelectedItems;
            if (selectedUserList == null || selectedUserList.Count == 0)
            {
                MessageBox.Show(this, App.Current.FindResource("Message_35").ToString());
                return;
            }

            MessageBoxResult result = MessageBox.Show(this, App.Current.FindResource("Message_17").ToString(), "Send Data", MessageBoxButton.YesNo, MessageBoxImage.Information);
            if (result == MessageBoxResult.Yes)
            {
                //判断报告是否已经填写Techinican名称
                SelectTechnicianPage SelectTechnicianPage = new SelectTechnicianPage(App.reportSettingModel.TechNames);
                SelectTechnicianPage.Owner = this;
                SelectTechnicianPage.ShowDialog();
                if (string.IsNullOrEmpty(App.reportSettingModel.ReportTechName))
                {
                    return;
                }

                //隐藏已MRN区域显示的上传过的图标
                foreach (Person selectedUser in selectedUserList)
                {
                    selectedUser.Uploaded = Visibility.Collapsed.ToString();
                }
                //定义委托代理
                ProgressBarGridDelegate progressBarGridDelegate = new ProgressBarGridDelegate(progressBarGrid.SetValue);
                UpdateProgressBarDelegate updatePbDelegate = new UpdateProgressBarDelegate(uploadProgressBar.SetValue);
                //使用系统代理方式显示进度条面板
                Dispatcher.Invoke(progressBarGridDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { System.Windows.Controls.Grid.VisibilityProperty, Visibility.Visible });
                try
                {
                    List<string> errMsg = new List<string>();
                    int n = 0;
                    double groupValue = 100 / selectedUserList.Count;
                    double sizeValue = groupValue / 10;
                    //循环处理选择的每一个患者档案
                    foreach (Person selectedUser in selectedUserList)
                    {
                        //string dataFile = dataFolder + System.IO.Path.DirectorySeparatorChar + selectedUser.Code + ".dat";
                        string dataFile = selectedUser.ArchiveFolder + System.IO.Path.DirectorySeparatorChar + selectedUser.Code + ".dat";
                        //如果是医生模式但当前的患者档案中却没有报告数据,则不能发送数据
                        if (!File.Exists(dataFile) && deviceType == 2)
                        {
                            errMsg.Add(selectedUser.Code + " :: " + App.Current.FindResource("Message_16").ToString());
                            continue;
                        }

                        //把检测员名称和证书写入.crd文件
                        try
                        {
                            OperateIniFile.WriteIniData("Report", "Technician Name", selectedUser.TechName, selectedUser.IniFilePath);
                            OperateIniFile.WriteIniData("Report", "Technician License", selectedUser.TechLicense, selectedUser.IniFilePath);
                            OperateIniFile.WriteIniData("Report", "Screen Venue", App.reportSettingModel.ScreenVenue, selectedUser.IniFilePath);                            
                        }
                        catch (Exception exe)
                        {
                            //如果不能写入ini文件
                            FileHelper.SetFolderPower(selectedUser.ArchiveFolder, "Everyone", "FullControl");
                            FileHelper.SetFolderPower(selectedUser.ArchiveFolder, "Users", "FullControl");
                        }

                        Dispatcher.Invoke(updatePbDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { System.Windows.Controls.ProgressBar.ValueProperty, Convert.ToDouble(groupValue * n + sizeValue) });

                        //打包数据文件,并上传到FPT服务
                        string zipFile = dataFolder + System.IO.Path.DirectorySeparatorChar + selectedUser.Code + "-" + selectedUser.SurName;
                        zipFile = zipFile + (string.IsNullOrEmpty(selectedUser.GivenName) ? "" : "," + selectedUser.GivenName) + (string.IsNullOrEmpty(selectedUser.OtherName) ? "" : " " + selectedUser.OtherName) + ".zip";

                        try
                        {
                            //ZipTools.Instance.ZipFolder(selectedUser.ArchiveFolder, zipFile, 1);
                            ZipTools.Instance.ZipFiles(selectedUser.ArchiveFolder, zipFile, 1);
                            Dispatcher.Invoke(updatePbDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { System.Windows.Controls.ProgressBar.ValueProperty, Convert.ToDouble(groupValue * n + sizeValue * 5) });
                        }
                        catch (Exception ex1)
                        {
                            errMsg.Add(selectedUser.Code + " :: " + string.Format(App.Current.FindResource("Message_21").ToString() + " " + ex1.Message, selectedUser.ArchiveFolder));
                            continue;
                        }

                        //上传到FTP服务器
                        try
                        {
                            FtpHelper.Instance.Upload(App.reportSettingModel.FtpUser, App.reportSettingModel.FtpPwd, App.reportSettingModel.FtpPath + "Send/", zipFile);
                            //上传成功后保存上传状态,以便让用户知道这个患者今天已经成功提交过数据
                            if (!App.uploadedCodeList.Contains(selectedUser.Code))
                            {
                                App.uploadedCodeList.Add(selectedUser.Code);
                            }
                            selectedUser.Uploaded = Visibility.Visible.ToString();
                            try
                            {
                                File.Delete(zipFile);
                            }
                            catch { }
                        }
                        catch (Exception ex2)
                        {
                            errMsg.Add(selectedUser.Code + " :: " + App.Current.FindResource("Message_52").ToString() + " " + ex2.Message);
                            continue;
                        }
                        Dispatcher.Invoke(updatePbDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { System.Windows.Controls.ProgressBar.ValueProperty, Convert.ToDouble(groupValue * n + sizeValue * 9) });

                        ////如果是检测员模式,则每天要上传一次扫描记录
                        //string currentDate = System.DateTime.Now.ToString("yyyyMMdd");
                        //if (App.countDictionary.Count > 0 && !currentDate.Equals(App.reportSettingModel.RecordDate))
                        //{
                        //    string excelFile = dataFolder + System.IO.Path.DirectorySeparatorChar + deviceNo + "_Count.xls";
                        //    try
                        //    {
                        //        if (File.Exists(excelFile))
                        //        {
                        //            try
                        //            {
                        //                File.Delete(excelFile);
                        //            }
                        //            catch { }
                        //        }
                        //        exportExcel(excelFile);
                        //        if (!FtpHelper.Instance.FolderExist(App.reportSettingModel.FtpUser, App.reportSettingModel.FtpPwd, App.reportSettingModel.FtpPath, "ScreeningRecords"))
                        //        {
                        //            FtpHelper.Instance.MakeDir(App.reportSettingModel.FtpUser, App.reportSettingModel.FtpPwd, App.reportSettingModel.FtpPath, "ScreeningRecords");
                        //        }
                        //        FtpHelper.Instance.Upload(App.reportSettingModel.FtpUser, App.reportSettingModel.FtpPwd, App.reportSettingModel.FtpPath + "/ScreeningRecords/", excelFile);
                        //        App.reportSettingModel.RecordDate = currentDate;
                        //        OperateIniFile.WriteIniData("Data", "Record Date", currentDate, System.AppDomain.CurrentDomain.BaseDirectory + "Config.ini");
                        //        try
                        //        {
                        //            File.Delete(excelFile);
                        //        }
                        //        catch { }
                        //    }
                        //    catch { }
                        //}
                        n++;
                    }

                    try
                    {
                        //发送通知邮件  
                        SendEmail((selectedUserList.Count - errMsg.Count), true);
                    }
                    catch (Exception ex3)
                    {
                        errMsg.Add(App.Current.FindResource("Message_19").ToString() + " " + ex3.Message);
                    }

                    Dispatcher.Invoke(updatePbDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { System.Windows.Controls.ProgressBar.ValueProperty, Convert.ToDouble(100) });
                    //显示没有成功发送数据的错误消息
                    if (errMsg.Count > 0)
                    {
                        StringBuilder sb = new StringBuilder();
                        sb.Append(string.Format(App.Current.FindResource("Message_36").ToString(), errMsg.Count));
                        foreach (var err in errMsg)
                        {
                            sb.Append("\r\n" + err);
                        }
                        MessageBox.Show(this, sb.ToString());
                    }
                    else
                    {
                        MessageBox.Show(this, App.Current.FindResource("Message_18").ToString());
                    }
                }
                finally
                {
                    Dispatcher.Invoke(progressBarGridDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { System.Windows.Controls.Grid.VisibilityProperty, Visibility.Collapsed });
                }
            }
        }
        private void usrcheatDownload(string usrcheat) //connects and tries to download the usrcheat
        {
            Title = "Downloading...";
            progressBar1.Value = 0; //empty the progress bar
            usrcheatDownloaded = new byte[0];

            try
            {
                //Fetch the usrcheat from Syntechx.com
                WebRequest req = WebRequest.Create(usrcheat);
                WebResponse res = req.GetResponse();
                Stream stream = res.GetResponseStream();

                byte[] buffer = new byte[1024];

                //Get the length, in bytes, of content sent by the client.
                //usrcheatLength = MaxLength of the usrcheat file
                int usrcheatLength = (int)res.ContentLength;

                //set the progressbar's max value to the usrcheatLength
                progressBar1.Maximum = usrcheatLength;

                //Time to download...
                MemoryStream memStream = new MemoryStream();
                UpdateProgressBarDelegate updatePbDelegate = new UpdateProgressBarDelegate(progressBar1.SetValue);

                while (true)
                {
                    //Try to read the data
                    int bytesRead = stream.Read(buffer, 0, buffer.Length);

                    if (bytesRead == 0) //Are we finished downloading? 
                    {
                        progressBar1.Value = progressBar1.Maximum;
                        break;
                    }
                    else //Eh, I guess not...
                    {
                        //Write the downloaded data to the current stream
                        memStream.Write(buffer, 0, bytesRead);

                        //Update the progress bar
                        if (progressBar1.Value + bytesRead <= progressBar1.Maximum)
                        {
                            progressBar1.Value += bytesRead;
                            Dispatcher.Invoke(updatePbDelegate, System.Windows.Threading.DispatcherPriority.Background, 
                                                        new object[] { ProgressBar.ValueProperty, progressBar1.Value });
                        }
                    }
                }

                usrcheatDownloaded = memStream.ToArray(); //Convert the downloaded stream to a byte array
                stream.Close(); //Closes the current stream and releases everything associated with it
                memStream.Close(); //Closes the stream for reading and writing.
            }
            catch (System.Exception) //No internet connection? 
            {
                MessageBox.Show("A problem occurred while trying to download the latest usrcheat. Please check your internet settings and retry.",
                                                                                "Download Incomplete", MessageBoxButton.OK, MessageBoxImage.Error);
            }

            Title = "Download Complete";
        }
Beispiel #58
0
        private void SendReportButton_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(App.reportSettingModel.MailAddress) || string.IsNullOrEmpty(App.reportSettingModel.MailHost)
                || string.IsNullOrEmpty(App.reportSettingModel.MailUsername) || string.IsNullOrEmpty(App.reportSettingModel.MailPwd)
                || string.IsNullOrEmpty(App.reportSettingModel.ToMailAddress))
            {
                MessageBox.Show(this, App.Current.FindResource("Message_15").ToString());
                return;
            }
            string deviceNo = App.reportSettingModel.DeviceNo;
            int deviceType = App.reportSettingModel.DeviceType;
            var selectedUserList = this.CodeListBox.SelectedItems;
            if (selectedUserList == null || selectedUserList.Count==0)
            {
                MessageBox.Show(this, App.Current.FindResource("Message_35").ToString());
                return;
            }
                                                
            MessageBoxResult result = MessageBox.Show(this, App.Current.FindResource("Message_17").ToString(), "Send Report", MessageBoxButton.YesNo, MessageBoxImage.Information);
            if (result == MessageBoxResult.Yes)
            {                
                foreach (Person selectedUser in selectedUserList)
                {
                    selectedUser.Uploaded = Visibility.Collapsed.ToString();
                }
                ProgressBarGridDelegate progressBarGridDelegate = new ProgressBarGridDelegate(progressBarGrid.SetValue);
                UpdateProgressBarDelegate updatePbDelegate = new UpdateProgressBarDelegate(uploadProgressBar.SetValue);
                //使用系统代理方式显示进度条面板
                Dispatcher.Invoke(progressBarGridDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { System.Windows.Controls.Grid.VisibilityProperty, Visibility.Visible });
                try
                {
                    List<string> errMsg = new List<string>();
                    int n = 0;
                    double groupValue = 100 / selectedUserList.Count;
                    double sizeValue = groupValue / 10;
                    //循环处理选择的每一个患者档案
                    foreach (Person selectedUser in selectedUserList)
                    {                        
                        string dataFile = selectedUser.ArchiveFolder + System.IO.Path.DirectorySeparatorChar + selectedUser.Code + ".dat";
                        //如果是医生模式但当前的患者档案中却没有报告数据,则不能发送数据
                        if (!File.Exists(dataFile) && deviceType == 2)
                        {
                            errMsg.Add(selectedUser.Code + " :: " + App.Current.FindResource("Message_16").ToString());
                            continue;
                        }                        

                        Dispatcher.Invoke(updatePbDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { System.Windows.Controls.ProgressBar.ValueProperty, Convert.ToDouble(groupValue * n + sizeValue) });

                        //打包数据文件,并上传到FPT服务
                        string zipFile = dataFolder + System.IO.Path.DirectorySeparatorChar + "R_" + selectedUser.Code + "-" + selectedUser.SurName;                        
                        zipFile = zipFile + (string.IsNullOrEmpty(selectedUser.GivenName) ? "" : "," + selectedUser.GivenName) + (string.IsNullOrEmpty(selectedUser.OtherName) ? "" : " " + selectedUser.OtherName) + ".zip";                        

                        try
                        {
                            //ZipTools.Instance.ZipFolder(selectedUser.ArchiveFolder, zipFile, deviceType);
                            ZipTools.Instance.ZipFiles(selectedUser.ArchiveFolder, zipFile,2);
                            Dispatcher.Invoke(updatePbDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { System.Windows.Controls.ProgressBar.ValueProperty, Convert.ToDouble(groupValue * n + sizeValue * 5) });
                        }
                        catch (Exception ex1)
                        {
                            errMsg.Add(selectedUser.Code + " :: " + string.Format(App.Current.FindResource("Message_21").ToString() + " " + ex1.Message, selectedUser.ArchiveFolder));
                            continue;
                        }

                        //上传到FTP服务器
                        try
                        {
                            FtpHelper.Instance.Upload(App.reportSettingModel.FtpUser, App.reportSettingModel.FtpPwd, App.reportSettingModel.FtpPath+"Send/", zipFile);
                            //上传成功后保存上传状态,以便让用户知道这个患者今天已经成功提交过数据
                            if (!App.uploadedCodeList.Contains(selectedUser.Code))
                            {
                                App.uploadedCodeList.Add(selectedUser.Code);
                            }
                            selectedUser.Uploaded = Visibility.Visible.ToString();
                            try
                            {
                                File.Delete(zipFile);
                            }
                            catch { }
                        }
                        catch (Exception ex2)
                        {
                            errMsg.Add(selectedUser.Code + " :: " + App.Current.FindResource("Message_52").ToString() + " " + ex2.Message);
                            continue;
                        }
                        Dispatcher.Invoke(updatePbDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { System.Windows.Controls.ProgressBar.ValueProperty, Convert.ToDouble(groupValue * n + sizeValue * 9) });
                        
                        n++;
                    }

                    try
                    {
                        //发送通知邮件  
                        SendEmail((selectedUserList.Count - errMsg.Count), true);
                    }
                    catch (Exception ex3)
                    {
                        errMsg.Add(App.Current.FindResource("Message_19").ToString() + " " + ex3.Message);                        
                    }
                    //完成进度条
                    Dispatcher.Invoke(updatePbDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { System.Windows.Controls.ProgressBar.ValueProperty, Convert.ToDouble(100) });

                    //显示没有成功发送数据的错误消息
                    if (errMsg.Count > 0)
                    {
                        StringBuilder sb = new StringBuilder();
                        sb.Append(string.Format(App.Current.FindResource("Message_36").ToString(), errMsg.Count));
                        foreach (var err in errMsg)
                        {
                            sb.Append("\r\n" + err);
                        }
                        MessageBox.Show(this, sb.ToString());
                    }
                    else
                    {
                        MessageBox.Show(this, App.Current.FindResource("Message_18").ToString());
                    }
                }
                finally
                {
                    //关闭进度条蒙板
                    Dispatcher.Invoke(progressBarGridDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { System.Windows.Controls.Grid.VisibilityProperty, Visibility.Collapsed });
                }
                
            }
        }
        private void btnExport_Click(object sender, RoutedEventArgs e)
        {
            exportProgress.Minimum = 0;
            exportProgress.Maximum = TestInfoList.Count ;
            exportProgress.Value = 0;
            double value = 0;
            UpdateProgressBarDelegate updatePbDelegate = new UpdateProgressBarDelegate(exportProgress.SetValue);
            try
            {
                excelApp = new ApplicationClass();
                Workbooks myWorkBooks = excelApp.Workbooks;
                myWorkBooks.Open(templatePath, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
                Sheets sheets = excelApp.Sheets;
                mySheet1 = (Worksheet)sheets[1];
                mySheet1.Activate();

                int rowCount = TestInfoList.Count + 2; ;//总行数

                //写入参数信息
                int paramCount = 0;//参数行数
                if (IsExportParams)
                {
                    paramCount = ParamList.Count * 4;
                    for (int i = 0; i < ParamList.Count; i++)
                    {
                        Model.Parameter p = ParamList[i];

                        Range r = mySheet1.get_Range(mySheet1.Cells[1, testInfoColumnCount + i * 4 + 1], mySheet1.Cells[1, testInfoColumnCount + i * 4 + 4]);
                        r.Merge();
                        r.Value = p.ParamName;
                        r.Font.Bold = true;
                        r.HorizontalAlignment = XlHAlign.xlHAlignCenter;
                        r.VerticalAlignment = XlHAlign.xlHAlignCenter;

                        Range r1 = mySheet1.get_Range(mySheet1.Cells[2, testInfoColumnCount + i * 4 + 1], mySheet1.Cells[2, testInfoColumnCount + i * 4 + 4]);
                        r1.Value2 = paramContents;
                        r1.Font.Bold = true;

                        r1.EntireColumn.AutoFit();
                    }
                }

                //写入测试信息
                string[,] content = new string[rowCount, testInfoColumnCount + paramCount];
                //double?[,] paramContent = new double?[rowCount, paramCount];

                XDocument xdoc;
                BLL.TB_Dict dictBLL = new BLL.TB_Dict();
                for (int i = 0; i < TestInfoList.Count; i++)
                {
                    int rowIndex = i;
                    Model.TestInfoModel model = TestInfoList[i];

                    content[rowIndex, 0] = string.Format("测试{0}", i + 1);//测试顺序
                    content[rowIndex, 1] = model.Ath_Name;//姓名
                    content[rowIndex, 2] = model.TestDate.ToString("yyyy-MM-dd HH:mm");//测试日期
                    content[rowIndex, 3] = model.DJoint;//测试关节
                    content[rowIndex, 4] = model.DJointSide;//测试侧
                    content[rowIndex, 5] = model.DPlane;//运动方式
                    content[rowIndex, 6] = model.DTestMode;//测试模式
                    content[rowIndex, 7] = model.MotionRange;//运动范围
                    content[rowIndex, 8] = model.Speed;//测试速度
                    content[rowIndex, 9] = model.Break;//休息时间
                    content[rowIndex, 10] = model.NOOfSets;//测试组数
                    content[rowIndex, 11] = model.NOOfRepetitions;//重复次数
                    content[rowIndex, 12] = model.DInsuredSide;//受伤测
                    content[rowIndex, 13] = model.DGravitycomp;//重力补偿
                    if (IsExportParams)
                    {
                        string xmlPath = Model.AppPath.XmlDataDirPath + model.DataFileName;
                        xdoc = XDocument.Load(xmlPath);
                        List<XElement> action1 = xdoc.Descendants("action1").Elements<XElement>().ToList<XElement>();
                        List<XElement> action2 = xdoc.Descendants("action2").Elements<XElement>().ToList<XElement>();
                        for (int j = 0; j < ParamList.Count; j++)
                        {
                            int paramOneColumnIndex = j * 4;
                            double p1;
                            if (double.TryParse(action1[ParamList[j].Index].Attribute("max").Value, out p1)) {
                                //paramContent[rowIndex, paramOneColumnIndex] = p1;
                                mySheet1.Cells[rowIndex + 3, paramOneColumnIndex + testInfoColumnCount + 1] = p1;
                            }
                            double p2;
                            if (double.TryParse(action1[ParamList[j].Index].Attribute("avg").Value, out p2))
                            {
                                //paramContent[rowIndex, paramOneColumnIndex + 1] = p2;
                                mySheet1.Cells[rowIndex + 3, paramOneColumnIndex + testInfoColumnCount + 2] = p2;
                            }
                            double p3;
                            if (double.TryParse(action2[ParamList[j].Index].Attribute("max").Value, out p3))
                            {
                                //paramContent[rowIndex, paramOneColumnIndex + 2] = p3;
                                mySheet1.Cells[rowIndex + 3, paramOneColumnIndex + testInfoColumnCount + 3] = p3;
                            }
                            double p4;
                            if (double.TryParse(action2[ParamList[j].Index].Attribute("avg").Value, out p4))
                            {
                                //paramContent[rowIndex, paramOneColumnIndex + 3] = p4;
                                mySheet1.Cells[rowIndex + 3, paramOneColumnIndex + testInfoColumnCount + 4] = p4;
                            }

                        }
                    }

                    //写进度条
                    value += 1;
                    Dispatcher.Invoke(updatePbDelegate,
                        System.Windows.Threading.DispatcherPriority.Background,
                        new object[] { ProgressBar.ValueProperty, value });
                }
                //写入测试信息
                Range range1 = mySheet1.get_Range(mySheet1.Cells[3, 1], mySheet1.Cells[rowCount, testInfoColumnCount]);
                range1.Value2 = content;
                //写入参数信息
                //Range range2 = mySheet1.get_Range(mySheet1.Cells[3, testInfoColumnCount + 1], mySheet1.Cells[rowCount, testInfoColumnCount + paramCount]);
                //range2.Value2 = paramContent;

                //if (IsExportParams)
                //{
                //    rowCount = TestInfoList.Count + (ParamList.Count + 1) * TestInfoList.Count + 1;//信息行数+信息行数×参数行数+第一行列头信息
                //    paramCount = ParamList.Count + 1;//参数行数加1行参数名
                //}
                //else {
                //    rowCount = TestInfoList.Count + 1;
                //}

                //string[,] content = new string[rowCount, 13];

                //XDocument xdoc;
                //Model.TB_Dict actionModel;
                //BLL.TB_Dict dictBLL = new BLL.TB_Dict();
                //for (int i = 0; i < TestInfoList.Count; i++) {
                //    int rowIndex = i + i * paramCount;
                //    Model.TestInfoModel model = TestInfoList[i];

                //    content[rowIndex, 0] = model.Ath_Name;//姓名
                //    content[rowIndex, 1] = model.TestDate.ToString("yyyy-MM-dd HH:mm");//测试日期
                //    content[rowIndex, 2] = model.DJoint;//测试关节
                //    content[rowIndex, 3] = model.DJointSide;//测试侧
                //    content[rowIndex, 4] = model.DPlane;//运动方式
                //    content[rowIndex, 5] = model.DTestMode;//测试模式
                //    content[rowIndex, 6] = model.MotionRange;//运动范围
                //    content[rowIndex, 7] = model.Speed;//测试速度
                //    content[rowIndex, 8] = model.Break;//休息时间
                //    content[rowIndex, 9] = model.NOOfSets;//测试组数
                //    content[rowIndex, 10] = model.NOOfRepetitions;//重复次数
                //    content[rowIndex, 11] = model.DInsuredSide;//受伤测
                //    content[rowIndex, 12] = model.DGravitycomp;//重力补偿
                //    if (IsExportParams) {
                //        //写入参数信息
                //        actionModel = dictBLL.GetModel(model.Joint, model.Plane, model.Test_Mode);
                //        content[rowIndex + 1, 0] = "所选测试顺序";
                //        content[rowIndex + 1, 1] = "参数";
                //        content[rowIndex + 1, 2] = actionModel.actionone + "(极值)";
                //        content[rowIndex + 1, 3] = actionModel.actionone + "(平均值)";
                //        content[rowIndex + 1, 4] = actionModel.actiontwo + "(极值)";
                //        content[rowIndex + 1, 5] = actionModel.actiontwo + "(平均值)";
                //        string xmlPath = Model.AppPath.XmlDataDirPath + model.DataFileName;
                //        xdoc = XDocument.Load(xmlPath);
                //        List<XElement> action1 = xdoc.Descendants("action1").Elements<XElement>().ToList<XElement>();
                //        List<XElement> action2 = xdoc.Descendants("action2").Elements<XElement>().ToList<XElement>();
                //        for (int j = 0; j < ParamList.Count; j++)
                //        {
                //            content[rowIndex + 1 + j + 1, 0] = "测试" + (i + 1);
                //            content[rowIndex + 1 + j + 1, 1] = ParamList[j].ParamName;
                //            content[rowIndex + 1 + j + 1, 2] = action1[ParamList[j].Index].Attribute("max").Value;
                //            content[rowIndex + 1 + j + 1, 3] = action1[ParamList[j].Index].Attribute("avg").Value;
                //            content[rowIndex + 1 + j + 1, 4] = action2[ParamList[j].Index].Attribute("max").Value;
                //            content[rowIndex + 1 + j + 1, 5] = action2[ParamList[j].Index].Attribute("avg").Value;
                //        }
                //    }

                //    //写进度条
                //    value += 1;
                //    Dispatcher.Invoke(updatePbDelegate,
                //        System.Windows.Threading.DispatcherPriority.Background,
                //        new object[] { ProgressBar.ValueProperty, value });
                //}
                //Range range = mySheet1.get_Range(mySheet1.Cells[2, 1], mySheet1.Cells[rowCount, 13]);
                //range.Value2 = content;
                mySheet1.SaveAs(choosePath, missing, missing, missing, missing, missing, missing, missing, missing, missing);
                myWorkBooks.Close();
                excelApp.Quit();
                MessageBox.Show("导出成功!", "系统信息");
                System.Windows.Window.GetWindow(this).Close();
            }
            catch (Exception ee) {
                MessageBox.Show("导出出错!\r\n错误信息为:" + ee.Message, "系统错误");
            }
        }
        private void RemoveBtnClick(object sender, RoutedEventArgs e)
        {
            if (fileStructListView.SelectedItems.Count < 1)
            {
                MessageBox.Show("No files selected.", "No Files Selected");
                return;
            }
            var updatePbDelegate = new UpdateProgressBarDelegate(progressBar1.SetValue);
            var updateCurFile = new UpdateLabelDelegate(curFileLabel.SetValue);

            double value = 0;
            progressBar1.Minimum = 0;
            progressBar1.Maximum = fileStructListView.SelectedItems.Count;
            progressBar1.Value = 0;
            foreach (fileStruct file in fileStructListView.SelectedItems)
            {
                if (_stop)
                {
                    ClearVars();
                    _stop = false;
                    break;
                }
                Dispatcher.Invoke(updatePbDelegate,
                    System.Windows.Threading.DispatcherPriority.Background,
                    new object[] { ProgressBar.ValueProperty, value });

                var progressMessage = "Deleting: " + file.fullPath;
                Dispatcher.Invoke(updateCurFile,
                    System.Windows.Threading.DispatcherPriority.Background,
                    new object[] { TextBox.TextProperty, progressMessage });

                _removeFiles.removeFiles(file, _permanentDelete);
            }

            selectOldestBtn.IsEnabled = false;
            selectNewestBtn.IsEnabled = false;
            curFileLabel.Text = "";
            ClearVars();
        }