Inheritance: INotifyPropertyChanged
示例#1
0
        public DesignerViewModel(int width, int height)
        {
            Width           = width;
            Height          = height;
            Selection       = new SelectionViewModel(Guid.NewGuid(), Vector2.Zero, Vector2.Zero);
            CreateSelection = new SelectionViewModel(Guid.NewGuid(), Vector2.Zero, Vector2.Zero)
            {
                BorderColor = Color.Green
            };

            NewConnectionPath = new PathViewModel();
            MousePoint        = new PointViewModel(Guid.NewGuid(), Vector2.Zero)
            {
                IsShown = false
            };

            ResizeDirection = ResizeDirection.None;

            Interactor.AddPoint      += UserInteractionManager_AddPoint;
            Interactor.CreateAt      += UserInteractionManager_CreateAt;
            Interactor.DeleteAt      += UserInteractionManager_DeleteAt;
            Interactor.SelectAt      += UserInteractionManager_SelectAt;
            Interactor.MouseMoved    += UserInteractionManager_MouseMoved;
            Interactor.MouseReleased += UserInteractionManager_MouseReleased;

            Interactor.MouseClicked       += Interactor_MouseClicked;
            Interactor.MouseDoubleClicked += Interactor_MouseDoubleClicked;
            Interactor.KeyPressed         += Interactor_KeyPressed;
        }
示例#2
0
        public async Task <IActionResult> Selection(Guid guid)
        {
            var model = await ApplicantDetailsRepository.LoadApplicantDetails(guid);

            int age = model.DateOfBirth.CalculateAge();

            var viewModel = new SelectionViewModel();
            var cards     = CardsRepository.LoadCards(age, model.AnnualIncome).ToList();

            if (cards.Any())
            {
                viewModel.Cards = cards;
                var searchResult = new SearchResult
                {
                    ResultsAsString       = string.Join(",", viewModel.Cards.Select(x => x.Name).ToList()),
                    ExtApplicantDetailsId = model.Id
                };

                searchResult.Initialize();

                await ApplicantDetailsRepository.Create(searchResult);
            }
            else
            {
                viewModel.Message = "No credit cards available.";
            }

            return(View(viewModel));
        }
示例#3
0
        public CalibratorViewModel(EyeTrackerCalibrator calibrator, ICalibrationProfilesService calibrations)
        {
            calibrator.ThrowIfNull(nameof(calibrator));

            _calibrator = calibrator;
            _calibrator.StateChanged += (_, __) => _commands.TryRaiseCanExecuteChanged();

            var plans = new List <CalibrationPlan>()
            {
                CalibrationPlansFactory.CreateBasicPlan9(),
                CalibrationPlansFactory.CreateBasicPlan5(),
                CalibrationPlansFactory.CreateDiamondPlan12(),
            };

            PlansSelection = new SelectionViewModel <CalibrationPlan>(plans)
            {
                SelectedIndex = 0
            };

            Calibration            = new CalibrationViewModel(_calibrator);
            Calibration.Completed += Calibration_Completed;
            Calibration.Cancelled += Calibration_Cancelled;

            HeadPosition       = new HeadPositioningViewModel(_calibrator.HeadPositioning);
            StoredCalibrations = new StoredCalibrationsViewModel(calibrations);
            StoredCalibrations.CalibrationLoaded += StoredCalibrations_CalibrationLoaded;
        }
示例#4
0
        /// <summary>
        /// Selects the single asynchronous.
        /// </summary>
        /// <returns>Task.</returns>
        private Task SelectSingleAsync()
        {
            var selectionVm = new SelectionViewModel <TestItem>(Context, BaseCommonServices, Logger, Items, SelectedTestItems, SelectionModes.Single);

            selectionVm.Submitted += SelectionVm_SingleSubmitted;
            return(BaseCommonServices.NavigationService.OpenBladeAsync(this, selectionVm));
        }
