public void TestCollectionSync()
        {
            string item0 = "Item0";
            string item1 = "Item1";
            string item2 = "Item2";
            string item3 = "Item3";

            ObservableCollection<string> collection = new ObservableCollection<string>();

            HelperLabeledViewModelCollection viewModel = new HelperLabeledViewModelCollection(null, collection, o => o);

            collection.Add(item0);
            collection.Add(item1);
            collection.Add(item3);
            Assert.IsTrue(CompareCollectionValues(collection, viewModel), "Add did not work.");

            collection.Insert(2, item2);
            Assert.IsTrue(CompareCollectionValues(collection, viewModel), "Insert did not work.");

            collection.Remove(item3);
            Assert.IsTrue(CompareCollectionValues(collection, viewModel), "Remove did not work.");

            collection.Move(0, 1);
            Assert.IsTrue(CompareCollectionValues(collection, viewModel), "Move did not work.");

            collection.Clear();
            Assert.IsTrue(CompareCollectionValues(collection, viewModel), "Clear did not work.");
        }
        public ColorGeneratorViewModel()
        {
            m_colors = new ObservableCollection<RybColor>();

            m_generateColorsCommand = new RelayCommand(parameter =>
                {
                    string text = CountText;
                    if (text == null)
                        return;

                    int count;
                    if (int.TryParse(text, out count))
                    {
                        var colorsGenerator = new ColorGenerator(count);
                        m_colors.Clear();

                        for (int i = 0; i < count; i++)
                        {
                            var color = colorsGenerator.PickNextColor();
                            m_colors.Add(color);
                        }
                    }
                });

            CountText = "15";
        }
        public static void ClearTest()
        {
            string[] anArray = { "one", "two", "three", "four" };
            ObservableCollection<string> col = new ObservableCollection<string>(anArray);

            col.Clear();
            Assert.Equal(0, col.Count);
            Assert.Empty(col);

            Assert.Throws<ArgumentOutOfRangeException>(() => col[1]);

            //tests that the collectionChanged events are fired.
            CollectionAndPropertyChangedTester helper = new CollectionAndPropertyChangedTester();
            col = new ObservableCollection<string>(anArray);
            helper.ClearTest(col);
        }
        public static void ClearTest()
        {
            string[] anArray = { "one", "two", "three", "four" };
            ObservableCollection<string> col = new ObservableCollection<string>(anArray);

            col.Clear();
            Assert.Equal(0, col.Count);
            foreach (var item in col)
            {
                Assert.True(false, "Should not be able to iterate through an empty collection.");
            }

            Assert.Throws<ArgumentOutOfRangeException>(() => col[1]);
            
            //tests that the collectionChanged events are fired.
            CollectionAndPropertyChangedTester helper = new CollectionAndPropertyChangedTester();
            col = new ObservableCollection<string>(anArray);
            helper.ClearTest(col);
        }
