Visual Basic.NET - API Drive con Visual Basic .NET

 
Vista:

API Drive con Visual Basic .NET

Publicado por Sebastian (3 intervenciones) el 23/10/2017 18:03:40
Necesito ayuda para manipular la API Drive de Google, toda la documentación está escrita en c# por lo tanto no me sirve.
He "traducido" el código a vb pero sigue sin funcionar, estoy usando la versión 2, y usando windows forms.
Les adjunto el código.
Gracias por su ayuda :D

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
Imports Google.Apis.Auth.OAuth2
Imports Google.Apis.Drive.v2
Imports Google.Apis.Drive.v2.Data
Imports Google.Apis.Services
Imports Google.Apis.Util.Store
Imports System
Imports System.Collections.Generic
Imports System.IO
Imports System.Linq
Imports System.Text
Imports System.Threading
Imports System.Threading.Tasks
 
Imports Google
Imports Google.Apis.Auth
Imports Google.Apis.Download
 
Public Class Form1
 
 
Private Service As DriveService = New DriveService
 
Private Sub CreateService()
 
    Dim ClientId = "My id client"
    Dim ClientSecret = "My secret client"
    Dim MyUserCredential As UserCredential = GoogleWebAuthorizationBroker.AuthorizeAsync(New ClientSecrets() With {.ClientId = ClientId, .ClientSecret = ClientSecret}, {DriveService.Scope.Drive}, "user", CancellationToken.None).Result
    Service = New DriveService(New BaseClientService.Initializer() With {.HttpClientInitializer = MyUserCredential, .ApplicationName = "PruebaAPIDrivee"})
 
End Sub
 
 
Private Sub UploadFile(FilePath As String)
    Me.Cursor = Cursors.WaitCursor
    If Service.ApplicationName <> "PruebaAPIDrivee" Then CreateService()
 
    Dim TheFile As New Apis.Drive.v2.Data.File()
    TheFile.Title = "My document"
    TheFile.Description = "A test document"
    TheFile.MimeType = "text/plain"
 
    Dim ByteArray As Byte() = System.IO.File.ReadAllBytes(FilePath)
    Dim Stream As New System.IO.MemoryStream(ByteArray)
 
    Dim UploadRequest As FilesResource.InsertMediaUpload = Service.Files.Insert(TheFile, Stream, TheFile.MimeType)
 
    Me.Cursor = Cursors.Default
 
    MsgBox("Upload Finished")
End Sub
 
Private Sub DownloadFile(url As String, DownloadDir As String)
    Me.Cursor = Cursors.WaitCursor
    If Service.ApplicationName <> "Google Drive VB Dot Net" Then CreateService()
 
    Dim Downloader = New MediaDownloader(Service)
    Downloader.ChunkSize = 256 * 1024 '256 KB
 
    ' figure out the right file type base on UploadFileName extension
    Dim Filename = DownloadDir & "NewDoc.txt"
    Using FileStream = New System.IO.FileStream(Filename, System.IO.FileMode.Create, System.IO.FileAccess.Write)
        Dim Progress = Downloader.DownloadAsync(url, FileStream)
        Threading.Thread.Sleep(1000)
        Do While Progress.Status = TaskStatus.Running
        Loop
        If Progress.Status = TaskStatus.RanToCompletion Then
            MsgBox("Downloaded!")
        Else
            MsgBox("Not Downloaded :(")
        End If
    End Using
    Me.Cursor = Cursors.Default
End Sub
 
 
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Dim openFileDialog1 As New OpenFileDialog()
 
    openFileDialog1.InitialDirectory = "c:\"
    openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
    openFileDialog1.FilterIndex = 2
    openFileDialog1.RestoreDirectory = True
 
    If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
 
        TextBox1.Text = openFileDialog1.FileName()
    End If
End Sub
 
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
 
    UploadFile(TextBox1.Text)
End Sub
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
sin imagen de perfil

API Drive con Visual Basic .NET

Publicado por omar (166 intervenciones) el 24/10/2017 15:43:37
Saludos, dime que deseas hacer para poder ayudarte
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

API Drive con Visual Basic .NET

Publicado por Sebastian (3 intervenciones) el 24/10/2017 16:25:17
Lo que sucede es que simplemente no funciona, cambie el lenguaje y ahora lo hice en c# por consola.
Uso las credenciales etc etc, y por ejemplo uso una función para subir un archivo y sale subida exitosa y todo, pero en el drive no cambia nada, no entiendo que sucede, aquí el código...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Drive.v3.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
 
using System.IO;
using System.Threading;
using Google.Apis.Download;
 
