Esempio n. 1
0
        private async Task AllowPermissionsForGoogleDriveFile(GoogleAuthDTO authDTO, string fileId)
        {
            //create google drive service for file manipulation
            var driveService = await _googleDrive.CreateDriveService(authDTO);

            var batch = new BatchRequest(driveService);

            //bach service callback for successfull permission set
            BatchRequest.OnResponse <Permission> callback = delegate(
                Permission permission, RequestError error, int index, HttpResponseMessage message){
                if (error != null)
                {
                    // Handle error
                    throw new ApplicationException($"Problem with Google Drive Permissions: {error.Message}");
                }
            };

            var userPermission = new Permission
            {
                Type         = "user",
                Role         = "writer",
                EmailAddress = CloudConfigurationManager.GetSetting("GoogleMailAccount")
            };
            var request = driveService.Permissions.Create(userPermission, fileId);

            request.Fields = "id";
            batch.Queue(request, callback);

            await batch.ExecuteAsync();
        }
        public async Task DeleteAllFiles()
        {
            var ids = await ListFileIds();

            if (ids.Count == 0)
            {
                return;
            }

            var batch = new BatchRequest(_service);

            void Callback(Permission permission, RequestError error, int index, HttpResponseMessage message)
            {
                if (error != null)
                {
                    Console.WriteLine(error.Message);
                }
            }

            ids.ForEach(id =>
            {
                var deleteRequest = _service.Files.Delete(id);
                batch.Queue(deleteRequest, (BatchRequest.OnResponse <Permission>)Callback);
            });
            await batch.ExecuteAsync();
        }
Esempio n. 3
0
        public static void SendIndexingRequest(List <string> linksToIndex, string action)
        {
            try
            {
                var indexRequest          = new BatchRequest(_googleIndexingApiClientService);
                var notificationResponses = new List <PublishUrlNotificationResponse>();
                foreach (var url in linksToIndex)
                {
                    var urlNotification = new UrlNotification {
                        Url = url, Type = action
                    };
                    indexRequest.Queue <PublishUrlNotificationResponse>(
                        new UrlNotificationsResource.PublishRequest(_googleIndexingApiClientService, urlNotification), (response, error, i, message) =>
                    {
                        notificationResponses.Add(response);
                    });
                }

                indexRequest.ExecuteAsync().ConfigureAwait(false);
                Log.Info($"{action} request to Google Indexing API for '{string.Join(",", linksToIndex)}' succeeded", linksToIndex);
            }
            catch (Exception ex)
            {
                Log.Error($"{action} request to Google Indexing API for '{string.Join(",", linksToIndex)}' failed: {ex.Message}", ex, linksToIndex);
            }
        }
        /// <summary>
        /// </summary>
        /// <param name="syncMetric"></param>
        /// <param name="accountName"></param>
        /// <returns>
        /// </returns>
        public async Task<bool> UploadSyncData(SyncMetric syncMetric, string accountName)
        {
            try
            {
                var analyticsService = new AnalyticsService(new BaseClientService.Initializer
                {
                    ApplicationName = ApplicationInfo.ProductName,
                    ApiKey = "AIzaSyBrpqcL6Nh1vVecfhIbxGVnyGHMZ8-aH6k"
                });
                var batchRequest = new BatchRequest(analyticsService);
                var metric = new CustomMetric
                {
                    Name = "SyncMetric",
                    Kind = "string"
                };

                var insertRequest = analyticsService.Management.CustomMetrics.Insert(metric, "", "");
                batchRequest.Queue<CustomMetric>(insertRequest, InsertMetricCallback);
                await batchRequest.ExecuteAsync();
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                return false;
            }
            return true;
        }
Esempio n. 5
0
        /// <summary>
        /// Add multiple students in a specified course.
        /// </summary>
        /// <param name="courseId">Id of the course to add students.</param>
        /// <param name="studentEmails">Email address of the students.</param>
        public static void ClassroomBatchAddStudents(string courseId,
                                                     List <string> studentEmails)
        {
            try
            {
                /* Load pre-authorized user credentials from the environment.
                 * TODO(developer) - See https://developers.google.com/identity for
                 * guides on implementing OAuth2 for your application. */
                GoogleCredential credential = GoogleCredential.GetApplicationDefault()
                                              .CreateScoped(ClassroomService.Scope.ClassroomRosters);

                // Create Classroom API service.
                var service = new ClassroomService(new BaseClientService.Initializer
                {
                    HttpClientInitializer = credential,
                    ApplicationName       = "Classroom Snippets"
                });

                var batch = new BatchRequest(service, "https://classroom.googleapis.com/batch");
                BatchRequest.OnResponse <Student> callback = (student, error, i, message) =>
                {
                    if (error != null)
                    {
                        Console.WriteLine("Error adding student to the course: {0}", error.Message);
                    }
                    else
                    {
                        Console.WriteLine("User '{0}' was added as a student to the course.",
                                          student.Profile.Name.FullName);
                    }
                };
                foreach (var studentEmail in studentEmails)
                {
                    var student = new Student()
                    {
                        UserId = studentEmail
                    };
                    var request = service.Courses.Students.Create(student, courseId);
                    batch.Queue <Student>(request, callback);
                }

                Task.WaitAll(batch.ExecuteAsync());
            }
            catch (Exception e)
            {
                // TODO(developer) - handle error appropriately
                if (e is AggregateException)
                {
                    Console.WriteLine("Credential Not found");
                }
                else if (e is GoogleApiException)
                {
                    Console.WriteLine("Course does not exist.");
                }
                else
                {
                    throw;
                }
            }
        }
        public async Task <TasksWrapper> DeleteReminderTasks(List <ReminderTask> reminderTasks, IDictionary <string, object> taskListSpecificData)
        {
            var deletedTasks = new TasksWrapper();

            if (!reminderTasks.Any())
            {
                deletedTasks.IsSuccess = true;
                return(deletedTasks);
            }

            CheckTaskListSpecificData(taskListSpecificData);

            var errorList = new Dictionary <int, ReminderTask>();
            //Get Calendar Service
            var calendarService = GetTasksService(AccountName);

            if (reminderTasks == null || string.IsNullOrEmpty(TaskListId))
            {
                deletedTasks.IsSuccess = false;
                return(deletedTasks);
            }

            try
            {
                if (reminderTasks.Any())
                {
                    //Create a Batch Request
                    var batchRequest = new BatchRequest(calendarService);

                    //Split the list of calendarAppointments by 1000 per list
                    //Iterate over each appointment to create a event and batch it
                    for (var i = 0; i < reminderTasks.Count; i++)
                    {
                        if (i != 0 && i % 999 == 0)
                        {
                            await batchRequest.ExecuteAsync();

                            batchRequest = new BatchRequest(calendarService);
                        }

                        var appointment   = reminderTasks[i];
                        var deleteRequest = calendarService.Tasks.Delete(TaskListId,
                                                                         appointment.TaskId);
                        batchRequest.Queue <Task>(deleteRequest,
                                                  (content, error, index, message) =>
                                                  CallbackEventErrorMessage(content, error, index, message, reminderTasks,
                                                                            "Error in deleting events", errorList, deletedTasks));
                    }
                    await batchRequest.ExecuteAsync();
                }
            }
            catch (Exception exception)
            {
                Logger.Error(exception);
                deletedTasks.IsSuccess = false;
                return(deletedTasks);
            }
            deletedTasks.IsSuccess = true;
            return(deletedTasks);
        }
Esempio n. 7
0
        public async Task ShareAsync(string itemId, string userEmail)
        {
            var batch = new BatchRequest(_service);

            var userPermission = new Permission
            {
                Type         = "user",
                Role         = "reader",
                EmailAddress = userEmail,
            };

            var request = _service.Permissions.Create(userPermission, itemId);

            request.Fields = "id";
            batch.Queue(request, (BatchRequest.OnResponse <Permission>)((permission, error, index, message) =>
            {
                if (error != null)
                {
                    Console.WriteLine(error.Message);
                }
                else
                {
                    Console.WriteLine("Permission ID: " + permission.Id);
                }
            }));
            await batch.ExecuteAsync();
        }
Esempio n. 8
0
        /// <summary>
        /// </summary>
        /// <param name="syncMetric"></param>
        /// <param name="accountName"></param>
        /// <returns>
        /// </returns>
        public async Task <bool> UploadSyncData(SyncMetric syncMetric, string accountName)
        {
            try
            {
                var analyticsService = new AnalyticsService(new BaseClientService.Initializer
                {
                    ApplicationName = ApplicationInfo.ProductName,
                    ApiKey          = "AIzaSyBrpqcL6Nh1vVecfhIbxGVnyGHMZ8-aH6k"
                });
                var batchRequest = new BatchRequest(analyticsService);
                var metric       = new CustomMetric
                {
                    Name = "SyncMetric",
                    Kind = "string"
                };

                var insertRequest = analyticsService.Management.CustomMetrics.Insert(metric, "", "");
                batchRequest.Queue <CustomMetric>(insertRequest, InsertMetricCallback);
                await batchRequest.ExecuteAsync();
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                return(false);
            }
            return(true);
        }
        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);
        }
Esempio n. 10
0
        /// <summary>
        /// Adds several products to the specified account, as a batch.
        /// </summary>
        /// <returns>The task containing the list of products</returns>
        private async Task <List <Product> > InsertProductBatch(ulong merchantId)
        {
            Console.WriteLine("=================================================================");
            Console.WriteLine("Inserting several products");
            Console.WriteLine("=================================================================");

            // Create a batch request.
            BatchRequest request = new BatchRequest(service);

            List <Product> products = new List <Product>();

            // Add three product insertions to the queue.
            for (int i = 0; i < 3; i++)
            {
                ProductsResource.InsertRequest insertRequest =
                    service.Products.Insert(shoppingUtil.GenerateProduct(), merchantId);
                request.Queue <Product>(
                    insertRequest,
                    (content, error, index, message) =>
                {
                    products.Add(content);
                    Console.WriteLine(String.Format("Product inserted with id {0}", ((Product)content).Id));
                });
            }
            await request.ExecuteAsync(CancellationToken.None);

            return(products);
        }
Esempio n. 11
0
        /// <summary>
        /// Metoda pro hromadny import udalosti do google kalendare
        /// </summary>
        /// <param name="service"></param>
        /// <returns></returns>
        async static Task PrijdejHromadneUdalosti(CalendarService service)
        {
            var request2 = new BatchRequest(service);

            foreach (var zaznam in Uzivatel.ZaznamyProGoogleKalendar)
            {
                request2.Queue <Event>(service.Events.Insert(
                                           new Event
                {
                    Summary     = zaznam.Titulek,
                    Location    = zaznam.MistoUrl,
                    Description = zaznam.Popis,
                    Start       = new EventDateTime()
                    {
                        DateTime = zaznam.Start
                    },
                    End = new EventDateTime()
                    {
                        DateTime = zaznam.Konec
                    }
                }, CalendarId),
                                       (content, error, i, message) =>
                {
                    // Put your callback code here.
                    Uzivatel.ChybovaHlaska = "Chyba behem importu do google kalendáře.";
                });
            }

            await request2.ExecuteAsync();
        }
        public void ExecuteAsync_NoCallback_Test()
        {
            var handler     = new BatchMessageHandler(true);
            var initializer = new BaseClientService.Initializer()
            {
                HttpClientFactory = new MockHttpClientFactory(handler)
            };

            using (var service = new MockClientService(initializer, "http://sample.com"))
            {
                var responses = new List <Tuple <MockResponse, RequestError, HttpResponseMessage> >();
                var batch     = new BatchRequest(service);
                var request1  = new TestClientServiceRequest(service, new MockRequest
                {
                    ETag = "\"100\"",
                    Name = "Name1"
                });
                var request2 = new TestClientServiceRequest(service, new MockRequest
                {
                    ETag = "\"200\"",
                    Name = "Name1-1"
                });
                batch.Queue <MockResponse>(request1, null);
                batch.Queue <MockResponse>(request2, null);
                batch.ExecuteAsync().Wait();
            }
        }
