Click here to Skip to main content
15,886,622 members
Articles / Desktop Programming / WPF

C.B.R.

Rate me:
Please Sign up or sign in to vote.
4.96/5 (52 votes)
22 Oct 2012GPL329 min read 124.3K   1.8K   132  
Comic and electronic publication reader with library management, extended file conversion, and devices support.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CBR.Core.Helpers;
using System.Windows.Input;
using System.Net;
using System.Xml;
using System.Windows;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows.Data;
using System.Windows.Markup;
using System.Windows.Controls;
using System.Reflection;
using System.IO;

namespace CBR.ViewModels
{
    public class HomeViewModel : ViewModelBase
    {
        #region ----------------CONSTRUCTOR----------------

        public HomeViewModel()
		{
		}

		#endregion

        private List<Headline> _Items = null;
        public ICollectionView ItemsSource
        {
            get
            {
                if (_Items != null)
                {
                    return CollectionViewSource.GetDefaultView(_Items);
                }
                else
                    return null;
            }
        }

        /// <summary>
        /// Gets or sets whether the view is loading headlines.
        /// </summary>
        private bool _IsLoading = false;

        public bool IsLoading
        {
            get { return _IsLoading; }
            set
            {
                if (_IsLoading != value)
                {
                    _IsLoading = value;
                    RaisePropertyChanged("IsLoading");
                }
            }
        }

        /// <summary>
        /// Gets or sets whether the view has got error.
        /// </summary>
        private bool _HasError = true;

        public bool HasError
        {
            get { return _HasError; }
            set
            {
                if (_HasError != value)
                {
                    _HasError = value;
                    RaisePropertyChanged("HasError");
                }
            }
        }

        public string ApplicationVersion
        {
            get { return Assembly.GetEntryAssembly().GetName().Version.ToString(); }
        }

        #region ---------------- COMMANDS ----------------

        #region forward command
        private ICommand forwardCommand;
        public ICommand ForwardCommand
        {
            get
            {
                if (forwardCommand == null)
                    forwardCommand = new DelegateCommand<string>(
                        delegate(string param)
                        {
                            Mediator.Instance.NotifyColleagues(ViewModelMessages.ContextCommand,
                                new CommandContext() { CommandName = param, CommandParameter = null });
                        },
                        delegate(string param)
                        {
                            return true;
                        });
                return forwardCommand;
            }
        }
        #endregion
        #endregion

        #region --------------------METHODS--------------------

        /// <summary>
        /// Load the feed.
        /// </summary>
        public void LoadFeed()
        {
			if (_Items == null)
			{
				Uri uri = null;

				if (!string.IsNullOrEmpty(CBR.Properties.Settings.Default.HeadlineUrl) &&
					Uri.TryCreate(CBR.Properties.Settings.Default.HeadlineUrl, UriKind.Absolute, out uri))
				{
					this.GetFeed(new Uri(CBR.Properties.Settings.Default.HeadlineUrl, UriKind.Absolute));
				}
			}
			else IsLoading = false;
        }

        /// <summary>
        /// Gets a feed from a Uri.
        /// </summary>
        /// <param name="uri">The Uri of the feed.</param>
        private void GetFeed(Uri uri)
        {
            IsLoading = true;
            WebClient client = new WebClient();
            client.OpenReadCompleted += new OpenReadCompletedEventHandler(this.Client_OpenReadCompleted);
            client.OpenReadAsync(uri);
            //Stream test = null;

            //try
            //{
            //    test = client.OpenRead(uri);

            //    if (test != null)
            //    {
            //        try
            //        {
            //            _Items = new List<Headline>();

            //            HeadlineCollection col = (HeadlineCollection)XmlHelper.Deserialize(test, typeof(HeadlineCollection));
            //            _Items.AddRange(col.HeadlineItems);

            //            RaisePropertyChanged("ItemsSource");

            //            HasError = false;
            //        }
            //        catch (XmlException exception)
            //        {
            //            HasError = true;
            //        }
            //    }
            //    else HasError = true;
            //}
            //catch( Exception err ) 
            //{
            //    HasError = true;
            //}

            //IsLoading = false;
        }

        /// <summary>
        /// Gets the response, and parses as a feed.
        /// </summary>
        /// <param name="sender">The web client.</param>
        /// <param name="e">Open Read Completed Event Args</param>
        private void Client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            if (e.Error == null && e.Result != null)
            {
                try
                {
                    _Items = new List<Headline>();

                    HeadlineCollection col = (HeadlineCollection)XmlHelper.Deserialize(e.Result, typeof(HeadlineCollection));
                    _Items.AddRange(col.HeadlineItems);

                    RaisePropertyChanged("ItemsSource");

                    HasError = false;
                }
                catch (XmlException exception)
                {
                    StringBuilder errorMessage = new StringBuilder();
                    errorMessage.AppendLine("An error occured:");
                    errorMessage.AppendLine("   " + exception.Message);
                    errorMessage.AppendLine("       " + exception.StackTrace);
                    HasError = true;
                }
            }
            else if (e.Error != null)
            {
                StringBuilder errorMessage = new StringBuilder();
                errorMessage.AppendLine("An error occured:");
                errorMessage.AppendLine("   " + e.Error.Message);
                errorMessage.AppendLine("       " + e.Error.StackTrace);
                HasError = true;
            }

            IsLoading = false;
        }
        
        #endregion
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The GNU General Public License (GPLv3)


Written By
Architect
France France
WPF and MVVM fan, I practice C # in all its forms from the beginning of the NET Framework without mentioning C ++ / MFC and other software packages such as databases, ASP, WCF, Web & Windows services, Application, and now Core and UWP.
In my wasted hours, I am guilty of having fathered C.B.R. and its cousins C.B.R. for WinRT and UWP on the Windows store.
But apart from that, I am a great handyman ... the house, a rocket stove to heat the jacuzzi and the last one: a wood oven for pizza, bread, and everything that goes inside

https://guillaumewaser.wordpress.com/
https://fouretcompagnie.wordpress.com/

Comments and Discussions