Click here to Skip to main content
Click here to Skip to main content
Add your own
alternative version

GoalBook - A Hybrid Smart Client

, 25 Sep 2009 CPOL
A WPF hybrid smart client that synchronises your goals with the Toodledo online To-do service.
GoalBook.zip
GoalBook
Dependencies
CAG WPF 2
Microsoft.Practices.Composite.dll
Microsoft.Practices.Composite.Presentation.dll
Microsoft.Practices.Composite.UnityExtensions.dll
Microsoft.Practices.ObjectBuilder2.dll
Microsoft.Practices.ServiceLocation.dll
Microsoft.Practices.Unity.dll
vssver2.scc
CSLA
Csla.dll
Csla.XmlSerializers.dll
vssver2.scc
Infragistics
Infragistics3.Wpf.DataPresenter.v9.1.Express.dll
Infragistics3.Wpf.Editors.v9.1.Express.dll
Infragistics3.Wpf.v9.1.Express.dll
vssver2.scc
WPFToolkit
vssver2.scc
WPFToolkit.dll
GoalBook.Controls
CheckedList
vssver2.scc
Properties
vssver2.scc
vssver2.scc
GoalBook.Goals
GoalBook.Goals.csproj.user
Properties
vssver2.scc
Views
vssver2.scc
vssver2.scc
GoalBook.Infrastructure
Comparers
vssver2.scc
Constants
vssver2.scc
Controls
Converters
vssver2.scc
Enums
vssver2.scc
Events
vssver2.scc
GoalBook.Infrastructure.csproj.user
Helpers
vssver2.scc
Interfaces
vssver2.scc
ObjectModel
vssver2.scc
Printing
vssver2.scc
Properties
vssver2.scc
vssver2.scc
GoalBook.Notes
GoalBook.Notes.csproj.user
Properties
vssver2.scc
Resources
arrow_redo.png
arrow_undo.png
cut.png
page_copy.png
paste_plain.png
text_bold.png
text_indent.png
text_indent_remove.png
text_italic.png
text_list_bullets.png
text_list_numbers.png
vssver2.scc
world_link.png
Views
vssver2.scc
vssver2.scc
GoalBook.Public
Encryption
vssver2.scc
HtmlConverter
vssver2.scc
HtmlParser
vssver2.scc
Misc
vssver2.scc
Properties
vssver2.scc
vssver2.scc
GoalBook.Shell
App.ico
Commands
vssver2.scc
GoalBook.Shell.csproj.user
Journal.ico
Journal48.ico
Misc
vssver2.scc
Modules
vssver2.scc
Properties
licenses.licx
vssver2.scc
Resources
arrow_refresh.png
arrow_undo.png
checked.gif
cross.png
disk.png
email.png
erase.png
error.png
exclamation.png
flag_red.png
group.png
help.png
information.png
magnifier.png
page_red.png
pencil.png
printer.png
user.png
vssver2.scc
Wave.jpg
world.png
world_link.png
Services
vssver2.scc
Splash.png
Views
vssver2.scc
vssver2.scc
Windows
vssver2.scc
GoalBook.snk
GoalBook.Synchronisation
Events
vssver2.scc
Properties
vssver2.scc
ToodleDo
vssver2.scc
vssver2.scc
GoalBook.Tasks
Controls
vssver2.scc
Properties
vssver2.scc
Views
vssver2.scc
vssver2.scc
vssver2.scc
//===============================================================================
// Goal Book.
// Copyright © 2009 Mark Brownsword. 
//===============================================================================

#region Using Statements
using System;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using GoalBook.Infrastructure.Constants;
using GoalBook.Infrastructure.Converters;
using GoalBook.Infrastructure.ObjectModel;
using GoalBook.Infrastructure;
#endregion

namespace GoalBook.Synchronisation.ToodleDo
{
    internal class TaskSynchronisor : Synchronisor<TaskList>
    {
        #region Constants and Enums

