Exemple #1
2
        public static void Main(string[] args)
        {
            // Display the header and initialize the sample.
            CommandLine.EnableExceptionHandling();
            CommandLine.DisplayGoogleSampleHeader("Tasks API");

            // Register the authenticator.
            var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description);
            FullClientCredentials credentials = PromptingClientCredentials.EnsureFullClientCredentials();
            provider.ClientIdentifier = credentials.ClientId;
            provider.ClientSecret = credentials.ClientSecret;
            var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization);

            // Create the service.
            var service = new TasksService(auth);

            // Execute request: Create sample list.
            if (!ListExists(service, SampleListName) &&
                CommandLine.RequestUserChoice("Do you want to create a sample list?"))
            {
                CreateSampleTasklist(service);
            }
            CommandLine.WriteLine();

            // Execute request: List task-lists.
            ListTaskLists(service);

            CommandLine.PressAnyKeyToExit();
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            GoogleAuthorizationCodeFlow flow;
            var assembly = Assembly.GetExecutingAssembly();
            using (var stream = assembly.GetManifestResourceStream("Tasks.ASP.NET.SimpleOAuth2.client_secrets.json"))
            {
                flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
                {
                    DataStore = new FileDataStore("Tasks.ASP.NET.Sample.Store"),
                    ClientSecretsStream = stream,
                    Scopes = new[] { TasksService.Scope.TasksReadonly }
                });
            }

            var uri = Request.Url.ToString();
            var code = Request["code"];
            if (code != null)
            {
                var token = flow.ExchangeCodeForTokenAsync(UserId, code,
                    uri.Substring(0, uri.IndexOf("?")), CancellationToken.None).Result;

                // Extract the right state.
                var oauthState = AuthWebUtility.ExtracRedirectFromState(
                    flow.DataStore, UserId, Request["state"]).Result;
                Response.Redirect(oauthState);
            }
            else
            {
                var result = new AuthorizationCodeWebApp(flow, uri, uri).AuthorizeAsync(UserId,
                    CancellationToken.None).Result;
                if (result.RedirectUri != null)
                {
                    // Redirect the user to the authorization server.
                    Response.Redirect(result.RedirectUri);
                }
                else
                {
                    // The data store contains the user credential, so the user has been already authenticated.
                    service = new TasksService(new BaseClientService.Initializer
                    {
                        ApplicationName = "Tasks API Sample",
                        HttpClientInitializer = result.Credential
                    });
                }
            }
        }
Exemple #3
0
        public async System.Threading.Tasks.Task TestGetTaskLists()
        {
            UserCredential credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                new ClientSecrets
                {
                    ClientId = _clientId,
                    ClientSecret = _clientSecret
                },
                new[] { TasksService.Scope.Tasks },
                "user",
                CancellationToken.None);

            var service = new TasksService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = _application
            });

            TaskLists lists = await service.Tasklists.List().ExecuteAsync();
            Assert.IsTrue(lists.Items.Count > 0);

            foreach (TaskList list in lists.Items)
            {
                Assert.IsNotNull(list.Title);
            }
        }
Exemple #4
0
        public async System.Threading.Tasks.Task TestCreateNewTask()
        {
            UserCredential credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                new ClientSecrets
                {
                    ClientId = _clientId,
                    ClientSecret = _clientSecret
                },
                new[] { TasksService.Scope.Tasks },
                "user",
                CancellationToken.None);

            var service = new TasksService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = _application
            });

            TaskLists lists = await service.Tasklists.List().ExecuteAsync();
            Assert.IsTrue(lists.Items.Count > 0);
            string listId = lists.Items[0].Id;

            Task newTask = new Task()
            {
                Title = "Test",   
            };

            Task result = await service.Tasks.Insert(newTask, listId).ExecuteAsync();
            Assert.AreEqual(newTask.Title, result.Title);
        }
        public static void Main(string[] args)
        {
            Console.WriteLine("Tasks API: E-Tag collision");
            Console.WriteLine("==========================");

            UserCredential credential;

            using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
            {
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    new[] { TasksService.Scope.Tasks },
                    "user", CancellationToken.None, new FileDataStore("Tasks.Auth.Store")).Result;
            }

            // Create the service.
            var service = new TasksService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = "Tasks API Sample",
            });

            // Run the sample code.
            RunSample(service, true, ETagAction.Ignore);
            RunSample(service, true, ETagAction.IfMatch);
            RunSample(service, true, ETagAction.IfNoneMatch);
            RunSample(service, false, ETagAction.Ignore);
            RunSample(service, false, ETagAction.IfMatch);
            RunSample(service, false, ETagAction.IfNoneMatch);

            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }
        public IEnumerable <CommentItem> GetCommentsForTask(string woid)
        {
            var comments = TasksService.GetTraceForWorkflow(new GetTraceForWorkflowRequest
            {
                WorkflowOids = new[] { Guid.Parse(woid) }
            });

            List <CommentItem> items = new List <CommentItem>();

            if (comments.Traces != null)
            {
                foreach (var t in comments.Traces)
                {
                    if (t.Action == ActionTrace.UserMessage.ToString())
                    {
                        items.Add(new CommentItem
                        {
                            When    = t.When,
                            User    = t.User,
                            Message = t.Message,
                            Avatar  = t.Avatar
                        });
                    }
                }
            }
            return(items);
        }
        public async Task <TasksService> RunAsync()
        {
            var clientId     = "792098940629-ocdlmose3reo78in6c61mpfaoj9htblp.apps.googleusercontent.com";
            var clientSecret = "_9CVAqCDxfa-MX_0Hexd92Ge";

            UserCredential credential;

            credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                new ClientSecrets
            {
                ClientId     = clientId,
                ClientSecret = clientSecret
            },
                new[] { TasksService.Scope.Tasks, TasksService.Scope.TasksReadonly },
                "user",
                CancellationToken.None,
                new FileDataStore("account.users"));

            // Create the service.
            var _service = new TasksService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = "Google Tasks Application",
            });

            return(_service);
        }
