Beispiel #1
0
        public static async Task <TaskListItem> RetryAddTaskList(IList <object> obj)
        {
            var restRequest = new RestRequest(Method.POST)
            {
                RequestFormat = DataFormat.Json,
                Resource      = "https://www.googleapis.com/tasks/v1/users/@me/lists",
                Timeout       = GTaskSettings.RequestTimeout
            };
            var ignored = "{title:\"" + ((TaskListItem)obj[0]).title + "\"}";

            restRequest.AddParameter("application/json", ignored, ParameterType.RequestBody);

            //Make the call
            var restResponse = await GTaskSettings.ExecuteRestTask(restRequest);

            try
            {
                if (restResponse.StatusCode == HttpStatusCode.OK)
                {
                    if (obj.Count > 1)
                    {
                        var callback = obj[1] as Action <bool>;
                        if (callback != null)
                        {
                            callback(true);
                        }
                    }

                    var TaskListObject = JObject.Parse(restResponse.Content);

                    var TaskList = new TaskListItem((string)TaskListObject.SelectToken("title"),
                                                    (string)TaskListObject.SelectToken("id"),
                                                    (string)TaskListObject.SelectToken("kind"),
                                                    (string)TaskListObject.SelectToken("selfLink"),
                                                    (string)TaskListObject.SelectToken("updated"));

                    // Submit new task list to local storage too
                    List <TaskListItem> list = await TaskListHelper.GetTaskListFromApplicationStorage();

                    TaskListItem newList = new TaskListItem((string)TaskListObject.SelectToken("title"),
                                                            (string)TaskListObject.SelectToken("id"),
                                                            (string)TaskListObject.SelectToken("kind"),
                                                            (string)TaskListObject.SelectToken("selfLink"),
                                                            (string)TaskListObject.SelectToken("updated"));

                    // Add this new list to the local list
                    list.Add(newList);
                    // Submit the list to local storage
                    await TaskListHelper.SubmitToLocalStorage(list);

                    return(TaskList);
                }
            }
            catch
            {
            }

            return(null);
        }
Beispiel #2
0
        public static async Task ClearCompletedTasks(string id)
        {
            const string message     = "Hmmm... I am having a hard time Clearing your Completed Tasks, can you try again?";
            var          restRequest = new RestRequest(Method.POST)
            {
                Resource = String.Format("https://www.googleapis.com/tasks/v1/lists/" + id + "/clear"),
                Timeout  = GTaskSettings.RequestTimeout
            };
            var restResponse = await GTaskSettings.ExecuteRestTask(restRequest);

            try
            {
                if (restResponse.StatusCode == HttpStatusCode.NoContent)
                {
                    //success - hide completed locally
                    // Update the task locally
                    List <TaskListItem> lists = await TaskListHelper.GetTaskListFromApplicationStorage();

                    foreach (TaskListItem list in lists.Where(x => x.id == id))
                    {
                        foreach (TaskItem task in list.taskList.Where(x => x.status == "completed" && (x.hidden == null || x.hidden == "true")))
                        {
                            task.hidden  = "True";
                            task.updated = DateTime.UtcNow.ToString("yyyy-MM-dd'T'hh:mm:ss.00Z"); // DateTime.UtcNow.ToString();
                        }
                    }

                    // Resubmit the list to local storage
                    await TaskListHelper.SubmitToLocalStorage(lists);
                }
                else
                {
                    if (GTaskSettings.MsgError)
                    {
                        MessageBox.Show(message);
                    }
                }
            }
            catch
            {
                if (GTaskSettings.MsgError)
                {
                    MessageBox.Show(message);
                }
            }
        }