        //Task constants
        private const string TASK = "task";
        private const string TASK_ID = "id";
        private const string TASK_PARENT = "parent";
        private const string TASK_CHILDREN = "children";
        private const string TASK_TITLE = "title";
        private const string TASK_TAG = "tag";            
        private const string TASK_FOLDER = "folder";
        private const string TASK_CONTEXT = "context";
        private const string TASK_GOAL = "goal";
        private const string TASK_TIMER = "timer";
        private const string TASK_TIMER_VAL = "timerval";
        private const string TASK_ADDED = "added";
        private const string TASK_MODIFIED = "modified";
        private const string TASK_START = "startdate";
        private const string TASK_DUE = "duedate";
        private const string TASK_DUE_MODIFIER = "modifier";
        private const string TASK_DUETIME = "duetime";
        private const string TASK_STARTTIME = "starttime";
        private const string TASK_COMPLETED = "completed";
        private const string TASK_COMPLETED_ON = "completedon";
        private const string TASK_RESCHEDULE = "reschedule";
        private const string TASK_REPEAT = "repeat";
        private const string TASK_REPEAT_ADVANCED = "rep_advanced";
        private const string TASK_STATUS = "status";
        private const string TASK_STAR = "star";
        private const string TASK_PRIORITY = "priority";
        private const string TASK_LENGTH = "length";        
        private const string TASK_NOTE = "note";
                
        //URL constants
        private const string GET_DELETED_TASKS_URL = @"http://api.toodledo.com/api.php?method=getDeleted;key={0};after={1}";
        private const string GET_TASKS_URL = @"http://api.toodledo.com/api.php?method=getTasks;key={0};modafter={1}";
        private const string ADD_TASK_URL = @"http://api.toodledo.com/api.php?method=addTask;key={0}{1}";
        private const string EDIT_TASK_URL = @"http://api.toodledo.com/api.php?method=editTask;key={0};id={1}{2}";
        private const string DELETE_TASK_URL = @"http://api.toodledo.com/api.php?method=deleteTask;key={0};id={1}";
               

        /*    Add Task    
        title={1};
        tag={2};
        folder={3};
        context={4};
        goal={5};
        parent={6};
        duedate={7};
        startdate={8};
        duetime={9};
        starttime={10};
        repeat={11};
        rep_advanced={12};
        status={13};
        length={14};
        priority={15};
        star={16};
        note={17};      
         */

        

        /* Edit Task
        id={1};
        title={2};
        tag={3};
        folder={4};
        context={5};
        goal={6};
        timer={7};
        timerval={8}; 
        parent={9}; 
        completed={10}; 
        completedon={11}; 
        reschedule={12}; 
        duedate={13};
        startdate={14};
        duetime={15};
        starttime={16};
        repeat={17};
        rep_advanced={18};
        status={19};
        length={20}; 
        priority={21};
        star={22};
        note={23}; 
         */
         

        #endregion

        #region Inner Classes and Structures
        #endregion

        #region Delegates and Events
        #endregion

        #region Instance and Shared Fields
        /// <summary>
        /// List of folders.
        /// </summary>
        private FolderList folders;

        /// <summary>
        /// Declaration for ToodledoToXamlConverter.
        /// </summary>
        private ToodledoToXamlConverter converter;
        #endregion

        #region Constructors
        /// <summary>
        /// Constructor.
        /// </summary>        
        internal TaskSynchronisor(ToodledoConnector connector, FolderList folders)
            : base(connector)
        {
            this.folders = folders;
            this.converter = new ToodledoToXamlConverter();
        }
        #endregion

        #region Properties
        #endregion

        #region Private and Protected Methods
        /// <summary>
        /// Get DueTime.
        /// </summary>
        /// <param name="input">input parameter</param>
        /// <returns>TwelveHourTimeInfo instance</returns>
        private TimeInfo? GetDueTime(string input)
        {
            TimeInfo result;
            if (TimeInfo.TryParse(input, out result))
            {
                return result;
            }

            return null;
        }