Exemple #8
0
        private TaskModel GetTasks(string workflowOid)
        {
            var task = new TaskModel();

            var tasks = TasksService.GetNextTasksForWorkflow(new GetNextTasksForWorkflowRequest
            {
                WorkflowOid = Guid.Parse(workflowOid)
            });

            List <TaskItem> items = new List <TaskItem>();

            foreach (var t in tasks.Tasks)
            {
                items.Add(new TaskItem
                {
                    Code        = t.TaskCode,
                    Title       = t.Title,
                    Description = t.Description,
                    AcceptedBy  = string.IsNullOrWhiteSpace(t.AcceptedBy) ? string.Empty : t.AcceptedBy,
                    TaskId      = t.TaskOid.ToString()
                });
            }

            task.Tasks = items;

            return(task);
        }
Exemple #9
0
        private TraceModel GetTraces(string workflowOid)
        {
            var trace = new TraceModel();

            var traces = TasksService.GetTraceForWorkflow(new GetTraceForWorkflowRequest
            {
                WorkflowOids = new[] { Guid.Parse(workflowOid) }
            });

            List <TraceItem> items = new List <TraceItem>();

            foreach (var t in traces.Traces)
            {
                items.Add(new TraceItem
                {
                    When    = t.When,
                    Action  = t.Action,
                    User    = t.User,
                    Message = t.Message
                });
            }

            trace.Traces = items;

            return(trace);
        }
Exemple #10
0
        public static void Main(string[] args)
        {
            Console.WriteLine(".NET Tasks API Sample");
            Console.WriteLine("=====================");

            UserCredential credential;

            using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
            {
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    new[] { TasksService.Scope.Tasks },
                    "user", CancellationToken.None, new FileDataStore("Tasks.Auth.Store")).Result;
            }

            // Create the service.
            var service = new TasksService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = "Tasks API Sample",
            });

            // Execute request: Create sample list.
            if (!ListExists(service, SampleListName) && CreateSampleList())
            {
                CreateSampleTasklist(service);
            }
            Console.WriteLine();

            // Execute request: List task-lists.
            ListTaskLists(service);

            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }
Exemple #11
0
        /// <summary>
        /// Get Attached Documents
        /// </summary>
        /// <param name="taskOid">TaskOid</param>
        /// <returns>List of DocumentModel</returns>
        private IEnumerable <DocumentModel> GetAttachedDocuments(Guid taskOid)
        {
            var properties = TasksService.GetPropertiesForTask(
                new GetPropertiesForTaskRequest {
                TaskOid = taskOid
            });

            var docs = new List <DocumentModel>();
            var oids = new List <Guid>();

            foreach (var prop in properties.Properties)
            {
                if (prop.Type == PropertyType.FlowDoc.ToString())
                {
                    oids.Add(Guid.Parse(prop.Value));
                }
            }

            var res = DocsDocument.DocumentInfos(oids.ToArray());

            return(res.Select(d => new DocumentModel
            {
                DocumentOid = d.OidDocument.ToString(),
                DocumentName = d.DocumentName
            }).ToList());
        }
        /// <summary>
        /// Moves the specified task to another position in the task list. This can include putting it as a child task under a new parent and/or move it to a different position among its sibling tasks.
        /// Documentation https://developers.google.com/tasks/v1/reference/tasks/move
        /// Generation Note: This does not always build corectly.  Google needs to standardise things I need to figuer out which ones are wrong.
        /// </summary>
        /// <param name="service">Authenticated Tasks service.</param>
        /// <param name="tasklist">Task list identifier.</param>
        /// <param name="task">Task identifier.</param>
        /// <param name="optional">Optional paramaters.</param>
        /// <returns>TaskResponse</returns>
        public static Task Move(TasksService service, string tasklist, string task, TasksMoveOptionalParms optional = null)
        {
            try
            {
                // Initial validation.
                if (service == null)
                {
                    throw new ArgumentNullException("service");
                }
                if (tasklist == null)
                {
                    throw new ArgumentNullException(tasklist);
                }
                if (task == null)
                {
                    throw new ArgumentNullException(task);
                }

                // Building the initial request.
                var request = service.Tasks.Move(tasklist, task);

                // Applying optional parameters to the request.
                request = (TasksResource.MoveRequest)SampleHelpers.ApplyOptionalParms(request, optional);

                // Requesting data.
                return(request.Execute());
            }
            catch (Exception ex)
            {
                throw new Exception("Request Tasks.Move failed.", ex);
            }
        }
Exemple #13
0
        public OAuth2()
        {
            // Create the Tasks-Service if it is null.
            if (_service == null)
            {
                _service = new TasksService(_authenticator = CreateAuthenticator());
            }
            else
            {
                try
                {
                    // Fetch all TasksLists of the user asynchronously.
                    TaskLists response = _service.Tasklists.List().Fetch();
                }
                catch (ThreadAbortException)
                {
                    // User was not yet authenticated and is being forwarded to the authorization page.
                    throw;
                }
                catch (Exception ex)
                {
                }
            }

            // Check if we received OAuth2 credentials with this request; if yes: parse it.
            if (HttpContext.Current.Request["code"] != null)
            {
                _authenticator.LoadAccessToken();
            }

            //This needs to be a redirect to the edit or proxy function depending on what the
            //user wants to do.
            HttpContext.Current.Response.Write("Did it");
        }
Exemple #14
0
        [HttpPost] // load file xamlx in server
        public ActionResult LoadWorkflow(string fname)
        {
            if (ModelState.IsValid)
            {
                var sketches = TasksService.GetSketchForFilter(new GetSketchForFilterRequest
                {
                    Name     = fname,
                    Statuses = new[] { SketchStatusType.Saved, SketchStatusType.SentToSketch }
                });

                if (sketches.Sketches.Count > 0)
                {
                    string path     = "/SketchWorkFlows/";
                    string fileName = fname + ".xamlx";

                    DocsDocument.DownloadDocument(new DocumentInfo {
                        OidDocument = sketches.Sketches[0].XamlxOid, DocumentName = fileName, Path = path
                    },
                                                  ConfigHelper.DownloadLocation, DocumentDownloadMode.LastVersion);

                    XmlDocument xamlx = new XmlDocument();
                    xamlx.Load(Path.Combine(ConfigHelper.DownloadLocation, fileName));

                    //convert xml to json
                    String json = Newtonsoft.Json.JsonConvert.SerializeXmlNode(xamlx);

                    return(Json(json));
                }
                return(Json("Error"));
            }
            return(Json("Error"));
        }
