public void InitService() { // Auth id and secret from google developers console string clientId = "354424347588-6bb4q1o8ufba3fu32tknk8elep233s4g.apps.googleusercontent.com"; string clientSecret = "NOSdJs3FPwfyoI62A6sCrfjg"; //Scopes for use with the Google Drive API string[] scopes = new string[] { DriveService.Scope.Drive // ,DriveService.Scope.DriveFile }; // here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData% UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync( new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret }, scopes, Environment.UserName, CancellationToken.None, new FileDataStore(CredentialSavePath, true)).Result; mDriveService = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = AppName, }); }
public void subirArchivo() { string ruta = @"C:\Users\addiaz\Desktop\DocumentosDrive\"; string nombre = FileUpload1.PostedFile.FileName; string sExtension = ObtenerTipoArchivo(FileUpload1.FileName); UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync( new ClientSecrets { ClientId = "704651064787-6l6ce8uiculoenaqera0fa40kd53t6sn.apps.googleusercontent.com", ClientSecret = "uonquuVkIoLXGWjhLSicKpUL", }, new[] { DriveService.Scope.Drive }, "user", CancellationToken.None).Result; // Servicio para realizar peticiones al google drive. var service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Drive API Sample", }); File body = new File(); body.Title = nombre; body.Description = "A test document"; body.MimeType = sExtension; // byte[] byteArray = System.IO.File.ReadAllBytes(Server.MapPath(nombre)); byte[] byteArray = System.IO.File.ReadAllBytes("C:/Users/Adrian/Desktop/DcomuentosDrive/" + nombre); System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray); FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, sExtension); request.Upload(); File file = request.ResponseBody; }
public void Connect() { string[] Scopes = new string[] { DriveService.Scope.Drive, DriveService.Scope.DriveFile}; string ApplicationName = "Drive API Quickstart"; UserCredential credential; using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read)) { string credPath = System.Environment.GetFolderPath( System.Environment.SpecialFolder.Personal); credPath = Path.Combine(credPath, ".credentials"); credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; //Console.WriteLine("Credential file saved to: " + credPath); } service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); listRequest = service.Files.List(); listRequest.MaxResults = 1000; firstPageToken = listRequest.PageToken; }
/// <summary> /// Uploads a file /// Documentation: https://developers.google.com/drive/v2/reference/files/insert /// </summary> /// <param name="_service">a Valid authenticated DriveService</param> /// <param name="_uploadFile">path to the file to upload</param> /// <param name="_parent">Collection of parent folders which contain this file. /// Setting this field will put the file in all of the provided folders. root folder.</param> /// <returns>If upload succeeded returns the File resource of the uploaded file /// If the upload fails returns null</returns> public static File uploadFile(DriveService _service, string _uploadFile, string _parent, string Description) { if (System.IO.File.Exists(_uploadFile)) { File body = new File(); body.Name = System.IO.Path.GetFileName(_uploadFile); body.Description = Description; body.MimeType = GetMimeType(_uploadFile); body.Parents = new List<string> { _parent }; // File's content. byte[] byteArray = System.IO.File.ReadAllBytes(_uploadFile); System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray); try { var request = _service.Files.Create(body, stream, GetMimeType(_uploadFile)); //request.Convert = true; // uncomment this line if you want files to be converted to Drive format request.Upload(); return request.ResponseBody; } catch (Exception) { return null; throw; } } else { Console.WriteLine("File does not exist: " + _uploadFile); return null; } }
public static String /*File*/ uploadFile(DriveService service, string localFilePath) { if (System.IO.File.Exists(localFilePath)) { //File's body File body = new File(); body.Title = System.IO.Path.GetFileName(localFilePath); body.Description = "Uploaded by Popcorn-GDrive"; body.MimeType = GetMimeType(localFilePath); //File content byte[] byteArray = System.IO.File.ReadAllBytes(localFilePath); System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray); try { FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, GetMimeType(localFilePath)); request.Upload(); //String fileID = request.ResponseBody.Id; return request.ResponseBody.Id; } catch(Exception e) { throw; } } else { return null; } }
public static DriveService AuthenticateOauth(string clientID, string clientSecret, string userName) { //Google Drive scopes Documentation: https://developers.google.com/drive/web/scopes string[] scopes = new string[] { DriveService.Scope.Drive, //View and manage files and documents DriveService.Scope.DriveAppdata, //View and manage its own configuration data DriveService.Scope.DriveAppsReadonly, //View and manage drive apps DriveService.Scope.DriveFile, //View and manage files created by Popcorn-GDrive DriveService.Scope.DriveMetadataReadonly, //View metadata for files DriveService.Scope.DriveReadonly, //View (only) files and documents on your drive /*DriveService.Scope.DriveScripts,*/ //View your app scripts }; try { UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = clientID, ClientSecret = clientSecret } , scopes , userName , CancellationToken.None , new FileDataStore("Popcorn-GDrive.Auth.Store")).Result; DriveService service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Popcorn-GDrive", }); return service; } catch (Exception e) { throw e; //Console.WriteLine(e.InnerException); } }
public static DriveService AuthenticateServiceAccount(string serviceAccountEmail, string keyFilePath, string applicationName) { if (!File.Exists(keyFilePath)) { throw new FileNotFoundException("Given key file is not found", keyFilePath); } // Google Drive scopes Documentation: https://developers.google.com/drive/web/scopes string[] scopes = new string[] { DriveService.Scope.Drive, // view and manage your files and documents DriveService.Scope.DriveAppdata, // view and manage its own configuration data DriveService.Scope.DriveAppsReadonly, // view your drive apps DriveService.Scope.DriveFile, // view and manage files created by this app DriveService.Scope.DriveMetadataReadonly, // view metadata for files DriveService.Scope.DriveReadonly, // view files and documents on your drive DriveService.Scope.DriveScripts }; // modify your app scripts var certificate = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.Exportable); var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail) { Scopes = scopes }.FromCertificate(certificate)); // Create the service. var service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = applicationName, }); return service; }
public DriveDataService(DriveService connectionService) { if (connectionService == null) throw new ArgumentNullException("connectionService == null"); ConnectionService = connectionService; }
public static File InsertFile(DriveService service, string mimeType, string filename, System.IO.Stream stream) { // File's metadata. File body = new File(); body.Title = filename; body.MimeType = mimeType; body.Parents = new List<ParentReference>() { new ParentReference() { Id = "0BySX8GhV2wf8enhxSU56N25Rbnc" } }; try { FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, mimeType); request.Upload(); File file = request.ResponseBody; // Uncomment the following line to print the File ID. // Console.WriteLine("File ID: " + file.Id); return file; } catch (Exception e) { Console.WriteLine("An error occurred: " + e.Message); return null; } }
public async Task Run(DriveService service) { GoogleAPIAuthorization googleApiAuthorization = GoogleAPIAuthorization.Instance; //File file = null; //Boolean exists = await IsApplicationDirectoryExist(service); //if (exists) //{ // //OK //} //else //{ //await CreateApplicationDirectory(service); await googleApiAuthorization.Deauthorize(service); //await CreateApplicationDirectory(service); //await googleApiAuthorization.Deauthorize(service); //} // await googleApiAuthorization.Deauthorize(service); }
/// <summary> /// Create a service connection to google. /// </summary> /// <param name="userEmail">The API email to use for authentication.</param> /// <param name="gService">The type of service to connect to.</param> /// <returns>Returns an open connection to the google api service, or null.</returns> private static BaseClientService BuildService(string userEmail, GoogleServices gService = GoogleServices.Directory) { X509Certificate2 certificate = new X509Certificate2(Properties.Resources.gsd_api,"notasecret", X509KeyStorageFlags.Exportable); ServiceAccountCredential credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(SERVICE_ACCOUNT_EMAIL) { Scopes = Scopes, User = userEmail }.FromCertificate(certificate)); switch (gService) { case GoogleServices.Directory: DirectoryService directoryService = new DirectoryService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "GSD GAMS", }); return directoryService; case GoogleServices.Drive: DriveService driveService = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "GSD GAMS", }); return driveService; } return null; }
public async Task<ActionResult> ListDrive(CancellationToken cancellationToken) { UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync( new ClientSecrets { ClientId = "904595749350-0m2f89cjfmhq8a9pplo62njot4pk977a.apps.googleusercontent.com", ClientSecret = "l6Inr8ki5h95x8QElYWxiwHS" }, new[] { DriveService.Scope.Drive }, "user", CancellationToken.None).Result; //var ctx = Request.GetOwinContext(); //var result = ctx.Authentication.AuthenticateAsync("ExternalCookie").Result; var service = new DriveService(new BaseClientService.Initializer { HttpClientInitializer = result, ApplicationName = "ASP.NET MVC Sample" }); var list = await service.Files.List().ExecuteAsync(); ViewBag.Message = "Files from google drive"; return View(list); }
public static DriveService GetDriveService() { UserCredential credential; using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read)) { var credPath = Environment.GetFolderPath( Environment.SpecialFolder.Personal); credPath = Path.Combine(credPath, ".credentials/drive-dotnet-quickstart"); credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; Console.WriteLine("Credential file saved to: " + credPath); } // Create Drive API service. var service = new DriveService(new BaseClientService.Initializer { HttpClientInitializer = credential, ApplicationName = ApplicationName }); return service; }
public static List<File> GetChildrenFiles(DriveService service, string idParent) { List<File> result = new List<File>(); FilesResource.ListRequest request = service.Files.List(); request.MaxResults = 1000; request.Q = ("'" + idParent + "'" + " IN parents"); int i = 0; do { try { using (var client = new WebClient()) { FileList files = request.Execute(); result.AddRange(files.Items); request.PageToken = files.NextPageToken; i++; } } catch (Exception e) { Console.WriteLine("An error occurred: " + e.Message); request.PageToken = null; } } while (!String.IsNullOrEmpty(request.PageToken)); return result; }
/// <summary> /// 구글의 Oauth 2.0을 사용하여 유저 정보를 가져온다. /// </summary> /// <param name="clientId">Developer console에서 발급받은 userid</param> /// <param name="clientSecret">Developer console에서 발급받은 보안 번호</param> /// <param name="userName">사용자를 구별하기 위한 유저 이름 (닉네임)</param> /// <returns></returns> public static DriveService AuthenticateOauth(string clientId, string clientSecret, string userName) { //Google Drive scopes Documentation: https://developers.google.com/drive/web/scopes string[] scopes = new string[] { DriveService.Scope.Drive, //Google 드라이브에서 파일 보기 및 관리 DriveService.Scope.DriveAppdata, //Google 드라이브에서 설정 데이터 조회 및 관리 DriveService.Scope.DriveAppsReadonly, // Google 드라이브 앱 조회 DriveService.Scope.DriveFile, // 이 앱으로 열거나 만든 Google 드라이브 파일과 폴더 조회 및 관리 DriveService.Scope.DriveMetadataReadonly, // Google 드라이브에서 파일의 메타데이터 보기 DriveService.Scope.DriveReadonly, // Google 드라이브에서 파일 보기 DriveService.Scope.DriveScripts }; // Google Apps Script 스크립트의 행동 변경 try { // 신규 유저 접근 권한을 받아오거나 혹은 저장되어 있는 (기본 위치 C:\Users\bit-user\AppData\Roaming\)에 토큰을 가지고 유저정보를 가져온다. UserCredential credential = GoogleWebAuthorization.LoginAuthorizationCodeFlowAsync(new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret } , scopes , userName , CancellationToken.None , new FileDataStore("Daimto.Drive.Auth.Store")).Result; // 받아온 유저의 정보를 이용하여 google drive 에 연결한다. DriveService service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "GoogleCloude Sample", }); return service; } catch (Exception ex) { return null; } }
private File GetFileByID(string fileID, DriveService service) { File file = service.Files.Get(fileID).Execute(); if (file.ExplicitlyTrashed == null) return file; return null; }
/* public Boolean DownloadFile(DriveService service, GFile _fileResource, string _saveTo) { try { //File file = service.Files.Get(fileId).Execute(); FilesResource.GetRequest request = service.Files.Get(_fileResource.Id); request.url return true; } catch (Exception e) { return false; } }*/ public Boolean DownloadFile(DriveService service, GFile _fileResource, string _saveTo) { GFile newFile = service.Files.Get(_fileResource.Id).Execute(); if (!String.IsNullOrEmpty(_fileResource.DownloadUrl)) { using (FileStream fs = System.IO.File.Create(_saveTo)) { //Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file."); // Add some information to the file. var x = service.HttpClient.GetByteArrayAsync(newFile.DownloadUrl); byte[] arrBytes = x.Result; //fs.WriteAllBytes(_saveTo, arrBytes); fs.Write(arrBytes, 0, arrBytes.Length); //fs.WriteAsync() //fs.Write(arrBytes, 0, arrBytes.Length); return true; } } else { // The file doesn't have any content stored on Drive. //winform.AddText("Error2"); return false; } return false; }
public async Task<ActionResult> DriveAsync(CancellationToken cancellationToken) { ViewBag.Message = "Your drive page."; var result = await new AuthorizationCodeMvcApp(this, new AppAuthFlowMetadata()). AuthorizeAsync(cancellationToken); if (result.Credential == null) return new RedirectResult(result.RedirectUri); var driveService = new DriveService(new BaseClientService.Initializer { HttpClientInitializer = result.Credential, ApplicationName = "ASP.NET Google APIs MVC Sample" }); var listReq = driveService.Files.List(); listReq.Fields = "items/title,items/id,items/createdDate,items/downloadUrl,items/exportLinks"; var list = await listReq.ExecuteAsync(); var items = (from file in list.Items select new FileModel { Title = file.Title, Id = file.Id, CreatedDate = file.CreatedDate, DownloadUrl = file.DownloadUrl ?? (file.ExportLinks != null ? file.ExportLinks["application/pdf"] : null), }).OrderBy(f => f.Title).ToList(); return View(items); }
public IDriveService Create() { const string applicationName = "GoogleDriveOfflineBackup"; var scopes = new[] { DriveService.Scope.DriveReadonly }; UserCredential credential; Console.WriteLine("Searching for settings file"); CredentialsProvider credentialsProvider = new CredentialsProvider(); string secretFile = credentialsProvider.LocateSettingsFile(); using (var stream = new FileStream(secretFile, FileMode.Open, FileAccess.Read)) { string personalPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); string credentialsPath = Path.Combine(personalPath, ".credentials"); string appCredentialsPath = Path.Combine(credentialsPath, "GoogleDriveOfflineBackup"); Console.WriteLine("Authorizing {0}", appCredentialsPath); var secrets = GoogleClientSecrets.Load(stream).Secrets; credential = GoogleWebAuthorizationBroker.AuthorizeAsync( secrets, scopes, "user", CancellationToken.None, new FileDataStore(appCredentialsPath, fullPath: true)).Result; // blocking! Console.WriteLine("Credentials written to {0}", appCredentialsPath); } // create service var service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = applicationName }); return new DriveServiceWrapper(service); }
/// <summary> /// Authenticate to Google Using Oauth2 /// Documentation https://developers.google.com/accounts/docs/OAuth2 /// </summary> /// <param name="clientId">From Google Developer console https://console.developers.google.com</param> /// <param name="clientSecret">From Google Developer console https://console.developers.google.com</param> /// <param name="userName">A string used to identify a user.</param> /// <returns></returns> public static DriveService AuthenticateOauth(string clientId, string clientSecret, string userName) { //Google Drive scopes Documentation: https://developers.google.com/drive/web/scopes string[] scopes = new string[] { DriveService.Scope.Drive, // view and manage your files and documents DriveService.Scope.DriveAppdata, // view and manage its own configuration data DriveService.Scope.DriveAppsReadonly, // view your drive apps DriveService.Scope.DriveFile, // view and manage files created by this app DriveService.Scope.DriveMetadataReadonly, // view metadata for files DriveService.Scope.DriveReadonly, // view files and documents on your drive DriveService.Scope.DriveScripts }; // modify your app scripts try { // here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData% UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret } , scopes , userName , CancellationToken.None , new FileDataStore("Pet.Store")).Result; DriveService service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Pet Store Api", }); return service; } catch (Exception ex) { Console.WriteLine(ex.InnerException); return null; } }
/// <summary> /// Updates a file /// Documentation: https://developers.google.com/drive/v2/reference/files/update /// </summary> /// <param name="_service">a Valid authenticated DriveService</param> /// <param name="_uploadFile">path to the file to upload</param> /// <param name="_parent">Collection of parent folders which contain this file. /// Setting this field will put the file in all of the provided folders. root folder.</param> /// <param name="_fileId">the resource id for the file we would like to update</param> /// <returns>If upload succeeded returns the File resource of the uploaded file /// If the upload fails returns null</returns> public static File updateFile(DriveService _service, string _uploadFile, string _parent,string _fileId) { if (System.IO.File.Exists(_uploadFile)) { File body = new File(); body.Title = System.IO.Path.GetFileName(_uploadFile); body.Description = "File updated by Diamto Drive Sample"; body.MimeType = GetMimeType(_uploadFile); body.Parents = new List<ParentReference>() { new ParentReference() { Id = _parent } }; // File's content. byte[] byteArray = System.IO.File.ReadAllBytes(_uploadFile); System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray); try { FilesResource.UpdateMediaUpload request = _service.Files.Update(body, _fileId, stream, GetMimeType(_uploadFile)); request.Upload(); return request.ResponseBody; } catch (Exception e) { Console.WriteLine("An error occurred: " + e.Message); return null; } } else { Console.WriteLine("File does not exist: " + _uploadFile); return null; } }
public MainWindow() { string[] scopes = new string[] { DriveService.Scope.Drive }; InitializeComponent(); var keyFilePath = @"c:\file.p12"; // Downloaded from https://console.developers.google.com var serviceAccountEmail = "*****@*****.**"; // found https://console.developers.google.com //loading the Key file var certificate = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.Exportable); var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail) { Scopes = scopes }.FromCertificate(certificate)); var service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Drive API Sample", }); FilesResource.ListRequest request = service.Files.List(); FileList files = request.Execute(); foreach (var file in files.Items) { Console.WriteLine(file.Title); } }
public static void ValidHttpClientInitializer(DriveService service) { if (service.HttpClientInitializer == null) { throw new AuthenticationException("Authentication error! Please use the Authentication class to initialize the Google Drive service!"); } }
public static DriveService AuthenticateServiceAccount(string serviceAccountEmail, string keyFilePath) { if (!System.IO.File.Exists(keyFilePath)) { //Console.WriteLine("Key File does not exist"); return null; } string[] scopes = new string[] { DriveService.Scope.Drive }; var certificate = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.Exportable); try { ServiceAccountCredential credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(serviceAccountEmail) { Scopes = scopes }.FromCertificate(certificate)); DriveService service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "PepitoTW" }); //Console.WriteLine("Authenticate Success"); return service; } catch (Exception ex) { //Console.WriteLine(ex.InnerException); return null; } }
public static IList<File> GetFiles(DriveService service, string search) { IList<File> Files = new List<File>(); try { FilesResource.ListRequest list = service.Files.List(); list.MaxResults = 1000; if (search != null) { list.Q = search; } FileList filesFeed = list.Execute(); while (filesFeed.Items != null) { foreach (File item in filesFeed.Items) { Files.Add(item); } if (filesFeed.NextPageToken == null) { break; } list.PageToken = filesFeed.NextPageToken; filesFeed = list.Execute(); } } catch (Exception ex) { Console.WriteLine(ex.Message); } return Files; }
public void UploadUnauthenticatedServiceShouldThrowTest() { var unauthenticated = new DriveService(); var fileName = TestFile; DaimtoGoogleDriveHelper.UploadFile(unauthenticated, fileName, rootDirectoryID); }
public static async Task<ConnectionResult> ConnectToGoogleDrive(Controller controller, CancellationToken token) { string userId = controller.User.Identity.GetUserId(); GoogleDriveService service = null; if (ServiceCache.TryGetValue(userId, out service)) return new ConnectionResult(service, null); var result = await new AuthorizationCodeMvcApp(controller, new AppFlowMetadata()).AuthorizeAsync(token); if (result.Credential == null) { return new ConnectionResult(null, result.RedirectUri); } var Service = new DriveService(new BaseClientService.Initializer { HttpClientInitializer = result.Credential, ApplicationName = GoogleDriveSettings.APP_NAME }); service = new GoogleDriveService(new DriveDataService(Service)); ServiceCache[userId] = service; return new ConnectionResult(service, null); }
public void Login() { // creeaza si stocheaza obiectul credentiale using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read)) { string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); credPath = Path.Combine(credPath, ".credentials/drive-dotnet-quickstart"); Credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, new[] { DriveService.Scope.Drive}, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; // Directory.Delete(credPath, true); } //creeaza serviciul Service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = Credential, ApplicationName = "Sorin Drive API", }); }
public static string DeleteFileById(DriveService service, string id) { Validator.IsStringNullOrEmpty(id, "File id"); Validator.ValidHttpClientInitializer(service); string request = service.Files.Delete(id).Execute(); return request; }
public void Init() { clientID = "122586258718-lbpu876ap5o81fib62egce3aiqa87bpu.apps.googleusercontent.com"; clientSecret = "JxjLSk0O0tYNjAeoW39qBGbH"; rootDirectoryID = "0B9-BhHxB4VqLcmh1TXZYV1NkZGc"; service = Authentication.AuthenticateOauth(clientID, clientSecret, Environment.UserName); }
public string SaveToDrive(HttpPostedFileBase file1) { try { UserCredential credential; using (var stream = new FileStream(Server.MapPath("~/Documents/credentials.json"), FileMode.Open, FileAccess.ReadWrite)) { // The file token.json stores the user's access and refresh tokens, and is created // automatically when the authorization flow completes for the first time. string credPath = Server.MapPath("~/Documents/token.json"); credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, "admin", CancellationToken.None, new FileDataStore(credPath, true)).Result; Console.WriteLine("Credential file saved to: " + credPath); } // Create Drive API service. var service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); string _parent = "1licsmd8Lz5OZ2ROE9wEcW1sw1IiY4uGi"; Google.Apis.Drive.v3.Data.File body = new Google.Apis.Drive.v3.Data.File(); body.Name = System.IO.Path.GetFileName(file1.FileName); body.Description = "Inward Entry Doc"; body.MimeType = GetMimeType(file1.FileName); if (!string.IsNullOrEmpty(_parent)) { body.Parents = new List <string>() { _parent }; } var fileMetadata = new Google.Apis.Drive.v3.Data.File() { Name = file1.FileName, Parents = new List <string> { _parent } }; // File's content. System.IO.BinaryReader b = new System.IO.BinaryReader(file1.InputStream); byte[] byteArray = b.ReadBytes(file1.ContentLength); System.IO.MemoryStream _stream = new System.IO.MemoryStream(byteArray); FilesResource.CreateMediaUpload request = service.Files.Create(body, _stream, GetMimeType(file1.FileName)); request.Alt = FilesResource.CreateMediaUpload.AltEnum.Json; request.Fields = "id"; request.Upload(); var d = request.ResponseBody; return(d.Id); } catch (Exception e) { return("Error " + e.InnerException.ToString()); } }
static void Main(string[] args) { TCPServer <TCPData> server = new TCPServer <TCPData>(); server.Start(); server.OnDataReceived += Server_OnDataReceived; Console.ReadLine(); return; if (!Directory.Exists(billPath)) { Directory.CreateDirectory(billPath); } TesseractEngine engine = new TesseractEngine(Directory.GetCurrentDirectory(), "ces"); Pix img = Pix.LoadFromFile("unnamed1.jpg"); Page p = engine.Process(img, PageSegMode.Auto); string s = p.GetText(); Console.WriteLine(s); Console.ReadLine(); UserCredential credential; using (FileStream stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read)) { credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, new string[1] { DriveService.Scope.Drive }, "user", CancellationToken.None, new FileDataStore(folderPath, true)).Result; } // Create Drive API service. DriveService service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Bill Scanner" }); FilesResource.ListRequest listRequest = service.Files.List(); //TODO: if other ways are found, this has to be edited listRequest.Q = "mimeType != 'application/vnd.google-apps.folder' and name contains 'Dokument aplikace' and name contains 'Google Keep'"; IList <Google.Apis.Drive.v3.Data.File> files = listRequest.Execute().Files; Console.WriteLine("Files to download ({0}):", files.Count); if (files.Count == 0) { Console.WriteLine("No Files found in the drive!"); End(); return; } ShopsDefinition def = new ShopsDefinition(); foreach (Google.Apis.Drive.v3.Data.File file in files) { Console.WriteLine("{0} ({1})", file.Name, file.Id); if (file.Name.Contains("Google") || file.Name.Contains("Keep")) { Stream fs; string fileName = billPath + file.Name + "-" + file.Id.Replace("-", "") + ".txt"; try { fs = new FileStream(fileName, FileMode.CreateNew); } catch (IOException e) { Console.WriteLine(e.Message); continue; } service.Files.Export(file.Id, "text/plain").DownloadWithStatus(fs); fs.Close(); fs.Dispose(); //TODO delete file from drive string content = File.ReadAllText(fileName); ShopsDefinition.Shop shop = def.GetShopType(content); switch (shop) { case ShopsDefinition.Shop.LIDL: { Shops.Lidl l = new Shops.Lidl(); //l.Parse(content); break; } case ShopsDefinition.Shop.MC_DONALDS: { Shops.McDonalds m = new Shops.McDonalds(); //m.Parse(content); break; } case ShopsDefinition.Shop.ŠMAK: { Shops.BilboSmak bs = new Shops.BilboSmak(); //bs.Parse(content); break; } case ShopsDefinition.Shop.ALBERT: { Shops.Albert a = new Shops.Albert(); //a.Parse(content); break; } } } } End(); }
public DriveRepository(string keyFile) { driveService = DriveHelper.Authenticate(keyFile); GetOrCreateModPackDirectory(); }
static void Main(string[] args) { UserCredential credential; using (var stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read)) { // The file token.json stores the user's access and refresh tokens, and is created // automatically when the authorization flow completes for the first time. string credPath = "token.json"; credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; Console.WriteLine("Credential file saved to: " + credPath); } // Create Drive API service. var service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); // Define parameters of request. FilesResource.ListRequest listRequest = service.Files.List(); listRequest.PageSize = 10; listRequest.Fields = "nextPageToken, files(id, name)"; // List files. IList <Google.Apis.Drive.v3.Data.File> files = listRequest.Execute() .Files; Console.WriteLine("Files:"); if (files != null && files.Count > 0) { foreach (var file in files) { Console.WriteLine("{0} ({1})", file.Name, file.Id); } } else { Console.WriteLine("No files found."); } Console.WriteLine("/n Add a file"); Console.WriteLine("File name: "); string folderName = Console.ReadLine(); var fileMetadata = new Google.Apis.Drive.v3.Data.File() { Name = folderName, MimeType = "application/pdf" }; var request = service.Files.Create(fileMetadata); request.Fields = "id"; var filee = request.Execute(); Console.WriteLine("Folder ID: " + filee.Id); }
//220680762635-qg38qgp1g1bbmkdjma1o50df199sbsjm.apps.googleusercontent.com //3Iub0pwzrs3-tCB4UyP4dgig //220680762635-qg38qgp1g1bbmkdjma1o50df199sbsjm.apps.googleusercontent.com public static void DownloadGrids() { FileStream fileStream = null; try { UserCredential credential; using (var stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read)) { // The file token.json stores the user's access and refresh tokens, and is created // automatically when the authorization flow completes for the first time. string credPath = "token.json"; credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; } // Create Drive API service. var service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "miqocrafter", }); // Define parameters of request. FilesResource.ListRequest listRequest = service.Files.List(); listRequest.PageSize = 10; listRequest.Fields = "nextPageToken, files(id, name)"; // List files. IList <Google.Apis.Drive.v3.Data.File> files = listRequest.Execute().Files; if (files != null && files.Count > 0) { foreach (var file in files) { if (file.Name == "Release.zip") { //Delete old zip if any FileInfo zipPath = new FileInfo(Path.Combine(Service_Misc.GetExecutionPath(), "Release.zip")); if (zipPath.Exists) { zipPath.Delete(); } //Download new zip String fileId = file.Id; fileStream = File.Create(zipPath.FullName); Stream stream = fileStream; service.Files.Get(fileId).Download(stream); fileStream.Close(); fileStream = null; //Unzip fileStream = File.OpenRead(zipPath.FullName); using (ZipArchive archive = new ZipArchive(fileStream)) { archive.ExtractToDirectory(Service_Misc.GetExecutionPath(), true); } fileStream.Close(); fileStream = null; } } } } catch (Exception exc) { Console.WriteLine(exc.Message); } if (null != fileStream) { fileStream.Close(); } }
/// <summary> /// Gets the root folder identifier. /// </summary> /// <param name="service">The service.</param> /// <returns>The root folder identifier as <see cref="string"/>.</returns> private string GetRootFolderId(DriveService service) { return(this.customGDriveService.GetRootFolderId(service)); }
/// <summary> /// Gets the total quota. /// </summary> /// <param name="service">The service.</param> /// <returns>The total quota as <see cref="long"/>.</returns> private long GetQuotaTotal(DriveService service) { return(this.customGDriveService.GetQuotaTotal(service)); }
public void getauthorization() { UserCredential credential; using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read)) { string credPath = System.Environment.GetFolderPath( System.Environment.SpecialFolder.Personal); credPath = Path.Combine(credPath, ".credentials111/drive-dotnet-quickstart.json"); credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, new[] { DriveService.Scope.Drive } , "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; Console.WriteLine("Credential file saved to: " + credPath); } // Create Drive API service. service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "MIM Project", }); /* string pageToken = null; * string fileId = ""; * do * { * var request = service.Files.List(); * // request.Q = "mimeType = 'application/vnd.google-apps.folder' "; * // string parent_id = "0B1auUUiGcbbBOEIyNjg0alkwc3c"; * request.Q = "name contains 'Disposition Table for MIM 10/07/19' "; * request.Spaces = "Drive"; * request.Fields = "nextPageToken, files(id, name)"; * request.PageToken = pageToken; * * var result = request.Execute(); * foreach (var file in result.Files) * { * // if (file.Name == "Rack Delivery Plan [go/rackdeliveryplan]") * // { * fileId = file.Id; * break; * // } * } * pageToken = result.NextPageToken; * } while (pageToken != null); */ // string message = fileId; string fileId = "1ZnnRVMvx0Ma4GUih2wq3hcJK1vg0LbxoXmKCzwlz1j4";//1Y4hdHIkkVv5SmGtj8QWM-jAccZdEOhhV6Ofx_kb3IBs"; //"1OSr1IqrUjqo3RdAn1WwoNpTf2v64jzY3rKgJ8SS3hf4";//"11emBYnY-_tLQ43TFEAWIsMEtVgwyXEaAmVCPxcnp6Ag";// "1Y4hdHIkkVv5SmGtj8QWM-jAccZdEOhhV6Ofx_kb3IBs";// string fileName = "\\\\mimsftp\\e$\\sftp\\msgGoogle\\MDS\\PROD\\inbound\\DISPOSITION\\INBOUND\\Decom Disposition Table For MIM.xlsx"; if (downloadFile(service, fileId, fileName)) { runJob(); // RunPackage(); } }
private static IList <File> GetFiles(DriveService service) { return(service.Files.List().Execute().Files); }
public FileList GetAllFiles(DriveService service) { return(getFileMetadata(null, service).Result); }
public GoogleDriveFolderController(IEnumerable <string> grantedUsers, IGoogleAccountProvider accountProvider) { _grantedUsers = grantedUsers.ToList(); _service = accountProvider.CreateDriveService(); }
/// <summary> /// Initializes module with drive service /// </summary> /// <param name="service"></param> public ServiceModule(DriveService service) { driveService = service; }
public async Task <ActionResult <Product> > PostProduct([FromBody] InsertProductViewModel model) { if (String.IsNullOrEmpty(model.productId)) { return(Ok("Mã sản phẩm không được để trống.")); } if (!CategoryExists(model.categoryId)) { return(NotFound()); } foreach (var item in model.supplies) { if (!SupplierExists(item)) { return(NotFound()); } } if (string.IsNullOrEmpty(model.images)) { return(Ok("Vui lòng chọn hình ảnh đính kèm.")); } if (model.images.Length > 1048576) { return(Ok("Kích thước không vượt quá 1mb")); } string path = _webhostEnvieronment.WebRootPath + "\\uploads\\"; string filename = model.productId + ".png"; try { Base64ToImage(model.images, path + filename); //if (model.images.Length > 0) //{ // if (!Directory.Exists(path)) // { // Directory.CreateDirectory(path); // } // using (FileStream file = System.IO.File.Create(path + model.images.FileName)) // { // model.Image.CopyTo(file); // file.Flush(); // } //} } catch (Exception e) { return(Ok(e.Message)); } UserCredential credential; credential = GetCredentials(); // Create Drive API service. var service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); //Id của folder muốn upload string folderid = "1iCNelsHCSLGKQL9XRJwMu9nUHZURFgR8"; var filePath = path + filename; string fileId = "1paIUZyOqIW5ZllHXE0b6r-kZWJHQMQYR"; try { fileId = UploadImage(filePath, service, folderid); model.images = fileId; } catch (Exception e) { return(Ok(e.Message)); } var product = model.ToProduct(); WareHouse ware = new WareHouse(); ware.Date = DateTime.Now; ware.ProductId = product.ProductId; ware.Quantity = 0; product.WareHouses.Add(ware); _context.Products.Add(product); try { await _context.SaveChangesAsync(); } catch (DbUpdateException) { if (ProductExists(product.ProductId)) { return(Conflict()); } else { throw; } } return(CreatedAtAction("GetProductDetails", new { productId = product.ProductId }, product)); }
public void UploadDoc() { UserCredential credential; using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read)) { string credPath = System.Environment.GetFolderPath( System.Environment.SpecialFolder.Personal); credPath = Path.Combine(credPath, ".credentials/drive-dotnet-quickstart.json"); credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, new[] { DriveService.Scope.Drive } , "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; Console.WriteLine("Credential file saved to: " + credPath); } // Create Drive API service. service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "MIM Project", }); string ArchiveParentid = ""; string MainParentid = ""; string pageToken = null; string fileId = ""; do { var request = service.Files.List(); // request.Q = "mimeType = 'application/vnd.google-apps.folder' "; request.Q = "mimeType = 'application/vnd.google-apps.folder'"; request.Spaces = "Drive"; request.Fields = "nextPageToken, files(id, name)"; request.PageToken = pageToken; var result = request.Execute(); foreach (var file in result.Files) { if (file.Name == "MIM First Article Folder") { MainParentid = file.Id; break; } } pageToken = result.NextPageToken; } while (pageToken != null); do { var request = service.Files.List(); // request.Q = "mimeType = 'application/vnd.google-apps.folder' "; string parent_id = MainParentid; request.Q = "'" + parent_id + "' in parents"; request.Spaces = "Drive"; request.Fields = "nextPageToken, files(id, name)"; request.PageToken = pageToken; var result = request.Execute(); foreach (var file in result.Files) { if (file.Name == "First Article Sheet (2015W34)") { fileId = file.Id; break; } } pageToken = result.NextPageToken; } while (pageToken != null); try { Google.Apis.Drive.v3.Data.File body = new Google.Apis.Drive.v3.Data.File(); body.Name = "TEST CSV DOC"; body.Description = "TEST CSV DOC"; body.MimeType = "text/csv"; filename1 = filename1.Replace("file:\\", " "); filename1 = "e:\\ACCPurchaseOrderDetail.csv"; // MessageBox.Show("filename=" + filename); System.IO.Stream fileStream = System.IO.File.Open(filename1, System.IO.FileMode.Open, System.IO.FileAccess.Read); byte[] byteArray = new byte[fileStream.Length]; fileStream.Read(byteArray, 0, (int)fileStream.Length); System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray); // FilesResource.UpdateMediaUpload request = service.Files.Update(body, fileId, stream, "text/csv");//application/x-vnd.oasis.opendocument.spreadsheet"); FilesResource.CreateMediaUpload request1 = service.Files.Create(body, stream, "application/x-vnd.oasis.opendocument.spreadsheet"); request1.Upload(); MessageBox.Show("File has been uploaded in shared doc"); fileStream.Close(); fileStream.Dispose(); } catch (Exception exp) { MessageBox.Show("Exception to upload file"); } finally { } }
public GDriveFile() { service = GDriveHelper.GetService(); this.Children = new List <GDriveFile>(); }
// Gets path from cache or downloads image to cache from drive public static string ImagePath(int num, bool isAlt, bool refresh = false) { Commands.Gec.RefreshGec(); FileUtils.checkForCacheExistance(); string name = addZeros(num); if (isAlt) { name = "b" + name; } // If image already exists in cache, use it string cached = CheckCache(name); if (cached != null && Commands.Gec.geckos.ContainsKey(EmoteUtils.escapeforbidden(name))) { if (!refresh) { return(cached); } File.Delete(cached); cached = null; } if (refresh && Commands.Gec.geckos.ContainsKey(EmoteUtils.escapeforbidden(name))) { Commands.Gec.geckos.Remove(EmoteUtils.escapeforbidden(name)); } // Otherwise, fetch it from google drive DriveService driveService = AuthenticateServiceAccount( "*****@*****.**", "../../../GeckoBot-af43fa71833e.json"); var listRequest = driveService.Files.List(); listRequest.PageSize = 1; // Only fetch one listRequest.Q = $"name contains '{name}_'"; // Search for the image via the given number IList <Google.Apis.Drive.v3.Data.File> files = listRequest.Execute().Files; if (files != null && files.Count > 0) { // Use the first result var file = files[0]; //adds name of gecko to list if (!Commands.Gec.geckos.ContainsKey(name)) { Commands.Gec.geckos.TryAdd(EmoteUtils.escapeforbidden(name), EmoteUtils.escapeforbidden(file.Name)); FileUtils.Save(Globals.DictToString(Commands.Gec.geckos, "{0} ⁊ {1} ҩ "), @"..\..\Cache\gecko7.gek"); if (cached != null) { return(cached); } } //Console.WriteLine(file.MimeType); string type = file.MimeType.Replace("image/", ""); // sorta hacky solution to get file type for (int i = 0; i < 1000; i++) { try { using (var fileStream = new FileStream($"../../Cache/{name}_icon.{type}", FileMode.Create, FileAccess.Write)) { driveService.Files.Get(file.Id).Download(fileStream); } break; } catch { continue; } } return(CheckCache(name) ?? throw new Exception("Drive download failed!")); } throw new Exception("File " + name + " not found!"); }
// Gets path from cache or downloads image to cache from drive public static int saveAll(int highest) { Commands.Gec.RefreshGec(); FileUtils.checkForCacheExistance(); DriveService driveService = AuthenticateServiceAccount( "*****@*****.**", "../../../GeckoBot-af43fa71833e.json"); var listRequest = driveService.Files.List(); listRequest.PageSize = 1000; // Only fetch one thousand listRequest.Q = "mimeType contains 'image'"; // Filter out folders or other non image types Google.Apis.Drive.v3.Data.FileList files2 = listRequest.Execute(); IList <Google.Apis.Drive.v3.Data.File> files = files2.Files; int totalAmount = 0; int amount = 0; while (totalAmount < highest) { foreach (Google.Apis.Drive.v3.Data.File file in files) { string name = file.Name.Remove(3); if (name.Contains("b")) { name = file.Name.Remove(4); } if (CheckCache(name) == null) { string type = file.MimeType.Replace("image/", ""); // sorta hacky solution to get file type using var fileStream = new FileStream( $"../../Cache/{name}_icon.{type}", FileMode.Create, FileAccess.Write); driveService.Files.Get(file.Id).Download(fileStream); amount++; } if (!Commands.Gec.geckos.ContainsKey(EmoteUtils.escapeforbidden(name))) { Commands.Gec.geckos.Add(EmoteUtils.escapeforbidden(name), EmoteUtils.escapeforbidden(file.Name)); if (CheckCache(name) != null) { continue; } } else if (!Commands.Gec.geckos.ContainsValue(EmoteUtils.escapeforbidden(file.Name))) { Commands.Gec.geckos.Remove(EmoteUtils.escapeforbidden(name)); Commands.Gec.geckos.Add(EmoteUtils.escapeforbidden(name), EmoteUtils.escapeforbidden(file.Name)); } totalAmount++; } listRequest.PageToken = files2.NextPageToken; } FileUtils.Save(Globals.DictToString(Commands.Gec.geckos, "{0} ⁊ {1} ҩ "), @"..\..\Cache\gecko7.gek"); return(amount); }
private async Task <string> UploadFile(string path, string contentType, string fileName, string folderID, DriveService service) { var fileMetadata = new Google.Apis.Drive.v3.Data.File { Name = fileName, MimeType = contentType }; fileMetadata.Parents = new List <string> { folderID }; FilesResource.CreateMediaUpload request; using (var stream = new System.IO.FileStream(path, System.IO.FileMode.Open)) { request = service.Files.Create(fileMetadata, stream, contentType); request.Fields = "id"; await request.UploadAsync(); } var file = request.ResponseBody; return(file.Id); }
public GoogleDriveRootNode(DriveService service) : base(service) { _service = service; }
/// <summary> /// Constructor which forwards drive service instance to base class. /// </summary> public GoogleDriveReader(DriveService driveService, IFileReader fileReader) : base(driveService) { _localFileReader = new LocalFileReader(fileReader); }
public List <string> Invoke(List <string> fileIds) { try { using (DriveService driveService = DriveService.Create()) { var untrashStreams = new List <API.DriveService.UntrashStream>(); foreach (string fileId in fileIds) { FileInfo fileInfo = driveService.GetFile(fileId); if (fileInfo == null) { throw new Exception("File no longer exists."); } var untrashStream = new API.DriveService.UntrashStream(); untrashStream.Init(fileInfo); untrashStream.Visible = false; untrashStreams.Add(untrashStream); } driveService.UntrashFiles(untrashStreams); while (true) { bool finished = true; for (int i = 0; i < untrashStreams.Count; i++) { API.DriveService.UntrashStream untrashStream = untrashStreams[i]; if (!untrashStream.Finished) { finished = false; break; } } if (finished) { break; } System.Threading.Thread.Sleep(250); } var untrashedFileIds = new List <string>(); foreach (DriveService.UntrashStream untrashStream in untrashStreams) { if (untrashStream.Completed) { untrashedFileIds.Add(untrashStream.FileId); } else if (untrashStream.Cancelled) { } else if (untrashStream.Failed) { throw new LogException("Untrash could not complete - " + untrashStream.ExceptionMessage, true, true); } } return(untrashedFileIds); } } catch (Exception exception) { Log.Error(exception); return(null); } }
private async Task Run() { string[] Scopes = new[] { DriveService.Scope.DriveReadonly }; UserCredential credential; ClientSecrets secrets = new ClientSecrets { ClientId = "703137161297-kcdmjcjk5caa9ampgvraqa4ktt5nsqit.apps.googleusercontent.com", ClientSecret = "2XXbusAQkVUsY7MvoxXQRlIi" }; credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(secrets, Scopes, "user", CancellationToken.None); // Create the service. var service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "hitfit.app", }); FilesResource.ListRequest request = service.Files.List(); //request.PageSize = pageSize; request.Q = "mimeType = 'application/vnd.google-apps.document'"; request.Fields = "nextPageToken, files(id, name, mimeType, starred)"; var result = await request.ExecuteAsync(); var articles = new List <Article>(); foreach (var file in result.Files) { var docHtml = await service.Files.Export(file.Id, "text/html").ExecuteAsync(); var article = ParseGoogleDoc(docHtml); article.DocumentId = file.Id; article.Title = file.Name; if (file.Starred.HasValue) { article.Published = file.Starred.Value; } articles.Add(article); } //NpgsqlConnection connection = new NpgsqlConnection("Server=hitfitdbserver.postgres.database.azure.com;Database=hitfitdb;Port=5432;User Id=postgres@hitfitdbserver;Password=Tsunami9;"); NpgsqlConnection connection = new NpgsqlConnection("User ID=postgres;Password=Tsunami9;Host=localhost;Port=5432;Database=hitfitdb;Pooling=true;"); await connection.OpenAsync(); NpgsqlCommand command = new NpgsqlCommand(); command.Connection = connection; foreach (var article in articles) { command.Parameters.Clear(); command.CommandText = string.Format("SELECT content FROM articles WHERE documentid = '{0}'", article.DocumentId); NpgsqlDataReader reader = command.ExecuteReader(); if (reader.HasRows) { await reader.CloseAsync(); command.CommandText = string.Format( "UPDATE articles SET title = @title, headerimage = @headerimage, content = @content, published = @published WHERE documentid = @documentid", article.Title, article.HeaderImage, article.Content, article.Published, article.DocumentId); command.Parameters.AddWithValue("@documentid", article.DocumentId); command.Parameters.AddWithValue("@title", article.Title); command.Parameters.AddWithValue("@headerimage", article.HeaderImage); command.Parameters.AddWithValue("@content", article.Content); command.Parameters.AddWithValue("@published", article.Published); await command.ExecuteNonQueryAsync(); } else { await reader.CloseAsync(); command.CommandText = string.Format( "INSERT INTO articles (documentid, title, headerimage, content, published) SELECT @documentid, @title, @headerimage, @content, @published", article.DocumentId, article.Title, article.HeaderImage, article.Content, article.Published ? "true" : "false"); command.Parameters.AddWithValue("@documentid", article.DocumentId); command.Parameters.AddWithValue("@title", article.Title); command.Parameters.AddWithValue("@headerimage", article.HeaderImage); command.Parameters.AddWithValue("@content", article.Content); command.Parameters.AddWithValue("@published", article.Published); await command.ExecuteNonQueryAsync(); } } connection.Close(); }
private void button1_Click_1(object sender, EventArgs e) { System.Windows.Forms.Cursor.Current = Cursors.WaitCursor; table = new DataTable(); g.AutoGenerateColumns = false; //g.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None; table.Columns.Add("Name", typeof(string)); table.Columns.Add("Modified", typeof(DateTime)); table.Columns.Add("Size", typeof(double)); table.Columns.Add("Parent", typeof(string)); table.Columns.Add("Id", typeof(string)); g.DataSource = table; stat.Text = "Connecting"; System.IO.FileStream stream = new System.IO.FileStream( "client_secret.json", System.IO.FileMode.Open, System.IO.FileAccess.Read ); // credential.Token // https://developers.google.com/accounts/docs/OAuth2InstalledApp // http://stackoverflow.com/questions/7367449/google-api-how-to-authenticate-without-redirection // http://stackoverflow.com/questions/9809742/how-to-automate-login-to-google-api-to-get-oauth-2-0-token-to-access-known-user // token is stored here: %AppData%\Roaming\Drive.Auth.Store\Google.Apis.Auth.OAuth2.Responses.TokenResponse-user // http://www.daimto.com/google-oauth2-csharp/#Loading_Stored_refresh-Token UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, new[] { DriveService.Scope.Drive }, "user", CancellationToken.None ).Result; stream.Close(); // Create the service. service = new DriveService( new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Google Drive Trash Selective Cleaner", } ); // first request FilesResource.ListRequest request = service.Files.List(); request.MaxResults = 1000; request.Fields = "items(id,fileSize,labels/trashed,modifiedDate,title,parents/id),nextPageToken"; // RFC 3339 format, default timezone is UTC, e.g., 2012-06-04T12:00:00-08:00. string d1 = XmlConvert.ToString(fromdate.Value, XmlDateTimeSerializationMode.Utc); string d2 = XmlConvert.ToString(todate.Value.AddDays(1), XmlDateTimeSerializationMode.Utc); string fname; string fext; int ind = filetitle.Text.LastIndexOf('.'); if (ind >= 0) { fname = filetitle.Text.Substring(0, ind); fext = filetitle.Text.Substring(ind); } else { fname = filetitle.Text; fext = ""; } request.Q = "trashed=true " + "and modifiedDate >= '" + d1 + "' " + "and modifiedDate < '" + d2 + "' " + "and title contains '" + fname + "' "; double savedmb = 0; int count = 0; long fromsize = (long)(double.Parse(minsize.Text, culture.NumberFormat) * 1024 * 1024); long tosize = (long)(double.Parse(maxsize.Text, culture.NumberFormat) * 1024 * 1024); stat.Text = "Searching"; do { FileList files = request.Execute(); request.PageToken = files.NextPageToken; foreach (File f in files.Items) { // since filesize and fileextension are not queryable // (and mimeType is not reliable) long filesize = f.FileSize ?? 0; if (filesize >= fromsize && filesize <= tosize && f.Title.EndsWith(fext)) { DataRow r = table.NewRow(); r["Id"] = f.Id; r["Name"] = f.Title; r["Modified"] = f.ModifiedDate; double kb = (double)(filesize) / 1024; savedmb += kb / 1024; r["Size"] = kb; // filling the first rows will be slower because of an empty cache if (f.Parents.Count > 0) { r["Parent"] = GetFullPath(f.Parents[0].Id); } table.Rows.Add(r); count++; l1.Text = "Items: " + count; l2.Text = "MB: " + Math.Round(savedmb, 2); Application.DoEvents(); } } } while (!String.IsNullOrEmpty(request.PageToken)); System.Windows.Forms.Cursor.Current = Cursors.Default; button2.Enabled = count > 0; stat.Text = ""; MessageBox.Show("Done searching"); }
static void Main(string[] args) { //refer to https://developers.google.com/drive/api/v3/quickstart/dotnet to get this json file string credPath = @"c:\orbit-y-drive-service.json"; GoogleCredential credential; using (var stream = new FileStream(credPath, FileMode.Open, FileAccess.Read)) { credential = GoogleCredential.FromStream(stream).CreateScoped(Scopes); } DriveService service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); string teamDrivePageToken = null; string teamDriveID = null; do { TeamdrivesResource.ListRequest teamDriveList = service.Teamdrives.List(); teamDriveList.Fields = "nextPageToken, teamDrives(kind, id, name)"; teamDriveList.PageToken = teamDrivePageToken; var result = teamDriveList.Execute(); var teamDrives = result.TeamDrives; if (teamDrives != null && teamDrives.Count > 0) { foreach (TeamDrive drive in teamDrives) { if (drive.Name == TeamDriveName) { teamDriveID = drive.Id; break; } } } teamDrivePageToken = result.NextPageToken; } while (teamDrivePageToken != null && teamDriveID == null); if (teamDriveID == null) { WriteLogEntry("Team drive not found", null); StopService(); return; } string rootFolderPageToken = null; string rootFolderId = ""; do { FilesResource.ListRequest rootFolderRequest = service.Files.List(); rootFolderRequest.Fields = "nextPageToken, files(id, name, parents, mimeType)"; rootFolderRequest.PageToken = rootFolderPageToken; rootFolderRequest.SupportsTeamDrives = true; rootFolderRequest.IncludeTeamDriveItems = true; rootFolderRequest.Corpora = "teamDrive"; rootFolderRequest.TeamDriveId = teamDriveID; rootFolderRequest.Q = "parents='" + teamDriveID + "' and trashed=false and name='" + RootFolderName + "'"; var result = rootFolderRequest.Execute(); var files = result.Files; if (files != null && files.Count == 1) { var file = files[0]; if (file.MimeType == "application/vnd.google-apps.folder") { rootFolderId = file.Id; break; } } rootFolderPageToken = result.NextPageToken; } while (rootFolderPageToken != null && rootFolderId == null); if (rootFolderId == "") { WriteLogEntry("Error finding Root Folder. This can be caused by a duplicate folder, no folder, or execution error etc.", null); StopService(); return; } string recordFolderPageToken = null; List <Google.Apis.Drive.v3.Data.File> recordFolders = new List <Google.Apis.Drive.v3.Data.File>(); do { FilesResource.ListRequest recordFoldersRequest = service.Files.List(); recordFoldersRequest.Fields = "nextPageToken, files(id, name, parents, mimeType)"; recordFoldersRequest.PageToken = recordFolderPageToken; recordFoldersRequest.SupportsTeamDrives = true; recordFoldersRequest.IncludeTeamDriveItems = true; recordFoldersRequest.Corpora = "teamDrive"; recordFoldersRequest.TeamDriveId = teamDriveID; recordFoldersRequest.Q = "parents='" + rootFolderId + "' and trashed=false"; var result = recordFoldersRequest.Execute(); var files = result.Files; if (files != null && files.Count > 0) { foreach (Google.Apis.Drive.v3.Data.File file in files) { if (file.MimeType == "application/vnd.google-apps.folder") { recordFolders.Add(file); } else { //file found. shouldnt happen - delete TrashDriveObject(service, file.Id); } } } recordFolderPageToken = result.NextPageToken; } while (recordFolderPageToken != null); if (recordFolders.Count != 0) { foreach (Google.Apis.Drive.v3.Data.File recordFolder in recordFolders) { string addOnEmail = ""; if (isAddOnFinished(service, teamDriveID, recordFolder.Id, ref addOnEmail)) { string recordNumber = recordFolder.Name; if (isValidRecordNumber(recordNumber) == false && isValidSubawardNumber(recordNumber) == false) { SendErrorEmail(addOnEmail, "Record number " + recordNumber + " does not exist in ORBiT."); TrashDriveObject(service, recordFolder.Id); continue; } string EFilesFolder = GetEFilesFolder(recordNumber); if (EFilesFolder == "") { SendErrorEmail(addOnEmail, "Could not find an EFiles folder. Record number is " + recordNumber); TrashDriveObject(service, recordFolder.Id); continue; } string filePageToken = null; List <string> lstSavedFiles = new List <string>(); do { FilesResource.ListRequest filesRequest = service.Files.List(); filesRequest.Fields = "nextPageToken, files(id, name, parents, mimeType)"; filesRequest.PageToken = filePageToken; filesRequest.SupportsTeamDrives = true; filesRequest.IncludeTeamDriveItems = true; filesRequest.Corpora = "teamDrive"; filesRequest.TeamDriveId = teamDriveID; filesRequest.Q = "parents='" + recordFolder.Id + "' and trashed=false"; var result = filesRequest.Execute(); var files = result.Files; bool stopFlag = false; foreach (Google.Apis.Drive.v3.Data.File file in files) { var fileInfo = service.Files.Get(file.Id); if (file.MimeType == "application/vnd.google-apps.folder") { //folder found - shouldnt happen - trash folder TrashDriveObject(service, file.Id); } else { if (file.Name == FlagFileName || file.Name == TempFileName) { continue; } else { using (MemoryStream ms = new MemoryStream()) { fileInfo.Download(ms); string filenameToSave = getUniqueFilename(EFilesFolder, file.Name); try { using (FileStream fs = new FileStream(EFilesFolder + filenameToSave, FileMode.Create, System.IO.FileAccess.Write)) { try { fs.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length); } catch (Exception e) { string message = "Error saving file to Y Drive. Record Number: " + recordNumber + ", file name: " + file.Name; WriteLogEntry(message, e); if (lstSavedFiles.Count > 0) { message += "<br /><br />"; message += "The following files were saved successfully:<br /><ul>"; for (int i = 0; i < lstSavedFiles.Count; i++) { message += "<li>" + lstSavedFiles[i] + "</li>"; } message += "</ul>"; } SendErrorEmail(addOnEmail, message); stopFlag = true; ms.Close(); break; } lstSavedFiles.Add(filenameToSave); } ms.Close(); } catch (Exception e) { WriteLogEntry("Error writing to filestream. File name is " + filenameToSave, e); string message = "Error saving file to Y Drive. Record Number: " + recordNumber + ", file name: " + file.Name; if (lstSavedFiles.Count > 0) { message += "<br /><br />"; message += "The following files were saved successfully:<br /><ul>"; for (int i = 0; i < lstSavedFiles.Count; i++) { message += "<li>" + lstSavedFiles[i] + "</li>"; } message += "</ul>"; } SendErrorEmail(addOnEmail, message); stopFlag = true; break; } } } } } if (stopFlag == true) { break; } filePageToken = result.NextPageToken; } while (filePageToken != null); TrashDriveObject(service, recordFolder.Id); } } } }
public async Task <IActionResult> Edit(int id, [Bind("Id,Judul,Path,FImage,PenulisBuku,Terbitan,ISBN,Deskripsi,Tebal,Tanggal,Kategori,Tag,Penulis,Status,DriveId,Parents")] Buku buku, IFormFile file) { if (id != buku.Id) { return(NotFound()); } if (ModelState.IsValid) { try { DriveService service = driveService.GetService(); var folderId = "1aB_0pJ9qsHjP3DhOERmWacA2Mn1jDW7H"; string path = Path.GetTempFileName(); var fileMetadata = new Google.Apis.Drive.v3.Data.File() { Name = Path.GetFileName(file.FileName), Parents = new List <string> { folderId } }; FilesResource.CreateMediaUpload request; using (var stream = new System.IO.FileStream(path, System.IO.FileMode.Open)) { await file.CopyToAsync(stream); request = service.Files.Create( fileMetadata, stream, "image/jpeg"); request.Fields = "id"; request.Upload(); } var fileUploaded = request.ResponseBody; buku.FImage = "https://drive.google.com/uc?id=" + fileUploaded.Id; if (buku.FImage != null) { buku.FImage = buku.FImage.Replace("file/d/", "uc?id="); buku.FImage = buku.FImage.Replace("/view?usp=sharing", ""); } if (buku.Penulis == null) { buku.Penulis = "admin"; } buku.Tanggal = DateTime.Now; _context.Update(buku); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!BukuExists(buku.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(List))); } return(View(buku)); }
public Files(DriveService service) : base(service) { DefaultGetFieldsOnResponse = "nextPageToken, files(id, name, mimeType, owners, parents, permissions, shared, trashed, webContentLink, webViewLink)"; DefaultFileFieldsOnResponse = "id, name, mimeType, owners, parents, permissions, shared, trashed, webContentLink, webViewLink"; DefaultPageSizePerRequest = 1000; }
static void Main(string[] args) { // ************************************************************ // ASSUMPTION: Unit test has been run on Google Drive first // ************************************************************ var googleDriveManager = new GoogleDriveManager(); var googleSheetManager = new GoogleSheetManager(); GoogleCredential credentialReadOnly = null; GoogleCredential credentialFullAccess = null; DriveService driveServiceReadOnly = null; DriveService driveServiceFullAccess = null; SheetsService sheetsServiceReadOnly = null; SheetsService sheetsServiceFullAccess = null; #region STEP 0: Pre-test validation if (System.IO.File.Exists("client-secret.json") == false) { Console.WriteLine("******* ERROR: Please ensure you have downloaded your Google API .JSON file and copied into same folder as the .EXE *******"); Console.ReadKey(); return; } // Get the readonly drive credentials. (If it fails here run UnitTestGoogleDriveViaConsole to troubleshoot) credentialReadOnly = googleDriveManager.GetUserCredential("client-secret.json", googleDriveManager.ReadOnlyScope); if (credentialReadOnly == null) { Console.WriteLine("******* PRE-TEST VALIDATION FAILED - Credentials returned null when getting Read Only Scope permissions"); Console.WriteLine("*******"); Console.ReadKey(); return; } // Get the full access drive credentials. (If it fails here run UnitTestGoogleDriveViaConsole to troubleshoot) credentialFullAccess = googleDriveManager.GetUserCredential("client-secret.json", googleDriveManager.FullAccessScope); if (credentialFullAccess == null) { Console.WriteLine("******* PRE-TEST VALIDATION FAILED - Credentials returned null when getting Full Access Scope permissions"); Console.WriteLine("*******"); Console.ReadKey(); return; } // Get Drive Service Instance as Read-Only driveServiceReadOnly = googleDriveManager.CreateDriveServiceInstance(credentialReadOnly, "UnitTest Google Sheet Library"); if (driveServiceReadOnly == null) { Console.WriteLine("******* STEP 2.2.1 - FAILED - drive service returned null getting it with Read Only credentials. "); Console.WriteLine("*******"); Console.ReadKey(); return; } // Get Drive Service Instance as Full Access driveServiceFullAccess = googleDriveManager.CreateDriveServiceInstance(credentialFullAccess, "UnitTest Google Sheet Library"); if (driveServiceFullAccess == null) { Console.WriteLine("******* STEP 2.2.2 - FAILED - drive service returned null getting it with Full Access credentials. "); Console.WriteLine("*******"); Console.ReadKey(); return; } var t1Folder = googleDriveManager.GetFolderByName(driveServiceReadOnly, "T1"); if (t1Folder == null) { Console.WriteLine("******* ERROR: T1 folder should already exist. Please ensure you ran UnitTestGoogleDriveViaConsole first. *******"); Console.ReadKey(); return; } // Check if sheet exists and so delete it var sheetFile = googleDriveManager.GetSheetFileInChildFolderByName(driveServiceReadOnly, "TestSheet", t1Folder.Id); if (sheetFile != null) { googleDriveManager.DeleteFile(driveServiceFullAccess, sheetFile.Id); } #endregion #region STEP 1: Create the test sheet #region STEP 1.1: Negative Testing // STEP 1.1.1 - Test no drive service try { var expectedFailure = googleDriveManager.CreateGoogleSheet(null, string.Empty, string.Empty, null); } catch (Exception exception) { Console.WriteLine("******* STEP 1.1.1 - PASSED : EXPECTED FAILURE with no drive service passed: "); Console.WriteLine(exception.ToString()); Console.WriteLine("*******"); Console.ReadKey(); } // STEP 3.1.2 - Test drive service, no sheet name try { var expectedFailure = googleDriveManager.CreateGoogleSheet(driveServiceFullAccess, string.Empty, string.Empty, new List <string> { t1Folder.Id }); } catch (Exception exception) { Console.WriteLine("******* STEP 3.1.2 - PASSED : EXPECTED FAILURE with drive service but no sheet name: "); Console.WriteLine(exception.ToString()); Console.WriteLine("*******"); Console.ReadKey(); } #endregion #region STEP 1.2 Positive Testing var sheetFileId = googleDriveManager.CreateGoogleSheet(driveServiceFullAccess, "TestSheet", "Sheet used to Unit test CSHARP Sheet Library.", new List <string> { t1Folder.Id }); if (string.IsNullOrEmpty(sheetFileId)) { Console.WriteLine("******* ERROR: Failed to create test sheet *******"); Console.ReadKey(); return; } #endregion #endregion #region STEP 2: Assign Read Permissions to [email protected] // Get the permission object so we can use it to assign permission to the sheet var permission = googleDriveManager.CreateUserPermission("reader", "*****@*****.**"); if (permission == null) { Console.WriteLine("******* ERROR: Failed to create user permission object for [email protected] *******"); Console.ReadKey(); return; } // Assign the permission to the sheet if (googleDriveManager.AssignPermissionToFile(driveServiceFullAccess, sheetFileId, permission) == false) { Console.WriteLine("******* ERROR: Failed to set reader permission for user [email protected] for spreadsheet *******"); Console.ReadKey(); return; } // Get the permission object so we can use it to assign permission to the sheet permission = googleDriveManager.CreateUserPermission("writer", "*****@*****.**"); if (permission == null) { Console.WriteLine("******* ERROR: Failed to create user permission object for [email protected] *******"); Console.ReadKey(); return; } // Assign the permission to the sheet if (googleDriveManager.AssignPermissionToFile(driveServiceFullAccess, sheetFileId, permission) == false) { Console.WriteLine("******* ERROR: Failed to set write permission for user [email protected] for spreadsheet *******"); Console.ReadKey(); return; } #endregion #region STEP 3: Get Sheets Service Instance #region STEP 3.1: Negative Testing // STEP 3.1.1 - Test no credentials passed in and no application name try { var expectedFailure = googleSheetManager.CreateSheetServiceInstance(null, string.Empty); } catch (Exception exception) { Console.WriteLine("******* STEP 3.1.1 - PASSED : EXPECTED FAILURE with no credentials passed: "); Console.WriteLine(exception.ToString()); Console.WriteLine("*******"); Console.ReadKey(); } // STEP 2.1.2 - Test credentials passed in but no application name try { var expectedFailure = googleSheetManager.CreateSheetServiceInstance(credentialReadOnly, string.Empty); } catch (Exception exception) { Console.WriteLine("******* STEP 3.1.2 - PASSED : EXPECTED FAILURE with no application name passed: "); Console.WriteLine(exception.ToString()); Console.WriteLine("*******"); Console.ReadKey(); } #endregion #region STEP 3.2: Positive Testing // STEP 3.2.1 - Test getting sheet service with ReadOnly Scope try { sheetsServiceReadOnly = googleSheetManager.CreateSheetServiceInstance(credentialReadOnly, "UnitTest Google Sheet Library"); if (sheetsServiceReadOnly == null) { Console.WriteLine("******* STEP 3.2.1 - FAILED - sheets service returned null getting it with Read Only credentials. "); Console.WriteLine("*******"); Console.ReadKey(); return; } } catch (Exception exception) { Console.WriteLine("******* STEP 3.2.1 - FAILED - Exception thrown getting sheets service using Read Only credentials."); Console.WriteLine(exception.ToString()); Console.WriteLine("*******"); Console.ReadKey(); return; } // STEP 3.2.2 - Test getting sheet service with Full Access Scope try { sheetsServiceFullAccess = googleSheetManager.CreateSheetServiceInstance(credentialFullAccess, "UnitTest Google Sheet Library"); if (sheetsServiceFullAccess == null) { Console.WriteLine("******* STEP 3.2.2 - FAILED - sheets service returned null getting it with Full Access credentials. "); Console.WriteLine("*******"); Console.ReadKey(); return; } } catch (Exception exception) { Console.WriteLine("******* STEP 3.2.2 - FAILED - Exception thrown getting sheets service using Full Access credentials."); Console.WriteLine(exception.ToString()); Console.WriteLine("*******"); Console.ReadKey(); return; } Console.WriteLine("******* STEP 3.2 - PASSED"); Console.WriteLine("*******"); Console.ReadKey(); #endregion #endregion #region STEP 4: Read and Write Values from test sheet #region STEP 4.1 - Read range (should be blank) var testRange = "Sheet1!A2:E2"; var valueResults = googleSheetManager.GetSheetDataRange(sheetsServiceReadOnly, sheetFileId, testRange); if (valueResults == null) { Console.WriteLine("******* ERROR: Failed to get range in sheet *******"); Console.ReadKey(); return; } // Review the cells are empty. The Values are stored in an array of arrays IList <IList <Object> > values = valueResults.Values; if (values == null || values.Count == 0) { Console.WriteLine("******* PASSED: Expected range in sheet to be empty as we just created it *******"); Console.ReadKey(); } else { Console.WriteLine("******* ERROR: Failed as sheet range should have no data *******"); Console.ReadKey(); return; } #endregion #region STEP 4.2 - Write a single value and confirm it got written var singleCellTestRange = "Sheet1!A2"; googleSheetManager.UpdateSheetCellValue(sheetsServiceFullAccess, sheetFileId, singleCellTestRange, "New Text In A2"); var singleCellValueResult = googleSheetManager.GetSheetDataRange(sheetsServiceReadOnly, sheetFileId, singleCellTestRange); if (singleCellValueResult == null || singleCellValueResult.Values.Count == 0) { Console.WriteLine("******* ERROR: Failed to read back single cell value *******"); Console.ReadKey(); return; } if (singleCellValueResult.Values[0].Count == 0) { Console.WriteLine("******* ERROR: Failed to read back single cell value *******"); Console.ReadKey(); return; } if (singleCellValueResult.Values[0][0].ToString() != "New Text In A2") { Console.WriteLine("******* ERROR: Failed as single text value was not updated in the sheet *******"); Console.ReadKey(); return; } #endregion #region STEP 5: Bulk Write data to test sheet // Getting the range again as we did update a cell in the range. valueResults = googleSheetManager.GetSheetDataRange(sheetsServiceReadOnly, sheetFileId, testRange); // Fill in values in the results for (int rowIndex = 0; rowIndex < valueResults.Values.Count; rowIndex++) { for (int colIndex = 0; colIndex < valueResults.Values[rowIndex].Count; colIndex++) { valueResults.Values[rowIndex][colIndex] = rowIndex.ToString() + ":" + colIndex.ToString(); } } // Write the values googleSheetManager.UpdateSheetDataRange(sheetsServiceFullAccess, sheetFileId, testRange, valueResults); // Getting the range again to confirm updates. valueResults = googleSheetManager.GetSheetDataRange(sheetsServiceReadOnly, sheetFileId, testRange); // Check the expected values in the results for (int rowIndex = 0; rowIndex < valueResults.Values.Count; rowIndex++) { for (int colIndex = 0; colIndex < valueResults.Values[rowIndex].Count; colIndex++) { if (valueResults.Values[rowIndex][colIndex].ToString() != rowIndex.ToString() + ":" + colIndex.ToString()) { Console.WriteLine("******* ERROR: Failed as the value we expected to be updated was not: " + rowIndex.ToString() + ":" + colIndex.ToString() + " * ******"); Console.ReadKey(); return; } } } #endregion #endregion }
public void UploadFile() { UserCredential credential; credential = GetCredentials(); // Create Drive API service. var service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); string folderid; var requestFolder = service.Files.List(); requestFolder.Q = "mimeType = 'application/vnd.google-apps.folder' and name contains 'EBOOK'"; requestFolder.Spaces = "drive"; requestFolder.Fields = "nextPageToken, files(id, name)"; var result = requestFolder.Execute(); OpenFileDialog openFileDialog1 = new OpenFileDialog(); if (openFileDialog1.ShowDialog() == DialogResult.OK) { foreach (string filename in openFileDialog1.FileNames) { //Thread thread = new Thread(() => //{ //UploadImage(filename, service, folderid); //var a = requests.Resp; IList <string> folders = new List <string>(); folders.Add(result.Files.FirstOrDefault().Id); var fileMetadatas = new Google.Apis.Drive.v3.Data.File() { Name = filename.Split('\\').Last().ToString(), Parents = folders, }; FilesResource.CreateMediaUpload request; using (var stream = new System.IO.FileStream(filename, System.IO.FileMode.Open)) { request = service.Files.Create( fileMetadatas, stream, "image/jpeg"); request.Fields = "id"; request.Upload(); var file = request.ResponseBody; var a = fileMetadatas; this.FileId = file.Id; } //}); //thread.IsBackground = true; //thread.Start(); } } //string pageToken = null; //do //{ // ListFiles(service, ref pageToken); //} while (pageToken != null); }
public async Task UploadBackupToDriveAsync() { bool result = _model.DoBackupToFile(); if (!result) { return; } //UserCredential credential; string credentialsFilePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "./credentials.json"); using (var stream = new FileStream(credentialsFilePath, FileMode.Open, FileAccess.Read)) { string credPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "/token.json"); Thread thread = new Thread(() => { credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, scopes, "user", CancellationToken.None, new FileDataStore(credPath, true) ).Result; }); thread.Start(); if (!thread.Join(60000)) { MessageBox.Show("Error en iniciar sesión!"); return; } } // Create Drive API service. var service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "MejiaDrive", }); //File info var FileMetadata = new Google.Apis.Drive.v3.Data.File(); FileMetadata.Name = "MejiaBackup"; FileMetadata.MimeType = "application/octet-stream"; //Request FilesResource.CreateMediaUpload request; string fileToUploadPath = @"C:\Users\Public\Documents\SqlBackups\MejiaBackup.bak"; //Take fileStream and Execute request using (var stream = new FileStream(fileToUploadPath, FileMode.Open)) { fileSize = stream.Length; request = service.Files.Create(FileMetadata, stream, "application/octet-stream"); request.Fields = "id"; request.ProgressChanged += UploadProgressEvent; //await request.UploadAsync(); //Google.Apis.Upload.IUploadProgress x = await request.UploadAsync(); await request.UploadAsync(); } }
public bool InitService() { driverservice = createService(); serviceStarted = true; return(true); }