public Boolean exportData( String[] inTableName, String[] inSelectStmt, String inFullFileName ) { Boolean returnStatus = false; StreamWriter outBuffer = File.CreateText( inFullFileName ); StringBuilder inReturnMessage = new StringBuilder( "" ); if (outBuffer != null) { myProgressInfo = new ProgressWindow(); myProgressInfo.setProgessMsg( "Exporting selected data for " + inTableName.Length + " data types" ); myProgressInfo.Show(); myProgressInfo.Refresh(); myProgressInfo.setProgressMax( inTableName.Length ); for ( int idx = 0; idx < inTableName.Length; idx++ ) { returnStatus = exportData( inTableName[idx], inSelectStmt[idx], outBuffer, false, inReturnMessage ); myProgressInfo.setProgressValue( idx + 1 ); myProgressInfo.Refresh(); } outBuffer.Close(); myProgressInfo.Close(); if (inReturnMessage.Length > 1) { MessageBox.Show( inReturnMessage.ToString() ); } } return returnStatus; }
private void progressTh() { progWindow = new ProgressWindow(); progWindow.Show(); System.Windows.Threading.Dispatcher.Run(); }
// Send values to Excel public void RunMultiframe(Data data, System.Windows.Controls.Button mfButton) { this.mfButton = mfButton; this.data = data; progressWindow = new ProgressWindow(); try { IsRunning = true; mfButton.IsEnabled = false; fileName = Properties.Settings.Default.ExcelWorkbookFilepath; // Run Excel/Multiframe in new thread bw = new BackgroundWorker(); bw.WorkerReportsProgress = true; bw.DoWork += new DoWorkEventHandler(BackgroundWorker_DoWork); bw.ProgressChanged += new ProgressChangedEventHandler(BackgroundWorker_ProgressChanged); bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(BackgroundWorker_RunWorkerCompleted); bw.RunWorkerAsync(data); progressWindow.ShowDialog(); } catch (Exception e) { MessageBox.Show("Error while running Excel component", "Error in MFA Program"); } finally { IsRunning = false; mfButton.IsEnabled = true; } }
public VisioGraph(ProgressWindow progressWindow, ProcessViewerDialog parent) { try { var drawItem = parent.Result; _vapp = new Visio.InvisibleApp(); if (!IsCorrectVisioVersion(_vapp)) return; _progressWindow = progressWindow; _vdoc = _vapp.Documents.Add(""); if (!File.Exists(_vapp.Path + @"1033\Concept.vss")) { File.Delete(_vapp.Path + @"1033\Concept.vss"); File.WriteAllBytes(_vapp.Path + @"1033\Concept.vss", Properties.Resources.Concept); } _stencil = _vapp.Documents.OpenEx(_vapp.Path + @"1033\Concept.vss", (short)Visio.VisOpenSaveArgs.visOpenDocked | (short)Visio.VisOpenSaveArgs.visOpenRO | (short)Visio.VisOpenSaveArgs.visAddStencil); _vdoc.Pages[1].Name = "Overview Page"; _parent = parent; _bgWorker = new BackgroundWorker { WorkerReportsProgress = true, WorkerSupportsCancellation = true }; _bgWorker.DoWork += DoWork; _bgWorker.RunWorkerCompleted += RunWorkerCompleted; _bgWorker.ProgressChanged += ProgressChanged; _progressWindow.pbarTotal.Minimum = 0; int totalOperations = 0; foreach (var process in drawItem.Process) { process.GenerateContent(drawItem.ConnectionString); totalOperations += process.SubProcesses.Count(); totalOperations += process.Connectors.Count(); } int stepSize = totalOperations / 20; _progressWindow.pbarTotal.Maximum = (totalOperations) + stepSize; var args = new WorkerArgs { DrawItem = drawItem, StepSize = stepSize, }; _bgWorker.RunWorkerAsync(args); } catch (Exception) { MessageBox.Show(@"Unable to load Visio. Please make sure Visio 2010 has been installed on your system."); } }
public ProgressWindow BeginPopupProgressWindow(Progress progress) { ProgressWindow progressWindow = null; this.Dispatcher.InvokeAsync(() => { progressWindow = new ProgressWindow(null, progress); progressWindow.Show(); }); return progressWindow; }
public void CalculateEstimatedCompressedSize(Window owner) { ProgressWindow progressWindow = new ProgressWindow { IsIndeterminate = false, ProgressMinimum = 0, ProgressMaximum = ImageShrinkerViewModel.SelectedImageCount, Title = "Geschätze Archivgröße", Owner = owner, }; DoWorkerJob(progressWindow, CalculateEstimatedCompressedSizeWorker); }
/// <summary> /// Invoked when the login button is clicked. /// </summary> /// <param name="sender">Object that caused this event to be triggered.</param> /// <param name="e">Arguments explaining why this event occured.</param> private void loginButton_Click(object sender, EventArgs e) { string password = passwordTextBox.Text; string username = usernameTextBox.Text; if (password == null || password.Length < 6 || username == null || username.Length < 6) { MessageBox.Show("A password and username must be entered. Both must be equal to or longer than 6 characters", "Invalid Login", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { ProgressWindow progressWindow = new ProgressWindow("Logging in", "Verifying login"); progressWindow.Marquee = true; progressWindow.Show(); this.Enabled = false; FileDownloader downloader = new FileDownloader("http://www.binaryphoenix.com/index.php?action=fusionverifylogin&username="******"&password="******"") { MessageBox.Show("An error occured while connecting to the server. Please try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } Application.DoEvents(); } this.Enabled = true; progressWindow.Dispose(); ASCIIEncoding encoding = new ASCIIEncoding(); string response = encoding.GetString(downloader.FileData); if (response.ToLower() == "invalid") MessageBox.Show("The login given was invalid. If you have lost your password please click the password reset link.", "Invalid Login", MessageBoxButtons.OK, MessageBoxIcon.Warning); else if (response.ToLower() == "valid") { MessageBox.Show("Your login was successfull.", "Valid Login", MessageBoxButtons.OK, MessageBoxIcon.Information); // Place the password / username in the config file if we are to remember them. Fusion.GlobalInstance.CurrentUsername = username; Fusion.GlobalInstance.CurrentPassword = password; Fusion.GlobalInstance.RememberUser = rememberMeCheckBox.Checked; Close(); } else MessageBox.Show("Unexpected value returned from server. Please try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
/// <summary> /// Invoked when the reset button is clicked. /// </summary> /// <param name="sender">Object that caused this event to be triggered.</param> /// <param name="e">Arguments explaining why this event occured.</param> private void resetButton_Click(object sender, EventArgs e) { string email = emailTextBox.Text; if (email == null || !email.Contains("@")) { MessageBox.Show("A valid email must be entered.", "Invalid Email", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { ProgressWindow progressWindow = new ProgressWindow("Reseting Password", "Contacting server"); progressWindow.Marquee = true; progressWindow.Show(); this.Enabled = false; FileDownloader downloader = new FileDownloader("http://www.binaryphoenix.com/index.php?action=fusionresetpassword&email=" + System.Web.HttpUtility.UrlEncode(email)); downloader.Start(); while (downloader.Complete == false) { if (downloader.Error != "") { MessageBox.Show("An error occured while connecting to the server. Please try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } Application.DoEvents(); } this.Enabled = true; progressWindow.Dispose(); ASCIIEncoding encoding = new ASCIIEncoding(); string response = encoding.GetString(downloader.FileData); if (response.ToLower() == "noaccount") MessageBox.Show("No account exists with the email that your provided.", "Invalid Email", MessageBoxButtons.OK, MessageBoxIcon.Warning); else if (response.ToLower() == "invalid") MessageBox.Show("The email you provided was invalid.", "Invalid Email", MessageBoxButtons.OK, MessageBoxIcon.Warning); else if (response.ToLower() == "valid") { MessageBox.Show("An email has been sent to the email account we have in our database. It contains a link to a webpage you can reset your password at.", "Password Reset", MessageBoxButtons.OK, MessageBoxIcon.Information); DialogResult = DialogResult.OK; Close(); return; } else MessageBox.Show("Unexpected value returned from server. Please try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } DialogResult = DialogResult.Cancel; Close(); }
private void sortByLanguageMergeButton_Click(object sender, RoutedEventArgs e) { Thread progressThread = new Thread(new ThreadStart(progressTh)); progressThread.SetApartmentState(ApartmentState.STA); progressThread.IsBackground = true; progressThread.Start(); ex2 = engine.ExecuteFile(ex2FileAddr); database = ex2.sortByLangMergeSort(ex2DirAddTextBox.Text); System.Windows.Threading.Dispatcher.FromThread(progressThread).BeginInvoke(new Action(() => { progWindow.Close(); progWindow = null; } )); System.Windows.Threading.Dispatcher.FromThread(progressThread).InvokeShutdown(); }
private void btnInstallNow_Click(object sender, RoutedEventArgs e) { try { string localInstallerPath = App.AppTempPath + "Setup.exe"; var pw = new ProgressWindow("Please wait while the installer is being downloaded...\n" + _installerURL); pw.Show(); var webClient = new WebClient(); webClient.DownloadProgressChanged += delegate(object o, DownloadProgressChangedEventArgs args) { pw.SetProgressBarValue(args.ProgressPercentage); }; webClient.DownloadFileCompleted += delegate { pw.CanClose = true; pw.Close(); if ( MessageBox.Show( "NBA Stats Tracker will now close to install the latest version and then restart.\n\nAre you sure you want to continue?", "NBA Stats Tracker", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.Yes) != MessageBoxResult.Yes) { return; } string newUpdaterPath = App.AppTempPath + "\\Updater.exe"; try { File.Copy(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\Updater.exe", newUpdaterPath, true); } catch (Exception ex) { MessageBox.Show("Couldn't run the Updater. " + ex.Message); return; } Process.Start(newUpdaterPath, "\"" + localInstallerPath + "\""); Environment.Exit(0); }; webClient.DownloadFileAsync(new Uri(_installerURL), localInstallerPath); } catch (Exception ex) { MessageBox.Show("The changelog couldn't be downloaded at this time. Please try again later.\n\n" + ex.Message); } }
///<summary> /// /// Executes action. Called after Update, that set ActionPresentation.Enabled to true. /// ///</summary> /// ///<param name="context">DataContext</param> ///<param name="nextExecute">delegate to call</param> public void Execute(IDataContext context, DelegateExecute nextExecute) { IClass @class = context.GetData<IDeclaredElement>(JetBrains.ReSharper.DataConstants.DECLARED_ELEMENT) as IClass; ISolution solution = @class.GetManager().Solution; @class.GetManager().CommitAllDocuments(); Assert.CheckNotNull(@class); using (WriteLockCookie cookie = WriteLockCookie.Create()) { SearchInheritorsRequest request = new SearchInheritorsRequest(@class, SearchScope.SOLUTION, @class.GetManager().Solution); bool canceled = false; ICollection<IOccurence> occurences = null; using (ProgressWindow taskExecutor = new ProgressWindow(true)) { taskExecutor.ExecuteTask(delegate(IProgressIndicator progress) { occurences = request.Search(progress); return null; }, "", out canceled); } if (canceled) return; Assert.CheckNotNull(occurences); using (CommandCookie.Create("MarkSerializableDerivedTypes")) { PsiManager.GetInstance(solution).DoTransaction( delegate(object[] args) { foreach (IOccurence occurence in occurences) { DeclaredElementOccurence declaredElementOccurence = (DeclaredElementOccurence)occurence; IClass inheritClass = declaredElementOccurence.OccurenceElement.GetValidDeclaredElement() as IClass; if (inheritClass != null) AddAtribute(inheritClass); } }, new object[] { }); } } }
public override void Execute(object parameter) { var stream = GetOutputStream(); if (stream == null) return; var columns = model.Columns.Columns.ToList(); var collectionSource = model.Documents.Source; if (model.DocumentsHaveId) { columns.Insert(0, new ColumnDefinition() { Binding = "$JsonDocument:Key", Header = "Id" }); } var cts = new CancellationTokenSource(); var progressWindow = new ProgressWindow() { Title = "Exporting Report"}; progressWindow.Closed += delegate { cts.Cancel(); }; var exporter = new Exporter(stream, collectionSource, columns); var exportTask = exporter.ExportAsync(cts.Token, progress => progressWindow.Progress = progress) .ContinueOnUIThread(t => { // there's a bug in silverlight where if a ChildWindow gets closed too soon after it's opened, it leaves the UI // disabled; so delay closing the window by a few milliseconds TaskEx.Delay(TimeSpan.FromMilliseconds(350)) .ContinueOnSuccessInTheUIThread(progressWindow.Close); if (t.IsFaulted) { ApplicationModel.Current.AddErrorNotification(t.Exception, "Exporting Report Failed"); } else if (!t.IsCanceled) { ApplicationModel.Current.AddInfoNotification("Report Exported Successfully"); } }); progressWindow.Show(); }
/// <summary> /// Exports the selected files for the selected platforms /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void mExportButton_Click(object sender, EventArgs e) { mExporter = new ImporterExporter(); ArrayList list = new ArrayList(); foreach (object obj in mFilesListBox.CheckedItems) list.Add(obj); // The Progress Window kicks off a thread that will individually process // each of our items. ProgressWindow progressWindow = new ProgressWindow(); progressWindow.ObjectList = list; progressWindow.ProcessObjectDelegate = new ProgressWindow.ObjectDelegate(ProcessFileExport); progressWindow.OnProgressComplete += new ProgressWindow.ProgressDelegate(progressWindow_OnProgressComplete); DialogResult result = progressWindow.ShowDialog(); this.Close(); }
private void openDemoToolStripMenuItem_Click(object sender, EventArgs e) { DialogResult r = openDemoDialog.ShowDialog(); if (r == DialogResult.OK) { demo = Plugin.GetPlugin<IDemo>(openDemoDialog.FileName); if (demo == null) { MessageBox.Show("Could not find an IDemo in that assembly. :(", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } demo.Init(demoSplit.Panel1.Handle); ProgressWindow progressWindow = new ProgressWindow("Loading demo"); progressWindow.Show(this); demo.Load(progressWindow); progressWindow.Hide(); } }
private Point windowOffset = new Point(16, 70); // window padding to add to previewWindow #endregion Fields #region Constructors public NyaaSnapMain() { self = this; InitializeComponent(); UpMan = new UploadManager(); progressWindow = new ProgressWindow(); saveAction = "Save to file"; BTT_Save.Text = saveAction; CM_FileDests.Items.Add(saveAction); foreach (string ety in UpMan.GetUploaders()) CM_FileDests.Items.Add(ety); SetCaptureDims(); if (MessageBox.Show("Temporaly set the window style to basic? \nBasic will improve the capture preformance by a whole lot so please say yes.", "Enable Windows Aero Basic?", MessageBoxButtons.YesNo) == DialogResult.Yes) DwmEnableComposition(DWM_EC_DISABLECOMPOSITION); }
/// <summary> /// Starts the download process /// </summary> /// <param name="item">the appcast item to download</param> private void InitDownloadAndInstallProcess(NetSparkleAppCastItem item) { // get the filename of the download lin string[] segments = item.DownloadLink.Split('/'); string fileName = segments[segments.Length - 1]; // get temp path _downloadTempFileName = Environment.ExpandEnvironmentVariables("%temp%\\" + fileName); if (ProgressWindow == null) { ProgressWindow = UIFactory.CreateProgressWindow(item, _applicationIcon); } else { ProgressWindow.InstallAndRelaunch -= OnProgressWindowInstallAndRelaunch; } ProgressWindow.InstallAndRelaunch += OnProgressWindowInstallAndRelaunch; // set up the download client // start async download if (_webDownloadClient != null) { _webDownloadClient.DownloadProgressChanged -= ProgressWindow.OnClientDownloadProgressChanged; _webDownloadClient.DownloadFileCompleted -= OnWebDownloadClientDownloadFileCompleted; _webDownloadClient = null; } _webDownloadClient = new WebClient { UseDefaultCredentials = true }; _webDownloadClient.DownloadProgressChanged += ProgressWindow.OnClientDownloadProgressChanged; _webDownloadClient.DownloadFileCompleted += OnWebDownloadClientDownloadFileCompleted; Uri url = new Uri(item.DownloadLink); _webDownloadClient.DownloadFileAsync(url, _downloadTempFileName); ProgressWindow.ShowDialog(); }
private static bool RunLocally() { if (!File.Exists(DisconnectedClient.DatabaseFile) && !File.Exists(DisconnectedClient.DownloadBackupFile)) { return(false); } if (!SelectorWindow.ShowDialog( EnumExtensions.GetValues <StartOption>(), out StartOption result, elementIcon: so => SouthwindImageLoader.GetImageSortName(so == StartOption.RunLocally ? "local.png" : "server.png"), elementText: so => so.NiceToString(), title: "Startup mode", message: "A local database has been found on your system.\r\nWhat you want to do?")) { Environment.Exit(0); } if (result == StartOption.RunLocally) { if (File.Exists(DisconnectedClient.DownloadBackupFile)) { ProgressWindow.Wait("Waiting", "Restoring database...", () => { LocalServer.RestoreDatabase( Settings.Default.LocalDatabaseConnectionString, DisconnectedClient.DownloadBackupFile, DisconnectedClient.DatabaseFile, DisconnectedClient.DatabaseLogFile); File.Delete(DisconnectedClient.DownloadBackupFile); }); } return(true); } else { return(false); } }//RunLocally
private async void Potvrdi_Click(object sender, RoutedEventArgs e) { var dataProvider = new EFCoreDataProvider(); // Dodavanje podataka za trenutni projekat ZapocetiProjekat.DatumPocetka = dpDatumPocetkaProjekta.DisplayDate.ToShortDateString(); ZapocetiProjekat.StanjeProjekta = "Aktivan"; // Kreiranje i prikazivanje progress windowa var progressWindow = new ProgressWindow("Kreiranje projekta u toku..."); progressWindow.Show(); // U bazi se kreira novi projekat i za njega se kreiraju odgovarajuca dokumenta var listaDokumenata = GetListuDokumenata(ZapocetiProjekat.VrstaProjekta); await dataProvider.KreirajProjekatIDodajDokumenta(ZapocetiProjekat, listaDokumenata); // Unose se generalni troskovi - neka default vrednosti, 1 uplata, ukupnonovca = 100 await dataProvider.AddGeneralniTrosakAsync(new GeneralniTrosak { IDProjekta = ZapocetiProjekat.IDProjekta, BrojUplata = 1, Procenti = "100", UkupnoNovca = 100 }); // TODO: Ovde mogu i ostali atributi informaicje o lokaciji da se unose if (informacijaOLokaciji != null) // Ako je vec uneta informacija o lokaciji onda se ona pamti u bazi pri kreiranju projekta { await dataProvider.AddPDFAsync(new PDF { IDDokumenta = listaDokumenata[0].IDDokumenta, PDFFajl = informacijaOLokaciji }, Helper.TrenutniKorisnik); } // Zatvaranja ProgressWindow-a progressWindow.Close(); // Prelazak na ClanoviProjektaPage var parent = (Parent as MainWindow); Helper.TrenutniProjekat = ZapocetiProjekat; parent.Content = new ClanoviProjektaPage(); }
private void VerifyPreset(CameraPreset preset) { if (preset == null) { return; } var dlg = new ProgressWindow(); dlg.Show(); try { int i = 0; dlg.MaxValue = ServiceProvider.DeviceManager.ConnectedDevices.Count; foreach (ICameraDevice connectedDevice in ServiceProvider.DeviceManager.ConnectedDevices) { if (connectedDevice == null || !connectedDevice.IsConnected) { continue; } try { dlg.Label = connectedDevice.DisplayName; dlg.Progress = i; i++; preset.Verify(connectedDevice); } catch (Exception exception) { Log.Error("Unable to set property ", exception); } Thread.Sleep(250); } } catch (Exception exception) { Log.Error("Unable to set property ", exception); } dlg.Hide(); }
public ProgressDialog(Window parentWindow, string title, string text, int maxProgress = 0) { _cancellationTokenSource = new CancellationTokenSource(); _progressAccumulator = new ProgressAccumulator(i => _viewModel.Progress = i); _maxProgress = new Progress <int>(i => _viewModel.MaxProgress = i); _viewModel = new ProgressWindowViewModel { Title = title, Text = text, Progress = 0, MaxProgress = maxProgress, ShowProgressNumber = true, }; _window = new ProgressWindow { DataContext = _viewModel, Owner = parentWindow }; _window.Closed += WindowOnClosed; }
public void Run(int sypuchIndex, bool fixedMass) { _isFixedMass = fixedMass; GoodMeltsQuant = 0; try { // TODO: Params.SelectedPlant должно начинаться с 1. LoadFromCountData(Params.SelectedPlant); LoadFromLoose(sypuchIndex); LoadMixAndOstShl(); DetectBaseLenth(); var longOperation = new ProgressWindow { MaximumProgress = BaseLenth }; longOperation.Run(this); if (GoodMeltsQuant >= 10) { AdaptResultsSave(); MessageBox.Show( string.Format("Адаптация системы расчета шихты успешно проведена. Использованы данные '{0}' плавок", GoodMeltsQuant), "Адаптация завершена"); } else { MessageBox.Show( "Адаптация системы НЕ ПРОВЕДЕНА из-за неполноты или некорректности исходных данных. Результаты расчета по плавкам сохранены", "Внимание"); } } catch (Exception ex) { MessageBox.Show(ex.ToString(), "Exception", MessageBoxButton.OK, MessageBoxImage.Error); } }
public static void SaveAs(LibertyV window) { string result = GUI.FileSaveSelection(Path.GetFileName(window.File.Filename)); if (result == null) { return; } FileStream file = null; try { file = System.IO.File.Create(result); } catch (IOException ex) { MessageBox.Show(ex.Message, "Failed to open file for writing", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } ProgressWindow progress = new ProgressWindow("Saving", update => window.File.Write(file, update), true); try { progress.Run(); } catch (OperationCanceledException) { // delete the file file.Close(); System.IO.File.Delete(result); MessageBox.Show("Operation canceled."); return; } // Now open this file file.Seek(0, SeekOrigin.Begin); window.LoadRPF(new RPF7File(file, Path.GetFileName(result), result), true); }
private void Prepare() { var directory = Directory.CreateDirectory(AppPaths.AppPath); musicLoader = new MusicLoader(directory.FullName, tokenID, userID); DependencyUtility.RegisterInstance(musicLoader); DependencyUtility.RegisterType <MusicPlayer>(); DependencyUtility.RegisterInstance(new AutorunHelper(System.Reflection.Assembly.GetExecutingAssembly().Location)); var progressWindow = new ProgressWindow("Синхронизация", musicLoader); progressWindow.Show(); musicWorker = DependencyUtility.Resolve <TrackList>(); musicPlayer = DependencyUtility.Resolve <MusicPlayer>(); musicLoader.LoadAsync().ContinueWith((t) => Dispatcher.Invoke(firstSynchronizationCompleted)); var settingsWindow = new SettingsWindow(); fastTimer.Tick += (s, e) => { if (!mutexShow.WaitOne(0, true)) { musicPlayer.InvokeShow(); } else { mutexShow.ReleaseMutex(); } }; }
public static async Task <List <ModInfo> > FetchMods(Window progressOwner, ModCollection installedMods) { var progressWindow = new ProgressWindow() { Owner = progressOwner }; var progressViewModel = (ProgressViewModel)progressWindow.ViewModel; progressViewModel.ActionName = App.Instance.GetLocalizedResourceString("FetchingModsAction"); progressViewModel.CanCancel = false; progressViewModel.IsIndeterminate = true; Task <List <ModInfo> > fetchModsTask = ModWebsite.GetModsAsync(installedMods); Task closeWindowTask = fetchModsTask.ContinueWith(t => progressWindow.Dispatcher.Invoke(progressWindow.Close)); progressWindow.ShowDialog(); List <ModInfo> modInfos = await fetchModsTask; await closeWindowTask; return(modInfos); }
public JobWorker(MainForm mf) { mainForm = mf; InitializeComponent(); Util.SetSize(this, MeGUI.Properties.Settings.Default.JobWorkerSize, MeGUI.Properties.Settings.Default.JobWorkerWindowState); jobQueue1.SetStartStopButtonsTogether(); jobQueue1.RequestJobDeleted = new RequestJobDeleted(GUIDeleteJob); jobQueue1.AddMenuItem("Return to main job queue", null, delegate(List <TaggedJob> jobs) { foreach (TaggedJob j in jobs) { mainForm.Jobs.ReleaseJob(j); } }); pw = new ProgressWindow(JobTypes.AUDIO); // pw.WindowClosed += new WindowClosedCallback(pw_WindowClosed); pw.Abort += new AbortCallback(pw_Abort); // pw.setPriority(job.Priority); pw.PriorityChanged += new PriorityChangedCallback(pw_PriorityChanged); pw.CreateControl(); mainForm.RegisterForm(pw); }
public static void OpenAsynchroneStatisticsPage(ChartsListFormViewModel chartsListFormViewModel) { Action <string, string> exec = (s, s1) => { chartsListFormViewModel.ChartsDtoList = StatistiquesBLL.Current.GetChartsDtoList(); }; var progressWindow = new ProgressWindow(); progressWindow.SetTitle("Chargement en cours"); var backgroundWorker = new BackgroundWorker(); // set the worker to call your long-running method backgroundWorker.DoWork += (object sender2, DoWorkEventArgs e) => { exec.Invoke("path", "parameters"); }; // set the worker to close your progress form when it's completed backgroundWorker.RunWorkerCompleted += (object sender2, RunWorkerCompletedEventArgs e) => { progressWindow.Close(); }; progressWindow.Show(); backgroundWorker.RunWorkerAsync(); }
private void Compute() { // build imposition solutions impositionTool = ImpositionTool.Instantiate(Factory, ImpSettings); // -> margins impositionTool.SpaceBetween = ImpSpace; impositionTool.Margin = ImpMargin; impositionTool.MinMargin = ImpRemainingMargin; impositionTool.HorizontalAlignment = HorizontalAlignment; impositionTool.VerticalAlignment = VerticalAlignment; // -> patterns impositionTool.AllowRotationInColumns = AllowColumnRotation; impositionTool.AllowRotationInRows = AllowRowRotation; impositionTool.AllowBothDirection = AllowBothDirection; // -> offset impositionTool.ImpositionOffset = Offset; try { // instantiate ProgressWindow and launch process ProgressWindow progress = new ProgressWindow(); System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(GenerateImpositionSolutions), progress); progress.ShowDialog(); LoadSolutions(); } catch (PicToolTooLongException /*ex*/) { MessageBox.Show( string.Format(Properties.Resources.ID_ABANDONPROCESSING, PicToolArea.MaxNoSegments) , Application.ProductName , MessageBoxButtons.OK); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }
/// <summary> /// Evento para validar los documentos listados que falten realizar el proceso /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnValidarArchivos_Click(object sender, RoutedEventArgs e) { if (lista_reporte.Count > 0) { verificarDocs = true; int count = 0; //obtener todos los docs sin validar y por cada uno reload la pagina docsValidados = 0; foreach (var item in lista_reporte) { if (item.EstadoValidar == "4") { count++; } } if (count > 0) { string resultado = string.Empty; ProgressDialogResult result = ProgressWindow.Execute(VentanaPrincipal, "Procesando...", () => { resultado = validarDocs(); }); liberarVariableConsulta(); } verificarDocs = false; lblValidaron.Content = "Se validaron " + docsValidados + " documentos de " + count; cs_pxCargarDgvComprobanteselectronicos(); } else { System.Windows.Forms.MessageBox.Show("No existen documentos a validar.", "Advertencia", MessageBoxButtons.OK, MessageBoxIcon.Warning); } // btnGrabar.IsEnabled = true; // btnExportar.IsEnabled = true; }
private void btnRestauracionUnico_Click(object sender, RoutedEventArgs e) { if (txtRutaUnico.Text.Trim().Length > 0) { string rutaArchivo = txtRutaUnico.Text; clsEntityDatabaseLocal local = new clsEntityDatabaseLocal().cs_fxObtenerUnoPorDeclaranteId(declarante.Cs_pr_Declarant_Id); //clsBaseConexion cn = new clsBaseConexion(); string cadenaServidor = local.cs_prConexioncadenaservidor(); clsBaseLog.cs_pxRegistarAdd(cadenaServidor); string resultado = string.Empty; ProgressDialogResult result = ProgressWindow.Execute(VentanaPrincipal, "Procesando...", () => { resultado = restaurarUnico(local, cadenaServidor, rutaArchivo); }); if (resultado.Trim().Length <= 0) { System.Windows.Forms.MessageBox.Show("El backup se ha restaurado correctamente.\n", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { // System.Windows.Forms.MessageBox.Show("Se ha producido un error al procesar el backup.\n", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); CustomDialogWindow obj = new CustomDialogWindow(); obj.AdditionalDetailsText = resultado; obj.Buttons = CustomDialogButtons.OK; obj.Caption = "Mensaje"; obj.DefaultButton = CustomDialogResults.OK; obj.InstructionHeading = "Restauración fallida."; obj.InstructionIcon = CustomDialogIcons.Warning; obj.InstructionText = "Se ha producido un error al procesar el backup. Revise los detalles para mayor información"; CustomDialogResults objResults = obj.Show(); } } else { System.Windows.Forms.MessageBox.Show("Seleccione un archivo para restaurar el backup", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Warning); } }
private void btnConvert_Click(object sender, RoutedEventArgs e) { MessageBoxResult _result = MessageBox.Show( "Files will be overrwritten.", "Convertation JSD to JSD-HD", MessageBoxButton.OKCancel); if (_result != MessageBoxResult.OK) { return; } ProgressHolder _ph = new ProgressHolder(); _ph.IsCancelable = true; ProgressWindow.Run(_ph); int _filesCount = 0; try { foreach (string _fileName in this.FFileNames) { if (_ph.Progress < 0) { break; } JsdFile.ConvertJsdFileToHighDefinition(_fileName); _filesCount++; _ph.Progress = 100 * _filesCount / this.FFileNames.Length; } } finally { _ph.Progress = -1; } }
public void Reload() { if (this.ViewModel == null) { return; } if (this.mgShape == null) { this.mgShape = new Model3DGroup(); } this.mgShape.Children.Clear(); this.FLayers = new List <GeometryModel3D> [this.ViewModel.DrewLayers.Length]; for (int i = 0; i < this.FLayers.Length; i++) { this.FLayers[i] = new List <GeometryModel3D>(); } this.FPh = new ProgressHolder(); this.FPh.IsCancelable = true; try { ProgressWindow.Run(this.FPh); this.BuildMap(); } finally { this.FPh.Progress = -1; } CreateLandSurface(); this.SetTransparentAll(false); }
private void OpenThermalSequenceCommandExecute() { string pathToFile = null; string pathToLicences = ApplicationViewModel.LicenseFilesFolder; using (OpenFileDialog dlg = new OpenFileDialog()) { dlg.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); DialogResult result = dlg.ShowDialog(); if (result == System.Windows.Forms.DialogResult.OK) { pathToFile = dlg.FileName; try { thermalSequencePlayer = new ThermalSequencePlayer(pathToFile, pathToLicences); } catch (Exception e) { string messageBoxText = e.Message; string caption = "Warning"; MessageBoxButton button = MessageBoxButton.OK; MessageBoxImage icon = MessageBoxImage.Warning; System.Windows.MessageBox.Show(messageBoxText, caption, button, icon); } thermalSequencePlayer.RecalculationCompleted += thermalSequencePlayer_RecalculationCompleted; if (thermalSequencePlayer.IsRadiometricSequence && !thermalSequencePlayer.IsRadiometrisSequenceRecalculated) { ProgressWindow.OpenWindow("Recalculating sequence", "Recalculating..."); } RaiseInit(); RaiseParameters(); RaiseImage(); } } }
public void ShowError(Exception ex) { if (ex is NuGetResolverConstraintException || ex is PackageAlreadyInstalledException || ex is NuGetVersionNotSatisfiedException || ex is FrameworkException || ex is PackagingException || ex is InvalidOperationException) { // for exceptions that are known to be normal error cases, just // display the message. ProgressWindow.Log(ProjectManagement.MessageLevel.Info, ex.Message); // write to activity log var message = string.Format(CultureInfo.CurrentCulture, ex.ToString()); ActivityLog.LogError(LogEntrySource, message); } else { ProgressWindow.Log(ProjectManagement.MessageLevel.Error, ex.ToString()); } ProgressWindow.ReportError(ex.Message); }
public static void ExportAWC(FileEntry entry) { string selectedFolder = GUI.FolderSelection(); if (selectedFolder != null) { try { using (AWCFile awc = new AWCFile(entry.Data.GetStream())) { ProgressWindow progress = new ProgressWindow("Exporting", report => awc.ExportWav(Path.Combine(selectedFolder, entry.Name), report), true); progress.Run(); } } catch (OperationCanceledException) { MessageBox.Show("Operation canceled."); } catch (Exception) { MessageBox.Show("Failed to open AWC, please report to the developer"); } } }
protected override void SaveWorkerRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { if (Global.ShowQuestion(this)) { var count = PropsService.CountOfNotNotifiable() + MaterialsService.CountOfNotNotifiable(); var progressWindow = new ProgressWindow(count); progressWindow.Show(this); foreach (var propID in PropsService.GetAllNotNotifiables()) { PropsService.ChangeNotifiable(propID, true); progressWindow.IncreaseProgress(); } foreach (var materialID in MaterialsService.GetAllNotNotifiables()) { MaterialsService.ChangeNotifiable(materialID, true); progressWindow.IncreaseProgress(); } progressWindow.Close(); Global.ShowSuceeded(this); TryToLoad(); } aiLoader.Visibility = Visibility.Collapsed; OnSaving = false; }
public static int Compact(VoidPtr srcAddr, int srcLen, Stream outStream, ResourceNode r) { using (ProgressWindow prog = new ProgressWindow(r.RootNode._mainForm, "Huffman", String.Format("Compressing {0}, please wait...", r.Name), false)) return(new Huffman().Compress(srcAddr, srcLen, outStream, prog)); }
public static void SaveToFile(IWin32Window owner) { SaveFileDialog sfd = new SaveFileDialog(); // HTML Files (*.htm;*.html)|*.htm;*.html sfd.Filter = "Process Hacker Dump Files (*.phi)|*.phi|Text Files (*.txt;*.log)|*.txt;*.log|" + "Comma-separated values (*.csv)|*.csv|All Files (*.*)|*.*"; //if (Program.HackerWindow.SelectedPid == -1) //{ // sfd.FileName = "Process List.txt"; //} //else //{ // string processName = Windows.GetProcessName(Program.HackerWindow.SelectedPid); // if (processName != null) // sfd.FileName = processName + ".txt"; // else // sfd.FileName = "Process Info.txt"; //} sfd.FileName = "phdump-" + DateTime.Now.ToString("ddMMyy") + ".phi"; if (sfd.ShowDialog() == DialogResult.OK) { FileInfo fi = new FileInfo(sfd.FileName); string ext = fi.Extension.ToLowerInvariant(); if (ext == ".phi") { ThreadTask dumpTask = new ThreadTask(); dumpTask.RunTask += delegate(object result, ref object param) { var mfs = Dump.BeginDump(fi.FullName, ProcessHacker.Native.Mfs.MfsOpenMode.OverwriteIf); Dump.DumpProcesses(mfs, Program.ProcessProvider); Dump.DumpServices(mfs); mfs.Dispose(); }; ProgressWindow progressWindow = new ProgressWindow(); progressWindow.CloseButtonVisible = false; progressWindow.ProgressBarStyle = ProgressBarStyle.Marquee; progressWindow.ProgressText = "Creating the dump file..."; dumpTask.Completed += (result) => { progressWindow.SetCompleted(); if (progressWindow.IsHandleCreated) progressWindow.BeginInvoke(new MethodInvoker(progressWindow.Close)); }; dumpTask.Start(); if (dumpTask.Running) progressWindow.ShowDialog(owner); if (dumpTask.Exception != null) PhUtils.ShowException("Unable to create the dump file", dumpTask.Exception); return; } try { using (StreamWriter sw = new StreamWriter(fi.FullName)) { Program.HackerWindow.ProcessTree.Tree.ExpandAll(); if (ext == ".htm" || ext == ".html") { } else if (ext == ".csv") { sw.Write(GetProcessTreeText(false)); } else { sw.Write(GetEnvironmentInfo()); sw.WriteLine(); sw.Write(GetProcessTreeText(true)); sw.WriteLine(); if (Program.HackerWindow.SelectedPid != -1) { sw.Write(GetProcessDetailsText(Program.HackerWindow.SelectedPid)); sw.WriteLine(); } } } } catch (IOException ex) { PhUtils.ShowException("Unable to save the process list", ex); } } }
private void CreateConnection_Click(object sender, RoutedEventArgs e) { DtoDivision model = GetConnectionsModel(); if (model == null) { return; } bool hasValues = GetElementAssemblies(false); if (!hasValues) { MessageBoxHelper.ShowInformation("Please create the objects first.", _parentWindow); return; } string propertyName = "ConnectionChild-Element"; ProgressWindow.Text = "Create connections."; ProgressWindow.Show(); bool hideProgressWindow = true; try { DtoCsgTree csgTree = new DtoCsgTree { Color = (uint)Color.LightSteelBlue.ToArgb() }; csgTree.Elements.Add(new Path { Rotation = 0, Geometry = new List <CsgGeoElement> { new StartPolygon { Point = new List <double> { 0, 300, 6.5 } }, new Line { Point = new List <double> { 0, 300, 15.5 } }, } }); csgTree.Elements.Add(new OuterContour { Rotation = 0, Geometry = new List <CsgGeoElement> { new StartPolygon { Point = new List <double> { 0, -40 } }, new Line { Point = new List <double> { 290, -40 } }, new Line { Point = new List <double> { 290, -550 } }, new Line { Point = new List <double> { 0, -550 } }, new Line { Point = new List <double> { 0.0, -40 } }, } }); SteelPlate Slab = new SteelPlate { Name = "Slab", Parent = model.TopologyDivisionId, Division = model.Id, LogParentID = _integrationBase.CurrentProject.Id, CsgTree = csgTree }; Slab.AddProperty(TableNames.tabAttribConstObjInstObj, propertyName, _bar0); DtoCsgTree rectangle = new DtoCsgTree { Color = (uint)Color.IndianRed.ToArgb() }; rectangle.Elements.Add(new Path { Rotation = 0, Geometry = new List <CsgGeoElement> { new StartPolygon { Point = new List <double> { 40, 300.0, 15.5 } }, new Line { Point = new List <double> { 550, 300.0, 15.5 } } } }); rectangle.Elements.Add(new OuterContour { Rotation = 0, Geometry = new List <CsgGeoElement> { new StartPolygon { Point = new List <double> { 20, 0.0 } }, new Line { Point = new List <double> { 0.0, 0.0 } }, new Line { Point = new List <double> { 0, 10 } }, new Line { Point = new List <double> { 20, 0.0 } } } }); Weld Weld_1 = new Weld { Name = "Weld_1", Parent = model.TopologyDivisionId, Division = model.Id, LogParentID = _integrationBase.CurrentProject.Id, CsgTree = rectangle }; Weld_1.AddProperty(TableNames.tabAttribConstObjInstObj, propertyName, _bar0); Weld Weld_2 = new Weld { Name = "Weld_2", Parent = model.TopologyDivisionId, Division = model.Id, LogParentID = _integrationBase.CurrentProject.Id, CsgTree = rectangle }; TmpMatrix matrix = new TmpMatrix { Values = new[] { 1, 0.0, 0.0, 0.0, 0.0, 1, 0.0, 0.0, 0.0, 0.0, -1, 9, //-10 0.0, 0.0, 0.0, 1 } }; Weld_2.AddProperty(TableNames.tabAttribConstObjInstObj, propertyName, _bar0); Weld_2.AddProperty("element", "matrix", matrix); DtoCsgTree cabin = new DtoCsgTree { Color = (uint)Color.DarkBlue.ToArgb() }; cabin.Elements.Add(new Path { Rotation = 0, Geometry = new List <CsgGeoElement> { new StartPolygon { Point = new List <double> { 0, 300, 30 } }, new Line { Point = new List <double> { 0, 300, 40 } }, } }); cabin.Elements.Add(new OuterContour { Rotation = 0, Geometry = new List <CsgGeoElement> { new StartPolygon { Point = new List <double> { 0.0, -10.0 } }, new Line { Point = new List <double> { 8.666, -5 } }, new Line { Point = new List <double> { 8.666, 5 } }, new Line { Point = new List <double> { 0.0, 10 } }, new Line { Point = new List <double> { -8.666, 5 } }, new Line { Point = new List <double> { -8.666, -5 } }, new Line { Point = new List <double> { 0.0, -10 } } } }); DtoCsgTree CircularTree = new DtoCsgTree { Color = (uint)Color.Gray.ToArgb() }; CircularTree.Elements.Add(new Path { Rotation = 0, Geometry = new List <CsgGeoElement> { new StartPolygon { Point = new List <double> { 0, 300, -20 } }, new Line { Point = new List <double> { 0, 300, 30 } } }, CrossSection = "RD8" }); ChildGeometryObject Cabin1 = new ChildGeometryObject { Name = "Cabin1", Parent = model.TopologyDivisionId, Division = model.Id, CsgTree = cabin }; TmpMatrix matrix1 = new TmpMatrix { Values = new[] { 1, 0.0, 0.0, 100.0, 0.0, 1, 0.0, 200.0, 0.0, 0.0, 1, 0.0, 0.0, 0.0, 0.0, 1 } }; Cabin1.AddProperty("element", "matrix", matrix1); ChildGeometryObject Circular1 = new ChildGeometryObject { Name = "Circular1", Parent = model.TopologyDivisionId, Division = model.Id, CsgTree = CircularTree }; Circular1.AddProperty("element", "matrix", matrix1); MechanicalFastener Screw_1 = new MechanicalFastener { Name = "Screw_1", Parent = model.TopologyDivisionId, Division = model.Id, LogParentID = _integrationBase.CurrentProject.Id, }; Screw_1.Children = new List <DtObject> { Cabin1, Circular1 }; ChildGeometryObject Cabin2 = new ChildGeometryObject { Name = "Cabin2", Parent = model.TopologyDivisionId, Division = model.Id, CsgTree = cabin }; TmpMatrix matrix2 = new TmpMatrix { Values = new[] { 1, 0.0, 0.0, 500, 0.0, 1, 0.0, 100.0, 0.0, 0.0, 1, 0.0, 0.0, 0.0, 0.0, 1 } }; Cabin2.AddProperty("element", "matrix", matrix2); ChildGeometryObject Circular2 = new ChildGeometryObject { Name = "Circular2", Parent = model.TopologyDivisionId, Division = model.Id, CsgTree = CircularTree }; Circular2.AddProperty("element", "matrix", matrix2); MechanicalFastener Screw_2 = new MechanicalFastener { Name = "Screw_2", Parent = model.TopologyDivisionId, Division = model.Id, LogParentID = _integrationBase.CurrentProject.Id, }; Screw_2.Children = new List <DtObject> { Cabin2, Circular2 }; ChildGeometryObject Cabin3 = new ChildGeometryObject { Name = "Cabin3", Parent = model.TopologyDivisionId, Division = model.Id, CsgTree = cabin }; TmpMatrix matrix3 = new TmpMatrix { Values = new[] { 1, 0.0, 0.0, 100, 0.0, 1, 0.0, 100, 0.0, 0.0, 1, 0.0, 0.0, 0.0, 0.0, 1 } }; Cabin3.AddProperty("element", "matrix", matrix3); ChildGeometryObject Circular_3 = new ChildGeometryObject { Name = "Circular_3", Parent = model.TopologyDivisionId, Division = model.Id, CsgTree = CircularTree }; Circular_3.AddProperty("element", "matrix", matrix3); MechanicalFastener Screw_3 = new MechanicalFastener { Name = "Screw_3", Parent = model.TopologyDivisionId, Division = model.Id, LogParentID = _integrationBase.CurrentProject.Id, }; Screw_3.Children = new List <DtObject> { Cabin3, Circular_3 }; ChildGeometryObject Cabin4 = new ChildGeometryObject { Name = "Cabin4", Parent = model.TopologyDivisionId, Division = model.Id, CsgTree = cabin }; TmpMatrix matrix4 = new TmpMatrix { Values = new[] { 1, 0.0, 0.0, 500, 0.0, 1, 0.0, 200, 0.0, 0.0, 1, 0.0, 0.0, 0.0, 0.0, 1 } }; Cabin4.AddProperty("element", "matrix", matrix4); ChildGeometryObject Circular_4 = new ChildGeometryObject { Name = "Circular_4", Parent = model.TopologyDivisionId, Division = model.Id, CsgTree = CircularTree }; Circular_4.AddProperty("element", "matrix", matrix4); MechanicalFastener Screw_4 = new MechanicalFastener { Name = "Screw_4", Parent = model.TopologyDivisionId, Division = model.Id, LogParentID = _integrationBase.CurrentProject.Id, }; Screw_4.Children = new List <DtObject> { Cabin4, Circular_4 }; DtoCsgTree Hole = new DtoCsgTree { Color = (uint)Color.Gray.ToArgb() }; Hole.Elements.Add(new Path { Rotation = 0, Geometry = new List <CsgGeoElement> { new StartPolygon { Point = new List <double> { 0, 300, -100 } }, new Line { Point = new List <double> { 0, 300, 200 } } }, CrossSection = "RD8" }); Opening Hole_1 = new Opening { Name = "Hole_1", Parent = model.TopologyDivisionId, Division = model.Id, LogParentID = _integrationBase.CurrentProject.Id, CsgTree = Hole }; Hole_1.AddProperty("element", "matrix", matrix1); Opening Hole_2 = new Opening { Name = "Hole_2", Parent = model.TopologyDivisionId, Division = model.Id, LogParentID = _integrationBase.CurrentProject.Id, CsgTree = Hole }; Hole_2.AddProperty("element", "matrix", matrix2); Opening Hole_3 = new Opening { Name = "Hole_3", Parent = model.TopologyDivisionId, Division = model.Id, LogParentID = _integrationBase.CurrentProject.Id, CsgTree = Hole }; Hole_3.AddProperty("element", "matrix", matrix3); Opening Hole_4 = new Opening { Name = "Hole_4", Parent = model.TopologyDivisionId, Division = model.Id, LogParentID = _integrationBase.CurrentProject.Id, CsgTree = Hole }; Hole_4.AddProperty("element", "matrix", matrix4); DtoConnections connections = new DtoConnections { ConnectionElement = new ConnectionElement(), ElementIds = new List <Guid>() }; connections.ConnectionElement.Name = _connectionElementName; connections.ConnectionElement.Description = "Connection_Part_Of_Test"; connections.ElementIds.Add(_bar0.Id); connections.ElementIds.Add(_bar1.Id); connections.ConnectionElement.Children = new List <DtObject> { Slab, Weld_1, Weld_2, Screw_1, Screw_2, Screw_3, Screw_4, Hole_1, Hole_2, Hole_3, Hole_4 }; _savedDtoConnections = _integrationBase.ApiCore.DtoConnection.CreateConnection(_integrationBase.CurrentProject.Id, connections); if (_savedDtoConnections == null) { MessageBoxHelper.ShowInformation("DtoConnections could not be generated.", _parentWindow); } else { _savedDtoConnectionsId = _savedDtoConnections.Id; _integrationBase.ApiCore.Projects.ConvertGeometry(model.ProjectId); hideProgressWindow = false; NavigateToControl(); CreateConnection.IsEnabled = false; DeleteConnection.IsEnabled = true; } } finally { if (hideProgressWindow) { ProgressWindow.Hide(); } } }
private void CreateObjects_Click(object sender, RoutedEventArgs e) { DtoDivision model = GetConnectionsModel(); if (model == null) { return; } bool hasValues = GetElementAssemblies(false); if (hasValues) { MessageBoxHelper.ShowInformation("ElementAssemblies are already created.", _parentWindow); return; } ProgressWindow.Text = "Create objects."; ProgressWindow.Show(); bool hideProgressWindow = true; try { // Create a horizontal steel column by using Path with reference to IPE600. DtoCsgTree csg = new DtoCsgTree { Color = (uint)Color.Gray.ToArgb() }; csg.Elements.Add(new Path { Rotation = Math.PI / 2, Geometry = new List <CsgGeoElement> { new StartPolygon { Point = new List <double> { 0, 0, 0 } }, new Line { Point = new List <double> { 1500, 0, 0 } } }, CrossSection = "IPE600" }); ElementAssembly bar0 = new ElementAssembly { Name = _bar0Name, Parent = model.TopologyDivisionId, Division = model.Id, LogParentID = _integrationBase.CurrentProject.Id, CsgTree = csg }; // Test string jsonString = JsonConvert.SerializeObject(bar0); // Post object to Bimplus. _bar0 = _integrationBase.ApiCore.DtObjects.PostObject(bar0) as ElementAssembly; DtoCsgTree csg2 = new DtoCsgTree { Color = (uint)Color.Gray.ToArgb() }; csg2.Elements.Add(new Path { Rotation = Math.PI / 2, OffsetY = -300, Geometry = new List <CsgGeoElement> { new StartPolygon { Point = new List <double> { 0.0, 310, 0 } }, new Line { Point = new List <double> { 0.0, 1810, 0 } } }, CrossSection = "IPE600" }); ElementAssembly bar1 = new ElementAssembly { Name = _bar1Name, Parent = model.TopologyDivisionId, Division = model.Id, LogParentID = _integrationBase.CurrentProject.Id, CsgTree = csg2 }; // Test jsonString = JsonConvert.SerializeObject(bar1); // Post object to Bimplus. _bar1 = _integrationBase.ApiCore.DtObjects.PostObject(bar1) as ElementAssembly; if (_bar0 == null || _bar1 == null) { MessageBoxHelper.ShowInformation("Not all objects could be created.", _parentWindow); } else { _integrationBase.ApiCore.Projects.ConvertGeometry(model.ProjectId); hideProgressWindow = false; NavigateToControl(); DeleteModelAndObject.IsEnabled = true; } } finally { if (hideProgressWindow) { ProgressWindow.Hide(); } } }
/// <summary> /// This function displays a processing and display of progress with RuProgressBar /// </summary> public void RunProgress() { try { // Init ProgressBar ProgressWindow progress = new ProgressWindow(); progress.Text = "Copying Files..."; // Run Application with ProgressBar System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(Copy), progress); progress.ShowDialog(); } catch { } }
private void OnProgressClick(object sender, RoutedEventArgs e) { var window = new ProgressWindow(); window.Show(); }
private void patchImport_Click(object sender, EventArgs e) { //output to show to the user bool differentRomsWarning = false; // tells if we have shown the warning int fileCount = 0; //open the input patch if (openPatchDialog.ShowDialog() == DialogResult.Cancel) return; FileStream fs = new FileStream(openPatchDialog.FileName, FileMode.Open, FileAccess.Read, FileShare.Read); BinaryReader br = new BinaryReader(fs); string header = br.ReadString(); if (header != "NSMBe4 Exported Patch") { MessageBox.Show( LanguageManager.Get("Patch", "InvalidFile"), LanguageManager.Get("Patch", "Unreadable"), MessageBoxButtons.OK, MessageBoxIcon.Error); br.Close(); return; } ProgressWindow progress = new ProgressWindow(LanguageManager.Get("Patch", "ImportProgressTitle")); progress.Show(); byte filestartByte = br.ReadByte(); try { while (filestartByte == 1) { string fileName = br.ReadString(); progress.WriteLine(string.Format(LanguageManager.Get("Patch", "ReplacingFile"), fileName)); ushort origFileID = br.ReadUInt16(); NSMBe4.DSFileSystem.File f = ROM.FS.getFileByName(fileName); uint length = br.ReadUInt32(); byte[] newFile = new byte[length]; br.Read(newFile, 0, (int)length); filestartByte = br.ReadByte(); if (f != null) { ushort fileID = (ushort)f.id; if (!differentRomsWarning && origFileID != fileID) { MessageBox.Show(LanguageManager.Get("Patch", "ImportDiffVersions"), LanguageManager.Get("General", "Warning"), MessageBoxButtons.OK, MessageBoxIcon.Warning); differentRomsWarning = true; } if (!f.isSystemFile) { Console.Out.WriteLine("Replace " + fileName); f.beginEdit(this); f.replace(newFile, this); f.endEdit(this); } fileCount++; } } } catch (AlreadyEditingException) { MessageBox.Show(string.Format(LanguageManager.Get("Patch", "Error"), fileCount), LanguageManager.Get("General", "Completed"), MessageBoxButtons.OK, MessageBoxIcon.Error); } br.Close(); MessageBox.Show(string.Format(LanguageManager.Get("Patch", "ImportReady"), fileCount), LanguageManager.Get("General", "Completed"), MessageBoxButtons.OK, MessageBoxIcon.Information); // progress.Close(); }
//Evento de consulta de ticket. private void btnTicket_Click(object sender, RoutedEventArgs e) { string no_procesados = ""; int cantidad_seleccionados = 0; try { //Recorrer la lista para obtener los elementos seleccionados. List <ReporteResumen> seleccionados = new List <ReporteResumen>(); foreach (var item in lista_reporte) { //Recorrer la lista de items if (item.Check == true) { cantidad_seleccionados++; if ((item.EstadoSunatCodigo == "5" || item.EstadoSunatCodigo == "4" || item.EstadoSunatCodigo == "2") && item.Ticket != "") { seleccionados.Add(item); } else { no_procesados += item.Archivo + "\n"; } } } if (cantidad_seleccionados > 0) { if (no_procesados.Length > 0) { System.Windows.MessageBox.Show("Los siguientes resumenes de reversion no seran procesados. Verifique ticket de consulta. \n" + no_procesados); } if (seleccionados.Count() > 0) { string resultado = string.Empty; ProgressDialogResult result = ProgressWindow.Execute(VentanaPrincipal, "Procesando...", () => { resultado = consultaTicket(seleccionados); }); refrescarGrilla(); if (resultado.Trim().Length > 0) { CustomDialogWindow obj = new CustomDialogWindow(); obj.AdditionalDetailsText = "Los siguientes comprobantes se consultaron correctamente:\n" + resultado; obj.Buttons = CustomDialogButtons.OK; obj.Caption = "Mensaje"; obj.DefaultButton = CustomDialogResults.OK; // obj.FooterIcon = CustomDialogIcons.Shield; // obj.FooterText = "This is a secure program"; obj.InstructionHeading = "Documentos consultados "; obj.InstructionIcon = CustomDialogIcons.Information; obj.InstructionText = "Los tickets de los documentos enviados fueron consultados correctamente."; CustomDialogResults objResults = obj.Show(); } } //Si existen elementos no procesados } else { System.Windows.MessageBox.Show("Seleccione los items a procesar."); } } catch (Exception ex) { clsBaseMensaje.cs_pxMsgEr("ERR15", ex.Message); clsBaseLog.cs_pxRegistarAdd("EnvioRA" + ex.ToString()); } }
/// <summary> /// Evento click para enviar los comprobantes a comunicacion de baja. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnEnviarSunat_Click(object sender, RoutedEventArgs e) { try { string no_procesados = string.Empty; //Recorrer las grilla para obtener los elementos seleccionados y alamcenarlos en una lista con los ids de los seleccionados. List <string> seleccionados = new List <string>(); foreach (var item in lista_reporte) { if (item.Check == true) { //Si el comprobante no esta asigando a una comunicacion de baja se guarda como seleccionado if (item.ComunicacionBaja == "") { seleccionados.Add(item.Id); } else { //En caso este asignado ya a una comunicacion de baja entonces asignar a no procesados. no_procesados += item.SerieNumero + "\n"; } } } // Si existen comprobantes no procesados porque ya fueron agregados a comunicaion de baja entonces mostrar menaje al usuario. if (no_procesados.Trim().Length > 0) { System.Windows.Forms.MessageBox.Show("Los siguientes comprobantes no sera procesados. Ya fueron agregados a comunicación de baja\n" + no_procesados, "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information); } //Si existen comprobantes seleccionados entonces procesar if (seleccionados.Count > 0) { //Confirmacion para enviar a comunicacion de baja los documentos seleccionados. if (System.Windows.Forms.MessageBox.Show("¿Está seguro que desea enviar a comunicación de baja los documentos seleccionados?", "¿Está seguro?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { string resultadoNoAgregados = string.Empty; // ProgressDialogResult result = ProgressWindow.Execute(VentanaPrincipal, "Procesando...", () => { resultadoNoAgregados = ProcesarComunicacionBaja(seleccionados); }); if (resultadoNoAgregados.Trim().Length > 0) { //no se agregaron CustomDialogWindow obj = new CustomDialogWindow(); obj.AdditionalDetailsText = "Los comprobantes no agregados son los siguientes:\n" + resultadoNoAgregados; obj.Buttons = CustomDialogButtons.OK; obj.Caption = "Mensaje"; obj.DefaultButton = CustomDialogResults.OK; // obj.FooterIcon = CustomDialogIcons.Shield; // obj.FooterText = "This is a secure program"; obj.InstructionHeading = "Documentos no agregados"; obj.InstructionIcon = CustomDialogIcons.Information; obj.InstructionText = "Algunos documentos no se agregaron a su comunicacion de baja. Verifique la fecha de emision no mayor a 7 dias."; CustomDialogResults objResults = obj.Show(); } else { //Si el resultado es vacio quiere decir que se agregaron todos los comprobantes: System.Windows.Forms.MessageBox.Show("Los documentos se agregaron a su respectiva comunicación de baja.", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information); } actualizarGrilla(); } } } catch (Exception ex) { clsBaseLog.cs_pxRegistarAdd("btnEnviarSunat " + ex.ToString()); } }
private void convertButton_Click(object sender, EventArgs e) { // Checks input and output files are specified if (inputTextBox.Text == String.Empty || outputTextBox.Text == String.Empty) { MessageBox.Show("You need to set both the input and output file fields.", "Unable to Convert", MessageBoxButtons.OK, MessageBoxIcon.Error); return; // Cancel conversion } // Checks at least one output is selected if ((!audioCheckBox.Checked || !audioCheckBox.Enabled) && (!videoCheckBox.Checked || !videoCheckBox.Enabled)) { MessageBox.Show("Both audio and video are disabled. Please select at least one output.", "Unable to Convert", MessageBoxButtons.OK, MessageBoxIcon.Error); return; // Cancel conversion } // Checks bitrate specified when set to vbr if (vbrRadioButton.Checked && vbrTextBox.Text == String.Empty) { MessageBox.Show("You have set to use an average video bitrate but have not specified a bitrate to target.", "Unable to Convert", MessageBoxButtons.OK, MessageBoxIcon.Error); return; // Cancel conversion } // Checks vbr buffer size set when max bitrate is specified if (vbrRadioButton.Checked) if (vbrMaxTextBox.Text != String.Empty && vbrBufferTextBox.Text == String.Empty) { MessageBox.Show("To set a maximum bitrate you need to set a buffer size.", "Unable to Convert", MessageBoxButtons.OK, MessageBoxIcon.Error); return; // Cancel conversion } // Checks bitrate specified when set to cbr if (cbrRadioButton.Checked && cbrTextBox.Text == String.Empty) { MessageBox.Show("You have set to use an constant video bitrate but have not specified a bitrate to use.", "Unable to Convert", MessageBoxButtons.OK, MessageBoxIcon.Error); return; // Cancel conversion } // Asks for confirmation to overwrite if the output file already exists if (System.IO.File.Exists(outputTextBox.Text)) { if (MessageBox.Show("The output file you have specified already exists. Would you like to overwrite it?", "Overwrite File", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No) return; // Cancel conversion } // Create arguments for FFmpeg from options set in UI // Clear any existing arguments Arguments = ""; VideoFilters = String.Empty; if (Format != String.Empty) Arguments += "-f " + Format; // Video tab if (videoCheckBox.Enabled && videoCheckBox.Checked) // If video enabled { if (Video != String.Empty) Arguments += " -vcodec " + Video; if (sameQualRadioButton.Checked) Arguments += " -same_quant"; if (vbrRadioButton.Checked) { Arguments += " -b:v " + vbrTextBox.Text + "k"; if (vbrMinTextBox.Text != String.Empty) Arguments += " -minrate " + vbrMinTextBox.Text + "k"; if (vbrMaxTextBox.Text != String.Empty) Arguments += " -maxrate " + vbrMaxTextBox.Text + "k"; if (vbrBufferTextBox.Text != String.Empty) Arguments += " -bufsize " + vbrBufferTextBox.Text + "k"; } if (cbrRadioButton.Checked) { Arguments += " -b:v " + cbrTextBox.Text + "k"; Arguments += " -bufsize " + (Convert.ToInt16(cbrTextBox.Text) / 4) + "k"; Arguments += " -minrate " + cbrTextBox.Text + "k"; Arguments += " -maxrate " + cbrTextBox.Text + "k"; } if (aspectComboBox.Text != String.Empty) Arguments += " -aspect " + aspectComboBox.Text; if (frameRateComboBox.Text != String.Empty) Arguments += " -r " + frameRateComboBox.Text; if (interlaceCheckBox.Checked) Arguments += " -flags +ilme+ildct"; if (Advanced != String.Empty) Arguments += " " + Advanced; } else // Else disable video recording Arguments += " -vn"; // Post Processing Tab if (deinterlacingComboBox.SelectedItem.ToString() == "Yadif") addVideoFilter("yadif=0:-1:0"); else if (deinterlacingComboBox.SelectedItem.ToString() == "Yadif (Double Framerate)") addVideoFilter("yadif=1:-1:0"); else if (deinterlacingComboBox.SelectedItem.ToString() == "MCDeint (Double Framerate)") addVideoFilter("yadif=1:-1:0,mp=mcdeint=2:1:10"); if (scalingComboBox.SelectedItem.ToString() == "Nearest Neighbor") Arguments += " -sws_flags neighbor"; else if (scalingComboBox.SelectedItem.ToString() == "Bilinear") Arguments += " -sws_flags bilinear"; else if (scalingComboBox.SelectedItem.ToString() == "Bicubic") Arguments += " -sws_flags bicubic"; else if (scalingComboBox.SelectedItem.ToString() == "Sinc") Arguments += " -sws_flags sinc"; else if (scalingComboBox.SelectedItem.ToString() == "Lanczos") Arguments += " -sws_flags lanczos"; else if (scalingComboBox.SelectedItem.ToString() == "Spline") Arguments += " -sws_flags spline"; if (denoiseComboBox.SelectedItem.ToString() == "Weak") addVideoFilter("hqdn3d=2:1:2:3"); else if (denoiseComboBox.SelectedItem.ToString() == "Medium") addVideoFilter("hqdn3d=3:2:2:3"); else if (denoiseComboBox.SelectedItem.ToString() == "Strong") addVideoFilter("hqdn3d=7:7:5:5"); if (deblockingComboBox.SelectedItem.ToString() == "On") addVideoFilter("mp=pp7"); // Audio Tab if (audioCheckBox.Enabled && audioCheckBox.Checked) // If audio enabled { if (Audio != String.Empty) Arguments += " -acodec " + Audio; if (channelsComboBox.Text != String.Empty) Arguments += " -ac " + channelsComboBox.Text; if (audioBitrateRadioButton.Checked && audioBitratePanel.Enabled) { if (audioBitrateTextBox.Text != String.Empty) Arguments += " -b:a " + audioBitrateTextBox.Text + "k"; } if (audioQualRadioButton.Checked && audioBitratePanel.Enabled) { if (audioQualTextBox.Text != String.Empty) Arguments += " -aq " + audioQualTextBox.Text; } if (sampleComboBox.Text != String.Empty) Arguments += " -ar " + sampleComboBox.Text; } else // Else disable audio recording Arguments += " -an"; // Crop and Pad tab if (cropTopUpDown.Value > 0 || cropLeftUpDown.Value > 0 || cropRightUpDown.Value > 0 || cropBottomUpDown.Value > 0) addVideoFilter("crop=in_w-" + (cropLeftUpDown.Value + cropRightUpDown.Value).ToString() + ":in_h-" + (cropTopUpDown.Value + cropBottomUpDown.Value).ToString() + ":" + cropLeftUpDown.Value.ToString() + ":" + cropTopUpDown.Value.ToString()); if (padTopUpDown.Value > 0 || padLeftUpDown.Value > 0 || padRightUpDown.Value > 0 || padBottomUpDown.Value > 0) addVideoFilter("pad=in_w+" + (padLeftUpDown.Value + padRightUpDown.Value).ToString() + ":in_h+" + (padTopUpDown.Value + padBottomUpDown.Value).ToString() + ":" + padLeftUpDown.Value.ToString() + ":" + padTopUpDown.Value.ToString() + ":0x" + padColourComboBox.SelectedColor.R.ToString("X2") + padColourComboBox.SelectedColor.G.ToString("X2") + padColourComboBox.SelectedColor.B.ToString("X2")); // Add Video Filters from Video, Post Processing, Pad and Crop if (widthTextBox.Text != String.Empty && heightTextBox.Text != String.Empty) addVideoFilter("scale=" + widthTextBox.Text + ":" + heightTextBox.Text + ":interl=-1"); if (fps != "" && frameRateComboBox.Text != String.Empty) if ((Convert.ToSingle(frameRateComboBox.Text) == (Convert.ToSingle(fps) / 2)) && interlaceCheckBox.Checked) addVideoFilter("tinterlace=4"); if (VideoFilters != String.Empty && videoPresent) Arguments += " -vf \"" + VideoFilters + "\""; // Trim tab if (trimStartTextBox.Text != String.Empty) { Arguments += " -ss " + trimStartTextBox.Text; ffmpeg.trimStart = new TimeSpan(0, 0, Convert.ToInt16(trimStartTextBox.Text)); } if (trimEndTextBox.Text != String.Empty) { Arguments += " -t " + trimEndTextBox.Text; ffmpeg.trimLength = new TimeSpan(0, 0, Convert.ToInt16(trimEndTextBox.Text)); } // Meta data tab if (titleTextBox.Text != String.Empty && titleTextBox.Enabled) Arguments += " -metadata title=\"" + titleTextBox.Text + "\""; if (authorTextBox.Text != String.Empty && authorTextBox.Enabled) Arguments += " -metadata artist=\"" + authorTextBox.Text + "\""; if (authorTextBox.Text != String.Empty && authorTextBox.Enabled) Arguments += " -metadata album=\"" + albumTextBox.Text + "\""; if (copyrightTextBox.Text != String.Empty && copyrightTextBox.Enabled) Arguments += " -metadata copyright=\"" + copyrightTextBox.Text + "\""; if (commentTextBox.Text != String.Empty && commentTextBox.Enabled) Arguments += " -metadata comment=\"" + commentTextBox.Text + "\""; //Output tab ffmpeg.outputFile = outputTextBox.Text; if (twoPassCheckBox.Enabled && twoPassCheckBox.Checked) ffmpeg.twoPass = true; else ffmpeg.twoPass = false; // Pass arguments to FFmpeg ffmpeg.procArguments = Arguments; // Open progress window to start conversion ProgressWindow progressWindow = new ProgressWindow(); progressWindow.ShowDialog(); }
// Spawns the website creation thread, which calls CWebsite.Create to do the work. private bool CreateWebsite(string sOutputFolder, string sImageFolder) { LogFile.TheLogFile.WriteLine(LogFile.DT_APP, LogFile.EDebugLevel.Note, "Creating website"); DialogResult dialogResult; // If user has specified a background image, check it exists if (s_config.m_sBackgroundImage != null && s_config.m_sBackgroundImage.Length != 0 && File.Exists(s_config.m_sBackgroundImage) == false) { LogFile.TheLogFile.WriteLine(LogFile.DT_APP, LogFile.EDebugLevel.Warning, "Can't find background image " + s_config.m_sBackgroundImage); dialogResult = MessageBocx.Show(m_mainForm, String.Format("The file {0} is missing. " + "\r\nPages will be created without any background image.", s_config.m_sBackgroundImage), "Creating website", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation, false); if (dialogResult == DialogResult.Cancel) { LogFile.TheLogFile.WriteLine(LogFile.DT_APP, LogFile.EDebugLevel.Note, "Message box cancelled (1)"); return false; } } LogFile.TheLogFile.WriteLine(LogFile.DT_APP, LogFile.EDebugLevel.Note, "Starting progress window"); ProgressWindow progressWindow = new ProgressWindow(); progressWindow.Text = "Creating web pages"; CWebsite website = new CWebsite(m_gedcom, progressWindow); ThreadStart threadStart = new ThreadStart(website.Create); Thread threadWorker = new Thread(threadStart); LogFile.TheLogFile.WriteLine(LogFile.DT_APP, LogFile.EDebugLevel.Note, "Starting progress thread"); dialogResult = DialogResult.Abort; try { threadWorker.Start(); dialogResult = progressWindow.ShowDialog(this); } catch (CHTMLException e) { MessageBocx.Show(m_mainForm, String.Concat(e.Message), "Creating website", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, false); } finally { threadWorker.Join(); } if (dialogResult == DialogResult.Abort) { LogFile.TheLogFile.WriteLine(LogFile.DT_APP, LogFile.EDebugLevel.Note, "Thread aborted"); if (progressWindow.m_threaderror.m_sMessage == "") { // Abort means there were file IO errors MessageBocx.Show(m_mainForm, String.Format("A problem was encountered while creating the website files:\r\n\r\n{0}", LogFile.TheLogFile.ErrorReport()), MainForm.m_sSoftwareName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation, true); } else { // Abort means there were file IO errors MessageBocx.Show(m_mainForm, progressWindow.m_threaderror.m_sMessage, MainForm.m_sSoftwareName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation, true); } } if (dialogResult != DialogResult.OK) { LogFile.TheLogFile.WriteLine(LogFile.DT_APP, LogFile.EDebugLevel.Note, "Dialog not OK"); return false; } LogFile.TheLogFile.WriteLine(LogFile.DT_APP, LogFile.EDebugLevel.Note, "Website create done."); return true; }
public void BuildLayout() { Pic.Factory2D.Control.FormImpositionSettings formSettings = new Pic.Factory2D.Control.FormImpositionSettings(); if (null != _cardboardFormatLoader) formSettings.FormatLoader = _cardboardFormatLoader; // get offset Vector2D impositionOffset = Component.ImpositionOffset(CurrentParameterStack); // initialize form with offsets formSettings.OffsetX = impositionOffset.X; formSettings.OffsetY = impositionOffset.Y; if (DialogResult.OK == formSettings.ShowDialog()) { using (PicFactory factory = new PicFactory()) { // build factory entities Component.CreateFactoryEntities(factory, CurrentParameterStack); if (_reflectionX) factory.ProcessVisitor(new PicVisitorTransform(Transform2D.ReflectionX)); if (_reflectionY) factory.ProcessVisitor(new PicVisitorTransform(Transform2D.ReflectionY)); // build imposition solutions if (formSettings.Mode == 0) _impositionTool = new ImpositionToolCardboardFormat(factory, formSettings.CardboardFormat); else _impositionTool = new ImpositionToolXY(factory, formSettings.NumberDirX, formSettings.NumberDirY); // -> margins _impositionTool.HorizontalAlignment = formSettings.HorizontalAlignment; _impositionTool.VerticalAlignment = formSettings.VerticalAlignment; _impositionTool.SpaceBetween = new Vector2D(formSettings.ImpSpaceX, formSettings.ImpSpaceY); _impositionTool.Margin = new Vector2D(formSettings.ImpMarginLeftRight, formSettings.ImpMarginBottomTop); _impositionTool.MinMargin = new Vector2D(formSettings.ImpRemainingMarginLeftRight, formSettings.ImpRemainingMarginBottomTop); // -> allowed patterns _impositionTool.AllowRotationInColumnDirection = formSettings.AllowColumnRotation; _impositionTool.AllowRotationInRowDirection = formSettings.AllowRowRotation; // -> offsets _impositionTool.ImpositionOffset = new Vector2D(formSettings.OffsetX, formSettings.OffsetY); // instantiate ProgressWindow and launch process ProgressWindow progress = new ProgressWindow(); System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(GenerateImpositionSolutions), progress); progress.ShowDialog(); // show dialog if (null != _solutions && _solutions.Count > 0) { Pic.Factory2D.Control.FormImposition form = new Pic.Factory2D.Control.FormImposition(); form.Solutions = _solutions; form.Format = formSettings.CardboardFormat; if (DialogResult.OK == form.ShowDialog(this)) { } } } } }
// Handles the processing needed at each stage of the app, as the user moves through each page of the wizard. private bool ValidateCurrentPanel() { LogFile.TheLogFile.WriteLine(LogFile.DT_APP, LogFile.EDebugLevel.Note, "ValidateCurrentPanel()"); DialogResult result; // Loop gives user the option to retry folder creation. Use return to exit. while (true) { switch (m_nCurrentPanel) { case 2: if (File.Exists(InputFile) == false) { LogFile.TheLogFile.WriteLine(LogFile.DT_APP, LogFile.EDebugLevel.Note, "File not found."); MessageBocx.Show(m_mainForm, "The file you have selected could not be found.", "File Not Found", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, false); LogFile.TheLogFile.WriteLine(LogFile.DT_APP, LogFile.EDebugLevel.Note, "File not found. Returning. "); return false; } ProgressWindow progressWindow = new ProgressWindow(); progressWindow.Text = "Reading GEDCOM file"; if (s_config.m_sOutputFolder == "" || s_config.m_sInputFilename != InputFile) { s_config.m_sOutputFolder = Path.GetDirectoryName(InputFile); s_config.m_sOutputFolder += "\\GEDmill_Output"; } if (s_config.m_sInputFilename != InputFile) { s_config.m_sInputFilename = InputFile; s_config.m_sFirstRecordXref = ""; // User is using a new file, so key individuals won't be the same as they were in config s_config.m_alKeyIndividuals = new ArrayList(); s_config.m_sFirstRecordXref = ""; } m_gedcom.Filename = InputFile; m_gedcom.DataMayStartWithWhitespace = s_config.m_bDataMayStartWithWhitespace; m_gedcom.DataMayEndWithWhitespace = s_config.m_bDataMayEndWithWhitespace; m_gedcom.ProgressCallback = progressWindow; LogFile.TheLogFile.WriteLine(LogFile.DT_APP, LogFile.EDebugLevel.Note, "Reading GEDCOM file " + InputFile); ThreadStart threadStart = new ThreadStart(m_gedcom.ParseFile); Thread threadWorker = new Thread(threadStart); LogFile.TheLogFile.WriteLine(LogFile.DT_APP, LogFile.EDebugLevel.Note, "Starting thread"); threadWorker.Start(); result = progressWindow.ShowDialog(this); threadWorker.Join(); LogFile.TheLogFile.WriteLine(LogFile.DT_APP, LogFile.EDebugLevel.Note, "Thread finished, result=" + result.ToString()); if (result == DialogResult.Abort) // Abort means abnormal failure (ie. not user pressing cancel) { // Abort means there were file IO errors MessageBocx.Show(m_mainForm, String.Format("A problem was encountered while reading the GEDCOM file:\r\n\r\n{0}", LogFile.TheLogFile.ErrorReport()), MainForm.m_sSoftwareName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation, true); } else if (result == DialogResult.Retry) // Something went wrong, let user retry { // Currently the only thing this can be is "file already open" MessageBocx.Show(m_mainForm, "A problem was encountered while reading the GEDCOM file.\r\n\r\nPerhaps the file is already open elsewhere.", MainForm.m_sSoftwareName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation, true); } if (result != DialogResult.OK) { return false; // Go back and let user retry loading file. } m_bPrunepanelDataChanged = false; // A fresh file, no user changes yet. FillIndividualsList(m_listviewPruneRecordsIndis, false, null, true); FillSourcesList(m_listviewPruneRecordsSources, true); return true; case 3: // Go through individuals list and set restricted flag as appropriate bool bSomethingChecked = false; foreach (ListViewItem li in m_listviewPruneRecordsIndis.Items) { bool bChecked = ((ListViewItem)li).Checked; if (bChecked) { bSomethingChecked = true; } // Already done on click event: ((CListableBool)((ListViewItem)li)).SetRestricted( !bChecked ); if (!bChecked) { m_gedcom.RestrictAssociatedSources((LLClasses.CIndividualRecord)(((CListableBool)((ListViewItem)li)).ISRecord)); } } if (bSomethingChecked == false) { MessageBocx.Show(m_mainForm, "Please select at least one individual.", "No Individuals Selected", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, false); return false; } if (m_bPrunepanelDataChanged) { DialogResult dialogResult = MessageBocx.Show(m_mainForm, "You have made changes which will affect the website but have not saved them.\r\nWould you like to save them now?", "Save changes", MessageBoxButtons.YesNo, MessageBoxIcon.Question, false); if (dialogResult == DialogResult.Yes) { buttonPruneRecordsSave_click(null, null); } } return true; case 4: s_config.m_sTitle = m_textboxSelectKey.Text; return true; case 5: s_config.m_sOutputFolder = m_textboxChooseOutput.Text; string sImageFolder = s_config.m_sImageFolder; string sOutputFolder = s_config.m_sOutputFolder; if (sOutputFolder != "") { sOutputFolder = sOutputFolder + '\\'; } string sAbsImageFolder = String.Concat(sOutputFolder, sImageFolder); bool bPreserveFiles = false; if (s_config.m_bPreserveFrontPage || s_config.m_bPreserveStylesheet) { // To generate warning if deleting folder & files. bPreserveFiles = true; } for (; ; ) { result = PrepareOutputDirectory(sOutputFolder, bPreserveFiles); if (result == DialogResult.Cancel) { return false; } if (result == DialogResult.OK) { break; } } for (; ; ) { result = PrepareOutputDirectory(sAbsImageFolder, false); if (result == DialogResult.Cancel) { return false; } if (result == DialogResult.OK) { break; } } if (CreateWebsite(sOutputFolder, sAbsImageFolder)) { return true; } return false; case 6: return true; default: return true; } } }
public static int Compact(VoidPtr srcAddr, int srcLen, Stream outStream, ResourceNode r, bool extendedFormat) { using (ProgressWindow prog = new ProgressWindow(r.RootNode._mainForm, "Differential", String.Format("Compressing {0}, please wait...", r.Name), false)) return(new Differential().Compress(srcAddr, srcLen, outStream, prog)); }
/// <summary> ///Function: go through an populates an arrayList containing all writable user attributes. /// </summary> private void createWriteableAttribList() { //First, get schemea of properties, both single and multivalued //Get current server string ADServer = Environment.GetEnvironmentVariable("LOGONSERVER"); //Remove the "//" ADServer = ADServer.Substring(2); //Get the selected domain string domainName = cboDC.Text.ToString(); //Concatenate to make full server name string fullServerName = ADServer + "." + domainName; //MessageBox.Show("The directory context is: " + fullServerName); //Specify server stuff ex. "prjdc.project.com" DirectoryContext adamContext = new DirectoryContext(DirectoryContextType.DirectoryServer, fullServerName); //MessageBox.Show(adamContext.Name); //Get schema for that servers active directory ActiveDirectorySchema schema = ActiveDirectorySchema.GetSchema(adamContext); /* // Test for getting all classes foreach (ActiveDirectorySchemaClass schemaClass in schema.FindAllClasses()) { MessageBox.Show(schemaClass.GetAllProperties().ToString()); } */ //Get the user schema class ActiveDirectorySchemaClass schemaClass = schema.FindClass("user"); //Now that we have the correct class, GET ALL PROPERTIES in that class (these properties themselves are readonly because we don't want to alter them) ReadOnlyActiveDirectorySchemaPropertyCollection adPropertyCollection = schemaClass.GetAllProperties(); //There are 342 //http://stackoverflow.com/questions/4931982/how-can-i-check-if-a-user-has-write-rights-in-active-directory-using-c //Find the current logged on user that will be modfying user properties string userName = Environment.UserName; //Get the users domain string userDomainName = Environment.UserDomainName; //MessageBox.Show("The domain name which the user is in: " + userDomainName); DirectoryEntry de = new DirectoryEntry(); de.Path = "LDAP://" + userDomainName; de.AuthenticationType = AuthenticationTypes.Secure; DirectorySearcher deSearch = new DirectorySearcher(); deSearch.SearchRoot = de; deSearch.Filter = "(&(objectClass=user) (cn=" + userName + "))"; SearchResult result = deSearch.FindOne(); DirectoryEntry deUser = new DirectoryEntry(result.Path); //Refresh Cache to get the values, I guess? deUser.RefreshCache(new string[] { "allowedAttributesEffective" }); // Proof this is the user //MessageBox.Show("About to show the username: "******"cn"].Value.ToString()); //MessageBox.Show("About to show the users distinguished name: " + deUser.Properties["distinguishedName"].Value.ToString()); //Now get the property["allowedAttributesEffective"] of the user //Test on a property that did not have to refresh cache for, just to ensure enumeration was working //string propertyName = deUser.Properties["otherHomePhone"].PropertyName; string propertyName = deUser.Properties["allowedAttributesEffective"].PropertyName; //MessageBox.Show("About to loop through the multi-valued property: " + deUser.Properties["allowedAttributesEffective"].PropertyName); //MessageBox.Show("About to loop through the multi-valued property: " + propertyName); //MessageBox.Show("Number of elements: " + deUser.Properties[propertyName].Count); alWritableProperties.Clear(); //Go through all the elements of that multi-valued property IEnumerator propEnumerator = deUser.Properties[propertyName].GetEnumerator(); //Getting the Enumerator propEnumerator.Reset(); //Position at the Beginning //Loading Bar for writable properties int i = 0; ProgressWindow pwBar = new ProgressWindow("Finding Writable User Properties", deUser.Properties[propertyName].Count); pwBar.Show(); pwBar.SetPercentDone(i); while (propEnumerator.MoveNext()) //while there is a next one to move to { //MessageBox.Show("" + propEnumerator.Current.ToString()); try { ActiveDirectorySchemaProperty propertyToTest = new ActiveDirectorySchemaProperty(adamContext, propEnumerator.Current.ToString()); //See if property is writable //is property single valued if (adPropertyCollection[adPropertyCollection.IndexOf(propertyToTest)].IsSingleValued == true) { //Single valued comparison deUser.Properties[propEnumerator.Current.ToString()].Value = deUser.Properties[propEnumerator.Current.ToString()].Value; } else { //Multi-valued comparison (Not implemented) //http://stackoverflow.com/questions/5067363/active-directory-unable-to-add-multiple-email-addresses-in-multi-valued-propert //MessageBox.Show("Dealing with multivalued property: " + propEnumerator.Current.ToString()); //deUser.Properties[propEnumerator.Current.ToString()].Clear(); //deUser.Properties[propEnumerator.Current.ToString()].Count; //MessageBox.Show("Number of elements: " + deUser.Properties[propEnumerator.Current.ToString()].Count.ToString()); //deUser.Properties[propEnumerator.Current.ToString()].Value = deUser.Properties[propEnumerator.Current.ToString()].Value; /* if (propEnumerator.Current.ToString().Equals("departmentNumber")) { MessageBox.Show("Number of elements before: " + deUser.Properties[propEnumerator.Current.ToString()].Count.ToString()); deUser.Properties[propEnumerator.Current.ToString()].Add("9"); MessageBox.Show("Number of elements after: " + deUser.Properties[propEnumerator.Current.ToString()].Count.ToString()); //MessageBox.Show("Number of elements before: " + deUser.Properties[propEnumerator.Current.ToString()].Count.ToString()); //object tempObject = deUser.Properties[propEnumerator.Current.ToString()].Value; //deUser.Properties[propEnumerator.Current.ToString()].Clear(); //MessageBox.Show("Number of elements now cleared: " + deUser.Properties[propEnumerator.Current.ToString()].Count.ToString()); //deUser.Properties[propEnumerator.Current.ToString()].Value = tempObject; //MessageBox.Show("Number of elements after: " + deUser.Properties[propEnumerator.Current.ToString()].Count.ToString()); } */ } deUser.CommitChanges(); //Add to array since it is writable alWritableProperties.Add(propEnumerator.Current.ToString()); } catch (Exception e) { //MessageBox.Show(propEnumerator.Current.ToString() + " can only be viewed" + e.Message); } pwBar.SetPercentDone(i++); } deUser.Close(); //MessageBox.Show("Number of actual writable properties: " + alWritableProperties.Count); //End loading bar pwBar.Close(); // OLD STUFF BELOW // http://msdn.microsoft.com/en-us/library/ms180940(v=vs.80).aspx //ActiveDirectorySchemaClass // http://stackoverflow.com/questions/3290730/how-can-i-read-the-active-directory-schema-programmatically // http://msdn.microsoft.com/en-us/library/bb267453.aspx#sdsadintro_topic3_manageschema /* //Get current server string ADServer = Environment.GetEnvironmentVariable("LOGONSERVER"); //Remove the "//" ADServer = ADServer.Substring(2); //Get the selected domain string domainName = cboDC.Text.ToString(); //Concatenate to make full server name string fullServerName = ADServer + "." + domainName; MessageBox.Show("The directory context is: " + fullServerName); //Specify server stuff ex. "prjdc.project.com" DirectoryContext adamContext = new DirectoryContext(DirectoryContextType.DirectoryServer, fullServerName); MessageBox.Show(adamContext.Name); //Get schema for that servers active directory ActiveDirectorySchema schema = ActiveDirectorySchema.GetSchema(adamContext); */ /* // Test for getting all classes foreach (ActiveDirectorySchemaClass schemaClass in schema.FindAllClasses()) { MessageBox.Show(schemaClass.GetAllProperties().ToString()); } */ /* //Get the user schema class ActiveDirectorySchemaClass schemaClass = schema.FindClass("user"); //Now that we have the correct class, GET ALL PROPERTIES in that class (these properties themselves are readonly because we don't want to alter them) ReadOnlyActiveDirectorySchemaPropertyCollection adPropertyCollection = schemaClass.GetAllProperties(); //There are 342 //ActiveDirectorySchemaPropertyCollection adPropertyCollection = schemaClass.OptionalProperties; //There are 335 //ActiveDirectorySchemaPropertyCollection adPropertyCollection = schemaClass.MandatoryProperties; //There are 7 */ /* foreach (ActiveDirectorySchemaProperty schemaProperty in adPropertyCollection) { // http://msdn.microsoft.com/en-us/library/system.reflection.propertyattributes.aspx // Final test with "systemOnly" attribute, if this doesn't work, it won't ever... // Get the PropertyAttributes enumeration of the property. // Get the type. TypeAttributes schemaPropertyAttributes = schemaProperty.GetType().Attributes; // Get the property attributes. //PropertyInfo schemaPropertyInfo = schemaPropertyType.GetProperty("systemOnly"); //PropertyAttributes propAttributes = schemaPropertyInfo.Attributes; //Display the property attributes value. MessageBox.Show("Property: " + schemaProperty.CommonName.ToString() + " has attributes: " + s; } */ //Have a fake read-only property //ActiveDirectorySchemaProperty fakeProperty = new ActiveDirectorySchemaProperty(adamContext, "cn"); //AttributeCollection fakePropertyAttributes = TypeDescriptor.GetAttributes(fakeProperty); //DirectoryServicesPermissionAttribute a = new DirectoryServicesPermissionAttribute( /* MessageBox.Show("Does fake property contain read-write attribute: " + fakePropertyAttributes.Contains(ReadOnlyAttribute.No).ToString()); if (a) { MessageBox.Show("READ ONLY"); } else { //Can't be, when try to go fakeProperty.Name = "MEGADEATH" it says can't because prop is read-only MessageBox.Show("READ AND WRITE"); } */ //http://technet.microsoft.com/en-us/library/cc773309(WS.10).aspx // CURRENT PROBLEM: // Can get all properties, but cannot seem to separate writable from read-only // have heard of attributeSchema but no luck // now thinking of using systemOnly flag, but no idea how to check for that http://msdn.microsoft.com/en-us/library/aa772300.aspx /* // Test value of flags using bitwise AND. bool test = (meetingDays & Days2.Thursday) == Days2.Thursday; // true Console.WriteLine("Thursday {0} a meeting day.", test == true ? "is" : "is not"); // Output: Thursday is a meeting day. * */ /* Type type = typeof(ActiveDirectorySchemaProperty); object[] ac = type.GetCustomAttributes(true); //Test for what's in collection MessageBox.Show("Now Testing what is in ReadOnlyActiveDirectorySchemaPropertyCollection"); int actualNumber = 0; foreach (ActiveDirectorySchemaProperty adProperty in adPropertyCollection) { actualNumber++; //MessageBox.Show("Property: " + adProperty.Name + " // Common Name: " + adProperty.CommonName); // http://msdn.microsoft.com/en-us/library/system.componentmodel.attributecollection.aspx // //Get attributes of that property (ex. is a string, is read only, is writable, etc) AttributeCollection attributes = TypeDescriptor.GetAttributes(adProperty); //List of systemOnly of the property MessageBox.Show("Now showing attributes in current property"); //attributes.Contains(Attribute.GetCustomAttribute(AssemblyFlagsAttribute"systemOnly",typeof(FlagsAttribute))); AssemblyName a = new AssemblyName(); //https://connid.googlecode.com/svn-history/r169/bundles/ad/trunk/src/main/java/org/connid/ad/schema/ADSchemaBuilder.java //AssemblyNameFlags aName = new AssemblyNameFlags(); //AssemblyFlagsAttribute afa = new AssemblyFlagsAttribute(aName); //See if the attributes collection isn't writable //if (attributes.Contains(ReadOnlyAttribute.No) == false) //if(attributes.Contains(Attribute.GetCustomAttribute(typeof(ActiveDirectorySchemaProperty),"systemOnly"))) // More freaking testing // http://stackoverflow.com/questions/2051065/check-if-property-has-attribute // //http://msdn.microsoft.com/en-us/library/cc220922(v=prot.10).aspx //Go through all attributes and see if systemOnly is false, if it is then add the property to the array //Go through all attributes and see if systemOnly is false, if it is then add the property to the array foreach (Attribute currentattribute in attributes) { MessageBox.Show(currentattribute.TypeId.ToString()); } /* if () { //Cannot read and write } else { //Our property is read/write! //Add the name of the property to our alWritableProperties array list alWritableProperties.Add(adProperty.Name.ToString()); } */ /* } MessageBox.Show("Now Seeing what has been added to the writable properties list"); MessageBox.Show("Number of Properties: " + actualNumber.ToString() + "\nNumber of Writable Properties: " + alWritableProperties.Count); */ /* #region Properties of the schema /* // This will get the properties of the schema class PropertyInfo[] aPropertyInfo = schemaClass.GetType().GetProperties(); //For each property foreach (PropertyInfo property in aPropertyInfo) { MessageBox.Show("Property: " + property.Name); /* if (property.PropertyType.Assembly == schemaClass.GetType().Assembly) { //Show just property MessageBox.Show("Property: " + property.Name); } else { MessageBox.Show("Property: " + property.Name + " Value: " + propValue); } */ /* } */ /* #endregion */ /* http://msdn.microsoft.com/en-us/library/windows/desktop/ms677167(v=vs.85).aspx */ //IDEA: We get do foreach madatory, and a foreach optional property, put all into huge property array // Then for each property, we do the whole type thing //http://stackoverflow.com/questions/6196413/how-to-recursively-print-the-values-of-an-objects-properties-using-reflection /* //foreach (ActiveDirectorySchemaProperty schemaProperty in schemaClass.MandatoryProperties) //ActiveDirectorySchemaPropertyCollection //ActiveDirectorySchemaPropertyCollection[] properties = schemaClass.GetType().GetProperties(); foreach(ActiveDirectorySchemaProperty schemaProperty in schemaClass.MandatoryProperties) { PropertyInfo[] properties = schemaProperty.GetType().GetProperties(); //findAttrValue //See what we have in the properties MessageBox.Show(properties.GetEnumerator().ToString()); /* http://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute(v=vs.71).aspx */ //[C#] // Gets the attributes for the property. //AttributeCollection attributes = TypeDescriptor.GetProperties(this)["MyProperty"].Attributes; //AttributeCollection attributes = TypeDescriptor.GetProperties(this)[schemaProperty.Name].Attributes; //AttributeCollection attributes = [schemaProperty.Name].Attributes; //Prints the default value by retrieving the DefaultValueAttribute //from the AttributeCollection. //DefaultValueAttribute myAttribute = (DefaultValueAttribute)attributes[typeof(DefaultValueAttribute)]; //MessageBox.Show("The default value is: " + myAttribute.Value.ToString()); /* // Checks to see whether the value of the ReadOnlyAttribute is Yes. if (attributes[typeof(ReadOnlyAttribute)].Equals(ReadOnlyAttribute.Yes)) { // Insert code here. MessageBox.Show("The Property " + schemaProperty.Name + " is read-only"); } */ //AttributeCollection attributes = TypeDescriptor.GetProperties(schemaProperty)[schemaProperty.Name].Attributes; //Attribute a = attributes[schemaProperty]. /* foreach (PropertyInfo property in properties) { MessageBox.Show("Property: " + property.Name); } } */ /* //Find all mandatory properties for the schemaClass foreach (ActiveDirectorySchemaProperty schemaProperty in schemaClass.MandatoryProperties) { MessageBox.Show("Property: " + schemaProperty.ToString()); MessageBox.Show("Name(what we write to): " + schemaProperty.Name + ", Common Name(Display Name to show on datagridview): " + schemaProperty.CommonName); //Determine if it is a writable property //To get the CanWrite property, first get the class Type. //Type propertyType = Type.GetType(schemaProperty.Name); Type propertyType = schemaProperty.GetType(); //Type propertyType = schemaProperty.Name.GetType(); //Type propertyType = Type.GetType(schemaProperty.Name); //From the Type, get the PropertyInfo. From the PropertyInfo, get the CanWrite value. MessageBox.Show("Made it past Type: " + propertyType.ToString()); PropertyInfo[] properties = propertyType.GetProperties(); foreach (PropertyInfo property in properties) { object propValue = property.GetValue(schemaProperty, null); if (property.PropertyType.Assembly == propertyType.Assembly) { MessageBox.Show("Property: " + property.Name); } else { MessageBox.Show("Property: " + property.Name + " Value: " + propValue); } } /* PropertyInfo propInfo = propertyType.GetProperty(schemaProperty.ToString()); PropertyAttributes pAttributes = propInfo.Attributes; MessageBox.Show("Attributes: " + pAttributes.ToString()); */ /* //MessageBox.Show("Made it past Info! " + propInfo.CanWrite); if (propInfo.CanWrite == true) { MessageBox.Show("We CAN write to this mofo!"); } else { MessageBox.Show("We CANNOT write to this mofo!"); } */ //MessageBox.Show("Can we write to this mofo? " + propInfo.CanWrite.ToString()); //Old //PropertyInfo[] propInfo = propertyType.GetProperties(BindingFlags.Public | BindingFlags.Instance); /* http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.canwrite.aspx */ //using reflection /* http://www.codersource.net/microsoft-net/c-basics-tutorials/reflection-in-c.aspx */ /* for (int i = 0; i < propInfo.Length ;i++) { MessageBox.Show(propInfo[0].ToString()); } */ /* if(propertyType) { //Since this is a writable property, add it to the array } */ /* } */ }
private void btnExport_Click(object sender, RoutedEventArgs e) { List <Model.TB_StandardInfo> checkedStandList = GetCheckedStand(); if (checkedStandList.Count == 0) { DSJL.Tools.MessageBoxTool.ShowConfirmMsgBox("请选择要导出的测试参考值!"); return; } if (DSJL.Tools.ShowFileDialogTool.ShowSaveFileDialog(out exportPath, "", "dsf", "等速肌力参考值导出") == false) { return; } exportPath = exportPath.Substring(0, exportPath.LastIndexOf("\\") + 1); Console.WriteLine("export path is:{0}", exportPath); ProgressWindow window = new ProgressWindow(); window.WindowTilte = "导出参考值进度"; window.MaxValue = checkedStandList.Count; window.MinValue = 0; window.CancleMessage = "确定取消导出吗?"; window.onCancling += Window_onCancling; window.Owner = this; Task task = new Task(() => { int progress = 0; foreach (var item in checkedStandList) { if (isCancleExport) { break; } //1、查询测试信息 List <Model.TestInfoModel> testInfoModelList = Caches.Util.AthTestInfoModelUtil.AthTestUtil(refeBLL.GetStandTestInfoModelList(item.ID)); if (testInfoModelList.Count == 0) { continue; } Model.TestInfoModel avgTestInfoModel = GetAvgTestInfoModel(testInfoModelList); string testInfoModelJson = Newtonsoft.Json.JsonConvert.SerializeObject(avgTestInfoModel); // Console.WriteLine(testInfoModelJson); //2、计算平均值 List <List <XElement> > paramList = DSJL.Export.GenerateCompareResportXml.ComputeAvg(testInfoModelList); string paramJson = Newtonsoft.Json.JsonConvert.SerializeObject(paramList); // Console.WriteLine(paramJson); Dictionary <DataPointsType, List <List <double> > > dataPointsDict = StandardChartCache.GetStandardDataPoints(item, testInfoModelList); List <List <double> > oddavgsd = dataPointsDict[DataPointsType.ODDAvgSD]; List <List <double> > evenavgsd = dataPointsDict[DataPointsType.EVENAVGSD]; string oddavgsdjson = Newtonsoft.Json.JsonConvert.SerializeObject(oddavgsd); string evenavgsdjson = Newtonsoft.Json.JsonConvert.SerializeObject(evenavgsd); // Console.WriteLine(oddavgsdjson); // Console.WriteLine(evenavgsdjson); //3、写入文件 Model.TB_StandardInfo parentStandModel = standList.Find(x => x.ID == item.Stand_ParentID); Model.ExportStandModel exportStandModel = new Model.ExportStandModel(); exportStandModel.ParentName = parentStandModel.Stand_Name; exportStandModel.StandName = item.Stand_Name; exportStandModel.TestModel = avgTestInfoModel; exportStandModel.ParamList = paramList; exportStandModel.OddAvgSD = oddavgsd; exportStandModel.EvenAvgSD = evenavgsd; string standJson = Newtonsoft.Json.JsonConvert.SerializeObject(exportStandModel); standJson = DSJL.Tools.DES.Encrypt(standJson, "cissdsjl"); string filename = string.Format("{0}{1}.dsf", exportPath, item.Stand_Name); StreamWriter sw = new StreamWriter(filename); sw.Write(standJson); sw.Close(); progress++; Dispatcher.BeginInvoke(new Action(() => { window.CurrentValue = progress; })); } DSJL.Tools.MessageBoxTool.ShowConfirmMsgBox("导出完成!"); Dispatcher.BeginInvoke(new Action(() => { window.Close(); this.Close(); })); }); task.Start(); window.ShowDialog(); }
private async Task ExecuteReport() { QueryErrorMessage.Value = ""; IsErrorVisible.Value = false; if (string.IsNullOrEmpty(GroupByField.Value)) { ApplicationModel.Current.Notifications.Add(new Notification("You must select a field to group by")); return; } if (ValueCalculations.Count == 0) { ApplicationModel.Current.Notifications.Add(new Notification("You must add at least one Value")); return; } var facets = new List<AggregationQuery>(); foreach (var value in ValueCalculations) { var facetForField = facets.FirstOrDefault(f => f.AggregationField == value.Field); if (facetForField != null) { facetForField.Aggregation |= value.SummaryMode; } else { facets.Add(new AggregationQuery { Name = GroupByField.Value, DisplayName = GroupByField.Value + "-" + value.Field, AggregationField = value.Field, Aggregation = value.SummaryMode }); } } ResultColumns = null; Results.Clear(); var cancelationTokenSource = new CancellationTokenSource(); var progressWindow = new ProgressWindow() { Title = "Preparing Report", IsIndeterminate = false, CanCancel = true }; progressWindow.Closed += delegate { cancelationTokenSource.Cancel(); }; progressWindow.Show(); var queryStartTime = DateTime.UtcNow.Ticks; try { var results = new List<KeyValuePair<string, FacetResult>>(); var hasMoreResults = true; var fetchedResults = 0; while (hasMoreResults) { var queryFacetsTask = DatabaseCommands.GetFacetsAsync(IndexName, new IndexQuery() {Query = FilterDoc.Text}, AggregationQuery.GetFacets(facets), fetchedResults, 256); await TaskEx.WhenAny( queryFacetsTask, TaskEx.Delay(int.MaxValue, cancelationTokenSource.Token)); if (cancelationTokenSource.IsCancellationRequested) { return; } var facetResults = await queryFacetsTask; results.AddRange(facetResults.Results); fetchedResults += facetResults.Results.Select(r => r.Value.Values.Count).Max(); var remainingResults = facetResults.Results.Select(r => r.Value.RemainingTermsCount).Max(); var totalResults = fetchedResults + remainingResults; progressWindow.Progress = (int) ((fetchedResults/(double) totalResults)*100); hasMoreResults = remainingResults > 0; } var rowsByKey = new Dictionary<string, ReportRow>(); var rows = new List<ReportRow>(); foreach (var facetResult in results) { var calculatedField = facetResult.Key.Split('-')[1]; foreach (var facetValue in facetResult.Value.Values) { ReportRow result; if (!rowsByKey.TryGetValue(facetValue.Range, out result)) { result = new ReportRow {Key = facetValue.Range}; rowsByKey.Add(result.Key, result); rows.Add(result); } foreach ( var valueCalculation in ValueCalculations.Where(v => v.Field == calculatedField)) { var value = facetValue.GetAggregation(valueCalculation.SummaryMode); if (value.HasValue) { result.Values.Add(valueCalculation.Header, facetValue.GetAggregation(valueCalculation.SummaryMode) ?? 0); } } } } var columns = new ColumnsModel(); columns.Columns.Add(new ColumnDefinition() { Header = "Key", Binding = "Key" }); columns.Columns.AddRange( ValueCalculations.Select( k => new ColumnDefinition() {Header = k.Header, Binding = "Values[" + k.Header + "]"})); Results.AddRange(rows); ResultColumns = columns; var queryEndTime = DateTime.UtcNow.Ticks; ExecutionElapsedTime.Value = new TimeSpan(queryEndTime - queryStartTime); } catch (AggregateException ex) { var badRequest = ex.ExtractSingleInnerException() as BadRequestException; if (badRequest != null) { QueryErrorMessage.Value = badRequest.Message; IsErrorVisible.Value = true; } else { throw; } } catch (TaskCanceledException) { } finally { // there's a bug in silverlight where if a ChildWindow gets closed too soon after it's opened, it leaves the UI // disabled; so delay closing the window by a few milliseconds TaskEx.Delay(TimeSpan.FromMilliseconds(350)) .ContinueOnSuccessInTheUIThread(progressWindow.Close); } }
//Evento de envio a sunat de la comunicacion de baja. private void btnSunat_Click(object sender, RoutedEventArgs e) { string comentario = ""; string procesados = ""; string ya_enviados = ""; string no_enviados_motivo = ""; int cantidad_seleccionados = 0; try { List <ReporteResumen> seleccionados = new List <ReporteResumen>(); //Recorrer la lista para obtener los seleccionados. foreach (var item in lista_reporte) { if (item.Check == true) { //Si el item fue seleccionado cantidad_seleccionados++; if (item.Ticket != "" || item.Comentario != "") { ya_enviados += " -> " + item.Archivo + " \n"; } else { bool validar_motivos_baja = new clsEntityVoidedDocuments(localDB).cs_pxValidarMotivosDeBajaEnItems(item.Id); if (validar_motivos_baja == true) { seleccionados.Add(item); } else { no_enviados_motivo += " -> " + item.Archivo + " \n"; } } } } //SI existen documentos seleccionados. if (cantidad_seleccionados > 0) { //Mostrar resumen de comprobantes procesados y no procesados. comentario += ya_enviados + no_enviados_motivo; if (comentario.Length > 0) { comentario = ""; if (ya_enviados.Length > 0) { comentario += "Ya enviadas:\n" + ya_enviados; } if (no_enviados_motivo.Length > 0) { comentario += "Sin motivos de baja" + no_enviados_motivo; } System.Windows.MessageBox.Show("Los siguientes resumen de reversiones no seran procesados.\n" + comentario, "Mensaje", MessageBoxButton.OK, MessageBoxImage.Information); } //Si existen items selccionados. if (seleccionados.Count > 0) { //string resultado = string.Empty; ProgressDialogResult result = ProgressWindow.Execute(VentanaPrincipal, "Procesando...", () => { procesados = sendToSunat(seleccionados); }); refrescarGrilla(); } if (procesados.Length > 0) { CustomDialogWindow obj = new CustomDialogWindow(); obj.AdditionalDetailsText = "Los siguientes comprobantes fueron enviados correctamente:\n" + procesados; obj.Buttons = CustomDialogButtons.OK; obj.Caption = "Mensaje"; obj.DefaultButton = CustomDialogResults.OK; // obj.FooterIcon = CustomDialogIcons.Shield; // obj.FooterText = "This is a secure program"; obj.InstructionHeading = "Documentos enviados"; obj.InstructionIcon = CustomDialogIcons.Information; obj.InstructionText = "Los documentos se enviaron correctamente a SUNAT."; CustomDialogResults objResults = obj.Show(); // System.Windows.MessageBox.Show("Las siguientes comunicaciones de baja fueron procesadas correctamente.\n" + procesados, "Mensaje", MessageBoxButton.OK, MessageBoxImage.Information); } } else { System.Windows.MessageBox.Show("Seleccione los items a procesar.", "Mensaje", MessageBoxButton.OK, MessageBoxImage.Exclamation); } } catch (Exception ex) { clsBaseMensaje.cs_pxMsgEr("ERR15", ex.Message); clsBaseLog.cs_pxRegistarAdd("EnvioRA" + ex.ToString()); } }
/// <summary> /// Called when the installer is downloaded /// </summary> /// <param name="sender">not used.</param> /// <param name="e">used to determine if the download was successful.</param> private void OnWebDownloadClientDownloadFileCompleted(object sender, AsyncCompletedEventArgs e) { if (e.Error != null) { UIFactory.ShowDownloadErrorMessage(e.Error.Message, _appCastUrl); ProgressWindow.ForceClose(); return; } // test the item for DSA signature bool isDSAOk = false; if (!e.Cancelled && e.Error == null) { ReportDiagnosticMessage("Finished downloading file to: " + _downloadTempFileName); // report ReportDiagnosticMessage("Performing DSA check"); // get the assembly if (File.Exists(_downloadTempFileName)) { // check if the file was downloaded successfully String absolutePath = Path.GetFullPath(_downloadTempFileName); if (!File.Exists(absolutePath)) { throw new FileNotFoundException(); } if (UserWindow.CurrentItem.DSASignature == null) { isDSAOk = true; // REVIEW. The correct logic, seems to me, is that if the existing, running version of the app //had no DSA, and the appcast didn't specify one, then it's ok that the one we've just //downloaded doesn't either. This may be just checking that the appcast didn't specify one. Is //that really enough? If someone can change what gets downloaded, can't they also change the appcast? } else { // get the assembly reference from which we start the update progress // only from this trusted assembly the public key can be used Assembly refassembly = Assembly.GetEntryAssembly(); if (refassembly != null) { // Check if we found the public key in our entry assembly if (NetSparkleDSAVerificator.ExistsPublicKey("NetSparkle_DSA.pub")) { // check the DSA Code and modify the back color NetSparkleDSAVerificator dsaVerifier = new NetSparkleDSAVerificator("NetSparkle_DSA.pub"); isDSAOk = dsaVerifier.VerifyDSASignature(UserWindow.CurrentItem.DSASignature, _downloadTempFileName); } } } } } if (EnableSilentMode) { OnProgressWindowInstallAndRelaunch(this, new EventArgs()); } if (ProgressWindow != null) { ProgressWindow.ChangeDownloadState(isDSAOk); } }
/** * PATCH FILE FORMAT * * - String "NSMBe4 Exported Patch" * - Some files (see below) * - byte 0 * * STRUCTURE OF A FILE * - byte 1 * - File name as a string * - File ID as ushort (to check for different versions, only gives a warning) * - File length as uint * - File contents as byte[] */ private void patchExport_Click(object sender, EventArgs e) { //output to show to the user bool differentRomsWarning = false; // tells if we have shown the warning int fileCount = 0; //load the original rom MessageBox.Show(LanguageManager.Get("Patch", "SelectROM"), LanguageManager.Get("Patch", "Export"), MessageBoxButtons.OK, MessageBoxIcon.Information); if (openROMDialog.ShowDialog() == DialogResult.Cancel) return; NitroROMFilesystem origROM = new NitroROMFilesystem(openROMDialog.FileName); //open the output patch MessageBox.Show(LanguageManager.Get("Patch", "SelectLocation"), LanguageManager.Get("Patch", "Export"), MessageBoxButtons.OK, MessageBoxIcon.Information); if (savePatchDialog.ShowDialog() == DialogResult.Cancel) return; FileStream fs = new FileStream(savePatchDialog.FileName, FileMode.Create, FileAccess.Write, FileShare.None); BinaryWriter bw = new BinaryWriter(fs); bw.Write("NSMBe4 Exported Patch"); //DO THE PATCH!! ProgressWindow progress = new ProgressWindow(LanguageManager.Get("Patch", "ExportProgressTitle")); progress.Show(); progress.SetMax(ROM.FS.allFiles.Count); int progVal = 0; MessageBox.Show(LanguageManager.Get("Patch", "StartingPatch"), LanguageManager.Get("Patch", "Export"), MessageBoxButtons.OK, MessageBoxIcon.Information); foreach (NSMBe4.DSFileSystem.File f in ROM.FS.allFiles) { if (f.isSystemFile) continue; Console.Out.WriteLine("Checking " + f.name); progress.SetCurrentAction(string.Format(LanguageManager.Get("Patch", "ComparingFile"), f.name)); NSMBe4.DSFileSystem.File orig = origROM.getFileByName(f.name); //check same version if(!differentRomsWarning && f.id != orig.id) { if (MessageBox.Show(LanguageManager.Get("Patch", "ExportDiffVersions"), LanguageManager.Get("General", "Warning"), MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes) differentRomsWarning = true; else { fs.Close(); return; } } byte[] oldFile = orig.getContents(); byte[] newFile = f.getContents(); if (!arrayEqual(oldFile, newFile)) { //include file in patch string fileName = orig.name; Console.Out.WriteLine("Including: " + fileName); progress.WriteLine(string.Format(LanguageManager.Get("Patch", "IncludedFile"), fileName)); fileCount++; bw.Write((byte)1); bw.Write(fileName); bw.Write((ushort)f.id); bw.Write((uint)newFile.Length); bw.Write(newFile, 0, newFile.Length); } progress.setValue(++progVal); } bw.Write((byte)0); bw.Close(); origROM.close(); progress.SetCurrentAction(""); progress.WriteLine(string.Format(LanguageManager.Get("Patch", "ExportReady"), fileCount)); }
public void importData(String inFileName) { string inputBuffer, colValue, MatchCommand = "", curMatchCommand = "", curLastUpdateDateIn = ""; string[] inputCols = null, inputColNames = null, inputKeys = null, curImportDataMatchMsg = { "", "", "", "" }; char[] tabDelim = new char[] { '\t' }; char[] singleQuoteDelim = new char[] { '\'' }; DateTime curLastUpdateDate = new DateTime(), curDateValue = new DateTime(); Boolean rowFound = false; bool curImportConfirmMsg = true; int curInputLineCount = 0; int idx = 0, rowsRead = 0, rowsfound = 0, rowsAdded = 0, rowsUpdated = 0, rowsSkipped = 0; StringBuilder stmtSelect = new StringBuilder( "" ); StringBuilder stmtWhere = new StringBuilder( "" ); StringBuilder stmtInsert = new StringBuilder( "" ); StringBuilder stmtData = new StringBuilder( "" ); StreamReader myReader = null; SqlCeCommand sqlStmt = null; SqlCeConnection myDbConn = null; DataTable curDataTable = null; myProgressInfo = new ProgressWindow(); ArrayList curFileList = new ArrayList(); if ( inFileName == null ) { curFileList = getImportFileList(); try { mySanctionNum = Properties.Settings.Default.AppSanctionNum; if ( mySanctionNum == null ) { mySanctionNum = ""; } else { if ( mySanctionNum.Length < 6 ) { mySanctionNum = ""; } } } catch { mySanctionNum = ""; } } else { curFileList.Add( inFileName ); mySanctionNum = ""; } if (curFileList.Count > 0) { DialogResult msgResp = MessageBox.Show( "Do you want a confirmation dialog for each successful data type imported?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1 ); if (msgResp == DialogResult.Yes) { curImportConfirmMsg = true; } else { curImportConfirmMsg = false; } try { myDbConn = new global::System.Data.SqlServerCe.SqlCeConnection(); myDbConn.ConnectionString = Properties.Settings.Default.waterskiConnectionStringApp; myDbConn.Open(); foreach (String curFileName in curFileList) { myReader = getImportFile( curFileName ); if (myReader != null) { curInputLineCount = 0; while (( inputBuffer = myReader.ReadLine() ) != null) { curInputLineCount++; myProgressInfo.setProgressValue( curInputLineCount ); rowFound = false; inputCols = inputBuffer.Split( tabDelim ); if (inputCols[0].ToLower().Equals( "table:" ) || inputCols[0].ToLower().Equals( "tablename:" )) { //Display statistics when another table entry is found if (myTableName != null) { if (curImportConfirmMsg) { MessageBox.Show( "Info: Import data processed for " + myTableName + "\nRows Read: " + rowsRead + "\nRows Added: " + rowsAdded + "\nRows Matched: " + rowsfound + "\nRows Updated: " + rowsUpdated + "\nRows Skipped: " + rowsSkipped ); rowsRead = 0; rowsfound = 0; rowsAdded = 0; rowsUpdated = 0; rowsSkipped = 0; } } //Check for table name and assume all subsequent records are for this table TableName = inputCols[1]; myProgressInfo.setProgessMsg( "Processing " + TableName ); myProgressInfo.Refresh(); inputColNames = null; inputKeys = getTableKeys( TableName ); } else if (inputColNames == null) { //Column names are required and must preceed the data rows inputColNames = new string[inputCols.Length]; for (idx = 0; idx < inputCols.Length; idx++) { inputColNames[idx] = inputCols[idx]; } } else { #region Process data rows for table and columns on input file //Process data rows. Table name and column names are required //before data rows can be processed if (myTableName == null) { MessageBox.Show( "Error: Table name not provide. Unable to process import file." ); break; } else if (inputColNames == null) { MessageBox.Show( "Error: Column definitions not provide. Unable to process import file." ); break; } else { rowsRead++; stmtSelect = new StringBuilder( "" ); stmtWhere = new StringBuilder( "" ); sqlStmt = myDbConn.CreateCommand(); if (inputKeys != null) { //Use update date if available curLastUpdateDateIn = findColValue( "LastUpdateDate", inputColNames, inputCols ); if (curLastUpdateDateIn == null) curLastUpdateDateIn = ""; #region Identify key columns if available //Use key column data items to see if input row already exists on database foreach (string keyName in inputKeys) { colValue = findColValue( keyName, inputColNames, inputCols ); if (colValue == null) colValue = ""; if (stmtSelect.Length > 1) { stmtSelect.Append( ", " + keyName ); stmtWhere.Append( " AND " + keyName + " = '" + colValue + "'" ); } else { stmtSelect.Append( "Select " ); if (curLastUpdateDateIn.Length > 0) { stmtSelect.Append( "LastUpdateDate, " ); } stmtSelect.Append( keyName ); stmtWhere.Append( " Where " + keyName + " = '" + colValue + "'" ); } } try { curMatchCommand = ""; curDataTable = getData( stmtSelect.ToString() + " From " + myTableName + stmtWhere.ToString() ); if (curDataTable.Rows.Count > 0) { rowFound = true; rowsfound++; if (!( MatchCommand.ToLower().Equals( "skipall" ) )) { if (curLastUpdateDateIn.Length > 0) { try { curLastUpdateDate = (DateTime)curDataTable.Rows[0]["LastUpdateDate"]; curDateValue = Convert.ToDateTime( curLastUpdateDateIn ); if (curDateValue > curLastUpdateDate) { curMatchCommand = "Update"; } else { curMatchCommand = "Skip"; } } catch { curMatchCommand = "Update"; curLastUpdateDate = Convert.ToDateTime( "01/01/2000" ); } } } } } catch (Exception ex) { String ExcpMsg = ex.Message; MessageBox.Show( "Error: Checking " + myTableName + " for import data" + "\n\nError: " + ExcpMsg ); return; } #endregion } stmtInsert = new StringBuilder( "" ); stmtData = new StringBuilder( "" ); if (rowFound) { #region Show information if input data found on database //Show information if input data found on database //Skip display if previoius display specfied to process all records the same if (MatchCommand.Length < 2) { if (curMatchCommand.Equals( "" ) || curMatchCommand.ToLower().Equals( "update" )) { curImportDataMatchMsg[0] = "Table: " + myTableName; curImportDataMatchMsg[1] = stmtWhere.ToString(); if (curMatchCommand.ToLower().Equals( "update" )) { curImportDataMatchMsg[2] = "Current record date = " + curLastUpdateDate.ToString(); curImportDataMatchMsg[3] = " Import record date = " + curLastUpdateDateIn; } else { curImportDataMatchMsg[2] = ""; curImportDataMatchMsg[3] = ""; } MatchDialog.ImportKeyDataMultiLine = curImportDataMatchMsg; MatchDialog.MatchCommand = MatchCommand; if (MatchDialog.ShowDialog() == DialogResult.OK) { MatchCommand = MatchDialog.MatchCommand; } } } if (curMatchCommand.Equals( "skip" )) { rowsSkipped++; //Re-initialize dialog response unless specified to process rows if (MatchCommand.ToLower().Equals( "skip" )) { MatchCommand = ""; } } else { if (MatchCommand.ToLower().Equals( "update" ) || MatchCommand.ToLower().Equals( "updateall" )) { //Build update command with input record if specified idx = 0; foreach (string colName in inputColNames) { if (inputKeys.Contains( colName ) || colName.ToLower().Equals( "pk" )) { } else if (colName.Equals( "TimeInTol1" ) || colName.Equals( "TimeInTol2" ) || colName.Equals( "TimeInTol3" ) || colName.Equals( "BoatSplitTimeTol" ) || colName.Equals( "BoatSplitTime2Tol" ) || colName.Equals( "BoatEndTimeTol" ) || ( colName.Equals( "Pass1VideoUrl" ) && myTableName.Equals( "TrickScore" ) ) || ( colName.Equals( "Pass2VideoUrl" ) && myTableName.Equals( "TrickScore" ) ) ) { } else { if (stmtData.Length > 1) { stmtData.Append( ", [" + colName + "] = " ); } else { stmtData.Append( "[" + colName + "] = " ); } if (inputCols[idx].Length > 0) { String tempValue = stringReplace( inputCols[idx], singleQuoteDelim, "''" ); stmtData.Append( "'" + tempValue + "'" ); } else { if (inputKeys.Contains( colName )) { stmtData.Append( " ''" ); } else { stmtData.Append( " null" ); } } } idx++; } try { //Update database with input record if specified //Delete detail if event scores which assumes the detail will also be imported if (myTableName.ToLower().Equals( "slalomscore" )) { sqlStmt.CommandText = "Delete SlalomRecap " + stmtWhere.ToString(); int rowsDeleted = sqlStmt.ExecuteNonQuery(); } else if (myTableName.ToLower().Equals( "trickscore" )) { sqlStmt.CommandText = "Delete TrickPass " + stmtWhere.ToString(); int rowsDeleted = sqlStmt.ExecuteNonQuery(); } else if (myTableName.ToLower().Equals( "jumpscore" )) { sqlStmt.CommandText = "Delete JumpRecap " + stmtWhere.ToString(); int rowsDeleted = sqlStmt.ExecuteNonQuery(); } sqlStmt.CommandText = "Update " + myTableName + " set " + stmtData.ToString() + stmtWhere.ToString(); int rowsProc = sqlStmt.ExecuteNonQuery(); rowsUpdated++; } catch (Exception ex) { String ExcpMsg = ex.Message; if (sqlStmt != null) { ExcpMsg += "\n" + sqlStmt.CommandText; } MessageBox.Show( "Error: Adding import data to " + myTableName + "\n\nError: " + ExcpMsg ); return; } //Re-initialize dialog response unless specified to process rows if (MatchCommand.ToLower().Equals( "update" )) { MatchCommand = ""; } } else { rowsSkipped++; //Re-initialize dialog response unless specified to process rows if (MatchCommand.ToLower().Equals( "skip" )) { MatchCommand = ""; } } } #endregion } else { #region New data identified and will be added //Database record does not exist therefore data is added to database //Build insert command idx = 0; foreach (string colName in inputColNames) { if (colName.ToLower().Equals( "pk" ) || colName.Equals( "TimeInTol1" ) || colName.Equals( "TimeInTol2" ) || colName.Equals( "TimeInTol3" ) || colName.Equals( "BoatSplitTimeTol" ) || colName.Equals( "BoatSplitTime2Tol" ) || colName.Equals( "BoatEndTimeTol" ) || ( colName.Equals( "Pass1VideoUrl" ) && myTableName.Equals( "TrickScore" ) ) || ( colName.Equals( "Pass2VideoUrl" ) && myTableName.Equals( "TrickScore" ) ) ) { } else { if (stmtInsert.Length > 1) { stmtInsert.Append( ", [" + colName + "]" ); if (inputCols[idx].Length > 0) { String tempValue = stringReplace( inputCols[idx], singleQuoteDelim, "''" ); stmtData.Append( ", '" + tempValue + "'" ); } else { if (inputKeys.Contains( colName )) { stmtData.Append( ", ''" ); } else { stmtData.Append( ", null" ); } } } else { stmtInsert.Append( "[" + colName + "]" ); if (inputCols[idx].Length > 0) { String tempValue = stringReplace( inputCols[idx], singleQuoteDelim, "''" ); stmtData.Append( "'" + tempValue + "'" ); } else { if (inputKeys.Contains( colName )) { stmtData.Append( "''" ); } else { stmtData.Append( "null" ); } } } } idx++; } try { sqlStmt.CommandText = "Insert " + myTableName + " (" + stmtInsert.ToString() + ") Values (" + stmtData.ToString() + ")"; int rowsProc = sqlStmt.ExecuteNonQuery(); rowsAdded++; } catch (Exception ex) { rowsSkipped++; String ExcpMsg = ex.Message; if (sqlStmt != null) { ExcpMsg += "\n" + sqlStmt.CommandText; } MessageBox.Show( "Error: Adding import data to " + myTableName + "\n\nError: " + ExcpMsg ); } #endregion } } #endregion } } if (inFileName == null) { if (curImportConfirmMsg) { MessageBox.Show( "Info: Import data processed for " + myTableName + "\nRows Read: " + rowsRead + "\nRows Added: " + rowsAdded + "\nRows Matched: " + rowsfound + "\nRows Updated: " + rowsUpdated + "\nRows Skipped: " + rowsSkipped ); } else { MessageBox.Show( "Info: Total import data processed" + "\nRows Read: " + rowsRead + "\nRows Added: " + rowsAdded + "\nRows Matched: " + rowsfound + "\nRows Updated: " + rowsUpdated + "\nRows Skipped: " + rowsSkipped ); } rowsRead = 0; rowsAdded = 0; rowsfound = 0; rowsUpdated = 0; rowsSkipped = 0; } } } } catch (Exception ex) { String ExcpMsg = ex.Message; if (sqlStmt != null) { ExcpMsg += "\n" + sqlStmt.CommandText; } MessageBox.Show( "Error: Performing SQL operations" + "\n\nError: " + ExcpMsg ); } finally { myDbConn.Close(); myReader.Close(); myReader.Dispose(); } myProgressInfo.Close(); } }
void start() { fileDialog = new OpenFileDialog(); fileDialog.Title = "Вибиріть файл для " + choice + ":"; fileDialog.ShowDialog(); if (fileDialog.FileName != "") { trdProcess = new Thread(new ThreadStart(this.ThreadTaskProcesing)); trdProcess.IsBackground = true; trdProcess.Start(); progressW = new ProgressWindow(); progressW.Show(); } // textBox1.Text = "" + ArchivingLibrary.BWT.pr; }
public void ImportGIF(string file) { Action <object, DoWorkEventArgs> work = (object sender, DoWorkEventArgs e) => { GifDecoder decoder = new GifDecoder(); decoder.Read(file, null); e.Result = decoder; }; Action <object, RunWorkerCompletedEventArgs> completed = (object sender, RunWorkerCompletedEventArgs e) => { GifDecoder decoder = e.Result as GifDecoder; string s = Path.GetFileNameWithoutExtension(file); PAT0Node p = CreateResource <PAT0Node>(s); p._loop = true; p.CreateEntry(); PAT0TextureNode textureNode = p.Children[0].Children[0] as PAT0TextureNode; PAT0TextureEntryNode entry = textureNode.Children[0] as PAT0TextureEntryNode; //Get the number of images in the file int frames = decoder.GetFrameCount(); //The framecount will be created by adding up each image delay. float frameCount = 0; bool resized = false; int w = 0, h = 0; Action <int, int> onResized = (newW, newH) => { if (resized != true) { w = newW; h = newH; resized = true; } }; using (TextureConverterDialog dlg = new TextureConverterDialog()) { using (ProgressWindow progress = new ProgressWindow(RootNode._mainForm, "GIF to PAT0 converter", "Converting, please wait...", true)) { Bitmap prev = null; progress.Begin(0, frames, 0); for (int i = 0; i < frames; i++, entry = new PAT0TextureEntryNode()) { if (progress.Cancelled) { break; } string name = s + "." + i; dlg.ImageSource = name + "."; using (Bitmap img = (Bitmap)decoder.GetFrame(i)) { if (i == 0) { dlg.LoadImages(img.Copy()); dlg.Resized += onResized; if (dlg.ShowDialog(null, this) != DialogResult.OK) { return; } textureNode._hasTex = dlg.TextureData != null; textureNode._hasPlt = dlg.PaletteData != null; prev = img.Copy(); } else { //Draw the current image over the previous //This is because some GIFs use pixels of the previous frame //in order to compress the overall image data using (Graphics graphics = Graphics.FromImage(prev)) { graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; graphics.CompositingQuality = CompositingQuality.HighQuality; graphics.CompositingMode = CompositingMode.SourceOver; graphics.SmoothingMode = SmoothingMode.HighQuality; graphics.DrawImage(img, 0, 0, prev.Width, prev.Height); } dlg.LoadImages(prev.Copy()); if (resized) { dlg.ResizeImage(w, h); } else { dlg.UpdatePreview(); } dlg.EncodeSource(); textureNode.AddChild(entry); } } entry._frame = (float)Math.Round(frameCount, 2); frameCount += decoder.GetDelay(i) / 1000.0f * 60.0f; if (textureNode._hasTex) { entry.Texture = name; } if (textureNode._hasPlt) { entry.Palette = name; } progress.Update(progress.CurrentValue + 1); } progress.Finish(); if (prev != null) { prev.Dispose(); } } } p._numFrames = (ushort)(frameCount + 0.5f); }; using (BackgroundWorker b = new BackgroundWorker()) { b.DoWork += new DoWorkEventHandler(work); b.RunWorkerCompleted += new RunWorkerCompletedEventHandler(completed); b.RunWorkerAsync(); } }
public bool execCommandFile() { bool curReturn = true; int curDelimIdx; decimal curDatabaseVersion = 9999.00M; String inputBuffer, curSqlStmt = ""; StringBuilder curInputCmd = new StringBuilder( "" ); ImportData curImportData = new ImportData(); StreamReader myReader; myProgressInfo = new ProgressWindow(); #region Process all commands in the input file myReader = getImportFile(); if ( myReader != null ) { int curInputLineCount = 0; try { while ( ( inputBuffer = myReader.ReadLine() ) != null ) { curInputLineCount++; myProgressInfo.setProgressValue( curInputLineCount ); if ( inputBuffer.TrimStart( ' ' ).StartsWith( "## " ) ) { curDatabaseVersion = Convert.ToDecimal( inputBuffer.Substring( 4 ) ); } if ( inputBuffer.TrimStart( ' ' ).StartsWith( "//" ) || inputBuffer.TrimStart( ' ' ).StartsWith( "##" ) ) { } else { if ( curDatabaseVersion > myDatabaseVersion ) { curDelimIdx = inputBuffer.IndexOf( ';' ); if ( curDelimIdx >= 0 ) { if ( curDelimIdx > 0 ) { curInputCmd.Append( inputBuffer.Substring( 0, curDelimIdx ) ); } curSqlStmt = curInputCmd.ToString(); curSqlStmt.TrimStart( ' ' ); if ( curSqlStmt.Trim().ToUpper().StartsWith( "DROP " ) ) { execDropTable( replaceLinefeed( curSqlStmt ) ); } else if ( curSqlStmt.Trim().ToUpper().StartsWith( "CREATE " ) ) { execCreateTable( replaceLinefeed( curSqlStmt ) ); curInputCmd = new StringBuilder( "" ); } else { execSchemaCmd( replaceLinefeed( curSqlStmt ) ); } curInputCmd = new StringBuilder( "" ); } else { curInputCmd.Append( inputBuffer ); } } } } curSqlStmt = ""; System.Data.SqlServerCe.SqlCeEngine mySqlEngine = new SqlCeEngine(); mySqlEngine.LocalConnectionString = Properties.Settings.Default.waterskiConnectionStringApp; mySqlEngine.Shrink(); } catch ( Exception ex ) { curReturn = false; String ExcpMsg = ex.Message; if ( mySqlStmt != null ) { ExcpMsg += "\n" + curSqlStmt; } MessageBox.Show( "Error attempting to update database schema" + "\n\nError: " + ExcpMsg ); } } #endregion myProgressInfo.Close(); return curReturn; }
/// <summary>Updates the templates.</summary> private void UpdateTemplates() { var window = new ProgressWindow(); try { int maxTemplates; if (!int.TryParse(this.MaxTemplates.Text, out maxTemplates)) { MessageBox.Show("Max Suggestions must be a number."); return; } int occurances; if (!int.TryParse(this.Occurances.Text, out occurances)) { MessageBox.Show("Occurances must be a number."); return; } int minPercentage; if (!int.TryParse(this.MinPercentage.Text, out minPercentage)) { MessageBox.Show("Minimum Percentage must be a number."); return; } window.Show(); var builder = new AutoTemplateBuilder(); builder.Process(window.ProgressIndicator, maxTemplates, occurances, minPercentage); AutoTemplateManager.Invalidate(); this.RefreshInfo(); } finally { if (window.Visible) { window.Close(); } } }