Exemple #15
0
        public void GetTasksInProject()
        {
            TasksService taskService = new TasksService(API_KEY);

            Task[] tasks = taskService.GetTasks(new TasksQuery()
            {
                ProjectId = TEST_PROJECT_ID
            });
            Assert.IsNotNull(tasks, "we should have gotten some tasks back");
            Assert.IsTrue(tasks.Length > 0, "task.Length should be > 0, but it was " + tasks.Length.ToString());
            foreach (var item in tasks)
            {
                Assert.AreEqual(DateTime.MinValue, item.CreatedAt, "Since ReturnCompleteTaskRecords is false, CreatedAt shouldn't come back");
            }


            Task[] tasks2 = taskService.GetTasksInProject(TEST_PROJECT_ID);
            Assert.IsNotNull(tasks2, "we should have gotten some tasks back");
            Assert.IsTrue(tasks2.Length > 0, "task.Length should be > 0, but it was " + tasks2.Length.ToString());
            foreach (var item in tasks2)
            {
                Assert.AreEqual(DateTime.MinValue, item.CreatedAt, "Since ReturnCompleteTaskRecords is false, CreatedAt shouldn't come back");
            }

            CompareTasks(tasks, tasks2);
        }
Exemple #16
0
        public void Should_Return_TaskResponse_If_call_GetAllTasks()
        {
            var moqDocumentRepositor = new Mock <ITaskRepository>();
            var Listdata             = new List <TasksDB>();
            var taskComplition       = new TaskCompletionSource <List <TasksDB> >();

            taskComplition.SetResult(new List <TasksDB>()
            {
                new TasksDB()
                {
                    TaskId   = new Guid("75A55861-4442-4FD1-A150-725CE51186E4"),
                    TaskName = "Task 1"
                },
                new TasksDB()
                {
                    TaskId   = new Guid("0F8FAD5B-D9CB-469F-A165-70867728950E"),
                    TaskName = "Task 2"
                }
            });
            moqDocumentRepositor.Setup(x => x.GetAllTasks()).Returns(taskComplition.Task);
            var moqLogger = new Mock <ILogger>();

            int?expected_count = 2;
            var TasksService   = new TasksService();

            // Act
            var actual   = (ObjectResult)TasksService.GetTasks(moqDocumentRepositor.Object, moqLogger.Object).Result;
            var response = (List <TaskResponse>)actual.Value;

            // Assert
            Assert.AreEqual(expected_count, response.Count);
        }
Exemple #17
0
        protected void btnDeleteAd_ServerClick(object sender, EventArgs e)
        {
            using (var stream =
                       new FileStream(Server.MapPath("client_secret.json"), FileMode.Open, FileAccess.Read))
            {
                string credPath = System.Environment.GetFolderPath(
                    System.Environment.SpecialFolder.Personal);;
                credPath = Path.Combine(credPath, ".credentials/taskdelete-dotnet-quickstart.json");

                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result;
                // Console.WriteLine("Credential file saved to: " + credPath);
            }

            // Create Google Tasks API service.
            var service = new TasksService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName,
            });


            service.Tasks.Delete("@default", taskid).ExecuteAsync();
            changePagedelete();
        }
Exemple #18
0
        /// <summary>
        /// Apply holidays
        /// </summary>
        /// <remarks>
        /// http://localhost/Flow.tasks.web/api/users/holiday/cgrant
        /// </remarks>
        /// <param name="name"></param>
        /// <param name="dates"></param>
        /// <returns></returns>
        [HttpPost] public HttpResponseMessage ApplyHoliday(string name, IEnumerable <string> dates)
        {
            try
            {
                var resp = TasksService.ApplyHoliday(new ApplyHolidayRequest {
                    User = name, Type = 2, Holiday = dates
                });

                var json = JsonConvert.SerializeObject(
                    new { resp.HolidayId },
                    Formatting.Indented,
                    new JsonSerializerSettings {
                    ContractResolver = new CamelCasePropertyNamesContractResolver()
                }
                    );
                var result = Request.CreateResponse(HttpStatusCode.OK);
                result.Content = new StringContent(json, Encoding.UTF8, "text/plain");

                return(result);
            }
            catch (Exception ex)
            {
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, ex));
            }
        }
Exemple #19
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            UserCredential credential;

            using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
            {
                GoogleWebAuthorizationBroker.Folder = "Tasks.Auth.Store";
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    new[] { TasksService.Scope.Tasks },
                    "user", CancellationToken.None).Result;
            }

            // Initialize the service.
            Service = new TasksService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = "Tasks API Sample"
            });

            // Open a NoteForm for every task list.
            foreach (TaskList list in Service.Tasklists.List().Execute().Items)
            {
                // Open a NoteForm.
                new NoteForm(list).Show();
            }
            Application.Run();
        }
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            UserCredential credential;
            using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
            {
                GoogleWebAuthorizationBroker.Folder = "Tasks.Auth.Store";
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    new[] { TasksService.Scope.Tasks },
                    "user", CancellationToken.None).Result;
            }

            // Initialize the service.
            Service = new TasksService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Tasks API Sample"
                });

            // Open a NoteForm for every task list.
            foreach (TaskList list in Service.Tasklists.List().Execute().Items)
            {
                // Open a NoteForm.
                new NoteForm(list).Show();
            }
            Application.Run();
        }
        /// <summary>
        /// Deletes the specified task from the task list.
        /// Documentation https://developers.google.com/tasks/v1/reference/tasks/delete
        /// Generation Note: This does not always build corectly.  Google needs to standardise things I need to figuer out which ones are wrong.
        /// </summary>
        /// <param name="service">Authenticated Tasks service.</param>
        /// <param name="tasklist">Task list identifier.</param>
        /// <param name="task">Task identifier.</param>
        public static void Delete(TasksService service, string tasklist, string task)
        {
            try
            {
                // Initial validation.
                if (service == null)
                {
                    throw new ArgumentNullException("service");
                }
                if (tasklist == null)
                {
                    throw new ArgumentNullException(tasklist);
                }
                if (task == null)
                {
                    throw new ArgumentNullException(task);
                }

                // Make the request.
                service.Tasks.Delete(tasklist, task).Execute();
            }
            catch (Exception ex)
            {
                throw new Exception("Request Tasks.Delete failed.", ex);
            }
        }