Beispiel #3
0
        public static async Task <bool> RemoveHidden()
        {
            try {
                // Grap the local task lists to remove all the Hidden tasks
                List <TaskListItem> lists = await TaskListHelper.GetTaskListFromApplicationStorage();

                foreach (TaskListItem list in lists)
                {
                    list.taskList.RemoveAll(x => x.hidden == "True");
                }

                // Resubmit the list to local storage
                await TaskListHelper.SubmitToLocalStorage(lists);

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Beispiel #4
0
        public static async Task <bool> RefreshData(bool alertWhenNoConnection = false, string specificList = null, bool refresh = false)
        {
            try
            {
                // Create a list to hold the local data
                List <Model.TaskListItem> localStorageList = await TaskListHelper.GetTaskListFromApplicationStorage(false);

                if (localStorageList == null)
                {
                    localStorageList = new List <Model.TaskListItem>();
                }

                // Create a list to hold the data from the api
                // If no data locally then populate it, else if AutoRefreshLists or AutoRefreshTasks = true then get data
                // Goal is to only get Google data when needed

                // Create a final list to hold the results for local storage
                List <Model.TaskListItem> finalList = new List <Model.TaskListItem>();

                // Get the settings
                var settings = IsolatedStorageSettings.ApplicationSettings;

                // Sync w/ google?
                bool googleSync = false;

                List <Model.TaskListItem> googleApiList = null;
                if (AutoRefreshLists || AutoRefreshTasks || localStorageList.Count == 0 || refresh || GTaskSettings.FirstRun == true)
                {
                    googleApiList = await TaskListHelper.LoadTaskDataFromApi(alertWhenNoConnection, null);// specificList);
                }
                else
                {
                    //if (specificList != null)
                    //{
                    //    localStorageList.RemoveAll(x => x.id != specificList);
                    //    finalList = localStorageList;
                    //    goto finish;
                    //}
                    //else
                    //{
                    finalList = localStorageList;
                    goto finish;
                    //}
                }

                // If the google api list returns null then we must assume that we can't get a connection, so error out
                if (googleApiList == null)
                {
                    return(false);
                }
                googleSync = true;

                // Get the last sync date
                DateTime lastSyncDate = DateTime.Parse("1/1/1901");
                if (settings.Contains("LastSyncDate"))
                {
                    DateTime.TryParse(settings["LastSyncDate"].ToString(), out lastSyncDate);
                }

                // Loop through the two lists and check if any changes need to be synced
                foreach (Model.TaskListItem lSList in localStorageList)
                {
                    // Create a boolean to determine if we need to reorder tasks
                    bool reOrderTasks = false;

                    // Look for a corresponding list in the API
                    if (googleApiList.Where(x => x.id == lSList.id).Count() > 0)
                    {
                        // Get the corresponding google api list
                        Model.TaskListItem gAList = googleApiList.Where(x => x.id == lSList.id).First();

                        // Remove this list from the google api list to narrow things down
                        googleApiList.RemoveAll(x => x.id == gAList.id);

                        // Check if the titles are the same
                        if (lSList.title != gAList.title)
                        {
                            // Check which one was more recently updated
                            if (DateTime.Parse(lSList.updated) > DateTime.Parse(gAList.updated))
                            {
                                // Set the new title for the ga list
                                gAList.title = lSList.title;

                                // Update the list in the api
                                await TaskListHelper.RetryUpdateList(new List <object> {
                                    gAList
                                });
                            }
                            else if (DateTime.Parse(lSList.updated) <= DateTime.Parse(gAList.updated))
                            {
                                // Set the new title for the ls list
                                lSList.title = gAList.title;
                            }
                        }

                        // Create a final TaskListtem
                        Model.TaskListItem finalTaskListItem = new Model.TaskListItem();

                        //Convert to universal
                        string lSListupdated = Universal.ConvertToUniversalDate(lSList.updated);
                        string gAListupdated = Universal.ConvertToUniversalDate(gAList.updated);
                        //string lSListupdatedFormat = (DateTime)lSListupdated.ToString("MM/dd/yyyy hh:mm:ss");

                        // Set the necessary properties
                        finalTaskListItem.updated  = (DateTime.Parse(lSListupdated) > DateTime.Parse(gAListupdated)) ? lSList.updated : gAList.updated;
                        finalTaskListItem.title    = lSList.title;
                        finalTaskListItem.id       = lSList.id;
                        finalTaskListItem.selfLink = gAList.selfLink;
                        finalTaskListItem.kind     = gAList.kind;

                        // The lists are the same now but lets compare the individual tasks
                        #region Tasks
                        foreach (Model.TaskItem lSItem in lSList.taskList)
                        {
                            if (lSItem == null)
                            {
                                continue;
                            }

                            // Check if there is a corresponding task in the gAList
                            if (gAList.taskList.Where(x => x.id == lSItem.id).Count() > 0)
                            {
                                // Get the task from the gAList
                                Model.TaskItem gAItem = gAList.taskList.Where(x => x.id == lSItem.id).First();

                                // If the positions do not match then we need to update them all
                                if (lSItem.position != gAItem.position)
                                {
                                    reOrderTasks = true;
                                }

                                // Remove the gAItem from the gAList to narrow things down
                                gAList.taskList.RemoveAll(x => x.id == gAItem.id);

                                //Get due dates and compare formatted correctly
                                //local vars
                                string lSItemdue       = Universal.ConvertToUniversalDate(lSItem.due);
                                string lSItemupdated   = Universal.ConvertToUniversalDate(lSItem.updated);
                                string lSItemcompleted = Universal.ConvertToUniversalDate(lSItem.completed);
                                //string lSItemnotes = lSItem.notes;
                                //string lSItemtitle = lSItem.title;

                                //google vars
                                string gAItemdue       = Universal.ConvertToUniversalDate(gAItem.due);
                                string gAItemupdated   = Universal.ConvertToUniversalDate(gAItem.updated);
                                string gAItemcompleted = Universal.ConvertToUniversalDate(gAItem.completed);
                                //string gAItemnotes = gAItem.notes;
                                //string gAItemtitles = gAItem.title;

                                // Now we check the properties of the item, get the more recently updated one
                                if (DateTime.Parse(lSItemupdated) > DateTime.Parse(gAItemupdated) && (lSItemcompleted != gAItemcompleted ||
                                                                                                      lSItem.deleted != gAItem.deleted || lSItemdue != gAItemdue ||
                                                                                                      lSItem.hidden != gAItem.hidden || lSItem.kind != gAItem.kind ||
                                                                                                      lSItem.notes != gAItem.notes || lSItem.parent != gAItem.parent ||
                                                                                                      lSItem.position != gAItem.position || lSItem.status != gAItem.status ||
                                                                                                      lSItem.title != gAItem.title))
                                {
                                    // The local storage item was updated more recently, submit it to the api
                                    await TaskHelper.RetryUpdateTask(new List <object> {
                                        lSItem
                                    });

                                    // Check if we need ot update the status specifically
                                    if (lSItem.status != gAItem.status)
                                    {
                                        string due = null;
                                        if (lSItemdue != null)
                                        {
                                            due = Convert.ToDateTime(Universal.ConvertToUniversalDate(lSItem.due)).ToString("yyyy-MM-dd'T'hh:mm:ss.00Z");
                                        }
                                        bool isChecked = false;
                                        if (lSItem.status == "completed")
                                        {
                                            isChecked = true;
                                        }

                                        await TaskHelper.UpdateTaskStatus(lSList.id, lSItem.id, lSItemdue, isChecked);
                                    }

                                    // Add the lSItem to the final list
                                    finalTaskListItem.taskList.Add(lSItem);
                                }
                                else
                                {
                                    // The item was updated more recently on a remote device, simply add it to the final list
                                    finalTaskListItem.taskList.Add(gAItem);
                                }
                            }
                            else
                            {
                                // There was no corresponding item in the list from the google api
                                // Check if the item was added while in offline mode
                                if (settings.Contains("Task_" + lSItem.id + "_Action") && settings.Contains("Task_" + lSItem.id + "_Timestamp") &&
                                    settings["Task_" + lSItem.id + "_Action"].ToString() == "added" &&
                                    DateTime.Parse(settings["Task_" + lSItem.id + "_Timestamp"].ToString()) > lastSyncDate)
                                {
                                    // Submit the item to the google api
                                    Model.TaskItem result = await TaskHelper.RetryAddTask(new List <object> {
                                        lSItem, null, lSList.id
                                    });

                                    // Add the item to the final list
                                    finalTaskListItem.taskList.Add(result);

                                    // Continue to the next one
                                    continue;
                                }

                                // At this point we can assume the item was deleted on a remote device, no need to add it to the final list
                            }

                            // Remove any settings associated with the task
                            settings.Remove("Task_" + lSItem.id + "_Action");
                            settings.Remove("Task_" + lSItem.id + "_Timestamp");
                        }

                        // Loop through what is left in the google api tasks
                        foreach (Model.TaskItem task in gAList.taskList)
                        {
                            // Check if this task was deleted locally
                            if (settings.Contains("Task_" + task.id + "_Action") && settings["Task_" + task.id + "_Action"].ToString() == "deleted" &&
                                DateTime.Parse(settings["Task_" + task.id + "_Timestamp"].ToString()) >= DateTime.Parse(task.updated))
                            {
                                // Delete the list in the api
                                await TaskHelper.DeleteTask(gAList.id, task.id);
                            }
                            else
                            {
                                finalTaskListItem.taskList.Add(task);
                            }

                            // Remove any settings
                            settings.Remove("Task_" + task.id + "_Action");
                            settings.Remove("Task_" + task.id + "_Timestamp");
                        }
                        #endregion

                        finalList.Add(finalTaskListItem);
                    }
                    else
                    {
                        // There was no corresponding list in the list from the google api
                        // Check if the list was added while in offline mode
                        if (settings.Contains("List_" + lSList.id + "_Action") && settings.Contains("List_" + lSList.id + "_Timestamp") &&
                            settings["List_" + lSList.id + "_Action"].ToString() == "added" &&
                            DateTime.Parse(settings["List_" + lSList.id + "_Timestamp"].ToString()) > lastSyncDate)
                        {
                            // Submit the list to the google api
                            Model.TaskListItem results = await TaskListHelper.RetryAddTaskList(new List <object> {
                                lSList
                            });

                            // Add the list to the final list
                            if (results != null)
                            {
                                // Check if we need to update an ID value
                                if (settings.Contains("GetNewListId") && settings["GetNewListId"].ToString() == lSList.id)
                                {
                                    settings["GetNewListId"] = results.id;
                                }

                                // Add the tasks
                                #region Tasks
                                foreach (Model.TaskItem lSItem in lSList.taskList)
                                {
                                    // Submit the item to the google api
                                    Model.TaskItem task = await TaskHelper.RetryAddTask(new List <object> {
                                        lSItem, null, results.id
                                    });

                                    // Add the item to the final list
                                    results.taskList.Add(task);

                                    // Remove any settings associated with the task
                                    settings.Remove("Task_" + lSItem.id + "_Action");
                                    settings.Remove("Task_" + lSItem.id + "_Timestamp");
                                }
                                #endregion

                                finalList.Add(results);
                            }
                            else
                            {
                                MessageBox.Show("Uh oh! There was an error when syncing the tasks. Please try again soon.");

                                return(false);
                            }
                        }

                        // At this point we can assume the list was deleted on a remote device and we don't have to add it to the final list
                    }

                    // Get the final task list
                    if (finalList.Count > 0)
                    {
                        Model.TaskListItem finalTaskList = finalList.Last();
                        finalTaskList.taskList = finalTaskList.taskList.OrderBy(x => double.Parse(x.position)).ToList();

                        // Loop through the tasks
                        //if ((GTaskSettings.TaskSort == 0 && GTaskSettings.DisableDragDrop != true) //only move if settings are enabled
                        if (reOrderTasks) //only move if reOrderTasks is detected
                        {
                            for (int i = 0; i < finalTaskList.taskList.Count; i++)
                            {
                                string position = "";
                                if (i == 0)
                                {
                                    position = await TaskHelper.MoveTask(finalTaskList.id, finalTaskList.taskList[i].id, null);
                                }
                                else
                                {
                                    position = await TaskHelper.MoveTask(finalTaskList.id, finalTaskList.taskList[i].id, finalTaskList.taskList[i - 1].id);
                                }

                                // Update the position
                                finalList.Last().taskList.First(x => x.id == finalTaskList.taskList[i].id).position = position;
                            }
                        }
                    }

                    // Remove any settings
                    settings.Remove("List_" + lSList.id + "_Action");
                    settings.Remove("List_" + lSList.id + "_Timestamp");
                }

                // Loop through what is left in the google api list
                foreach (Model.TaskListItem list in googleApiList)
                {
                    // Check if this list was deleted locally
                    if (settings.Contains("List_" + list.id + "_Action") && settings["List_" + list.id + "_Action"].ToString() == "deleted" &&
                        DateTime.Parse(settings["List_" + list.id + "_Timestamp"].ToString()) >= DateTime.Parse(list.updated))
                    {
                        // Delete the list in the api
                        await TaskListHelper.DeleteList(list.id);
                    }
                    else
                    {
                        finalList.Add(list);
                    }

                    // Remove any settings
                    settings.Remove("List_" + list.id + "_Action");
                    settings.Remove("List_" + list.id + "_Timestamp");
                }

                // Create a temp list
                List <string> keyStrList = settings.Select(x => x.Key.ToString()).ToList <string>();

                // Remove any remaining settings
                foreach (string keyStr in keyStrList)
                {
                    if (keyStr.Contains("List_") || keyStr.Contains("Task_"))
                    {
                        settings.Remove(keyStr);
                    }
                }


                // Save the final list to local storage
                //if (specificList == null) //only commit to storage if it isn't for a specific list
                //{
                await TaskListHelper.SubmitToLocalStorage(finalList);

                //}

finish:

                // Update any live tiles
                // Loop through the live tiles
                foreach (ShellTile shellTile in ShellTile.ActiveTiles)
                {
                    try
                    {
                        if (shellTile.NavigationUri.ToString().Contains("/Views/TaskView.xaml?Id="))
                        {
                            // Get the ID
                            string id = shellTile.NavigationUri.ToString().Substring(shellTile.NavigationUri.ToString().IndexOf("?Id=")).Replace("?Id=", "");
                            if (id.Contains("&"))
                            {
                                id = id.Substring(0, id.IndexOf("&"));
                            }

                            // Check if there is a corresponding list
                            if (finalList.Where(x => x.id == id).Count() > 0)
                            {
                                // Get the list
                                Model.TaskListItem list = finalList.Where(x => x.id == id).First();

                                // Get the title
                                string title = list.title;
                                if (title.Length > 24)
                                {
                                    title = title.Substring(0, 21) + "...";
                                }

                                //Create a completed list
                                var NCtasks = new List <TaskItem>();
                                NCtasks.Clear();
                                NCtasks.AddRange(list.taskList.Where(y => y.status != "completed").ToList());

                                // Update the tile accordingly
                                int count = 0;
                                if ((int)settings["LiveTileCount"] > 0)
                                {
                                    if ((bool)settings["IncludeNoDueDate"])
                                    {
                                        count = NCtasks.Where(y => (y.due != null ? DateTime.Parse(y.due).AddHours(-12) : DateTime.MinValue) <= DateTime.Now).Count();
                                        settings["DueCount_" + list.id] = count;
                                    }
                                    else
                                    {
                                        count = NCtasks.Where(y => (y.due != null ? DateTime.Parse(y.due).AddHours(-12) : DateTime.MaxValue) <= DateTime.Now).Count();
                                        settings["DueNDCount_" + list.id] = count;
                                    }
                                }
                                else
                                {
                                    count = NCtasks.Count;
                                    settings["Count_" + list.id] = count;
                                }

                                //most displays cut off the 16th charactor, this reduces it to 13 + ... for the Edit page and LiveTile
                                var tileData = new StandardTileData {
                                    Title = title, BackgroundImage = new Uri("/Assets/Icons/202.png", UriKind.Relative), Count = count
                                };
                                shellTile.Update(tileData);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        // Do nothing
                        Console.WriteLine(e.ToString());
                    }
                }

                // Set the last sync date
                if (googleSync)
                {
                    settings["LastSyncDate"] = DateTime.UtcNow;
                }

                //If you've made it this far on your first attempt them you FirstRun is complete
                GTaskSettings.FirstRun = false;

                // Return true
                return(true);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                Console.WriteLine(e.StackTrace.ToString());

                return(false);
            }
        }
Beispiel #5
0
        public static async void Reminder()
        {
            //Update License (eg. If someone bought the app)
            SetLicense();

            //Set ApplicationTitle
            if (GTaskSettings.IsFree)
            {
                GTaskSettings.ApplicationTitle = "GTask";
            }
            else
            {
                GTaskSettings.ApplicationTitle = "GTask+";
            }

            //New Feature Popup (increment 1 each time you want it to show up)
            int NumFeature = 9;

            if (GTaskSettings.NewFeatureCount < NumFeature)
            {
                MessageBox.Show("- Offline Mode \r\n- Speech-to-Text \r\n- New Icons \r\n- Auto-Sync\r\n- More Customizations in Settings", "New Features!", MessageBoxButton.OK);

                if (GTaskSettings.IsFree)
                {
                    MessageBox.Show("To get the latest data from Google use the 'Sync' button.\r\n \r\nYou can enable Auto-Sync by upgrading to the Paid version\r\n \r\nSend me any questions, feedback, or issues:\r\n   - Tweet @MattLoflin\r\n   - [email protected]", "Instructions", MessageBoxButton.OK);
                }
                else
                {
                    MessageBox.Show("To get the latest data from Google use the 'Sync' button OR enable Auto-Sync in settings.\r\n \r\nSend me any questions, feedback, or issues:\r\n   - Tweet @MattLoflin\r\n   - [email protected]", "Instructions", MessageBoxButton.OK);
                }

                //due to possible data issues with localization changes - force update of Google data
                //Remove LocalStorage (if exists)
                string ApplicationDataFileName = "TaskListData.txt";

                IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
                if (storage.FileExists(ApplicationDataFileName))
                {
                    storage.DeleteFile(ApplicationDataFileName);
                }

                //Set First run to true for forced sync
                GTaskSettings.FirstRun = true;


                if (GTaskSettings.IsFree) //if free then turn off 'auto' features
                {
                    GTaskSettings.AutoClear        = false;
                    GTaskSettings.AutoRefreshLists = false;
                    GTaskSettings.AutoRefreshTasks = false;
                }

                //If the user already installed the app and HideCompleted = true then remove hidden to speed up processing
                //localStorageList should be null if not used yet
                List <Model.TaskListItem> localStorageList = await TaskListHelper.GetTaskListFromApplicationStorage(false);

                if (GTaskSettings.HideCompleted == true && (localStorageList != null || localStorageList.Count == 0))
                {
                    bool results = await GTaskSettings.RemoveHidden();
                }

                //Check for pinned lists - if pinned then prompt user to re-pin
                bool pinned = false;
                foreach (ShellTile shellTile in ShellTile.ActiveTiles)
                {
                    try
                    {
                        if (shellTile.NavigationUri.ToString().Contains("/Views/TaskView.xaml?Id="))
                        {
                            pinned = true;
                        }
                    }
                    catch (Exception)// e)
                    {
                    }
                }

                if (pinned)
                {
                    MessageBox.Show("I noticed that you have Task List(s) pinned to the Start Screen.\r\n \r\nPlease Re-pin any Task List(s) to enable updated features.", "Action Required", MessageBoxButton.OK);
                }

                //update NewFeatureCount to latest so user doesn't see this again
                GTaskSettings.NewFeatureCount = NumFeature;
            }
            //Only try to do one popup per session - if the new feature popup isn't being used, then do others (if applicable)
            else
            {
                //
                //##RATE ME POPUP##
                //
                int daysElapsed = (int)(DateTime.Now.Subtract(GTaskSettings.ReminderDate).TotalDays);
                if (daysElapsed > 7 && !GTaskSettings.Rated)
                {
                    MessageBoxResult m = MessageBox.Show("Hey! I see you have been using the app for a while now, could you click 'OK' to Rate it or Send me feedback through 'Settings'->'About'?", "Feedback?", MessageBoxButton.OKCancel);
                    if (m == MessageBoxResult.OK)
                    {
                        //Navigate to Rating Page
                        MarketplaceReviewTask oRateTask = new MarketplaceReviewTask();
                        oRateTask.Show();

                        //Set Rated = True (assuming they rated by clicking OK)
                        GTaskSettings.Rated = true;
                    }
                    else
                    {
                        //Set Reminder Date to Today to remind again in 7 days
                        GTaskSettings.ReminderDate = DateTime.Now;
                    }
                }
            }
            //If this was added after someone logged it, the value wouldn't be set until they login again
            //Given the default return is MaxValue - we can catch it and reset it to Today's date
            if (GTaskSettings.ReminderDate == DateTime.MaxValue)
            {
                GTaskSettings.ReminderDate = DateTime.Now;
            }
        }
Beispiel #6
0
        public static async Task <string> MoveTask(string TaskListID, string Id, string PrevID)
        {
            //const string message = "I'm having issues moving this task, can you try again?";

            var restRequest = new RestRequest(Method.POST)
            {
                Timeout = GTaskSettings.RequestTimeout
            };

            if (PrevID == "")
            {
                restRequest.RequestFormat = DataFormat.Json;
                restRequest.Resource      = String.Format("https://www.googleapis.com/tasks/v1/lists/" + TaskListID + "/tasks/" + Id + "/move?");
            }
            else
            {
                restRequest.RequestFormat = DataFormat.Json;
                restRequest.Resource      = String.Format("https://www.googleapis.com/tasks/v1/lists/" + TaskListID + "/tasks/" + Id + "/move?previous=" + PrevID);
            }

            restRequest.AddParameter("application/json", ParameterType.RequestBody);

            //Make the call
            var restResponse = await GTaskSettings.ExecuteRestTask(restRequest);

            try
            {
                if (restResponse.StatusCode == HttpStatusCode.OK)
                {
                    // Get the new position from the response
                    var    m        = JObject.Parse(restResponse.Content);
                    string position = (string)m.SelectToken("position");

                    //success
                    return(position);
                }
            }
            catch
            {
            }

            // Get the locally stored list
            List <TaskListItem> TaskListList = await TaskListHelper.GetTaskListFromApplicationStorage(false);

            // Check that the task list and tasks are available in local storage
            if (TaskListList.Where(x => x.id == TaskListID).Count() == 0 ||
                TaskListList.Where(x => x.id == TaskListID).First().taskList.Where(x => x.id == Id).Count() == 0)
            {
                return(null);
            }

            if (string.IsNullOrEmpty(PrevID))
            {
                // The item has been moved to the first position
                TaskListList.Where(x => x.id == TaskListID).First().taskList.Where(x => x.id == Id).First().position = "0";
                TaskListList.Where(x => x.id == TaskListID).First().taskList.Where(x => x.id == Id).First().updated  = DateTime.UtcNow.ToString("yyyy-MM-dd'T'hh:mm:ss.00Z"); // DateTime.UtcNow.ToString();
            }
            else
            {
                // Check that the prev id item is available in local storage
                if (TaskListList.Where(x => x.id == TaskListID).First().taskList.Where(x => x.id == PrevID).Count() == 0)
                {
                    return(null);
                }

                // get the position of the prev id item
                double position = double.Parse(TaskListList.Where(x => x.id == TaskListID).First().taskList.Where(x => x.id == PrevID).First().position);

                // Set the position of the item to 1+ the position of the previous item
                TaskListList.Where(x => x.id == TaskListID).First().taskList.Where(x => x.id == Id).First().position = (position + 1).ToString();
                TaskListList.Where(x => x.id == TaskListID).First().taskList.Where(x => x.id == Id).First().updated  = DateTime.UtcNow.ToString("yyyy-MM-dd'T'hh:mm:ss.00Z");// DateTime.UtcNow.ToString();
            }

            //submit the task list to local storage
            await TaskListHelper.SubmitToLocalStorage(TaskListList);

            return(null);
        }
Beispiel #7
0
        public static async Task <TaskItem> RetryAddTask(IList <object> obj)
        {
            //const string message = "Golly Gee, There was an error Creating the Task, can you try it again?";
            var restRequest = new RestRequest(Method.POST)
            {
                RequestFormat = DataFormat.Json,
                Resource      = String.Format("https://www.googleapis.com/tasks/v1/lists/{0}/tasks", obj[2]),
                Timeout       = GTaskSettings.RequestTimeout
            };
            string dueDate = string.Empty;

            if (!string.IsNullOrEmpty(((TaskItem)obj[0]).due))
            {
                TaskItem t = ((TaskItem)obj[0]);
                dueDate = ",due: \"" + t.due + "\"";
            }
            var info = "{title:\"" + ((TaskItem)obj[0]).title + "\",notes:\"" + ((TaskItem)obj[0]).notes + "\"" + dueDate + "}";

            info = info.Replace("\r", "\\n");
            restRequest.AddParameter("application/json", info, ParameterType.RequestBody);

            //Make the call
            var restResponse = await GTaskSettings.ExecuteRestTask(restRequest);

            try
            {
                if (restResponse.StatusCode == HttpStatusCode.OK)
                {
                    //Success
                    var      m       = JObject.Parse(restResponse.Content);
                    TaskItem newTask = new TaskItem((string)m.SelectToken("id"),
                                                    (string)m.SelectToken("kind"),
                                                    ((string)m.SelectToken("title")) ==
                                                    String.Empty
                                                            ? "Empty"
                                                            : (string)
                                                    m.SelectToken("title"),
                                                    ((TaskItem)obj[0]).notes,
                                                    obj[2].ToString(),
                                                    (string)
                                                    m.SelectToken("position"),
                                                    (string)m.SelectToken("updated"),
                                                    (string)m.SelectToken("due"),
                                                    (string)m.SelectToken("deleted"),
                                                    (string)m.SelectToken("hidden"),
                                                    (string)m.SelectToken("status"),
                                                    (string)
                                                    m.SelectToken("selfLink"),
                                                    (string)
                                                    m.SelectToken("completed"),
                                                    (string)
                                                    m.SelectToken("updated")
                                                    );

                    // Submit task to local storage too
                    List <TaskListItem> list = await TaskListHelper.GetTaskListFromApplicationStorage();

                    // Add the task to the list
                    list.Where(x => x.id == obj[2].ToString()).First().taskList.Insert(0, newTask);

                    // Resubmit the list to local storage
                    await TaskListHelper.SubmitToLocalStorage(list);

                    return(newTask);
                }
            }
            catch
            {
            }

            return(null);
        }