Esempio n. 13
0
        public async Task <CalendarUpdateResult> AddStudentGroupSchedule(CalendarService calendarService,
                                                                         StudentGroupSchedule schedule)
        {
            var calendarEvents = ResolveEventsFromSchedule(schedule);

            try
            {
                var batchRequest = new BatchRequest(calendarService);

                foreach (var calendarEvent in calendarEvents.Take(3)) //TODO: Take all at the end of project
                {
                    batchRequest.Queue(calendarService.Events.Insert(calendarEvent, "primary"),
                                       async(Event content, RequestError error, int index, HttpResponseMessage message) =>
                    {
                        var messageContent = await message.Content.ReadAsStringAsync();
                        if (error is null)
                        {
                            return;
                        }

                        throw new Exception(error.Message);
                    });
                }

                await batchRequest.ExecuteAsync();

                return(new CalendarUpdateResult(true));
            }
            catch (Exception e)
            {
                return(new CalendarUpdateResult(e.Message));
            }
        }
Esempio n. 14
0
        private async Task ShareWithAccountsAsync(string fileId, string accounts)
        {
            if (string.IsNullOrEmpty(accounts))
            {
                return;
            }

            var newEmails = accounts.Split(';', StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim()).Distinct().ToArray();

            _logger.LogInformation($"Sharing file {fileId} with {accounts}.");

            var folder = await new FilesResource.GetRequest(_driveService, fileId)
            {
                Fields = "id,permissions", QuotaUser = QuotaUser
            }.ExecuteAsync();
            var remove = folder.Permissions.Where(x => !newEmails.Contains(x.EmailAddress) && x.EmailAddress != _config.CredentialParameters.ClientEmail).Select(x => _driveService.Permissions.Delete(folder.Id, x.Id)).ToList();
            var add    = newEmails.Except(folder.Permissions.Select(x => x.EmailAddress))
                         .Select(x => new PermissionsResource.CreateRequest(_driveService, new Permission {
                EmailAddress = x, Type = "user", Role = "reader"
            }, folder.Id)
            {
                QuotaUser             = QuotaUser,
                SendNotificationEmail = false
            }).ToList();

            var cb    = DefaultBatchCallback <Permission>();
            var batch = new BatchRequest(_driveService);

            remove.ForEach(x => batch.Queue(x, cb));
            add.ForEach(x => batch.Queue(x, cb));
            await batch.ExecuteAsync();
        }
        /// <summary>
        /// Metoda wysyła wszystkie zdarzenia do kalendarza jako jeden request.
        /// Wykonywana po zaktualizowaniu wszystkich zdarzeń z bazy danych.
        /// </summary>
        public async Task SendEventsRequest()
        {
            Logs.WriteErrorLog("SendEventsRequest " + Request.Count.ToString());

            await Request.ExecuteAsync();

            Request = new BatchRequest(Service);
        }
        public async void BatchInsertFromTemplate(int UserId, string Timezone, List <WeeklyTemplateEventData> fromTemplateEvents)
        {
            string AccessToken = oAuthService.GetGoogleAccessToken(UserId);

            if (AccessToken != null && fromTemplateEvents.Count != 0)
            {
                System.Diagnostics.Debug.WriteLine("Calendar has FromTemplate events!... attemping Google batch insert!");

                string[] scopes = new string[] { "https://www.googleapis.com/auth/calendar" };
                var      flow   = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
                {
                    ClientSecrets = new ClientSecrets
                    {
                        ClientId     = oAuthService.GoogleClientId,
                        ClientSecret = oAuthService.GoogleClientSecret
                    },
                    Scopes    = scopes,
                    DataStore = new FileDataStore("Store")
                });
                var token = new TokenResponse
                {
                    AccessToken  = AccessToken,
                    RefreshToken = oAuthService.GetGoogleRefreshToken(UserId)
                };
                var credential = new UserCredential(flow, UserId.ToString(), token);

                var service = new CalendarService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName       = oAuthService.GoogleApplicationName,
                });

                var request = new BatchRequest(service);

                foreach (WeeklyTemplateEventData template in fromTemplateEvents)
                {
                    request.Queue <Event>(service.Events.Insert(
                                              new Event
                    {
                        Summary = template.Title,
                        Start   = new EventDateTime()
                        {
                            DateTimeRaw = template.StartDateTime, TimeZone = Timezone
                        },
                        End = new EventDateTime()
                        {
                            DateTimeRaw = template.EndDateTime, TimeZone = Timezone
                        },
                        ColorId = exCalHelperService.GetGoogleColor(template.CategoryId)
                    }, "primary"),
                                          (content, error, i, message) =>
                    {
                        exCalHelperService.StoreExternalEventId(UserId, template.LocalId, content.Id, 1, content.ETag);
                    });
                }
                await request.ExecuteAsync();
            }
        }
Esempio n. 17
0
        private static void SafeExecuteSync(BatchRequest batchRequest, int attemptOrderNumber)
        {
            // Attempt to execute provided request.
            try { Task.Run(async() => { await batchRequest.ExecuteAsync(); }).Wait(); }

            // On request operation canceled
            catch (OperationCanceledException ex)
            {
                // Increase attempt order number by one.
                attemptOrderNumber++;

                // Validate whether request reattempt limit hasn't been exceeded
                if (RequestsExecutor._cancellationErrorAttemptsLimit < attemptOrderNumber)
                {
                    // ... and throw appropriate exception if has. attempt
                    throw new BatchRequestExecutionUnexpectedException(batchRequest, ex);
                }

                // Await appropriate cooldown period.
                Thread.Sleep(RequestsExecutor._cancellationErrorCooldown);

                // Reattempt.
                RequestsExecutor.SafeExecuteSync(batchRequest, attemptOrderNumber);
            }

            // On google internal error encounter, retry
            catch (Google.GoogleApiException ex) when(ex.Message.Contains("Internal error encountered. [500]"))
            {
                // Increase attempt order number by one.
                attemptOrderNumber++;

                // Validate whether request reattempt limit hasn't been exceeded
                if (RequestsExecutor._internalErrorAttemptsLimit < attemptOrderNumber)
                {
                    // ... and throw appropriate exception if has. attempt
                    throw new BatchRequestExecutionUnexpectedException(batchRequest, ex);
                }

                // Await appropriate cooldown period.
                Thread.Sleep(RequestsExecutor._internalErrorCooldown);

                // Reattempt.
                RequestsExecutor.SafeExecuteSync(batchRequest, attemptOrderNumber);
            }

            // On used all available requests quota
            catch (Google.GoogleApiException ex) when(ex.Message.Contains("Quota exceeded for quota group"))
            {
                // Set session request limiter state to indicate no available google requests quota at this time.
                SessionRequestsLimiter.Instance.ClearAvailableQuota();

                // Reattempt.
                RequestsExecutor.SafeExecuteSync(batchRequest, attemptOrderNumber);
            }

            // On any other unexpected database error
            catch (Google.GoogleApiException ex) { throw new BatchRequestExecutionUnexpectedException(batchRequest, ex); }
        }