Exemple #22
0
        /// <summary>
        ///     <see cref="Authenticate" /> to Google Using Oauth2 Documentation
        ///     https://developers.google.com/accounts/docs/OAuth2
        /// </summary>
        /// <param name="clientId">
        ///     From Google Developer console https://console.developers.google.com
        /// </param>
        /// <param name="clientSecret">
        ///     From Google Developer console https://console.developers.google.com
        /// </param>
        /// <param name="userName">
        ///     A string used to identify a user (locally).
        /// </param>
        /// <param name="fileDataStorePath">
        ///     Name/Path where the Auth Token and refresh token are stored (usually
        ///     in %APPDATA%)
        /// </param>
        /// <param name="applicationName">Applicaiton Name</param>
        /// <param name="isFullPath">
        ///     <paramref name="fileDataStorePath" /> is completePath or Directory
        ///     Name
        /// </param>
        /// <returns>
        /// </returns>
        public TasksService AuthenticateTasksOauth(string clientId, string clientSecret, string userName,
                                                   string fileDataStorePath, string applicationName, bool isFullPath = false)
        {
            try
            {
                var authTask = Authenticate(clientId, clientSecret, userName, fileDataStorePath, isFullPath);

                authTask.Wait(30000);

                if (authTask.Status == TaskStatus.WaitingForActivation)
                {
                    return(null);
                }

                var service = new TasksService(new BaseClientService.Initializer
                {
                    HttpClientInitializer = authTask.Result,
                    ApplicationName       = applicationName
                });

                return(service);
            }
            catch (AggregateException exception)
            {
                Logger.Error(exception);
                return(null);
            }
            catch (Exception exception)
            {
                Logger.Error(exception);
                return(null);
            }
        }
Exemple #23
0
        public async Task ModTest(string taskDescription, int priority, string startDateStr, string endDateStr)
        {
            DateTime startDate = DateTime.Parse(startDateStr);
            DateTime endDate   = DateTime.Parse(endDateStr);
            var      taskMod   = new TaskMod
            {
                EndDate         = endDate,
                StartDate       = startDate,
                Priority        = priority,
                TaskDescription = taskDescription
            };
            var resulTasks = new Tasks
            {
                EndDate      = endDate,
                Priortiy     = priority,
                TaskDeatails = taskDescription,
                Status       = 1,
                StartDate    = startDate,
                TaskId       = 1
            };
            var mockMapper = new Mock <IMapper>();

            mockMapper.Setup(map => map.Map <Tasks>(It.IsAny <TaskMod>())).Returns(resulTasks);
            var mockTaskRepo = new Mock <ITaskRepo>();

            mockTaskRepo.Setup(tskService => tskService.EditTask(It.IsAny <Tasks>()))
            .Returns(Task.FromResult <bool>(true));
            var taskService = new TasksService(mockMapper.Object, mockTaskRepo.Object, logger);
            var result      = await taskService.ModifyTask(taskMod);

            Assert.True(result);
        }
        public HttpResponseMessage Operations(string op, string woid, string wcode, [FromBody] IEnumerable <WfProperty> props)
        {
            Guid oid;

            if (!string.IsNullOrWhiteSpace(woid) && !Guid.TryParse(woid, out oid))
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            try
            {
                if (op.Equals(WorkflowOperation.Start.ToString(), StringComparison.OrdinalIgnoreCase))
                {
                    var startWorkflowRequest = new StartWorkflowRequest
                    {
                        Domain          = ConfigHelper.WorkflowDomain,
                        WorkflowCode    = wcode,
                        WfRuntimeValues = props.ToArray()
                    };

                    TasksService.StartWorkflow(startWorkflowRequest);
                }
                else
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest));
                }
            }
            catch (Exception ex)
            {
                return(Request.CreateResponse(HttpStatusCode.InternalServerError));
            }

            return(Request.CreateResponse(HttpStatusCode.OK));
        }
        private async Task <List <ReminderTask> > AddTasksInternal(List <ReminderTask> reminderTasks,
                                                                   TasksService taskService, Dictionary <int, ReminderTask> errorList)
        {
            var addedEvents = new List <ReminderTask>();
            //Create a Batch Request
            var batchRequest = new BatchRequest(taskService);

            for (var i = 0; i < reminderTasks.Count; i++)
            {
                if (i != 0 && i % 999 == 0)
                {
                    await batchRequest.ExecuteAsync();

                    batchRequest = new BatchRequest(taskService);
                }

                var reminderTask  = reminderTasks[i];
                var googleTask    = CreaterGoogleTask(reminderTask);
                var insertRequest = taskService.Tasks.Insert(googleTask,
                                                             TaskListId);
                batchRequest.Queue <Task>(insertRequest,
                                          (content, error, index, message) =>
                                          CallbackEventErrorMessage(content, error, index, message,
                                                                    reminderTasks, "Error in adding events", errorList,
                                                                    addedEvents));
            }

            await batchRequest.ExecuteAsync();

            return(addedEvents);
        }
        /// <summary>
        /// Updates the specified task.
        /// Documentation https://developers.google.com/tasks/v1/reference/tasks/update
        /// Generation Note: This does not always build corectly.  Google needs to standardise things I need to figuer out which ones are wrong.
        /// </summary>
        /// <param name="service">Authenticated Tasks service.</param>
        /// <param name="tasklist">Task list identifier.</param>
        /// <param name="task">Task identifier.</param>
        /// <param name="body">A valid Tasks v1 body.</param>
        /// <returns>TaskResponse</returns>
        public static Task Update(TasksService service, string tasklist, string task, Task body)
        {
            try
            {
                // Initial validation.
                if (service == null)
                {
                    throw new ArgumentNullException("service");
                }
                if (body == null)
                {
                    throw new ArgumentNullException("body");
                }
                if (tasklist == null)
                {
                    throw new ArgumentNullException(tasklist);
                }
                if (task == null)
                {
                    throw new ArgumentNullException(task);
                }

                // Make the request.
                return(service.Tasks.Update(body, tasklist, task).Execute());
            }
            catch (Exception ex)
            {
                throw new Exception("Request Tasks.Update failed.", ex);
            }
        }
