//************************************************** //* FILL DATA ON START //************************************************** private void InitializeFormWithData() { _turnPresenter = new TurnPresenter(new TurnsServices()); turnGrid.ItemsSource = turnsList; turnsList.AddRange(_turnPresenter.GetAllTurns()); cleanView(); }
//************************************************** //* FILL DATA ON START //************************************************** private void InitializeFormWithData() { _unitPresenter = new UnitPresenter(new UnitsServices()); unitsGrid.ItemsSource = unitsList; unitsList.AddRange(_unitPresenter.GetAllUnits()); cleanView(); }
//************************************************** //* FILL DATA ON START //************************************************** private void InitializeFormWithData() { _brandPresenter = new BrandPresenter(new BrandsServices()); brandsGrid.ItemsSource = brandsList; brandsList.AddRange(_brandPresenter.GetAllMarcas()); cleanView(); }
//************************************************** //* FILL DATA ON START //************************************************** private void InitializeFormWithData() { _UnitSatPresenter = new UnitSatPresenter(new UnitSatServices()); txtClave.PreviewTextInput += txtClave.OnlyNumbersValidationTextBox; unitsSatGrid.ItemsSource = unitsSatList; unitsSatList.AddRange(_UnitSatPresenter.GetAllUnitSat()); cleanView(); }
private void Form1_FormClosing(object sender, FormClosingEventArgs e) { BindingList <HtmlItems> combined = new BindingList <HtmlItems>(); combined.AddRange(_gekozenItems); combined.AddRange(_htmlItemsList); HtmlItems.Save(combined); }
//************************************************** //* FILL DATA ON START //************************************************** private void InitializeFormWithData() { _ScreenPresenter = new ScreenPresenter(new ScreenServices()); txtNivel.PreviewTextInput += txtNivel.OnlyNumbersValidationTextBox; screenGrid.ItemsSource = screenList; screenList.AddRange(_ScreenPresenter.GetAllPantallas()); cleanView(); }
public CreatePromo() { InitializeComponent(); _promotionsPresenter = new PromotionsPresenter(new PromotionsServices()); HoraInicio.Value = DateTime.Now; HoraFin.Value = DateTime.Now; PromotionsGrid.ItemsSource = promocionesList; ProductsPromotionsGrid.ItemsSource = producsPromotionList; ComboDepartamentos.ItemsSource = _promotionsPresenter.GetAllDepartamentos(); ComboMarcas.ItemsSource = _promotionsPresenter.GetAllMarca(); promocionesList.AddRange(_promotionsPresenter.GetAllPromociones()); }
private void LoadSettings() { _log.Debug("Loading for geometry ..."); if (!Settings.Default.FrmFindReplace_Geometry.IsNullEmptyOrWhitespace()) { try { Utilities.Forms.RestoreFormPosition.GeometryFromString(Settings.Default.FrmFindReplace_Geometry, this); } catch (Exception ex) { _log.Error("Error loading form geometry."); _log.Error(ex.Message, ex); } } else { _log.Warn("Form geometry is not set."); } _log.Debug("Loading search terms ..."); try { if (!string.IsNullOrEmpty(Settings.Default.FrmFindReplace_SearchTerms)) { var list = Deserialize(Settings.Default.FrmFindReplace_SearchTerms); _searchTerms.AddRange(list); } } catch (Exception ex) { _log.Error("Error loading search terms."); _log.Error(ex.Message, ex); } _log.Debug("Loading replace terms ..."); try { if (!string.IsNullOrEmpty(Settings.Default.FrmFindReplace_ReplaceTerms)) { var list = Deserialize(Settings.Default.FrmFindReplace_ReplaceTerms); _replaceTerms.AddRange(list); } } catch (Exception ex) { _log.Error("Error loading replace terms."); _log.Error(ex.Message, ex); } }
public void AddRangeTest() { BindingList<string> b1 = new BindingList<string>() { "a", "b" }; BindingList<string> b2 = new BindingList<string>(); b2.AddRange(b1); Assert.AreEqual(2, b2.Count); }
private async Task LoadFullBlobAsync() { if (SelectedBlob == null || Storage == null) { return; } IsLoading = true; EditableMetadata.Clear(); try { FullBlob = await Storage.GetBlobAsync(SelectedBlob); if (FullBlob != null) { EditableMetadata.AddRange(FullBlob.Metadata.Select(p => new EditableKeyValue { Key = p.Key, Value = p.Value })); } } catch (Exception ex) { await DialogService.ShowMessageAsync("Failed to load", ex.Message); } finally { IsDirty = false; IsLoading = false; } }
private void almacenComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { ComboBox almacenes = (ComboBox)sender; Almacenes almancen = almacenes.SelectedItem as Almacenes; productoAlmacenList.AddRange(_inventoryPresenter.GetProductosByAlmacen(almancen.idAlmacen)); }
private void LoadNuGetConnections() { var data = LoadPersistedData <List <NuGetGalleryConnection> >("nuget-connections.xml"); var viewModels = NuGetGalleryConnectionViewModel.FromDto <NuGetGalleryConnectionViewModel>(data); NuGetConnections.AddRange(viewModels); }
public void SetData(DataSchema dataSchema, ReportResults reportResults, ClusteringSpec clusteringSpec) { _clusterSpecRows.Clear(); _clusterSpecRows.AddRange(MakeRows(dataSchema, reportResults, clusteringSpec)); comboDistanceMetric.SelectedItem = ClusterMetricType.FromName(clusteringSpec?.DistanceMetric) ?? ClusterMetricType.DEFAULT; }
/// <summary> /// 转换为BindingList。 /// </summary> /// <typeparam name="T">迭代器的数据类型。</typeparam> /// <param name="items">迭代器实例。</param> /// <returns>返回BindingList实例</returns> public static BindingList <T> ToBindingList <T>(this IEnumerable <T> items) { var collection = new BindingList <T>(); collection.AddRange(items); return(collection); }
private void LoadUsers() { _users.Clear(); _users.AddRange(_repo.Read()); WireUpDropDown(); }
private void endCashClose() { cortesToSave = _cashClosePresenter.GetCurrentCashClose(App._userApplication.idUsuario); cortesToSave.FolioVentaFin = _cashClosePresenter.GetLastFolio(); cortesToSave.TotalVenta = _cashClosePresenter.GetTotalSale(App._userApplication.idUsuario, cortesToSave.FolioVentaInicio, (long)cortesToSave.FolioVentaFin); paymentsGrid.ItemsSource = cortePagoList; cortePagoList.AddRange(_cashClosePresenter.GetAllPagosCorte(cortesToSave.FolioVentaInicio, (long)cortesToSave.FolioVentaFin, App._userApplication.idUsuario)); taxesGrid.ItemsSource = impuestoList; impuestoList.AddRange(_cashClosePresenter.GetAllTaxes(cortesToSave.FolioVentaInicio, (long)cortesToSave.FolioVentaFin, App._userApplication.idUsuario)); totalSale.Text = cortesToSave.TotalVenta.ToString("C2"); totalTaxe = _cashClosePresenter.GetTotalTaxes(cortesToSave.FolioVentaInicio, (long)cortesToSave.FolioVentaFin, App._userApplication.idUsuario); totalTaxes.Text = totalTaxe.ToString("C2"); ivaGrid.ItemsSource = tasaList; tasaList.AddRange(_cashClosePresenter.GetTotalWithTaxes(cortesToSave.FolioVentaInicio, (long)cortesToSave.FolioVentaFin, App._userApplication.idUsuario)); returnsGrid.ItemsSource = returnList; totalTasa.Text = cortesToSave.TotalVenta.ToString("C2"); ivaTasa = _cashClosePresenter.CalcIvaTasa(App._userApplication.idUsuario, cortesToSave.FolioVentaInicio, (long)cortesToSave.FolioVentaFin); totalTasaIva.Text = ivaTasa.ToString("C2"); returnList.AddRange(_cashClosePresenter.GetReturnsWithTaxes(cortesToSave.FolioVentaInicio, (long)cortesToSave.FolioVentaFin, App._userApplication.idUsuario)); totalReturns = _cashClosePresenter.GetTotalReturns(cortesToSave.FolioVentaInicio, (long)cortesToSave.FolioVentaFin, App._userApplication.idUsuario); totalReturn.Text = totalReturns.ToString("C2"); ivaReturns = _cashClosePresenter.CalcIvaReturn(App._userApplication.idUsuario, cortesToSave.FolioVentaInicio, (long)cortesToSave.FolioVentaFin); totalReturnIva.Text = ivaReturns.ToString("C2"); saveCashClose(cortesToSave); }
/// <summary> /// Creates a BindingList of T and adds everything from items to it. /// </summary> /// <typeparam name="T">Any type</typeparam> /// <param name="items">The source from which to get items of type T</param> /// <returns></returns> public static BindingList <T> ToBindingList <T>(this IEnumerable <T> items) { var list = new BindingList <T>(); list.AddRange(items); return(list); }
public CroInfoViewModel(string name, CroInfo info) { mInfo = info; mOriginalKey = info.Key; if (string.IsNullOrWhiteSpace(mOriginalKey)) { mOriginalKey = new FileInfo(info.Filepath).Directory.Name; } mTypes = new BindingList <CroInfoTypeItem>(); mTypes.AddRange(CroInfoTypeItem.All); mPatterns = new BindingList <CroPatternViewModel>(); LoadPatterns(); mAddNewPatternCommand = new DelegateCommand(DoAddNewPattern, CanAddNewPattern); mSetPatternTextCommand = new DelegateCommand(DoSetPatternText, CanSetPatternText); Name = name; Key = mOriginalKey; AddToPath = info.AddToPath; UpdateIsEditable(); }
private void LoadPatterns() { using (mPatterns.DeferBinding()) { mPatterns.Clear(); mPatterns.AddRange(mInfo.Patterns.Select(p => new CroPatternViewModel(mPatterns, p))); } }
private void InitializeFormWithData() { _permissionsPresenter = new PermissionsPresenter(new PermissionsServices()); usersList.AddRange(_permissionsPresenter.GetAllUsuariosWithPermissions()); UserGrid.ItemsSource = usersList; screensList.AddRange(_permissionsPresenter.GetAllPantallas()); searchUserTxtBox.PreviewTextInput += searchUserTxtBox.OnlyLettersValidationTextBox; }
public ProductDealer(OrderPurchasePresenter orderPurchasePresenter, string supplier, ProveedorEntity supplierToSave) { InitializeComponent(); _supplierToSave = supplierToSave; _orderPurchasePresenter = orderPurchasePresenter; supplierNametxt.Text = supplier; List <Departamentos> departmentsList = new List <Departamentos>(); departmentsList.Add(new Departamentos { idDepartamento = 0, Descripcion = "TODOS" }); departmentsList.AddRange(_orderPurchasePresenter.GetAllDepartamentos()); comboDepartmentsProducts.ItemsSource = departmentsList; productsDepartmentGrid.ItemsSource = productsDepartment; productsSupplierGrid.ItemsSource = productsSupplier; productsSupplier.AddRange(_supplierToSave.productosWithDepartment); comboDepartmentsProducts.SelectedValue = 0; }
private void InitializeFormWithData() { _orderPurchasePresenter = new OrderPurchasePresenter(new OrderPurchaseServices()); productsToBuyList.ListChanged += ProductsToBuyList_ListChanged; ordersList.AddRange(_orderPurchasePresenter.GetAllOrders()); IEnumerable <ProveedorEntity> proveedores = _orderPurchasePresenter.GetSuppliersWithProducts(); IEnumerable <Almacenes> almacenes = _orderPurchasePresenter.GetAllAlmacenes(); suppliersList.AddRange(proveedores); suppliersGrid.ItemsSource = suppliersList; ComboWarehouse.ItemsSource = almacenes.ToList(); ComboWarehouse.SelectedIndex = 0; comboSuppliersGral.ItemsSource = proveedores.ToList(); Order.ItemsSource = productsToBuyList; OrdersHome.ItemsSource = ordersList; initialDateSearch.SelectedDate = finalDateSearch.SelectedDate = DateTime.Now; checkTodas.IsChecked = true; }
public static void SafeAddRange <T>(this BindingList <T> bindingList, IEnumerable <T> data) { bindingList.RaiseListChangedEvents = false; bindingList.AddRange(data); bindingList.RaiseListChangedEvents = true; Application.Current.Dispatcher.BeginInvoke(bindingList.ResetBindings); }
/// <inheritdoc /> public void Adapt(ISortedChangeSet <TObject, TKey> changes) { if (changes == null) { throw new ArgumentNullException(nameof(changes)); } switch (changes.SortedItems.SortReason) { case SortReason.InitialLoad: case SortReason.ComparerChanged: case SortReason.Reset: using (new BindingListEventsSuspender <TObject>(_list)) { _list.Clear(); _list.AddRange(changes.SortedItems.Select(kv => kv.Value)); } break; case SortReason.DataChanged: if (changes.Count - changes.Refreshes > _refreshThreshold) { using (new BindingListEventsSuspender <TObject>(_list)) { _list.Clear(); _list.AddRange(changes.SortedItems.Select(kv => kv.Value)); } } else { DoUpdate(changes); } break; case SortReason.Reorder: DoUpdate(changes); break; default: throw new ArgumentOutOfRangeException(nameof(changes)); } }
/// <summary> /// Gets a list of <see cref="SelectionCandidate"/>s from the <see cref="ISolver"/> to populate <see cref="dataGridVersions"/>. /// </summary> private void UpdateDataGridVersions() { var candidates = checkBoxShowAllVersions.Checked ? _candidates : _candidates.Where(candidate => candidate.IsSuitable); var list = new BindingList <SelectionCandidate> { AllowEdit = true, AllowNew = false }; list.AddRange(candidates); dataGridVersions.DataSource = list; }
/// <summary> /// Scrapes the Title value /// </summary> /// <param name="id">The MovieUniqueId for the scraper.</param> /// <param name="threadID">The thread MovieUniqueId.</param> /// <param name="output">The scraped Title value.</param> /// <param name="alternatives">Alternative namings found for a title.</param> /// <param name="logCatagory">The log catagory.</param> /// <returns>Scrape succeeded [true/false]</returns> public new bool ScrapeTitle(string id, int threadID, out string output, out BindingList <string> alternatives, string logCatagory) { output = string.Empty; alternatives = new BindingList <string>(); try { var html = this.GetHtml("main", threadID, id); var releaseInfoHtml = this.GetHtml("releaseinfo", threadID, id); output = YRegex.Match("(<title>)(.*)( [(].*</title>)", html, 2, true); var titleAltHtml = YRegex.Match( @"\(AKA\)</a></h5><table\sborder=""0""\scellpadding=""2"">(?<html>.*?)</tr></table>", releaseInfoHtml, "html"); var altTitles = YRegex.Matches( @"<td>(?<name>.*?)</td><td>(?<details>.*?)</td>", titleAltHtml, "name", "details", true); alternatives.AddRange(from s in altTitles where !s.Value.ToLower().Contains(new[] { "imax ", "working ", "fake " }) select s.Key); if (html.Contains("title-extra")) { var origTitle = YRegex.Match( @"class=""title-extra"">(?<title>.*?) <i>\(original title\)</i>", html, "title"); if (origTitle.Trim().Length > 0) { output = origTitle; } } output = Regex.Replace(output, @"\(\d{4}\)", string.Empty); output = Tools.Clean.Text.ValidizeResult(output); return(output.IsFilled()); } catch (Exception ex) { Log.WriteToLog(LogSeverity.Error, threadID, logCatagory, ex.Message); return(false); } }
private void loadInfoOrder(Ordenes currentOrder) { IEnumerable <ProductToBuy> productsResult = _orderPurchasePresenter.GetProductsByList(currentOrder.ProductosOrden.ToList()); productsResult = productsResult.Select(s => { ProductosCompra productoAux = (from producto in currentOrder.ProductosOrden where producto.idProducto.Equals(s.idProducto) select producto).SingleOrDefault(); s.idProveedor = currentOrder.idProveedor; s.quantity = productoAux.Cantidad; s.total = productoAux.Monto; return(s); }).ToList(); productsToBuyList.Clear(); productsToBuyList.AddRange(productsResult); if (currentOrder != null) { tabControlOrder.SelectedIndex = 1; if (currentOrder.estatus != 'S') { cancelOrder = true; generateOrderButton.Content = "CANCELAR"; } else { cancelOrder = false; generateOrderButton.Content = "GENERAR \nORDEN(ES)"; } } }
public PasswordManagerForm(List <PasswordModel> models) { InitializeComponent(); if (models == null) { throw new ArgumentNullException(nameof(models)); } Models.AddRange(models); GridView.AutoGenerateColumns = false; GridView.DataSource = Models; }
private void FillPromoData(Promociones promotion) { idPromocion = promotion.idPromocion; producsPromotionList.AddRange(promotion.Productos); NombrePromocionTxt.Text = promotion.NombrePromocion; DiasPromocionTxt.Text = promotion.DiasPromocion; PrecioTxt.Text = promotion.Monto.ToString(); PorcentajeTxt.Text = promotion.Porcentaje.ToString(); HoraInicio.Value = new DateTime(promotion.Inicio); HoraFin.Value = new DateTime(promotion.Fin); ComboDepartamentos.SelectedValue = promotion.idDepartamento != 0 ? promotion.idDepartamento : -1; ComboMarcas.SelectedValue = promotion.idMarca != 0 ? promotion.idMarca : -1; }
private void ActiveTasksForm_Load(object sender, EventArgs e) { Text = ResourceManager.GetString("ActiveTasks"); ActiveTasks.AddRange(TaskManager.Tasks); TaskManager.TaskCompleted += TaskCompleted; TaskManager.TaskManagerCompleted += TaskManagerCompleted; if (!ActiveTasks.Any() || ActiveTasks.All(x => x.InnerTask.IsCompleted)) { AllTasksCompleted?.Invoke(); } ActiveTasksGridView.AutoGenerateColumns = false; ActiveTasksGridView.DataSource = ActiveTasks; ActiveTasksGridView.Refresh(); }
private void comboDepartmentsProducts_SelectionChanged(object sender, SelectionChangedEventArgs e) { int idDepartment = (int)comboDepartmentsProducts.SelectedValue; productsSupplier.Clear(); if (idDepartment != 0) { productsSupplier.AddRange(_supplierToSave.productosWithDepartment.Where(x => x.idDepartamento.Equals(idDepartment))); } else { productsSupplier.AddRange(_supplierToSave.productosWithDepartment); } productsDepartment.Clear(); productsDepartment.AddRange(_orderPurchasePresenter.GetAllProductsByDepartment(idDepartment).Where(x => !_supplierToSave.productosWithDepartment.Select(y => y.idProducto).ToList().Contains(x.idProducto))); }
public SpiderGame(CardInfo.SuitEnum[] level) { Width = DefaultWidth; Height = DefaultHeight; //this.ClipTo(0, 0, DefaultWidth, DefaultHeight); var GameOverBox = new TextBox { Width = DefaultWidth, TextAlignment = System.Windows.TextAlignment.Center, Foreground = Brushes.White, Background = Brushes.Transparent, BorderThickness = new Thickness(0), IsReadOnly = true, FontSize = 24, }.MoveTo(0, DefaultHeight / 2).AttachTo(this); GameOver += delegate { GameOverBox.Text = "Congratulations! You Won!"; }; // add autoscroll ? this.MyDeck.SizeTo(DefaultWidth, DefaultHeight); this.MyDeck.AttachContainerTo(this); this.MyDeck.GetRank = e => (int)RankMapping[e]; this.MyDeck.CardCustomBackgroundSource = new Abstractatech.Avalon.Cards.Avalon.Images.spider().Source; //this.MyDeck.Overlay.Opacity = 0.6; MyStatus = new StatusControl().AttachContainerTo(this).MoveContainerTo( (DefaultWidth - StatusControl.Width) / 2, (DefaultHeight - StatusControl.Height) ); MyStatus.Container.Hide(); System.Console.WriteLine("--- spider ---"); System.Console.WriteLine("adding card infos... "); MyDeck.UnusedCards.AddRange(CardInfo.By(2, level)); System.Console.WriteLine("creating stacklists... "); DealStacks = MyDeck.CreateStackList(); PlayStacks = MyDeck.CreateStackList(); DeadStacks = MyDeck.CreateStackList(); PlayStacks.ListChanged += (sender, args) => { if (args.ListChangedType == ListChangedType.ItemAdded) { var s = PlayStacks[args.NewIndex]; } }; DeadStacks.ListChanged += (sender, args) => { if (args.ListChangedType == ListChangedType.ItemAdded) { var s = DeadStacks[args.NewIndex]; //s.Control.Hide(); s.CardMargin = new Vector { X = 2, Y = 0 }; s.Cards.ListChanged += (sender2, args2) => { if (args2.ListChangedType == ListChangedType.ItemAdded) { //s[args2.NewIndex].Enabled = false; } }; } }; #region drag rules MyDeck.ApplyCardRules += delegate(Card c) { c.Moved += delegate { if (c.StackedCards.Length == 0) { CheckForGoodSuit(c.CurrentStack); MyStatus.Moves++; MyStatus.Score--; MyStatus.Update(); } CheckForWin(); }; c.ValidateDragStart += delegate { if (Cheat) return true; return c.SelectedCards.AllWithPrevious( (Previous, Current) => { if (Previous.Info.Suit != Current.Info.Suit) return false; return Previous.Rank + 1 == Current.Rank; } ); }; c.ValidateDragStop += CandidateStack => { if (Cheat) return true; if (PlayStacks.Contains(CandidateStack)) { if (CandidateStack.Cards.Count == 0) return true; var Candidate = CandidateStack.Last(); // we do not care about the suit if (c.Rank == Candidate.Rank + 1) //if (c.Info.Suit == Candidate.Info.Suit) return true; return false; } return false; }; }; #endregion System.Console.WriteLine("creating playstack... "); var Margin = (DefaultWidth - CardInfo.Width * 10) / 11; PlayStacks.AddRange( Enumerable.Range(0, 10).ToArray( i => new CardStack { Name = "PlayStack " + i, CardMargin = new Vector { Y = 20 } }.MoveTo( Margin + i * (CardInfo.Width + Margin), Margin + 40 ).Apply( s => { if (i < 4) s.Cards.AddRange(MyDeck.FetchCards(5)); else s.Cards.AddRange(MyDeck.FetchCards(4)); if (Cheat) s.Cards.ForEach(k => k.VisibleSide = Card.SideEnum.TopSide); } ) ) ); PlayStacks.ForEach( delegate(CardStack s) { s.Cards.ListChanged += (sender, args) => { if (args.ListChangedType == ListChangedType.ItemDeleted) //if (MyStatus.Ready) s.RevealLastCard(); }; } ); DealStacks.ListChanged += (sender, args) => { if (args.ListChangedType == ListChangedType.ItemAdded) { var s = DealStacks[args.NewIndex]; s.CardMargin = new Vector { Y = 0, X = 0 }; s.Update(); s.Click += delegate { if (DealStacks.Contains(s)) { //if (MyStatus.Ready) DealRow(null); } else { System.Console.WriteLine("whoops wrong stack click - " + args.NewIndex); } }; } }; System.Console.WriteLine("creating dealstack... "); var dealpoint = new Point { X = DefaultWidth - CardInfo.Width - Margin, Y = DefaultHeight - CardInfo.Height - Margin - 17 - Margin }; while (MyDeck.UnusedCards.Count > 0) { var s = new CardStack { MyDeck.FetchCards(10) }; //s.Overlay.Opacity = 1; s.Name = "DealStack"; DealStacks.Add( s.MoveTo(Convert.ToInt32(dealpoint.X), Convert.ToInt32(dealpoint.Y)) ); dealpoint.X -= 10; } // we will collect cards here DeadStacks.Add(new CardStack().MoveTo(Margin, Convert.ToInt32(dealpoint.Y))); DealRow( delegate { MyStatus.Score = 500; MyStatus.Moves = 0; MyStatus.Update(); MyStatus.Container.Show(); } ); }
/// <summary> /// Gets a list of <see cref="SelectionCandidate"/>s from the <see cref="ISolver"/> to populate <see cref="dataGridVersions"/>. /// </summary> private void UpdateDataGridVersions() { var candidates = checkBoxShowAllVersions.Checked ? _candidates : _candidates.Where(candidate => candidate.IsSuitable); var list = new BindingList<SelectionCandidate> {AllowEdit = true, AllowNew = false}; list.AddRange(candidates); dataGridVersions.DataSource = list; }
public MineMapLoader(BindingList<MineFieldButton> Context) { this.Context = Context; const int ProgressbarWidth = 16; var Progressbar = Enumerable.Range(0, ProgressbarWidth).ToArray( i => { var k = new MineFieldButton { IndexX = i - ProgressbarWidth / 2, IndexY = 0, IsEnabled = false, BackgroundColor = Colors.Gray }; Context.Add(k); return k; } ); var Gradient = new[] { Colors.Red, Colors.Gray, Colors.Gray }.ToGradient(Progressbar.Length); var ProgressbarTimer = (1000 / 24).AtIntervalWithCounter( c => { for (int i = 0; i < Progressbar.Length; i++) { Progressbar[Progressbar.Length - 1 - i].BackgroundColor = Gradient.AtModulus(c + i); } } ); Action<double, Color> SetPercentage = (value, color) => { var k = Math.Ceiling(ProgressbarWidth * value); for (int i = 0; i < Progressbar.Length; i++) { if (i < k) Progressbar[i].BackgroundColor = color; else Progressbar[i].BackgroundColor = Colors.Gray; } }; const int ChunkLoad = 8; Action<MineFieldButton[], Action> PrepareCache = (a, done) => { var n = new List<MineFieldButton>(); a.ForEach( (j, next) => { j.CachedNeighbours = j.Neighbours.ToArray(); j.CachedRegion = j.Region.ToArray(); n.Add(j); SetPercentage((double)n.Count / (double)a.Length, Colors.Red); if (n.Count % ChunkLoad == 0) 1.AtDelay(next); else next(); } )( delegate { foreach (var k in Progressbar) { Context.Remove(k); } Context.AddRange(a.ToArray()); done(); } ); }; this.Prepare = (i, done) => { ProgressbarTimer.Stop(); foreach (var k in Progressbar) { k.BackgroundColor = Colors.Gray; } var a = i.ToArray(); var n = new List<MineFieldButton>(); a.ForEach( (j, next) => { var k = new MineFieldButton { IndexX = j.IndexX, IndexY = j.IndexY, BackgroundColor = j.BackgroundColor, IsMined = j.IsMined }; var lx = j.IndexX + this.Lookup.XLength / 2; var ly = j.IndexY + this.Lookup.YLength / 2; this.Lookup[lx, ly] = k; k.ByOffset = (x, y) => this.Lookup[lx + x, ly + y]; n.Add(k); SetPercentage((double)n.Count / (double)a.Length, Colors.Blue); if (n.Count % ChunkLoad == 0) 1.AtDelay(next); else next(); } )( delegate { PrepareCache(n.ToArray(), done); } ); }; }
/// <summary> /// Scrapes the Title value /// </summary> /// <param name="id">The MovieUniqueId for the scraper.</param> /// <param name="threadID">The thread MovieUniqueId.</param> /// <param name="output">The scraped Title value.</param> /// <param name="alternatives">Alternative namings found for a title.</param> /// <param name="logCatagory">The log catagory.</param> /// <returns>Scrape succeeded [true/false]</returns> public new bool ScrapeTitle(string id, int threadID, out string output, out BindingList<string> alternatives, string logCatagory) { output = string.Empty; alternatives = new BindingList<string>(); try { var html = this.GetHtml("main", threadID, id); var releaseInfoHtml = this.GetHtml("releaseinfo", threadID, id); output = YRegex.Match("(<title>)(.*)( [(].*</title>)", html, 2, true); var titleAltHtml = YRegex.Match( @"\(AKA\)</a></h5><table\sborder=""0""\scellpadding=""2"">(?<html>.*?)</tr></table>", releaseInfoHtml, "html"); var altTitles = YRegex.Matches( @"<td>(?<name>.*?)</td><td>(?<details>.*?)</td>", titleAltHtml, "name", "details", true); alternatives.AddRange(from s in altTitles where !s.Value.ToLower().Contains(new[] { "imax ", "working ", "fake " }) select s.Key); if (html.Contains("title-extra")) { var origTitle = YRegex.Match( @"class=""title-extra"">(?<title>.*?) <i>\(original title\)</i>", html, "title"); if (origTitle.Trim().Length > 0) { output = origTitle; } } output = Regex.Replace(output, @"\(\d{4}\)", string.Empty); output = Tools.Clean.Text.ValidizeResult(output); return output.IsFilled(); } catch (Exception ex) { Log.WriteToLog(LogSeverity.Error, threadID, logCatagory, ex.Message); return false; } }
public SolitaireGame() { Width = DefaultWidth; Height = DefaultHeight; System.Console.WriteLine("--- solitare ---"); this.MyStatus = new StatusControl().AttachContainerTo(this).MoveContainerTo( (DefaultWidth - StatusControl.Width) / 2, (DefaultHeight - StatusControl.Height) ); var GameOverBox = new TextBox { Width = DefaultWidth, TextAlignment = System.Windows.TextAlignment.Center, Foreground = Brushes.White, Background = Brushes.Transparent, BorderThickness = new Thickness(0), IsReadOnly = true, FontSize = 24, }.MoveTo(0, DefaultHeight / 2).AttachTo(this); // add autoscroll ? this.MyDeck.SizeTo(DefaultWidth, DefaultHeight); this.MyDeck.AttachContainerTo(this); this.MyDeck.GetRank = e => (int)RankMapping[e]; System.Console.WriteLine("adding card infos... "); MyDeck.UnusedCards.AddRange(CardInfo.FullDeck()); this.MyStatus.Score = -1; this.MyStatus.CardsLeft = this.MyDeck.UnusedCards.Count; this.MyStatus.Update(); MyDeck.Stacks.ListChanged += (sender, args) => { if (args.ListChangedType == ListChangedType.ItemAdded) { // fixme: dynamically set backside for this card //var s = MyDeck.Stacks[args.NewIndex]; //s.SetBackground(MyDeck.GfxPath + "/spider.empty.png"); } }; System.Console.WriteLine("creating stacklists... "); PlayStacks = MyDeck.CreateStackList(); TempStacks = MyDeck.CreateStackList(); GoalStacks = MyDeck.CreateStackList(); PlayStacks.ForEachNewItem( delegate(CardStack s) { s.CardMargin = new Vector { Y = 20 }; s.Update(); s.Cards.ListChanged += (sender, args) => { if (args.ListChangedType == ListChangedType.ItemDeleted) s.RevealLastCard(); }; } ); GameOver += delegate { GameOverBox.Text = "Congratulations! You Won!"; }; System.Console.WriteLine("creating goalstack... "); var Margin = (DefaultWidth - CardInfo.Width * 7) / 8; var ReserveStack = new CardStack().MoveTo(Margin, Margin); var UsedChoiceStack = new CardStack().MoveTo(Margin + CardInfo.Width + Margin, Margin); var ChoiceStack = new CardStack().MoveTo(Margin + CardInfo.Width + Margin, Margin); TempStacks.AddRange( ReserveStack, UsedChoiceStack, ChoiceStack ); ReserveStack.CardMargin.X = 0; ReserveStack.CardMargin.Y = 0; UsedChoiceStack.CardMargin.X = 0; UsedChoiceStack.CardMargin.Y = 0; ChoiceStack.CardMargin.X = 20; ChoiceStack.CardMargin.Y = 0; #region rules Func<bool> Rule_WinConditionMet = delegate { if (PlayStacks.All(s => s.Cards.Count > 0)) return false; if (TempStacks.All(s => s.Cards.Count == 0)) return false; return true; }; Func<Card, Card, bool> RuleForStackingCardsInGoalStack = (Previous, Current) => { if (Cheat) return true; if (Previous == null) return Current.Info.Rank == CardInfo.RankEnum.RankAce; if (Previous.Info.Suit != Current.Info.Suit) return false; if (Previous.Rank != Current.Rank + 1) return false; return true; }; Func<Card, Card, bool> RuleForStackingCardsInPlayStack = (Previous, Current) => { if (Cheat) return true; if (Previous.Info.SuitColor == Current.Info.SuitColor) return false; if (Previous.Rank + 1 != Current.Rank) return false; return true; }; #endregion MyDeck.ApplyCardRules += delegate(Card card) { card.MovedByLocalPlayer += delegate { MyStatus.Moves++; MyStatus.Update(); }; card.ValidateDragStart = delegate { if (Cheat) return true; // cannot remove cards from goal stack if (GoalStacks.Contains(card)) return false; if (TempStacks.Contains(card)) { return (card == ChoiceStack.LastOrDefault()); } // cannot drag a pile of cards unless alternate colors and descending numbers return card.SelectedCards.AllWithPrevious(RuleForStackingCardsInPlayStack); }; card.ValidateDragStop = CandidateStack => { if (Cheat) return true; if (TempStacks.Contains(CandidateStack)) { return false; } if (PlayStacks.Contains(CandidateStack)) { if (CandidateStack.Cards.Count == 0) return card.Info.Rank == CardInfo.RankEnum.RankKing; return (RuleForStackingCardsInPlayStack(CandidateStack.Cards.Last(), card)); } if (GoalStacks.Contains(CandidateStack)) { if (card.StackedCards.Length > 0) return false; return (RuleForStackingCardsInGoalStack(CandidateStack.Cards.LastOrDefault(), card)); } return false; }; }; GoalStacks.ForEachNewItem( s => { s.CardMargin.X = 0; s.CardMargin.Y = 0; s.Cards.ForEachNewItem( card => { this.MyStatus.CardsLeft--; this.MyStatus.Update(); if (card.Info.Rank == CardInfo.RankEnum.RankKing) { card.VisibleSide = Card.SideEnum.BackSide; if (Rule_WinConditionMet()) { // winner! MyDeck.Sounds.win(); if (this.GameOver != null) this.GameOver(); } } } ); } ); GoalStacks.AddRange( Enumerable.Range(0, 4).ToArray( i => new CardStack().MoveTo(DefaultWidth - ((CardInfo.Width + Margin) * 4) + i * (CardInfo.Width + Margin), Margin) ) ); System.Console.WriteLine("creating playstack... "); PlayStacks.AddRange( Enumerable.Range(0, 7).ToArray( i => new CardStack().MoveTo(Margin + i * (CardInfo.Width + Margin), Margin * 3 + CardInfo.Height).Apply(s => s.Cards.AddRange(MyDeck.FetchCards(i + 1))) ) ); ReserveStack.Cards.AddRange(MyDeck.FetchCards(MyDeck.UnusedCards.Count)); ReserveStack.Update(); PlayStacks.ForEach(k => k.Last().VisibleSide = Card.SideEnum.TopSide); UsedChoiceStack.Cards.ForEachNewItem( card => card.VisibleSide = Card.SideEnum.BackSide ); ChoiceStack.Cards.ForEachNewItem( card => card.VisibleSide = Card.SideEnum.TopSide ); ChoiceStack.Click += delegate { ChoiceStack.Update(); } ; ReserveStack.Overlay.Cursor = Cursors.Hand; ReserveStack.Cards.ForEachNewItem( card => card.VisibleSide = Card.SideEnum.BackSide ); var ReserveStackEnabled = true; ReserveStack.Click += delegate { if (!ReserveStackEnabled) return; if (ReserveStack.Cards.Count == 0) { MyDeck.Sounds.deal(); ChoiceStack.FirstOrDefault().Apply( card => { card.AnimatedMoveToStack(ReserveStack, null, null); } ); UsedChoiceStack.FirstOrDefault().Apply( card => { card.AnimatedMoveToStack(ReserveStack, null, null); } ); } else { ReserveStackEnabled = false; ChoiceStack.Cards.ToArray().ForEach( card => { card.AttachToStack(UsedChoiceStack); } ); UsedChoiceStack.Update(); 3.Times( SignalNext => ReserveStack.LastOrDefault().Apply( card => { card.BringToFront(); Console.WriteLine(card.ToString()); card.AnimatedMoveToStack(ChoiceStack, null, null); MyDeck.Sounds.deal(); 200.AtDelay(SignalNext); } ) ); } // a timepoint when movements are done.. this should ba an event actually 2000.AtDelay(() => ReserveStackEnabled = true); }; }
public FreeCellGame() { Width = DefaultWidth; Height = DefaultHeight; var Margin = (DefaultWidth - CardInfo.Width * 8) / 9; var GameOverBox = new TextBox { Width = DefaultWidth, TextAlignment = System.Windows.TextAlignment.Center, Foreground = Brushes.White, Background = Brushes.Transparent, BorderThickness = new Thickness(0), IsReadOnly = true, FontSize = 24, }.MoveTo(0, DefaultHeight / 2).AttachTo(this); GameOver += delegate { GameOverBox.Text = "Congratulations! You Won!"; }; #region king var KingCanvas = new Canvas { Width = 96, Height = 96 }.AttachTo(this).MoveTo( (DefaultWidth - 32) / 2, Margin * 2 + (CardInfo.Height - 32) / 2 ); var KingRight = new kingbitm().AttachTo(KingCanvas); var KingLeft = new kingleft().AttachTo(KingCanvas); var KingSmile = new kingsmil().AttachTo(KingCanvas); KingSmile.Hide(); #endregion this.MyDeck.Overlay.MouseMove += (sender, args) => { var p = args.GetPosition(this.MyDeck.Overlay); if (p.X < DefaultWidth / 2) { KingLeft.Show(); KingRight.Hide(); } else { KingLeft.Hide(); KingRight.Show(); } }; this.MyStatus = new StatusControl().AttachContainerTo(this).MoveContainerTo( (DefaultWidth - StatusControl.Width) / 2, (DefaultHeight - StatusControl.Height) ); //this.MyStatus.Container.Hide(); // add autoscroll ? this.MyDeck.SizeTo(DefaultWidth, DefaultHeight); this.MyDeck.AttachContainerTo(this); this.MyDeck.GetRank = e => (int)RankMapping[e]; System.Console.WriteLine("--- freecell ---"); System.Console.WriteLine("adding card infos... "); MyDeck.UnusedCards.AddRange(CardInfo.FullDeck()); this.MyStatus.CardsLeft = MyDeck.UnusedCards.Count; this.MyStatus.Score = -1; this.MyStatus.Update(); System.Console.WriteLine("creating stacklists... "); PlayStacks = MyDeck.CreateStackList(); PlayStacks.ForEachNewItem( k => { k.CardMargin = new Vector { Y = 20 }; k.Update(); } ); TempStacks = MyDeck.CreateStackList(); Func<bool> Rule_WinConditionMet = delegate { if (PlayStacks.All(s => s.Cards.Count > 0)) return false; if (TempStacks.All(s => s.Cards.Count == 0)) return false; return true; }; Action MyStatus_UpdateCardsLeft = delegate { MyStatus.CardsLeft = 0; PlayStacks.ForEach(q => MyStatus.CardsLeft += q.Cards.Count); TempStacks.ForEach(q => MyStatus.CardsLeft += q.Cards.Count); }; GoalStacks = MyDeck.CreateStackList(); GoalStacks.ForEachNewItem( k => { k.CardMargin.Y = 0; k.Cards.ForEachNewItem( card => { Console.WriteLine("GoalStacks ForEachNewItem " + new { k.CardMargin.Y }); if (card.Info.Rank == CardInfo.RankEnum.RankKing) { KingSmile.Show(); card.VisibleSide = Card.SideEnum.BackSide; if (Rule_WinConditionMet()) { // winner! MyDeck.Sounds.win(); if (this.GameOver != null) this.GameOver(); } else { 600.AtDelay(KingSmile.Hide); } } MyStatus_UpdateCardsLeft(); MyStatus.Update(); } ); } ); Func<Card, Card, bool> RuleForStackingCardsInGoalStack = (Previous, Current) => { if (Cheat) return true; if (Previous == null) return Current.Info.Rank == CardInfo.RankEnum.RankAce; if (Previous.Info.Suit != Current.Info.Suit) return false; if (Previous.Rank != Current.Rank + 1) return false; return true; }; Func<Card, Card, bool> RuleForStackingCardsInPlayStack = (Previous, Current) => { if (Cheat) return true; if (Previous.Info.SuitColor == Current.Info.SuitColor) return false; if (Previous.Rank + 1 != Current.Rank) return false; return true; }; #region rules MyDeck.ApplyCardRules += delegate(Card card) { #region MovedByLocalPlayer card.MovedByLocalPlayer += delegate { var FrozenTokens = new { card.CurrentStack, card.PreviousStack }; Console.WriteLine(new { HistoryMove = card, StackedCards = card.StackedCards.Length, Previous = card.PreviousStack, Current = card.CurrentStack }.ToString()); History.History.Add( delegate { // we already are at the state we want to be if (card.CurrentStack == FrozenTokens.PreviousStack) return; card.VisibleSide = Card.SideEnum.TopSide; card.AnimatedMoveToStack(FrozenTokens.PreviousStack, null); this.MyDeck.Sounds.deal(); MyStatus.Moves--; MyStatus_UpdateCardsLeft(); MyStatus.Update(); }, delegate { MyStatus.Moves++; MyStatus.Update(); // we already are at the state we want to be if (card.CurrentStack == FrozenTokens.CurrentStack) return; card.AnimatedMoveToStack(FrozenTokens.CurrentStack, null); this.MyDeck.Sounds.deal(); } ); }; #endregion card.VisibleSide = Card.SideEnum.TopSide; card.ValidateDragStart = delegate { if (Cheat) return true; // cannot remove cards from goal stack if (GoalStacks.Contains(card)) return false; // cannot drag a pile of cards unless alternate colors and descending numbers return card.SelectedCards.AllWithPrevious(RuleForStackingCardsInPlayStack); }; card.ValidateDragStop = CandidateStack => { if (Cheat) return true; if (TempStacks.Contains(CandidateStack)) { // temp only holds one card if (CandidateStack.Cards.Count > 0) return false; // and only one card can be inserted if (card.StackedCards.Length > 0) return false; return true; } if (PlayStacks.Contains(CandidateStack)) { if (CandidateStack.Cards.Count == 0) return true; return (RuleForStackingCardsInPlayStack(CandidateStack.Cards.Last(), card)); } if (GoalStacks.Contains(CandidateStack)) { if (CandidateStack.Cards.Count == 0) { return (RuleForStackingCardsInGoalStack(null, card)); } return (RuleForStackingCardsInGoalStack(CandidateStack.Cards.Last(), card)); } return false; }; }; #endregion System.Console.WriteLine("creating goalstack... "); GoalStacks.AddRange( Enumerable.Range(0, 4).ToArray( i => new CardStack { Name = "GoalStack " + i }.MoveTo( DefaultWidth - Margin / 2 - ((CardInfo.Width + Margin / 2) * 4) + i * (CardInfo.Width + Margin / 2), Margin * 2 ) ) ); System.Console.WriteLine("creating tempstack... "); TempStacks.AddRange( Enumerable.Range(0, 4).ToArray( i => new CardStack { Name = "TempStack " + i }.MoveTo( Margin + i * (CardInfo.Width + Margin / 2), Margin * 2 ) ) ); System.Console.WriteLine("creating playstack... "); PlayStacks.AddRange( Enumerable.Range(0, 8).ToArray( i => new CardStack { Name = "PlayStack " + i }.MoveTo( Margin + (i) * (CardInfo.Width + Margin), Margin * 4 + CardInfo.Height ).Apply( s => { var Count = 6; if (i < 4) Count = 7; s.Cards.AddRange(MyDeck.FetchCards(Count)); } ) ) ); }