        /// <summary>
        /// Get Adjust From ServerTime.
        /// </summary>
        /// <param name="input">input parameter</param>
        /// <returns>DateTime or null</returns>
        private DateTime? GetAdjustFromServerTime(string input)
        {
            DateTime? result = GetDateTime(input);

            if (result.HasValue)
            {
                return Connector.AdjustFromServerTime(result.Value);
            }

            return null;
        }

        /// <summary>
        /// Get DateTime from string input.
        /// </summary>
        /// <param name="date">date parameter</param>
        /// <returns>DateTime</returns>
        private DateTime? GetDateTime(string input)
        {
            DateTime result;
            if (DateTime.TryParse(input, out result))
            {
                return result;
            }

            return null;
        }  

        /// <summary>
        /// Get Task from list.
        /// </summary>
        /// <param name="noteList">TaskList</param>
        /// <param name="id">Identifier for the task</param>
        /// <returns>Note</returns>
        private Task GetTask(TaskList taskList, int id)
        {
            var targetList = from g in taskList where g.ExternalIdentifier == id select g;
            foreach (Task task in targetList)
            {
                return task; //One only can exist.
            }

            return null;
        }

        /// <summary>
        /// Get FolderID for specified identifier.
        /// </summary>
        /// <param name="id">id parameter</param>
        /// <returns>Folder Guid</returns>
        private Guid GetFolderID(int id)
        {
            var targetList = from g in folders where g.ExternalIdentifier == id select g;
            foreach (Folder folder in targetList)
            {
                return folder.FolderID; //One only can exist.
            }

            return Guid.Empty;
        }

        /// <summary>
        /// GetGoalID.
        /// </summary>
        /// <param name="id">id parameter</param>
        /// <returns>Guid</returns>
        private Guid GetGoalID(int id)
        {
            return Guid.Empty;
        }

        /// <summary>
        /// GetContextID.
        /// </summary>
        /// <param name="id">id parameter</param>
        /// <returns>Guid</returns>
        private Guid GetContextID(int id)
        {
            return Guid.Empty;
        }

        /// <summary>
        /// Get Folder ExternalIdentifier.
        /// </summary>
        /// <param name="guid">FolderID parameter</param>
        /// <returns>External Identifier for specified folder</returns>
        private int GetFolderExternalIdentifier(Guid folderID)
        {
            var targetList = from g in folders where g.FolderID == folderID select g;
            foreach (Folder folder in targetList)
            {
                return folder.ExternalIdentifier; //One only can exist.
            }

            return 0;
        }
                
