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(); }
/// <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; } } }
//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); } }
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); }
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(); }
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; } }
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; } }
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); }
//Apenas edit pois não há suporte para criar folder ao mesmo tempo inserir permissoes public static void EditPermission(DriveService service, Permission permission, string Id) { var batch = new BatchRequest(service); BatchRequest.OnResponse <Permission> callback = delegate( Permission permissionCb, RequestError error, int index, HttpResponseMessage message) { if (error != null) { throw new Exception(); } }; var request = service.Permissions.Create(permission, Id); request.Fields = "id"; batch.Queue(request, callback); request.Execute(); }
public void Queue <TResponse>(IClientServiceRequest request, BatchRequest.OnResponse <TResponse> callback) where TResponse : class { if (request == null) { throw new ArgumentNullException(nameof(request)); } if (callback == null) { throw new ArgumentNullException(nameof(callback)); } var currentBatch = _batches.Last(); if (currentBatch.Count == BatchSizeLimit) { currentBatch = new BatchRequest(_service); _batches.Add(currentBatch); } currentBatch.Queue(request, callback); }
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(); }
/// <summary> /// Batch permission modification. /// </summary> /// <param name="realFileId">File id.</param> /// <param name="realUser">User id.</param> /// <param name="realDomain">Domain id.</param> /// <returns>list of modified permissions, null otherwise.</returns> public static IList <String> DriveShareFile(string realFileId, string realUser, string realDomain) { 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(DriveService.Scope.Drive); // Create Drive API service. var service = new DriveService(new BaseClientService.Initializer { HttpClientInitializer = credential, ApplicationName = "Drive API Snippets" }); var ids = new List <String>(); var batch = new BatchRequest(service); BatchRequest.OnResponse <Permission> callback = delegate( Permission permission, RequestError error, int index, HttpResponseMessage message) { if (error != null) { // Handle error Console.WriteLine(error.Message); } else { Console.WriteLine("Permission ID: " + permission.Id); // [START_EXCLUDE silent] ids.Add(permission.Id); // [END_EXCLUDE] } }; Permission userPermission = new Permission() { Type = "user", Role = "writer", EmailAddress = realUser }; var request = service.Permissions.Insert(userPermission, realFileId); request.Fields = "id"; batch.Queue(request, callback); Permission domainPermission = new Permission() { Type = "domain", Role = "reader", Domain = realDomain }; request = service.Permissions.Insert(domainPermission, realFileId); request.Fields = "id"; batch.Queue(request, callback); var task = batch.ExecuteAsync(); task.Wait(); return(ids); } catch (Exception e) { // TODO(developer) - handle error appropriately if (e is AggregateException) { Console.WriteLine("Credential Not found. Error {0}", e.Message); } else if (e is GoogleApiException) { Console.WriteLine("Failed with an error {0}", e.Message); } else { throw; } } return(null); }
private void WrapBatchOperation <TSource>(IReadOnlyList <TSource> sourceList, Func <TSource, IClientServiceRequest> commandProvider, Action <int> callback = null) { _logger.LogMessage("Начало пакетной операции."); // nonlinear logic! List <RequestsInfo> requestsInfo = null; BatchRequest.OnResponse <object> batchCallback = (_, error, index, __) => { requestsInfo[index].ErrorMsg = error?.Message; if (requestsInfo[index].Success) { callback?.Invoke(index); } if (index == (requestsInfo.Count - 1) && requestsInfo.Any(ri => !ri.Success)) { var messages = requestsInfo.Where(ri => !ri.Success).Select(ri => ri.ErrorMsg).Distinct(); throw new InvalidOperationException(string.Join(Environment.NewLine, messages)); } }; var consideredCount = 0; const int batchSize = 100; while (consideredCount != sourceList.Count) { var batchSources = sourceList.Skip(consideredCount).Take(batchSize).ToArray(); var batch = new BatchRequest(_driveService); requestsInfo = new List <RequestsInfo>(); foreach (var source in batchSources) { var request = commandProvider(source); if (request == null) { continue; } requestsInfo.Add(new RequestsInfo { Request = request }); batch.Queue(request, batchCallback); } _logger.LogMessage($"Сформирован пакет запросов из {batch.Count} штук."); _expBackoffPolicy.GrantedDelivery( () => { _logger.LogMessage($"Отправка пакета на сервер Google Drive..."); batch.ExecuteAsync().Wait(); _logger.LogMessage($"Отправка пакета на сервер Google Drive прошла успешно."); }, () => { _logger.LogMessage($"Из-за ошибки при пакетной операции, будет сформирован новый пакет из провальных запросов"); // prepare retry batch composed of nonsuccess requests requestsInfo = requestsInfo.Where(ri => !ri.Success).ToList(); var newBatch = new BatchRequest(_driveService); foreach (var requestInfo in requestsInfo) { newBatch.Queue(requestInfo.Request, batchCallback); } _logger.LogMessage($"Сформирован новый пакет запросов из {newBatch.Count} штук..."); newBatch.ExecuteAsync().Wait(); _logger.LogMessage($"Отправка пакета на сервер Google Drive прошла успешно."); }); consideredCount += batchSources.Length; } _logger.LogMessage("Пакетная операция завершена."); }