//------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ /// <summary> /// Returns type of the items in the source collection. /// </summary> /// <returns>Type of the items in the source collection.</returns> internal Type GetItemType(bool useRepresentativeItem) { Type collectionType = SourceCollection.GetType(); Type[] interfaces = collectionType.GetInterfaces(); // Look for IEnumerable<T>. All generic collections should implement // this. We loop through the interface list, rather than call // GetInterface(IEnumerableT), so that we handle an ambiguous match // (by using the first match) without an exception. for (int i = 0; i < interfaces.Length; ++i) { Type interfaceType = interfaces[i]; if (interfaceType.Name == IEnumerableT) { // found IEnumerable<>, extract T Type[] typeParameters = interfaceType.GetGenericArguments(); if (typeParameters.Length == 1) { return(typeParameters[0]); } } } // No generic information found. Use a representative item instead. if (useRepresentativeItem) { // get type of a representative item object item = GetRepresentativeItem(); if (item != null) { return(item.GetType()); } } return(null); }
public IDisposable SuspendNotifications() { return(SourceCollection.SuspendNotifications()); }
public void Initialize() { _source = new SourceCollection(); }
public void CurrencyWithAddItemTest() { // set the current item to the last item in the collection TestClass item = CollectionView[24] as TestClass; CollectionView.MoveCurrentToLast(); Assert.AreEqual(24, CollectionView.CurrentPosition); Assert.AreEqual(item, CollectionView.CurrentItem); // verify that when an item is inserted in an index after the // current item, the current item does not change MethodInfo mi = SourceCollection.GetType().GetMethod("Insert"); TestClass newItem = new TestClass() { IntProperty = 6 }; _expectedEventQueue.Clear(); _expectedEventQueue.Add(new EventNotification() { EventType = "CollectionChanged", Parameter = "Add" }); mi.Invoke(SourceCollection, new object[] { 25, newItem }); Assert.AreEqual(0, _expectedEventQueue.Count); Assert.AreEqual(24, CollectionView.CurrentPosition); Assert.AreEqual(item, CollectionView.CurrentItem); // now verify that if we insert into an index before the current item // then because the current item shifts position, the currency events // are fired. newItem = new TestClass() { IntProperty = 6 }; _expectedEventQueue.Clear(); _expectedEventQueue.Add(new EventNotification() { EventType = "CurrentChanging" }); _expectedEventQueue.Add(new EventNotification() { EventType = "CollectionChanged", Parameter = "Add" }); _expectedEventQueue.Add(new EventNotification() { EventType = "CurrentChanged" }); mi.Invoke(SourceCollection, new object[] { 10, newItem }); Assert.AreEqual(0, _expectedEventQueue.Count); Assert.AreEqual(25, CollectionView.CurrentPosition); Assert.AreEqual(item, CollectionView.CurrentItem); // now add grouping and verify that the items will be inserted into // the correct groups CollectionView.GroupDescriptions.Add(new PropertyGroupDescription("IntProperty")); Assert.AreEqual(24, CollectionView.CurrentPosition); Assert.AreEqual(item, CollectionView.CurrentItem); // verify that adding an item in an earlier group would push the item and update // the current item newItem = new TestClass() { IntProperty = 1 }; _expectedEventQueue.Clear(); _expectedEventQueue.Add(new EventNotification() { EventType = "CurrentChanging" }); _expectedEventQueue.Add(new EventNotification() { EventType = "CollectionChanged", Parameter = "Add" }); _expectedEventQueue.Add(new EventNotification() { EventType = "CurrentChanged" }); mi.Invoke(SourceCollection, new object[] { 10, newItem }); Assert.AreEqual(0, _expectedEventQueue.Count); Assert.AreEqual(25, CollectionView.CurrentPosition); Assert.AreEqual(item, CollectionView.CurrentItem); // now add paging and sorting. we should have updated the current item // to the first item in the collection because we switched pages CollectionView.SortDescriptions.Add(new SortDescription("IntProperty", ListSortDirection.Ascending)); CollectionView.PageSize = 5; Assert.AreEqual(0, CollectionView.CurrentPosition); Assert.AreNotEqual(item, CollectionView.CurrentItem); // move currency to the last item on the page CollectionView.MoveCurrentToLast(); // update our reference to "item" so that we point to the current item item = CollectionView[4] as TestClass; Assert.AreEqual(item, CollectionView.CurrentItem); // now add an item that would push the current item off the page newItem = new TestClass() { IntProperty = 0 }; _expectedEventQueue.Clear(); _expectedEventQueue.Add(new EventNotification() { EventType = "CurrentChanging" }); _expectedEventQueue.Add(new EventNotification() { EventType = "CollectionChanged", Parameter = "Remove" }); _expectedEventQueue.Add(new EventNotification() { EventType = "CurrentChanging" }); _expectedEventQueue.Add(new EventNotification() { EventType = "CollectionChanged", Parameter = "Add" }); _expectedEventQueue.Add(new EventNotification() { EventType = "CurrentChanged" }); mi.Invoke(SourceCollection, new object[] { 10, newItem }); Assert.AreEqual(0, _expectedEventQueue.Count); Assert.AreEqual(4, CollectionView.CurrentPosition); Assert.AreNotEqual(item, CollectionView.CurrentItem); // now set currency to the first item and add an item that // will not change currency CollectionView.PageSize = 10; CollectionView.MoveCurrentToFirst(); newItem = new TestClass() { IntProperty = 1 }; _expectedEventQueue.Clear(); _expectedEventQueue.Add(new EventNotification() { EventType = "CollectionChanged", Parameter = "Remove" }); _expectedEventQueue.Add(new EventNotification() { EventType = "CollectionChanged", Parameter = "Add" }); mi.Invoke(SourceCollection, new object[] { 10, newItem }); Assert.AreEqual(0, _expectedEventQueue.Count); }
public bool DoSearch() { var arguments = GetSearchArguments(Input); if (arguments == null) { throw new ArgumentNullException("args", "Search arguments cant be null."); } IEnumerable <Band> query = null; foreach (var arg in arguments) { if (arg.Value == "") { continue; } string key = (arg.Key != null) ? arg.Key.ToLower() : ""; switch (key) { case "song": // Fall through case "": var querySetSong = new SortedSet <Band>(); foreach (var band in SourceCollection) { bool appendBand = false; var newBand = new Band() { Name = band.Name, Collection = band.Collection }; foreach (var album in band.Albums) { var newAlbum = new Album() { Band = band, Name = album.Name, Year = album.Year }; foreach (var song in album.Songs) { if (song.Name.StartsWith(arg.Value, StringComparison.InvariantCultureIgnoreCase)) { newAlbum.Songs.Add(song); } } if (newAlbum.Songs.Count > 0) { newBand.Albums.Add(newAlbum); appendBand = true; } } if (appendBand) { querySetSong.Add(newBand); appendBand = false; } } query = (querySetSong.Count > 0) ? querySetSong : null; break; case "band": query = SourceCollection .Where <Band>(band => band.Name .StartsWith(arg.Value, StringComparison.InvariantCultureIgnoreCase)); break; case "album": var querySet = new SortedSet <Band>(); foreach (var band in SourceCollection) { var newBand = new Band() { Name = band.Name, Collection = band.Collection }; foreach (var album in band.Albums) { if (album.Name.StartsWith(arg.Value, StringComparison.InvariantCultureIgnoreCase)) { newBand.Albums.Add(album); } } if (newBand.Albums.Count > 0) { querySet.Add(newBand); } } query = (querySet.Count > 0) ? querySet : null; break; default: return(false); } if (query == null) { ResultCollection.Clear(); break; } else { ResultCollection = new SortedSet <Band>(query); } } return(true); }
public void RemoveRange(IEnumerable <T> collection) { SourceCollection.RemoveRange(collection); }
protected virtual IEnumerator GetEnumerator() { return(SourceCollection.GetEnumerator()); }
/// <summary> /// Removes the first occurrence of a specific object from the <see cref="ICollection{T}"/>. /// </summary> /// /// <returns> /// true if item was successfully removed from the <see cref="ICollection{T}"/>; /// otherwise, false. This method also returns false if item is not found in the /// original <see cref="ICollection{T}"/>. /// </returns> /// /// <param name="item">The object to remove from the <see cref="ICollection{T}"/>.</param> /// <exception cref="NotSupportedException"> /// When the <see cref="ICollection{T}"/> is read-only. /// </exception> public override bool Remove(TBase item) { return(item is TSub && SourceCollection.Remove((TSub)item)); }
/// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <remarks> /// Subclass must implement this method. /// </remarks> /// <returns> /// A <see cref="IEnumerator{T}"/> that can be used to iterate /// through the collection. /// </returns> /// <filterpriority>1</filterpriority> public override IEnumerator <TTo> GetEnumerator() { return(new TransformingEnumerator <TFrom, TTo>(SourceCollection.GetEnumerator(), Transform)); }
/// <summary> /// Removes all items from the <see cref="ICollection{T}"/>. This implementation /// clears the the source collection. /// </summary> /// /// <exception cref="NotSupportedException"> /// The <see cref="ICollection{T}"/> is read-only. /// </exception> public override void Clear() { SourceCollection.Clear(); }
public int Add(object value) { return(SourceCollection.Add(value) + 1); }
public int IndexOf(object value) { return(value == NullObject || value == null ? 0 : SourceCollection.IndexOf(value) + 1); }
public bool Contains(object value) { return(value == NullObject || SourceCollection.Contains(value)); }
protected virtual void Dispose(bool disposing) { if (_IsDisposed) return; _wantPreviewRendered = false; _wantCaptureRendered = false; CaptureComplete = null; try { destroyGraph(); } catch { } if (_videoSources != null) _videoSources.Dispose(); _videoSources = null; if (_audioSources != null) _audioSources.Dispose(); _audioSources = null; _IsDisposed = true; }
/// <summary> /// Completely tear down a filter graph and /// release all associated resources. /// </summary> private void destroyGraph() { // Derender the graph (This will stop the graph // and release preview window. It also destroys // half of the graph which is unnecessary but // harmless here.) (ignore errors) try { derenderGraph(); } catch { } // Update the state after derender because it // depends on correct status. But we also want to // update the state as early as possible in case // of error. _graphState = GraphState.Null; _isCaptureRendered = false; _isPreviewRendered = false; // Remove graph from the ROT //if (_rotCookie != 0) //{ // DsROT.RemoveGraphFromRot(ref _rotCookie); // _rotCookie = 0; //} // Remove filters from the graph // This should be unnecessary but the Nvidia WDM // video driver cannot be used by this application // again unless we remove it. Ideally, we should // simply enumerate all the filters in the graph // and remove them. (ignore errors) if (_muxFilter != null) _graphBuilder.RemoveFilter(_muxFilter); if (_videoCompressorFilter != null) _graphBuilder.RemoveFilter(_videoCompressorFilter); if (_audioCompressorFilter != null) _graphBuilder.RemoveFilter(_audioCompressorFilter); if (_videoDeviceFilter != null) _graphBuilder.RemoveFilter(_videoDeviceFilter); if (_audioDeviceFilter != null) _graphBuilder.RemoveFilter(_audioDeviceFilter); // Clean up properties if (_videoSources != null) _videoSources.Dispose(); _videoSources = null; if (_audioSources != null) _audioSources.Dispose(); _audioSources = null; if (_propertyPages != null) _propertyPages.Dispose(); _propertyPages = null; if (Tuner != null) Tuner.Dispose(); Tuner = null; // Cleanup if (_graphBuilder != null) Marshal.ReleaseComObject(_graphBuilder); _graphBuilder = null; if (_captureGraphBuilder != null) Marshal.ReleaseComObject(_captureGraphBuilder); _captureGraphBuilder = null; if (_muxFilter != null) Marshal.ReleaseComObject(_muxFilter); _muxFilter = null; if (_fileWriterFilter != null) Marshal.ReleaseComObject(_fileWriterFilter); _fileWriterFilter = null; if (_videoDeviceFilter != null) Marshal.ReleaseComObject(_videoDeviceFilter); _videoDeviceFilter = null; if (_audioDeviceFilter != null) Marshal.ReleaseComObject(_audioDeviceFilter); _audioDeviceFilter = null; if (_videoCompressorFilter != null) Marshal.ReleaseComObject(_videoCompressorFilter); _videoCompressorFilter = null; if (_audioCompressorFilter != null) Marshal.ReleaseComObject(_audioCompressorFilter); _audioCompressorFilter = null; // These are copies of graphBuilder _mediaControl = null; _videoWindow = null; // For unmanaged objects we haven't released explicitly GC.Collect(); }
public void Update(IEnumerable <T> items) { SourceCollection.Update(items); }
/// <summary> /// Create a new filter graph and add filters (devices, compressors, /// misc), but leave the filters unconnected. Call renderGraph() /// to connect the filters. /// </summary> private void createGraph() { DsGuid cat; DsGuid med; // Ensure required properties are set if (VideoDevice == null && AudioDevice == null) throw new ArgumentException("The video and/or audio device have not been set. Please set one or both to valid capture devices.\n"); // Skip if we are already created if ((int)_graphState < (int)GraphState.Created) { // Garbage collect, ensure that previous filters are released GC.Collect(); // Make a new filter graph //_graphBuilder = (IGraphBuilder)Activator.CreateInstance(Type.GetTypeFromCLSID(Clsid.FilterGraph, true)); _graphBuilder = (IGraphBuilder)new FilterGraph(); // Get the Capture Graph Builder //Guid clsid = Clsid.CaptureGraphBuilder2; //Guid riid = typeof(ICaptureGraphBuilder2).GUID; //_captureGraphBuilder = (ICaptureGraphBuilder2)DsBugWO.CreateDsInstance(ref clsid, ref riid); _captureGraphBuilder = (ICaptureGraphBuilder2)new CaptureGraphBuilder2(); // Link the CaptureGraphBuilder to the filter graph Marshal.ThrowExceptionForHR(_captureGraphBuilder.SetFiltergraph(_graphBuilder)); // Add the graph to the Running Object Table so it can be // viewed with GraphEdit #if DEBUG //DsROT.AddGraphToRot(_graphBuilder, out _rotCookie); #endif // Get the video device and add it to the filter graph if (VideoDevice != null) { _videoDeviceFilter = (IBaseFilter)Marshal.BindToMoniker(VideoDevice.MonikerString); Marshal.ThrowExceptionForHR(_graphBuilder.AddFilter(_videoDeviceFilter, "Video Capture Device")); } // Get the audio device and add it to the filter graph if (AudioDevice != null) { _audioDeviceFilter = (IBaseFilter)Marshal.BindToMoniker(AudioDevice.MonikerString); Marshal.ThrowExceptionForHR(_graphBuilder.AddFilter(_audioDeviceFilter, "Audio Capture Device")); } // Get the video compressor and add it to the filter graph if (VideoCompressor != null) { _videoCompressorFilter = (IBaseFilter)Marshal.BindToMoniker(VideoCompressor.MonikerString); Marshal.ThrowExceptionForHR(_graphBuilder.AddFilter(_videoCompressorFilter, "Video Compressor")); } // Get the audio compressor and add it to the filter graph if (AudioCompressor != null) { _audioCompressorFilter = (IBaseFilter)Marshal.BindToMoniker(AudioCompressor.MonikerString); Marshal.ThrowExceptionForHR(_graphBuilder.AddFilter(_audioCompressorFilter, "Audio Compressor")); } // Retrieve the stream control interface for the video device // FindInterface will also add any required filters // (WDM devices in particular may need additional // upstream filters to function). // Try looking for an interleaved media type object o; cat = DsGuid.FromGuid(PinCategory.Capture); med = DsGuid.FromGuid(MediaType.Interleaved); Guid iid = typeof(IAMStreamConfig).GUID; int hr = _captureGraphBuilder.FindInterface(cat, med, _videoDeviceFilter, iid, out o); //int hr = _captureGraphBuilder.FindInterface(ref cat, ref med, _videoDeviceFilter, ref iid, out o); if (hr != 0) { // If not found, try looking for a video media type med = MediaType.Video; hr = _captureGraphBuilder.FindInterface(cat, med, _videoDeviceFilter, iid, out o); //hr = _captureGraphBuilder.FindInterface(ref cat, ref med, _videoDeviceFilter, ref iid, out o); if (hr != 0) o = null; } _videoStreamConfig = o as IAMStreamConfig; // Retrieve the stream control interface for the audio device o = null; cat = DsGuid.FromGuid(PinCategory.Capture); med = DsGuid.FromGuid(MediaType.Audio); iid = typeof(IAMStreamConfig).GUID; hr = _captureGraphBuilder.FindInterface(cat, med, _audioDeviceFilter, iid, out o); // hr = _captureGraphBuilder.FindInterface(ref cat, ref med, _audioDeviceFilter, ref iid, out o); if (hr != 0) o = null; _audioStreamConfig = o as IAMStreamConfig; // Retreive the media control interface (for starting/stopping graph) _mediaControl = (IMediaControl)_graphBuilder; // Reload any video crossbars if (_videoSources != null) _videoSources.Dispose(); _videoSources = null; // Reload any audio crossbars if (_audioSources != null) _audioSources.Dispose(); _audioSources = null; // Reload any property pages exposed by filters if (_propertyPages != null) _propertyPages.Dispose(); _propertyPages = null; // Reload capabilities of video device _videoCaps = null; // Reload capabilities of video device _audioCaps = null; // Retrieve TV Tuner if available o = null; cat = DsGuid.FromGuid(PinCategory.Capture); med = DsGuid.FromGuid(MediaType.Interleaved); iid = typeof(IAMTVTuner).GUID; hr = _captureGraphBuilder.FindInterface(cat, med, _videoDeviceFilter, iid, out o); //hr = _captureGraphBuilder.FindInterface(ref cat, ref med, _videoDeviceFilter, ref iid, out o); if (hr != 0) { med = DsGuid.FromGuid(MediaType.Video); hr = _captureGraphBuilder.FindInterface(cat, med, _videoDeviceFilter, iid, out o); //hr = _captureGraphBuilder.FindInterface(ref cat, ref med, _videoDeviceFilter, ref iid, out o); if (hr != 0) o = null; } IAMTVTuner t = o as IAMTVTuner; if (t != null) Tuner = new Tuner(t); /* // ----------- VMR 9 ------------------- //## check out samples\inc\vmrutil.h :: RenderFileToVMR9 IBaseFilter vmr = null; if ( ( VideoDevice != null ) && ( previewWindow != null ) ) { vmr = (IBaseFilter) Activator.CreateInstance( Type.GetTypeFromCLSID( Clsid.VideoMixingRenderer9, true ) ); hr = graphBuilder.AddFilter( vmr, "VMR" ); if( hr < 0 ) Marshal.ThrowExceptionForHR( hr ); IVMRFilterConfig9 vmrFilterConfig = (IVMRFilterConfig9) vmr; hr = vmrFilterConfig.SetRenderingMode( VMRMode9.Windowless ); if( hr < 0 ) Marshal.ThrowExceptionForHR( hr ); IVMRWindowlessControl9 vmrWindowsless = (IVMRWindowlessControl9) vmr; hr = vmrWindowsless.SetVideoClippingWindow( previewWindow.Handle ); if( hr < 0 ) Marshal.ThrowExceptionForHR( hr ); } //------------------------------------------- // ---------- SmartTee --------------------- IBaseFilter smartTeeFilter = (IBaseFilter) Activator.CreateInstance( Type.GetTypeFromCLSID( Clsid.SmartTee, true ) ); hr = graphBuilder.AddFilter( smartTeeFilter, "Video Smart Tee" ); if( hr < 0 ) Marshal.ThrowExceptionForHR( hr ); // Video -> SmartTee cat = PinCategory.Capture; med = MediaType.Video; hr = captureGraphBuilder.RenderStream( ref cat, ref med, videoDeviceFilter, null, smartTeeFilter ); if( hr < 0 ) Marshal.ThrowExceptionForHR( hr ); // smarttee -> mux cat = PinCategory.Capture; med = MediaType.Video; hr = captureGraphBuilder.RenderStream( ref cat, ref med, smartTeeFilter, null, muxFilter ); if( hr < 0 ) Marshal.ThrowExceptionForHR( hr ); // smarttee -> vmr cat = PinCategory.Preview; med = MediaType.Video; hr = captureGraphBuilder.RenderStream( ref cat, ref med, smartTeeFilter, null, vmr ); if( hr < 0 ) Marshal.ThrowExceptionForHR( hr ); // ------------------------------------- */ // Update the state now that we are done _graphState = GraphState.Created; } }
protected override string BuildPackage() { var project = new PackageProject(); var sourceCollection = new SourceCollection <PackageEntry>(); var itemSource = new ExplicitItemSource { SkipVersions = false }; sourceCollection.Add(itemSource); var list = new List <ID>(); foreach (var item in Items) { var i = item; if (list.Any(id => id == i.ID)) { continue; } list.Add(item.ID); var reference = new ItemReference(item.Database.Name, item.Paths.Path, item.ID, LanguageManager.DefaultLanguage, Data.Version.Latest).Reduce(); itemSource.Entries.Add(reference.ToString()); } var fileSource = new ExplicitFileSource(); sourceCollection.Add(fileSource); foreach (var fileName in Files) { if (FileUtil.IsFolder(fileName)) { foreach (var file in Directory.GetFiles(FileUtil.MapPath(fileName), "*", SearchOption.AllDirectories)) { var fileInfo = new FileInfo(file); if ((fileInfo.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden) { continue; } if ((fileInfo.Attributes & FileAttributes.System) == FileAttributes.System) { continue; } fileSource.Entries.Add(file); } } else { fileSource.Entries.Add(fileName); } } project.Sources.Add(sourceCollection); project.Name = "Sitecore Package"; project.Metadata.PackageName = PackageName; project.Metadata.Author = Author; project.Metadata.Version = Version; project.Metadata.Publisher = Publisher; project.Metadata.License = License; project.Metadata.Comment = Comment; project.Metadata.Readme = Readme; project.Metadata.PostStep = PostStep; var context = new SimpleProcessingContext(); var intermediateFile = GetIntermediateFileName(FileName); try { using (var writer = new PackageWriter(PathUtils.MapPath(intermediateFile))) { writer.Initialize(context); PackageGenerator.GeneratePackage(project, writer); } Commit(intermediateFile, FileName); } catch { Cleanup(intermediateFile); throw; } return(FileName); }
protected override void EvaluateSourceCollection() { SourceCollection.Evaluate(); }
public virtual SourceCollection GetSourceList(SourceColumns orderBy, string orderDirection, int page, int pageSize, out int totalRecords) { try { Database database = DatabaseFactory.CreateDatabase(); DbCommand dbCommand = database.GetStoredProcCommand("spSourceGetList"); database.AddInParameter(dbCommand, "@OrderBy", DbType.AnsiString, orderBy.ToString()); database.AddInParameter(dbCommand, "@OrderDirection", DbType.AnsiString, orderDirection.ToString()); database.AddInParameter(dbCommand, "@Page", DbType.Int32, page); database.AddInParameter(dbCommand, "@PageSize", DbType.Int32, pageSize); database.AddOutParameter(dbCommand, "@TotalRecords", DbType.Int32, 4); SourceCollection sourceCollection = new SourceCollection(); using (IDataReader reader = database.ExecuteReader(dbCommand)) { while (reader.Read()) { Source source = CreateSourceFromReader(reader); sourceCollection.Add(source); } reader.Close(); } totalRecords = (int)database.GetParameterValue(dbCommand, "@TotalRecords"); return sourceCollection; } catch (Exception ex) { // log this exception log4net.Util.LogLog.Error(ex.Message, ex); // wrap it and rethrow throw new ApplicationException(SR.DataAccessGetSourceListException, ex); } }
public void AddRange(IEnumerable <T> collection) { SourceCollection.AddRange(collection); }
// if the IEnumerable has changed, bring the snapshot up to date. // (This isn't necessary if the IEnumerable is also INotifyCollectionChanged // because we keep the snapshot in sync incrementally.) void EnsureSnapshot() { if (_pollForChanges) { try { _trackingEnumerator.MoveNext(); } catch (InvalidOperationException) { // We need to remove the code that detects un-notified changes // This "feature" is necessarily incomplete (we cannot detect // the changes when they happen, only as a side-effect of some // later operation), and inconsistent (none of the other // collection views does this). Instead we should document // that changing a collection without raising a notification // is not supported, and let the chips fall where they may. // // For WPF 3.5 (SP1), use TraceData to warn the user that // this scenario is not really supported. if (TraceData.IsEnabled && !_warningHasBeenRaised) { _warningHasBeenRaised = true; TraceData.Trace(TraceEventType.Warning, TraceData.CollectionChangedWithoutNotification(SourceCollection.GetType().FullName)); } // collection was changed - start over with a new enumerator LoadSnapshotCore(SourceCollection); } } }
public bool Replace(T oldValue, T newValue) { return(SourceCollection.Replace(oldValue, newValue)); }
// if the IEnumerable has changed, bring the snapshot up to date. // (This isn't necessary if the IEnumerable is also INotifyCollectionChanged // because we keep the snapshot in sync incrementally.) void EnsureSnapshot() { if (_pollForChanges) { try { _trackingEnumerator.MoveNext(); } catch (InvalidOperationException) { // if (TraceData.IsEnabled && !_warningHasBeenRaised) { _warningHasBeenRaised = true; TraceData.Trace(TraceEventType.Warning, TraceData.CollectionChangedWithoutNotification(SourceCollection.GetType().FullName)); } // collection was changed - start over with a new enumerator LoadSnapshotCore(SourceCollection); } } }
public void AddItemWithPagingTest() { // verify that when we do not have sorting or grouping, when an item // is inserted, we will respect the index specified by the event. CollectionView.PageSize = 5; Assert.AreEqual(5, CollectionView.Count); MethodInfo mi = SourceCollection.GetType().GetMethod("Insert"); TestClass newItem = new TestClass() { IntProperty = 6 }; mi.Invoke(SourceCollection, new object[] { 1, newItem }); Assert.AreEqual(1, CollectionView.IndexOf(newItem)); Assert.AreEqual(5, CollectionView.Count); // however, if that index is beyond what the current page is showing, // it will not be present in the view newItem = new TestClass() { IntProperty = 6 }; mi.Invoke(SourceCollection, new object[] { 10, newItem }); Assert.IsFalse(CollectionView.Contains(newItem)); // now add sorting CollectionView.SortDescriptions.Add(new SortDescription("IntProperty", ListSortDirection.Ascending)); // verify that if we insert into the current page, the last item will be // pushed off TestClass lastItem = CollectionView[4] as TestClass; Assert.IsTrue(CollectionView.Contains(lastItem)); newItem = new TestClass() { IntProperty = 0 }; mi.Invoke(SourceCollection, new object[] { 0, newItem }); Assert.AreEqual(0, CollectionView.IndexOf(newItem)); Assert.IsFalse(CollectionView.Contains(lastItem)); // also in this case, if the sorting pushes the item to a different // page, it will not be displayed newItem = new TestClass() { IntProperty = 2 }; mi.Invoke(SourceCollection, new object[] { 20, newItem }); Assert.IsFalse(CollectionView.Contains(newItem)); // now add grouping - because of paging, only two of the groups will // be currently displayed (0 and 1). CollectionView.GroupDescriptions.Add(new PropertyGroupDescription("IntProperty")); Assert.AreEqual(2, CollectionView.Groups.Count); // add an item in the first group and verify that the last item in the // second group gets pushed off newItem = new TestClass() { IntProperty = 0 }; Assert.AreEqual(1, (CollectionView.Groups[0] as CollectionViewGroup).Items.Count); Assert.AreEqual(4, (CollectionView.Groups[1] as CollectionViewGroup).Items.Count); mi.Invoke(SourceCollection, new object[] { 0, newItem }); Assert.AreEqual(2, (CollectionView.Groups[0] as CollectionViewGroup).Items.Count); Assert.AreEqual(3, (CollectionView.Groups[1] as CollectionViewGroup).Items.Count); // again add an item into another page beyond the current one and verify that // the items remain unchanged newItem = new TestClass() { IntProperty = 6 }; Assert.AreEqual(2, (CollectionView.Groups[0] as CollectionViewGroup).Items.Count); Assert.AreEqual(3, (CollectionView.Groups[1] as CollectionViewGroup).Items.Count); mi.Invoke(SourceCollection, new object[] { 0, newItem }); Assert.AreEqual(2, (CollectionView.Groups[0] as CollectionViewGroup).Items.Count); Assert.AreEqual(3, (CollectionView.Groups[1] as CollectionViewGroup).Items.Count); // move to the last page and add an item in an earlier group to // verify that an item gets pushed up into this page CollectionView.MoveToLastPage(); Assert.AreEqual(1, (CollectionView.Groups[0] as CollectionViewGroup).Items.Count); newItem = new TestClass() { IntProperty = 2 }; mi.Invoke(SourceCollection, new object[] { 0, newItem }); Assert.AreEqual(2, (CollectionView.Groups[0] as CollectionViewGroup).Items.Count); }
private void EnsureGroupsExists(TSource element) { var key = _keySelectorCompiled(element); var groupExists = FindGroup(key, ResultCollection); if (!groupExists) { IBindableGrouping <TKey, TElement> newGroup = new BindableGrouping <TKey, TElement>(key, SourceCollection.Where(e => CompareKeys(_keySelectorCompiled(e), key)).DependsOnExpression(_keySelector.Body, _keySelector.Parameters[0]).Select(_elementSelector), Dispatcher); newGroup.CollectionChanged += Group_CollectionChanged; ResultCollection.Add(newGroup); } }
public void AddItemTest() { // verify that when we do not have sorting or grouping, when an item // is inserted, we will respect the index specified by the event. Assert.AreEqual(25, CollectionView.Count); MethodInfo mi = SourceCollection.GetType().GetMethod("Insert"); TestClass newItem = new TestClass() { IntProperty = 6 }; mi.Invoke(SourceCollection, new object[] { 5, newItem }); Assert.AreEqual(5, CollectionView.IndexOf(newItem)); Assert.AreEqual(26, CollectionView.Count); newItem = new TestClass() { IntProperty = 6 }; mi.Invoke(SourceCollection, new object[] { 10, newItem }); Assert.AreEqual(10, CollectionView.IndexOf(newItem)); Assert.AreEqual(27, CollectionView.Count); // verify that once we add sorting, the items will be inserted into the correct index // instead of looking at the index from the event handler. CollectionView.SortDescriptions.Add(new SortDescription("IntProperty", ListSortDirection.Ascending)); newItem = new TestClass() { IntProperty = 0 }; mi.Invoke(SourceCollection, new object[] { 15, newItem }); Assert.AreEqual(0, CollectionView.IndexOf(newItem)); Assert.AreEqual(28, CollectionView.Count); newItem = new TestClass() { IntProperty = 1 }; mi.Invoke(SourceCollection, new object[] { 20, newItem }); Assert.AreEqual(2, CollectionView.IndexOf(newItem)); Assert.AreEqual(29, CollectionView.Count); // verify that when we add grouping, the items will be inserted into // the correct groups CollectionView.GroupDescriptions.Add(new PropertyGroupDescription("IntProperty")); newItem = new TestClass() { IntProperty = 1 }; mi.Invoke(SourceCollection, new object[] { 0, newItem }); Assert.AreEqual(6, CollectionView.IndexOf(newItem)); Assert.IsTrue((CollectionView.Groups[1] as CollectionViewGroup).Items.Contains(newItem)); Assert.AreEqual(30, CollectionView.Count); newItem = new TestClass() { IntProperty = 2 }; mi.Invoke(SourceCollection, new object[] { 0, newItem }); Assert.AreEqual(10, CollectionView.IndexOf(newItem)); Assert.IsTrue((CollectionView.Groups[2] as CollectionViewGroup).Items.Contains(newItem)); Assert.AreEqual(31, CollectionView.Count); }
protected override void EvaluateSourceCollection() { ResultCollection.AddRange(SourceCollection.OrderBy(x => _itemSorter._keySelector)); }
public void AddSource(WonkaRefSource poNewSource) { SourceCollection.Add(poNewSource); }
/// <summary> /// Display the current file stats /// </summary> public void DisplayStats(PeopleCollection people, SourceCollection sources, RepositoryCollection repositories) { #region fields // Media double photos = 0; double notes = 0; double attachments = 0; double sourcesCount = 0; double repositoriesCount = 0; double citations = 0; double relationshipCitations = 0; PhotoCollection allPhotos = new PhotoCollection(); AttachmentCollection allAttachments = new AttachmentCollection(); // Events double relationships = 0; double marriages = 0; double divorces = 0; double births = 0; double deaths = 0; double occupations = 0; double cremations = 0; double burials = 0; double educations = 0; double religions = 0; double livingFacts = 7; double deceasedFacts = 4 + livingFacts; // Normally a person either has cremation or burial date and place so this counts a 2 events plus death place and death date events plus the normal 7 events. double marriageFacts = 2; double divorceFacts = 1; double totalEvents = 0; double living = 0; double deceased = 0; decimal minimumYear = DateTime.Now.Year; decimal maximumYear = DateTime.MinValue.Year; DateTime?marriageDate = DateTime.MaxValue; DateTime?divorceDate = DateTime.MaxValue; DateTime?birthDate = DateTime.MaxValue; DateTime?deathDate = DateTime.MaxValue; DateTime?cremationDate = DateTime.MaxValue; DateTime?burialDate = DateTime.MaxValue; // Top names string[] maleNames = new string[people.Count]; string[] femaleNames = new string[people.Count]; string[] surnames = new string[people.Count]; // Data quality double progress = 0; int i = 0; // Counter #endregion foreach (Person p in people) { #region top names if (p.Gender == Gender.Male) { maleNames[i] = p.FirstName.Split()[0]; } else { femaleNames[i] = p.FirstName.Split()[0]; } surnames[i] = p.LastName; #endregion #region photos foreach (Photo photo in p.Photos) { bool add = true; foreach (Photo existingPhoto in allPhotos) { if (string.IsNullOrEmpty(photo.RelativePath)) { add = false; } if (existingPhoto.RelativePath == photo.RelativePath) { add = false; break; } } if (add == true) { allPhotos.Add(photo); } } #endregion #region attachments foreach (Attachment attachment in p.Attachments) { bool add = true; foreach (Attachment existingAttachment in allAttachments) { if (string.IsNullOrEmpty(attachment.RelativePath)) { add = false; } if (existingAttachment.RelativePath == attachment.RelativePath) { add = false; break; } } if (add == true) { allAttachments.Add(attachment); } } #endregion if (p.HasNote) { notes++; } #region events and citations if ((!string.IsNullOrEmpty(p.ReligionSource)) && (!string.IsNullOrEmpty(p.ReligionCitation)) && (!string.IsNullOrEmpty(p.Religion))) { citations++; } if ((!string.IsNullOrEmpty(p.CremationSource)) && (!string.IsNullOrEmpty(p.CremationCitation)) && (!string.IsNullOrEmpty(p.CremationPlace) || p.CremationDate > DateTime.MinValue)) { citations++; } if ((!string.IsNullOrEmpty(p.OccupationSource)) && (!string.IsNullOrEmpty(p.OccupationCitation)) && (!string.IsNullOrEmpty(p.Occupation))) { citations++; } if ((!string.IsNullOrEmpty(p.EducationSource)) && (!string.IsNullOrEmpty(p.EducationCitation)) && (!string.IsNullOrEmpty(p.Education))) { citations++; } if ((!string.IsNullOrEmpty(p.BirthSource)) && (!string.IsNullOrEmpty(p.BirthCitation)) && ((!string.IsNullOrEmpty(p.BirthPlace)) || p.BirthDate > DateTime.MinValue)) { citations++; } if ((!string.IsNullOrEmpty(p.DeathSource)) && (!string.IsNullOrEmpty(p.DeathCitation)) && ((!string.IsNullOrEmpty(p.DeathPlace)) || p.DeathDate > DateTime.MinValue)) { citations++; } if ((!string.IsNullOrEmpty(p.BurialSource)) && (!string.IsNullOrEmpty(p.BurialCitation)) && ((!string.IsNullOrEmpty(p.BurialPlace)) || p.BurialDate > DateTime.MinValue)) { citations++; } foreach (Relationship rel in p.Relationships) { if (rel.RelationshipType == RelationshipType.Spouse) { SpouseRelationship spouseRel = ((SpouseRelationship)rel); marriages++; if (!string.IsNullOrEmpty(spouseRel.MarriageCitation) && !string.IsNullOrEmpty(spouseRel.MarriageSource) && (!string.IsNullOrEmpty(spouseRel.MarriagePlace) || spouseRel.MarriageDate > DateTime.MinValue)) { relationshipCitations++; } if (!string.IsNullOrEmpty(spouseRel.MarriagePlace)) { progress++; } if (spouseRel.MarriageDate != null) { if (spouseRel.MarriageDate > DateTime.MinValue) { marriageDate = spouseRel.MarriageDate; progress++; } } if (spouseRel.SpouseModifier == SpouseModifier.Former) { divorces++; if (spouseRel.DivorceDate != null) { if (spouseRel.DivorceDate > DateTime.MinValue) { divorceDate = spouseRel.DivorceDate; progress++; } } if (!string.IsNullOrEmpty(spouseRel.DivorceCitation) && !string.IsNullOrEmpty(spouseRel.DivorceSource) && spouseRel.DivorceDate > DateTime.MinValue) { relationshipCitations++; } } } } if (!string.IsNullOrEmpty(p.Religion)) { religions++; } if (!string.IsNullOrEmpty(p.Education)) { educations++; } if (!string.IsNullOrEmpty(p.Occupation)) { occupations++; } if (p.BurialDate > DateTime.MinValue || !string.IsNullOrEmpty(p.BurialPlace)) { burials++; } if (p.CremationDate > DateTime.MinValue || !string.IsNullOrEmpty(p.CremationPlace)) { cremations++; } if (p.DeathDate > DateTime.MinValue || !string.IsNullOrEmpty(p.DeathPlace)) { deaths++; } if (p.BirthDate > DateTime.MinValue || !string.IsNullOrEmpty(p.BirthPlace)) { births++; } #endregion #region min/max dates if (p.BirthDate != null) { birthDate = p.BirthDate; } if (p.DeathDate != null) { deathDate = p.DeathDate; } if (p.CremationDate != null) { cremationDate = p.CremationDate; } if (p.BurialDate != null) { burialDate = p.BurialDate; } DateTime?yearmin = year(marriageDate, divorceDate, birthDate, deathDate, cremationDate, burialDate, "min"); DateTime?yearmax = year(marriageDate, divorceDate, birthDate, deathDate, cremationDate, burialDate, "max"); if (minimumYear > yearmin.Value.Year) { minimumYear = yearmin.Value.Year; } if (maximumYear < yearmax.Value.Year && yearmax.Value.Year <= DateTime.Now.Year) { maximumYear = yearmax.Value.Year; } #endregion relationships += p.Relationships.Count; #region progress if (!string.IsNullOrEmpty(p.FirstName)) { progress++; } if (!string.IsNullOrEmpty(p.LastName)) { progress++; } if (!string.IsNullOrEmpty(p.BirthPlace)) { progress++; } if (p.BirthDate > DateTime.MinValue) { progress++; } if (!string.IsNullOrEmpty(p.Occupation)) { progress++; } if (!string.IsNullOrEmpty(p.Education)) { progress++; } if (!string.IsNullOrEmpty(p.Religion)) { progress++; } if (!p.IsLiving) { deceased++; // Only add progress for one cremation or burial not both if (p.CremationDate > DateTime.MinValue || !string.IsNullOrEmpty(p.CremationPlace)) { if (p.CremationDate > DateTime.MinValue) { progress++; } if (!string.IsNullOrEmpty(p.CremationPlace)) { progress++; } } else { if (p.BurialDate > DateTime.MinValue) { progress++; } if (!string.IsNullOrEmpty(p.BurialPlace)) { progress++; } } if (p.DeathDate > DateTime.MinValue) { progress++; } if (!string.IsNullOrEmpty(p.DeathPlace)) { progress++; } } else { living++; } #endregion i++; } // Will have double counted as marriage/divorce/relationships is always between 2 people marriages = marriages / 2; divorces = divorces / 2; relationships = relationships / 2; relationshipCitations = relationshipCitations / 2; citations += relationshipCitations; // Media data photos = allPhotos.Count; attachments = allAttachments.Count; sourcesCount = sources.Count; repositoriesCount = repositories.Count; Photos.Text = Properties.Resources.Photos + ": " + photos; Notes.Text = Properties.Resources.Notes + ": " + notes; Attachments.Text = Properties.Resources.Attachments + ": " + attachments; Citations.Text = Properties.Resources.Citations + ": " + citations; Sources.Text = Properties.Resources.Sources + ": " + sourcesCount; Repositories.Text = Properties.Resources.Repositories + ": " + repositoriesCount; // Relationship and event data totalEvents = births + deaths + marriages + divorces + cremations + burials + educations + occupations + religions; Marriages.Text = Properties.Resources.Marriages + ": " + marriages; Divorces.Text = Properties.Resources.Divorces + ": " + divorces; MinYear.Text = Properties.Resources.EarliestKnownEvent + ": " + minimumYear; if (maximumYear == DateTime.MinValue.Year) { MaxYear.Text = Properties.Resources.LatestKnownEvent + ": " + DateTime.Now.Year; } else { MaxYear.Text = Properties.Resources.LatestKnownEvent + ": " + maximumYear; } if (totalEvents == 0) { MinYear.Text = Properties.Resources.EarliestKnownEvent + ": "; MaxYear.Text = Properties.Resources.LatestKnownEvent + ": "; } TotalFactsEvents.Text = Properties.Resources.FactsEvents + ": " + totalEvents; Relationships.Text = Properties.Resources.Relationships + ": " + relationships; // Top 3 names string[,] mostCommonNameMale3 = Top3(maleNames); string[,] mostCommonNameFemale3 = Top3(femaleNames); string[,] mostCommonSurname3 = Top3(surnames); FemaleNames.Text = Properties.Resources.TopGirlsNames + ": \n" + "1. " + mostCommonNameFemale3[0, 0] + " " + mostCommonNameFemale3[0, 1] + " 2. " + mostCommonNameFemale3[1, 0] + " " + mostCommonNameFemale3[1, 1] + " 3. " + mostCommonNameFemale3[2, 0] + " " + mostCommonNameFemale3[2, 1]; MaleNames.Text = Properties.Resources.TopBoysNames + ": \n" + "1. " + mostCommonNameMale3[0, 0] + " " + mostCommonNameMale3[0, 1] + " 2. " + mostCommonNameMale3[1, 0] + " " + mostCommonNameMale3[1, 1] + " 3. " + mostCommonNameMale3[2, 0] + " " + mostCommonNameMale3[2, 1]; Surnames.Text = Properties.Resources.TopSurnames + ": \n" + "1. " + mostCommonSurname3[0, 0] + " " + mostCommonSurname3[0, 1] + " 2. " + mostCommonSurname3[1, 0] + " " + mostCommonSurname3[1, 1] + " 3. " + mostCommonSurname3[2, 0] + " " + mostCommonSurname3[2, 1]; #region data quality // Data quality is a % measuring the number of sourced events converted to a 5 * rating star1.Visibility = Visibility.Collapsed; star2.Visibility = Visibility.Collapsed; star3.Visibility = Visibility.Collapsed; star4.Visibility = Visibility.Collapsed; star5.Visibility = Visibility.Collapsed; if (totalEvents > 0) { double dataQuality = citations / totalEvents; string tooltip = Math.Round(dataQuality * 100, 2) + "%"; star1.ToolTip = tooltip; star2.ToolTip = tooltip; star3.ToolTip = tooltip; star4.ToolTip = tooltip; star5.ToolTip = tooltip; if (dataQuality >= 0) { star1.Visibility = Visibility.Visible; } if (dataQuality >= 0.2) { star2.Visibility = Visibility.Visible; } if (dataQuality >= 0.4) { star3.Visibility = Visibility.Visible; } if (dataQuality >= 0.6) { star4.Visibility = Visibility.Visible; } if (dataQuality >= 0.8) { star5.Visibility = Visibility.Visible; } } #endregion #region progress // Progress is a measure of the completness of a family tree // When a person's fields are completed the completeness score increases (ignores suffix as most people won't have one) double totalProgress = progress / ((living * livingFacts) + (deceased * deceasedFacts) + (marriages * marriageFacts) + (divorces * divorceFacts)); if (totalProgress > 100) { FileProgressBar.Value = 100; FileProgressText.Text = "100%"; } else { FileProgressBar.Value = totalProgress * 100; FileProgressText.Text = Math.Round(totalProgress * 100, 2) + "%"; } #endregion #region size //Data size breakdown of file sizes string appLocation = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), App.ApplicationFolderName); appLocation = Path.Combine(appLocation, App.AppDataFolderName); // Absolute path to the photos folder string photoLocation = Path.Combine(appLocation, Photo.PhotosFolderName); string noteLocation = Path.Combine(appLocation, Story.StoriesFolderName); string attachmentLocation = Path.Combine(appLocation, Attachment.AttachmentsFolderName); string xmlLocation = Path.Combine(appLocation, "content.xml"); string currentLocation = App.FamilyCollection.FullyQualifiedFilename; long photoSize = 0; long attachmentSize = 0; long noteSize = 0; long xmlSize = 0; long currentSize = 0; if (Directory.Exists(photoLocation)) { photoSize = FileSize(Directory.GetFiles(photoLocation, "*.*")); } if (Directory.Exists(noteLocation)) { noteSize = FileSize(Directory.GetFiles(noteLocation, "*.*")); } if (Directory.Exists(attachmentLocation)) { attachmentSize = FileSize(Directory.GetFiles(attachmentLocation, "*.*")); } if (File.Exists(xmlLocation)) { xmlSize = (new FileInfo(xmlLocation).Length) / 1024; //convert to Kb } if (File.Exists(currentLocation)) { currentSize = (new FileInfo(currentLocation).Length) / 1024; //convert to Kb } if (currentSize > 0) { DataSize.Text = Properties.Resources.DataSize + ": " + currentSize + " KB - (" + Properties.Resources.Photos + " " + photoSize + " KB, " + Properties.Resources.Notes + " " + noteSize + " KB, " + Properties.Resources.Attachments + " " + attachmentSize + " KB, " + Properties.Resources.Xml + " " + xmlSize + " KB)"; } else { DataSize.Text = Properties.Resources.DataSize + ": "; } #endregion #region charts //Gender bar chart ListCollectionView histogramView = CreateView("Gender", "Gender"); GenderDistributionControl.View = histogramView; GenderDistributionControl.CategoryLabels.Clear(); GenderDistributionControl.CategoryLabels.Add(Gender.Male, Properties.Resources.Male); GenderDistributionControl.CategoryLabels.Add(Gender.Female, Properties.Resources.Female); //Living bar chart ListCollectionView histogramView2 = CreateView("IsLiving", "IsLiving"); LivingDistributionControl.View = histogramView2; LivingDistributionControl.CategoryLabels.Clear(); LivingDistributionControl.CategoryLabels.Add(false, Properties.Resources.Deceased); LivingDistributionControl.CategoryLabels.Add(true, Properties.Resources.Living); //Age group bar chart ListCollectionView histogramView4 = CreateView("AgeGroup", "AgeGroup"); AgeDistributionControl.View = histogramView4; AgeDistributionControl.CategoryLabels.Clear(); AgeDistributionControl.CategoryLabels.Add(AgeGroup.Youth, Properties.Resources.AgeGroupYouth); AgeDistributionControl.CategoryLabels.Add(AgeGroup.Unknown, Properties.Resources.AgeGroupUnknown); AgeDistributionControl.CategoryLabels.Add(AgeGroup.Senior, Properties.Resources.AgeGroupSenior); AgeDistributionControl.CategoryLabels.Add(AgeGroup.MiddleAge, Properties.Resources.AgeGroupMiddleAge); AgeDistributionControl.CategoryLabels.Add(AgeGroup.Adult, Properties.Resources.AgeGroupAdult); #endregion // Ensure the controls are refreshed AgeDistributionControl.Refresh(); SharedBirthdays.Refresh(); LivingDistributionControl.Refresh(); GenderDistributionControl.Refresh(); }
public void RaiseReset() { SourceCollection.RaiseReset(); }
/// <summary> /// Adds an item to the <see cref="ICollection{T}"/>. This implementation /// throw <see cref="InvalidCastException"/> if <paramref name="item"/> /// is not a <typeparamref name="TSub"/>. /// </summary> /// /// <param name="item"> /// The object to add to the <see cref="ICollection{T}"/>. /// </param> /// <exception cref="NotSupportedException"> /// The <see cref="ICollection{T}"/> is read-only. /// </exception> /// <exception cref="InvalidCastException"> /// When <paramref name="item"/> is not of type <typeparamref name="TSub"/>. /// </exception> public override void Add(TBase item) { SourceCollection.Add((TSub)item); }
public T[] ToArray() { return(SourceCollection.ToArray()); }
/// <summary> /// Determines whether the <see cref="ICollection{T}"/> contains a specific /// value. /// </summary> /// <returns> /// true if item is found in the <see cref="ICollection{T}"/>; otherwise, false. /// </returns> /// /// <param name="item"> /// The object to locate in the <see cref="ICollection{T}"/>. /// </param> public override bool Contains(TBase item) { return(item is TSub && SourceCollection.Contains((TSub)item)); }