        /// <summary>
        /// Sync Tasks Client. Upload local changes to Toodledo.
        /// </summary>
        /// <param name="noteList">TaskList parameter</param>
        private void SyncTasksClient(TaskList taskList)
        {
            // Delete.
            var deleteList = from g in taskList.DeletedPendingSync select g;
            foreach (Task task in deleteList.ToArray())
            {
                string deleteTaskURL = string.Format(DELETE_TASK_URL, Connector.GetSessionKey(), task.ExternalIdentifier);
                XDocument result = Connector.MakeServerCall(deleteTaskURL, ToodledoConnector.SyncMethod.Post);

                if (result.Element(SUCCESS) != null)
                {
                    int deleteResult = 0;
                    if (int.TryParse(result.Element(SUCCESS).Value, out deleteResult) && deleteResult == 1)
                    {
                        taskList.DeletedPendingSync.Remove(task);
                    }
                }
                else
                {
                    /*<error>Invalid note ID number</error>*/
                }
            }

            // Initialise StringBuilder for Add/Edit URL.
            StringBuilder urlBuilder = new StringBuilder();

            // Add.
            var addList = from g in taskList where g.ExternalIdentifier == 0 select g;
            foreach (Task task in addList)
            {
                urlBuilder.Remove(0, urlBuilder.Length); 
                urlBuilder.Append(GetTaskParameter(TASK_TITLE, task.Title));
                urlBuilder.Append(GetTaskParameter(TASK_TAG, task.Tag));
                urlBuilder.Append(GetTaskParameter(TASK_FOLDER, this.GetFolderExternalIdentifier(task.FolderID)));
                //context={4};
                //goal={5};
                //parent={6};
                urlBuilder.Append(GetTaskParameter(TASK_DUE, string.Concat(task.DueModifier, task.Due.HasValue ?
                    task.Due.Value.ToString(SynchronisationConstants.SYNC_DATE_FORMAT) : null)));
                //startdate={8};
                urlBuilder.Append(GetTaskParameter(TASK_DUETIME, task.DueTime.ToString() == string.Empty ? "0" : task.DueTime.ToString()));
                //starttime={10};
                //repeat={11};
                //rep_advanced={12};
                //status={13};
                //length={14};
                //priority={15};
                //star={16};
                //note={17}; 

                string addTaskURL = string.Format(
                    ADD_TASK_URL,
                    Connector.GetSessionKey(),
                    urlBuilder.ToString());

                XDocument result = this.Connector.MakeServerCall(addTaskURL, ToodledoConnector.SyncMethod.Post);

                if (result.Element(ADDED) != null)
                {
                    int addResult = 0;
                    if (int.TryParse(result.Element(ADDED).Value, out addResult) && addResult > 0)
                    {
                        task.ExternalIdentifier = addResult;
                        task.SyncRequired = false;
                    }
                }
                else
                {
                    /*TODO: Log <error></error>*/
                }
            }

            // Edit
            var editList = from g in taskList where g.ExternalIdentifier > 0 && g.SyncRequired select g;
            foreach (Task task in editList)
            {
                urlBuilder.Remove(0, urlBuilder.Length);
                urlBuilder.Append(GetTaskParameter(TASK_TITLE, task.Title));
                urlBuilder.Append(GetTaskParameter(TASK_TAG, task.Tag));
                urlBuilder.Append(GetTaskParameter(TASK_FOLDER, this.GetFolderExternalIdentifier(task.FolderID)));
                //context={5};
                //goal={6};
                //timer={7};
                //timerval={8}; 
                //parent={9}; 
                //completed={10}; 
                //completedon={11}; 
                //reschedule={12}; 
                urlBuilder.Append(GetTaskParameter(TASK_DUE, string.Concat(task.DueModifier, task.Due.HasValue ? 
                    task.Due.Value.ToString(SynchronisationConstants.SYNC_DATE_FORMAT) : null)));
                //startdate={14};
                urlBuilder.Append(GetTaskParameter(TASK_DUETIME, task.DueTime.ToString() == string.Empty ? "0" : task.DueTime.ToString()));
                //starttime={16};
                //repeat={17};
                //rep_advanced={18};
                //status={19};
                //length={20}; 
                //priority={21};
                //star={22};
                //note={23}; 

                string editTaskURL = string.Format(
                    EDIT_TASK_URL, 
                    Connector.GetSessionKey(), 
                    task.ExternalIdentifier,
                    urlBuilder.ToString());

                XDocument result = this.Connector.MakeServerCall(editTaskURL, ToodledoConnector.SyncMethod.Post);

                if (result.Element(SUCCESS) != null)
                {
                    int editResult = 0;
                    if (int.TryParse(result.Element(SUCCESS).Value, out editResult) && editResult == 1)
                    {
                        task.SyncRequired = false;
                    }
                }
                else
                {
                    /*TODO: Log <error></error>*/
                }
            }
        }

        private string GetTaskParameter(string parameter, object value)
        {
            if (value == null || string.IsNullOrEmpty(value.ToString()))
            {
                return string.Empty;
            }

            return string.Format(";{0}={1}", parameter, Connector.UrlEncodeParameterValue(value));
        }
        
