Anda di halaman 1dari 14

using using using using using using using using using using using using using using using

using using

System; System.Collections.Generic; System.Linq; System.Text; Interaction.Base; Interaction.Interfaces; System.Collections.ObjectModel; System.Windows.Data; System.ComponentModel; System.Reflection; Interaction.Attributes; Interaction.Utilities; System.Windows; System.Xml.Serialization; System.Xml; System.IO; System.Runtime.Serialization.Formatters.Binary;

namespace Interaction.Classes { [Serializable()] public class CollectionManager<T> : ICollectionManager , INotifyPropertyChan ged { #region INotifyPropertyChanged [field: NonSerialized] public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Raised when propertie's value changed. /// </summary> public void OnPropertyChanged(PropertyChangedEventArgs e) { if (PropertyChanged != null) { PropertyChanged(this, e); } } /// <summary> /// Raised when propertie's value changed. /// </summary> public void OnPropertyChanged(String propertyName) { this.OnPropertyChanged(new PropertyChangedEventArgs(propertyName)); } #endregion #region Constructors public CollectionManager(IDataManager dataManager) { this.dataManager = dataManager; this.sourceCollection = new CollectionBase<T>(this); PropertyInfo[] pi = typeof(T).GetProperties(); for (Int32 i = 0; i < pi.Count(); i++) {

LabelAttribute labelAtt = (LabelAttribute)pi[i].GetCustomAttribu tes(typeof(LabelAttribute), false).FirstOrDefault(); if (labelAtt != null) { this.labelProperty = pi[i].Name; } } collectionView = new ListCollectionView(this.SourceCollection); } public CollectionManager() { this.sourceCollection = new CollectionBase<T>(this); PropertyInfo[] pi = typeof(T).GetProperties(); for (Int32 i = 0; i < pi.Count(); i++) { LabelAttribute labelAtt = (LabelAttribute)pi[i].GetCustomAttribu tes(typeof(LabelAttribute), false).FirstOrDefault(); if (labelAtt != null) { this.labelProperty = pi[i].Name; } } collectionView = new ListCollectionView(this.SourceCollection); } #endregion #region CollectionBase private CollectionBase<T> sourceCollection; public CollectionBase<T> SourceCollection { get { return (CollectionBase<T>)this.sourceCollection; } set { this.sourceCollection = (CollectionBase<T>)value; this.OnPropertyChanged("SourceCollection"); } } //public ICollection ISourceCollection //{ // get { return this.SourceCollection; } //} [XmlIgnore] private ObservableCollection<T> resetItemsCollection = new ObservableCol lection<T>(); [XmlIgnore] [EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public ObservableCollection<T> ResetItemsCollection { get { return this.resetItemsCollection; }

} [XmlIgnore] private ObservableCollection<T> addedItemsCollection = new ObservableCol lection<T>(); /// <summary> /// Returns the added items in the main collection. /// </summary> [XmlIgnore] [EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public ObservableCollection<T> AddedItemsCollection { get { return this.addedItemsCollection; } } //--[XmlIgnore] private ObservableCollection<T> removedItemsCollection = new ObservableC ollection<T>(); /// <summary> /// Returns the removed items in the main collection. /// </summary> [XmlIgnore] [EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public ObservableCollection<T> RemovedItemsCollection { get { return this.removedItemsCollection; } } [XmlIgnore] private ListCollectionView collectionView = null; /// <summary> /// Returns the collection view for SourceCollection property. /// </summary> [XmlIgnore] public ListCollectionView CollectionView { get { return collectionView; } //CollectionViewSource.GetDefaultView (this.SourceCollection); } set { this.collectionView = value; this.OnPropertyChanged("CollectionView"); } } public CollectionState CollectionState { get { return this.SourceCollection.CollectionState; } set { this.SourceCollection.CollectionState = value; this.OnPropertyChanged("CollectionState"); } } #endregion #region Functions and Methods for Collection operations

/// <summary> /// Get the next Id in collection. /// </summary> /// <returns></returns> public Id NextId() { Id newId = null; Int32 itemIdentifier = (Int32)this.ItemType.GetProperty("ItemIdentif ier").GetValue(Activator.CreateInstance(this.ItemType)); PropertyInfo[] pi = this.ItemType.GetProperties(); for (Int32 i = 0; i < pi.Count(); i++) { FieldAttribute fieldAtt = (FieldAttribute)pi[i].GetCustomAttribu tes(typeof(FieldAttribute), false).FirstOrDefault(); if ((fieldAtt != null) && (fieldAtt.IsField == true)) { if (fieldAtt.IsIdentity == true & fieldAtt.AutoIncrement == true) { if (this.SourceCollection.Count() == 0) { newId = new Id(fieldAtt.AutoIncrementSeed, fieldAtt. IdFormat, itemIdentifier); //this.Item.Id = Id; } else { Int32 index = this.SourceCollection.NewIndex(fieldAt t.AutoIncrementStep); // //((ObservableCollection<T>)this.SourceCollect ion).Max(Item => ((IItem)Item).Id.Index); newId = new Id((index), fieldAtt.IdFormat, itemIdent ifier); } } } } return newId; } /// <summary> /// Add items to the main collection. /// </summary> /// <param name="item"></param> public Boolean Add(IItem item, Boolean disableAutoGenerated = false) {

Boolean result = false; item.Pendences.Clear(); PropertyInfo[] pi = typeof(T).GetProperties(); for (Int32 i = 0; i < pi.Count(); i++) { FieldAttribute fieldAtt = (FieldAttribute)pi[i].GetCustomAttribu tes(typeof(FieldAttribute), false).FirstOrDefault(); if ((fieldAtt != null) && (fieldAtt.IsField == true)) { if (fieldAtt.IsIdentity == true & fieldAtt.AutoIncrement == true ) { if (fieldAtt.AutoGenerateId == true & disableAutoGenerat ed == false) { if (this.SourceCollection.Count == 0) { Id Id = new Id(fieldAtt.AutoIncrementSeed, field Att.IdFormat, ((IItem)item).ItemIdentifier); ((IItem)item).Id = Id; } else { Int32 index = this.SourceCollection.NewIndex(fie ldAtt.AutoIncrementStep); Id Id = new Id((index), fieldAtt.IdFormat, ((IIt em)item).ItemIdentifier); ((IItem)item).Id = Id; } } ((ItemBase)item).BackupUnformatedId = item.Id.UnFormated Id; } if (fieldAtt.IsUnique == true) { Int32 marchesCount = ((ObservableCollection<T>)this.Sour ceCollection).Where(Item => Comparing.Compare(pi[i].GetValue(Item, null), pi[i]. GetValue(item, null), pi[i].PropertyType)).Count(); IItem matchItem = (IItem)((ObservableCollection<T>)this. SourceCollection).FirstOrDefault(Item => Comparing.Compare(pi[i].GetValue(Item, null), pi[i].GetValue(item, null), pi[i].PropertyType)); if (marchesCount > 0) { ((IItem)item).AreTherePendencies = true; ((IItem)item).Pendences.Add(new Pendence() { Title = "Campo: " + fieldAtt.DisplayName.ToUpper(), Value = pi[i].GetValue(item, null). ToString().ToUpper(), Message = ("J existe um item com este valor."), MatchItem = matchItem, PendenceType = PendenceType.Unique }); } } if (fieldAtt.CanBeNull == false)

{ if (pi[i].GetValue(item, null) == null | Converting.Conv ertValue(pi[i].GetValue(item, null), pi[i].PropertyType) == null) { ((IItem)item).AreTherePendencies = true; ((IItem)item).Pendences.Add(new Pendence() { Title = "Campo: " + fieldAtt.DisplayName.ToUpper(), Message = "O campo no pode conter um valor nulo.", PendenceType = PendenceType.CannotBeNull }); } } } } if (((IItem)item).AreTherePendencies == false) { this.SourceCollection.Add((IItem)item); item.ItemState = ItemState.Added; this.AddedItemsCollection.Add((T)item); result = true; } else { String message = ""; foreach (Pendence Pd in ((IItem)item).Pendences) { if (Pd.PendenceType == PendenceType.Unique) { message = ""; message += "Item Id: " + ((IItem)item).Id.FormatedId; message += System.Environment.NewLine; message += "Id do item existente na lista: " + Pd.MatchI tem.Id.FormatedId; message += System.Environment.NewLine; message += System.Environment.NewLine; message += Pd.Title + " -> Valor inserido: " + Pd.Value; message += System.Environment.NewLine; message += System.Environment.NewLine; message += Pd.Message; System.Windows.MessageBox.Show(message, "Pendncias", Mess ageBoxButton.OK, MessageBoxImage.Exclamation); } if (Pd.PendenceType == PendenceType.CannotBeNull) { message = ""; message += "Item Id: " + ((IItem)item).Id.FormatedId; message += System.Environment.NewLine; message += System.Environment.NewLine; message += Pd.Title; message += System.Environment.NewLine; message += System.Environment.NewLine; message += Pd.Message; MessageBox.Show(message, "Pendncias", MessageBoxButton.OK , MessageBoxImage.Exclamation); }

} } item.Pendences.Clear(); item.AreTherePendencies = false; return result; } //--/// <summary> /// Add items to the main collection. /// </summary> /// <param name="item"></param> public Boolean Edit(IItem item) { Boolean result = false; ((IItem)item).Pendences.Clear(); PropertyInfo[] pi = typeof(T).GetProperties(); for (Int32 i = 0; i < pi.Count(); i++) { FieldAttribute fieldAtt = (FieldAttribute)pi[i].GetCustomAttribu tes(typeof(FieldAttribute), false).FirstOrDefault(); if ((fieldAtt != null) && (fieldAtt.IsField == true)) { //if (fieldAtt.IsIdentity == true & fieldAtt.AutoIncrement = = true) //{ // // if (this.SourceCollection.Count == 0) {

// Id Id = new Id(fieldAtt.AutoIncrementSeed, fieldAt t.IdFormat, ((IItem)item).ItemIdentifier); // // // // // eCollection).Max(Item => ((IItem)item).Id = Id; } else { Int32 index = ((ObservableCollection<T>)this.Sourc ((IItem)Item).Id.Index);

// Id Id = new Id((index + fieldAtt.AutoIncrementStep ), fieldAtt.IdFormat, ((IItem)item).ItemIdentifier); // // //} if (fieldAtt.IsUnique == true) { Int32 marchesCount = ((ObservableCollection<T>)this.Sour ceCollection).Where(Item => Comparing.Compare(pi[i].GetValue(Item, null), pi[i]. GetValue(item, null), pi[i].PropertyType)).Count(); IItem matchItem = (IItem)((ObservableCollection<T>)this. ((IItem)item).Id = Id; }

SourceCollection).FirstOrDefault(Item => Comparing.Compare(pi[i].GetValue(Item, null), pi[i].GetValue(item, null), pi[i].PropertyType)); if (marchesCount > 1) { ((IItem)item).AreTherePendencies = true; ((IItem)item).Pendences.Add(new Pendence() { Title = "Campo: " + fieldAtt.DisplayName.ToUpper(), Value = pi[i].GetValue(item, null). ToString().ToUpper(), Message = ("J existe um item com este valor."), MatchItem = matchItem, PendenceType = PendenceType.Unique }); } } if (fieldAtt.CanBeNull == false) { if (pi[i].GetValue(item, null) == null | Converting.Conv ertValue(pi[i].GetValue(item, null), pi[i].PropertyType) == null) { ((IItem)item).AreTherePendencies = true; ((IItem)item).Pendences.Add(new Pendence() { Title = "Campo: " + fieldAtt.DisplayName.ToUpper(), Message = "O campo no pode conter um valor nulo.", PendenceType = PendenceType.CannotBeNull }); } } }

} if (((IItem)item).AreTherePendencies == false) { //this.SourceCollection.Add((IItem)item); //this.AddedItemsCollection.Add((T)item); if (item.ItemState != ItemState.Added) { item.ItemState = ItemState.Changed; } result = true; } else { String message = ""; foreach (Pendence Pd in ((IItem)item).Pendences) { if (Pd.PendenceType == PendenceType.Unique) { message = ""; message += "Item Id: " + ((IItem)item).Id.FormatedId; message += System.Environment.NewLine; message += "Id do item existente na lista: " + Pd.MatchI tem.Id.FormatedId; message += System.Environment.NewLine; message += System.Environment.NewLine; message += Pd.Title + " -> Valor inserido: " + Pd.Value; message += System.Environment.NewLine; message += System.Environment.NewLine;

message += Pd.Message; MessageBox.Show(message, "Pendncias", MessageBoxButton.OK , MessageBoxImage.Exclamation); } if (Pd.PendenceType == PendenceType.CannotBeNull) { message = ""; message += "Item Id: " + ((IItem)item).Id.FormatedId; message += System.Environment.NewLine; message += System.Environment.NewLine; message += Pd.Title; message += System.Environment.NewLine; message += System.Environment.NewLine; message += Pd.Message; MessageBox.Show(message, "Pendncias", MessageBoxButton.OK , MessageBoxImage.Exclamation); } } } return result; } /// <summary> /// Remove items from the main collection. /// </summary> /// <param name="Item"></param> public void Remove(IItem item, Boolean disableMessage = false) { String message = ""; //message += "Id: " + ((IItem)item).Id.FormatedId; //message += System.Environment.NewLine; message += "Deseja remover o(a) "; PropertyInfo[] pi = typeof(T).GetProperties(); for (Int32 i = 0; i < pi.Count(); i++) { LabelAttribute labelAtt = (LabelAttribute)pi[i].GetCustomAttribu tes(typeof(LabelAttribute), false).FirstOrDefault(); if (labelAtt != null) { message += labelAtt.Name + " " + pi[i].GetValue(item).ToStri ng() + "?"; } } if (disableMessage == false) { if (MessageBox.Show(message, "Remover item", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes) { this.SourceCollection.Remove((IItem)item); this.RemovedItemsCollection.Add((T)item); //item.ItemState = ItemState.Removed; } } else

{ this.SourceCollection.Remove((IItem)item); this.RemovedItemsCollection.Add((T)item); } } /// <summary> /// Remove items from the main collection by index. /// </summary> /// <param name="Item"></param> public void RemoveAt(Int32 index) { if (this.SourceCollection.Count > 0) { IItem Item = (IItem)this.SourceCollection[index]; this.SourceCollection.Remove((IItem)Item); this.RemovedItemsCollection.Add((T)Item); } } public void SetGroup(String groupName) { this.CollectionView.GroupDescriptions.Clear(); this.CollectionView.GroupDescriptions.Add(new PropertyGroupDescripti on(groupName)); } public void SetSort(String fieldName, ListSortDirection direction) { this.CollectionView.SortDescriptions.Clear(); this.CollectionView.SortDescriptions.Add(new SortDescription(fieldNa me, direction)); } [XmlIgnore] public Predicate<Object> Filter { get { return this.CollectionView.Filter; } set { this.CollectionView.Filter = value; } } #endregion #region Exporting Functions and Methods public virtual void SaveToXMLFormat(String path) { XmlSerializer XS = new XmlSerializer(typeof(ObservableCollection<T>) ); UTF8StringWriter StW = new UTF8StringWriter(); XS.Serialize(StW, (ObservableCollection<T>)(this.SourceCollection)); XmlDocument XDoc = new XmlDocument(); XDoc.LoadXml(StW.ToString());

XDoc.Save(path); } public virtual void LoadFromXMLFormat(String path, String orderByPropert yName, Boolean addInSourceCollection = false) { this.ResetItemsCollection.Clear(); this.SourceCollection.Clear(); XmlDocument XDoc = new XmlDocument(); XDoc.Load(path); XmlSerializer XS = new XmlSerializer(typeof(ObservableCollection<T>) ); ObservableCollection<T> mirrorCollection = new ObservableCollection< T>(); using (TextReader txtreader = new StringReader(XDoc.OuterXml)) { mirrorCollection = (ObservableCollection<T>)XS.Deserialize(txtre ader); } foreach (T item in mirrorCollection.OrderBy(p => typeof(T).GetProper ty(orderByPropertyName).GetGetMethod())) { this.SourceCollection.Add(item); this.ResetItemsCollection.Add(item); if (addInSourceCollection) { this.AddedItemsCollection.Add(item); } ((IItem)item).ItemState = ItemState.Added; } } public void SaveToBinFormat(String path) { XmlSerializer XS = new XmlSerializer(typeof(ObservableCollection<T>) ); UTF8StringWriter StW = new UTF8StringWriter(); XS.Serialize(StW, (ObservableCollection<T>)(this.SourceCollection)); XmlDocument XDoc = new XmlDocument(); XDoc.LoadXml(StW.ToString()); MemoryStream memStream = new MemoryStream(); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(memStream, XDoc.OuterXml);

Byte[] bytes = memStream.GetBuffer(); using (FileStream fileStream = new FileStream(path, FileMode.Create, FileAccess.Write)) { fileStream.Write(bytes, 0, bytes.Count()); } } public void LoadFromBinFormat(String path) { Byte[] bytes; String source; using (FileStream file = new FileStream(path, FileMode.Open, FileAcc ess.Read)) { bytes = new Byte[file.Length]; file.Read(bytes, 0, (Int32)file.Length); } MemoryStream memStream = new MemoryStream(bytes); BinaryFormatter formatter = new BinaryFormatter(); source = (String)formatter.Deserialize(memStream); this.SourceCollection.Clear(); memStream.Close(); XmlDocument XDoc = new XmlDocument(); XDoc.LoadXml(source); XmlSerializer XS = new XmlSerializer(typeof(ObservableCollection<T>) ); ObservableCollection<T> mirrorCollection = new ObservableCollection< T>(); using (TextReader txtreader = new StringReader(XDoc.OuterXml)) { mirrorCollection = (ObservableCollection<T>)XS.Deserialize(txtre ader); } foreach (T item in mirrorCollection) { this.SourceCollection.Add(item); ((IItem)item).ItemState = ItemState.Unchanged; } } public Byte[] ConvertToByteArray() { XmlSerializer XS = new XmlSerializer(typeof(ObservableCollection<T>) ); UTF8StringWriter StW = new UTF8StringWriter(); XS.Serialize(StW, (ObservableCollection<T>)(this.SourceCollection));

XmlDocument XDoc = new XmlDocument(); XDoc.LoadXml(StW.ToString()); MemoryStream memStream = new MemoryStream(); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(memStream, XDoc.OuterXml); return memStream.GetBuffer(); } public void LoadFromByteArray(Byte[] bytes) { String source; MemoryStream memStream = new MemoryStream(bytes); BinaryFormatter formatter = new BinaryFormatter(); source = (String)formatter.Deserialize(memStream); this.SourceCollection.Clear(); memStream.Close(); XmlDocument XDoc = new XmlDocument(); XDoc.LoadXml(source); XmlSerializer XS = new XmlSerializer(typeof(ObservableCollection<T>) ); ObservableCollection<T> mirrorCollection = new ObservableCollection< T>(); using (TextReader txtreader = new StringReader(XDoc.OuterXml)) { mirrorCollection = (ObservableCollection<T>)XS.Deserialize(txtre ader); } foreach (T item in mirrorCollection) { this.SourceCollection.Add(item); ((IItem)item).ItemState = ItemState.Unchanged; } } #endregion public DataSet DataSet { get { return null; } } [EditorBrowsable(EditorBrowsableState.Never)] public void ResetID() { PropertyInfo pi = typeof(T).GetProperty("Id"); FieldAttribute fieldAtt = (FieldAttribute)pi.GetCustomAttributes(typ eof(FieldAttribute), false).FirstOrDefault(); Int32 n = 0; foreach (T item in this.ResetItemsCollection) { Id id = new Id(n, fieldAtt.IdFormat, ((IItem)item).ItemIdentifie

r); ((IItem)item).Id = id; n += 1; } } [XmlIgnore] public Type ItemType { get { return typeof(T); } } private string labelProperty; [XmlIgnore] public string LabelProperty { get { return this.labelProperty; } } private IDataManager dataManager; public IDataManager DataManager { get { return this.dataManager; } }

} }

Anda mungkin juga menyukai