Exemple #27
0
        public async Task EndTaskTest(int taskId, int parentTaskId, int priority, string strStartDate, string strEndDate)
        {
            var startDate = DateTime.Parse(strStartDate);
            var endDate   = DateTime.Parse(strEndDate);
            var tasks     = new List <Tasks> {
                new Tasks {
                    EndDate      = endDate,
                    ParentTaskId = parentTaskId,
                    Priortiy     = priority,
                    StartDate    = startDate,
                    Status       = 1,
                    TaskDeatails = "Task1",
                    TaskId       = taskId,
                    ParentTask   = new ParentTask
                    {
                        ParentTaskDescription = "ParentTask",
                        Parent_ID             = 1,
                        Parent_Task           = 1,
                    }
                }
            };

            var mockMapper   = new Mock <IMapper>();
            var mockTaskRepo = new Mock <ITaskRepo>();

            mockTaskRepo.Setup(repo => repo.GetTaskForAnyCriteria(It.IsAny <SearchMsg>())).Returns(tasks);
            mockTaskRepo.Setup(repo => repo.EditTask(It.IsAny <Tasks>())).Returns(Task.FromResult(true));
            var taskService = new TasksService(mockMapper.Object, mockTaskRepo.Object, logger);
            var result      = await taskService.EndTask(taskId);

            Assert.True(result);
        }
Exemple #28
0
        public void Authentication(Ctx ctx)
        {
            var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description);

            provider.ClientIdentifier = ClientCredentials.ClientID;
            provider.ClientSecret     = ClientCredentials.ClientSecret;
            // Create the service. This will automatically call the authenticator.

            if (isTask)
            {
                var service = new TasksService(new OAuth2Authenticator <NativeApplicationClient>(provider, GetAuthentication));
                Google.Apis.Tasks.v1.TasklistsResource.ListRequest clrq = service.Tasklists.List();
                clrq.MaxResults = "1000";

                TaskLists taskslist = clrq.Fetch();


                FetchingTasks(service, taskslist, ctx);
            }
            else
            {
                var service = new CalendarService(new OAuth2Authenticator <NativeApplicationClient>(provider, GetAuthentication));
                Google.Apis.Calendar.v3.CalendarListResource.ListRequest clrq = service.CalendarList.List();
                var result = clrq.Fetch();
                FetchingCalendar(result, service, ctx);
            }
        }
        public void Init()
        {
            _tasksRepositoryMock = new Mock <IItemRepository <Task> >();
            _mapperMock          = new Mock <IMapper>();

            _tasksService = new TasksService(_tasksRepositoryMock.Object, _mapperMock.Object);
        }
Exemple #30
0
        public async Task GetAllParentTaskTest()
        {
            var parentTasks = new List <ParentTask> {
                new ParentTask {
                    ParentTaskDescription = "Task0",
                    Parent_ID             = 1,
                    Parent_Task           = 1,
                }
            };
            var parentTaskMsgs = new List <ParentTaskMsg> {
                new ParentTaskMsg {
                    Parent_ID               = 1,
                    ParentTask_ID           = 1,
                    Parent_Task_Description = "Task0"
                }
            };
            var mockMapper = new Mock <IMapper>();

            mockMapper.Setup(map => map.Map <List <ParentTaskMsg> >(It.IsAny <List <ParentTask> >()))
            .Returns(parentTaskMsgs);
            var mockTaskRepo = new Mock <ITaskRepo>();

            mockTaskRepo.Setup(repo => repo.GetAllParentTasks()).Returns(Task.FromResult(parentTasks));
            var taskService = new TasksService(mockMapper.Object, mockTaskRepo.Object, logger);
            var result      = await taskService.GetAllParentTask();

            Assert.Single(result);
        }
        public TasksViewController(TasksService service, TaskList list)
            : base(UITableViewStyle.Plain, null, true)
        {
            if (service == null)
            {
                throw new ArgumentNullException("service");
            }
            if (list == null)
            {
                throw new ArgumentNullException("list");
            }

            this.service = service;
            this.list    = list;

            NavigationItem.RightBarButtonItem = new UIBarButtonItem(UIBarButtonSystemItem.Add, OnAddItem);

            Root = new RootElement(list.Title)
            {
                new Section()
            };

            RefreshRequested += (s, e) => Refresh();
            Refresh();
        }
        public static void Main(string[] args)
        {
            Console.WriteLine(".NET Tasks API Sample");
            Console.WriteLine("=====================");

            UserCredential credential;
            using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
            {
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    new[] { TasksService.Scope.Tasks },
                    "user", CancellationToken.None, new FileDataStore("Tasks.Auth.Store")).Result;
            }

            // Create the service.
            var service = new TasksService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = "Tasks API Sample",
            });

            // Execute request: Create sample list.
            if (!ListExists(service, SampleListName) && CreateSampleList())
            {
                CreateSampleTasklist(service);
            }
            Console.WriteLine();

            // Execute request: List task-lists.
            ListTaskLists(service);

            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }
Exemple #33
0
        private static ToDoGoogleService Initialize()
        {
            UserCredential credential;

            string[] Scopes          = { TasksService.Scope.Tasks };
            string   ApplicationName = "Google Tasks API .NET Quickstart";

            using (var stream =
                       new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
            {
                // The file token.json stores the user's access and refresh tokens, and is created
                // automatically when the authorization flow completes for the first time.
                string credPath = "token.json";
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None).Result;
                Console.WriteLine("Credential file saved to: " + credPath);
            }

            // Create Google Tasks API service.
            var service = new TasksService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName,
            });

            return(new ToDoGoogleService(service));
        }
Exemple #34
0
        public static void Main(string[] args)
        {
            // Display the header and initialize the sample.
            CommandLine.EnableExceptionHandling();
            CommandLine.DisplayGoogleSampleHeader("Tasks API: E-Tag collision");

            // Register the authenticator.
            var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description);
            FullClientCredentials credentials = PromptingClientCredentials.EnsureFullClientCredentials();

            provider.ClientIdentifier = credentials.ClientId;
            provider.ClientSecret     = credentials.ClientSecret;
            var auth = new OAuth2Authenticator <NativeApplicationClient>(provider, GetAuthentication);

            // Create the service.
            var service = new TasksService(auth);

            // Run the sample code.
            RunSample(service, true, ETagAction.Ignore);
            RunSample(service, true, ETagAction.IfMatch);
            RunSample(service, true, ETagAction.IfNoneMatch);
            RunSample(service, false, ETagAction.Ignore);
            RunSample(service, false, ETagAction.IfMatch);
            RunSample(service, false, ETagAction.IfNoneMatch);
            CommandLine.PressAnyKeyToExit();
        }
        public static void Main(string[] args)
        {
            Console.WriteLine("Tasks API: E-Tag collision");
            Console.WriteLine("==========================");

            UserCredential credential;
            using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
            {
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    new[] { TasksService.Scope.Tasks },
                    "user", CancellationToken.None, new FileDataStore("Tasks.Auth.Store")).Result;
            }

            // Create the service.
            var service = new TasksService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = "Tasks API Sample",
            });

            // Run the sample code.
            RunSample(service, true, ETagAction.Ignore);
            RunSample(service, true, ETagAction.IfMatch);
            RunSample(service, true, ETagAction.IfNoneMatch);
            RunSample(service, false, ETagAction.Ignore);
            RunSample(service, false, ETagAction.IfMatch);
            RunSample(service, false, ETagAction.IfNoneMatch);

            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }
        public static void Main(string[] args)
        {
            Console.WriteLine("Tasks OAuth2 Sample");
            Console.WriteLine("===================");

            UserCredential credential;
            using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
            {
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    new[] { TasksService.Scope.Tasks },
                    "user", CancellationToken.None, new FileDataStore("Tasks.Auth.Store")).Result;
            }

            // Create the service.
            var service = new TasksService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = "Tasks API Sample",
            });

            TaskLists results = service.Tasklists.List().Execute();
            Console.WriteLine("\tLists:");

            foreach (TaskList list in results.Items)
            {
                Console.WriteLine("\t\t" + list.Title);
            }

            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }
Exemple #37
0
        public static void Main(string[] args)
        {
            // Display the header and initialize the sample.
            CommandLine.EnableExceptionHandling();
            CommandLine.DisplayGoogleSampleHeader("Tasks API");

            // Register the authenticator.
            var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description);
            FullClientCredentials credentials = PromptingClientCredentials.EnsureFullClientCredentials();

            provider.ClientIdentifier = credentials.ClientId;
            provider.ClientSecret     = credentials.ClientSecret;
            var auth = new OAuth2Authenticator <NativeApplicationClient>(provider, GetAuthorization);

            // Create the service.
            var       service = new TasksService(auth);
            TaskLists results = service.Tasklists.List().Fetch();

            CommandLine.WriteLine("   ^1Lists:");
            foreach (TaskList list in results.Items)
            {
                CommandLine.WriteLine("     ^2" + list.Title);
            }
            CommandLine.PressAnyKeyToExit();
        }
        public ReportController(DatabaseContext databaseContext, IMapper mapper)
        {
            var taskRepository = new TasksRepository(databaseContext);

            _projectsService = new ProjectsService(new ProjectsRepository(databaseContext), taskRepository, mapper);
            _tasksService    = new TasksService(taskRepository, mapper);
        }
