Пример #1
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();
        }
        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();
            }
        }
Пример #3
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);
        }
Пример #4
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();
        }
Пример #5
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();
        }
Пример #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();
        }
Пример #8
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>
        /// Metoda tworząca listę wydarzeń do kalendarza.
        /// </summary>
        /// <param name="booking">Pojedyncza rezerwacja z listą gości.</param>
        public void MakeEventRequest(SimpleBookingUser booking)
        {
            Logs.WriteErrorLog("Robie request eventa (wrzucam zdarzenia na kolejke).");
            Logs.WriteErrorLog(booking.BookingEndTime.ToString("g"));
            Logs.WriteErrorLog(booking.BookingBeginTime.ToString("g"));
            var eventStartDateTime = new EventDateTime {
                DateTime = booking.BookingBeginTime
            };

            Logs.WriteErrorLog("Moja data rozp: " + eventStartDateTime.DateTime.ToString());
            var eventEndDateTime = new EventDateTime {
                DateTime = booking.BookingEndTime
            };

            Logs.WriteErrorLog("Moja data zakonczenia: " + eventEndDateTime.DateTime.ToString());
            Request = new BatchRequest(Service);
            Logs.WriteErrorLog("tytul: " + booking.BookingTitle);
            Logs.WriteErrorLog("Opis" + booking.BookingDescription);
            Request.Queue <Event>(Service.Events.Insert(
                                      new Event
            {
                Summary     = booking.BookingTitle,
                Description = booking.BookingDescription,
                Start       = eventStartDateTime,
                End         = eventEndDateTime
            }, CalendarId),
                                  (content, error, i, message) =>
            {
                //Do wypełnienia "Callback"
            });
            Logs.WriteErrorLog("Wrzucilem.");
        }
Пример #10
0
        // Returns google request which once executed makes spreadsheet view access allowed for specified domain
        internal static BatchRequest GetAssureViewIsDomainPermittedRequest(DriveService driveService, string spreadsheetId, string domain)
        {
            // Construct new instance of batch request
            BatchRequest batchRequest = new BatchRequest(driveService);

            // Build instance of permission class, indicating view access for the specified domain.
            Permission domainPermission = new Permission()
            {
                Type   = "domain",
                Role   = "reader",
                Domain = domain
            };

            // Construct appropriate permission resources partial request to allow specified domain spreadsheet view.
            PermissionsResource.CreateRequest domainCanViewRequest = driveService.Permissions.Create(domainPermission, spreadsheetId);
            domainCanViewRequest.Fields = "id";

            // Add partial permission resources domainCanViewRequest into the batch update queue.
            batchRequest.Queue <Permission>(domainCanViewRequest, new BatchRequest.OnResponse <Permission>((permission, error, index, message) =>
            {
                // On request response... if any error found throw appropriate exception.
                if (error != null)
                {
                    throw new InvalidOperationException($"Google drive apis is unable to provide domain specific view permission for the spreadsheet id: {spreadsheetId} Read request error message for more details: {error.Message}");
                }
            }));

            return(batchRequest);
        }
Пример #11
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));
            }
        }
Пример #12
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);
        }
Пример #13
0
        // Returns google request which once executed makes spreadsheet edit access allowed for specified email address
        internal static BatchRequest GetAssureEditIsEmailPermittedRequest(DriveService driveService, string spreadsheetId, string email)
        {
            // Construct new instance of batch request
            BatchRequest batchRequest = new BatchRequest(driveService);

            // Build instance of permission class, indicating specified email address edit access.
            Permission emailAddressPermission = new Permission()
            {
                Type         = "user",
                Role         = "writer",
                EmailAddress = email
            };

            // Construct appropriate permission resources partial request to allow specified email address spreadsheet edit access.
            PermissionsResource.CreateRequest emailAddressCanEditRequest = driveService.Permissions.Create(emailAddressPermission, spreadsheetId);
            emailAddressCanEditRequest.Fields = "id";

            // Add partial permission resources emailAddressCanEditRequest into the batch update queue.
            batchRequest.Queue <Permission>(emailAddressCanEditRequest, new BatchRequest.OnResponse <Permission>((permission, error, index, message) =>
            {
                // On request response... if any error found throw appropriate exception.
                if (error != null)
                {
                    throw new InvalidOperationException($"Google drive apis is unable to provide email address specific view permission for the spreadsheet id: {spreadsheetId} Read request error message for more details: {error.Message}");
                }
            }));

            return(batchRequest);
        }
