public ActionResult TrackProgress() { // If not logged in, redirect to the sign in page if (Session["username"] == null) { return(RedirectToAction("SignIn", "Account")); } ProgressViewModel progView = new ProgressViewModel(); Progress progress = new Progress(); string user = Session["username"].ToString(); // If has no progress, direct to another page for user to fill in details. var checkUsername = smokeFreeDB.Progress.FirstOrDefault(m => m.userName == user); if (checkUsername == null) { return(RedirectToAction("FillInDetails")); } else { // query for the correct progress progress = smokeFreeDB.Progress.Find(user); // query for all checkins List <CheckInDate> checkins = new List <CheckInDate>(); checkins = smokeFreeDB.CheckInDate.Where(c => c.userName == user).OrderByDescending(c => c.checkInDate).ToList(); int totalCheckins = checkins.Count(); // query for user's name string user_realname = smokeFreeDB.GeneralUser.Where(c => c.userName == user).FirstOrDefault().name; // pass out the calculated display ViewBag.progressName = user_realname; progView.userName = user; progView.streak = getStreak(checkins); progView.totalCheck = totalCheckins; progView.cigaSaved = progress.cigaIntake * totalCheckins; progView.cashSaved = (progress.cigaPrice / 20) * progView.cigaSaved * totalCheckins; } return(View(progView)); }
private bool OpenProject(ProgressViewModel vm, string path, out string errorMsg) { string projectName = Path.GetFileNameWithoutExtension(path); vm.DisplayName = $"Opening {projectName} - Cog"; vm.Text = "Loading project file..."; errorMsg = null; FileStream fileStream = null; CogProject project = null; try { fileStream = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None); if (ConfigManager.Load(_spanFactory, _segmentPool, fileStream, out project)) { IsChanged = true; } } catch (ConfigException) { errorMsg = "The specified file is not a valid Cog configuration file."; } catch (IOException ioe) { errorMsg = $"Error opening project file:\n{ioe.Message}"; } catch (UnauthorizedAccessException) { errorMsg = "The specified file is in use or you do not have access to it."; } if (errorMsg != null) { fileStream?.Close(); return(false); } Debug.Assert(project != null); _projectFileStream = fileStream; SetupProject(vm, path, projectName, project); _isNew = false; return(true); }
public void CompareAll(object ownerViewModel) { if (_projectService.Project.Varieties.Count == 0 || _projectService.Project.Meanings.Count == 0) { return; } Messenger.Default.Send(new PerformingComparisonMessage()); var generator = new VarietyPairGenerator(); generator.Process(_projectService.Project); var pipeline = new MultiThreadedPipeline <VarietyPair>(GetCompareProcessors()); var progressVM = new ProgressViewModel(vm => { vm.Text = "Comparing all variety pairs..."; pipeline.Process(_projectService.Project.VarietyPairs); while (!pipeline.WaitForComplete(500)) { if (vm.Canceled) { pipeline.Cancel(); pipeline.WaitForComplete(); break; } } if (vm.Canceled) { _projectService.Project.VarietyPairs.Clear(); } else { vm.Text = "Analyzing results..."; Messenger.Default.Send(new ComparisonPerformedMessage()); } }, false, true); pipeline.ProgressUpdated += (sender, e) => progressVM.Value = e.PercentCompleted; _dialogService.ShowModalDialog(ownerViewModel, progressVM); }
public void ProgressViewModel_SetUpperBoundLimitedValue() { // Setup ProgressViewModel testSubject = new ProgressViewModel(); // Sanity Assert.AreEqual(0, testSubject.Value, "Default value expected"); // Act + Verify // Erroneous cases Exceptions.Expect <ArgumentOutOfRangeException>(() => testSubject.SetUpperBoundLimitedValue(double.NegativeInfinity)); Exceptions.Expect <ArgumentOutOfRangeException>(() => testSubject.SetUpperBoundLimitedValue(double.PositiveInfinity)); Exceptions.Expect <ArgumentOutOfRangeException>(() => testSubject.SetUpperBoundLimitedValue(0 - double.Epsilon)); Exceptions.Expect <ArgumentOutOfRangeException>(() => testSubject.SetUpperBoundLimitedValue(1.0 + ProgressViewModel.UpperBoundMarginalErrorSupport + ProgressViewModel.UpperBoundMarginalErrorSupport)); // Sanity Assert.AreEqual(0.0, testSubject.Value, "Erroneous cases should not change the default value"); // NaN supported testSubject.SetUpperBoundLimitedValue(double.NaN); Assert.AreEqual(double.NaN, testSubject.Value); // Zero in range testSubject.SetUpperBoundLimitedValue(0); Assert.AreEqual(0.0, testSubject.Value); // One is in range testSubject.SetUpperBoundLimitedValue(1); Assert.AreEqual(1.0, testSubject.Value); // Anything between zero and one is in range Random r = new Random(); double val = r.NextDouble(); testSubject.SetUpperBoundLimitedValue(val); Assert.AreEqual(val, testSubject.Value); // More than one (i.e floating point summation errors) will become one testSubject.SetUpperBoundLimitedValue(1.0 + ProgressViewModel.UpperBoundMarginalErrorSupport); Assert.AreEqual(1.0, testSubject.Value); }
//// Get for Tickets Graph public ActionResult TicketProgress() { var user = db.Users.Find(User.Identity.GetUserId()); var proj = user.Projects.Where(p => p.ProjectArchieved == false).ToList(); if (User.IsInRole("Admin")) { proj = db.Projects.Where(p => p.ProjectArchieved == false).ToList(); } var pvmList = new List <ProgressViewModel>(); foreach (var item in proj) { var pvm = new ProgressViewModel(); var projTickets = item.Tickets.ToList(); pvm.projectName = item.ProjectName; pvm.totalTickets = projTickets.Count(); pvm.closedTickets = projTickets.Where(c => c.TicketStatus.StatusName == "Close").Count(); pvm.unassignedTickets = projTickets.Where(c => c.TicketStatus.StatusName == "Unassigned").Count(); pvm.holdTickets = projTickets.Where(c => c.TicketStatus.StatusName == "On Hold").Count(); var asgn = projTickets.Where(a => a.TicketStatus.StatusName == "Assigned").Count(); var reasgn = projTickets.Where(a => a.TicketStatus.StatusName == "Reassigned").Count(); var test = projTickets.Where(a => a.TicketStatus.StatusName == "Testing").Count(); var open = projTickets.Where(a => a.TicketStatus.StatusName == "Open").Count(); pvm.inProgress = asgn + reasgn + test + open; if (pvm.totalTickets > 0) { //pvm.closedPer = Convert.ToInt32(((double)pvm.closedTickets / (double)pvm.totalTickets) * 100); pvm.closedPer = Convert.ToDouble(((double)pvm.closedTickets / (double)pvm.totalTickets) * 100); pvm.closedPer = Math.Round(pvm.closedPer, 2); } else { pvm.closedPer = 0; } pvmList.Add(pvm); } return(View(pvmList)); }
/// <summary> /// Создания потоков и запуск генерации изображений /// </summary> /// <param name="list">Коллекция Canvas</param> /// <param name="scenario">Сценарий для генерации изображений</param> /// <param name="progressViewModel">Загрузка (ViewModel)</param> public void CreateThreads(List <Canvas> list, SettingsScenario scenario, ProgressViewModel progressViewModel) { progressViewModel.FinishTotalNumbers = scenario.countDigits.Sum(); progressViewModel.TotalNumber = 0; for (int i = 0; i < list.Count; i++) { var canvas = XamlWriter.Save(list[i]); var canvasChildren = new List <string>(); foreach (var child in list[i].Children) { canvasChildren.Add(XamlWriter.Save(child)); } var count = scenario.countDigits[i]; Thread thread = new Thread(() => CreateMnistData(canvas, canvasChildren, count, scenario, progressViewModel)); thread.SetApartmentState(ApartmentState.STA); thread.Start(); } }
public ScriptsViewModel(UIServices uiServices, IScriptRunner scriptRunner, IOperationProgress progress, IScriptDependencyResolver scriptDependencyResolver, IScriptParser parser, IDeploymentContext deploymentContext, IOperationContext operationContext) { this.uiServices = uiServices; this.scriptRunner = scriptRunner; this.scriptDependencyResolver = scriptDependencyResolver; this.parser = parser; this.deploymentContext = deploymentContext; var canRun = this.WhenAnyValue(x => x.SelectedScript).Select(s => s != null); var runCommand = ReactiveCommand.CreateFromTask(Run, canRun); RunCommand = new ProgressViewModel(runCommand, progress, this, this.uiServices.ContextDialog, operationContext); IsBusyObservable = Observable.Merge(RunCommand.Command.IsExecuting); Tree = GetTree(new DirectoryInfo(extraScriptsPath)).Children.ToList(); MessageBus.Current.Listen <FolderNode>().Subscribe(x => SelectedScript = x); }
public DeploymentViewModel( IDeploymentContext context, IWoaDeployer woaDeployer, IOperationContext operationContext, UIServices uiServices, AdvancedViewModel advancedViewModel, IOperationProgress progress, WimPickViewModel wimPickViewModel, IFileSystemOperations fileSystemOperations, ILumiaSettingsService lumiaSettingsService) { this.context = context; this.woaDeployer = woaDeployer; this.uiServices = uiServices; this.advancedViewModel = advancedViewModel; this.wimPickViewModel = wimPickViewModel; this.fileSystemOperations = fileSystemOperations; this.lumiaSettingsService = lumiaSettingsService; var isSelectedWim = wimPickViewModel.WhenAnyObservable(x => x.WimMetadata.SelectedImageObs) .Select(metadata => metadata != null); FullInstallWrapper = new ProgressViewModel(ReactiveCommand.CreateFromTask(Deploy, isSelectedWim), progress, this, uiServices.ContextDialog, operationContext); IsBusyObservable = FullInstallWrapper.Command.IsExecuting; isBusyHelper = IsBusyObservable.ToProperty(this, model => model.IsBusy); }
/// <summary> /// Reset all viewmodel states in accordance with the /// given <paramref name="settings"/> object. This is /// useful when presenting a sequence of different /// progress indicators (eg. infinite first and finite later) /// in 1 dialog. /// </summary> /// <param name="settings"></param> protected void ResetSettings(ProgressSettings settings) { if (_Progress == null) { _Progress = new ProgressViewModel(settings); } _Progress.ResetSettings(settings); IsCancelable = IsCancelButtonVisible = settings.IsCancelable; CloseDialogOnProgressFinished = settings.CloseViewOnProgressFinished; Title = settings.Title; Message = settings.Message; CancelButtonText = settings.CancelButtonText; CloseButtonText = settings.CloseButtonText; DefaultResult = settings.DefaultResult; DefaultCloseResult = settings.DefaultCloseResult; }
/// <summary> /// Begins progress display where client manually updates progress</summary> /// <param name="message">Message to display with progress meter</param> /// <param name="canCancel">Should the cancel button appear and be enabled?</param> /// <param name="argument">Worker argument</param> /// <param name="workHandler">Background thread delegate</param> /// <param name="autoIncrement">Whether to auto increment the progress meter</param> /// <returns>True if the thread was cancelled</returns> public bool RunProgressDialog(string message, bool canCancel, object argument, DoWorkEventHandler workHandler, bool autoIncrement) { var vm = new ProgressViewModel() { Cancellable = canCancel, Description = message, IsIndeterminate = autoIncrement }; vm.RunWorkerThread(argument, workHandler); ProgressDialog progressDialog = new ProgressDialog(); progressDialog.DataContext = vm; progressDialog.Owner = DialogUtil.GetActiveWindow(); progressDialog.ShowDialog(); ProgressResult = vm.Result; ProgressError = vm.Error; return(vm.Cancelled); }
public WoaMaintenanceViewModel(IWindowsDeployer deployer, UIServices uiServices, IDeploymentContext context, IOperationProgress progress, IOperationContext operationContext, ILumiaSettingsService lumiaSettingsService) { this.deployer = deployer; this.uiServices = uiServices; this.context = context; this.progress = progress; this.lumiaSettingsService = lumiaSettingsService; BackupProgressViewModel = new ProgressViewModel(ReactiveCommand.CreateFromTask(Backup), progress, this, uiServices.ContextDialog, operationContext); RestoreProgressViewModel = new ProgressViewModel(ReactiveCommand.CreateFromTask(Restore), progress, this, uiServices.ContextDialog, operationContext); IsBusyObservable = Observable.Merge(new[] { BackupProgressViewModel.Command.IsExecuting, RestoreProgressViewModel.Command.IsExecuting, }); }
public ProgressPage() { ProgressViewModel viewModel; BindingContext = viewModel = new ProgressViewModel(); ListView listView = new ListView { ItemTemplate = new DataTemplate(() => { var textCell = new TextCell { TextColor = Color.Black }; textCell.SetBinding(TextCell.TextProperty, "Title"); textCell.SetBinding(TextCell.DetailProperty, "Exercises"); return(textCell); }) }; listView.SetBinding(ListView.ItemsSourceProperty, "Workouts"); listView.ItemSelected += async(s, e) => { var item = e.SelectedItem as ProgressInfo; if (item != null) { await Navigation.PushAsync(new DetailedProgressPage(item.ExerciseDetails, viewModel)); listView.SelectedItem = null; } }; Title = "Progress Overview"; Padding = new Thickness(10, 0); Content = new StackLayout { Children = { listView } }; }
private async void SaveUserConfigAsync(string progress, string configuration) { if (string.IsNullOrEmpty(progress)) { _probaLogger.LogWarning("SaveUserProgress: Progress is Empty ,Progress Changed to default Value"); progress = "Progress"; } if (string.IsNullOrEmpty(configuration)) { _probaLogger.LogWarning("SaveUserProgress: configuration is Empty ,configuration Changed to default Value"); configuration = "configuration"; } var progressViewModel = new ProgressViewModel() { Progress = progress, Configurations = configuration }; if (Application.internetReachability == NetworkReachability.NotReachable || _sending) { SaveSaveUserProgressInDB(progressViewModel); return; } try { var(success, statusCode) = await _probaHttpClient.SaveUserProgressAsync(progressViewModel); if (!success) { SaveSaveUserProgressInDB(progressViewModel); } } catch (Exception e) { _probaLogger.LogError(e.Message, e.StackTrace); SaveSaveUserProgressInDB(progressViewModel); } }
public async Task InstallAll() { var data = new ProgressViewModel { Progress = new TaskManager(new[] { new ProgressTask("Downloading dependencies: Youtube-DL"), new ProgressTask("Downloading dependencies: FFmpeg-base"), new ProgressTask("Downloading dependencies: FFmpeg-play"), new ProgressTask("Downloading dependencies: FFmpeg-probe"), new ProgressTask("Extracting downloaded files") }) { FinalizingText = "Cleaning up..." } }; var window = Application.Current.Dispatcher.Invoke(() => new ProgressWindow(data)); _ = Task.Run(() => Application.Current.Dispatcher.Invoke(() => window.ShowDialog())); await SetupDependencies(data); window.Close(); }
public ActionResult Create(ProgressViewModel progressviewmodel) { try { if (SingletonData.Singleton.StoreReparationInProgressInitalized == false) { SingletonData.Singleton.StoreReparationInProgress = new MockDataServiceReparationInProgress(); SingletonData.Singleton.StoreReparationInProgressInitalized = true; } SingletonData.Singleton.StoreReparationInProgress.AddItem(progressviewmodel); if (progressviewmodel.status.Value == "klaar") { return(RedirectToAction("Create", "Done")); } // TODO: Add insert logic here return(RedirectToAction("Index")); } catch { return(View()); } }
public ActionResult Progress() { var userName = this.Request.Query["userName"]; var range = this.Request.Query["range"]; var model = new ProgressViewModel( this.gameData, this.telemetryClient, this.databaseCommandFactory, this.userSettingsProvider, this.User, this.userManager, userName, range); if (!model.IsValid) { this.ViewBag.ErrorMessage = string.IsNullOrEmpty(userName) ? "You have no uploaded data!" : "That user does not exist or does not have public uploads"; return(this.View("Error")); } return(this.View(model)); }
private void TypeComboBox_Selected(object sender, RoutedEventArgs e) { if (!IsLoaded) { return; } if (TypeComboBox.SelectedIndex < 1) { MainPresenter.Content = null; return; } if (!IsEditing) { //Create a new model. switch ((TaskTypes)TypeComboBox.SelectedIndex) { case TaskTypes.MouseClicks: CurrentTask = MouseClicksViewModel.Default(); break; case TaskTypes.KeyStrokes: CurrentTask = KeyStrokesViewModel.Default(); break; case TaskTypes.Delay: CurrentTask = DelayViewModel.Default(); break; case TaskTypes.Progress: CurrentTask = ProgressViewModel.Default(); break; case TaskTypes.Border: CurrentTask = BorderViewModel.Default(); break; case TaskTypes.Shadow: CurrentTask = ShadowViewModel.Default(); break; } } switch ((TaskTypes)TypeComboBox.SelectedIndex) { case TaskTypes.MouseClicks: MainPresenter.Content = new MouseClicksPanel { DataContext = CurrentTask }; break; case TaskTypes.KeyStrokes: MainPresenter.Content = new KeyStrokesPanel { DataContext = CurrentTask }; break; case TaskTypes.Delay: MainPresenter.Content = new DelayPanel { DataContext = CurrentTask }; break; case TaskTypes.Progress: MainPresenter.Content = new ProgressPanel { DataContext = CurrentTask }; break; case TaskTypes.Border: MainPresenter.Content = new BorderPanel { DataContext = CurrentTask }; break; case TaskTypes.Shadow: MainPresenter.Content = new ShadowPanel { DataContext = CurrentTask }; break; } }
private void ReRunVideo(string fileName) { ProgressView view = new ProgressView(); ProgressViewModel viewModel = new ProgressViewModel(); view.DataContext = viewModel; viewModel.CancelPressed += (sender, args) => { CancelReRun(); }; viewModel.WindowAboutToClose += (sender, args) => { if (RbskVideo != null) { RbskVideo.Paused = true; } }; viewModel.WindowClosingCancelled += (sender, args) => { if (RbskVideo != null) { RbskVideo.Paused = false; } }; CancelTask = false; Task.Factory.StartNew(() => { IMouseDataResult result = Model.Results[SelectedVideo.Model]; try { IVideoSettings videoSettings = ModelResolver.Resolve <IVideoSettings>(); using (IRBSKVideo rbskVideo = ModelResolver.Resolve <IRBSKVideo>()) using (IVideo video = ModelResolver.Resolve <IVideo>()) { RbskVideo = rbskVideo; video.SetVideo(fileName); if (video.FrameCount < 100) { result.VideoOutcome = SingleFileResult.FrameCountTooLow; result.Message = "Exception: " + SelectedVideo.VideoFileName + " - Frame count too low"; //allResults.TryAdd(file, result); viewModel.ProgressValue = 1; //continue; return; } videoSettings.FileName = SelectedVideo.VideoFileName; videoSettings.ThresholdValue = BinaryThreshold; video.SetFrame(0); Image <Gray, Byte> binaryBackground; IEnumerable <IBoundaryBase> boundaries; videoSettings.GeneratePreview(video, out binaryBackground, out boundaries); result.Boundaries = boundaries.ToArray(); rbskVideo.GapDistance = GapDistance; rbskVideo.ThresholdValue = BinaryThreshold; rbskVideo.Video = video; rbskVideo.BackgroundImage = binaryBackground; rbskVideo.ProgressUpdates += (s, e) => { double progress = e.Progress; if (progress >= 1) { progress = 0.999; } Application.Current.Dispatcher.Invoke(() => { viewModel.ProgressValue = progress; }); }; rbskVideo.Process(); RbskVideo = null; //if (Stop) //{ // state.Stop(); // return; //} if (CancelTask) { return; } result.Results = rbskVideo.HeadPoints; result.GenerateResults(); result.VideoOutcome = SingleFileResult.Ok; //allResults.TryAdd(SelectedVideo, result); } Application.Current.Dispatcher.Invoke(() => { result.ResetFrames(); Results[SelectedVideo.Model] = result; CurrentResult = result; SliderValueChanged(); SaveCommand.RaiseCanExecuteChangedNotification(); viewModel.ProgressValue = 1; SelectedVideoChanged(); }); } catch (Exception e) { result.VideoOutcome = SingleFileResult.Error; result.Message = "Exception: " + SelectedVideo.VideoFileName + " - " + e.Message; //allResults.TryAdd(SelectedVideo, result); Application.Current.Dispatcher.Invoke(() => { viewModel.ProgressValue = 1; }); RbskVideo = null; } }); view.ShowDialog(); }
/// <summary> /// Converts the Revit elements that have been added to the stream by the user, sends them to /// the Server and the local DB, and creates a commit with the objects. /// </summary> /// <param name="state">StreamState passed by the UI</param> public override async Task SendStream(StreamState state, ProgressViewModel progress) { var kit = KitManager.GetDefaultKit(); var converter = kit.LoadConverter(ConnectorRevitUtils.RevitAppName); converter.SetContextDocument(CurrentDoc.Document); var streamId = state.StreamId; var client = state.Client; var selectedObjects = GetSelectionFilterObjects(state.Filter); state.SelectedObjectIds = selectedObjects.Select(x => x.UniqueId).ToList(); if (!selectedObjects.Any()) { progress.Report.LogOperationError(new Exception("There are zero objects to send. Please use a filter, or set some via selection.")); return; } converter.SetContextObjects(selectedObjects.Select(x => new ApplicationPlaceholderObject { applicationId = x.UniqueId }).ToList()); var commitObject = new Base(); var conversionProgressDict = new ConcurrentDictionary <string, int>(); conversionProgressDict["Conversion"] = 0; progress.Max = selectedObjects.Count(); var convertedCount = 0; var placeholders = new List <Base>(); foreach (var revitElement in selectedObjects) { try { if (revitElement == null) { continue; } if (!converter.CanConvertToSpeckle(revitElement)) { progress.Report.Log($"Skipped not supported type: {revitElement.GetType()}, name {revitElement.Name}"); continue; } if (progress.CancellationTokenSource.Token.IsCancellationRequested) { return; } var conversionResult = converter.ConvertToSpeckle(revitElement); conversionProgressDict["Conversion"]++; progress.Update(conversionProgressDict); placeholders.Add(new ApplicationPlaceholderObject { applicationId = revitElement.UniqueId, ApplicationGeneratedId = revitElement.UniqueId }); convertedCount++; //hosted elements will be returned as `null` by the ConvertToSpeckle method //since they are handled when converting their parents if (conversionResult != null) { var category = $"@{revitElement.Category.Name}"; if (commitObject[category] == null) { commitObject[category] = new List <Base>(); } ((List <Base>)commitObject[category]).Add(conversionResult); } } catch (Exception e) { progress.Report.LogConversionError(e); } } progress.Report.Merge(converter.Report); if (convertedCount == 0) { progress.Report.LogConversionError(new Exception("Zero objects converted successfully. Send stopped.")); return; } if (progress.CancellationTokenSource.Token.IsCancellationRequested) { return; } var transports = new List <ITransport>() { new ServerTransport(client.Account, streamId) }; var objectId = await Operations.Send( @object : commitObject, cancellationToken : progress.CancellationTokenSource.Token, transports : transports, onProgressAction : dict => progress.Update(dict), onErrorAction : (s, e) => { progress.Report.LogOperationError(e); progress.CancellationTokenSource.Cancel(); }, disposeTransports : true ); if (progress.Report.OperationErrorsCount != 0) { return; } if (progress.CancellationTokenSource.Token.IsCancellationRequested) { return; } var actualCommit = new CommitCreateInput() { streamId = streamId, objectId = objectId, branchName = state.BranchName, message = state.CommitMessage != null ? state.CommitMessage : $"Sent {convertedCount} objects from {ConnectorRevitUtils.RevitAppName}.", sourceApplication = ConnectorRevitUtils.RevitAppName, }; if (state.PreviousCommitId != null) { actualCommit.parents = new List <string>() { state.PreviousCommitId }; } try { var commitId = await client.CommitCreate(actualCommit); //await state.RefreshStream(); state.PreviousCommitId = commitId; } catch (Exception e) { progress.Report.LogOperationError(e); } //return state; }
private List <string> GetObjectsFromFilter(ISelectionFilter filter, ISpeckleConverter converter, ProgressViewModel progress) { var selection = new List <string>(); switch (filter.Slug) { case "all": return(Model.ConvertibleObjects(converter)); case "level": foreach (var levelName in filter.Selection) { var levelCache = Model.GetFileLevelCache(); var levelHandle = levelCache.GetLevelByName(levelName); var levelId = levelHandle.LevelId; var graphicElements = Model.GetGraphicElements(); var elementEnumerator = (ModelElementsEnumerator)graphicElements.GetEnumerator(); var objs = graphicElements.Where(el => el.LevelId == levelId).Select(el => el.ElementId.ToString()).ToList(); selection.AddRange(objs); } return(selection); case "elementType": foreach (var typeName in filter.Selection) { MSElementType selectedType = MSElementType.None; switch (typeName) { case "Arc": selectedType = MSElementType.Arc; break; case "Ellipse": selectedType = MSElementType.Ellipse; break; case "Line": selectedType = MSElementType.Line; break; case "Spline": selectedType = MSElementType.BsplineCurve; break; case "Line String": selectedType = MSElementType.LineString; break; case "Complex Chain": selectedType = MSElementType.ComplexString; break; case "Shape": selectedType = MSElementType.Shape; break; case "Complex Shape": selectedType = MSElementType.ComplexShape; break; case "Mesh": selectedType = MSElementType.MeshHeader; break; case "Surface": selectedType = MSElementType.BsplineSurface; break; default: break; } var graphicElements = Model.GetGraphicElements(); var elementEnumerator = (ModelElementsEnumerator)graphicElements.GetEnumerator(); var objs = graphicElements.Where(el => el.ElementType == selectedType).Select(el => el.ElementId.ToString()).ToList(); selection.AddRange(objs); } return(selection); #if (OPENROADS || OPENRAIL) case "civilElementType": foreach (var typeName in filter.Selection) { switch (typeName) { case "Alignment": var alignments = GeomModel.Alignments; if (alignments != null) { if (alignments.Count() > 0) { selection.Add("Alignment"); } } break; case "Corridor": var corridors = GeomModel.Corridors; if (corridors != null) { if (corridors.Count() > 0) { selection.Add("Corridor"); } } break; default: break; } } return(selection); #endif default: progress.Report.LogConversionError(new Exception("Filter type is not supported in this app. Why did the developer implement it in the first place?")); return(selection); } }
//// Get for Tickets Graph public ActionResult TicketProgress() { var user = db.Users.Find(User.Identity.GetUserId()); var proj = user.Projects.Where(p => p.ProjectArchieved == false).ToList(); if (User.IsInRole("Admin")) { proj = db.Projects.Where(p => p.ProjectArchieved == false).ToList(); } var pvmList = new List<ProgressViewModel>(); foreach (var item in proj) { var pvm = new ProgressViewModel(); var projTickets = item.Tickets.ToList(); pvm.projectName= item.ProjectName; pvm.totalTickets = projTickets.Count(); pvm.closedTickets = projTickets.Where(c => c.TicketStatus.StatusName == "Close").Count(); pvm.unassignedTickets = projTickets.Where(c => c.TicketStatus.StatusName == "Unassigned").Count(); pvm.holdTickets = projTickets.Where(c => c.TicketStatus.StatusName == "On Hold").Count(); var asgn = projTickets.Where(a => a.TicketStatus.StatusName == "Assigned").Count(); var reasgn = projTickets.Where(a => a.TicketStatus.StatusName == "Reassigned").Count(); var test = projTickets.Where(a => a.TicketStatus.StatusName == "Testing").Count(); var open = projTickets.Where(a => a.TicketStatus.StatusName == "Open").Count(); pvm.inProgress = asgn + reasgn + test + open; if (pvm.totalTickets > 0) { //pvm.closedPer = Convert.ToInt32(((double)pvm.closedTickets / (double)pvm.totalTickets) * 100); pvm.closedPer = Convert.ToDouble(((double)pvm.closedTickets / (double)pvm.totalTickets) * 100); pvm.closedPer = Math.Round(pvm.closedPer, 2); } else { pvm.closedPer = 0; } pvmList.Add(pvm); } return View(pvmList); }
public override async Task <StreamState> ReceiveStream(StreamState state, ProgressViewModel progress) { var kit = KitManager.GetDefaultKit(); var converter = kit.LoadConverter(Utils.BentleyAppName); var transport = new ServerTransport(state.Client.Account, state.StreamId); var stream = await state.Client.StreamGet(state.StreamId); var previouslyReceivedObjects = state.ReceivedObjects; if (converter == null) { throw new Exception("Could not find any Kit!"); } if (Control.InvokeRequired) { Control.Invoke(new SetContextDelegate(converter.SetContextDocument), new object[] { Session.Instance }); } else { converter.SetContextDocument(Session.Instance); } if (progress.CancellationTokenSource.Token.IsCancellationRequested) { return(null); } /* * if (Doc == null) * { * progress.Report.LogOperationError(new Exception($"No Document is open.")); * progress.CancellationTokenSource.Cancel(); * } */ //if "latest", always make sure we get the latest commit when the user clicks "receive" Commit commit = null; if (state.CommitId == "latest") { var res = await state.Client.BranchGet(progress.CancellationTokenSource.Token, state.StreamId, state.BranchName, 1); commit = res.commits.items.FirstOrDefault(); } else { commit = await state.Client.CommitGet(progress.CancellationTokenSource.Token, state.StreamId, state.CommitId); } string referencedObject = commit.referencedObject; var commitObject = await Operations.Receive( referencedObject, progress.CancellationTokenSource.Token, transport, onProgressAction : dict => progress.Update(dict), onTotalChildrenCountKnown : num => Execute.PostToUIThread(() => progress.Max = num), onErrorAction : (message, exception) => { progress.Report.LogOperationError(exception); progress.CancellationTokenSource.Cancel(); }, disposeTransports : true ); try { await state.Client.CommitReceived(new CommitReceivedInput { streamId = stream?.id, commitId = commit?.id, message = commit?.message, sourceApplication = Utils.BentleyAppName }); } catch { // Do nothing! } if (progress.Report.OperationErrorsCount != 0) { return(state); } // invoke conversions on the main thread via control var flattenedObjects = FlattenCommitObject(commitObject, converter); List <ApplicationPlaceholderObject> newPlaceholderObjects; if (Control.InvokeRequired) { newPlaceholderObjects = (List <ApplicationPlaceholderObject>)Control.Invoke(new NativeConversionAndBakeDelegate(ConvertAndBakeReceivedObjects), new object[] { flattenedObjects, converter, state, progress }); } else { newPlaceholderObjects = ConvertAndBakeReceivedObjects(flattenedObjects, converter, state, progress); } if (newPlaceholderObjects == null) { converter.Report.ConversionErrors.Add(new Exception("fatal error: receive cancelled by user")); return(null); } DeleteObjects(previouslyReceivedObjects, newPlaceholderObjects); state.ReceivedObjects = newPlaceholderObjects; progress.Report.Merge(converter.Report); if (progress.Report.OperationErrorsCount != 0) { return(null); // the commit is being rolled back } try { //await state.RefreshStream(); WriteStateToFile(); } catch (Exception e) { progress.Report.OperationErrors.Add(e); } return(state); }
public async Task <IActionResult> Index() { //get all rivers out of db with total length of river //give me the floats where userid= logged in user and river id is 1 - 2 - 3 //add up mileage from each float on the river to end up with 3 rivers and 3 separate totals //viewmodel depends on what progress bar needs //Get current user var user = await GetCurrentUserAsync(); //var river = await _context.River.ToListAsync(); if (user == null) { return(View("Welcome")); } else { ProgressViewModel viewModel = new ProgressViewModel(); //Get all of the float Trips for each of the 5 Rivers var River1Total = await _context.FloatTrip.Include(f => f.River).Include(f => f.User).Where(r => r.UserId == user.Id && r.RiverId == 1) .ToListAsync(); if (River1Total.Count > 0) { viewModel.River1 = River1Total.First().River; } float?totalMilesR1 = 0; float TotalLengthR1 = viewModel.River1.TotalLength; float?ProgressBarR1 = 0; foreach (var item in River1Total) { if (item.Distance != null) { totalMilesR1 += item.Distance; } } viewModel.DistanceTraveledOnRiver1 = totalMilesR1; ProgressBarR1 = totalMilesR1 / TotalLengthR1 * 100; viewModel.PercentofRiver1 = $"{Math.Round((decimal)ProgressBarR1)}%"; var River2Total = await _context.FloatTrip.Include(f => f.River).Include(f => f.User).Where(r => r.UserId == user.Id && r.RiverId == 2) .ToListAsync(); if (River2Total.Count > 0) { viewModel.River2 = River2Total.First().River; } float?totalMilesR2 = 0; float TotalLengthR2 = viewModel.River2.TotalLength; float?ProgressBarR2 = 0; foreach (var item in River2Total) { if (item.Distance != null) { totalMilesR2 += item.Distance; } } viewModel.DistanceTraveledOnRiver2 = totalMilesR2; ProgressBarR2 = (totalMilesR2 / TotalLengthR2) * 100; viewModel.PercentofRiver2 = $"{Math.Round((decimal)ProgressBarR2)}%"; var River3Total = await _context.FloatTrip.Include(f => f.River).Include(f => f.User).Where(r => r.UserId == user.Id && r.RiverId == 3) .ToListAsync(); if (River3Total.Count > 0) { viewModel.River3 = River3Total.First().River; } float?totalMilesR3 = 0; float TotalLengthR3 = viewModel.River3.TotalLength; float?ProgressBarR3 = 0; foreach (var item in River3Total) { if (item.Distance != null) { totalMilesR3 += item.Distance; } } viewModel.DistanceTraveledOnRiver3 = totalMilesR3; ProgressBarR3 = (totalMilesR3 / TotalLengthR3) * 100; viewModel.PercentofRiver3 = $"{Math.Round((decimal)ProgressBarR3)}%"; var River4Total = await _context.FloatTrip.Include(f => f.River).Include(f => f.User).Where(r => r.UserId == user.Id && r.RiverId == 4) .ToListAsync(); if (River4Total.Count > 0) { viewModel.River4 = River4Total.First().River; } float?totalMilesR4 = 0; float TotalLengthR4 = viewModel.River4.TotalLength; float?ProgressBarR4 = 0; foreach (var item in River4Total) { if (item.Distance != null) { totalMilesR4 += item.Distance; } } viewModel.DistanceTraveledOnRiver4 = totalMilesR4; ProgressBarR4 = (totalMilesR4 / TotalLengthR4) * 100; viewModel.PercentofRiver4 = $"{Math.Round((decimal)ProgressBarR4)}%"; var River5Total = await _context.FloatTrip.Include(f => f.River).Include(f => f.User).Where(r => r.UserId == user.Id && r.RiverId == 5) .ToListAsync(); if (River5Total.Count > 0) { viewModel.River5 = River5Total.First().River; } float?totalMilesR5 = 0; float TotalLengthR5 = viewModel.River5.TotalLength; float?ProgressBarR5 = 0; foreach (var item in River5Total) { if (item.Distance != null) { totalMilesR5 += item.Distance; } } viewModel.DistanceTraveledOnRiver5 = totalMilesR5; ProgressBarR5 = (totalMilesR5 / TotalLengthR5) * 100; viewModel.PercentofRiver5 = $"{Math.Round((decimal)ProgressBarR5)}%"; return(View(viewModel)); } }
private void ShowProgressDialog(ProgressViewModel progressVM) { LaunchAction(() => this.dlgService.ShowDialog <ProgressDialog>(progressVM)); }
/// <summary> /// Generate C header files for a list of project items. /// </summary> /// <param name="projectItems">A list of project items.</param> private void ProcessFiles(IReadOnlyCollection <ProjectItem> projectItems) { bool showIncludeGuard; bool autoSaveFiles; var codeWriter = new CHeaderFileWriter(); // Add Options using (var options = GetDialogPage(typeof(CSourceFileOptions)) as CSourceFileOptions) { codeWriter.HeaderComment = SetHeaderComment(options.HeaderComment); codeWriter.IncludeStaticFunctions = options.IncludeStaticFunctions; codeWriter.IncludeExternFunctions = options.IncludeExternFunctions; showIncludeGuard = options.ShowIncludeGuard; autoSaveFiles = options.AutoSaveFiles; } // Initialize viewmodel to keep track of progress using (var progressVM = new ProgressViewModel { Minimum = 0.0, Maximum = 1.0, Message = "Starting...", ProgressValue = 0.0 }) { this.ShowProgressDialog(progressVM); int i = 0; foreach (var projectItem in projectItems) { if (projectItem.Document != null && !projectItem.Document.Saved && autoSaveFiles) { projectItem.Document.Save(); } string file = projectItem.FileNames[0]; string itemToAdd = GetItemFileName(file); bool error = false; try { // Parse the file log.Info("Processing {0}/{1}: {2}", ++i, projectItems.Count, file); progressVM.Message = string.Format("{0}/{1}: Processing {2}", i, projectItems.Count, file); if (!ParseItem(file, itemToAdd, codeWriter, showIncludeGuard, projectItem)) { break; } progressVM.ProgressValue = Convert.ToDouble(i); } catch (ParserException tex) { // Go to file/line where the error occurred and display a dialog with the error message. var window = ApplicationObject.ItemOperations.OpenFile(file); window.Activate(); if (tex.LineNumber > 0) { var textSelection = window.Selection as TextSelection; if (textSelection != null) { textSelection.GotoLine(tex.LineNumber, true); } } log.Error(string.Format("Failed to parse file: {0}", file), tex); this.ShowExceptionDialog(tex, string.Format("Failed to parse file: {0}", file)); error = true; } catch (Exception ex) { // Show a dialog with a less-than-helpful exception message. log.Error(string.Format("Unknown error while parsing file: {0}", file), ex); this.ShowExceptionDialog(ex, string.Format("Unknown exception while parsing: {0}", file)); error = true; } finally { // Log the result of the parse operation. var messageBuilder = new System.Text.StringBuilder(); messageBuilder.AppendFormat("Completed processing file {0}/{1}: {2}.", i, projectItems.Count, file); if (error) { messageBuilder.Append(" There were one or more errors detected during processing."); } else { messageBuilder.Append(" The operation was completed successfully."); } log.Info(messageBuilder.ToString()); } } } }
private List <ApplicationPlaceholderObject> ConvertReceivedObjects(List <Base> objects, ISpeckleConverter converter, StreamState state, ProgressViewModel progress) { var placeholders = new List <ApplicationPlaceholderObject>(); var conversionProgressDict = new ConcurrentDictionary <string, int>(); conversionProgressDict["Conversion"] = 1; foreach (var @base in objects) { if (progress.CancellationTokenSource.Token.IsCancellationRequested) { placeholders = null; break; } try { conversionProgressDict["Conversion"]++; // wrapped in a dispatcher not to block the ui progress.Update(conversionProgressDict); var convRes = converter.ConvertToNative(@base); if (convRes is ApplicationPlaceholderObject placeholder) { placeholders.Add(placeholder); } else if (convRes is List <ApplicationPlaceholderObject> placeholderList) { placeholders.AddRange(placeholderList); } } catch (Exception e) { progress.Report.LogConversionError(e); } } return(placeholders); }
public override async Task SendStream(StreamState state, ProgressViewModel progress) { var kit = KitManager.GetDefaultKit(); var converter = kit.LoadConverter(Utils.AutocadAppName); var streamId = state.StreamId; var client = state.Client; if (state.Filter != null) { state.SelectedObjectIds = GetObjectsFromFilter(state.Filter, converter); } // remove deleted object ids var deletedElements = new List <string>(); foreach (var handle in state.SelectedObjectIds) { if (Doc.Database.TryGetObjectId(Utils.GetHandle(handle), out ObjectId id)) { if (id.IsErased || id.IsNull) { deletedElements.Add(handle); } } } state.SelectedObjectIds = state.SelectedObjectIds.Where(o => !deletedElements.Contains(o)).ToList(); if (state.SelectedObjectIds.Count == 0) { progress.Report.LogOperationError(new Exception("Zero objects selected; send stopped. Please select some objects, or check that your filter can actually select something.")); return; } var commitObj = new Base(); var units = Units.GetUnitsFromString(Doc.Database.Insunits.ToString()); commitObj["units"] = units; var conversionProgressDict = new ConcurrentDictionary <string, int>(); conversionProgressDict["Conversion"] = 0; Execute.PostToUIThread(() => progress.Max = state.SelectedObjectIds.Count()); int convertedCount = 0; bool renamedlayers = false; using (Transaction tr = Doc.Database.TransactionManager.StartTransaction()) { // set the context doc for conversion - this is set inside the transaction loop because the converter retrieves this transaction for all db editing when the context doc is set! converter.SetContextDocument(Doc); foreach (var autocadObjectHandle in state.SelectedObjectIds) { if (progress.CancellationTokenSource.Token.IsCancellationRequested) { return; } // get the db object from id Handle hn = Utils.GetHandle(autocadObjectHandle); DBObject obj = hn.GetObject(out string type, out string layer); if (obj == null) { progress.Report.Log($"Skipped not found object: ${autocadObjectHandle}."); continue; } if (!converter.CanConvertToSpeckle(obj)) { progress.Report.Log($"Skipped not supported type: ${type}. Object ${obj.Id} not sent."); continue; } // convert obj Base converted = null; string containerName = string.Empty; converted = converter.ConvertToSpeckle(obj); if (converted == null) { progress.Report.LogConversionError(new Exception($"Failed to convert object {autocadObjectHandle} of type {type}.")); continue; } /* TODO: adding the extension dictionary / xdata per object * foreach (var key in obj.ExtensionDictionary) * { * converted[key] = obj.ExtensionDictionary.GetUserString(key); * } */ if (obj is BlockReference) { containerName = "Blocks"; } else { // remove invalid chars from layer name string cleanLayerName = Utils.RemoveInvalidDynamicPropChars(layer); containerName = cleanLayerName; if (!cleanLayerName.Equals(layer)) { renamedlayers = true; } } if (commitObj[$"@{containerName}"] == null) { commitObj[$"@{containerName}"] = new List <Base>(); } ((List <Base>)commitObj[$"@{containerName}"]).Add(converted); conversionProgressDict["Conversion"]++; progress.Update(conversionProgressDict); converted.applicationId = autocadObjectHandle; convertedCount++; } tr.Commit(); } progress.Report.Merge(converter.Report); if (convertedCount == 0) { progress.Report.LogOperationError(new SpeckleException("Zero objects converted successfully. Send stopped.", false)); return; } if (renamedlayers) { progress.Report.Log("Replaced illegal chars ./ with - in one or more layer names."); } if (progress.CancellationTokenSource.Token.IsCancellationRequested) { return; } Execute.PostToUIThread(() => progress.Max = convertedCount); var transports = new List <ITransport>() { new ServerTransport(client.Account, streamId) }; var commitObjId = await Operations.Send( commitObj, progress.CancellationTokenSource.Token, transports, onProgressAction : dict => progress.Update(dict), onErrorAction : (err, exception) => { progress.Report.LogOperationError(exception); progress.CancellationTokenSource.Cancel(); }, disposeTransports : true ); if (progress.Report.OperationErrorsCount != 0) { return; } var actualCommit = new CommitCreateInput { streamId = streamId, objectId = commitObjId, branchName = state.BranchName, message = state.CommitMessage != null ? state.CommitMessage : $"Pushed {convertedCount} elements from {Utils.AppName}.", sourceApplication = Utils.AutocadAppName }; if (state.PreviousCommitId != null) { actualCommit.parents = new List <string>() { state.PreviousCommitId }; } try { var commitId = await client.CommitCreate(actualCommit); state.PreviousCommitId = commitId; } catch (Exception e) { progress.Report.LogOperationError(e); } }
public override async Task SendStream(StreamState state, ProgressViewModel progress) { //throw new NotImplementedException(); var kit = KitManager.GetDefaultKit(); //var converter = new ConverterETABS(); var converter = kit.LoadConverter(ConnectorETABSUtils.ETABSAppName); converter.SetContextDocument(Model); Exceptions.Clear(); var commitObj = new Base(); int objCount = 0; if (state.Filter != null) { state.SelectedObjectIds = GetSelectionFilterObjects(state.Filter); } var totalObjectCount = state.SelectedObjectIds.Count(); if (totalObjectCount == 0) { progress.Report.LogOperationError(new SpeckleException("Zero objects selected; send stopped. Please select some objects, or check that your filter can actually select something.", false)); return; } var conversionProgressDict = new ConcurrentDictionary <string, int>(); conversionProgressDict["Conversion"] = 0; progress.Update(conversionProgressDict); //if( commitObj["@Stories"] == null) //{ // commitObj["@Stories"] = converter.ConvertToSpeckle(("Stories", "ETABS")); //} foreach (var applicationId in state.SelectedObjectIds) { if (progress.CancellationTokenSource.Token.IsCancellationRequested) { return; } Base converted = null; string containerName = string.Empty; var selectedObjectType = ConnectorETABSUtils.ObjectIDsTypesAndNames .Where(pair => pair.Key == applicationId) .Select(pair => pair.Value.Item1).FirstOrDefault(); if (!converter.CanConvertToSpeckle(selectedObjectType)) { progress.Report.Log($"Skipped not supported type: ${selectedObjectType} are not supported"); continue; } Tracker.TrackPageview(Tracker.CONVERT_TOSPECKLE); var typeAndName = ConnectorETABSUtils.ObjectIDsTypesAndNames .Where(pair => pair.Key == applicationId) .Select(pair => pair.Value).FirstOrDefault(); converted = converter.ConvertToSpeckle(typeAndName); if (converted == null) { var exception = new Exception($"Failed to convert object ${applicationId} of type ${selectedObjectType}."); progress.Report.LogConversionError(exception); continue; } //if (converted != null) //{ // if (commitObj[selectedObjectType] == null) // { // commitObj[selectedObjectType] = new List<Base>(); // } // ((List<Base>)commitObj[selectedObjectType]).Add(converted); //} //objCount++; conversionProgressDict["Conversion"]++; progress.Update(conversionProgressDict); } Base ElementCount = converter.ConvertToSpeckle(("ElementsCount", "ETABS")); if (ElementCount.applicationId != null) { objCount = Convert.ToInt32(ElementCount.applicationId); } else { objCount = 0; } if (commitObj["@Model"] == null) { commitObj["@Model"] = converter.ConvertToSpeckle(("Model", "ETABS")); } if (commitObj["AnalysisResults"] == null) { commitObj["AnalysisResults"] = converter.ConvertToSpeckle(("AnalysisResults", "ETABS")); } progress.Report.Merge(converter.Report); if (objCount == 0) { progress.Report.LogOperationError(new SpeckleException("Zero objects converted successfully. Send stopped.", false)); return; } if (progress.CancellationTokenSource.Token.IsCancellationRequested) { return; } var streamId = state.StreamId; var client = state.Client; var transports = new List <SCT.ITransport>() { new SCT.ServerTransport(client.Account, streamId) }; var objectId = await Operations.Send( @object : commitObj, cancellationToken : progress.CancellationTokenSource.Token, transports : transports, onProgressAction : dict => progress.Update(dict), onErrorAction : (Action <string, Exception>)((s, e) => { progress.Report.LogOperationError(e); progress.CancellationTokenSource.Cancel(); }), disposeTransports : true ); if (progress.Report.OperationErrorsCount != 0) { //RaiseNotification($"Failed to send: \n {Exceptions.Last().Message}"); return; } var actualCommit = new CommitCreateInput { streamId = streamId, objectId = objectId, branchName = state.BranchName, message = state.CommitMessage != null ? state.CommitMessage : $"Pushed {objCount} elements from ETABS.", sourceApplication = ConnectorETABSUtils.ETABSAppName }; if (state.PreviousCommitId != null) { actualCommit.parents = new List <string>() { state.PreviousCommitId }; } try { var commitId = await client.CommitCreate(actualCommit); //await state.RefreshStream(); state.PreviousCommitId = commitId; //PersistAndUpdateStreamInFile(state); //RaiseNotification($"{objCount} objects sent to {state.Stream.name}. 🚀"); } catch (Exception e) { //Globals.Notify($"Failed to create commit.\n{e.Message}"); progress.Report.LogOperationError(e); } //return state; }
private List <ApplicationPlaceholderObject> ConvertAndBakeReceivedObjects(List <Base> objects, ISpeckleConverter converter, StreamState state, ProgressViewModel progress) { var placeholders = new List <ApplicationPlaceholderObject>(); var conversionProgressDict = new ConcurrentDictionary <string, int>(); conversionProgressDict["Conversion"] = 0; Execute.PostToUIThread(() => progress.Max = state.SelectedObjectIds.Count()); Action updateProgressAction = () => { conversionProgressDict["Conversion"]++; progress.Update(conversionProgressDict); }; foreach (var @base in objects) { if (progress.CancellationTokenSource.Token.IsCancellationRequested) { placeholders = null; break; } try { var convRes = converter.ConvertToNative(@base); if (convRes is ApplicationPlaceholderObject placeholder) { placeholders.Add(placeholder); } else if (convRes is List <ApplicationPlaceholderObject> placeholderList) { placeholders.AddRange(placeholderList); } // creating new elements, not updating existing! var convertedElement = convRes as Element; if (convertedElement != null) { var status = convertedElement.AddToModel(); if (status == StatusInt.Error) { converter.Report.LogConversionError(new Exception($"Failed to bake object {@base.id} of type {@base.speckle_type}.")); } } else { converter.Report.LogConversionError(new Exception($"Failed to convert object {@base.id} of type {@base.speckle_type}.")); } } catch (Exception e) { converter.Report.LogConversionError(e); } } return(placeholders); }
/// <summary> /// Receives a stream and bakes into the existing revit file. /// </summary> /// <param name="state"></param> /// <returns></returns> public override async Task <StreamState> ReceiveStream(StreamState state, ProgressViewModel progress) { var kit = KitManager.GetDefaultKit(); var converter = kit.LoadConverter(ConnectorRevitUtils.RevitAppName); converter.SetContextDocument(CurrentDoc.Document); var previouslyReceiveObjects = state.ReceivedObjects; var transport = new ServerTransport(state.Client.Account, state.StreamId); var stream = await state.Client.StreamGet(state.StreamId); if (progress.CancellationTokenSource.Token.IsCancellationRequested) { return(null); } Commit myCommit = null; //if "latest", always make sure we get the latest commit when the user clicks "receive" if (state.CommitId == "latest") { var res = await state.Client.BranchGet(progress.CancellationTokenSource.Token, state.StreamId, state.BranchName, 1); myCommit = res.commits.items.FirstOrDefault(); } else { myCommit = await state.Client.CommitGet(progress.CancellationTokenSource.Token, state.StreamId, state.CommitId); } string referencedObject = myCommit.referencedObject; var commitObject = await Operations.Receive( referencedObject, progress.CancellationTokenSource.Token, transport, onProgressAction : dict => progress.Update(dict), onErrorAction : (s, e) => { progress.Report.LogOperationError(e); progress.CancellationTokenSource.Cancel(); }, onTotalChildrenCountKnown : count => { progress.Max = count; }, disposeTransports : true ); try { await state.Client.CommitReceived(new CommitReceivedInput { streamId = stream?.id, commitId = myCommit?.id, message = myCommit?.message, sourceApplication = ConnectorRevitUtils.RevitAppName }); } catch { // Do nothing! } if (progress.Report.OperationErrorsCount != 0) { return(state); } if (progress.CancellationTokenSource.Token.IsCancellationRequested) { return(null); } await RevitTask.RunAsync(app => { using (var t = new Transaction(CurrentDoc.Document, $"Baking stream {state.StreamId}")) { var failOpts = t.GetFailureHandlingOptions(); failOpts.SetFailuresPreprocessor(new ErrorEater(converter)); failOpts.SetClearAfterRollback(true); t.SetFailureHandlingOptions(failOpts); t.Start(); var flattenedObjects = FlattenCommitObject(commitObject, converter); // needs to be set for editing to work converter.SetPreviousContextObjects(previouslyReceiveObjects); // needs to be set for openings in floors and roofs to work converter.SetContextObjects(flattenedObjects.Select(x => new ApplicationPlaceholderObject { applicationId = x.applicationId, NativeObject = x }).ToList()); var newPlaceholderObjects = ConvertReceivedObjects(flattenedObjects, converter, state, progress); // receive was cancelled by user if (newPlaceholderObjects == null) { progress.Report.LogConversionError(new Exception("fatal error: receive cancelled by user")); t.RollBack(); return; } DeleteObjects(previouslyReceiveObjects, newPlaceholderObjects); state.ReceivedObjects = newPlaceholderObjects; t.Commit(); progress.Report.Merge(converter.Report); } }); if (converter.Report.ConversionErrors.Any(x => x.Message.Contains("fatal error"))) { // the commit is being rolled back return(null); } return(state); }
public override async Task SendStream(StreamState state, ProgressViewModel progress) { var kit = KitManager.GetDefaultKit(); var converter = kit.LoadConverter(Utils.BentleyAppName); var streamId = state.StreamId; var client = state.Client; if (Control.InvokeRequired) { Control.Invoke(new SetContextDelegate(converter.SetContextDocument), new object[] { Session.Instance }); } else { converter.SetContextDocument(Session.Instance); } var selectedObjects = new List <Object>(); if (state.Filter != null) { if (Control.InvokeRequired) { state.SelectedObjectIds = (List <string>)Control.Invoke(new GetObjectsFromFilterDelegate(GetObjectsFromFilter), new object[] { state.Filter, converter, progress }); } else { state.SelectedObjectIds = GetObjectsFromFilter(state.Filter, converter, progress); } } if (state.SelectedObjectIds.Count == 0 && !ExportGridLines) { progress.Report.LogOperationError(new Exception("Zero objects selected; send stopped. Please select some objects, or check that your filter can actually select something.")); return; } var commitObj = new Base(); var units = Units.GetUnitsFromString(ModelUnits).ToLower(); commitObj["units"] = units; var conversionProgressDict = new ConcurrentDictionary <string, int>(); conversionProgressDict["Conversion"] = 0; Execute.PostToUIThread(() => progress.Max = state.SelectedObjectIds.Count()); int convertedCount = 0; // grab elements from active model var objs = new List <Element>(); #if (OPENROADS || OPENRAIL) bool convertCivilObject = false; var civObjs = new List <NamedModelEntity>(); if (civilElementKeys.Count(x => state.SelectedObjectIds.Contains(x)) > 0) { if (Control.InvokeRequired) { civObjs = (List <NamedModelEntity>)Control.Invoke(new GetCivilObjectsDelegate(GetCivilObjects), new object[] { state }); } else { civObjs = GetCivilObjects(state); } objs = civObjs.Select(x => x.Element).ToList(); convertCivilObject = true; } else { objs = state.SelectedObjectIds.Select(x => Model.FindElementById((ElementId)Convert.ToUInt64(x))).ToList(); } #else objs = state.SelectedObjectIds.Select(x => Model.FindElementById((ElementId)Convert.ToUInt64(x))).ToList(); #endif #if (OPENBUILDINGS) if (ExportGridLines) { var converted = ConvertGridLines(converter, progress); if (converted == null) { progress.Report.LogConversionError(new Exception($"Failed to convert Gridlines.")); } else { var containerName = "Grid Systems"; if (commitObj[$"@{containerName}"] == null) { commitObj[$"@{containerName}"] = new List <Base>(); } ((List <Base>)commitObj[$"@{containerName}"]).Add(converted); // not sure this makes much sense here conversionProgressDict["Conversion"]++; progress.Update(conversionProgressDict); convertedCount++; } } #endif foreach (var obj in objs) { if (progress.CancellationTokenSource.Token.IsCancellationRequested) { return; } if (obj == null) { progress.Report.Log($"Skipped not found object."); continue; } var objId = obj.ElementId.ToString(); var objType = obj.ElementType; if (!converter.CanConvertToSpeckle(obj)) { progress.Report.Log($"Skipped not supported type: ${objType}. Object ${objId} not sent."); continue; } // convert obj Base converted = null; string containerName = string.Empty; try { var levelCache = Model.GetFileLevelCache(); var objLevel = levelCache.GetLevel(obj.LevelId); var layerName = "Unknown"; if (objLevel != null) { layerName = objLevel.Name; } #if (OPENROADS || OPENRAIL) if (convertCivilObject) { var civilObj = civObjs[objs.IndexOf(obj)]; if (Control.InvokeRequired) { converted = (Base)Control.Invoke(new SpeckleConversionDelegate(converter.ConvertToSpeckle), new object[] { civilObj }); Control.Invoke((Action)(() => { containerName = civilObj.Name == "" ? "Unnamed" : civilObj.Name; })); } else { converted = converter.ConvertToSpeckle(civilObj); containerName = civilObj.Name == "" ? "Unnamed" : civilObj.Name; } } else { if (Control.InvokeRequired) { converted = (Base)Control.Invoke(new SpeckleConversionDelegate(converter.ConvertToSpeckle), new object[] { obj }); } else { converted = converter.ConvertToSpeckle(obj); } containerName = layerName; } #else if (Control.InvokeRequired) { converted = (Base)Control.Invoke(new SpeckleConversionDelegate(converter.ConvertToSpeckle), new object[] { obj }); } else { converted = converter.ConvertToSpeckle(obj); } containerName = layerName; #endif if (converted == null) { progress.Report.LogConversionError(new Exception($"Failed to convert object {objId} of type {objType}.")); continue; } } catch { progress.Report.LogConversionError(new Exception($"Failed to convert object {objId} of type {objType}.")); continue; } /* TODO: adding the feature data and properties per object * foreach (var key in obj.ExtensionDictionary) * { * converted[key] = obj.ExtensionDictionary.GetUserString(key); * } */ if (commitObj[$"@{containerName}"] == null) { commitObj[$"@{containerName}"] = new List <Base>(); } ((List <Base>)commitObj[$"@{containerName}"]).Add(converted); conversionProgressDict["Conversion"]++; progress.Update(conversionProgressDict); converted.applicationId = objId; convertedCount++; } progress.Report.Merge(converter.Report); if (progress.Report.OperationErrorsCount != 0) { return; } if (convertedCount == 0) { progress.Report.LogOperationError(new SpeckleException("Zero objects converted successfully. Send stopped.", false)); return; } if (progress.CancellationTokenSource.Token.IsCancellationRequested) { return; } Execute.PostToUIThread(() => progress.Max = convertedCount); var transports = new List <ITransport>() { new ServerTransport(client.Account, streamId) }; var commitObjId = await Operations.Send( commitObj, progress.CancellationTokenSource.Token, transports, onProgressAction : dict => progress.Update(dict), onErrorAction : (err, exception) => { progress.Report.LogOperationError(exception); progress.CancellationTokenSource.Cancel(); }, disposeTransports : true ); var actualCommit = new CommitCreateInput { streamId = streamId, objectId = commitObjId, branchName = state.BranchName, message = state.CommitMessage != null ? state.CommitMessage : $"Pushed {convertedCount} elements from {Utils.AppName}.", sourceApplication = Utils.BentleyAppName }; if (state.PreviousCommitId != null) { actualCommit.parents = new List <string>() { state.PreviousCommitId }; } try { var commitId = await client.CommitCreate(actualCommit); state.PreviousCommitId = commitId; } catch (Exception e) { progress.Report.LogOperationError(e); } }