Esempio n. 18
0
        // GET: Selection
        public async Task <ActionResult> Index(CancellationToken cancellationToken)
        {
            var result = await new AuthorizationCodeMvcApp(this, new AppFlowMetadata()).AuthorizeAsync(cancellationToken);

            if (result.Credential != null)
            {
                var service = new DriveService(new BaseClientService.Initializer
                {
                    HttpClientInitializer = result.Credential,
                    ApplicationName       = ApplicationName
                });

                try
                {
                    var selectionViewModel = new SelectionViewModel();
                    var examLinksList      = new List <ExamLink>();

                    var request          = new BatchRequest(service);
                    var selectedPaperIds = string.Join(",", ((List <int>)Session["SelectedIds"]).ToArray());
                    var examPapers       = HttpDataProvider.GetData <List <dynamic> >(string.Format("exam/forids?examIds={0}", selectedPaperIds));

                    examPapers.ForEach(delegate(dynamic examPaper) {
                        string fileId = examPaper.FileStoreId;

                        request.Queue <Google.Apis.Drive.v2.Data.File>(service.Files.Get(fileId),
                                                                       (file, error, x, message) =>
                        {
                            if (error != null)
                            {
                                throw new Exception("error");
                            }
                            else
                            {
                                examLinksList.Add(new ExamLink {
                                    PaperName = examPaper.PaperName, PaperUrl = file.WebContentLink, FileId = fileId
                                });
                            }
                        });
                    });

                    await request.ExecuteAsync();

                    selectionViewModel.ExamLinks = examLinksList;
                    Session.Remove("SelectedIds");
                    return(View(selectionViewModel));
                }
                catch (Exception ex)
                {
                    // Todo: Log errors and show friendly error
                    throw ex;
                }
            }
            else
            {
                return(new RedirectResult(result.RedirectUri));
            }
        }
Esempio n. 19
0
        public bool shareFile(CommonDescriptor fileToShare, string role, string email, string optionalMessage)
        {
            try {
                Console.WriteLine("STARTED SHARING");
                var _googleDriveService = InitializeAPI.googleDriveService;
                var batch = new BatchRequest(_googleDriveService);
                BatchRequest.OnResponse <Permission> callback = delegate(
                    Permission permission,
                    RequestError error,
                    int index,
                    System.Net.Http.HttpResponseMessage message)
                {
                    if (error != null)
                    {
                        // Handle error
                        Console.WriteLine(error.Message);
                    }
                    else
                    {
                        Console.WriteLine("Permission ID: " + permission.Id);
                    }
                };

                //TODO: launch the share window view, get the email address
                //shareWindow window = new shareWindow();
                //window.Show();
                //get the informaiton


                //TODO: replace these permissions with the permissions entered on the shareWindow
                Permission userPermission = new Permission();
                userPermission.Type         = "user";
                userPermission.Role         = role;  //TODO. pick the correct role
                userPermission.EmailAddress = email; //TODO, enter the email address

                var request = _googleDriveService.Permissions.Create(userPermission, fileToShare.FileID);
                request.Fields       = "id";
                request.EmailMessage = optionalMessage; //TODO enter message
                batch.Queue(request, callback);

                var task = batch.ExecuteAsync();
            }
            catch (Exception e)
            {
                //caught a bug
                Console.WriteLine(e.Message);
            }


            return(true);
        }
Esempio n. 20
0
    private async Task Run()
    {
        var privatekey          = "private key";
        var accountEmailAddress = "email address";
        var credentials         = new ServiceAccountCredential(
            new ServiceAccountCredential.Initializer(accountEmailAddress)
        {
            Scopes = new[] { AnalyticsService.Scope.AnalyticsReadonly }
        }.FromPrivateKey(privatekey));
        var service = new AnalyticsService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credentials,
            ApplicationName       = "Test"
        });
        var request = new BatchRequest(service);

        BatchRequest.OnResponse <GaData> callback = (content, error, i, message) =>
        {
            if (error != null)
            {
                Console.WriteLine("Error: {0}", error.Message);
            }
            else
            {
                if (content.Rows != null)
                {
                    foreach (var item in content.Rows)
                    {
                        foreach (var item1 in item)
                        {
                            Console.WriteLine(item1);
                        }
                    }
                }
                else
                {
                    Console.WriteLine("Not Found");
                }
            }
        };
        int counter = 0;

        while (counter < 5)
        {
            var req = service.Data.Ga.Get("ga:XXXXX", "30daysAgo", "yesterday", "ga:sessions");
            req.Filters = "ga:pagePath==/page" + counter + ".html";
            request.Queue <GaData>(req, callback);
            counter++;
        }
        await request.ExecuteAsync();
    }