Пример #14
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;
                }
            }
        }
        /// <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;
        }
        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();
            }
        }
Пример #17
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));
            }
        }
        //private List<BaseClientService> ServiceObjects = new List<BaseClientService>();

        public void Queue <TResponse>(IClientServiceRequest request, BatchRequest.OnResponse <TResponse> callback) where TResponse : class
        {
            SetCurrentBatchRequest(request);

            try
            {
                _currentBatchRequest.Queue(request, callback);
            }
            catch (InvalidOperationException ex)
            {
                throw;
            }
        }
        public static void QueueManySingleCallback <TResponse>(this BatchRequest batchRequest, IList <IClientServiceRequest> requests,
                                                               BatchRequest.OnResponse <TResponse> callback) where TResponse : class
        {
            if (batchRequest.Count + requests.Count() > 1000)
            {
                throw new InvalidOperationException("A batch request cannot contain more than 1000 single requests");
            }

            foreach (var clientServiceRequest in requests)
            {
                batchRequest.Queue(clientServiceRequest, callback);
            }
        }
Пример #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();
    }
Пример #21
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);
        }
Пример #22
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;
            }
        }
        /// <summary>
        /// Metoda wrzuca do kolejki żądań zdarzenia z kolejki "bezautoryzacyjnej".
        /// </summary>
        public async Task PushEventsFromQueue()
        {
            foreach (var e in EventsQueue)
            {
                Request.Queue <Event>(Service.Events.Insert(e, CalendarId),
                                      (content, error, i, message) =>
                {
                    //Do wypełnienia "Callback"
                });
            }
            await SendEventsRequest();

            EventsQueue.Clear();
        }
Пример #24
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));
            }
        }
Пример #25
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();
            }
        }
Пример #27
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);
            }
        }
Пример #28
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);
        }
Пример #29
0
        private BatchRequest CreateBatchRequest(
            IEnumerable <Message> messages,
            bool dryRun,
            BatchRequest.OnResponse <SingleMessageResponse> callback)
        {
            var batch = new BatchRequest(this.fcmClientService, FcmBatchUrl);

            foreach (var message in messages)
            {
                var body = new SendRequest()
                {
                    Message      = message,
                    ValidateOnly = dryRun,
                };
                batch.Queue(new FCMClientServiceRequest(this.fcmClientService, this.restPath, body), callback);
            }

            return(batch);
        }
Пример #30
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);
            }
        }
        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);
            }
        }
Пример #32
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;
        }
        /// <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);
        }
Пример #35
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);
      }

    }
 /// <summary>
 /// Metoda tworząca listę wydarzeń do kalendarza.
 /// </summary>
 /// <param name="booking">Pojedyncza rezerwacja z listą gości.</param>
 public void MakeEventRequest(SimpleBookingUser booking)
 {
     Logs.WriteErrorLog("Robie request eventa (wrzucam zdarzenia na kolejke).");
     Logs.WriteErrorLog(booking.BookingEndTime.ToString("g"));
     Logs.WriteErrorLog(booking.BookingBeginTime.ToString("g"));
     var eventStartDateTime = new EventDateTime { DateTime = booking.BookingBeginTime };
     Logs.WriteErrorLog("Moja data rozp: " + eventStartDateTime.DateTime.ToString());
     var eventEndDateTime = new EventDateTime { DateTime = booking.BookingEndTime };
     Logs.WriteErrorLog("Moja data zakonczenia: " + eventEndDateTime.DateTime.ToString());
     Request = new BatchRequest(Service);
     Logs.WriteErrorLog("tytul: " + booking.BookingTitle);
     Logs.WriteErrorLog("Opis" + booking.BookingDescription);
     Request.Queue<Event>(Service.Events.Insert(
         new Event
         {
             Summary = booking.BookingTitle,
             Description = booking.BookingDescription,
             Start = eventStartDateTime,
             End = eventEndDateTime
         }, CalendarId),
         (content, error, i, message) =>
         {
             //Do wypełnienia "Callback"
         });
     Logs.WriteErrorLog("Wrzucilem.");
 }