Exemple #39
0
 public void SetUserCredential(UserCredential credential)
 {
     _service = new TasksService(new BaseClientService.Initializer()
     {
         HttpClientInitializer = credential,
         ApplicationName = _application
     });
 }
 public DeleteTask(
     Task task, 
     TasksService tasksService,
     DataContext dataContext, 
     IBusyIndicator busyIndicator)
 {
     _task = task;
     _tasksService = tasksService;
     _dataContext = dataContext;
     _busyIndicator = busyIndicator;
 }
 public LoadTasks(
     string tasksListsId,
     DataContext dataContext,
     TasksService tasksService,
     IBusyIndicator busyIndicator)
 {
     _tasksListsId = tasksListsId;
     _dataContext = dataContext;
     _tasksService = tasksService;
     _busyIndicator = busyIndicator;
 }
 public EditTasksList(
     TaskList tasksList, 
     TasksService tasksService, 
     IBusyIndicator busyIndicator, 
     DataContext dataContext)
 {
     _tasksList = tasksList;
     _tasksService = tasksService;
     _busyIndicator = busyIndicator;
     _dataContext = dataContext;
 }
        public TaskListsViewController(TasksService service)
            : base(UITableViewStyle.Plain, null, true)
        {
            this.service = service;

            Root = new RootElement ("Lists");
            NavigationItem.RightBarButtonItem = new UIBarButtonItem (UIBarButtonSystemItem.Add, OnCreateList);

            RefreshRequested += (s, e) => Refresh();

            Refresh();
        }
 private void ServiceInstance(string accountId, string certPath)
 {
     var auth = new ServiceOAuth(accountId, certPath);
     DirectoryService = auth.DirectoryService();
     GroupSettingsService = auth.GroupSettingsService();
     LicensingService = auth.LicensingService();
     ReportsService = auth.ReportsService();
     CalendarService = auth.CalendarService();
     DriveService = auth.DriveService();
     AuditService = auth.AuditService();
     TasksService = auth.TasksService();
 }
        public static void Execute()
        {
            using (var svc = new TasksService()) {

                var expireList = svc.FindTasksThatShouldBeExpired();

                foreach(var t in expireList) {

                    svc.Expire(t.Id);
                }
            }
        }
        public async Task<ActionResult> AuditRepair(AuditRepairModel model)
        {
            var sharePointToken = await AuthenticationHelper.GetAccessTokenAsync(AppSettings.DemoSiteServiceResourceId);
            Dashboard dashboardModel = new Dashboard(sharePointToken);

            var tasksService = new TasksService(sharePointToken);
            await tasksService.CompleteRepairApprovalTaskAsync(model);

            if (model.Result == ApprovalResult.Approved)
                await dashboardModel.ApproveRepairAsync(model.IncidentId);

            return RedirectToAction("Index");
        }
        public async Task<ActionResult> ScheduleRepair(ScheduleRepairModel model)
        {
            var sharePointToken = AuthenticationHelper.GetAccessTokenAsync(AppSettings.DemoSiteServiceResourceId);
            var graphService = AuthenticationHelper.GetGraphServiceAsync();

            var tasksService = new TasksService(await sharePointToken);
            var dashboardModel = new Dashboard(await sharePointToken);

            await dashboardModel.UpdateRepairScheduleInfoToIncidentAsync(model)
                .ContinueWith(async task => await tasksService.CompleteRepairAssignmentTaskAsync(model.IncidentId));

            await dashboardModel.ScheduleRepairAsync(await graphService, model);
            await dashboardModel.CreateGroupRepairEventAsync(await graphService, model);

            return RedirectToAction("Index");
        }
Exemple #48
0
        protected void Page_Load(object sender, EventArgs e)
        {
            // Create the Tasks-Service if it is null.
            if (_service == null)
            {
                _service = new TasksService(_authenticator = CreateAuthenticator());
            }

            // Check if we received OAuth2 credentials with this request; if yes: parse it.
            if (HttpContext.Current.Request["code"] != null)
            {
                _authenticator.LoadAccessToken();
            }

            // Change the button depending on our auth-state.
            listButton.Text = AuthState == null ? "Authenticate" : "Fetch Tasklists";
        }
Exemple #49
0
        /// <summary>
        public static void Main(string[] args)
        {
            // Display the header and initialize the sample.
            CommandLine.EnableExceptionHandling();
            CommandLine.DisplayGoogleSampleHeader("Tasks API");
            // Register the authenticator.
            var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description);
            provider.ClientIdentifier = "<client id>";
            provider.ClientSecret = "<client secret>";

            var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization);
            // Create the service.
            var service = new TasksService(auth);
            TaskLists results = service.Tasklists.List().Fetch();
            Console.WriteLine("Lists:");
            foreach (TaskList list in results.Items)
            {
                Console.WriteLine("- " + list.Title);
            } Console.ReadKey();
        }
        public TasksViewController(TasksService service, TaskList list)
            : base(UITableViewStyle.Plain, null, true)
        {
            if (service == null)
                throw new ArgumentNullException ("service");
            if (list == null)
                throw new ArgumentNullException ("list");

            this.service = service;
            this.list = list;

            NavigationItem.RightBarButtonItem = new UIBarButtonItem (UIBarButtonSystemItem.Add, OnAddItem);

            Root = new RootElement (list.Title) {
                new Section()
            };

            RefreshRequested += (s, e) => Refresh();
            Refresh();
        }
        private static void RunSample(TasksService service, bool modify, ETagAction behaviour)
        {
            Console.WriteLine("Testing for E-Tag case " + behaviour + " with modified=" + modify + "...");

            // Create a new task list.
            TaskList list = service.Tasklists.Insert(new TaskList() { Title = "E-Tag Collision Test" }).Execute();

            // Add a task.
            Task myTask = service.Tasks.Insert(new Task() { Title = "My Task" }, list.Id).Execute();

            // Retrieve a second instance of this task, modify it and commit it.
            if (modify)
            {
                Task myTaskB = service.Tasks.Get(list.Id, myTask.Id).Execute();
                myTaskB.Title = "My Task B!";
                service.Tasks.Update(myTaskB, list.Id, myTaskB.Id).Execute();
            }

            // Modify the original task, and see what happens.
            myTask.Title = "My Task A!";
            var request = service.Tasks.Update(myTask, list.Id, myTask.Id);
            request.ETagAction = behaviour;

            try
            {
                request.Execute();
                Console.WriteLine("\tResult: Success!");
            }
            catch (GoogleApiException ex)
            {
                Console.WriteLine("\tResult: Failure! The error message is: " + ex.Message);
            }
            finally
            {
                // Delete the created list. 
                service.Tasklists.Delete(list.Id).Execute();
                Console.WriteLine();
            }
        }
        private void ShowList(TasksService service)
        {
            bltasklist.Items.Clear();
            TaskList list = service.Tasklists.List().Execute().Items.Where(l => l.Title == "Default").SingleOrDefault();
            var tasks = service.Tasks.List(list.Id).Execute();
            if(tasks.Items!= null)
            {
                foreach (var item in tasks.Items)
                {
                    if (item.Title != null)
                    {
                        bltasklist.Items.Add(item.Title);
                    }

                }
            }
            else
            {
                bltasklist.Items.Add("List Is Empty!");
            }
            
            
        }