示例#5
0
        /// <summary>
        /// Creates a single export settings for the current selection.
        /// </summary>
        public static SingleExportSettings CreateForSelection(Preset preset)
        {
            SelectionViewModel svm = new SelectionViewModel(Instance.Default.Application);
            // If the ActiveChart property of the Excel application is not null,
            // either a chart or 'something in the chart' is selected. To make sure
            // we don't attempt to export 'something in the chart', we select the
            // entire chart.
            // If there is no workbook open, accessing the ActiveChart property causes
            // a COM exception.
            object activeChart = null;

            try
            {
                activeChart = Instance.Default.Application.ActiveChart;
            }
            catch (System.Runtime.InteropServices.COMException) { }
            finally
            {
                if (activeChart != null)
                {
                    ChartViewModel cvm = new ChartViewModel(activeChart as Chart);
                    // Handle chart sheets and embedded charts differently
                    cvm.SelectSpecial();
                }
            }
            if (svm.Selection != null)
            {
                return(new SingleExportSettings(preset, svm.Bounds.Width, svm.Bounds.Height));
            }
            else
            {
                return(new SingleExportSettings());
            }
        }
示例#6
0
 /// <summary>
 /// Copies the current selection to the clipboard.
 /// </summary>
 private bool CopySelection()
 {
     using (SelectionViewModel selection = new SelectionViewModel(Instance.Default.Application))
     {
         selection.CopyToClipboard();
     }
     return(true);
 }
示例#7
0
        protected override bool CanExport()
        {
            SelectionViewModel svm = new SelectionViewModel(Instance.Default.Application);

            return((svm.Selection != null) && (SelectedPreset != null) &&
                   (Settings.Preset != null) && (Settings.Preset.Dpi > 0) &&
                   (Width > 0) && (Height > 0));
        }
示例#8
0
        public async Task <IActionResult> Details(Guid id, SelectionViewModel selection)
        {
            if (await _movieService.AddActorAsync(id, selection.Selected) == null)
            {
                return(RedirectToAction(nameof(Details), new { Id = id }));
            }

            return(RedirectToAction(nameof(Details)));
        }
示例#9
0
        // GET: Selection
        public async Task <ActionResult> Index(CancellationToken cancellationToken)
        {
            var result = await new AuthorizationCodeMvcApp(this, new AppFlowMetadata()).AuthorizeAsync(cancellationToken);

            if (result.Credential != null)
            {
                var service = new DriveService(new BaseClientService.Initializer
                {
                    HttpClientInitializer = result.Credential,
                    ApplicationName       = ApplicationName
                });

                try
                {
                    var selectionViewModel = new SelectionViewModel();
                    var examLinksList      = new List <ExamLink>();

                    var request          = new BatchRequest(service);
                    var selectedPaperIds = string.Join(",", ((List <int>)Session["SelectedIds"]).ToArray());
                    var examPapers       = HttpDataProvider.GetData <List <dynamic> >(string.Format("exam/forids?examIds={0}", selectedPaperIds));

                    examPapers.ForEach(delegate(dynamic examPaper) {
                        string fileId = examPaper.FileStoreId;

                        request.Queue <Google.Apis.Drive.v2.Data.File>(service.Files.Get(fileId),
                                                                       (file, error, x, message) =>
                        {
                            if (error != null)
                            {
                                throw new Exception("error");
                            }
                            else
                            {
                                examLinksList.Add(new ExamLink {
                                    PaperName = examPaper.PaperName, PaperUrl = file.WebContentLink, FileId = fileId
                                });
                            }
                        });
                    });

                    await request.ExecuteAsync();

                    selectionViewModel.ExamLinks = examLinksList;
                    Session.Remove("SelectedIds");
                    return(View(selectionViewModel));
                }
                catch (Exception ex)
                {
                    // Todo: Log errors and show friendly error
                    throw ex;
                }
            }
            else
            {
                return(new RedirectResult(result.RedirectUri));
            }
        }
        // GET: Vehicle
        public ActionResult Index(string selection)
        {
            SelectionViewModel SelectionModel = new SelectionViewModel();

            SelectionModel.Selection   = selection;
            SelectionModel.SwVehicles  = StarWarsApiData.GetSwVehicles();
            SelectionModel.SwStarships = StarWarsApiData.GetSwStarships();

            return(View(SelectionModel));
        }
示例#11
0
 public MainViewModel()
 {
     SelectionViewModel
     .WhenAnyValue(a => a.SelectedValue)
     .Where(a => a != null)
     .Select(method => (a: method, method.GetParameters().Count()))
     .CombineLatest(I1.WhenAnyValue(_ => _.Output), I2.WhenAnyValue(a => a.Output), (a, b, c) => NewMethod(b, c, v => a.a.Invoke(null, v), a.Item2))
     .SelectMany(a => a.ToObservable())
     .ObserveOnDispatcher()
     .Subscribe(normal =>
     {
         O.Mean = normal.Mean;
         O.StandardDeviation = normal.StdDev;
     });
示例#12
0
        public SessionDefinitionsViewModel(SessionDefinitionsSource definitions, ILocalSessionDefinitionsService service, Dispatcher dispatcher)
        {
            _definitions = definitions;
            _dispatcher  = dispatcher;

            _import = new ImportSessionDefinitions(service);
            definitions.Link(_import);

            Selection = new SelectionViewModel <ISessionChoiceViewModel>(_definitions.Definitions.Select(s => new SessionDefinitionViewModel(s)).Cast <ISessionChoiceViewModel>().Prepend(new CreateSessionViewModel()));
            _definitions.DefinitionsChanged += definitions_DefinitionsChanged;

            SelectLastDefinition();
            Selection.SelectedItemChanged += Selection_SelectedItemChanged;
        }
示例#13
0
 private void DoResetDimensions()
 {
     Logger.Info("DoResetDimensions");
     if (CanResetDimensions())
     {
         SelectionViewModel selection = new SelectionViewModel(
             Instance.Default.Application);
         bool oldAspectSwitch = PreserveAspect;
         PreserveAspect     = false;
         Width              = Unit.Point.ConvertTo(selection.Bounds.Width, Units.AsEnum);
         Height             = Unit.Point.ConvertTo(selection.Bounds.Height, Units.AsEnum);
         PreserveAspect     = oldAspectSwitch;
         _dimensionsChanged = false;
     }
 }
        public SelectionViewModel createSelectionViewModel(int scheduleID, int totalTickets, string row, string chairs, int totalRegular, int totalChild, int totalStudent, int totalSenior, int totalPopcorn, int totalLadies, decimal totalPrice)
        {
            SelectionViewModel model = new SelectionViewModel();

            model.schedule        = scheduleRepo.Schedules.FirstOrDefault(s => s.Id == scheduleID);
            model.totalTickets    = totalTickets;
            model.row             = row;
            model.regularQuantity = totalRegular;
            model.childQuantity   = totalChild;
            model.studentQuantity = totalStudent;
            model.seniorQuantity  = totalSenior;
            model.popcornQuantity = totalPopcorn;
            model.ladiesQuantity  = totalLadies;
            model.totalPrice      = totalPrice;

            List <int> selectedChairs    = new List <int>();
            int        newChair          = 0;
            string     currentChair      = "";
            string     removedWhiteSpace = chairs.Remove(0, 1);
            string     newChairString    = removedWhiteSpace += " ";

            foreach (Char c in newChairString)
            {
                if (c.ToString() != " ")
                {
                    if (currentChair != "")
                    {
                        currentChair = currentChair += c.ToString();
                    }
                    else
                    {
                        currentChair = c.ToString();
                    }
                }
                else
                {
                    newChair = int.Parse(currentChair);
                    selectedChairs.Add(newChair);
                    newChair     = 0;
                    currentChair = "";
                }
            }
            model.chairs = selectedChairs.ToArray();

            return(model);
        }
        public ActionResult Edit(SelectionViewModel model)
        {
            SelectionDTO selectionDTO = new SelectionDTO
            {
                Id                  = model.Id,
                Name                = model.Name.Trim(),
                EducationId         = model.EducationId,
                ExperienceId        = model.ExperienceId,
                TrainingId          = model.TrainingId,
                CertificationTestId = model.CertificationTestId,
                SportProgrammingId  = model.SportProgrammingId
            };

            selectionService.Update(selectionDTO);

            return(RedirectToAction("Index"));
        }
示例#16
0
        public DataTable(IEnumerable itemsSource, SelectionViewModel selection) : this(itemsSource)
        {
            if (selection != null)
            {
                LinkedSelection = selection;
                selection.GetCollection().CollectionChanged += Selection_CollectionChanged;

                //Doesn't work, because Selection is readonly...!

                /*Binding selectionBinding = new Binding();
                 * selectionBinding.Source = selection;
                 * selectionBinding.Path = new PropertyPath("Selection");
                 * selectionBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
                 * //selectionBinding.Mode = BindingMode.TwoWay;
                 * BindingOperations.SetBinding(this, SelectedItemsProperty, selectionBinding);*/
            }
        }
示例#17
0
        public async Task <IActionResult> Selection(string city)
        {
            var location = new Location(city);
            var user     = await _userManager.GetUserAsync(User);

            var followedArtists = await _spotifyService.GetFollowedArtists(user.SpotifyUserId);

            var followedArtistsWithEvents =
                await _artistService.FilterArtistsWithEventsUsingAreaCalendar(followedArtists, location);

            var model = new SelectionViewModel
            {
                Artists  = followedArtistsWithEvents,
                User     = user,
                Location = location
            };

            return(View(model));
        }
示例#18
0
        static void StoreOrRestoreCsvSelection()
        {
            SelectionViewModel svm = new SelectionViewModel(Instance.Default.Application);

            if (svm.IsRange)
            {
                Logger.Info("RestoreLastCsvSelection: Current selection is range");
                Excel.Models.Reference reference = new Excel.Models.Reference(svm.Range);

                // If there currently is no range selection (only 1 cell selected), restore the previously
                // saved range.
                if (reference.CellCount == 1)
                {
                    Logger.Info("RestoreLastCsvSelection: Selection is a single cell: Attempting to restore");
                    using (WorkbookStorage.Store store = new WorkbookStorage.Store(true))
                    {
                        reference.ReferenceString = store.Get(XLToolbox.Properties.StoreNames.Default.CsvRange, String.Empty);
                        if (reference.IsValid)
                        {
                            Logger.Info("RestoreLastCsvSelection: Activating the range");
                            reference.Activate();
                        }
                        else
                        {
                            Logger.Warn("RestoreLastCsvSelection: Invalid reference");
                        }
                    }
                }
                else
                {
                    Logger.Info("RestoreLastCsvSelection: Selection is range of cells: Storing");
                    using (WorkbookStorage.Store store = new WorkbookStorage.Store(true))
                    {
                        store.Put(XLToolbox.Properties.StoreNames.Default.CsvRange, "=" + reference.ReferenceString);
                    }
                }
            }
            else
            {
                Logger.Info("RestoreLastCsvSelection: Current selection is not a range");
            }
        }
示例#19
0
        public WorkspaceViewModel SelectBarcodesWorkspace(IEnumerable <WorkspaceViewModel> workspaces)
        {
            var selectedWorkspace = workspaces.First();
            var input             = new SelectionInput <WorkspaceViewModel>
            {
                Title             = "Barcodes - Workspaces",
                ContentHeader     = "Select desired workspace",
                Label             = "Workspace:",
                Items             = workspaces,
                SelectedItem      = selectedWorkspace,
                DisplayMemberPath = "Name"
            };
            var dataContext = new SelectionViewModel <WorkspaceViewModel>(input);
            var window      = new SelectionWindow(dataContext)
            {
                Owner = MainWindow
            };

            window.ShowDialog();
            return(dataContext.Result);
        }
示例#20
0
        public StorageBarcodeViewModel SelectStorageBarcode(object parentViewModel, List <StorageBarcodeViewModel> barcodes)
        {
            var selectedBarcode = barcodes.First();
            var input           = new SelectionInput <StorageBarcodeViewModel>
            {
                Title             = "Barcodes - Import",
                ContentHeader     = "Select barcode",
                Label             = "Barcode:",
                Items             = barcodes,
                SelectedItem      = selectedBarcode,
                DisplayMemberPath = "Title"
            };
            var dataContext = new SelectionViewModel <StorageBarcodeViewModel>(input);
            var window      = new SelectionWindow(dataContext)
            {
                Owner = GetWindowWithDataContext(parentViewModel)
            };

            window.ShowDialog();
            return(dataContext.Result);
        }
示例#21
0
        public void Does_The_Best_It_Can_With_AutoSelecting_ViewModel()
        {
            // Tests the following scenario:
            //
            // - Items changes from empty to having 1 item
            // - ViewModel auto-selects item 0 in CollectionChanged
            // - SelectionModel receives CollectionChanged
            // - And so adjusts the selected item from 0 to 1, which is past the end of the items.
            //
            // There's not much we can do about this situation because the order in which
            // CollectionChanged handlers are called can't be known (the problem also exists with
            // WPF). The best we can do is not select an invalid index.
            var vm = new SelectionViewModel();

            vm.Items.CollectionChanged += (s, e) =>
            {
                if (vm.SelectedIndex == -1 && vm.Items.Count > 0)
                {
                    vm.SelectedIndex = 0;
                }
            };

            var target = new ListBox
            {
                [!ListBox.ItemsProperty]         = new Binding("Items"),
                [!ListBox.SelectedIndexProperty] = new Binding("SelectedIndex"),
                DataContext = vm,
            };

            Prepare(target);

            vm.Items.Add("foo");
            vm.Items.Add("bar");

            Assert.Equal(0, target.SelectedIndex);
            Assert.Equal(new[] { 0 }, target.Selection.SelectedIndexes);
            Assert.Equal("foo", target.SelectedItem);
            Assert.Equal(new[] { "foo" }, target.SelectedItems);
        }
示例#22
0
        public static e3Application Connect()
        {
            var processList = Process.GetProcessesByName(Identifier);

            switch (processList.Length)
            {
                case 0:
                    return null;
                case 1:
                    return Connect(processList[0].Id);
                default:
                    IntPtr hWnd = WinApi.GetForegroundWindow();
                    int curPid;
                    WinApi.GetWindowThreadProcessId(hWnd, out curPid);

                    if (Process.GetProcessById(curPid).ProcessName == Assembly.GetEntryAssembly().GetName().Name)
                    {
                        IntPtr targetHwnd =
                            WinApi.GetWindow(Process.GetCurrentProcess().MainWindowHandle,
                                (uint)WinApi.GetWindowCmd.GW_HWNDNEXT);
                        while (true)
                        {
                            IntPtr temp = WinApi.GetParent(targetHwnd);
                            if (temp.Equals(IntPtr.Zero)) break;
                            targetHwnd = temp;
                        }
                        WinApi.GetWindowThreadProcessId(targetHwnd, out curPid);
                    }

                    if (Process.GetProcessById(curPid).ProcessName == Identifier)
                        return Connect(Process.GetProcessById(curPid).Id);

                    var vm = new SelectionViewModel();

                    return vm.ShowDialog() == true
                        ? vm.SelectedE3Application
                        : null;
            }
        }
示例#23
0
        public SelectionViewModel[][] SelectionsAsParticipantArray()
        {
            SelectionViewModel[][] array =
                new SelectionViewModel[SelectionsByParticipant.Keys.Count][];

            int participantI = 0;

            foreach (KeyValuePair <string, List <SelectionViewModel> > x in SelectionsByParticipant)
            {
                array[participantI] = new SelectionViewModel[x.Value.Count];

                int selectionI = 0;
                foreach (SelectionViewModel y in x.Value)
                {
                    array[participantI][selectionI] = y;
                    selectionI++;
                }
                participantI++;
            }

            return(array);
        }
示例#24
0
        private void sendEmail(SelectionViewModel model)
        {
            var emailTemplate = System.IO.File.ReadAllText(Server.MapPath(ConfigurationManager.AppSettings["EmailTemplatePath"]));
            var body          = Engine.Razor.RunCompile(emailTemplate, "TemplateKey", typeof(SelectionViewModel), model);

            using (MailMessage mail = new MailMessage())
            {
                mail.From = new MailAddress(ConfigurationManager.AppSettings["EmailFrom"]);
                mail.To.Add(model.EmailAddress);
                mail.Subject    = string.Format("ICAS Papers {0}", model.CustomerName);
                mail.Body       = body;
                mail.IsBodyHtml = true;

                using (SmtpClient smtp = new SmtpClient(ConfigurationManager.AppSettings["SmtpHost"], Convert.ToInt16(ConfigurationManager.AppSettings["SmtpPort"])))
                {
                    smtp.UseDefaultCredentials = false;
                    smtp.EnableSsl             = true;
                    smtp.Credentials           = new NetworkCredential(ConfigurationManager.AppSettings["EmailFrom"], ConfigurationManager.AppSettings["EmailFromPassword"]);
                    smtp.Send(mail);
                }
            }
        }
        public ActionResult Create(SelectionViewModel model)
        {
            if (model != null)
            {
                SelectionDTO selectionDTO = new SelectionDTO
                {
                    Name                = model.Name.Trim(),
                    EducationId         = model.EducationId,
                    ExperienceId        = model.ExperienceId,
                    TrainingId          = model.TrainingId,
                    CertificationTestId = model.CertificationTestId,
                    SportProgrammingId  = model.SportProgrammingId
                };

                selectionService.Create(selectionDTO);

                ModelState.Clear();
                return(RedirectToAction("Index"));
            }

            return(View(model));
        }
示例#26
0
        /// <summary>
        /// Performs the actual export for a given selection. This method is
        /// called by the <see cref="ExportSelection"/> method and during
        /// a batch export process.
        /// </summary>
        /// <param name="widthInPoints">Width of the output graphic.</param>
        /// <param name="heightInPoints">Height of the output graphic.</param>
        /// <param name="fileName">Destination filename (must contain placeholders).</param>
        private void ExportWithDimensions(double widthInPoints, double heightInPoints)
        {
            if (Preset == null)
            {
                Logger.Fatal("ExportWithDimensions: No export preset!");
                throw new InvalidOperationException("Cannot export without export preset");
            }
            Logger.Info("ExportWithDimensions: Preset: {0}", Preset);
            // Copy current selection to clipboard
            SelectionViewModel.CopyToClipboard();

            // Get a metafile view of the clipboard content
            // Must not dispose the WorkingClipboard instance before the metafile
            // has been drawn on the bitmap canvas! Otherwise the metafile will not draw.
            Metafile emf;

            using (WorkingClipboard clipboard = new WorkingClipboard())
            {
                Logger.Info("ExportWithDimensions: Get metafile");
                emf = clipboard.GetMetafile();
                switch (Preset.FileType)
                {
                case FileType.Emf:
                    ExportEmf(emf);
                    break;

                case FileType.Png:
                case FileType.Tiff:
                    ExportViaFreeImage(emf, widthInPoints, heightInPoints);
                    break;

                default:
                    throw new NotImplementedException(String.Format(
                                                          "No export implementation for {0}.", Preset.FileType));
                }
            }
        }
示例#27
0
 private void HandleSelectionViewAdded(SelectionViewModel selectionView)
 {
     _selectionViewModels.Add(selectionView);
 }
示例#28
0
 public PageListViewModel()
 {
     Items     = new ObservableCollection <PageViewModel>();
     Selection = new SelectionViewModel <PageViewModel>(this);
 }
示例#29
0
 /// <summary>
 /// Show a data table for the specified data
 /// </summary>
 /// <param name="name"></param>
 /// <param name="data"></param>
 public abstract void ShowDataTable(string name, IEnumerable data, SelectionViewModel selection = null);
 public void StartExcel()
 {
     svm = new SelectionViewModel(Instance.Default.Application);
     Instance.Default.CreateWorkbook();
     ws = Instance.Default.Application.ActiveWorkbook.Worksheets[1];
 }
        public ViewResult selectionOverview(int scheduleID, int totalTickets, string row, string chairs, int totalRegular, int totalChild, int totalStudent, int totalSenior, int totalPopcorn, int totalLadies, decimal totalPrice)
        {
            SelectionViewModel model = createSelectionViewModel(scheduleID, totalTickets, row, chairs, totalRegular, totalChild, totalStudent, totalSenior, totalPopcorn, totalLadies, totalPrice);

            return(View("selectionOverview", model));
        }
示例#32
0
文件: Workspace.cs 项目: sispd/Wider
        private void LoadTools()
        {
            SelectionViewModel selectionViewModel = Container.Resolve <SelectionViewModel>();

            Tools.Add(selectionViewModel);
        }