Esempio n. 21
0
        public static void FileSharing(string fileId, DriveService driveService)
        {
            try
            {
                fileId = "1XY2zomDP2qYZJ-aTAPLHSMEu-v7RVjii";
                var batch = new BatchRequest(driveService);
                BatchRequest.OnResponse <Permission> callback = delegate(
                    Permission permission,
                    RequestError error,
                    int index,
                    System.Net.Http.HttpResponseMessage message)
                {
                    if (error != null)
                    {
                        // Handle error
                        Console.WriteLine(error.Message);
                    }
                    else
                    {
                        Console.WriteLine("Permission ID: " + permission.Id);
                    }
                };
                Permission userPermission = new Permission()
                {
                    Type         = "user",
                    Role         = "writer",
                    EmailAddress = "*****@*****.**",
                };
                var request = driveService.Permissions.Create(userPermission, fileId);
                request.Fields = "id";

                batch.Queue(request, callback);

                //Permission domainPermission = new Permission()
                //{
                //    Type = "user",
                //    Role = "reader",
                //    Domain = "gmail.com"
                //};
                //request = driveService.Permissions.Create(domainPermission, fileId);
                //request.Fields = "id";
                //batch.Queue(request, callback);
                var task = batch.ExecuteAsync();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
Esempio n. 22
0
        public async Task <ActionResult> SendEmailAsync(CancellationToken cancellaionToken, SelectionViewModel model)
        {
            var result = await new AuthorizationCodeMvcApp(this, new AppFlowMetadata()).AuthorizeAsync(cancellaionToken);

            if (result.Credential != null)
            {
                var service = new DriveService(new BaseClientService.Initializer
                {
                    HttpClientInitializer = result.Credential,
                    ApplicationName       = ApplicationName
                });

                var request = new BatchRequest(service);

                try
                {
                    Google.Apis.Drive.v2.Data.Permission newPermission = new Google.Apis.Drive.v2.Data.Permission();
                    newPermission.Value = model.EmailAddress;
                    newPermission.Type  = "user";
                    newPermission.Role  = "reader";
                    //service.Permissions.Insert()
                    model.ExamLinks.ForEach(delegate(ExamLink examLink) {
                        request.Queue <Google.Apis.Drive.v2.Data.Permission>(service.Permissions.Insert(newPermission, examLink.FileId),
                                                                             (permission, error, x, message) =>
                        {
                            if (error != null)
                            {
                                throw new Exception("error");
                            }
                        });
                    });

                    await request.ExecuteAsync();

                    //sendEmail(model);
                    return(View("Index", model));
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            else
            {
                return(new RedirectResult(result.RedirectUri));
            }
        }
Esempio n. 23
0
        public async Task FileSharing(DriveService driveService, string fileId, string email)
        {
            try
            {
                var batch = new BatchRequest(driveService);
                BatchRequest.OnResponse <Permission> callback = delegate(
                    Permission permission,
                    RequestError error,
                    int index,
                    HttpResponseMessage message)
                {
                    if (error != null)
                    {
                        // Handle error
                        foreach (var singleError in error.Errors)
                        {
                            _logger.LogError($"Message: {singleError.Message}");
                            _logger.LogError($"Domain: {singleError.Domain}");
                            _logger.LogError($"Location: {singleError.Location}");
                            _logger.LogError($"LocationType: {singleError.LocationType}");
                            _logger.LogError($"Reason: {singleError.Reason}");
                        }
                    }
                    else
                    {
                        _logger.LogInformation("Permission ID: " + permission.Id);
                    }
                };
                var userPermission = new Permission
                {
                    Type         = "user",
                    Role         = "writer",
                    EmailAddress = email,
                };
                var request = driveService.Permissions.Create(userPermission, fileId);
                request.Fields = "id";

                batch.Queue(request, callback);

                await batch.ExecuteAsync();
            }
            catch (Exception e)
            {
                _logger.LogError(default(EventId), e, e.Message);
                throw;
            }
        }
        public async void BatchDeleteFromTemplateEvents(int UserId, List <ExternalEventIds> externalEventIds)
        {
            string AccessToken = oAuthService.GetGoogleAccessToken(UserId);

            if (AccessToken != null && externalEventIds.Count != 0)
            {
                string[] scopes = new string[] { "https://www.googleapis.com/auth/calendar" };
                var      flow   = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
                {
                    ClientSecrets = new ClientSecrets
                    {
                        ClientId     = oAuthService.GoogleClientId,
                        ClientSecret = oAuthService.GoogleClientSecret
                    },
                    Scopes    = scopes,
                    DataStore = new FileDataStore("Store")
                });
                var token = new TokenResponse
                {
                    AccessToken  = AccessToken,
                    RefreshToken = oAuthService.GetGoogleRefreshToken(UserId)
                };
                var credential = new UserCredential(flow, UserId.ToString(), token);

                var service = new CalendarService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName       = oAuthService.GoogleApplicationName,
                });

                var request = new BatchRequest(service);

                foreach (ExternalEventIds template in externalEventIds)
                {
                    if (template.GoogleId != null)
                    {
                        request.Queue <Event>(service.Events.Delete("primary", template.GoogleId),
                                              (content, error, i, message) =>
                        {
                            exCalHelperService.DeleteExternalEvent(template.GoogleId);
                        });
                    }
                }
                await request.ExecuteAsync();
            }
        }
Esempio n. 25
0
        /// <summary>
        /// Delete Events from the Google Calendar
        /// </summary>
        /// <param name="owner">calendar owner</param>
        /// <param name="calendarId">calendar id</param>
        /// <param name="events">events to remove</param>
        /// <returns>async task for the background Api tasks</returns>
        private static async Task DeleteGoogleEventsAsync(string owner, string calendarId, List <GCalEventItem> events)
        {
            try
            {
                int batchCount = 1;

                // Create a batch request.
                var request = new BatchRequest(GetCalendarService(owner));

                foreach (GCalEventItem e in events)
                {
                    if (batchCount < 900)
                    {
                        request.Queue <Event>(
                            GetCalendarService(owner).Events.Delete(calendarId, e.EventId), (content, error, i, message) =>
                        {
                            // Put your callback code here.
                            if (error != null)
                            {
                                log.Error("Error deleting removed appointments from Google Calendar: " + error.Message);
                            }
                        });
                        batchCount++;
                    }
                    else
                    {
                        // Execute the batch request and create a new batch as cannot send more than 1000
                        await request.ExecuteAsync();

                        batchCount = 1;
                        request    = new BatchRequest(GetCalendarService(owner));
                    }
                }

                // Execute the batch request
                await request.ExecuteAsync();

                googleCalEvents = (List <GCalEventItem>)googleCalEvents.Except(events).ToList();
            }
            catch (Exception e)
            {
                log.Error("Error deleting Google Events : " + e.Message);
            }
        }
        public async Task DeleteContainerAsync(string containerName)
        {
            try
            {
                var batch = new BatchRequest(_storageService);

                foreach (var blob in await ListBlobsAsync(containerName))
                {
                    batch.Queue <string>(_storageService.Objects.Delete(_bucket, $"{blob.Container}/{blob.Name}"),
                                         (content, error, i, message) => { });
                }

                await batch.ExecuteAsync();
            }
            catch (GoogleApiException gae)
            {
                throw Error(gae);
            }
        }
Esempio n. 27
0
        public static List <UrlNotificationMetadata> VerifySubmissionStatus(List <string> urls)
        {
            var metadataRequest   = new BatchRequest(_googleIndexingApiClientService);
            var metadataResponses = new List <UrlNotificationMetadata>();

            foreach (var url in urls)
            {
                metadataRequest.Queue <UrlNotificationMetadata>(
                    new UrlNotificationsResource.GetMetadataRequest(_googleIndexingApiClientService)
                {
                    Url = url
                }, (response, error, i, message) =>
                {
                    metadataResponses.Add(response);
                });
            }
            metadataRequest.ExecuteAsync().ConfigureAwait(false);
            return(metadataResponses);
        }
Esempio n. 28
0
        public void DeleteContainer(string containerName)
        {
            try
            {
                var batch = new BatchRequest(_storageService);

                foreach (var blob in ListBlobs(containerName))
                {
                    batch.Queue <string>(_storageService.Objects.Delete(_bucket, $"{blob.Container}/{blob.Name}"),
                                         (content, error, i, message) => { });
                }

                AsyncHelpers.RunSync(() => batch.ExecuteAsync());
            }
            catch (GoogleApiException gae)
            {
                throw Error(gae);
            }
        }
Esempio n. 29
0
        private static void ShareFileById(string fileId, string filename, string recipientEmail, string senderName, RoleType roleType)
        {
            var batch = new BatchRequest(DriveService);

            BatchRequest.OnResponse <Permission> callback = delegate(
                Permission permission,
                RequestError error,
                int index,
                System.Net.Http.HttpResponseMessage message)
            {
                if (error != null)
                {
                    MessageBox.Show("Could not share the file with " + recipientEmail + "!\nReason: " + error.Message, "Drive Crypt", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            };

            Permission userPermission = new Permission();

            userPermission.Type         = "user";
            userPermission.Role         = roleType.ToString();
            userPermission.EmailAddress = recipientEmail;

            var request = DriveService.Permissions.Create(userPermission, fileId);

            request.Fields = "id";
            if (Path.GetExtension(filename) == FileCryptor.DRIVE_CRYPT_EXTENSTION)
            {
                request.SendNotificationEmail = true;
                request.EmailMessage          = string.Format("{0} has shared the following encoded file with you:\n{1}\nwhich you can view under http://drive.google.com/file/d/{2} \nbut it can only be readable after decoding, using DriveCrypt application.", senderName, filename, fileId);
            }
            else
            {
                request.SendNotificationEmail = false;
            }

            batch.Queue(request, callback);

            batch.ExecuteAsync();
        }
Esempio n. 30
0
        /// <summary>
        /// Deletes several products from the specified account, as a batch.
        /// </summary>
        private async Task DeleteProductsBatch(ulong merchantId, List <Product> newProductsBatch)
        {
            Console.WriteLine("=================================================================");
            Console.WriteLine("Deleting several products");
            Console.WriteLine("=================================================================");

            // Create a batch request.
            BatchRequest request = new BatchRequest(service);

            foreach (Product product in newProductsBatch)
            {
                ProductsResource.DeleteRequest deleteRequest = service.Products.Delete(merchantId, product.Id);
                request.Queue <Product>(
                    deleteRequest,
                    (content, error, i, message) =>
                {
                    Console.WriteLine("Product deleted.");
                });
            }

            await request.ExecuteAsync(CancellationToken.None);
        }
        private async Task <List <Appointment> > AddCalendarEventsInternal(List <Appointment> calendarAppointments,
                                                                           bool addDescription, bool addReminder,
                                                                           bool addAttendees,
                                                                           bool attendeesToDescription, CalendarService calendarService,
                                                                           Dictionary <int, Appointment> errorList)
        {
            var addedEvents = new List <Appointment>();
            //Create a Batch Request
            var batchRequest = new BatchRequest(calendarService);

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

                    batchRequest = new BatchRequest(calendarService);
                }

                var appointment   = calendarAppointments[i];
                var calendarEvent = CreateGoogleCalendarEvent(appointment, addDescription, addReminder,
                                                              addAttendees,
                                                              attendeesToDescription);
                var insertRequest = calendarService.Events.Insert(calendarEvent,
                                                                  CalendarId);
                insertRequest.SendNotifications = false;
                insertRequest.MaxAttendees      = 10000;
                batchRequest.Queue <Event>(insertRequest,
                                           (content, error, index, message) =>
                                           CallbackEventErrorMessage(content, error, index, message,
                                                                     calendarAppointments, "Error in adding events", errorList,
                                                                     addedEvents));
            }

            await batchRequest.ExecuteAsync();

            return(addedEvents);
        }
        /// <summary>
        /// Deletes several products from the specified account, as a batch.
        /// </summary>
        private async Task DeleteProductsBatch(ulong merchantId, List<Product> newProductsBatch)
        {
            Console.WriteLine("=================================================================");
            Console.WriteLine("Deleting several products");
            Console.WriteLine("=================================================================");

            // Create a batch request.
            BatchRequest request = new BatchRequest(service);
            foreach (Product product in newProductsBatch) {
                ProductsResource.DeleteRequest deleteRequest = service.Products.Delete(merchantId, product.Id);
                request.Queue<Product>(
                         deleteRequest,
                         (content, error, i, message) =>
                         {
                             Console.WriteLine("Product deleted.");
                         });
            }

            await request.ExecuteAsync(CancellationToken.None);
        }
Esempio n. 33
0
        public async Task<AppointmentsWrapper> UpdateCalendarEvents(List<Appointment> calendarAppointments, bool addDescription,
            bool addReminder, bool addAttendees, bool attendeesToDescription,
            IDictionary<string, object> calendarSpecificData)
        {
            var updatedAppointments = new AppointmentsWrapper();
            if (!calendarAppointments.Any())
            {
                updatedAppointments.IsSuccess = true;
                return updatedAppointments;
            }

            CheckCalendarSpecificData(calendarSpecificData);

            var errorList = new Dictionary<int, Appointment>();
            //Get Calendar Service
            var calendarService = GetCalendarService(AccountName);

            if (calendarAppointments == null || string.IsNullOrEmpty(CalendarId))
            {
                updatedAppointments.IsSuccess = false;
                return updatedAppointments;
            }

            try
            {
                if (calendarAppointments.Any())
                {
                    //Create a Batch Request
                    var batchRequest = new BatchRequest(calendarService);

                    //Split the list of calendarAppointments by 1000 per list

                    //Iterate over each appointment to create a event and batch it 
                    for (var i = 0; i < calendarAppointments.Count; i++)
                    {
                        if (i != 0 && i % 999 == 0)
                        {
                            await batchRequest.ExecuteAsync();
                            batchRequest = new BatchRequest(calendarService);
                        }

                        var appointment = calendarAppointments[i];
                        var calendarEvent = CreateUpdatedGoogleCalendarEvent(appointment, addDescription, addReminder,
                            addAttendees, attendeesToDescription);
                        var updateRequest = calendarService.Events.Update(calendarEvent,
                            CalendarId, calendarEvent.Id);
                        
                        batchRequest.Queue<Event>(updateRequest,
                            (content, error, index, message) =>
                                CallbackEventErrorMessage(content, error, index, message, calendarAppointments, "Error in updating event",errorList,updatedAppointments));
                    }

                    await batchRequest.ExecuteAsync();
                }
            }
            catch (Exception exception)
            {
                Logger.Error(exception);
                updatedAppointments.IsSuccess = false;
                return updatedAppointments;
            }
            updatedAppointments.IsSuccess = true;
            return updatedAppointments;
        }
Esempio n. 34
0
        private async Task<List<Appointment>> AddCalendarEventsInternal(List<Appointment> calendarAppointments,
            bool addDescription, bool addReminder,
            bool addAttendees,
            bool attendeesToDescription, CalendarService calendarService,
            Dictionary<int, Appointment> errorList)
        {
            var addedEvents = new List<Appointment>();
            //Create a Batch Request
            var batchRequest = new BatchRequest(calendarService);

            for (var i = 0; i < calendarAppointments.Count; i++)
            {
                if (i != 0 && i % 999 == 0)
                {
                    await batchRequest.ExecuteAsync();
                    batchRequest = new BatchRequest(calendarService);
                }

                var appointment = calendarAppointments[i];
                var calendarEvent = CreateGoogleCalendarEvent(appointment, addDescription, addReminder,
                    addAttendees,
                    attendeesToDescription);
                var insertRequest = calendarService.Events.Insert(calendarEvent,
                    CalendarId);
                insertRequest.MaxAttendees = 10000;
                batchRequest.Queue<Event>(insertRequest,
                    (content, error, index, message) =>
                        CallbackEventErrorMessage(content, error, index, message, 
                        calendarAppointments, "Error in adding events",errorList,
                            addedEvents));
            }

            await batchRequest.ExecuteAsync();

            return addedEvents;
        }
        public async Task<CalendarAppointments> DeleteCalendarEvents(List<Appointment> calendarAppointments,
            IDictionary<string, object> calendarSpecificData)
        {
            var deletedAppointments = new CalendarAppointments();
            if (!calendarAppointments.Any())
            {
                deletedAppointments.IsSuccess = true;
                return deletedAppointments;
            }

            CheckCalendarSpecificData(calendarSpecificData);

            var errorList = new Dictionary<int, Appointment>();
            //Get Calendar Service
            var calendarService = GetCalendarService(AccountName);

            if (calendarAppointments == null || string.IsNullOrEmpty(CalendarId))
            {
                deletedAppointments.IsSuccess = false;
                return deletedAppointments;
            }

            try
            {
                if (calendarAppointments.Any())
                {
                    //Create a Batch Request
                    var batchRequest = new BatchRequest(calendarService);

                    //Split the list of calendarAppointments by 1000 per list
                    //Iterate over each appointment to create a event and batch it 
                    for (var i = 0; i < calendarAppointments.Count; i++)
                    {
                        if (i != 0 && i % 999 == 0)
                        {
                            await batchRequest.ExecuteAsync();
                            batchRequest = new BatchRequest(calendarService);
                        }

                        var appointment = calendarAppointments[i];
                        var deleteRequest = calendarService.Events.Delete(CalendarId,
                            appointment.AppointmentId);
                        batchRequest.Queue<Event>(deleteRequest,
                            (content, error, index, message) =>
                                CallbackEventErrorMessage(content, error, index, message, calendarAppointments, 
                                "Error in deleting events",errorList,deletedAppointments));
                    }
                    await batchRequest.ExecuteAsync();
                }
            }
            catch (Exception exception)
            {
                Logger.Error(exception);
                deletedAppointments.IsSuccess = false;
                return deletedAppointments;
            }
            deletedAppointments.IsSuccess = true;
            return deletedAppointments;
        }
Esempio n. 36
0
    public async Task<ActionResult> Index(CancellationToken cancellationToken, string q = null)
    {
      var result = await new AuthorizationCodeMvcApp(this, new MyMailFlowMetadata()).AuthorizeAsync(cancellationToken);

      if (result.Credential != null)
      {
        List<Message> messages = new List<Message>();
        List<Label> labels = new List<Label>();

        var service = new GmailService(new BaseClientService.Initializer()
          {
            HttpClientInitializer = result.Credential,
            ApplicationName = ApplicationName
          });

        UsersResource.LabelsResource.ListRequest labelsRequest = service.Users.Labels.List("me");
        UsersResource.MessagesResource.ListRequest messagesRequest = service.Users.Messages.List("me");
        messagesRequest.Q = q ?? "label:inbox ";
        ListLabelsResponse labelsResponse = null;
        ListMessagesResponse messagesResponse = null;

        var batchRequests = new BatchRequest(service);
        batchRequests.Queue<ListLabelsResponse>(labelsRequest,
          (content, error, i, message) =>
          {
            labelsResponse = content;
          });
        batchRequests.Queue<ListMessagesResponse>(messagesRequest,
          (content, error, i, message) =>
          {
            messagesResponse = content;
          });

        await batchRequests.ExecuteAsync();

        batchRequests = new BatchRequest(service);
        foreach (var label in labelsResponse.Labels)
        {
          batchRequests.Queue<Label>(service.Users.Labels.Get("me", label.Id),
            (content, error, i, label2) =>
            {
              labels.Add(content);
            });
        }
        foreach (var message in messagesResponse.Messages)
        {
          batchRequests.Queue<Message>(service.Users.Messages.Get("me", message.Id),
            (content, error, i, message2) =>
            {
              messages.Add(content);
            });
        }

        await batchRequests.ExecuteAsync();
        ViewBag.Labels = labels;
        ViewBag.Messages = messages;
        return View();
      }
      else
      {
        return new RedirectResult(result.RedirectUri);
      }

    }
Esempio n. 37
0
    public async System.Threading.Tasks.Task UploadResults()
    {
        var request = new BatchRequest(Service);
        foreach (WorkDay day in Schedule)
        {
            // Setup request for current events.
            EventsResource.ListRequest listrequest = Service.Events.List(Calendarid);
            listrequest.TimeMin = DateTime.Today.AddDays(-6);
            listrequest.TimeMax = DateTime.Today.AddDays(15);
            listrequest.ShowDeleted = false;
            listrequest.SingleEvents = true;
            listrequest.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime;

            // Check to see if work events are already in place on the schedule, if they are,
            // setup a batch request to delete them.
            // Not the best implementation, but takes care of duplicates without tracking
            // eventIds to update existing events.
            String workevent = "Wegmans: ";
            Events eventslist = listrequest.Execute();
            if (eventslist.Items != null && eventslist.Items.Count > 0)
            {
                foreach (Event eventItem in eventslist.Items)
                {
                    if(eventItem.Start.DateTime != null)
                    {
                        DateTime eventcontainer = (DateTime)eventItem.Start.DateTime; // Typecast to use ToShortDateString() method for comparison.
                        if (((eventcontainer.ToShortDateString()) == (day.Date.ToShortDateString())) && (eventItem.Summary.Contains(workevent)))
                        {
                            request.Queue<Event>(Service.Events.Delete(Calendarid, eventItem.Id),
                                (content, error, i, message) =>
                                {
                                    if (error != null)
                                    {
                                        throw new Exception(error.ToString());
                                    }
                                });
                        }
                    }
                }
            }
            // Setup a batch request to upload the work events.
            request.Queue<Event>(Service.Events.Insert(
            new Event
            {
                Summary = workevent + day.Activity,
                Description = day.Comments,
                Location = day.Location,
                Start = new EventDateTime()
                {
                    DateTime = day.StartDateTime,
                    TimeZone = "America/New_York",
                },
                End = new EventDateTime()
                {
                    DateTime = day.EndDateTime,
                    TimeZone = "America/New_York",
                },
                Reminders = new Event.RemindersData()
                {
                    UseDefault = true,
                },
            }, Calendarid),
            (content, error, i, message) =>
            {
                if (error != null)
                {
                    throw new Exception(error.ToString());
                }
            });
        }
        // Execute batch request.
        await request.ExecuteAsync();
    }
        /// <summary>
        /// Adds several products to the specified account, as a batch.
        /// </summary>
        /// <returns>The task containing the list of products</returns>
        private async Task<List<Product>> InsertProductBatch(ulong merchantId)
        {

            Console.WriteLine("=================================================================");
            Console.WriteLine("Inserting several products");
            Console.WriteLine("=================================================================");

            // Create a batch request.
            BatchRequest request = new BatchRequest(service);

            List<Product> products = new List<Product>();
            // Add three product insertions to the queue.
            for (int i = 0; i < 3; i++)
            {
                ProductsResource.InsertRequest insertRequest =
                    service.Products.Insert(shoppingUtil.GenerateProduct(), merchantId);
                request.Queue<Product>(
                         insertRequest,
                         (content, error, index, message) =>
                         {
                             products.Add(content);
                             Console.WriteLine(String.Format("Product inserted with id {0}", ((Product)content).Id));
                         });
            }
            await request.ExecuteAsync(CancellationToken.None);
            return products;
        }
Esempio n. 39
0
        public async Task<TasksWrapper> UpdateReminderTasks(List<ReminderTask> reminderTasks,  IDictionary<string, object> taskListSpecificData)
        {
            var updatedAppointments = new TasksWrapper();
            if (!reminderTasks.Any())
            {
                updatedAppointments.IsSuccess = true;
                return updatedAppointments;
            }

            CheckTaskListSpecificData(taskListSpecificData);

            var errorList = new Dictionary<int, ReminderTask>();
            //Get Calendar Service
            var calendarService = GetTasksService(AccountName);

            if (reminderTasks == null || string.IsNullOrEmpty(TaskListId))
            {
                updatedAppointments.IsSuccess = false;
                return updatedAppointments;
            }

            try
            {
                if (reminderTasks.Any())
                {
                    //Create a Batch Request
                    var batchRequest = new BatchRequest(calendarService);

                    //Split the list of calendarAppointments by 1000 per list

                    //Iterate over each appointment to create a event and batch it 
                    for (var i = 0; i < reminderTasks.Count; i++)
                    {
                        if (i != 0 && i % 999 == 0)
                        {
                            await batchRequest.ExecuteAsync();
                            batchRequest = new BatchRequest(calendarService);
                        }

                        var appointment = reminderTasks[i];
                        var task = CreateUpdatedGoogleTask(appointment);
                        var updateRequest = calendarService.Tasks.Update(task,
                            TaskListId, task.Id);
                        batchRequest.Queue<Task>(updateRequest,
                            (content, error, index, message) =>
                                CallbackEventErrorMessage(content, error, index, message, reminderTasks,
                                "Error in updating event", errorList, updatedAppointments));
                    }

                    await batchRequest.ExecuteAsync();
                }
            }
            catch (Exception exception)
            {
                Logger.Error(exception);
                updatedAppointments.IsSuccess = false;
                return updatedAppointments;
            }
            updatedAppointments.IsSuccess = reminderTasks.Count == updatedAppointments.Count;
            return updatedAppointments;
        }
Esempio n. 40
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;
        }