Пример #5
0
        private void ConfigureAndTriggerSchedule(DAL.Schedule currentSchedule)
        {
            Boolean CoreWorkingOK = true;

            si.sie("ConfigureAndTriggerSchedule");
            string allTickerText = "";
            KillTicker();

            Boolean tickerFound = false;
            TickerMetaToUse = "";
            contentCollection.Clear();

            try
            {
                //"text 0 690 1024 80 clWhite Arial 48 5"
                gridFive.Visibility = Visibility.Collapsed;
                gridFour.Visibility = Visibility.Collapsed;
                gridThree.Visibility = Visibility.Collapsed;
                gridTwo.Visibility = Visibility.Collapsed;

                #region CollectContentCollection
                try
                {
                    foreach (DAL.Content item in proxy.CollectMedia())
                    {
                        contentCollection.Add(item);
                    }
                }
                catch (Exception ex)
                {
                    CoreWorkingOK = false;
                    contentCollection.Clear();
                }

                si.sii("Content Collection Count = " + contentCollection.Count().ToString());


                //if there is an error the collection is cleared and loaded from xml, if it worked the collection is saved for future use
                if (contentCollection.Count > 0)
                {
                    SerializeContentCollection(@"c:\tmp\content.xml");
                }
                else
                {
                    contentCollection.Clear();
                    if (FTPONLY)
                    {
                        contentCollection = DeSerializeContentCollection(@"c:\tmp\xml\content.xml");
                    } 
                    else
                    {
                        contentCollection = DeSerializeContentCollection(@"c:\tmp\content.xml");
                    }
                };
                #endregion


                si.sii("Collecting Media in Content Collection");
                CollectMediaInContentCollection(); //Collect All Media
                si.sii("Collect this loop:"+currentSchedule.Loopname);

                #region CollectCurrentLoop
                try
                {
                    if (CoreWorkingOK)
                    {
                        currentLoop = proxy.CollectThisLoop(currentSchedule.Loopname); //Collect Loop
                        SerializeCurrentLoop(@"c:\tmp\loop.xml");
                    }
                    else
                    {
                        currentLoop = null;
                    }
                }
                catch (Exception)
                {
                    currentLoop = null;
                }

                if (currentLoop == null) si.sii("Current Loop is NULL possibly because Core isn't working - Collect from XML");
                si.sii("FTP Only Variable = "+FTPONLY.ToString());

                if (currentLoop == null)
                {
                    if (FTPONLY)
                    {
                        si.sii(@"INSIDE FTP ONLY - Deserializing c:\tmp\xml\loops.xml");
                        ObservableCollection<Loop> lc = new ObservableCollection<Loop>();
                        //DAL.LoopCollection lc = new LoopCollection();
                        try
                        {
                            lc = DeSerializeLoopCollection(@"c:\tmp\xml\loops.xml");
                            si.sii(@"Items in Loops.xml:"+lc.Count.ToString());
                        }
                        catch (Exception e3)
                        {
                            si.six(e3);
                        }
                        
                        foreach (var l in lc)
                        {
                            si.sii("Stepping through loops.xml:"+l.Name+"/"+l.Templatename+"/"+l.Templateid.ToString());
                           if (l.Name == currentSchedule.Loopname)
                           {
                               currentLoop = l;
                               si.sii("Current Loop = "+currentLoop.Name);
                               break;
                           }
                        }
                    } else
                    {
                        currentLoop = DeSerializeCurrentLoop(@"c:\tmp\loop.xml");    
                    }
                }
                #endregion

                try
                {
                    LastLoopTick = proxy.CollectDelta("loop");
                    LastTickerTick = proxy.CollectDelta("ticker");
                }
                catch (Exception)
                {
                }

                #region CollectTemplateCollection
                si.sii("Collect this template:" + currentLoop.Templatename);
                try
                {
                    templateCollection = proxy.CollectZonesForThisTemplateName(currentLoop.Templatename); //CollectTemplate
                }
                catch (Exception)
                {
                    templateCollection.Clear();
                }

                if (templateCollection.Count > 0)
                {
                    SerializeTemplateCollection(@"c:\tmp\template.xml");
                }
                else
                {
                    if (FTPONLY)
                    {
                        try
                        {
                            templateCollection.Clear();
                            //TemplateCollection tmpCollection = new TemplateCollection();
                            ObservableCollection<Template> tmpCollection = new ObservableCollection<DAL.Template>();
                            tmpCollection = DeSerializeTemplateCollection(@"c:\tmp\xml\template.xml");
                            foreach (var t in tmpCollection)
                            {
                                if (t.Name == currentLoop.Templatename && t.Zonename != "_template")
                                {
                                    templateCollection.Add(t);
                                    si.sii("Template Zone Added = " + t.Name + "/" + t.Zonename + "/" + t.Zonedescription);
                                }
                            }
                            si.sii("Zones in Template = "+templateCollection.Count.ToString());
                        }
                        catch (Exception x1)
                        {
                            si.six(x1);
                        }
                    } else
                    {
                        templateCollection = DeSerializeTemplateCollection(@"c:\tmp\template.xml");
                        foreach (var t in templateCollection)
                        {
                            si.sii("Template Zone Added = " + t.Name + "/" + t.Zonename + "/" + t.Zonedescription);
                        }
                        si.sii("Zones in Template = " + templateCollection.Count.ToString());
                    }
                }
                #endregion

                //Populate Zones
                contentQ.Clear();
                contentQ2.Clear();
                contentQ3.Clear();
                contentQ4.Clear();
                contentQ5.Clear();
                int count = 1;
                int tickerInCount = 0; //equals count where ticker is found, 0 by default means no ticker
                int backGroundCount = 0; // //equals count where ticker is found, 0 by default means background is empty (we hide this grid)
                string TickerBackgroundColour = "";
                double TickerOpacity = 0;
                allTickerText = "";

                si.sii("===============================");
                si.sii("===============================");

                foreach (var item in templateCollection)
                {
                    try
                    {
                        if (CoreWorkingOK)
                        {
                            loopContentCollection = proxy.CollectLoopContentForZoneByName(item.Zonename, currentLoop.Name);
                            SerializeLoopContentCollection(@"c:\tmp\zone\" + item.Zonename + ".xml", loopContentCollection);
                        }
                        else
                            if (FTPONLY && File.Exists(@"c:\tmp\xml\allloopcontent.xml"))
                            {
                                //LoopContentCollection tmpLCC = new LoopContentCollection();
                                ObservableCollection<LoopContent> tmpLCC = new ObservableCollection<LoopContent>();
                                si.sii("Collecting from tmpxml alllloopcontent.xml");
                                tmpLCC = DeSerializeLoopContentCollection(@"c:\tmp\xml\allloopcontent.xml");
                                si.sii("LoopContent Items collected from xml = " + tmpLCC.Count.ToString());
                                loopContentCollection.Clear();
                                foreach (LoopContent c in tmpLCC)
                                {
                                    si.sii("STEPPING THROUGH Loop Content tmpLCC:" + c.Medianame);
                                    if (c.Zonename == item.Zonename && c.Loopname == currentLoop.Name)
                                    {
                                        si.sii("ADDING TO LOOP Content Collection Content tmpLCC:" + c.Medianame);
                                        loopContentCollection.Add(c);
                                    }
                                }
                            }
                            else
                            {
                                loopContentCollection = DeSerializeLoopContentCollection(@"c:\tmp\zone\" + item.Zonename + ".xml");
                            }
                    }
                    catch (Exception ei)
                    {
                        si.six(ei);
                    }

                    if (item.ZoneType.ToLower() == "Location and Weather strip".ToLower())
                    {
                        tbLocation.Text = Properties.Settings.Default.ClientID.ToUpper();
                        borderWeatherStrip.Visibility = Visibility.Visible;
                        UpdateWeather();
                    }

                    if (item.ZoneType.ToLower() == "Weather Box".ToLower())
                    {
                        tbLocation.Text = Properties.Settings.Default.ClientID.ToUpper();
                        borderWeatherRight.Visibility = Visibility.Visible;
                        UpdateWeather();
                    }

                    si.sii(item.Zonename + "/" + item.X + "/" + item.Width);
                    foreach (var lc in loopContentCollection)
                    {
                        #region First Configure the Ticker
                        try
                        {
                            foreach (var cc in contentCollection)
                            {
                                if (cc.Contenttype == "Ticker" && lc.Mediaid == cc.Id)
                                {
                                    //Return All TickerMeta
                                    allTickerText += cc.Metadata8 + "    ";
                                    TickerMeta = "text";
                                    TickerMeta += " " + item.X.ToString(); //"text 0 690 1024 80 clWhite Arial 48 5"
                                    TickerMeta += " " + item.Y.ToString();
                                    TickerMeta += " " + item.Width.ToString();
                                    TickerMeta += " " + item.Height.ToString();
                                    Color tickerC = new Color();
                                    ColorConverter ccv = new ColorConverter();
                                    string tickerColour = cc.Metadata4;
                                    TickerMeta += " $00" + tickerColour.Substring(7, 2) + tickerColour.Substring(5, 2) + tickerColour.Substring(3, 2);//0000FF";// Color.FromRgb(0xFF, 0xFF, 0xFF).ToString(); //Color

                                    TickerBackgroundColour = cc.Metadata6;
                                    TickerOpacity = Convert.ToDouble(cc.Metadata7);
                                    UserControlContent.TickerBackgroundOpacity = TickerOpacity;
                                    
                                    TickerMeta += " " + cc.Metadata2; //Font
                                    TickerMeta += " " + cc.Metadata3; //Size
                                    //TickerMeta += " " + cc.Metadata5; //Speed
                                    TickerMeta += " 12";
                                    if (lc.Order == 1)
                                    {
                                        tickerFound = true;
                                        UserControlContent.TickerBackgroundColour = TickerBackgroundColour;
                                        TickerMetaToUse = TickerMeta;
                                        tickerInCount = count;
                                        si.sii("TICKER METADATA = " + TickerMeta);
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {    
                        }
                        #endregion

                        //Do the rest
                        si.sii("Looping through ContentCollection...Medianame="+lc.Medianame+" / LoopName="+lc.Loopname);
                        foreach (var cc in contentCollection)
                        {
                            if (cc.Contenttype != "Ticker" && lc.Mediaid == cc.Id)
                                {
                                    //selectedn = @"c:\content\_media\" + System.IO.Path.GetFileName(selectedn);
                                    if (cc.Contenttype == "Background") backGroundCount = count;
                                    if (count == 1)
                                    {
                                        contentQ2.Add(cc);
                                        si.sii("ADDING CONTENT TO Q2:"+cc.Filelocation);
                                    }
                                    if (count == 2)
                                    {
                                        contentQ3.Add(cc);
                                        si.sii("ADDING CONTENT TO Q3:" + cc.Filelocation);
                                    }
                                    if (count == 3)
                                    {
                                        contentQ4.Add(cc);
                                    }
                                    if (count == 4) contentQ5.Add(cc);
                                    si.sii(@"c:\content\_media\" + System.IO.Path.GetFileName(cc.Filelocation));
                                }
                        }
                    }

                    try
                    {
                        WriteTickerFile(allTickerText);
                    }
                    catch (Exception)
                    {
                    }

                    uccTwo = new UserControlContent();
                    uccThree = new UserControlContent();
                    uccFour = new UserControlContent();
                    uccFive = new UserControlContent();

                    Grid currentGrid = null;

                    #region PopulateGridWithContent
                    if (count == 1)
                    {
                        if (tickerInCount == 1)
                        {
                            uccTwo.IsTickerBackground = true;
                        }
                        gridTwo.Children.Clear();
                        gridTwo.Children.Add(uccTwo);
                        currentGrid = gridTwo;
                        if (contentQ.Count == 0) currentGrid = gridHiddenGrid;
                        uccTwo.SetContentQ(contentQ2);
                        KeepAliveTicker++;
                        si.sii("Firing Grid 2");
                    }
                    else
                        if (count == 2)
                        {
                            if (tickerInCount == 2)
                            {
                                uccThree.IsTickerBackground = true;
                            }
                            gridThree.Children.Clear();
                            gridThree.Children.Add(uccThree);
                            currentGrid = gridThree;
                            uccThree.SetContentQ(contentQ3);
                            KeepAliveTicker++;
                            si.sii("Firing Grid 3");
                        }
                        else
                            if (count == 3)
                            {
                                if (tickerInCount == 3)
                                {
                                    uccFour.IsTickerBackground = true;
                                }
                                gridFour.Children.Clear();
                                gridFour.Children.Add(uccFour);
                                currentGrid = gridFour;
                                uccFour.SetContentQ(contentQ4);
                                KeepAliveTicker++;
                                si.sii("Firing Grid 4");
                            }
                            else
                                if (count == 4)
                                {
                                    if (tickerInCount == 4)
                                    {
                                        uccFive.IsTickerBackground = true;
                                    }
                                    gridFive.Children.Clear();
                                    gridFive.Children.Add(uccFive);
                                    currentGrid = gridFive;
                                    uccFive.SetContentQ(contentQ5);
                                    KeepAliveTicker++;
                                    si.sii("Firing Grid 5");
                                };
                    #endregion
                    //gridTwo.Children.Add(ucc);
                    //ucc.SetContentQ(contentQ);

                    double x = Convert.ToDouble(item.X); //sim("targetx=" + target.x);
                    double y = Convert.ToDouble(item.Y); //sim("targety=" + target.y);
                    double width = Convert.ToDouble(item.Width);
                    double height = Convert.ToDouble(item.Height);

                    currentGrid.Width = width;
                    currentGrid.Height = height;
                    currentGrid.Opacity = Convert.ToDouble(item.Opacity);
                    Canvas.SetTop(currentGrid, y);
                    Canvas.SetLeft(currentGrid, x);

                    //Canvas.SetZIndex(currentGrid, Convert.ToInt16(target.layer));
                    //sim(gridIndex + "|" + currentGrid + "x=" + x + " y=" + y);

                    currentGrid.Visibility = Visibility.Visible;

                    count++;

                    if (backGroundCount == 1) gridTwo.Visibility = Visibility.Collapsed;
                    if (backGroundCount == 2) gridThree.Visibility = Visibility.Collapsed;
                    if (backGroundCount == 3) gridFour.Visibility = Visibility.Collapsed;
                    if (backGroundCount == 4) gridFive.Visibility = Visibility.Collapsed;
                }
            }
            catch
            {
            }
            try
            {
                tickerTimer.Start();
            }
            catch (Exception ex)
            {
                
            }
            
            si.sil("ConfigureAndTriggerSchedule");
            //this.Topmost = true;
            //this.Activate();
            //this.Focus();
        }
Пример #6
0
        private void CollectUpdatedScheduleForThisDisplay()
        {
            si.sie("UpdateScheduleForThisDisplay");
            SimulateMouseClick();

            if (FTPONLY)
            {
                CollectXMLFileForFTPOnly();
            }

            try
            {
                //DAL.ScheduleCollection sch = new DAL.ScheduleCollection();
                ObservableCollection<Schedule> sch = new ObservableCollection<Schedule>();
                try
                {
                    sch = proxy.CollectScheduleForScreen();
                    SerializeScheduleCollection(@"c:\tmp\schedule.xml", sch);
                }
                catch (Exception)
                {
                    try
                    {
                        if (FTPONLY)
                        {
                            sch = DeSerializeScheduleCollection(@"c:\tmp\xml\schedule.xml");
                        } else
                        {
                            sch = DeSerializeScheduleCollection(@"c:\tmp\schedule.xml");    
                        }
                    }
                    catch (Exception)
                    {
                        sch.Clear();
                    }
                }
                
                si.sii("Current ClientID="+Properties.Settings.Default.ClientID);
                scheduleCollection.Clear();
                foreach (DAL.Schedule item in sch)
                {
                    if (Properties.Settings.Default.ClientID == item.Screenname || _GROUPID == item.Groupname)
                    {
                        scheduleCollection.Add(item);
                        si.sii(item.Loopname + ":" + item.Loopstart.ToString()+"/"+item.Screenname+"/"+item.Groupname);
                    }
                }

                try
                {
                    LastScheduleTick = proxy.CollectDelta("schedule");
                }
                catch (Exception)
                {
                }
                
            }
            catch (Exception ex)
            {
            }
            si.sil("UpdateScheduleForThisDisplay - "+scheduleCollection.Count().ToString()+" items in schedule");
        }
        /// <summary>
        /// Clears the given Collection.
        /// </summary>
        public void ClearTest(ReadOnlyObservableCollection<string> readOnlyCol, ObservableCollection<string> collection)
        {
            INotifyPropertyChanged readOnlyPropertyChanged = readOnlyCol;
            readOnlyPropertyChanged.PropertyChanged += Collection_PropertyChanged;
            _expectedPropertyChanged = new[]
            {
                new PropertyNameExpected(COUNT),
                new PropertyNameExpected(ITEMARRAY)
            };

            INotifyCollectionChanged readOnlyCollectionChange = readOnlyCol;
            readOnlyCollectionChange.CollectionChanged += Collection_CollectionChanged;
            _expectedCollectionChangedFired++;
            _expectedAction = NotifyCollectionChangedAction.Reset;
            _expectedNewItems = null;
            _expectedNewStartingIndex = -1;
            _expectedOldItems = null;
            _expectedOldStartingIndex = -1;

            collection.Clear();
            Assert.Equal(0, readOnlyCol.Count);
            Assert.Equal(_expectedCollectionChangedFired, _numCollectionChangedFired);

            foreach (var item in _expectedPropertyChanged)
                Assert.True(item.IsFound, "The propertychanged event should have fired for" + item.Name + ", since we just cleared the collection.");

            readOnlyCollectionChange.CollectionChanged -= Collection_CollectionChanged;
            readOnlyPropertyChanged.PropertyChanged -= Collection_PropertyChanged;
        }
Пример #8
0
        /// <summary>
        /// Starts the Drag if the Item under the curser is a valid Drag Item
        /// </summary>
        /// <param name="sender">not used</param>
        /// <param name="e">MousePos</param>
        void ListViewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            int index = GetCurrentIndex(e.GetPosition);

            // check to see if drag can be done
            FrameworkElement ele = e.OriginalSource as FrameworkElement;
            if (ele != null && ele.DataContext != null)
            {
                if (ele.DataContext.GetType() != typeof(Mp3Song) && ele.DataContext.GetType() != typeof(Song))
                    return;
            }

            const DragDropEffects allowedEffects = DragDropEffects.Move;

            if (e.LeftButton != MouseButtonState.Pressed || e.ClickCount != 1)
                return;

            var draggSongs = new ObservableCollection<ISong>();

            foreach (ISong song in listView.SelectedItems)
                draggSongs.Add(song);

            ISong actDragSong = listView.Items[index] as ISong;

            if (listView.SelectedItems.Count < 2)
            {
                if (!draggSongs.Contains(actDragSong))
                    draggSongs.Clear();

                draggSongs.Add(actDragSong);
            }
            else
            {
                if (!draggSongs.Contains(actDragSong))
                    return;
            }

            try
            {
                DragDrop.DoDragDrop(listView, draggSongs, allowedEffects);
            }
            catch (ArgumentNullException)
            {}
            catch (NullReferenceException)
            {}

            ColorCurrentPlayedSong();
        }
 public static void FillDTUInfoOC(ObservableCollection<DTUInfo> dtuInfoOc, string content, bool clear = true)
 {
     if (clear == true)
         dtuInfoOc.Clear();
     if (string.IsNullOrWhiteSpace(content))
         return;
     content = content.Trim(new char[] { '\0' });
     string[] sa = content.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);
     if (sa == null || sa.Length < 1)
         return;
     foreach (string sai in sa)
     {
         string[] saia = sai.Split(new string[] { "\t" }, StringSplitOptions.None);
         if (saia == null || (saia.Length != Consts.DTU_INFO_ITEM_COUNT))
             continue;
         bool online = false;
         if (string.Compare(saia[4].Trim(), "y", true) == 0)
             online = true;
         DTUInfo dtui = new DTUInfo()
         {
             DtuId = saia[0].Trim(),
             SimId = saia[1].Trim(),
             UserName = saia[2].Trim(),
             UserTel = saia[3].Trim(),
             Online = online,
             DtLogString = saia[5].Trim(),
             Controller = (string.IsNullOrWhiteSpace(saia[6].Trim()) ?
             null :
             new UserInfo()
             {
                 UserName = saia[6].Trim()
             })
         };
         if (FindDTUInfo(saia[0].Trim(), dtuInfoOc) == null)
             dtuInfoOc.Add(dtui);
     }
 }
Пример #10
0
        private void UpdateProducts(ObservableCollection<Product> productList, IEnumerable<Product> productResults, bool completed)
        {
            if (productResults != null) {
                if (_clear) {
                    productList.Clear();
                    _clear = false;
                }

                foreach (Product p in productResults) {
                    productList.Add(p);
                }
            }

            Products = productList;

            if (ProductsLoaded != null) {
                ProductsLoaded(this, EventArgs.Empty);
            }

            if (completed) {
                _loading = false;
                RaisePropertyChanged("PriceRange", "IsLoading");
            }
        }
 /// <summary>
 /// Copies the <paramref name="from"/> collection to the <paramref name="to"/> collection
 /// </summary>
 /// <param name="from">The group descriptions to copy from</param>
 /// <param name="to">The group descriptions to copy to</param>
 private static void CopyGroupDescriptions(ObservableCollection<GroupDescription> from, ObservableCollection<GroupDescription> to)
 {
     to.Clear();
     foreach (GroupDescription gd in from)
     {
         to.Add(gd);
     }
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="AutoCompleteView"/> class.
        /// </summary>
        public AutoCompleteView()
        {
            _availableSuggestions = new ObservableCollection<object>();
            _stkBase = new StackLayout();
            var innerLayout = new StackLayout();
            _entText = new Entry
            {
                HorizontalOptions = TextHorizontalOptions,
                VerticalOptions = TextVerticalOptions,
                TextColor = TextColor,
                BackgroundColor = TextBackgroundColor
            };
            _btnSearch = new Button
            {
                VerticalOptions = SearchVerticalOptions,
                HorizontalOptions = SearchHorizontalOptions,
                Text = SearchText
            };

            _lstSuggestions = new ListView
            {
                HeightRequest = SuggestionsHeightRequest,
                HasUnevenRows = true
            };

            innerLayout.Children.Add(_entText);
            innerLayout.Children.Add(_btnSearch);
            _stkBase.Children.Add(innerLayout);
            _stkBase.Children.Add(_lstSuggestions);

            Content = _stkBase;


            _entText.TextChanged += (s, e) =>
            {
                Text = e.NewTextValue;
                OnTextChanged(e);
            };
            _btnSearch.Clicked += (s, e) =>
            {
                if (SearchCommand != null && SearchCommand.CanExecute(Text))
                {
                    SearchCommand.Execute(Text);
                }
            };
            _lstSuggestions.ItemSelected += (s, e) =>
            {
                _entText.Text = e.SelectedItem.ToString();

                _availableSuggestions.Clear();
                ShowHideListbox(false);
                OnSelectedItemChanged(e.SelectedItem);

                if (ExecuteOnSuggestionClick
                   && SearchCommand != null
                   && SearchCommand.CanExecute(Text))
                {
                    SearchCommand.Execute(e);
                }
            };
            ShowHideListbox(false);
            _lstSuggestions.ItemsSource = _availableSuggestions;
        }
 public void Test_ObservableCollection_Clear()
 {
     var list = new ObservableCollection<int>() { 6, 5, 8 };
     Assert.Equal(3, list.Count);
     list.CollectionChanged += (o, e) =>
     {
         Assert.Same(list, o);
         Assert.Equal(NotifyCollectionChangedAction.Reset, e.Action);
         Assert.Null(e.NewItems);
         Assert.NotNull(e.OldItems);
         Assert.Equal(3, e.OldItems.Count);
         Assert.Equal(6, e.OldItems[0]);
         Assert.Equal(5, e.OldItems[1]);
         Assert.Equal(8, e.OldItems[2]);
     };
     list.Clear();
 }
Пример #14
0
        public ExplorerViewModel(IMainModel mainModel, IGoogleDriveService googleDriveService, INavigationService navigationService, IMessageBoxService messageBoxService, ISystemTrayService systemTrayService, IPhotoChooserService photoChooserService)
        {
            _mainModel = mainModel;
            _googleDriveService = googleDriveService;
            _navigationService = navigationService;
            _messageBoxService = messageBoxService;
            _systemTrayService = systemTrayService;
            _photoChooserService = photoChooserService;

            Files = new ObservableCollection<GoogleFileViewModel>();
            PictureFiles = new ObservableCollection<GoogleFileViewModel>();

            OpenFileCommand = new RelayCommand<GoogleFileViewModel>(file =>
            {
                if (IsSelectionEnabled)
                {
                    return;
                }

                OpenFile(file);
            });

            ChangeStaredStatusCommand = new RelayCommand<GoogleFileViewModel>(file =>
            {
                if (IsSelectionEnabled)
                {
                    return;
                }

                ChangeStaredStatus(file);
            });

            AddFileCommand = new RelayCommand(UploadFile);

            EnableSelectionCommand = new RelayCommand(() =>
            {
                if (IsBusy)
                {
                    return;
                }

                IsSelectionEnabled = true;
            });

            RefreshFilesCommand = new RelayCommand(RefreshFiles);

            DeleteFilesCommand = new RelayCommand<IList>(files =>
            {
                _messageBoxService.Show("You are about to delete the selected files. Do you wish to proceed?", "Delete files?", new[] { "delete", "cancel" }, button =>
                {
                    if (button != 0)
                        return;

                    var filesArray = files
                        .Cast<GoogleFileViewModel>()
                        .ToArray();

                    IsSelectionEnabled = false;

                    DeleteFiles(filesArray);
                });
            });

            CreateNewFolderCommand = new RelayCommand(CreateNewFolder);

            RenameFileCommand = new RelayCommand<GoogleFileViewModel>(RenameFile);

            DeleteFileCommand = new RelayCommand<GoogleFileViewModel>(file =>
            {
                _messageBoxService.Show(string.Format("You are about to delete '{0}'. Do you wish to proceed?", file.Title), "Delete file?", new[] { "delete", "cancel" }, button =>
                {
                    if (button != 0)
                        return;

                    DeleteFile(file);
                });
            });

            ShowAboutCommand = new RelayCommand(() =>
            {
                _navigationService.NavigateTo("/View/AboutPage.xaml");
            });

            PageLoadedCommand = new RelayCommand(ExecuteInitialLoad);

            BackKeyPressCommand = new RelayCommand<CancelEventArgs>(e =>
            {
                GoogleDriveFile item;

                if (PivotSelectedIndex == 1)
                {
                    PivotSelectedIndex = 0;

                    e.Cancel = true;
                }
                else if (IsSelectionEnabled)
                {
                    IsSelectionEnabled = false;

                    e.Cancel = true;
                }
                else if (_mainModel.TryPop(out item))
                {
                    AbortCurrentCall();

                    RaisePropertyChanged(() => CurrentPath);

                    RefreshFiles();

                    e.Cancel = true;
                }
                else
                {
                    AbortCurrentCall(true);

                    Files.Clear();
                    PictureFiles.Clear();
                }
            });

            MessengerInstance.Register<RefreshFilesMessage>(this, message =>
            {
                DispatcherHelper.RunAsync(RefreshFiles);
            });
        }
Пример #15
0
 public void ChangingContentsOfObservableCollectionUpdatesTreeMap()
 {
     TreeMap treeMap = new TreeMap();
     ObservableCollection<int> itemsSource = new ObservableCollection<int>();
     treeMap.ItemsSource = itemsSource;
     TestAsync(
         treeMap,
         // +1 because of the Border in default template
         () => Assert.AreEqual(0 + 1, treeMap.GetVisualDescendents().OfType<Border>().Count()),
         () => itemsSource.Add(1),
         () => Assert.AreEqual(1 + 1, treeMap.GetVisualDescendents().OfType<Border>().Count()),
         () => itemsSource.Add(1),
         () => Assert.AreEqual(2 + 1, treeMap.GetVisualDescendents().OfType<Border>().Count()),
         () => itemsSource.Clear(),
         () => Assert.AreEqual(0 + 1, treeMap.GetVisualDescendents().OfType<Border>().Count()));
 }
Пример #16
0
        private void SetFilter()
        {
            if (filterType != null)
            {
                string[] valueOfType = filterType.Split(' ');
                filterItems = new ObservableCollection<String>();
                if (valueOfType[1].Equals("Gymnast"))
                {
                    filterItems.Clear();
                    dateVisibility = Visibility.Hidden;
                    foreach (gymnast gymnast in gymnastList)
                    {
                        String tempFullname = gymnast.name + (!String.IsNullOrWhiteSpace(gymnast.surname_prefix) ? " " + gymnast.surname_prefix + " " : " ") + gymnast.surname;
                        if (tempFullname.ToLower().Contains(FilterText.ToLower()))
                        {
                            filterItems.Add(tempFullname);
                        }
                    }

                }
                if (valueOfType[1].Equals("Location"))
                {
                    filterItems.Clear();
                    dateVisibility = Visibility.Hidden;
                    foreach (location location in locationList)
                    {
                        String tempLocationName = location.name;
                        if (tempLocationName.ToLower().Contains(FilterText.ToLower()))
                        {
                            filterItems.Add(tempLocationName);
                        }
                    }
                }
                if(valueOfType[1].Equals("Vault"))
                {
                    filterItems.Clear();
                    dateVisibility = Visibility.Hidden;
                    foreach(vaultnumber number in vaultNumberList)
                    {
                        String tempVaultnumber = number.code;
                        if(tempVaultnumber.ToLower().Contains(FilterText.ToLower()))
                        {
                            filterItems.Add(tempVaultnumber);
                        }
                    }
                }
                if(valueOfType[1].Equals("Date"))
                {
                    filterItems.Clear();
                    dateVisibility = Visibility.Visible;
                    OnPropertyChanged("DateVisibility");
                }
            }
            OnPropertyChanged("DateVisibility");
            OnPropertyChanged("FilterItems");
        }
Пример #17
0
 public void ChangingContentsOfNestedObservableCollectionUpdatesTreeMap()
 {
     TreeMap treeMap = new TreeMap();
     TreeMapItemDefinition itemDefinition = new TreeMapItemDefinition
     {
         ValueBinding = new Binding(),
         ItemsSource = new Binding("Value"),
     };
     itemDefinition.ItemTemplate = (DataTemplate)XamlReader.Load(SimpleItemTemplate);
     treeMap.ItemDefinition = itemDefinition;
     ObservableCollection<int> nestedItemsSourceA = new ObservableCollection<int>();
     ObservableCollection<int> nestedItemsSourceB = new ObservableCollection<int>();
     treeMap.ItemsSource = new KeyValuePair<int, ObservableCollection<int>>[]
     {
         new KeyValuePair<int, ObservableCollection<int>>(0, nestedItemsSourceA),
         new KeyValuePair<int, ObservableCollection<int>>(0, nestedItemsSourceB),
     };
     TestAsync(
         treeMap,
         // +1 because of the Border in default template
         () => Assert.AreEqual(0 + 2 + 1, treeMap.GetVisualDescendents().OfType<Border>().Count()),
         () => nestedItemsSourceA.Add(1),
         () => Assert.AreEqual(1 + 2 + 1, treeMap.GetVisualDescendents().OfType<Border>().Count()),
         () => nestedItemsSourceB.Add(2),
         () => Assert.AreEqual(2 + 2 + 1, treeMap.GetVisualDescendents().OfType<Border>().Count()),
         () => nestedItemsSourceA.Add(3),
         () => Assert.AreEqual(3 + 2 + 1, treeMap.GetVisualDescendents().OfType<Border>().Count()),
         () => nestedItemsSourceB.Clear(),
         () => Assert.AreEqual(2 + 2 + 1, treeMap.GetVisualDescendents().OfType<Border>().Count()),
         () => nestedItemsSourceA.Clear(),
         () => Assert.AreEqual(0 + 2 + 1, treeMap.GetVisualDescendents().OfType<Border>().Count()));
 }
Пример #18
0
        /// <summary>
        /// Checks the object validation for fields warnings or errors.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <param name="propertyChanged">The property changed.</param>
        /// <param name="infoList">The info list containing the warning or error info.</param>
        /// <param name="validationType">Type of the validation.</param>
        private static void CheckObjectValidationForFields(object value, string propertyChanged, ObservableCollection<FieldWarningOrErrorInfo> infoList,
            ValidationType validationType)
        {
            if (string.IsNullOrEmpty(propertyChanged))
            {
                infoList.Clear();
            }
            else
            {
                for (int i = 0; i < infoList.Count; i++)
                {
                    if (string.Compare(infoList[i].Field, propertyChanged) == 0)
                    {
                        infoList.RemoveAt(i);
                    }
                }
            }

            Dictionary<string, string> fieldWarningsOrErrors = CheckFieldWarningsOrErrors(value, propertyChanged, validationType);
            foreach (var fieldWarningOrError in fieldWarningsOrErrors)
            {
                var fieldWarningOrErrorInfo = new FieldWarningOrErrorInfo(fieldWarningOrError.Key, fieldWarningOrError.Value);
                if (!infoList.Contains(fieldWarningOrErrorInfo))
                {
                    infoList.Add(new FieldWarningOrErrorInfo(fieldWarningOrError.Key, fieldWarningOrError.Value));
                }
            }
        }
        /// <summary>
        /// Builds collection of item properties
        /// </summary>
        private void _BuildCollectionSource(ObservableCollection<DataGridItemPropertyBase> itemProperties)
        {
            itemProperties.Clear();
            foreach (DataGridItemProperty property in _itemPorpertiesCollection)
            {
                if (property.Name.Equals("Capacities") ||
                    property.Name.Equals("AddressFields") ||
                    property.Name.Equals("CustomOrderProperties"))
                {
                    Collection<DataGridItemProperty> dynamicProperties = null;
                    if (property.Name.Equals("Capacities"))
                        dynamicProperties = _GetDynamicCapacitiesProperties(property.ValuePath, property.IsReadOnly);
                    else if (property.Name.Equals("AddressFields"))
                        dynamicProperties = _GetDynamicAddressProperties(property.ValuePath, property.IsReadOnly);
                    else
                    {
                        Debug.Assert(property.Name.Equals("CustomOrderProperties"));
                        dynamicProperties = _GetDynamicCustomOrderProperties(property.ValuePath, property.IsReadOnly);
                    }

                    Debug.Assert(null != dynamicProperties);
                    foreach (DataGridItemProperty dynamicProperty in dynamicProperties)
                        itemProperties.Add(dynamicProperty);
                }
                else
                    itemProperties.Add(property);
            }
        }
        public async void GetData()
        {
            SessionList = new ObservableCollection<SessionItemModel>();
            SpeakerList = new ObservableCollection<SpeakerItemModel>();
            DateTime sessionLastDownload = DateTime.MinValue;


            // Get the data from Isolated storage if it is there
            if (IsolatedStorageSettings.ApplicationSettings.Contains("SessionData"))
            {
                var converted = (IsolatedStorageSettings.ApplicationSettings["SessionData"] as IEnumerable<SessionItemModel>);

                SessionList.Clear();
                converted.ToList().ForEach(p => SessionList.Add(p));
                var loadedEventArgs = new LoadEventArgs { IsLoaded = true, Message = string.Empty };
                OnDataLoaded(loadedEventArgs);
            }
            if (IsolatedStorageSettings.ApplicationSettings.Contains("SpeakerData"))
            {
                var converted = (IsolatedStorageSettings.ApplicationSettings["SpeakerData"] as IEnumerable<SpeakerItemModel>);

                SpeakerList.Clear();
                converted.OrderBy(p => p.SurnameFirstname).ToList().ForEach(p => SpeakerList.Add(p));
                var loadedEventArgs = new LoadEventArgs { IsLoaded = true, Message = string.Empty };
                OnDataLoaded(loadedEventArgs);
            }


            // Get the last time the data was downloaded.
            if (IsolatedStorageSettings.ApplicationSettings.Contains("SessionLastDownload"))
            {
                sessionLastDownload = (DateTime)IsolatedStorageSettings.ApplicationSettings["SessionLastDownload"];
            }

            // Check if we need to download the latest data, or if we can just use the isolated storage data
            // Cache the data for 2 hours
            if ((sessionLastDownload.AddHours(2) < DateTime.Now) || !IsolatedStorageSettings.ApplicationSettings.Contains("SessionData"))
            {
                var loadedEventArgs = new LoadEventArgs { IsLoaded = true, Message = string.Empty };
                // Download the data
                try
                {
                    var feedString = await TechEd2013ConferenceFeed.GetFeed();
                    ParseSessions(feedString);
                    ParseSpeakers(feedString);
                }
                catch (WebException)
                {
                    System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        loadedEventArgs = new LoadEventArgs { IsLoaded = false, Message = "There was a network error. Close the app and try again." };
                        OnDataLoaded(loadedEventArgs);
                        System.Windows.MessageBox.Show("There was a network error. Close the app and try again.");
                    });
                }
                catch (Exception ex)
                {
                    System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        loadedEventArgs = new LoadEventArgs { IsLoaded = false, Message = ex.Message };
                        OnDataLoaded(loadedEventArgs);
                        System.Windows.MessageBox.Show(ex.Message);
                    });
                }
                finally
                {
                    OnDataLoaded(loadedEventArgs);
                }
            }
        }