Exemple #53
0
        public static void Main(string[] args)
        {
            // Display the header and initialize the sample.
            CommandLine.EnableExceptionHandling();
            CommandLine.DisplayGoogleSampleHeader("Tasks API");

            // Register the authenticator.
            var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description);
            FullClientCredentials credentials = PromptingClientCredentials.EnsureFullClientCredentials();
            provider.ClientIdentifier = credentials.ClientId;
            provider.ClientSecret = credentials.ClientSecret;
            var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization);

            // Create the service.
            var service = new TasksService(auth);
            TaskLists results = service.Tasklists.List().Fetch();
            CommandLine.WriteLine("   ^1Lists:");
            foreach (TaskList list in results.Items)
            {
                CommandLine.WriteLine("     ^2" + list.Title);
            }
            CommandLine.PressAnyKeyToExit();
        }
        protected void Page_Load(object sender, EventArgs e)
        {
                //User Credentional Authorization
                UserCredential credential;
                using (var stream = new FileStream(Server.MapPath("/client_secret.json"), FileMode.Open, FileAccess.Read))
                {
                    credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                        GoogleClientSecrets.Load(stream).Secrets,
                        new[] { TasksService.Scope.Tasks },
                        "user", CancellationToken.None, new FileDataStore("Tasks.Auth.Store")).Result;
                }

                // Create the service.
                service = new TasksService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Tasks App",
                });
          
            //Check if default task list exist.
            // If yes show else create and show

            if (!ListExists(service, title))
            {
                //Create
                CreateTasklist(service);
                //Show
                ShowList(service);

            }
            else
            {
                //Show
                ShowList(service);
            }
            list = service.Tasklists.List().Execute().Items.Where(l => l.Title == "Default").SingleOrDefault();
        }
Exemple #55
0
        public OAuth2()
        {
            // Create the Tasks-Service if it is null.
            if (_service == null)
            {
                _service = new TasksService(_authenticator = CreateAuthenticator());
            }
            else
            {
                try
                {
                    // Fetch all TasksLists of the user asynchronously.
                    TaskLists response = _service.Tasklists.List().Fetch();

                }
                catch (ThreadAbortException)
                {
                    // User was not yet authenticated and is being forwarded to the authorization page.
                    throw;
                }
                catch (Exception ex)
                {

                }

            }

            // Check if we received OAuth2 credentials with this request; if yes: parse it.
            if (HttpContext.Current.Request["code"] != null)
            {
                _authenticator.LoadAccessToken();
            }

            //This needs to be a redirect to the edit or proxy function depending on what the
            //user wants to do.
            HttpContext.Current.Response.Write("Did it");
        }
        private static void CreateSampleTasklist(TasksService service)
        {
            var list = new TaskList();
            list.Title = SampleListName;
            list = service.Tasklists.Insert(list).Execute();

            service.Tasks.Insert(new Task { Title = "Learn the Task API" }, list.Id).Execute();
            service.Tasks.Insert(new Task { Title = "Implement a WP application using Task API" }, list.Id).Execute();
        }
 private static bool ListExists(TasksService service, string list)
 {
     return (from TaskList taskList in service.Tasklists.List().Execute().Items
             where taskList.Title == list
             select taskList).Count() > 0;
 }
        /// <summary>
        ///     <see cref="Authenticate" /> to Google Using Oauth2 Documentation
        ///     https://developers.google.com/accounts/docs/OAuth2
        /// </summary>
        /// <param name="clientId">
        ///     From Google Developer console https://console.developers.google.com
        /// </param>
        /// <param name="clientSecret">
        ///     From Google Developer console https://console.developers.google.com
        /// </param>
        /// <param name="userName">
        ///     A string used to identify a user (locally).
        /// </param>
        /// <param name="fileDataStorePath">
        ///     Name/Path where the Auth Token and refresh token are stored (usually
        ///     in %APPDATA%)
        /// </param>
        /// <param name="applicationName">Applicaiton Name</param>
        /// <param name="isFullPath">
        ///     <paramref name="fileDataStorePath" /> is completePath or Directory
        ///     Name
        /// </param>
        /// <returns>
        /// </returns>
        public TasksService AuthenticateTasksOauth(string clientId, string clientSecret, string userName,
            string fileDataStorePath, string applicationName, bool isFullPath = false)
        {
            try
            {
                var authTask = Authenticate(clientId, clientSecret, userName, fileDataStorePath, isFullPath);

                authTask.Wait(30000);

                if (authTask.Status == TaskStatus.WaitingForActivation)
                {
                    return null;
                }

                var service = new TasksService(new BaseClientService.Initializer
                {
                    HttpClientInitializer = authTask.Result,
                    ApplicationName = applicationName
                });

                return service;
            }
            catch (AggregateException exception)
            {
                Logger.Error(exception);
                return null;
            }
            catch (Exception exception)
            {
                Logger.Error(exception);
                return null;
            }
        }
Exemple #59
0
        private async Task<List<ReminderTask>> AddTasksInternal(List<ReminderTask> reminderTasks,
            TasksService taskService, Dictionary<int, ReminderTask> errorList)
        {
            var addedEvents = new List<ReminderTask>();
            //Create a Batch Request
            var batchRequest = new BatchRequest(taskService);
            
            for (var i = 0; i < reminderTasks.Count; i++)
            {
                if (i != 0 && i % 999 == 0)
                {
                    await batchRequest.ExecuteAsync();
                    batchRequest = new BatchRequest(taskService);
                }

                var reminderTask = reminderTasks[i];
                var googleTask = CreaterGoogleTask(reminderTask);
                var insertRequest = taskService.Tasks.Insert(googleTask,
                    TaskListId);
                batchRequest.Queue<Task>(insertRequest,
                    (content, error, index, message) =>
                        CallbackEventErrorMessage(content, error, index, message,
                        reminderTasks, "Error in adding events", errorList,
                            addedEvents));
            }

            await batchRequest.ExecuteAsync();
            return addedEvents;
        }
        private async void Window_Initialized(object sender, EventArgs e)
        {
            // Create the service.
            using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
            {
                var credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                                    GoogleClientSecrets.Load(stream).Secrets,
                                    new[] { TasksService.Scope.Tasks },
                                    "user", CancellationToken.None, new FileDataStore("Tasks.Auth.Store"));

                Service = new TasksService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Tasks API Sample",
                });
            }

            // Get all TaskLists.
            UpdateTaskLists();
        }