        /// <summary>
        /// Sync Tasks Server. Retrieves the tasks from Toodledo.
        /// </summary>
        /// <param name="noteList">TaskList</param>        
        private void SyncTasksServer(TaskList taskList)
        {
            // Delete    
            if (taskList.LastServerTaskEdit > DateTime.MinValue)
            {
                string deletedTasksURL = string.Format(GET_DELETED_TASKS_URL, Connector.GetSessionKey(), Connector.AdjustToServerTime(taskList.LastServerTaskEdit).ToString(SynchronisationConstants.SYNC_DATE_FORMAT));
                XDocument serverDeletedList = Connector.MakeServerCall(deletedTasksURL);

                var orderedServerDeletedList = from s in serverDeletedList.Descendants(TASK) orderby s.Element(TASK_ID).Value select s;
                foreach (XElement element in orderedServerDeletedList)
                {
                    Task target = GetTask(taskList, int.Parse(element.Element(TASK_ID).Value));
                    taskList.Remove(target);
                }
            }

            // Add, Edit.
            string tasksURL = string.Format(GET_TASKS_URL, Connector.GetSessionKey(), Connector.AdjustToServerTime(taskList.LastServerTaskEdit).ToString(SynchronisationConstants.SYNC_DATE_FORMAT));                       
            if (taskList.LastServerTaskEdit == DateTime.MinValue)
            {
                // For first time synchronisation retrieve 
                // only tasks marked as not completed. 
                tasksURL += ";notcomp=1";
            }

            XDocument serverList = Connector.MakeServerCall(tasksURL);
            
            var orderedServerList = from s in serverList.Descendants(TASK) orderby s.Element(TASK_ID).Value select s;
            foreach (XElement element in orderedServerList)
            {
                Task target = GetTask(taskList, int.Parse(element.Element(TASK_ID).Value));
                if (target == null)
                {                    
                    // Add   
                    int parent = 0; // int.Parse(element.Element(TASK_PARENT).Value);
                    int children = int.Parse(element.Element(TASK_CHILDREN).Value);
                    string title = element.Element(TASK_TITLE).Value;
                    string tag = element.Element(TASK_TAG).Value;
                    Guid folderID = GetFolderID(int.Parse(element.Element(TASK_FOLDER).Value));
                    Guid contextID = GetContextID(int.Parse(element.Element(TASK_CONTEXT).Attribute(TASK_ID).Value));
                    Guid goalID = GetGoalID(int.Parse(element.Element(TASK_GOAL).Attribute(TASK_ID).Value));
                    DateTime added = Connector.AdjustFromServerTime(Convert.ToDateTime(element.Element(TASK_ADDED).Value));
                    DateTime? modified = GetAdjustFromServerTime(element.Element(TASK_MODIFIED).Value);
                    DateTime? start = GetDateTime(element.Element(TASK_START).Value);
                    DateTime? due = GetDateTime(element.Element(TASK_DUE).Value);
                    string dueModifier = element.Element(TASK_DUE).Attribute(TASK_DUE_MODIFIER).Value;
                    TimeInfo? duetime = GetDueTime(element.Element(TASK_DUETIME).Value);
                    string starttime = element.Element(TASK_STARTTIME).Value;
                    DateTime? completed = GetAdjustFromServerTime(element.Element(TASK_COMPLETED).Value);
                    int repeat = int.Parse(element.Element(TASK_REPEAT).Value);
                    string rep_advanced = element.Element(TASK_REPEAT_ADVANCED).Value;
                    int status = int.Parse(element.Element(TASK_STATUS).Value);
                    bool star = element.Element(TASK_STAR).Value == NUMERIC_TRUE;
                    int priority = int.Parse(element.Element(TASK_PRIORITY).Value);
                    int length = int.Parse(element.Element(TASK_LENGTH).Value);
                    int timer = int.Parse(element.Element(TASK_TIMER).Value);
                    string note = element.Element(TASK_NOTE).Value;
                    int externalIdentifier = int.Parse(element.Element(TASK_ID).Value);

                    if (!completed.HasValue)
                    {
                        Task addTask = new Task(Guid.NewGuid(), parent, children, title, tag, folderID, contextID, goalID, added, modified, start,
                            due, dueModifier, duetime, starttime, completed, repeat, rep_advanced, status, star, priority, length, timer, note, externalIdentifier);
                        addTask.SyncRequired = false;
                    
                        taskList.Add(addTask);
                        taskList.EndNew(taskList.IndexOf(addTask));
                    }
                }
                else
                {
                    // Edit
                    Task editTask = target.Clone();

                    editTask.ParentTask = 0; // int.Parse(element.Element(TASK_PARENT).Value);
                    editTask.Children = int.Parse(element.Element(TASK_CHILDREN).Value);
                    editTask.Title = element.Element(TASK_TITLE).Value;
                    editTask.Tag = element.Element(TASK_TAG).Value;
                    editTask.FolderID = GetFolderID(int.Parse(element.Element(TASK_FOLDER).Value));
                    editTask.ContextID = GetContextID(int.Parse(element.Element(TASK_CONTEXT).Attribute(TASK_ID).Value));
                    editTask.GoalID = GetGoalID(int.Parse(element.Element(TASK_GOAL).Attribute(TASK_ID).Value));                
                    editTask.Modified = Connector.AdjustFromServerTime(Convert.ToDateTime(element.Element(TASK_MODIFIED).Value));
                    editTask.Start = GetAdjustFromServerTime(element.Element(TASK_START).Value);
                    editTask.Due = GetAdjustFromServerTime(element.Element(TASK_DUE).Value);
                    editTask.DueModifier = element.Element(TASK_DUE).Attribute(TASK_DUE_MODIFIER).Value;
                    editTask.DueTime = GetDueTime(element.Element(TASK_DUETIME).Value);
                    editTask.StartTime = element.Element(TASK_STARTTIME).Value;
                    editTask.Completed = GetAdjustFromServerTime(element.Element(TASK_COMPLETED).Value);
                    editTask.Repeat = int.Parse(element.Element(TASK_REPEAT).Value);
                    editTask.RepeatAdvanced = element.Element(TASK_REPEAT_ADVANCED).Value;
                    editTask.Status = int.Parse(element.Element(TASK_STATUS).Value);
                    editTask.Star = element.Element(TASK_STAR).Value == NUMERIC_TRUE;
                    editTask.Priority = int.Parse(element.Element(TASK_PRIORITY).Value);
                    editTask.Length = int.Parse(element.Element(TASK_LENGTH).Value);
                    editTask.Timer = int.Parse(element.Element(TASK_TIMER).Value);
                    editTask.Note = element.Element(TASK_NOTE).Value;

                    if (editTask.Completed.HasValue)
                    {
                        taskList.Remove(target);
                    }
                    else
                    {
                        taskList[taskList.IndexOf(target)].MapFields(editTask);
                        taskList[taskList.IndexOf(target)].SyncRequired = false;
                    }
                }
            }
        }        
        #endregion

        #region Public and internal Methods
        #endregion

        #region Event Handlers
        #endregion

        #region Base Class Overrides
        /// <summary>
        /// Sync the TaskList.
        /// </summary>
        /// <param name="list">TaskList</param>
        /// <returns>SyncTokenInfo</returns>
        internal override void Sync(TaskList taskList)
        {            
            DateTime savedLastServerTaskEdit = taskList.LastServerTaskEdit;

            if (taskList.SyncRequired)
            {
                // Client has changes.                
                SyncTasksClient(taskList);
            }

            if (Connector.LastTaskEdit > savedLastServerTaskEdit)
            {
                // Server has changes.                
                SyncTasksServer(taskList);
            }                                    
        }               
        #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 Code Project Open License (CPOL)

Share

About the Author

Mark Brownsword
Software Developer (Senior)
Australia Australia
I've been working as a software developer since 2000 and hold a Bachelor of Business degree from The Open Polytechnic of New Zealand. Computers are for people and I aim to build applications for people that they would want to use.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.141216.1 | Last Updated 25 Sep 2009
Article Copyright 2009 by Mark Brownsword
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid