public AddAlbumWindow(Album album) { m_album = album; InitializeComponent(); tbAlbumName.Text = m_album.Title; }
public void AlbumRepositoryTests() { var db = DbManger.GetInstance(); var mgr = db.GetAlbumsRepository(); var album1 = new Album() { CreationDate = DateTime.Now, VkId = 6666, ThumbImg = "asd", Title = "Title" }; mgr.Add(album1); if(album1.Id == 0) throw new Exception("Save operation failed"); album1.Title = "Title Updated"; mgr.Update(album1); var album2 = mgr.GetById(album1.Id); if(album2.Title != album1.Title) throw new Exception("GetById failed"); var album3 = mgr.GetByVkId(6666); if (album3.Title != album1.Title) throw new Exception("GetById failed"); album3.Title = "Title ReUpdated"; mgr.Update(album3); mgr.Delete(album1); }
private void lbAlbums_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (e.AddedItems.Count > 0) { var obj = e.AddedItems[0] as Album; if (obj != null) m_selectedAlbum = obj; } }
public List<Product> GetAllFromAlbum(Album album) { using (var s = m_dbManger.OpenSession()) { IQuery q = s.CreateQuery("from Product as a where a.AlbumId = :aid"); q.SetInt32("aid", album.Id); return (List<Product>) q.List<Product>(); } }
public List<Payment> AllForAlbum(Album album) { using (var s = m_dbManger.OpenSession()) { IQuery q = s.CreateQuery("from Payment as p where p.AlbumId = :aid"); q.SetInt32("aid", album.Id); return (List<Payment>)q.List<Payment>(); } }
public List<Payment> AllForCustomerInAlbum(Customer customer, Album album) { using (var s = m_dbManger.OpenSession()) { IQuery q = s.CreateQuery("from Payment as p where p.AlbumId = :aid and p.PayerId = :pid"); q.SetInt32("aid", album.Id); q.SetInt32("pid", customer.Id); return (List<Payment>)q.List<Payment>(); } }
public void Add(Album album) { using (var s = m_dbManger.OpenSession()) { using (var t = s.BeginTransaction()) { s.Save(album); t.Commit(); AddToCache(album); } } }
public void Delete(Album album) { using (var s = m_dbManger.OpenSession()) { using (var t = s.BeginTransaction()) { s.Delete(album); t.Commit(); DeleteFromCache(album); } } }
public ProductSelectionWindow(Window owner, Album currentAlbum) { m_currentAlbum = currentAlbum; m_products = new List<Product>(); m_allAlbums = new List<Album>(0); m_selectedProducts = new List<Product>(0); InitializeComponent(); this.Owner = owner; this.DataContext = this; PopolateAlbumsList(); PopulateProductsList(); }
public OrderEditWindow(Window owner, CustomerListViewItem customer, Album album) { m_sourceListViewItem = customer; m_customer = customer.Source; m_customerItem = customer; m_album = album; m_settings = RegistrySettings.GetInstance(); m_orders = new List<Order>(0); InitializeComponent(); Owner = owner; KeyUp += OnKeyUp; FillOrdersTable(); }
public AskExportSettingsWindow(Window owner, Album album, string filePrefix) { m_album = album; m_filePrefix = filePrefix; m_result = Result.None; m_settings = RegistrySettings.GetInstance(); InitializeComponent(); Title = String.Format("Экспорт: {0}", m_album.GetCleanTitle()); boxFormats.Items.Add(new ReportsExportFormatter(m_album)); boxFormats.Items.Add(new WordExportFormatter(m_album)); boxFormats.Items.Add(new PlainTextExportFormatter(m_album)); KeyUp += OnKeyUp; boxFormats.SelectedIndex = 0; Owner = owner; }
public ReportsExportFormatter(Album album) : base(album) { m_logger = log4net.LogManager.GetLogger("ReportsExportFormatter"); m_document = new FlowDocument {FontFamily = new FontFamily("Verdana"), FontSize = 10}; }
public Product CopyToAlbum(Album album) { var p = new Product { AlbumId = album.Id, GenericUrl = this.GenericUrl, ImageFile = this.ImageFile, MinAmount = this.MinAmount, Price = this.Price, Title = this.Title, VkId = this.VkId, CodeNumber = this.CodeNumber }; return p; }
private void ShowAlbumCutomersDetails(Album a) { #region приготовить view var view = lvDetails.View as GridView; lvDetails.Items.Clear(); view.Columns.Clear(); view.Columns.Add(new GridViewColumn { Width = 45, Header = "Код", DisplayMemberBinding = new Binding("Id") }); view.Columns.Add(new GridViewColumn { Width = 250, Header = "Имя", DisplayMemberBinding = new Binding("FullName"), }); view.Columns.Add(new GridViewColumn { Width = 100, Header = "Комиссия", DisplayMemberBinding = new Binding("AccountType"), }); // view.Columns.Add(new GridViewColumn // { // Width = 110, // Header = "Позиций в заказе", // DisplayMemberBinding = new Binding("OrderedItemsCount"), // }); view.Columns.Add(new GridViewColumn { Width = 110, Header = "Сумма заказа", DisplayMemberBinding = new Binding("CleanSum") { Converter = s_currencyVisualiser }, }); view.Columns.Add(new GridViewColumn { Width = 110, Header = "Комиссия", DisplayMemberBinding = new Binding("CommissionSum") { Converter = s_currencyVisualiser }, }); view.Columns.Add(new GridViewColumn { Width = 110, Header = "Итог", DisplayMemberBinding = new Binding("TotalSum") { Converter = s_roundedCurrencyVisualiser }, }); view.Columns.Add(new GridViewColumn { Width = 90, Header = "Статус", DisplayMemberBinding = new Binding("Status") { Converter = s_currencyVisualiser }, }); #endregion var bgw = new BackgroundWorker {WorkerReportsProgress = true}; bgw.ProgressChanged += (sender, args) => { if (m_waitingWindow != null) { m_waitingWindow.SetState(args.UserState.ToString()); } }; bgw.DoWork += (sender, args) => { var worker = sender as BackgroundWorker; var album = args.Argument as Album; var orderRepository = DbManger.GetInstance().GetOrderRepository(); var customersRepository = DbManger.GetInstance().GetCustomersRepository(); var payments = DbManger.GetInstance().GetPaymentsRepository(); List<Order> albumOrders = null; worker.ReportProgress(0, "Получение заказов для альбома"); try { albumOrders = orderRepository.GetOrdersForAlbum(album); } catch (Exception exception) { m_logger.ErrorException(exception); throw new BgWorkerException("Не удалось получить заказы альбома из БД."); } var result = new List<CustomerListViewItem>(); foreach (IGrouping<int, Order> ordersGroup in albumOrders.GroupBy(order => order.CustomerId)) { Customer custObj; try { worker.ReportProgress(0, "Получение данных о заказчике."); custObj = customersRepository.GetById(ordersGroup.Key); } catch (Exception exception) { m_logger.ErrorException(exception); throw new BgWorkerException("Ошибка получения данных из БД"); } if (custObj == null) { m_logger.ErrorFormat( "Обнаружено нарушение целостности БД!. Для заказа '{0}' не удалось найти покупателя", ordersGroup.Key); continue; } if (custObj.GetCommissionInfo() == null) { throw new BgWorkerException(String.Format("Ошибка: Для покупателя '{0}' неверно установлена ставка комиссии.", custObj.GetFullName())); } // создание объекта записи в таблице var clvi = new CustomerListViewItem(custObj);// {OrderedItemsCount = 0}; foreach (Order order in ordersGroup) { Product productInfo = null; long totalProductOrders; worker.ReportProgress(0, "Получение информации о продукте"); try { productInfo = order.GetOrderedProduct(); // посчитать сколько всего заказано этого товара totalProductOrders = orderRepository.GetProductTotalOrderedAmount(productInfo); } catch (Exception exception) { m_logger.ErrorException(exception); continue; } // добавляем к сумме заказа стоимость очередной позиции (кол-во на стоимость единицы) clvi.CleanSum += order.Amount * productInfo.Price; clvi.HasPartialPosition = (totalProductOrders < productInfo.MinAmount && totalProductOrders > 0) || (totalProductOrders == 0); } if (clvi.CleanSum == 0) continue; payments.AllForCustomerInAlbum(custObj, SelectedAlbum) .ForEach(payment => clvi.Payment += payment.Amount); result.Add(clvi); } result.Sort((x, y) => String.Compare(x.FullName, y.FullName, StringComparison.CurrentCultureIgnoreCase)); args.Result = result; }; bgw.RunWorkerCompleted += (sender, args) => { var worker = sender as BackgroundWorker; if (worker != null) { lock (m_workersPool) { m_workersPool.Remove(worker); } } if (m_waitingWindow != null) { m_waitingWindow.Close(); m_waitingWindow = null; } if (args.Cancelled) return; if (args.Error != null) { this.ShowError(args.Error.Message); return; } var list = args.Result as List<CustomerListViewItem>; if (list != null) { foreach (var clvi in list) { lvDetails.Items.Add(clvi); } } }; lock (m_workersPool) { m_workersPool.Add(bgw); } bgw.RunWorkerAsync(a); m_waitingWindow = new WaitingWindow(this); m_waitingWindow.ShowDialog(); }
private void cbAlbumsCollection_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (e.AddedItems.Count <= 0) return; var a = e.AddedItems[0] as Album; m_currentAlbum = a; m_selectedProducts.Clear(); PopulateProductsList(); }
private void UpdateInCache(Album album) { if (s_idToAlbumCache.ContainsKey(album.Id)) s_idToAlbumCache[album.Id] = album; if (s_vkidToAlbumCache.ContainsKey(album.VkId)) s_vkidToAlbumCache[album.VkId] = album; }
private void AddToCache(Album album) { if (!s_idToAlbumCache.ContainsKey(album.Id)) s_idToAlbumCache.Add(album.Id, album); if (!s_vkidToAlbumCache.ContainsKey(album.VkId)) s_vkidToAlbumCache.Add(album.VkId, album); }
private void ShowAlbumPaymentsDetails(Album album) { #region приготовить view var view = lvDetails.View as GridView; lvDetails.Items.Clear(); view.Columns.Clear(); view.Columns.Add(new GridViewColumn { Width = 40, Header = "№", DisplayMemberBinding = new Binding("Id") { Mode = BindingMode.OneWay }, }); view.Columns.Add(new GridViewColumn { Width = 350, Header = "Покупатель", DisplayMemberBinding = new Binding("Title"), }); view.Columns.Add(new GridViewColumn { Width = 100, Header = "Сумма", DisplayMemberBinding = new Binding("Amount"), }); view.Columns.Add(new GridViewColumn { Width = 200, Header = "Дата", DisplayMemberBinding = new Binding("Date"), }); view.Columns.Add(new GridViewColumn { Width = 300, Header = "Комментарий", DisplayMemberBinding = new Binding("Comment"), }); #endregion var bgw = new BackgroundWorker { WorkerReportsProgress = true }; bgw.ProgressChanged += (sender, args) => { if (m_waitingWindow != null) { m_waitingWindow.SetState(args.UserState.ToString()); } }; bgw.DoWork += (sender, args) => { var worker = (BackgroundWorker) sender; worker.ReportProgress(0, "Загрузка"); var payRepo = DbManger.GetInstance().GetPaymentsRepository(); var custRepo = DbManger.GetInstance().GetCustomersRepository(); var albumPayments = payRepo.AllForAlbum(album); var result = (from albumPayment in albumPayments let customer = custRepo.GetById(albumPayment.PayerId) select new PaymentsListViewItem(albumPayment, customer)).ToList(); result.Sort((i1, i2) => String.Compare(i1.Title, i2.Title, StringComparison.CurrentCultureIgnoreCase)); args.Result = result; }; bgw.RunWorkerCompleted += (sender, args) => { var worker = sender as BackgroundWorker; if (worker != null) { lock (m_workersPool) { m_workersPool.Remove(worker); } } if (m_waitingWindow != null) { m_waitingWindow.Close(); m_waitingWindow = null; } if (args.Cancelled) return; if (args.Error != null) { this.ShowError(args.Error.Message); return; } foreach (PaymentsListViewItem plvi in ((List<PaymentsListViewItem>)args.Result)) { lvDetails.Items.Add(plvi); } }; lock (m_workersPool) { m_workersPool.Add(bgw); } bgw.RunWorkerAsync(); m_waitingWindow = new WaitingWindow(this); m_waitingWindow.ShowDialog(); }
public PlainTextExportFormatter(Album album) : base(album) { m_logger = log4net.LogManager.GetLogger("PlainTextExportFormatter"); }
public List<Order> GetOrdersForAlbum(Album album) { using (var s = m_dbManger.OpenSession()) { IQuery productsQuery = s.CreateQuery("from Product p where p.AlbumId = :aid"); productsQuery.SetInt32("aid", album.Id); var idsList = productsQuery.List<Product>().Select(product => product.Id).ToList(); if(idsList.Count == 0) return new List<Order>(0); List<Order> result; if (idsList.Count > 0) { IQuery q = s.CreateQuery("from Order as o where o.ProductId in (:namesList)"); q.SetParameterList("namesList", idsList); result = (List<Order>)q.List<Order>(); } else result = new List<Order>(0); return result; } }
public List<Order> GetOrdersForCustomerFromAlbum(Customer customer, Album album) { using (var s = m_dbManger.OpenSession()) { IQuery productsQuery = s.CreateQuery("from Product p where p.AlbumId = :aid"); productsQuery.SetInt32("aid", album.Id); var idsList = productsQuery.List<Product>().Select(product => product.Id).ToList(); if (idsList.Count == 0) return new List<Order>(0); IQuery q = s.CreateQuery("from Order as o where o.CustomerId = :oid and o.ProductId in (:namesList)"); q.SetInt32("oid", customer.Id); q.SetParameterList("namesList", idsList); return (List<Order>)q.List<Order>(); } }
protected ExportFormatterBase(Album album) { WorkingAlbum = album; }
public void Update(Album album) { using (var s = m_dbManger.OpenSession()) { using (var t = s.BeginTransaction()) { s.Update(album); t.Commit(); UpdateInCache(album); } } }
public void OrderRepositoryTests() { var db = DbManger.GetInstance(); var orders = db.GetOrderRepository(); var products = db.GetProductRepository(); var albums = db.GetAlbumsRepository(); var customers = db.GetCustomersRepository(); var user1 = new Customer {FirstName = "aaaa", LastName = "bbbbb", VkId = 1}; var user2 = new Customer { FirstName = "aaaa", LastName = "bbbbb", VkId = 1 }; customers.Add(user1); customers.Add(user2); var album1 = new Album {CreationDate = DateTime.Now, VkId = 1, Title = "Album 1"}; var album2 = new Album { CreationDate = DateTime.Now, VkId = 2, Title = "Album 2" }; albums.Add(album1); albums.Add(album2); var p1 = new Product { GenericUrl = "aaa", Title = "Product 1", Price = 10, VkId = 1, AlbumId = album1.Id}; // p1 -> album1 var p2 = new Product { GenericUrl = "aaa", Title = "Product 2", Price = 10, VkId = 2, AlbumId = album1.Id }; // p2 -> album1 var p3 = new Product { GenericUrl = "aaa", Title = "Product 3", Price = 10, VkId = 3, AlbumId = album1.Id }; // p3 -> album1 var p4 = new Product { GenericUrl = "aaa", Title = "Product 4", Price = 10, VkId = 4, AlbumId = album1.Id }; // p4 -> album1 var p5 = new Product { GenericUrl = "aaa", Title = "Product 5", Price = 10, VkId = 5, AlbumId = album2.Id }; // p5 -> album1 var p6 = new Product { GenericUrl = "aaa", Title = "Product 6", Price = 10, VkId = 6, AlbumId = album2.Id }; // p6 -> album1 products.Add(p1); products.Add(p2); products.Add(p3); products.Add(p4); products.Add(p5); products.Add(p6); orders.Add(new Order{Amount = 10, CustomerId = user1.Id, Date = DateTime.Now, ProductId = p1.Id}); // user1 -> p1 (album1) orders.Add(new Order { Amount = 10, CustomerId = user1.Id, Date = DateTime.Now, ProductId = p2.Id }); // user1 -> p2 (album1) orders.Add(new Order { Amount = 10, CustomerId = user1.Id, Date = DateTime.Now, ProductId = p4.Id }); // user1 -> p4 (album1) orders.Add(new Order { Amount = 10, CustomerId = user1.Id, Date = DateTime.Now, ProductId = p6.Id }); // user1 -> p6 (album2) orders.Add(new Order { Amount = 10, CustomerId = user2.Id, Date = DateTime.Now, ProductId = p1.Id }); // user2 -> p1 (album1) orders.Add(new Order { Amount = 10, CustomerId = user2.Id, Date = DateTime.Now, ProductId = p3.Id }); // user2 -> p3 (album1) orders.Add(new Order { Amount = 10, CustomerId = user2.Id, Date = DateTime.Now, ProductId = p5.Id }); // user2 -> p5 (album2) var album1Orders = orders.GetOrdersForAlbum(album1); if (album1Orders.Count != 5) throw new Exception("GetOrdersForAlbum failed"); var album2Orders = orders.GetOrdersForAlbum(album2); if (album2Orders.Count != 2) throw new Exception("GetOrdersForAlbum x2 failed"); var user1Orders = orders.GetOrdersForCustomer(user1); if (user1Orders.Count != 4) throw new Exception("GetOrdersForCustomer failed"); var user2Orders = orders.GetOrdersForCustomer(user2); if (user2Orders.Count != 3) throw new Exception("GetOrdersForCustomer x2 failed"); var user1Album1Orders = orders.GetOrdersForCustomerFromAlbum(user1, album1); if (user1Album1Orders.Count != 3) throw new Exception("GetOrdersForCustomerFromAlbum failed"); var user1Album2Orders = orders.GetOrdersForCustomerFromAlbum(user1, album2); if (user1Album2Orders.Count != 1) throw new Exception("GetOrdersForCustomerFromAlbum failed"); var user2Album1Orders = orders.GetOrdersForCustomerFromAlbum(user2, album1); if (user2Album1Orders.Count != 2) throw new Exception("GetOrdersForCustomerFromAlbum failed"); var user2Album2Orders = orders.GetOrdersForCustomerFromAlbum(user2, album2); if (user2Album2Orders.Count != 1) throw new Exception("GetOrdersForCustomerFromAlbum failed"); products.Delete(p1); products.Delete(p2); products.Delete(p3); products.Delete(p4); products.Delete(p5); products.Delete(p6); albums.Delete(album1); albums.Delete(album2); customers.Delete(user1); customers.Delete(user2); }
private void DeleteFromCache(Album album) { if (s_idToAlbumCache.ContainsKey(album.Id)) s_idToAlbumCache.Remove(album.Id); if (s_vkidToAlbumCache.ContainsKey(album.VkId)) s_vkidToAlbumCache.Remove(album.VkId); }
private void CmdFileAddAlbum_OnClick(object sender, RoutedEventArgs e) { var a = new Album { CreationDate = DateTime.Now, VkId = 0, ThumbImg = "", Title = "", }; var w = new AddAlbumWindow(a); var res = w.ShowDialog(); if (!res.HasValue || !res.Value) return; var repo = DbManger.GetInstance().GetAlbumsRepository(); try { repo.Add(a); } catch (Exception exception) { m_logger.ErrorException(exception); this.ShowError("Не удалось добавить альбом. " + String.Format("({0}) {1}", exception.GetType().Name, exception.Message)); return; } FillAlbumsListAsync(); }
private void ShowAlbumProductsDetails(Album album) { #region приготовить view var view = lvDetails.View as GridView; if (view == null) return; lvDetails.Items.Clear(); view.Columns.Clear(); view.Columns.Add(new GridViewColumn { Width = 90, Header = "Артикул", DisplayMemberBinding = new Binding("CodeNumber"){Mode = BindingMode.OneWay } , }); view.Columns.Add(new GridViewColumn { Width = 350, Header = "Наименование", DisplayMemberBinding = new Binding("Title"), }); view.Columns.Add(new GridViewColumn { Width = 100, Header = "Цена", DisplayMemberBinding = new Binding("Price") { Converter = s_currencyVisualiser }, }); view.Columns.Add(new GridViewColumn { Width = 90, Header = "Минимум", DisplayMemberBinding = new Binding("MinAmount"), }); view.Columns.Add(new GridViewColumn { Width = 90, Header = "Заказано", DisplayMemberBinding = new Binding("OrderedAmount"), }); view.Columns.Add(new GridViewColumn { Width = 90, Header = "Статус", DisplayMemberBinding = new Binding("Status"), }); #endregion var bgw = new BackgroundWorker() { WorkerReportsProgress = true }; bgw.ProgressChanged += (sender, args) => { if (m_waitingWindow != null) m_waitingWindow.SetState(args.UserState.ToString()); }; bgw.DoWork += (sender, args) => { var worker = (BackgroundWorker) sender; worker.ReportProgress(0, "Загрузка..."); var productRepository = DbManger.GetInstance().GetProductRepository(); var orderRepository = DbManger.GetInstance().GetOrderRepository(); List<Product> products; List<Order> orders; try { products = productRepository.GetAllFromAlbum(album); orders = orderRepository.GetOrdersForAlbum(album); } catch (Exception exception) { m_logger.ErrorException(exception); throw new BgWorkerException("Ошибка. Не удалось получить информацию по альбому."); } var result = new List<ProductListViewItem>(); foreach (Product product in products) { var ordered = orders.Where(order => order.ProductId == product.Id).Sum(order => order.Amount); result.Add(new ProductListViewItem(product) {OrderedAmount = ordered}); } result.Sort((a, b) => String.Compare(a.Title, b.Title, StringComparison.CurrentCultureIgnoreCase)); args.Result = result; }; bgw.RunWorkerCompleted += (sender, args) => { if (m_waitingWindow != null) { m_waitingWindow.Close(); m_waitingWindow = null; } var worker = sender as BackgroundWorker; if (worker != null) { lock (m_workersPool) { m_workersPool.Remove(worker); } } if(args.Cancelled) return; if (args.Error != null) { this.ShowError(args.Error.Message); return; } foreach (ProductListViewItem plvi in ((List<ProductListViewItem>)args.Result)) { lvDetails.Items.Add(plvi); } }; lock (m_workersPool) { m_workersPool.Add(bgw); } bgw.RunWorkerAsync(); m_waitingWindow = new WaitingWindow(this); m_waitingWindow.ShowDialog(); }
private void FillAlbumsListAsync() { var bg = new BackgroundWorker {WorkerReportsProgress = true, WorkerSupportsCancellation = true}; bg.ProgressChanged += (sender, args) => SetStatus(args.UserState.ToString()); bg.DoWork += (sender, args) => { var worker = sender as BackgroundWorker; worker.ReportProgress(0, "Инициализация"); DbManger db; try { db = DbManger.GetInstance(); } catch (Exception exception) { m_logger.ErrorException(exception); throw new BgWorkerException("Ошибка: Не удалось инициализировать БД"); } var albumRepo = db.GetAlbumsRepository(); List<Album> albums; try { albums = albumRepo.GetAll(); } catch (Exception e) { m_logger.ErrorException(e); throw new BgWorkerException("Не удалось получить список альбомов. Проверьте настройки БД"); } albums.Sort((a1, a2) => String.Compare(a1.GetCleanTitle(), a2.GetCleanTitle(), StringComparison.CurrentCultureIgnoreCase)); args.Result = albums; }; bg.RunWorkerCompleted += (sender, args) => { AlbumsView.Items.Clear(); SelectedAlbum = null; m_selectedView = ServiceTreeNodes.None; if (args.Cancelled) return; if (args.Error != null) { this.ShowError(args.Error.Message); return; } var albums = args.Result as List<Album>; if (albums != null) { var hiddens = m_settings.GetHiddenList(); foreach (Album album in albums) { if (hiddens.Contains(album.VkId)) continue; var tvi = CreateTreeItem(album, album.GetCleanTitle(), @"pack://*****:*****@"pack://application:,,,/Images/group.png"); tvi.Items.Add(usersNode); var prodsNode = CreateTreeItem(ServiceTreeNodes.AlbumProducts, "Товары", @"pack://*****:*****@"pack://application:,,,/Images/coins.png"); tvi.Items.Add(payNode); AlbumsView.Items.Add(tvi); } } SetStatus(); }; bg.RunWorkerAsync(); }
public WordExportFormatter(Album album) : base(album) { m_log = log4net.LogManager.GetLogger("WordExportFormatter"); }
private void AlbumsView_OnSelected(object sender, RoutedEventArgs e) { e.Handled = false; SetStatus(); HeaderedItemsControl item = null; if (e.Source is TextBlock) { var panel = (e.Source as TextBlock).Parent as StackPanel; if (panel == null) return; item = panel.Parent as HeaderedItemsControl; } else if (e.Source is TreeViewItem) { item = e.Source as HeaderedItemsControl; } else if (e.Source is Image) { var panel = (e.Source as Image).Parent as StackPanel; if (panel == null) return; item = panel.Parent as HeaderedItemsControl; } if (item == null || item.Parent == null) return; ClearDetailsView(); if (item.Tag is Album) { SelectedAlbum = item.Tag as Album; } else { SelectedAlbum = (item.Parent as HeaderedItemsControl).Tag as Album; } tbSearchBox.Clear(); if (item.Tag.Equals(ServiceTreeNodes.AlbumProducts)) { m_selectedView = ServiceTreeNodes.AlbumProducts; ShowAlbumProductsDetails(SelectedAlbum); } else if (item.Tag.Equals(ServiceTreeNodes.AlbumCustomers)) { m_selectedView = ServiceTreeNodes.AlbumCustomers; ShowAlbumCutomersDetails(SelectedAlbum); } else if (item.Tag.Equals(ServiceTreeNodes.AlbumPaymets)) { m_selectedView = ServiceTreeNodes.AlbumPaymets; ShowAlbumPaymentsDetails(SelectedAlbum); } else { m_selectedView = ServiceTreeNodes.None; } }