void ShowLoadingProgress(DeviceChannelControl channControl, string title) { ProgressView progress = new ProgressView("Loading .."); channControl.Content = progress; channControl.Title = title; }
void ShowLoadingProgress(DeviceEngineControl engineControl, string title) { ProgressView progress = new ProgressView("Loading .."); engineControl.Content = progress; engineControl.Title = title; }
public MainWindow() { InitializeComponent(); Title = Title + $" {typeof(MainWindow).Assembly.GetName().Version}"; DependencyContainer.ComposeParts(this); #if DEBUG Log.Info("Running in debug mode"); #else Logger.Visibility = Visibility.Collapsed; #endif var dispatcher = Dispatcher.CurrentDispatcher; Func <(Action <string> show, Action <string> updateText, Action close)> createProgressingViewFunc = () => { var view = new ProgressView(); view.Owner = this; return(text => { view.TextToShow.Text = text; view.ShowDialog(); }, txt => { if (dispatcher.CheckAccess()) { view.TextToShow.Text = txt; } else { dispatcher.BeginInvoke((Action)(() => { view.TextToShow.Text = txt; })); } }, () => view.Close()); }; Action <Action <string, string, string> > createLoginViewFunc = loginAction => { var view = new LoginView { Owner = this }; var loginVm = new LoginViewModel(() => view.Close(), loginAction); view.DataContext = loginVm; view.ShowDialog(); }; _vm = new MainWindowsViewModel(createLoginViewFunc, createProgressingViewFunc); _vm.SetParentWindow(this); DataContext = _vm; Closing += OnClosing; Loaded += MainWindow_Loaded; Height = SystemParameters.PrimaryScreenHeight * 0.70; Width = Height * 1.5; }
private void ExtractClicked(object sender, RoutedEventArgs e) { DirectoryInfo root = new DirectoryInfo(Path.Text); root.Create(); // ensure that the folder exists List <ProgressTask> tasks = new List <ProgressTask>(); if (TicketCheckbox.IsChecked == true) { DirectoryInfo ticketDir = HACGUIKeyset.GetTicketsDirectory(Preferences.Current.DefaultConsoleName); // TODO: load console name from continuous location List <string> foundTickets = new List <string>(); foreach (Nca nca in SelectedNcas.Select(n => n.Nca)) { if (nca.Header.HasRightsId) { string rightsId = nca.Header.RightsId.ToHexString(); string ticketFileName = rightsId + ".tik"; FileInfo sourceTikFileInfo = ticketDir.GetFile(ticketFileName); if (sourceTikFileInfo.Exists) { FileInfo destinationTikFileInfo = root.GetFile(ticketFileName); if (!foundTickets.Contains(rightsId)) { foundTickets.Add(rightsId); destinationTikFileInfo.CreateAndClose(); LocalFile sourceTikFile = new LocalFile(sourceTikFileInfo.FullName, OpenMode.Read); LocalFile destinationTikFile = new LocalFile(destinationTikFileInfo.FullName, OpenMode.Write); destinationTikFile.SetSize(sourceTikFile.GetSize()); tasks.Add(new CopyTask($"Copying {ticketFileName}...", new FileStorage(sourceTikFile), new FileStorage(destinationTikFile))); } } } } } foreach (SwitchFsNca nca in SelectedNcas) { FileInfo destinationNcaFileInfo = root.GetFile(nca.Filename); destinationNcaFileInfo.CreateAndClose(); LocalFile destinationNcaFile = new LocalFile(destinationNcaFileInfo.FullName, OpenMode.Write); IStorage source = nca.Nca.BaseStorage; tasks.Add(new RunTask($"Allocating space for {nca.Filename}...", new Task(() => { destinationNcaFile.SetSize(source.GetSize()); }))); tasks.Add(new CopyTask($"Copying {nca.Filename}...", source, new FileStorage(destinationNcaFile))); } ProgressView view = new ProgressView(tasks); NavigationWindow window = new NavigationWindow { ShowsNavigationUI = false // get rid of the t r a s h }; window.Navigate(view); TaskManagerPage.Current.Queue.Submit(tasks); window.Owner = Window.GetWindow(this); window.ShowDialog(); }
public static Task ProgressbarShow(this MetroWindow @object, Func <Task> action) { return(Task.Run(() => { @object.Dispatcher.Invoke(() => { var progress = new ProgressView { Owner = @object, Left = @object.Left / 2, Width = @object.Width / 2, Top = @object.Top / 2, Height = @object.Height / 2 }; progress.Loaded += (s, e) => { action().ContinueWith(task => { progress.Dispatcher.Invoke(() => { progress.Close(); }); }); }; progress.ShowDialog(); }); })); }
public async void OnEdit() { var ids = View.SelectedBotIds; if (!ids.Any()) { _mbs.ShowInformation("No Bots selected"); return; } var botsToEdit = _bots.Where(x => ids.Contains(x.Id)).ToList(); if (botsToEdit.Any(x => x.Type != "Bot::SingleBot")) { _mbs.ShowError("Sorry, Bulk Edit only works for Simple Bots, not advanced."); return; } var dlg = new EditDialog.EditDialog(botsToEdit.Count); EditDto editData = new EditDto(); dlg.EditDto = editData; var dr = dlg.ShowDialog(View); if (dr == DialogResult.OK) { var loadingView = new ProgressView(botsToEdit, editData, _keys, _logger); loadingView.ShowDialog(View); _logger.LogInformation("Refreshing Bots"); await RefreshBots(); } }
void ReleaseDesignerOutlets() { if (btnNext != null) { btnNext.Dispose(); btnNext = null; } if (ProgressView != null) { ProgressView.Dispose(); ProgressView = null; } if (txtDescription != null) { txtDescription.Dispose(); txtDescription = null; } if (txtPayment != null) { txtPayment.Dispose(); txtPayment = null; } if (txtTitle != null) { txtTitle.Dispose(); txtTitle = null; } }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Set our view from the "main" layout resource SetContentView(Resource.Layout.main); topLayer = FindViewById <FrameLayout> (Resource.Id.top_layer); handler = new Handler(); if (!Utils.IsKitKatWithStepCounter(PackageManager)) { //no step detector detected :( var counter_layout = FindViewById <FrameLayout> (Resource.Id.counter_layout); var no_sensor = FindViewById <LinearLayout> (Resource.Id.no_sensor_box); var sensor_image = FindViewById <ImageView> (Resource.Id.no_sensor_image); sensor_image.SetImageResource(Resource.Drawable.ic_unsupporteddevice); no_sensor.Visibility = Android.Views.ViewStates.Visible; counter_layout.Visibility = Android.Views.ViewStates.Gone; this.Title = Resources.GetString(Resource.String.app_name); handler.PostDelayed(() => AnimateTopLayer(0), 500); return; } stepCount = FindViewById <TextView> (Resource.Id.stepcount); calorieCount = FindViewById <TextView> (Resource.Id.calories); distance = FindViewById <TextView> (Resource.Id.distance); percentage = FindViewById <TextView> (Resource.Id.percentage); progressView = FindViewById <ProgressView> (Resource.Id.progressView); highScore = FindViewById <ImageView> (Resource.Id.high_score); calorieString = Resources.GetString(Resource.String.calories); distanceString = Resources.GetString(Helpers.Settings.UseKilometeres ? Resource.String.kilometeres : Resource.String.miles); percentString = Resources.GetString(Resource.String.percent_complete); completedString = Resources.GetString(Resource.String.completed); this.Title = Utils.DateString; handler.PostDelayed(() => UpdateUI(), 500); StartStepService(); //for testing /*stepCount.Clickable = true; * stepCount.Click += (object sender, EventArgs e) => { * if(binder != null) * { * //if(testSteps == 1) * // testSteps = (int)binder.StepService.StepsToday; * testSteps += 100; * if(testSteps > 10000) * testSteps += 1000; * //binder.StepService.AddSteps(testSteps); * * * HandlePropertyChanged (null, new System.ComponentModel.PropertyChangedEventArgs ("StepsToday")); * } * };*/ }
public void CreateView(DeviceViewArgs args, IUnityContainer container) { this.container = container; ProgressView progress = new ProgressView("Loading .."); if (this.content.Content is IDisposable) { var dis = this.content.Content as IDisposable; dis.Dispose(); } this.content.Content = progress; loadingDisp.Add(Load(args.nvtSession, args.odmSession, args.capabilities) .ObserveOnCurrentDispatcher() .Subscribe(analyticsArgs => { SectionAnalytics analyticsView = new SectionAnalytics(container); disposables.Add(analyticsView); analyticsView.Init(analyticsArgs); this.content.Content = analyticsView; }, err => { ErrorView errorView = new ErrorView(err); disposables.Add(errorView); this.content.Content = errorView; } )); }
void ReleaseDesignerOutlets() { if (AnimatedImageView != null) { AnimatedImageView.Dispose(); AnimatedImageView = null; } if (LivePhotoView != null) { LivePhotoView.Dispose(); LivePhotoView = null; } #if __TVOS__ if (LivePhotoPlayButton != null) { LivePhotoPlayButton.Dispose(); LivePhotoPlayButton = null; } #endif if (ImageView != null) { ImageView.Dispose(); ImageView = null; } if (Space != null) { Space.Dispose(); Space = null; } if (TrashButton != null) { TrashButton.Dispose(); TrashButton = null; } if (PlayButton != null) { PlayButton.Dispose(); PlayButton = null; } if (EditButton != null) { EditButton.Dispose(); EditButton = null; } if (ProgressView != null) { ProgressView.Dispose(); ProgressView = null; } }
public void StopShowingProgress() { if (ProgressView != null) { ProgressView.RemoveFromSuperview(); ProgressView.Dispose(); ProgressView = null; } }
private ProgressView CreateView() { GameObject go = GameObject.Instantiate(Resources.Load <GameObject>("Prefabs/ProgressView"), GameObject.FindGameObjectWithTag("ProgressView").transform); ProgressView pv = go.GetComponent <ProgressView>(); pv.gameObject.SetActive(false); return(pv); }
protected override void OnElementChanged(ElementChangedEventArgs <Xamarin.Forms.View> e) { base.OnElementChanged(e); if (Control == null) { // Instantiate the native control and assign it to the Control property with // the SetNativeControl method progressView = new RadialProgressView(getLabelText, RadialProgressViewStyle.Small); SetNativeControl(progressView); } if (e.OldElement != null) { // Unsubscribe from event handlers and cleanup any resources progressView.LabelTextDelegate = null; progressView.Dispose(); progressView = null; formsControl = null; } if (e.NewElement != null) { // Configure the control and subscribe to event handlers formsControl = e.NewElement as ProgressView; var percentValue = formsControl.PercentComplete / 100.0f; progressView.LabelTextDelegate = (arg) => formsControl.LabelText; progressView.Value = percentValue; progressView.Center = new PointF((float)formsControl.Bounds.Center.X, (float)formsControl.Bounds.Center.Y - 100); if (formsControl.LabelStyle.ToLower().Equals("failure")) { progressView.ProgressColor = formsControl.FailureProgressColor.ToUIColor(); RadialProgressLayer.BackCircleBackgroundColor = formsControl.FailureBackgroundColor.ToCGColor(); progressView.InitSubviews(); } else if (formsControl.LabelStyle.ToLower().Equals("complete")) { progressView.ProgressColor = formsControl.SuccessProgressColor.ToUIColor(); RadialProgressLayer.BackCircleBackgroundColor = formsControl.SuccessBackgroundColor.ToCGColor(); progressView.InitSubviews(); } else { progressView.ProgressColor = RadialProgressLayer.DefaultFillColor; RadialProgressLayer.BackCircleBackgroundColor = RadialProgressLayer.DefaultBackgroundColor; progressView.InitSubviews(); } } }
public void _progress_ProgressStarted(object sender, EventArgs e) { _progressView = new ProgressView(); _progressView.ViewModel.OperationName = "Starting..."; _progressView.ViewModel.ProgressText = ""; _progressView.ViewModel.ProgressPercentage = 0; _progressView.ViewModel.ProgressBarText = ""; ProgressReportingActive = true; ShowProgress = true; _progressView.Show(); }
private void ExtractClicked(object sender, RoutedEventArgs e) { MountType mountType = (MountType)ComboBox.SelectedItem; NcaFormatType sectionType = NcaFormatType.Romfs; switch (mountType) { case MountType.Exefs: sectionType = NcaFormatType.Pfs0; break; case MountType.Romfs: sectionType = NcaFormatType.Romfs; break; } IEnumerable <Tuple <SwitchFsNca, int> > list = Indexed[sectionType]; string path = Path.Text; TaskManagerPage.Current.Queue.Submit(new RunTask("Opening filesystems to extract...", new Task(() => { List <IFileSystem> filesystems = new List <IFileSystem>(); foreach (Tuple <SwitchFsNca, int> t in list) { SwitchFsNca nca = t.Item1; NcaFsHeader section = t.Item1.Nca.Header.GetFsHeader(t.Item2); int index = t.Item2; filesystems.Add(nca.OpenFileSystem(index, IntegrityCheckLevel.ErrorOnInvalid)); } filesystems.Reverse(); LayeredFileSystem lfs = new LayeredFileSystem(filesystems); ExtractFileSystemTask task = new ExtractFileSystemTask($"Extracting {sectionType}...", lfs, path); Dispatcher.InvokeAsync(() => { ProgressView view = new ProgressView(new List <ProgressTask>() { task }); NavigationWindow window = new NavigationWindow { ShowsNavigationUI = false // get rid of the t r a s h }; window.Navigate(view); TaskManagerPage.Current.Queue.Submit(task); window.Owner = Window.GetWindow(this); window.ShowDialog(); }); }))); }
private static void Initialize() { if (_initialized) { return; } _progressModels = new List <ProgressModel>(); _progressView = new ProgressView(); _initialized = true; }
/// <summary> /// Starts the analysis for the uploaded images. /// </summary> private void StartAnalysis() { if (ImageEntries == null || ImageEntries.Count == 0) { LaunchImageUploadPage(); } _totalNumberOfChips = ImageEntries.Sum(imageEntry => GetNumberOfChips(imageEntry.Image)); _numberOfProcessedChips = 0; _task = Task.Factory.StartNew(() => { try { foreach (var imageEntry in ImageEntries) { var categoryManagers = ImageAnalysisService.AnalyzeImage(imageEntry.Image, ChipAnalysisService.AnalyzeChip, _ct, () => { Interlocked.Increment(ref _numberOfProcessedChips); BeginInvokeOnMainThread(() => { ProgressView.SetProgress((float)_numberOfProcessedChips / _totalNumberOfChips, true); }); }) .ToList(); var observations = PostProcessingService.SelectObservations( categoryManagers, SharedConstants.DefaultIOUThreshold, NSUserDefaults.StandardUserDefaults.DoubleForKey( Constants.ConfidenceThresholdUserDefaultName), _ct) .ToList(); imageEntry.Observations = observations; } if (_ts.IsCancellationRequested) { return; } Task.Delay(Constants.DelayBeforeResults / _numberOfProcessedChips, _ct).Wait(_ct); BeginInvokeOnMainThread(LaunchResultsView); } catch (OperationCanceledException) { // ignored } }, _ct); }
protected override void OnElementChanged(ElementChangedEventArgs <Xamarin.Forms.View> e) { base.OnElementChanged(e); if (Control == null) { progressView = new RadialProgressView(Context, labelTextFunc: getLabelText, progressType: RadialProgressViewStyle.Small); progressView.SetPadding(20, 20, 20, 20); SetNativeControl(progressView); } if (e.OldElement != null) { // Unsubscribe from event handlers and cleanup any resources progressView.LabelTextDelegate = null; progressView.Dispose(); progressView = null; formsControl = null; } if (e.NewElement != null) { // Configure the control and subscribe to event handlers formsControl = e.NewElement as ProgressView; var percentValue = formsControl.PercentComplete / 100.0f; if (formsControl.LabelStyle.ToLower().Equals("failure")) { progressView.ProgressColor = formsControl.FailureProgressColor.ToAndroid(); RadialProgressView.CircleBackgroundColor = formsControl.FailureBackgroundColor.ToAndroid(); progressView.InitPaints(); } else if (formsControl.LabelStyle.ToLower().Equals("complete")) { progressView.ProgressColor = formsControl.SuccessProgressColor.ToAndroid(); RadialProgressView.CircleBackgroundColor = formsControl.SuccessBackgroundColor.ToAndroid(); progressView.InitPaints(); } else { progressView.ProgressColor = RadialProgressView.DefaultColor; RadialProgressView.CircleBackgroundColor = RadialProgressView.DefaultCircleBackgroundColor; progressView.InitPaints(); } progressView.Value = percentValue; } }
public Progress CreateProgress() { var progressView = new ProgressView { Owner = _mainWindow, WindowStartupLocation = WindowStartupLocation.CenterOwner, SizeToContent = SizeToContent.Height }; _mainWindow.IsEnabled = false; progressView.CanClose = false; _mainWindow.CanClose = false; progressView.Show(); return(new Progress(_mainWindow, progressView)); }
private void RepackClicked(object sender, RoutedEventArgs e) { FileInfo info = new FileInfo(Path.Text); info.Directory.Create(); // ensure that the folder exists Pfs0Builder builder = new Pfs0Builder(); NspPackTask logger = new NspPackTask(builder, info); ProgressView view = new ProgressView(new List <ProgressTask> { logger }); if (TicketCheckbox.IsChecked == true) { DirectoryInfo ticketDir = HACGUIKeyset.GetTicketsDirectory(Preferences.Current.DefaultConsoleName); // TODO: load console name from continuous location List <string> foundTickets = new List <string>(); foreach (Nca nca in SelectedNcas) { if (nca.HasRightsId) { string rightsId = BitConverter.ToString(nca.Header.RightsId).Replace("-", "").ToLower(); string ticketFileName = rightsId + ".tik"; FileInfo sourceTikFileInfo = ticketDir.GetFile(ticketFileName); if (sourceTikFileInfo.Exists && !foundTickets.Contains(rightsId)) { foundTickets.Add(rightsId); LocalFile tikFile = new LocalFile(sourceTikFileInfo.FullName, OpenMode.Read); builder.AddFile(ticketFileName, new FileStorage(tikFile).AsStream()); } } } } foreach (Nca nca in SelectedNcas) { builder.AddFile(nca.Filename, nca.GetStorage().AsStream()); } NavigationWindow window = new NavigationWindow { ShowsNavigationUI = false // get rid of the t r a s h }; window.Navigate(view); TaskManagerPage.Current.Queue.Submit(logger); window.Owner = Window.GetWindow(this); window.ShowDialog(); }
public void LoaderFinish(string name) { LoaderView lv; for (int i = views.Count - 1; i >= 0; i--) { lv = views[i]; if (lv.Loader.Name == name) { ProgressView pv = lv.View; views.RemoveAt(i); pv.Remove(() => { Move(); TryNext(); lv.Loader.Recycle(); }); break; } } }
private void TryNext() { if (loaders.Count > 0) { ProgressView pv = MonoObjectPool <ProgressView> .Instance.Get(); ILoader loader = loaders.Dequeue(); pv.SetName(loader.Name); pv.cancelBtn.onClick.AddListener(() => OnClickCancelBtn(loader.Name)); pv.Register(loader.Progress); loader.StartAll(); pv.Show(views.Count); LoaderView lv = new LoaderView(loader, pv); views.Add(lv); } }
public void OnProgressViewValueChange(ProgressView progressView, float value) { GameConfigBean gameConfig = GameDataHandler.Instance.manager.GetGameConfig(); if (progressView == pvMusic) { gameConfig.musicVolume = value; } else if (progressView == pvSound) { gameConfig.soundVolume = value; } else if (progressView == pvEnvironment) { gameConfig.environmentVolume = value; } AudioHandler.Instance.InitAudio(); }
public static void LockScreen(bool locked) { if (locked) { int num = (PvpServer._autoRetryNum != 0) ? PvpServer._autoRetryNum : 1; ProgressView.ShowProgressText(string.Concat(new object[] { "重连中", num, "/", 5 })); } else { CtrlManager.CloseWindow(WindowID.ProgressView); } }
void ReleaseDesignerOutlets() { if (CancelToolbarItem != null) { CancelToolbarItem.Dispose(); CancelToolbarItem = null; } if (PauseToolbarItem != null) { PauseToolbarItem.Dispose(); PauseToolbarItem = null; } if (ProgressContainerView != null) { ProgressContainerView.Dispose(); ProgressContainerView = null; } if (ProgressView != null) { ProgressView.Dispose(); ProgressView = null; } if (ResetToolbarItem != null) { ResetToolbarItem.Dispose(); ResetToolbarItem = null; } if (ResumeToolbarItem != null) { ResumeToolbarItem.Dispose(); ResumeToolbarItem = null; } if (StartToolbarItem != null) { StartToolbarItem.Dispose(); StartToolbarItem = null; } }
internal override async Task DoCommandAsync() { if (FileManager.GetInstanse().GetFileInfo(_mFileName).Exists) { FileManager.GetInstanse().DeleteFileOrDir(_mFileName); } if (FileManager.GetInstanse().GetDirInfo(_mFileName).Exists) { FileManager.GetInstanse().DeleteFileOrDir(_mFileName); } _code = HttpStatusCodes.SuccessCreated; var progress = new ProgressView(Console.BufferWidth); long sum = 0; using (var file = FileManager.GetInstanse().CreateFile(_mFileName)) { var buffer = new byte[ProgramCostants.DefautBufferSize]; try { while (true) { var count = await _fileStream.ReadAsync(buffer, 0, buffer.Length); if (count > 0) { sum += count; await file.WriteAsync(buffer, 0, count); if (_size > ProgramCostants.MinProgressViewingSize) { progress.DrawProgress((double)sum / _size); } } else { Console.WriteLine(); break; } } } catch (HttpListenerException e) { Console.WriteLine(e.Message); } _fileStream.Close(); _code = HttpStatusCodes.SuccessCreated; } }
public void AddLoader(ILoader loader) { if (views.Count < showCount) { ProgressView v = MonoObjectPool <ProgressView> .Instance.Get(); LoaderView lv = new LoaderView(loader, v); v.SetName(loader.Name); v.cancelBtn.onClick.AddListener(() => OnClickCancelBtn(loader.Name)); v.Register(loader.Progress); loader.StartAll(); v.Show(views.Count); views.Add(lv); } else { loaders.Enqueue(loader); } }
private void OnClickCancelBtn(string name) { LoaderView lv; for (int i = views.Count - 1; i >= 0; i--) { lv = views[i]; if (lv.Loader.Name == name) { ProgressView pv = lv.View; pv.cancelBtn.gameObject.SetActive(false); pv.Stop(); lv.Loader.StopAll(); views.RemoveAt(i); pv.Remove(() => { Move(); TryNext(); }, 0.2f); break; } } }
public void ChangeNextView() { if (View.Content is FinishView) { this.Close(); } else { currentView++; View.Content = views[currentView]; //Erikoistoimintona asennus aloitetaan, kun vaihdetaan ProgressViewiin if (View.Content is ProgressView) { ProgressView progressView = View.Content as ProgressView; progressView.BeginInstallation(); } } }
private void ViewButtonClicked(object sender, RoutedEventArgs e) { List <ProgressTask> tasks = new List <ProgressTask>(); foreach (TaskElement element in List.SelectedItems) { tasks.Add(element.Task); } ProgressView view = new ProgressView(tasks); NavigationWindow window = new NavigationWindow { ShowsNavigationUI = false, // get rid of the t r a s h Owner = Window.GetWindow(this) }; window.Navigate(view); window.ShowDialog(); }
public override void ViewDidAppear(bool animated) { base.ViewDidAppear(animated); if(Settings.OverideDistance == false) { NSLocale locale = NSLocale.CurrentLocale; Settings.DistanceIsMetric = locale.UsesMetricSystem; } SetupParallax(); View.UserInteractionEnabled = true; View.AddGestureRecognizer(new UISwipeGestureRecognizer(gesture => _stepManager.StartCountingFrom(DateTime.Now)) {Direction = UISwipeGestureRecognizerDirection.Down,}); View.AddGestureRecognizer(new UISwipeGestureRecognizer(gesture => _stepManager.StartCountingFrom(DateTime.Today)) {Direction = UISwipeGestureRecognizerDirection.Up,}); // Perform any additional setup after loading the view, typically from a nib. _progressView = new ProgressView(); _progressView.Frame = this.View.Frame; this.View.AddSubview(_progressView); this.View.SendSubviewToBack(_progressView); _stepManager.DailyStepCountChanged += TodaysStepCountChanged; if (CMStepCounter.IsStepCountingAvailable == false) { var unsupportedDevice = new UnsupportedDevice(); unsupportedDevice.View.Frame = View.Frame; View.Add(unsupportedDevice.View); } btnDistance.SetTitleColor(UIColor.White, UIControlState.Normal); btnDistance.SetTitleColor(UIColor.White, UIControlState.Selected); btnDistance.SetTitleColor(UIColor.White, UIControlState.Highlighted); lblDate.Text = DateString; }
/// <summary> /// calculating the best trading routes /// </summary> /// <returns></returns> public DataTable calculateTradingRoutes() { String sqlBaseString; String sqlBaseString2; String sqlString; String sqlLocationString; DataSet Data = new DataSet(); var tmNeighbourstations = new dsEliteDB.tmneighbourstationsDataTable(); var tmFilteredStations = new dsEliteDB.tmfilteredstationsDataTable(); HashSet<String> Calculated = new HashSet<String>(); Int32 StationCount; Int32 SystemCount; Int32 Current = 0; ProgressView PV; Boolean Cancelled = false; Int32 maxTradingDistance; dsEliteDB.tmpa_s2s_besttripsDataTable Result; DateTime stopTime; try { Debug.Print("start :" + DateTime.Now.ToShortTimeString()); stopTime = (DateTime.Now - new TimeSpan(Program.DBCon.getIniValue<Int32>(IBE.MTPriceAnalysis.tabPriceAnalysis.DB_GROUPNAME, "TimeFilterDays", "30", true), 0, 0, 0)); // gettin' some freaky performance m_lDBCon.Execute("set global innodb_flush_log_at_trx_commit=2"); getFilteredSystemAndStationCount(out StationCount, out SystemCount); // get the results for a cancellable loop if(FixedStation == 0) { sqlString = "select * from tmfilteredstations" + " order by Station_ID"; } else { sqlString = String.Format("select * from tmfilteredstations" + " where Station_ID = {0}" + " order by Station_ID", FixedStation); } m_lDBCon.Execute(sqlString, tmFilteredStations); maxTradingDistance = -1; if(m_lDBCon.getIniValue<Boolean>(tabPriceAnalysis.DB_GROUPNAME, "MaxTripDistance")) maxTradingDistance = m_lDBCon.getIniValue<Int32>(tabPriceAnalysis.DB_GROUPNAME, "MaxTripDistanceValue"); // delete old content sqlString = "truncate table tmNeighbourstations;"; m_lDBCon.Execute(sqlString); sqlBaseString = "insert into tmNeighbourstations(System_ID_From, Station_ID_From, Distance_From," + " System_ID_To, Station_ID_To, Distance_To, " + " Distance_Between) " + " select BS.System_ID As System_ID_From, BS.Station_ID As Station_ID_From, BS.Distance As Distance_From," + " FS.System_ID As System_ID_To, FS.Station_ID As Station_ID_To, FS.Distance As Distance_To," + " sqrt(POW(FS.x - BS.x, 2) + POW(FS.y - BS.y, 2) + POW(FS.z - BS.z, 2)) as Distance_Between" + " from (select * from tmFilteredStations " + " where Station_ID = {0}" + " order by System_ID, Station_ID) BS"; if(maxTradingDistance >= 0) sqlBaseString += " join tmfilteredstations FS on (sqrt(POW(FS.x - BS.x, 2) + POW(FS.y - BS.y, 2) + POW(FS.z - BS.z, 2)) <= {1})"; else sqlBaseString += " join tmfilteredstations FS"; sqlBaseString += " join tbStations St on FS.Station_ID = St.ID" + " join tbSystems Sy on St.System_ID = Sy.ID" + " having BS.Station_ID <> FS.Station_ID;"; PV = new ProgressView(this.GUI); Current = 0; if(maxTradingDistance >= 0) PV.progressStart("determine neigbour-systems in range of "+ maxTradingDistance + " ly of " + SystemCount + " selected systems..."); else PV.progressStart("determine neigbour-systems without range limit of " + SystemCount + " selected systems..."); foreach (dsEliteDB.tmfilteredstationsRow CurrentStation in tmFilteredStations) { // preparing a table with the stations from "tmFilteredStations" and all // their neighbour stations who are not further away than the max trading distance if((CurrentStation.System_id == 12761) || (CurrentStation.System_id == 19737)) Debug.Print("Stop"); if(maxTradingDistance >= 0) sqlString = String.Format(sqlBaseString, CurrentStation.Station_id, maxTradingDistance); else sqlString = String.Format(sqlBaseString, CurrentStation.Station_id); m_lDBCon.Execute(sqlString); Current += 1; PV.progressUpdate(Current, tmFilteredStations.Rows.Count); if(PV.Cancelled) { Cancelled = true; break; } } PV.progressStop(); // get for one station and all of it's neighbours the tradings for all commodity combinations // result gives per "station to station" route only the one best profit for all combinations of commodities sqlBaseString = "insert ignore into tmBestProfits(Station_ID_From, Station_ID_To, Max_Profit)" + " select Station_ID_From, Station_ID_To, max(Profit) As Max_Profit from " + " (select PR1.Station_ID_From, PR1.Station_ID_To, Pr1.Forward, Pr2.Back, (ifnull(Pr1.Forward, 0) + ifnull(Pr2.Back,0)) As Profit from " + " (select L1.*, if((nullif(L2.Sell,0) - nullif(L1.Buy,0)) > 0, (nullif(L2.Sell,0) - nullif(L1.Buy,0)), null) As Forward, " + " if((nullif(L1.Sell,0) - nullif(L2.Buy,0)) > 0, (nullif(L1.Sell,0) - nullif(L2.Buy,0)), null) As Back " + " from (select N.Station_ID_From, N.Station_ID_To, CD.Commodity_ID, CD.Buy, CD.Sell " + " from tmNeighbourstations N join tbCommodityData CD on N.Station_ID_From = CD.Station_ID " + " and N.Station_ID_From = {0} {2}" + " ) L1 " + " join " + " (select N.Station_ID_From, N.Station_ID_To, CD.Commodity_ID, CD.Buy, CD.Sell " + " from tmNeighbourstations N join tbCommodityData CD on N.Station_ID_To = CD.Station_ID " + " and N.Station_ID_From = {0} {2}" + " ) L2 " + " on L1.Station_ID_From = L2.Station_ID_From " + " and L1.Station_ID_To = L2.Station_ID_To " + " and L1.Commodity_ID = L2.Commodity_ID" + " {4}) Pr1 " + " " + " join " + " " + " (select L1.*, if((nullif(L2.Sell,0) - nullif(L1.Buy,0)) > 0, (nullif(L2.Sell,0) - nullif(L1.Buy,0)), null) As Forward, " + " if((nullif(L1.Sell,0) - nullif(L2.Buy,0)) > 0, (nullif(L1.Sell,0) - nullif(L2.Buy,0)), null) As Back " + " from (select N.Station_ID_From, N.Station_ID_To, CD.Commodity_ID, CD.Buy, CD.Sell " + " from tmNeighbourstations N join tbCommodityData CD on N.Station_ID_From = CD.Station_ID " + " and N.Station_ID_From = {0} {3}" + " ) L1 " + " join " + " (select N.Station_ID_From, N.Station_ID_To, CD.Commodity_ID, CD.Buy, CD.Sell " + " from tmNeighbourstations N join tbCommodityData CD on N.Station_ID_To = CD.Station_ID " + " and N.Station_ID_From = {0} {3}" + " ) L2 " + " on L1.Station_ID_From = L2.Station_ID_From " + " and L1.Station_ID_To = L2.Station_ID_To " + " and L1.Commodity_ID = L2.Commodity_ID" + " {5}) Pr2 " + " " + " on Pr1.Station_ID_From = Pr2.Station_ID_From " + " and Pr1.Station_ID_To = Pr2.Station_ID_To) ALL_RESULTS " + " where Profit > {1}" + " group by Station_ID_From, Station_ID_To;" + " " + "delete BP1 from tmBestProfits BP1, (select Max_Profit from tmBestProfits" + " order by Max_Profit desc" + " limit 100,1) BP2" + " where BP1.Max_Profit < BP2.Max_Profit;" + " " + "select Max_Profit As Min_Profit from tmBestProfits" + " order by Max_Profit desc" + " limit 100,1;"; String wherePart_Return = ""; String wherePart_Send = ""; String havingPart_Return = ""; String havingPart_Send = ""; // time filter if(Program.DBCon.getIniValue<Boolean>(IBE.MTPriceAnalysis.tabPriceAnalysis.DB_GROUPNAME, "TimeFilter", false.ToString(), true)) { wherePart_Send = " where CD.timestamp >= " + DBConnector.SQLDateTime(stopTime); wherePart_Return = " where CD.timestamp >= " + DBConnector.SQLDateTime(stopTime); } // commodity filter if(CommoditiesSend.Count > 0) { if(String.IsNullOrEmpty(wherePart_Send)) wherePart_Send = " where " + DBConnector.GetString_Or<Int32>("CD.Commodity_ID", CommoditiesSend); else wherePart_Send += " and " + DBConnector.GetString_Or<Int32>("CD.Commodity_ID", CommoditiesSend); havingPart_Send = " having Forward > 0 "; } if(CommoditiesReturn.Count > 0) { if(String.IsNullOrEmpty(wherePart_Return)) wherePart_Return = " where " + DBConnector.GetString_Or<Int32>("CD.Commodity_ID", CommoditiesReturn); else wherePart_Return += " and " + DBConnector.GetString_Or<Int32>("CD.Commodity_ID", CommoditiesReturn); havingPart_Return = " having Back > 0 "; } if(!Cancelled) { Current = 0; Calculated.Clear(); m_lDBCon.Execute("truncate table tmBestProfits"); // get the start stations for a cancellable loop sqlString = "select Station_ID_From, count(*) As Neighbours from tmNeighbourstations" + " group by Station_ID_From" + " order by Station_ID_From"; m_lDBCon.Execute(sqlString, "StartStations", Data); PV = new ProgressView(this.GUI); if(maxTradingDistance >= 0) PV.progressStart("Processing market data of " + StationCount + " stations from " + SystemCount + " systems\n" + "(max. trading distance = " + maxTradingDistance + " ly)..."); else PV.progressStart("Processing market data of " + StationCount + " stations from " + SystemCount + " systems\n" + "(no trading distance limit)..."); Int32 currentMinValue = 0; foreach(DataRow StartStation in Data.Tables["StartStations"].Rows) { sqlString = String.Format(sqlBaseString, StartStation["Station_ID_From"], currentMinValue, wherePart_Send, wherePart_Return, havingPart_Send, havingPart_Return); m_lDBCon.Execute(sqlString, "MinProfit", Data); if((Data.Tables["minProfit"].Rows.Count > 0) && (!Convert.IsDBNull(Data.Tables["MinProfit"]))) currentMinValue = (Int32)Data.Tables["MinProfit"].Rows[0]["Min_Profit"]; Current += 1; PV.progressUpdate(Current, Data.Tables["StartStations"].Rows.Count); Data.Tables["MinProfit"].Clear(); if(PV.Cancelled) { Cancelled = true; break; } } m_lDBCon.Execute("truncate table tmPA_S2S_BestTrips"); sqlString = "create temporary table tmpForDelete As" + " (select BP1.Station_Id_From, BP1.Station_Id_To from tmBestProfits BP1" + " where exists (select * from tmBestProfits BP2 " + " where BP1.Station_Id_From = BP2.Station_Id_To " + " and BP1.Station_Id_To = BP2.Station_Id_From " + " and BP1.Max_Profit = BP1.Max_Profit" + " and BP1.Station_Id_From > BP2.Station_Id_From));" + "delete BP1 from tmBestProfits BP1, tmpForDelete T" + " where BP1.Station_Id_From = T.Station_Id_From" + " and BP1.Station_Id_To = T.Station_Id_To;" + "drop temporary table tmpForDelete;" ; m_lDBCon.Execute(sqlString); Result = new dsEliteDB.tmpa_s2s_besttripsDataTable(); PV.progressStop(); } m_lDBCon.Execute("set global innodb_flush_log_at_trx_commit=1"); sqlString = "select distinct St1.*, St2.*, Bp.Max_Profit As Profit, NS.Distance_Between As Distance," + " null As TimeStamp_1, null As TimeStamp_2 from tmBestProfits Bp" + " " + " join " + " " + " (select Sy.ID As System_ID_1, Sy.SystemName As SystemName_1, St.ID As Station_ID_1, St.StationName As StationName_1, " + " St.distance_to_star As DistanceToStar_1 from tmBestProfits BP, tbStations St, tbSystems Sy" + " where BP.Station_ID_From = St.ID " + " and St.System_ID = Sy.ID) St1" + " " + " on St1.Station_ID_1 = BP.Station_ID_From" + " " + " join " + " " + " (select Sy.ID As System_ID_2, Sy.SystemName As SystemName_2, St.ID As Station_ID_2, St.StationName As StationName_2, " + " St.distance_to_star As DistanceToStar_2 from tmBestProfits BP, tbStations St, tbSystems Sy" + " where BP.Station_ID_To = St.ID " + " and St.System_ID = Sy.ID) St2" + " " + " on St2.Station_ID_2 = BP.Station_ID_To" + " join " + " tmneighbourstations NS" + " on St1.Station_ID_1 = NS.Station_Id_From " + " and St2.Station_ID_2 = NS.Station_Id_To" + " " + " order by Max_Profit desc"; Result = new dsEliteDB.tmpa_s2s_besttripsDataTable(); m_lDBCon.Execute(sqlString, Result); sqlBaseString = "select PR1.Commodity_ID As FWCommodityID, Pr1.LocCommodity As FWCommodity," + " PR1.timestamp As FWTimeStamp," + " PR2.Commodity_ID As BkCommodityID, Pr2.LocCommodity As BkCommodity, " + " PR2.timestamp As BkTimeStamp," + " Pr1.Forward, Pr2.Back, (ifnull(Pr1.Forward, 0) + ifnull(Pr2.Back,0)) As Profit from " + " (select L1.Commodity_ID, T.LocCommodity, " + " if((nullif(L2.Sell,0) - nullif(L1.Buy,0)) > 0, (nullif(L2.Sell,0) - nullif(L1.Buy,0)), null) As Forward, " + " if((nullif(L1.Sell,0) - nullif(L2.Buy,0)) > 0, (nullif(L1.Sell,0) - nullif(L2.Buy,0)), null) As Back," + " if((nullif(L2.Sell,0) - nullif(L1.Buy,0)) > 0, L1.timestamp, if((nullif(L1.Sell,0) - nullif(L2.Buy,0)) > 0, L2.timestamp, null)) As timestamp" + " from (select CD.Commodity_ID, CD.Buy, CD.Sell, CD.timestamp " + " from tbCommodityData CD " + " where CD.Station_ID = {0} {4}" + " ) L1 " + " join" + " (select CD.Commodity_ID, CD.Buy, CD.Sell, CD.timestamp" + " from tbCommodityData CD " + " where CD.Station_ID = {1} {4}" + " ) L2" + " on L1.Commodity_ID = L2.Commodity_ID" + " join tbCommodity T" + " on L1.Commodity_ID = T.ID" + " ) Pr1" + " join " + " (select L1.Commodity_ID, T.LocCommodity," + " if((nullif(L2.Sell,0) - nullif(L1.Buy,0)) > 0, (nullif(L2.Sell,0) - nullif(L1.Buy,0)), null) As Forward, " + " if((nullif(L1.Sell,0) - nullif(L2.Buy,0)) > 0, (nullif(L1.Sell,0) - nullif(L2.Buy,0)), null) As Back," + " if((nullif(L2.Sell,0) - nullif(L1.Buy,0)) > 0, L1.timestamp, if((nullif(L1.Sell,0) - nullif(L2.Buy,0)) > 0, L2.timestamp, null)) As timestamp" + " from (select CD.Commodity_ID, CD.Buy, CD.Sell, CD.timestamp " + " from tbCommodityData CD " + " where CD.Station_ID = {0} {3}" + " ) L1 " + " join" + " (select CD.Commodity_ID, CD.Buy, CD.Sell, CD.timestamp" + " from tbCommodityData CD " + " where CD.Station_ID = {1} {3}" + " ) L2" + " on L1.Commodity_ID = L2.Commodity_ID" + " join tbCommodity T" + " on L1.Commodity_ID = T.ID" + " ) Pr2" + " order by Profit desc {2}"; sqlBaseString2 = "select distance from tmFilteredStations" + " where (Station_id = {0}" + " or Station_id = {1})" + " order by distance limit 1"; sqlLocationString = "select st1.is_planetary As FW_is_planetary, st2.is_planetary As BW_is_planetary from " + " (select is_planetary from tbstations" + " where ID = {0}) as st1 ," + " (select is_planetary from tbstations" + " where ID = {1}) as st2;"; wherePart_Send = ""; wherePart_Return = ""; // time filter if(Program.DBCon.getIniValue<Boolean>(IBE.MTPriceAnalysis.tabPriceAnalysis.DB_GROUPNAME, "TimeFilter", false.ToString(), true)) { wherePart_Send = " and CD.timestamp >= " + DBConnector.SQLDateTime(stopTime); wherePart_Return = " and CD.timestamp >= " + DBConnector.SQLDateTime(stopTime); } // commodity filter if(CommoditiesSend.Count > 0) { wherePart_Send += " and " + DBConnector.GetString_Or<Int32>("CD.Commodity_ID", CommoditiesSend); } if(CommoditiesReturn.Count > 0) { wherePart_Return += " and " + DBConnector.GetString_Or<Int32>("CD.Commodity_ID", CommoditiesReturn); } // now get the timestamps of the best-profit commodities and get other details foreach (dsEliteDB.tmpa_s2s_besttripsRow CurrentRow in Result) { sqlString = String.Format(sqlBaseString, CurrentRow.Station_ID_1, CurrentRow.Station_ID_2, "limit 1", wherePart_Send, wherePart_Return); m_lDBCon.Execute(sqlString, "Timestamps", Data); if(!DBNull.Value.Equals(Data.Tables["Timestamps"].Rows[0]["FWTimeStamp"])) CurrentRow.TimeStamp_1 = (DateTime)Data.Tables["Timestamps"].Rows[0]["FWTimeStamp"]; if(!DBNull.Value.Equals(Data.Tables["Timestamps"].Rows[0]["BkTimeStamp"])) CurrentRow.TimeStamp_2 = (DateTime)Data.Tables["Timestamps"].Rows[0]["BkTimeStamp"]; // distance sqlString = String.Format(sqlBaseString2, CurrentRow.Station_ID_1, CurrentRow.Station_ID_2); m_lDBCon.Execute(sqlString, "Distance", Data); if((Data.Tables["Distance"].Rows.Count > 0) && (!DBNull.Value.Equals(Data.Tables["Distance"].Rows[0]["distance"]))) CurrentRow.DistanceToRoute = (Double)Data.Tables["Distance"].Rows[0]["distance"]; else CurrentRow.DistanceToRoute = double.NaN; // location sqlString = String.Format(sqlLocationString, CurrentRow.Station_ID_1, CurrentRow.Station_ID_2); m_lDBCon.Execute(sqlString, "Location", Data); if(!DBNull.Value.Equals(Data.Tables["Location"].Rows[0]["FW_is_planetary"])) if(((Boolean)Data.Tables["Location"].Rows[0]["FW_is_planetary"])) CurrentRow.Station_Location_1 = "P"; else CurrentRow.Station_Location_1 = "S"; if(!DBNull.Value.Equals(Data.Tables["Location"].Rows[0]["BW_is_planetary"])) if(((Boolean)Data.Tables["Location"].Rows[0]["BW_is_planetary"])) CurrentRow.Station_Location_2 = "P"; else CurrentRow.Station_Location_2 = "S"; Data.Tables["Timestamps"].Clear(); Data.Tables["Distance"].Clear(); Data.Tables["Location"].Clear(); } Debug.Print("Ende :" + DateTime.Now.ToShortTimeString()); return Result; } catch (Exception ex) { m_lDBCon.Execute("set global innodb_flush_log_at_trx_commit=1"); throw new Exception("Error while calculating possible trading routes", ex); } }