using Google.Apis.Requests;
using Google;
using Google.Apis.Drive;
using Google.Apis;
 
namespace APIDrive
{
    class Program
    {
        static string[] Scopes = { DriveService.Scope.DriveReadonly };
        static string ApplicationName = "APIDrive";
 
        static void Main(string[] args)
        {
            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,
                     Scopes,
                     "user",
                     CancellationToken.None,
                     new FileDataStore(credPath, true)).Result;
                Console.WriteLine("El archivo credencial se guarda en: " + credPath);
            }
 
            // Crea el servicio de API Drive
            var service = new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = ApplicationName,
            });
 
 
            //LISTAR ARCHIVOS DEL DRIVE
            //  Definir lo parámetros de solicitud
            FilesResource.ListRequest listRequest = service.Files.List();
            listRequest.PageSize = 500;
            listRequest.Fields = "nextPageToken, files(id, name)";
 
            // Mostramos la lista de archivos
            IList<Google.Apis.Drive.v3.Data.File> files = listRequest.Execute()
                .Files;
            Console.WriteLine("Archivos:");
            if (files != null && files.Count > 0)
            {
                foreach (var archivos in files)
                {
                    Console.WriteLine("{0} ({1})", archivos.Name, archivos.Id);
                }
            }
            else
            {
                Console.WriteLine("No hay archivos disponibles");
            }
            Console.Read();
 
 
            descargarArchivo("0B8xKih1hNvVxbWpOSHVmWkNHV0U", service);
            //crearCarpeta("PruebaDriveApi", service);
            //subirImagen("C:\\Users\\John\\Pictures\\pollo.jpeg", service);
        }
 
        //DESCARGAR UN ARCHIVO DEL DRIVE
        public static void descargarArchivo(string idArchivo, DriveService service)
        {
            var fileId = idArchivo;
            var request = service.Files.Get(fileId);
            var streamm = new System.IO.MemoryStream();
 
            request.MediaDownloader.ProgressChanged +=
                (IDownloadProgress progress) =>
                {
                    switch (progress.Status)
                    {
                        case DownloadStatus.Downloading:
                            {
                                Console.WriteLine(progress.BytesDownloaded);
                                break;
                            }
                        case DownloadStatus.Completed:
                            {
                                Console.WriteLine("Descarga completada");
                                Console.WriteLine(fileId);
                                Console.WriteLine("Presione cualquier tecla para continuar...");
                                Console.ReadKey();
                                break;
 
                            }
                        case DownloadStatus.Failed:
                            {
                                Console.WriteLine("Fallo al descargar");
                                Console.WriteLine("Presione cualquier tecla para continuar...");
                                Console.ReadKey();
                                break;
                            }
                    }
                };
            request.Download(streamm);
        }
 
        //CREAR UNA CARPETA EN EL DRIVE
        public static void crearCarpeta(string nombreCarpeta, DriveService service)
        {
            var fileMetadata = new Google.Apis.Drive.v3.Data.File()
            {
                Name = nombreCarpeta,
                MimeType = "application/vnd.google-apps.folder"
            };
            var request = service.Files.Create(fileMetadata);
            request.Fields = "Id";
            var file = request.Execute();
            Console.WriteLine("ID del folder: " + file.Id);
        }
 
        ///////////SUBIR IMAGEN//////////////////7
        private static void subirImagen(string path, DriveService service)
        {
            var fileMetadata = new Google.Apis.Drive.v3.Data.File();
            fileMetadata.Name = Path.GetFileName(path);
            fileMetadata.MimeType = "image/jpeg";
            FilesResource.CreateMediaUpload request;
            using (var stream = new System.IO.FileStream(path, System.IO.FileMode.Open))
            {
                request = service.Files.Create(fileMetadata, stream, "image/jpeg");
                request.Fields = "id";
                request.Upload();
            }
 
            var file = request.ResponseBody;
 
            Console.WriteLine("Archivo subido: " + path);
            Console.WriteLine("Presione cualquier tecla para continuar...");
            Console.ReadKey();
 
        }
 
 
    }
}
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

API Drive con c# .NET

Publicado por Sebastian (3 intervenciones) el 24/10/2017 16:27:28
Lo mismo sucede con la función de descargar, sale como si se hubiera descargado pero en realidad no descarga, lo único que funciona es la parte de listar todos los archivos que hay en el drive, eso si lo muestra normal, lo cual quiere decir que el problema no es con las credenciales de la API.
Help Me!
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

API Drive con c# .NET

Publicado por bryann amortegui (1 intervención) el 11/11/2021 21:55:16
que tal, una pregunta, lograste solucionar eso ? me pasa exactamente lo mismo!!1
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar