public void ConnectControlViewModel_AddNewServer_ResourceRepositoryReturnExistingServers_False() { //------------Setup for test-------------------------- var mainViewModel = new Mock<IMainViewModel>(); var connectControlSingleton = new Mock<IConnectControlSingleton>(); var env1 = new TestEnvironmentModel(new Mock<IEventAggregator>().Object, Guid.NewGuid(), CreateConnection(true, false).Object, new Mock<IResourceRepository>().Object, false); var env2 = new TestEnvironmentModel(new Mock<IEventAggregator>().Object, Guid.NewGuid(), CreateConnection(true, false).Object, new Mock<IResourceRepository>().Object, false); var connectControlEnvironments = new ObservableCollection<IConnectControlEnvironment>(); var controEnv1 = new Mock<IConnectControlEnvironment>(); var controEnv2 = new Mock<IConnectControlEnvironment>(); controEnv1.Setup(c => c.EnvironmentModel).Returns(env1); controEnv2.Setup(c => c.EnvironmentModel).Returns(env2); controEnv1.Setup(c => c.IsConnected).Returns(true); connectControlEnvironments.Add(controEnv2.Object); connectControlEnvironments.Add(controEnv1.Object); connectControlSingleton.Setup(c => c.Servers).Returns(connectControlEnvironments); var environmentRepository = new Mock<IEnvironmentRepository>(); ICollection<IEnvironmentModel> environments = new Collection<IEnvironmentModel> { env1 }; environmentRepository.Setup(e => e.All()).Returns(environments); var viewModel = new ConnectControlViewModel(mainViewModel.Object, environmentRepository.Object, e => { }, connectControlSingleton.Object, "TEST : ", false); //------------Execution------------------------------- int serverIndex; var didAddNew = viewModel.AddNewServer(out serverIndex, i => { }); //------------Assert---------------------------------- Assert.IsNotNull(viewModel); Assert.IsFalse(didAddNew); }
public ConnectWindow() { InitializeComponent(); try { IsAvailableServer = ServiceCtrlClass.ServiceIsInstalled("EpgTimer Service") == true || System.IO.File.Exists(SettingPath.ModulePath.TrimEnd('\\') + "\\EpgTimerSrv.exe") == true; btn_edit.Visibility = Visibility.Collapsed; ConnectionList = new ObservableCollection<NWPresetItem>(Settings.Instance.NWPreset); var nowSet = new NWPresetItem(DefPresetStr, Settings.Instance.NWServerIP, Settings.Instance.NWServerPort, Settings.Instance.NWWaitPort, Settings.Instance.NWMacAdd, Settings.Instance.NWPassword); int pos = ConnectionList.ToList().FindIndex(item => item.EqualsTo(nowSet, true)); if (pos == -1) { ConnectionList.Add(nowSet); pos = ConnectionList.Count - 1; } if (IsAvailableServer == true) { ConnectionList.Insert(0, new NWPresetItem("ローカル接続", "", 0, 0, "", new SerializableSecureString())); pos++; } ConnectionList.Add(new NWPresetItem("<新規登録>", "", 0, 0, "", new SerializableSecureString())); listView_List.ItemsSource = ConnectionList; if (IsAvailableServer == false) { Settings.Instance.NWMode = true; } listView_List.SelectedIndex = Settings.Instance.NWMode == true ? pos : 0; } catch { } }
private void InitializeBootAddressList() { BootAddressList = new ObservableCollection<string>(); BootAddressList.Add("0x0000~0x8000"); BootAddressList.Add("0x8000~0xC000"); }
public ConfigurationWindow() { InitializeComponent(); DataContext = this; ObservableCollection<Personality> personalities = new ObservableCollection<Personality>(); // Add our default personality personalities.Add(Personality.Default()); foreach (Personality personality in Personality.AllFromDirectory()) { personalities.Add(personality); } // Add local personalities foreach (Personality personality in personalities) { Logging.Debug("Found personality " + personality.Name); } Personalities = personalities; SpeechResponderConfiguration configuration = SpeechResponderConfiguration.FromFile(); foreach (Personality personality in Personalities) { if (personality.Name == configuration.Personality) { Personality = personality; break; } } }
public MenuViewModel() { CanLoadMore = true; Title = "MasterDetailTabbed"; MenuItems = new ObservableCollection<HomeMenuItem>(); MenuItems.Add(new HomeMenuItem { Id = 0, Title = "Home", MenuType = MenuType.Home, Icon = "home.png" }); MenuItems.Add(new HomeMenuItem { Id = 5, Title = "Feedback", MenuType = MenuType.Feedback, Icon = "feedback.png" }); MenuItems.Add(new HomeMenuItem { Id = 6, Title = "About", MenuType = MenuType.About, Icon = "about.png" }); }
public SettingsViewModel() { SendMethodCollection = new ObservableCollection<string>(); SendMethodCollection.Add(StringResources.SettingsPage_Settings_SMS); SendMethodCollection.Add(StringResources.SettingsPage_Settings_Email); }
public void LoadFilters() { var bw = new ImageFilter(new BlackAndWhite()); var sepia = new ImageFilter(new Sepia()) { Value = 20 }; var brightness = new ImageFilter(new Brightness()) { Value = 20 }; var contrast = new ImageFilter(new Contrast()) { Value = 20 }; var filters = new ObservableCollection<ImageFilter> { bw, sepia }; bool isBrightnessBought; if (IsolatedStorageSettings.ApplicationSettings.TryGetValue(InAppProducts.BrightnessFilterIdentifier, out isBrightnessBought)) { if (isBrightnessBought) { filters.Add(brightness); } } bool isContrastBought; if (IsolatedStorageSettings.ApplicationSettings.TryGetValue(InAppProducts.ContrastFilterIdentifier, out isContrastBought)) { if (isContrastBought) { filters.Add(contrast); } } Filters = filters; SelectedFilter = Filters.First(); }
public ScreenVirtualContainer_VM() { PreviewFirstVirtualMode = VirtualModeType.Led3; PreviewSecondVirtualMode = VirtualModeType.Led31; ObservableCollection<VirtualLightType> sequence = new ObservableCollection<VirtualLightType>(); sequence.Add(VirtualLightType.Red); sequence.Add(VirtualLightType.Green); sequence.Add(VirtualLightType.Blue); sequence.Add(VirtualLightType.VRed); LightSequence = sequence; LightSequence.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(LightSequence_CollectionChanged); sequence = new ObservableCollection<VirtualLightType>(); sequence.Add(VirtualLightType.Red); sequence.Add(VirtualLightType.Green); sequence.Add(VirtualLightType.Blue); sequence.Add(VirtualLightType.VRed); PreviewFirstLightSequence = sequence; PreviewFirstLightSequence.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(LightSequence_CollectionChanged1); sequence = new ObservableCollection<VirtualLightType>(); sequence.Add(VirtualLightType.VRed); sequence.Add(VirtualLightType.Blue); sequence.Add(VirtualLightType.Red); sequence.Add(VirtualLightType.Green); PreviewSecondLightSequence = sequence; PreviewSecondLightSequence.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(LightSequence_CollectionChanged2); }
public MenuGeneral() { //Delegate pour exécuter du code personnalisé lors du changement de langue de l'UI. CultureManager.UICultureChanged += CultureManager_UICultureChanged; mapLangue = new ObservableCollection<LangueUI>(); //Le tag de langue IETF (ie: fr-CA) utilisé directement pour changer la langue d'affichage. //Récupéré selon la Langue active. string codeLangueActif; //Si l'utilisateur est connecté, utilise la langue sauvegarder sous son profil. if (App.MembreCourant.IdMembre != null) { codeLangueActif = App.MembreCourant.LangueMembre.IETF; } else { //Sinon, utilise la valeur par défault tel que défini sous App. codeLangueActif = App.LangueInstance.IETF; } mapLangue.Add(francais); mapLangue.Add(anglais); //Dans le dictionnaire, trouve l'élément qui a le tag IETF équivalent à selui enregistré sous codeLangueActif et le met à actif. mapLangue.FirstOrDefault(l => l.LangueSys.IETF == codeLangueActif).Actif = true; InitializeComponent(); //Configure la source de notre dataGrid. dgLangues.ItemsSource = mapLangue; }
public ExtensionUploadWarningDialog(IEnumerable<string> errors, IEnumerable<string> warnings) { InitializeComponent(); DataContext = this; Messages = new ObservableCollection<Dictionary<string, string>>(); foreach (string error in errors) { Dictionary<string, string> message = new Dictionary<string, string>(); message.Add("message", error); message.Add("image", "/ESRI.ArcGIS.Mapping.Controls;component/Images/icons/warning_icon.png"); Messages.Add(message); } foreach (string warning in warnings) { Dictionary<string, string> message = new Dictionary<string, string>(); message.Add("message", warning); message.Add("image", "/ESRI.ArcGIS.Mapping.Controls;component/Images/icons/caution16.png"); Messages.Add(message); } HasErrors = errors.Count() > 0; }
public ModuloAdminViewModel()// TODO Enviar el usuario logueado y sacar su rol { _children = new ObservableCollection<object>(); _children.Add(ListarFisioterapeutasViewModel.Instance()); _children.Add(ListarPacientesViewModel.Instance()); _children.Add(ListaPacientesAsociacionViewModel.Instance()); _children.Add(ListarResultadosReportesViewModel.Instance()); _children.Add(RutasAlmacenamientoViewModel.Instance()); CloseWindowFlag = true; BlnSavePathNoExist = false; iTabSelected = 0; CerrarSesionCommand = new RelayCommand(CerrarSesion); RolLogueado = "Administrador"; if (RutasConfiguracionDL.ObtenerConfiguraciones().Count == 0) { // the view does not recognize this variables, then is not possible to see an UI update BlnSavePathNoExist = true; iTabSelected = 4; //Manually fixed System.Windows.Forms.MessageBox.Show("Aún no ha determinado la rutas de almacenamiento de las fotos y exportaciones de archivos PDF. Por favor dirigirse a la pestaña Rutas de Almacenamiento para determinar las rutas de almacenamiento.", "Advertencia", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information); } //cargamos las configuranes de base de datos }
public ObservableCollection<MenuItem> GetMenuItems() { ObservableCollection<MenuItem> items = new ObservableCollection<MenuItem>(); MenuItem copyItem = new MenuItem() { IconUrl = new Uri("Images/copy.png", UriKind.Relative), Text = "Copy", Command = new CopyCommand() }; items.Add(copyItem); MenuItem pasteItem = new MenuItem() { IconUrl = new Uri("Images/paste.png", UriKind.Relative), Text = "Paste", Command = new PasteCommand() }; items.Add(pasteItem); MenuItem cutItem = new MenuItem() { IconUrl = new Uri("Images/cut.png", UriKind.Relative), Text = "Cut", Command = new CutCommand() }; items.Add(cutItem); return items; }
private void Window_Loaded_1(object sender, RoutedEventArgs e) { for (int i = 0; i < N - 1; i++) { _args.Add(_args[i] + _d); } BaseChartValues = new ObservableCollection<ChartValue>(); foreach (var arg in _args) { double res = MyFunction(arg); _a.Add(res); BaseChartValues.Add(new ChartValue(arg, res)); } ChartSource = new ObservableCollection<ObservableCollection<ChartValue>> {BaseChartValues}; Chart.DataContext = ChartSource; TransformedChartSource = new ObservableCollection<ObservableCollection<ChartValue>>(); DirectFourierChartValues = new ObservableCollection<ChartValue>(); TransformedChartSource.Add(DirectFourierChartValues); DiscrDirectFourierChartValues = new ObservableCollection<ChartValue>(); TransformedChartSource.Add(DiscrDirectFourierChartValues); TransformedChart.DataContext = TransformedChartSource; ReverseTransformedChartSource = new ObservableCollection<ObservableCollection<ChartValue>>(); ReverseFourierChartValues = new ObservableCollection<ChartValue>(); ReverseTransformedChartSource.Add(ReverseFourierChartValues); DiscrReverseFourierChartValues = new ObservableCollection<ChartValue>(); ReverseTransformedChartSource.Add(DiscrReverseFourierChartValues); ReverseTransformedChart.DataContext = ReverseTransformedChartSource; _FourierTransform = new FourierTransformLib.FourierTransform(N); }
public void Result_updated_after_Add() { var subject = new ObservableCollection<int>(new [] { 0, 1, 2, 3, 4, 5, 6, 7 }); var result = subject.ToQueryable().Where(i => i % 2 == 0).ToObservable(); subject.Add(8); Assert.IsInstanceOfType(result, typeof(IQueryableObservableCollection<int>)); Assert.AreEqual(0, result[0]); Assert.AreEqual(2, result[1]); Assert.AreEqual(4, result[2]); Assert.AreEqual(6, result[3]); Assert.AreEqual(8, result[4]); Assert.AreEqual(5, result.Count); subject.Add(9); Assert.IsInstanceOfType(result, typeof(IQueryableObservableCollection<int>)); Assert.AreEqual(0, result[0]); Assert.AreEqual(2, result[1]); Assert.AreEqual(4, result[2]); Assert.AreEqual(6, result[3]); Assert.AreEqual(8, result[4]); Assert.AreEqual(5, result.Count); }
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { var collection = (ObservableCollection<FunctionParameters>)value; var result = new ObservableCollection<string>(); foreach (var itm in collection) { switch (itm.ToString()) { case "CellName": result.Add("от колонки(по заголовку)"); break; case "CellNumber": result.Add("от колонки(по номеру)"); break; case "Header": result.Add("от верхнего заголовка"); break; case "Subheader": result.Add("от заголовка"); break; case "Sheet": result.Add("от вкладки"); break; } } return result; }
public ObservableCollection<TwitterDataItem> GetMockedTweets() { var ret = new ObservableCollection<TwitterDataItem>(); ret.Add(new TwitterDataItem("12389741623598172", "@techdrinkup", "2190675848", "http://a0.twimg.com/sticky/default_profile_images/default_profile_0.png", "#Test waschtrockner stiftung warentest http://t.co/b9GyagIs #shop #tests waschtrockner stiftung warentest kaufen")); ret.Add(new TwitterDataItem("12389741623598173", "@lucasvidalutn", "208112063", "https://twimg0-a.akamaihd.net/profile_images/1473386819/profile.jpg", "RT @ShauniLatu: “@blasfloss: Time to #fail this #math #test...” You fail at life.")); ret.Add(new TwitterDataItem("12389741623598174", "@oso_arturo", "467767993", "http://a0.twimg.com/profile_images/2191494082/virtuellemiss.jpg", "#2010 #maximebataille #test #coiffure #mode #model #mannequin http://t.co/yiQEygfr")); ret.Add(new TwitterDataItem("12389741623598175", "@ggonzalez30", "241319155", "http://a0.twimg.com/profile_images/2639300174/19fcbfeb78327fc6329c9d877b5b69dc.jpeg", "Time to #fail this #math #test...")); ret.Add(new TwitterDataItem("123897416235981726", "@juan_carlos_batman", "824545292", "https://twimg0-a.akamaihd.net/profile_images/2475729655/gjr49jeorqfcd6rm7djv.jpeg", "Studying all this week better have been worth it for my test on monday #collegebound #test")); return ret; }
public GroupedListCode () { var lstView = new ListView (); grouped = new ObservableCollection<GroupedVeggieModel> (); var veggieGroup = new GroupedVeggieModel () { LongName = "vegetables", ShortName="v" }; var fruitGroup = new GroupedVeggieModel () { LongName = "fruit", ShortName = "f" }; veggieGroup.Add (new VeggieModel () { Name = "celery", IsReallyAVeggie = true, Comment = "try ants on a log" }); veggieGroup.Add (new VeggieModel () { Name = "tomato", IsReallyAVeggie = false, Comment = "pairs well with basil" }); veggieGroup.Add (new VeggieModel () { Name = "zucchini", IsReallyAVeggie = true, Comment = "zucchini bread > bannana bread" }); veggieGroup.Add (new VeggieModel () { Name = "peas", IsReallyAVeggie = true, Comment = "like peas in a pod" }); fruitGroup.Add (new VeggieModel () {Name = "banana", IsReallyAVeggie = false,Comment = "available in chip form factor"}); fruitGroup.Add (new VeggieModel () {Name = "strawberry", IsReallyAVeggie = false,Comment = "spring plant"}); fruitGroup.Add (new VeggieModel () {Name = "cherry", IsReallyAVeggie = false,Comment = "topper for icecream"}); grouped.Add (veggieGroup); grouped.Add (fruitGroup); lstView.ItemsSource = grouped; lstView.IsGroupingEnabled = true; lstView.GroupDisplayBinding = new Binding ("LongName"); lstView.GroupShortNameBinding = new Binding ("ShortName"); lstView.ItemTemplate = new DataTemplate (typeof(TextCell)); lstView.ItemTemplate.SetBinding (TextCell.TextProperty, "Name"); // lstView.ItemTemplate.SetBinding (TextCell.DetailProperty, "Comment"); Content = lstView; }
public ResultDetailsViewModel() { #if DEBUG if (this.IsInDesignMode) { ObservableCollection<InventoryInfo> invInfo = new ObservableCollection<InventoryInfo>(); invInfo.Add(new InventoryInfo() { NumberInStock = 33, Product = new ProductListItem() { Id = 33, Name = "Domaine De La Seigneurie Des Tourelles Saumur 2008 750 mL bottle" } }); invInfo.Add(new InventoryInfo() { NumberInStock = 5600, Product = new ProductListItem() { Id = 56, Name = "Canadian" } }); for (int i = 0; i < 20; i++) { invInfo.Add(new InventoryInfo() { NumberInStock = 5600 + i, Product = new ProductListItem() { Id = i, Name = "Product " + i } }); } StoreWithInventory sWithInv = new StoreWithInventory(); sWithInv = new StoreWithInventory() { Inventory = invInfo, Store = new InvStore() { City = "City 123", Address = "Address 123", Latitude = 43.474249M, Longitude = -79.732728M } }; this.StoreWithInventory = new StoreWithInventoryViewModel(sWithInv); } #endif }
public void ReplaceColorBlockItemsFromString_MultipleLines_ExistingBlockItems() { // Arrange var testInputString = "SetTextColor 240 200 150 # Rarest Currency" + Environment.NewLine + "SetBackgroundColor 0 0 0 # Rarest Currency Background" + Environment.NewLine + "SetBorderColor 255 255 255 # Rarest Currency Border"; var testInputBlockItems = new ObservableCollection<IItemFilterBlockItem>(); var testInputTextColorBlockItem = new TextColorBlockItem(Colors.Red); var testInputBackgroundColorBlockItem = new BackgroundColorBlockItem(Colors.Blue); var testInpuBorderColorBlockItem = new BorderColorBlockItem(Colors.Yellow); testInputBlockItems.Add(testInputTextColorBlockItem); testInputBlockItems.Add(testInputBackgroundColorBlockItem); testInputBlockItems.Add(testInpuBorderColorBlockItem); // Act _testUtility.Translator.ReplaceColorBlockItemsFromString(testInputBlockItems, testInputString); // Assert var textColorBlockItem = testInputBlockItems.First(b => b is TextColorBlockItem) as TextColorBlockItem; Assert.IsNotNull(textColorBlockItem); Assert.AreNotSame(testInputTextColorBlockItem, textColorBlockItem); Assert.AreEqual(new Color {A = 255, R = 240, G = 200, B = 150}, textColorBlockItem.Color); var backgroundColorBlockItem = testInputBlockItems.First(b => b is BackgroundColorBlockItem) as BackgroundColorBlockItem; Assert.IsNotNull(backgroundColorBlockItem); Assert.AreNotSame(testInputBackgroundColorBlockItem, backgroundColorBlockItem); Assert.AreEqual(new Color { A = 255, R = 0, G = 0, B = 0 }, backgroundColorBlockItem.Color); var borderColorBlockItem = testInputBlockItems.First(b => b is BorderColorBlockItem) as BorderColorBlockItem; Assert.IsNotNull(borderColorBlockItem); Assert.AreNotSame(testInpuBorderColorBlockItem, borderColorBlockItem); Assert.AreEqual(new Color { A = 255, R = 255, G = 255, B = 255 }, borderColorBlockItem.Color); }
public DesignTimeEmployeeSelectionViewModel() { ViewData = new EmployeeSelectionViewData(); var employees = new ObservableCollection<EmployeeListItemViewData>(); employees.Add(new EmployeeListItemViewData() { EmployeeID = 24, FirstName = "John", LastName = "Doe", CPR = "2801 123456", EmpAddress = "Somewhwere in Denmark", City = "Odense", Zip = "5200", Country = "Denmark", Email = "*****@*****.**", TelephoneNumber = "+45 25 25 25 25", MobileNumber = "+45 00 00 00 00", CreditCard = "1234456", ExpDate = DateTime.Now, EmployeePosition = "Junior Detective" }); employees.Add(new EmployeeListItemViewData() { EmployeeID = 24, FirstName = "Jane", LastName = "Desole", CPR = "2801 123456", EmpAddress = "Somewhwere in Denmark 2", City = "Odense", Zip = "5200", Country = "Denmark", Email = "*****@*****.**", TelephoneNumber = "+45 25 25 25 25", MobileNumber = "+45 00 00 00 00", CreditCard = "1234456", ExpDate = DateTime.Now, EmployeePosition = "Senior Detective" }); employees.Add(new EmployeeListItemViewData() { EmployeeID = 10000, FirstName = "Johnny", LastName = "Doenning", CPR = "2801 123456", EmpAddress = "Somewhwere in Denmark 3", City = "Odense", Zip = "5200", Country = "Denmark", Email = "*****@*****.**", TelephoneNumber = "+45 25 25 25 25", MobileNumber = "+45 00 00 00 00", CreditCard = "1234456", ExpDate = DateTime.Now, EmployeePosition = "Grand Detective" }); ((EmployeeSelectionViewData)ViewData).Employees = employees; }
public VMStudent() { students3 = new CollectionViewSource(); Student stu1 = new Student(); Student stu2 = new Student(); stu1.Name = "zhangsan"; stu1.PhotoBitmapImage1 = "E:\\新建文件夹\\3.png"; stu2.Name = "lisi"; stu2.PhotoBitmapImage1 = "E:\\新建文件夹\\4.png"; students1 = new ObservableCollection<Student>(); students1.Add(stu1); students1.Add(stu2); Student stu3 = new Student(); Student stu4 = new Student(); stu3.Name = "wangwu"; stu3.PhotoBitmapImage1 = "E:\\新建文件夹\\1.png"; stu4.Name = "zhaoliu"; stu4.PhotoBitmapImage1 = "E:\\新建文件夹\\2.png"; students2 = new ObservableCollection<Student>(); students2.Add(stu3); students2.Add(stu4); students3.Source = students2; }
private void Window_Loaded(object sender, RoutedEventArgs e) { var list = new ObservableCollection<NodeItem>(); var item = new NodeItem() { DisplayName = "TestItem" }; var subitem = new NodeItem() { DisplayName = "SubItem222222222" }; subitem.Children.Add(new NodeItem() { DisplayName = "Sub2Item222222222222222222" }); subitem.Children.Add(new NodeItem() { DisplayName = "Sub2Item22222222222" }); item.Children.Add(subitem); item.Children.Add(subitem); list.Add(item); var item2 = new NodeItem() { DisplayName = "2TestItem" }; var subitem2 = new NodeItem() { DisplayName = "2SubItem222222222" }; subitem2.Children.Add(new NodeItem() { DisplayName = "2Sub2Item222222222222222222" }); subitem2.Children.Add(new NodeItem() { DisplayName = "2Sub2Item22222222222" }); item2.Children.Add(subitem2); item2.Children.Add(subitem2); list.Add(item2); comboBox.Items.Clear(); comboBox.ItemsSource = list; comboBox.DataContext = list; comboBox1.DataContext = list; comboBox2.DataContext = list; (comboBox2.Items[0] as ComboBoxItem).DataContext = subitem2; nodeList.DataContext = list; cboGroup.DataContext = list; comboTree.DataContext = list; comboTree.SelectedValue = subitem2; }
public TrackListViewModel() { Tracks = new ObservableCollection<Track>(); SelectedTracks = new ObservableCollection<Track>(); if (Windows.ApplicationModel.DesignMode.DesignModeEnabled) { // designtime data var album = new Album() { AlbumArtist = new Artist() { Name = "Miles Davis" }, Name = "Kind of Blue", ImageSource = "https://upload.wikimedia.org/wikipedia/en/9/9c/MilesDavisKindofBlue.jpg", Year = 1969, DateImported = new DateTime(1987, 6, 19) }; Tracks.Add(new Track() { TrackNumber = 1, Album = album, Artist = album.AlbumArtist, Name = "So What" }); Tracks.Add(new Track() { TrackNumber = 2, Album = album, Artist = album.AlbumArtist, Name = "Freddie Freeloader" }); Tracks.Add(new Track() { TrackNumber = 3, Album = album, Artist = album.AlbumArtist, Name = "Blue in Green" }); Tracks.Add(new Track() { TrackNumber = 4, Album = album, Artist = album.AlbumArtist, Name = "All Blues" }); Tracks.Add(new Track() { TrackNumber = 5, Album = album, Artist = album.AlbumArtist, Name = "Flamenco Sketches" }); return; } }
private void LoadResults(Lag mSelectedLag) { if (mSelectedLag == null) { ChosenLag = null; this.OnPropertyChanged("ChosenLag"); return; } var nyttLag = m_databaseService.GetLag(mSelectedLag.LagNummer); m_chosenLag = new ObservableCollection<ResultRowViewModel>(); foreach (var skive in nyttLag.SkiverILaget) { if (skive.SkytterGuid != null) { var results = m_databaseService.GetResultsForSkytter(skive.SkytterGuid.Value); m_chosenLag.Add(new ResultRowViewModel(mSelectedLag.LagNummer, skive.SkiveNummer, skive.Skytter, results)); } else { m_chosenLag.Add(new ResultRowViewModel(mSelectedLag.LagNummer, skive.SkiveNummer)); } } this.OnPropertyChanged("ChosenLag"); }
public LocalizationViewModel() { AvailableCultures = new ObservableCollection<CultureInfoDto>(); AvailableCultures.Add(new CultureInfoDto() { CultureKey = string.Empty, DisplayName = "Default (English)" }); var assembly = GetType().Assembly; var path = Path.GetDirectoryName(assembly.Location); foreach (var dir in Directory.GetDirectories(path)) { try { var dirinfo = new DirectoryInfo(dir); var tCulture = CultureInfo.GetCultureInfo(dirinfo.Name); AvailableCultures.Add(new CultureInfoDto { DisplayName = tCulture.DisplayName, CultureKey = tCulture.Name }); } catch { //Ignored. This will throw when we traverse into a directory that doesn't contain actual culture infos. } } }
public BinaryObjectViewModel(BaseDescriptor binaryObject) { SetAutomaticRegimeCommand = new RelayCommand(OnSetAutomaticRegime); SetManualRegimeCommand = new RelayCommand(OnSetManualRegime); SetIgnoreRegimeCommand = new RelayCommand(OnSetIgnoreRegime); BinaryObject = binaryObject; Description = binaryObject.XBase.PresentationName; switch (binaryObject.DescriptorType) { case DescriptorType.Device: ImageSource = binaryObject.Device.Driver.ImageSource; break; case DescriptorType.Zone: case DescriptorType.Direction: ImageSource = XManager.Drivers.FirstOrDefault(x => x.DriverType == XDriverType.System).ImageSource; break; } //Formula = BinaryObject.Formula.GetStringFomula(); StateBits = new ObservableCollection<StateBitViewModel>(); StateBits.Add(new StateBitViewModel(this, XStateBit.Norm, true)); StateBits.Add(new StateBitViewModel(this, XStateBit.Fire1)); StateBits.Add(new StateBitViewModel(this, XStateBit.Fire2)); StateBits.Add(new StateBitViewModel(this, XStateBit.On)); }
protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); string photoId = NavigationContext.QueryString["photo_id"]; photo = Cinderella.CinderellaCore.PhotoCache[photoId]; // Prepare data source dataSource = new ObservableCollection<ModelBase>(); dataSource.Add(photo); foreach (var comment in photo.Comments) { dataSource.Add(comment); } CommentsListView.ItemsSource = dataSource; // App bar ApplicationBar = Resources["PhotoPageAppBar"] as ApplicationBar; // Background if (PolicyKit.ShouldUseBlurredBackground) BackgroundImage.PhotoSource = photo; else if (BackgroundImage.PhotoSource != null) BackgroundImage.PhotoSource = null; }
/// <summary> /// Initializes a new instance of the <see cref="ClaimOnHoldListViewModel"/> class. /// </summary> /// <param name="accessControlManager">The access control manager.</param> /// <param name="commandFactory">The command factory.</param> public ClaimOnHoldListViewModel( IAccessControlManager accessControlManager, ICommandFactory commandFactory ) : base(accessControlManager, commandFactory) { OnHoldList = new ObservableCollection<TempClaimModel> (); var claim = new TempClaimModel { ServiceDate = DateTime.Now.AddDays ( -10 ), PayorName = "Aetna", ChargeAmount = ( decimal )50.0, PatientName = "Albert Smith", Message = "Not: This claim may need to be transfered to another payor.", PayorTypeName = "Commercial" }; var claim2 = new TempClaimModel { ServiceDate = DateTime.Now.AddDays ( -15 ), PayorName = "Medicaid", ChargeAmount = ( decimal )500.0, PatientName = "Tad Young", Message = "Note: The patient has indicated taht they would like to pay for this service out of pocket. Need to follow up.", PayorTypeName = "Medicare" }; OnHoldList.Add ( claim ); OnHoldList.Add ( claim2 ); }
public void Linq_Test_Employees() { var violation = false; var employees = new ObservableCollection<Person>(); var employeesWithUpdates = employees.WithUpdates(); var violations = from employee in employeesWithUpdates where employee.WorkItems > 2 * (from collegue in employeesWithUpdates where collegue.Team == employee.Team select collegue.WorkItems).Average() select employee.Name; violations.CollectionChanged += (o, e) => { violation = true; }; Assert.IsFalse(violation); employees.Add(new Person() { Name = "John", WorkItems = 20, Team = "A" }); Assert.IsFalse(violation); employees.Add(new Person() { Name = "Susi", WorkItems = 5, Team = "A" }); Assert.IsFalse(violation); employees.Add(new Person() { Name = "Joe", WorkItems = 3, Team = "A" }); Assert.IsTrue(violation); }
private ObservableCollection<HockeyPlayer> Get3TestPlayers() { ObservableCollection<HockeyPlayer> temp = new ObservableCollection<HockeyPlayer>(); temp.Add(new HockeyPlayer("Teemu Selänne", "8")); temp.Add(new HockeyPlayer("Jarkko Immonen", "28")); temp.Add(new HockeyPlayer("Ville Peltonen", "16")); return temp; }
public EntityCollection <TEntity> Merge(Entity <TEntity> entity) { if (entities.ContainsKey(entity.Instance)) { throw new InvalidOperationException("Current collection already contains this entity."); } entities[entity.Instance] = entity; observableCollection?.Add(entity.Instance); return(this); }
private string _importHash = ""; //prevents duplicate import internal void ProcessChildren(RuleRepositoryDefBase child, ObservableCollection <Artifact> list, string key) { if (_importHash.Contains(child.Name) == false) { _importHash = _importHash + child.Name; //update the hash //Console.WriteLine(child.Name); if (String.IsNullOrEmpty(key) == false) { if (IsSafeTemplateDef(child)) //some vocab definitions are not safe to stamp with an attribute { StampAttribute(child, key); } } Artifact a = new Artifact(); a.DefBase = child; list?.Add(a); var collquery = from childcollections in child.GetAllChildCollections() select childcollections; foreach (RuleRepositoryDefCollection defcollection in collquery) { var defquery = from RuleRepositoryDefBase items in defcollection select items; foreach (var def in defquery) { ProcessChildren(def, list, key); } } } }
/// <summary> /// Async parse all HTML to string, than add it to <see cref="HtmlDocument"/> /// Than try to find Artist name and his sounds by using HtmlAgilityPack method SelectNode\SelectSingleNode/> /// And add item's as new <see cref="SounInfo"/> observable/> /// </summary> /// <param name="client">Web client, which we are working with</param> /// <exception cref="Exception">Thrown if parameter was null or other exceptions</exception> /// <returns> <see cref="Task"/> which do all dirty work</returns> private async Task GetContectAsync(HttpClient client) { try { HttpResponseMessage response = await client.GetAsync(link); response.EnsureSuccessStatusCode(); string responseBody = await response.Content.ReadAsStringAsync(); var doc = new HtmlDocument(); doc.LoadHtml(responseBody); var sound_names = doc.DocumentNode.SelectNodes("//a[contains(@class, 'list-group-item removehref')]"); var header = doc.DocumentNode.SelectSingleNode("//div[contains(@class, 'col-md-9')]"); if (sound_names != null && header != null) { var name_artist = header.ChildNodes[1].InnerText; foreach (var item in sound_names) { observable?.Add(new SounInfo() { ArtistName = name_artist, SongName = item.ChildNodes[1].InnerText.Trim() }); } } } catch (Exception) { Exception ex; MessageBox.Show("smth went wrong, call your sysadmin xD" + nameof(ex)); } }
public static void AddRange <T>(this ObservableCollection <T> collection, IEnumerable <T> next) { foreach (var item in next) { collection?.Add(item); } }
public static bool LoadStoreCsv(string path, List <Store> list) //Gets the store csv from temp folder, and adds each entry to the lists { var p = new Store(); if (!File.Exists(path)) { return(false); } foreach (var item in File.ReadAllLines(path).Select(a => a.Split(',')) ) //Reads csv in order: name, price, description, image name { p.Name = item[0].Trim(); p.Price = Math.Round(decimal.Parse(item[1].Trim()), 2); p.Description = item[2].Trim(); p.ImageName = item[3].Trim(); list.Add(new Store { Name = p.Name, Price = p.Price, Description = p.Description, ImageName = p.ImageName }); //Add to storelist assortShow?.Add($"{p.Name} {p.Price}kr"); //Add to string list comparer.Add(p.Name.ToLower()); //Add to comparer list assortItemsSave.Add($"{p.Name},{p.Price},{p.Description},{p.ImageName}"); //Add to the assortItemsSave list } return(true); }
public static void AddRange <T>(this ObservableCollection <T> dest, IEnumerable <T> src) { foreach (var item in src ?? new T[] { }) { dest?.Add(item); } }
public static void AddRange <T>(this ObservableCollection <T> collection, params T[] @params) { foreach (var item in @params) { collection?.Add(item); } }
public void AddFreelancer(Freelancer freelancer) { if (freelancer != null) { freelancers?.Add(freelancer); } }
static public ObservableCollection <StatisticSample> modelingElement(int num, double LambdaValue, int itteration, ObservableCollection <StatisticSample> statisticSamples, ObservableCollection <double> tValue = null) { if (num <= 0) { return(null); } Random rand = new Random(); statisticSamples = new ObservableCollection <StatisticSample> { }; for (int i = 0; i < itteration; i++) { List <double> sample = new List <double> { }; for (int j = 0; j < num; j++) { sample.Add(Math.Round(-(Math.Log(rand.NextDouble()) / LambdaValue), 4)); } sample.Sort(); statisticSamples.Add(new StatisticSample { Sample = new ObservableCollection <double>(sample) }); double lambdaValue = (1.0 / statisticSamples.Last().QuantitiveCharactacteristics.AritmeitcMean); tValue?.Add(Math.Round((lambdaValue - LambdaValue) / (statisticSamples.Last().QuantitiveCharactacteristics.RouteMeanSquare) * Math.Sqrt(num), 4)); } return(statisticSamples); }
private void AddCar() { var maxCount = _cars?.Max(x => x.CarId) ?? 0; _cars?.Add(new Inventory { CarId = ++maxCount, Color = "Yellow", Make = "VW", PetName = "Birdie", IsChanged = false }); }
private void btnAddCar_Click(object sender, RoutedEventArgs e) { var maxCount = _cars?.Max(x => x.CarId) ?? 0; _cars?.Add(new Inventory { CarId = ++maxCount, Color = "Yellow", Make = "VW", PetName = "Birdie", IsChanged = false }); }
private void ClearChildren() { Children = new ObservableCollection <DirectoryItemViewModel>(); if (CanExpand) { Children?.Add(null); } }
public void AddReminder(Reminder reminder) { items?.Add(reminder); App.remindersManger.AddItem(reminder); Console.WriteLine(App.remindersManger.GetTripItems <Reminder>(MainPage.CurrentTrip.Id).Count); items = new ObservableCollection <Reminder>(items.OrderByDescending(x => x.Priority)); listView.ItemsSource = items; }
/// <summary> /// /// </summary> protected AssemblyResourceNodeBase1(bool addPlaceholder = true) { if (addPlaceholder) { _items?.Add(new AssemblyResourceNodesPlaceHolder()); } Dispatcher = Dispatcher.CurrentDispatcher; _taskScheduler = TaskScheduler.FromCurrentSynchronizationContext(); }
public DeviceModel(string deviceName, int interfaceCount) { DeviceName = deviceName; InterfaceCount = interfaceCount; InterfaceList = new ObservableCollection <DeviceInterface>(); for (int i = 0; i < InterfaceCount; i++) { InterfaceList?.Add(new DeviceInterface() { InterfaceName = string.Format("{0}", (1 + i)) }); } }
protected override void Append(LoggingEvent loggingEvent) { DgLogEntry newLogEntry = new DgLogEntry(); newLogEntry.evdatetime = loggingEvent.TimeStamp; newLogEntry.level = loggingEvent.Level.ToString(); newLogEntry.logger = loggingEvent.LoggerName; newLogEntry.message = loggingEvent.MessageObject.ToString(); newLogEntry.method = loggingEvent.LocationInformation.MethodName; newLogEntry.line = loggingEvent.LocationInformation.LineNumber; newLogEntry.classname = loggingEvent.LocationInformation.ClassName; newLogEntry.thread = loggingEvent.ThreadName; DgEventLog?.Add(newLogEntry); }
public static void Update(Note item) { if (item != null) { int index = FindInCollection(items, item); if (index >= 0) { items[index] = item; App.notesManger.Update(item); } else { items?.Add(item); App.notesManger.AddItem(item); } // TODO: Убрать сортировку при неизменении заметок. // Убрать Выделение после выбора. items = new ObservableCollection <Note>(items.OrderByDescending(x => x.Date)); } }
public void AutoPersistCollection() { var disposable = _collection?.AutoPersistCollection( _ => Observable.Create <Unit>( _ => { Console.WriteLine("Done stuff"); return(Disposable.Empty); }).Select(_ => Unit.Default), TimeSpan.FromMilliseconds(200)); for (int i = 0; i < 5; ++i) { _collection?.Add(new MockViewModel()); } _collection?.Clear(); disposable?.Dispose(); }
public void OnUserEnrolled(object sender, WorkshopDTO workshopDto) { if (_type == WorkshopBrowserType.Reserved) { workshopsRawList?.Add(workshopDto); displayList = ApplySorting(ApplyFilters(workshopsRawList)); return; } else { var workshop = workshopsRawList?.FirstOrDefault(dto => dto.Id == workshopDto.Id); if (workshop == null) { return; } workshop.TakenSpots++; workshop.IsEnrolled = true; } }
private void PopulateSearchFilterSettings() { SearchFilterCollection = new ObservableCollection <SearchFilterData>(); try { XElement xElement = XElement.Load("SearchFiltersConfig.xml"); var searchFilters = xElement.Elements(); foreach (var filter in searchFilters) { var nameAttr = filter.Attributes().FirstOrDefault((x) => x.Name == "Name"); if (nameAttr == null) { continue; } var name = nameAttr?.Value; var valAttr = filter.Attributes().FirstOrDefault((x) => x.Name == "Value"); if (valAttr == null) { continue; } var value = valAttr?.Value; SearchFilterCollection?.Add(new SearchFilterData(name, value, false)); } //set the all filter to true SelectedSearchFilter = SearchFilterCollection?.FirstOrDefault(); //allFilter.IsChecked = true; } catch (Exception ex) { CurrentStatus = ex.Message; } }
/// <summary> /// Load the CharacterAttribute from the XmlNode. /// </summary> /// <param name="objNode">XmlNode to load.</param> /// <param name="blnCopy"></param> public void Load(XmlNode objNode, bool blnCopy = false) { //Can't out property and no backing field if (objNode.TryGetField("sourceid", Guid.TryParse, out Guid source)) { SourceID = source; } if (blnCopy) { _guiID = Guid.NewGuid(); _intIncrements = 0; } else { objNode.TryGetInt32FieldQuickly("months", ref _intIncrements); objNode.TryGetField("guid", Guid.TryParse, out _guiID); } objNode.TryGetStringFieldQuickly("name", ref _strName); objNode.TryGetDecFieldQuickly("cost", ref _decCost); objNode.TryGetInt32FieldQuickly("dice", ref _intDice); objNode.TryGetDecFieldQuickly("multiplier", ref _decMultiplier); objNode.TryGetInt32FieldQuickly("area", ref _intArea); objNode.TryGetInt32FieldQuickly("comforts", ref _intComforts); objNode.TryGetInt32FieldQuickly("security", ref _intSecurity); objNode.TryGetInt32FieldQuickly("basearea", ref _intBaseArea); objNode.TryGetInt32FieldQuickly("basecomforts", ref _intBaseComforts); objNode.TryGetInt32FieldQuickly("basesecurity", ref _intBaseSecurity); objNode.TryGetDecFieldQuickly("costforarea", ref _decCostForArea); objNode.TryGetDecFieldQuickly("costforcomforts", ref _decCostForComforts); objNode.TryGetDecFieldQuickly("costforsecurity", ref _decCostForSecurity); objNode.TryGetInt32FieldQuickly("roommates", ref _intRoommates); objNode.TryGetDecFieldQuickly("percentage", ref _decPercentage); objNode.TryGetStringFieldQuickly("baselifestyle", ref _strBaseLifestyle); if (XmlManager.Load("lifestyles.xml").SelectSingleNode($"/chummer/lifestyles/lifestyle[name =\"{_strBaseLifestyle}\"]") == null && XmlManager.Load("lifestyles.xml").SelectSingleNode($"/chummer/lifestyles/lifestyle[name =\"{_strName}\"]") != null) { string baselifestyle = _strName; _strName = _strBaseLifestyle; _strBaseLifestyle = baselifestyle; } if (string.IsNullOrWhiteSpace(_strBaseLifestyle)) { objNode.TryGetStringFieldQuickly("lifestylename", ref _strBaseLifestyle); if (string.IsNullOrWhiteSpace(_strBaseLifestyle)) { List <ListItem> lstQualities = new List <ListItem>(); using (XmlNodeList xmlLifestyleList = XmlManager.Load("lifestyles.xml").SelectNodes("/chummer/lifestyles/lifestyle")) if (xmlLifestyleList != null) { foreach (XmlNode xmlLifestyle in xmlLifestyleList) { string strName = xmlLifestyle["name"]?.InnerText ?? LanguageManager.GetString("String_Error", GlobalOptions.Language); lstQualities.Add(new ListItem(strName, xmlLifestyle["translate"]?.InnerText ?? strName)); } } frmSelectItem frmSelect = new frmSelectItem { GeneralItems = lstQualities, Description = LanguageManager.GetString("String_CannotFindLifestyle", GlobalOptions.Language).Replace("{0}", _strName) }; frmSelect.ShowDialog(); if (frmSelect.DialogResult == DialogResult.Cancel) { return; } _strBaseLifestyle = frmSelect.SelectedItem; } } if (_strBaseLifestyle == "Middle") { _strBaseLifestyle = "Medium"; } if (!objNode.TryGetBoolFieldQuickly("allowbonuslp", ref _blnAllowBonusLP)) { GetNode()?.TryGetBoolFieldQuickly("allowbonuslp", ref _blnAllowBonusLP); } if (!objNode.TryGetInt32FieldQuickly("bonuslp", ref _intBonusLP) && _strBaseLifestyle == "Traveler") { _intBonusLP = 1 + GlobalOptions.RandomGenerator.NextD6ModuloBiasRemoved(); } objNode.TryGetStringFieldQuickly("source", ref _strSource); objNode.TryGetBoolFieldQuickly("trustfund", ref _blnTrustFund); if (objNode["primarytenant"] == null) { _blnIsPrimaryTenant = _intRoommates == 0; } else { objNode.TryGetBoolFieldQuickly("primarytenant", ref _blnIsPrimaryTenant); } objNode.TryGetStringFieldQuickly("page", ref _strPage); // Lifestyle Qualities using (XmlNodeList xmlQualityList = objNode.SelectNodes("lifestylequalities/lifestylequality")) if (xmlQualityList != null) { foreach (XmlNode xmlQuality in xmlQualityList) { LifestyleQuality objQuality = new LifestyleQuality(_objCharacter); objQuality.Load(xmlQuality, this); _lstLifestyleQualities.Add(objQuality); } } // Free Grids provided by the Lifestyle using (XmlNodeList xmlQualityList = objNode.SelectNodes("freegrids/lifestylequality")) if (xmlQualityList != null) { foreach (XmlNode xmlQuality in xmlQualityList) { LifestyleQuality objQuality = new LifestyleQuality(_objCharacter); objQuality.Load(xmlQuality, this); _lstFreeGrids.Add(objQuality); } } objNode.TryGetStringFieldQuickly("notes", ref _strNotes); string strTemp = string.Empty; if (objNode.TryGetStringFieldQuickly("type", ref strTemp)) { _eType = ConvertToLifestyleType(strTemp); } if (objNode.TryGetStringFieldQuickly("increment", ref strTemp)) { _eIncrement = ConvertToLifestyleIncrement(strTemp); } else if (_eType == LifestyleType.Safehouse) { _eIncrement = LifestyleIncrement.Week; } else { XmlNode xmlLifestyleNode = GetNode(); if (xmlLifestyleNode != null && xmlLifestyleNode.TryGetStringFieldQuickly("increment", ref strTemp)) { _eIncrement = ConvertToLifestyleIncrement(strTemp); } } LegacyShim(objNode); }
private void InternalAdd(string property, object newValue) { _inner.Add(property, newValue); _observable?.Add((TValue)newValue); }
private void UpdateMatch(string matchID, MatchDetails matchDetails) { try { Match match = matchDetails?.Match; if (match != null) { var allmatches = new ObservableCollection <Match>(_viewModel.AllMatches); var allMatchesWithDetails = new ObservableCollection <MatchDetails>(_viewModel.AllMatchesWithDetails); Match findMatch = allmatches?.FirstOrDefault(x => x.MatchID == match?.MatchID); if (findMatch != null) { // UPDATE MATCH allmatches.Remove(findMatch); allmatches.Add(match); _viewModel.AllMatches = new ObservableCollection <Match>(allmatches); // REMOVE MATCH if (match.StatusID > 14) { allmatches?.Remove(findMatch); _viewModel.AllMatches = new ObservableCollection <Match>(allmatches); } MatchDetails findMatchDetails = _viewModel.AllMatchesWithDetails.FirstOrDefault(x => x?.Match?.MatchID == findMatch?.MatchID); if (findMatchDetails != null) { // UPDATE MATCH DETAILS findMatchDetails.Match = match; findMatchDetails.PlayersOfMatch = new ObservableCollection <PlayerOfMatch>(matchDetails.PlayersOfMatch); findMatchDetails.EventsOfMatch = new ObservableCollection <EventOfMatch>(matchDetails.EventsOfMatch); findMatchDetails.IsDataLoaded = true; // REMOVE MATCH DETAILS if (match.StatusID > 14) { allMatchesWithDetails.Remove(findMatchDetails); _viewModel.AllMatchesWithDetails = new ObservableCollection <MatchDetails>(allMatchesWithDetails); _viewModel.SetMatchesBySelectedDate(); } } } else { // ADD MATCH allmatches?.Add(match); _viewModel.AllMatches = new ObservableCollection <Match>(allmatches); // ADD MATCH DETAILS allMatchesWithDetails.Add(matchDetails); _viewModel.AllMatchesWithDetails = new ObservableCollection <MatchDetails>(allMatchesWithDetails); _viewModel.SetMatchesBySelectedDate(); } if (match.StatusID != findMatch.StatusID || match.HomeTeamScore != findMatch.HomeTeamScore || match.AwayTeamScore != findMatch.AwayTeamScore) { _ = _viewModel.GetStandingsAsync(); _ = _viewModel.GetCompetitionStatisticsAsync(); } _viewModel.TimeCounter.MatchesTime(_viewModel); } } catch (Exception ex) { _ = ReloadAsync(LoadDataType.FullData); Console.WriteLine($"Error: {ex.Message}"); } }
private void FilteringOrganizationDifferenceImageComponents() { if (!this.IsControlsEnabled) { return; } this.Dispatcher.Invoke(() => { this._itemsSource?.Clear(); }); ToggleControls(null, false, Properties.OutputStrings.FilteringOrganizationDifferenceImageComponents); IEnumerable <SolutionImageComponent> filter = Enumerable.Empty <SolutionImageComponent>(); if (this._OrganizationDifferenceImage != null) { var location = GetComponentLocation(); switch (location) { case ComponentLocation.OnlyInFirst: if (this._OrganizationDifferenceImage.Connection1Image != null) { filter = this._OrganizationDifferenceImage.Connection1Image.Components; } break; case ComponentLocation.OnlyInSecond: if (this._OrganizationDifferenceImage.Connection2Image != null) { filter = this._OrganizationDifferenceImage.Connection2Image.Components; } break; case ComponentLocation.WithDifferences: default: if (this._OrganizationDifferenceImage.DifferentComponents != null) { filter = this._OrganizationDifferenceImage.DifferentComponents; } break; } } string textName = string.Empty; txtBFilter.Dispatcher.Invoke(() => { textName = txtBFilter.Text.Trim().ToLower(); }); if (!string.IsNullOrEmpty(textName)) { filter = filter.Where(s => !string.IsNullOrEmpty(s.Description) && s.Description.IndexOf(textName, StringComparison.InvariantCultureIgnoreCase) > -1); } int?category = null; cmBComponentType.Dispatcher.Invoke(() => { if (cmBComponentType.SelectedItem != null && cmBComponentType.SelectedItem is ComponentType comp ) { category = (int)comp; } }); if (category.HasValue) { filter = filter.Where(e => e.ComponentType == category); } foreach (var component in filter) { _itemsSource?.Add(component); } ToggleControls(null, true, Properties.OutputStrings.FilteringOrganizationDifferenceImageComponentsCompletedFormat1, filter.Count()); }
private async Task AddSubscribeAsync() { var cancellationToken = LoadSnapshotCancellationSource.Token; var config = new HostedConfig(); // Create source switch (sourcePivot.SelectedIndex) { case 0: // URL if (string.IsNullOrWhiteSpace(urlText.Text)) { throw new OperationCanceledException("Empty input"); } if (!Uri.IsWellFormedUriString(urlText.Text, UriKind.Absolute)) { throw new InvalidDataException("The URL is invalid"); } var urlSource = new UrlSource() { Url = urlText.Text }; config.Source = urlSource; break; case 1: // File if (!(previewFileNameText.DataContext is StorageFile file)) { file = await FileOpenPicker.PickSingleFileAsync(); } if (file == null) { throw new InvalidDataException("No file is chosen"); } config.Source = new FileSource(file); break; default: throw new NotSupportedException("The source type is not supported yet"); } // Create format Snapshot snapshot; cancellationToken.ThrowIfCancellationRequested(); switch (((NewHostedConfigType)hostedTypeGridView.SelectedItem).Id) { case "ssd": config.Format = new Ssd(); break; case "clash": config.Format = new Clash(); break; default: throw new NotSupportedException("The hosted config type is not supported yet"); } using (var source = await config.Source.FetchAsync().AsTask(cancellationToken)) { snapshot = await source.DecodeAsync(config.Format).AsTask(cancellationToken); } config.Name = config.Source.GetFileName(); // Save cancellationToken.ThrowIfCancellationRequested(); var configFile = await HostedUtils.SaveHostedConfigAsync(config); try { _ = CachedFileManager.CompleteUpdatesAsync(configFile); cancellationToken.ThrowIfCancellationRequested(); // No need to update local file _ = await HostedUtils.SaveSnapshotAsync(snapshot, config); } catch (Exception) { // Rollback if snapshot is not saved await configFile.DeleteAsync(); throw; } if (Frame.CanGoBack) { Frame.GoBack(); } var newItem = new HostedConfigListItem(config, snapshot); await Task.Delay(300); HostedConfigListItems?.Add(newItem); await Task.Delay(800); HostedConfigListPage.itemForBackNavigation = newItem; Frame.Navigate(typeof(HostedConfigPage), newItem); }
private void ExecuteAddColorCommand(ObservableCollection <UnityColor> target) { target?.Add(new UnityColor()); }
/// <summary> /// Updates a collection with a new list of items /// </summary> /// <typeparam name="T"><see cref="Type"/> of the <see cref="ObservableCollection{T}"/></typeparam> /// <param name="collection"><see cref="ObservableCollection{T}"/> to be updated</param> /// <param name="newCollection"><see cref="IList"/> containing the items and order for the collection to be updated to</param> public static void UpdateCollection <T>(this ObservableCollection <T> collection, IList <T> newCollection) { if (newCollection == null || newCollection.Count == 0) { collection.Clear(); return; } var i = 0; foreach (var item in newCollection) { if (collection.Count > i) { var itemIndex = collection.IndexOf(collection.Where(i => Comparer <T> .Default.Compare(i, item) == 0).FirstOrDefault()); if (itemIndex < 0) { // Item doesn't exist collection.Insert(i, item); } else if (itemIndex > i || itemIndex < i) { // Item exists, but has moved up or down collection.Move(itemIndex, i); } else { if ((!collection[i]?.Equals(item)) ?? false) { // Item has changed, replace it if (item != null) { foreach (var sourceProperty in item.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)) { var targetProperty = collection[i]?.GetType().GetProperty(sourceProperty.Name); if (targetProperty != null && targetProperty.CanWrite) { targetProperty.SetValue(collection[i], sourceProperty.GetValue(item, null), null); } } } } } } else { // Item doesn't exist collection.Add(item); } i++; } // Remove all old items while (collection.Count > newCollection.Count) { collection.RemoveAt(i); } }
public void Add(TData item) => _collection?.Add(item);
private async void LoadScripts() { try { if (!Directory.Exists(scriptDir)) { Directory.CreateDirectory(scriptDir); } if (!File.Exists("scripts.json")) { var scriptsFile = File.Create("scripts.json"); scriptsFile.Close(); } string jsonString = string.Empty; using (var sr = new StreamReader("scripts.json")) { string line; while ((line = sr.ReadLine()) != null) { jsonString += line; } } HashSet <string> extensions = new HashSet <string> { ".lua", ".bak" }; if (!string.IsNullOrEmpty(jsonString)) { var tempData = JsonConvert.DeserializeObject <IEnumerable <ScriptConfigModel> >(jsonString); ScriptsData = new ObservableCollection <ScriptConfigModel>(tempData.Where(x => File.Exists(MainViewModel.AssemblyPath + x.ScriptLocalPath))); foreach (var scriptData in ScriptsData) { if (scriptData.ScriptLocalPath.Contains(MainViewModel.AssemblyPath)) { scriptData.ScriptLocalPath = scriptData.ScriptLocalPath.Replace(MainViewModel.AssemblyPath, ""); } } foreach (var scriptPath in Directory.EnumerateFiles(scriptDir, "*.*").Where(x => extensions.Contains(Path.GetExtension(x)))) { var fileNameWOExt = Path.GetFileNameWithoutExtension(scriptPath); if (ScriptsData.FirstOrDefault(x => x.ScriptName == fileNameWOExt) != null) { continue; } var isEnabled = scriptPath.EndsWith(".bak") ? false : true; var newScriptData = new ScriptConfigModel { IsEnabled = isEnabled, ScriptName = fileNameWOExt, ScriptLocalPath = isEnabled == true ? $@"{scriptDir}\{fileNameWOExt}.lua".Replace(MainViewModel.AssemblyPath, "") : $@"{scriptDir}\{fileNameWOExt}.bak".Replace(MainViewModel.AssemblyPath, "") }; ScriptsData.Add(newScriptData); } } else { ScriptsData = new ObservableCollection <ScriptConfigModel>(); foreach (var scriptPath in Directory.EnumerateFiles(scriptDir, "*.*").Where(x => extensions.Contains(Path.GetExtension(x)))) { var isEnabled = scriptPath.EndsWith(".bak") ? false : true; var fileNameWOext = Path.GetFileNameWithoutExtension(scriptPath); var newScriptData = new ScriptConfigModel { IsEnabled = isEnabled, ScriptName = fileNameWOext, ScriptLocalPath = isEnabled == true ? $@"{scriptDir}\{fileNameWOext}.lua".Replace(MainViewModel.AssemblyPath, "") : $@"{scriptDir}\{fileNameWOext}.lua.bak".Replace(MainViewModel.AssemblyPath, "") }; ScriptsData.Add(newScriptData); } } UpdateScriptConfig(); } catch (Exception ex) { DotaViewModel.GameBrowserVm.MainViewModel.ShowError(ex.Message); Log.Error(ex, "null"); } }
/// <summary> /// Method for adding non working days /// </summary> private void AddNonWorkingDays() { nonWorkingDays = new ObservableCollection <DayOfWeek>(); nonWorkingDays.Add(DayOfWeek.Sunday); nonWorkingDays.Add(DayOfWeek.Saturday); }