Exemplo n.º 1
0
        public void Authenticate()
        {
            try
            {
                if (string.IsNullOrEmpty(strAppKey))
                {
                    MessageBox.Show("Please enter valid App Key !");
                    return;
                }
                if (DBB == null)
                {
                    DBB = new DropBoxIntegration(strAppKey, strAppSecret, "FileMI");

                    strAuthenticationURL = DBB.GeneratedAuthenticationURL(); // This method must be executed before generating Access Token.
                    strAccessToken       = DBB.GenerateAccessToken();
                    gbDropBox.IsEnabled  = true;
                    this.Authorization   = new HttpAuthorization(AuthorizationType.Bearer, DBB.AccessTocken);
                }
                else
                {
                    gbDropBox.IsEnabled = false;
                }
            }
            catch (Exception)
            {
                throw;
            }
            this.Getfiles();
        }
        public async Task UploadRangeFromUriAsync_SourceBearerToken()
        {
            // Arrange
            BlobServiceClient blobServiceClient = InstrumentClient(new BlobServiceClient(
                                                                       new Uri(TestConfigOAuth.BlobServiceEndpoint),
                                                                       GetOAuthCredential(TestConfigOAuth),
                                                                       GetBlobOptions()));
            BlobContainerClient containerClient = InstrumentClient(blobServiceClient.GetBlobContainerClient(GetNewShareName()));

            try
            {
                await containerClient.CreateIfNotExistsAsync();

                AppendBlobClient appendBlobClient = InstrumentClient(containerClient.GetAppendBlobClient(GetNewFileName()));
                await appendBlobClient.CreateAsync();

                byte[] data = GetRandomBuffer(Constants.KB);
                using Stream stream = new MemoryStream(data);
                await appendBlobClient.AppendBlockAsync(stream);

                ShareServiceClient serviceClient = GetServiceClient_OAuth_SharedKey();
                await using DisposingShare test = await GetTestShareAsync(
                                service : serviceClient,
                                shareName : GetNewShareName());

                ShareDirectoryClient directoryClient = InstrumentClient(test.Share.GetDirectoryClient(GetNewDirectoryName()));
                await directoryClient.CreateAsync();

                ShareFileClient fileClient = InstrumentClient(directoryClient.GetFileClient(GetNewFileName()));
                await fileClient.CreateAsync(Constants.KB);

                string sourceBearerToken = await GetAuthToken();

                HttpAuthorization sourceAuthHeader = new HttpAuthorization(
                    "Bearer",
                    sourceBearerToken);

                ShareFileUploadRangeFromUriOptions options = new ShareFileUploadRangeFromUriOptions
                {
                    SourceAuthentication = sourceAuthHeader
                };

                HttpRange range = new HttpRange(0, Constants.KB);

                // Act
                await fileClient.UploadRangeFromUriAsync(
                    sourceUri : appendBlobClient.Uri,
                    range : range,
                    sourceRange : range,
                    options : options);
            }
            finally
            {
                await containerClient.DeleteIfExistsAsync();
            }
        }
Exemplo n.º 3
0
        public async Task UploadRangeFromUriAsync_SourceBearerTokenFail()
        {
            // Arrange
            BlobServiceClient blobServiceClient = InstrumentClient(new BlobServiceClient(
                                                                       new Uri(Tenants.TestConfigOAuth.BlobServiceEndpoint),
                                                                       Tenants.GetOAuthCredential(Tenants.TestConfigOAuth),
                                                                       GetBlobOptions()));
            BlobContainerClient containerClient = InstrumentClient(blobServiceClient.GetBlobContainerClient(GetNewShareName()));

            try
            {
                await containerClient.CreateIfNotExistsAsync();

                AppendBlobClient appendBlobClient = InstrumentClient(containerClient.GetAppendBlobClient(GetNewFileName()));
                await appendBlobClient.CreateAsync();

                byte[] data = GetRandomBuffer(Constants.KB);
                using Stream stream = new MemoryStream(data);
                await appendBlobClient.AppendBlockAsync(stream);

                ShareServiceClient serviceClient = SharesClientBuilder.GetServiceClient_OAuthAccount_SharedKey();
                await using DisposingShare test = await GetTestShareAsync(
                                service : serviceClient,
                                shareName : GetNewShareName());

                ShareDirectoryClient directoryClient = InstrumentClient(test.Share.GetDirectoryClient(GetNewDirectoryName()));
                await directoryClient.CreateAsync();

                ShareFileClient fileClient = InstrumentClient(directoryClient.GetFileClient(GetNewFileName()));
                await fileClient.CreateAsync(Constants.KB);

                HttpAuthorization sourceAuthHeader = new HttpAuthorization(
                    "Bearer",
                    "auth token");

                ShareFileUploadRangeFromUriOptions options = new ShareFileUploadRangeFromUriOptions
                {
                    SourceAuthentication = sourceAuthHeader
                };

                HttpRange range = new HttpRange(0, Constants.KB);

                // Act
                await TestHelper.AssertExpectedExceptionAsync <RequestFailedException>(
                    fileClient.UploadRangeFromUriAsync(
                        sourceUri: appendBlobClient.Uri,
                        range: range,
                        sourceRange: range,
                        options: options),
                    e => Assert.AreEqual("CannotVerifyCopySource", e.ErrorCode));
            }
            finally
            {
                await containerClient.DeleteIfExistsAsync();
            }
        }
Exemplo n.º 4
0
 public static void DeleteAsync(string endpoint = null, HttpParameterCollection parameters                   = null,
                                HttpAuthorization authorization = null, NameValueCollection headers          = null, string contentType = null,
                                AccessToken accessToken         = null, ExecuteRequestAsyncCallback callback = null, bool allowWriteStreamBuffering = false,
                                bool allowSendChunked           = true, long contentLength = -1, HttpWriteRequestStream streamWriteCallback         = null,
                                int writeBufferSize             = 4096, int readBufferSize = 4096, bool donotEncodeKeys = false)
 {
     NewOAuthUtility.ExecuteRequestAsync("DELETE", endpoint, parameters, authorization, headers, contentType, accessToken,
                                         callback, allowWriteStreamBuffering, allowSendChunked, contentLength, streamWriteCallback, writeBufferSize,
                                         readBufferSize, donotEncodeKeys);
 }
Exemplo n.º 5
0
 private void Form1_Load(object sender, EventArgs e)
 {
     if (String.IsNullOrEmpty(Properties.Settings.Default.AccessToken))
     {
         this.GetAccesToken();
     }
     else
     {
         this.Authorization = new HttpAuthorization(AuthorizationType.Bearer, Properties.Settings.Default.AccessToken);
         this.GetFiles();
     }
 }
Exemplo n.º 6
0
        /// <summary>
        /// Checks the validity of the access token.
        /// </summary>
        private void CheckAccessToken()
        {
            this.RequestStart();

            this.Authorization = new HttpAuthorization(AuthorizationType.Bearer, Properties.Settings.Default.AccessToken);

            OAuthUtility.PostAsync
            (
                "https://api.dropboxapi.com/2/users/get_current_account",
                authorization: this.Authorization,
                callback: CheckAccessToken_Result
            );
        }
Exemplo n.º 7
0
        public void ToStringTest()
        {
            // Arrange
            string            scheme            = "scheme";
            string            parameter         = "parameter";
            HttpAuthorization httpAuthorization = new HttpAuthorization(scheme, parameter);

            // Act
            string s = httpAuthorization.ToString();

            // Assert

            Assert.AreEqual($"{scheme} {parameter}", s);
        }
Exemplo n.º 8
0
        protected override void ConfigureRequestContainer(ILifetimeScope container, NancyContext context)
        {
            base.ConfigureRequestContainer(container, context);

            var module = new BuilderModule();

            module.Register(c => new WebApiCall(
                                HttpLink.From(context.Request.Url.ToString()),
                                HttpAuthorization.From(context.Request.Headers.Authorization),
                                WebApiCallBody.From(context.Request.Headers.ContentType, () => context.Request.Body)))
            .InstancePerRequest();

            module.Update(container.ComponentRegistry);
        }
Exemplo n.º 9
0
        private void Login_Load(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(Properties.Settings.Default.AccessToken))
            {
                this.GetAccessToken();
            }
            else
            {
                // create authorization header
                this.Authorization = new HttpAuthorization(AuthorizationType.Bearer, Properties.Settings.Default.AccessToken);

                // get files
                //this.GetFiles();
            }
        }
Exemplo n.º 10
0
        public HttpRequest(string data)
        {
            var parts = data.Split(new[] { "\r\n\r\n" }, StringSplitOptions.None);

            if (parts.Length < 1)
            {
                throw new Exception("Invalid data");
            }

            Body = parts.Length == 2 ? parts[1] : "";

            var headers = parts[0].Split('\n').ToList();

            var startingLine = headers[0].Split(' ');

            headers.RemoveAt(0);

            if (startingLine.Length != 3)
            {
                throw new Exception();
            }
            Method = startingLine[0];
            Uri    = new HttpUri(startingLine[1]);

            Fields = headers.Select(p => p.Split(new[] { ':' }, 2)).Where(f => f.Count() > 1).ToDictionary(f => f[0].Trim().ToLower(), f => f[1].Trim());

            Host = this["Host"].Split(new[] { ':' })[0];

            UserAgent = this["User-Agent"] ?? "";


            if (this["Connection"] != null)
            {
                KeepAlive = string.Equals(this["Connection"], "keep-alive", StringComparison.CurrentCultureIgnoreCase);
            }

            Authorization = new HttpAuthorization(this["Authorization"]);

            try
            {
                HttpRange = new HttpRange(this["Range"]);
            }
            catch
            {
                // ignored
            }
        }
Exemplo n.º 11
0
        private void GetAccesToken()
        {
            var login = new DropboxLogin(clientId, clientSecret, "https://oauthproxy.nemiro.net/", false, false);

            login.Owner = this;
            login.ShowDialog();

            if (login.IsSuccessfully)
            {
                Properties.Settings.Default.AccessToken = login.AccessTokenValue;
                Properties.Settings.Default.Save();
                this.Authorization = new HttpAuthorization(AuthorizationType.Bearer, login.AccessTokenValue);
                this.GetFiles();
            }
            else
            {
                MessageBox.Show("Error...");
            }
        }
Exemplo n.º 12
0
 /*private void GetFiles()
  * {
  *  OAuthUtility.PostAsync
  *  (
  *    "https://api.dropboxapi.com/2/files/list_folder",
  *    new HttpParameterCollection
  *    {
  * new
  * {
  *  path = this.CurrentPath,
  *  include_media_info = true
  * }
  *    },
  *    contentType: "application/json",
  *    authorization: this.Authorization,
  *    callback: this.GetFiles_Result
  *  );
  * }*/
 private void retrieve()
 {
     this.Authorization = new HttpAuthorization(AuthorizationType.Bearer, Properties.Settings.Default.AccessToken);
     OAuthUtility.PostAsync
     (
         "https://api.dropboxapi.com/2/files/list_folder",
         new HttpParameterCollection
     {
         new
         {
             path = this.CurrentPath,
             include_media_info = true
         }
     },
         contentType: "application/json",
         authorization: this.Authorization,
         callback: this.GetFiles_Result
     );
 }
Exemplo n.º 13
0
        private void GetAccessToken()
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action(GetAccessToken));
                return;
            }

            // create login form
            var login = new DropboxLogin("5nkunr8uscwfoba", "n7x9icfwoe6dehq")
            {
                Owner = this
            };

            // show login form
            login.ShowDialog();

            // authorization is success
            if (login.IsSuccessfully)
            {
                // save the access token to the application settings
                Properties.Settings.Default.AccessToken = login.AccessToken.Value;
                Properties.Settings.Default.Save();

                this.Authorization = new HttpAuthorization(AuthorizationType.Bearer, Properties.Settings.Default.AccessToken);

                // update the list of files
                this.UpdateList();
            }
            // is fails
            else
            {
                if (MessageBox.Show("Please Click OK to login on Dropbox or CANCEL for exit from the program.", "Warning", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.Cancel)
                {
                    this.Close();
                }
                else
                {
                    this.GetAccessToken();
                }
            }
        }
Exemplo n.º 14
0
        private void GetAccessToken()
        {
            var login = new YandexLogin("80bbde206ef74606bf239039bce82ed0", "123c7a7a69614d18a5d5e23397009bac", this.AlwaysNewToken);

            login.Owner = this;
            login.ShowDialog();

            if (login.IsSuccessfully)
            {
                Properties.Settings.Default.AccessToken = login.AccessToken.Value;
                Properties.Settings.Default.Save();

                this.Authorization = new HttpAuthorization(AuthorizationType.OAuth, Properties.Settings.Default.AccessToken);
                this.GetFiles();
            }
            else
            {
                MessageBox.Show("error...");
            }
        }
Exemplo n.º 15
0
        private void GetAccessToken()
        {
            var login = new DropboxLogin("zxz080y5wvs3sa2", "ca8txuupwy3y9d9");

            login.Owner = this;
            login.ShowDialog();

            if (login.IsSuccessfully)
            {
                Properties.Settings.Default.AccessToken = login.AccessTokenValue;
                Properties.Settings.Default.Save();

                this.Authorization = new HttpAuthorization(AuthorizationType.Bearer, login.AccessTokenValue);

                this.GetFiles();
            }
            else
            {
                MessageBox.Show("Oupsss... cannot login!");
            }
        }
Exemplo n.º 16
0
        private void GetAccessToken()
        {
            var login = new DropboxLogin("4mlpoeq657vuif8", "1whj6c5mxtkns7m");

            login.Owner = this;
            login.ShowDialog();

            if (login.IsSuccessfully)
            {
                Properties.Settings.Default.AccessToken = login.AccessTokenValue;
                Properties.Settings.Default.Save();

                this.Authorization = new HttpAuthorization(AuthorizationType.Bearer, login.AccessTokenValue);

                this.GetFiles();
            }
            else
            {
                MessageBox.Show("error...");
            }
        }
Exemplo n.º 17
0
        /*private void GetFiles()
         * {
         *  throw new NotImplementedException();
         * }*/

        private void GetAccessToken()
        {
            var login = new DropboxLogin("bayrht5hltabnbb", "q6xl6zyr9s61huh", "https://oauthproxy.nemiro.net/", false, false);

            login.Owner = this;
            login.ShowDialog();

            if (login.IsSuccessfully)
            {
                Properties.Settings.Default.AccessToken = login.AccessTokenValue;
                Properties.Settings.Default.Save();

                this.Authorization = new HttpAuthorization(AuthorizationType.Bearer, login.AccessTokenValue);

                //this.GetFiles();
            }
            else
            {
                MessageBox.Show("error...");
            }
        }
Exemplo n.º 18
0
 public HomeController(IDataService dataService, CookieManager cookieManager, HttpAuthorization httpAuthorization)
 {
     _cookieManager     = cookieManager;
     _httpAuthorization = httpAuthorization;
     _repository        = new ContactsRepository(dataService);
 }
Exemplo n.º 19
0
 public static void ExecuteRequestAsync(string method = "POST", string endpoint = null, HttpParameterCollection parameters = null, HttpAuthorization authorization = null, NameValueCollection headers = null, string contentType = null, AccessToken accessToken = null, ExecuteRequestAsyncCallback callback = null, bool allowWriteStreamBuffering = false, bool allowSendChunked = true, long contentLength = -1, HttpWriteRequestStream streamWriteCallback = null, int writeBufferSize = 4096, int readBufferSize = 4096, bool donotEncodeKeys = false)
 {
     new Thread((ThreadStart)(() =>
     {
         RequestResult result;
         try
         {
             result = OAuthUtility.ExecuteRequest(method, endpoint, parameters, authorization, headers, contentType, accessToken, allowWriteStreamBuffering, allowSendChunked, contentLength, streamWriteCallback, writeBufferSize, readBufferSize, donotEncodeKeys);
         }
         catch (RequestException ex)
         {
             result = ex.RequestResult;
         }
         if (callback == null)
         {
             return;
         }
         callback(result);
     }))
     {
         IsBackground = true
     }.Start();
 }
Exemplo n.º 20
0
 public WebApiCall(HttpLink link, HttpAuthorization authorization, WebApiCallBody body)
 {
     Link          = link;
     Authorization = authorization;
     Body          = body;
 }
Exemplo n.º 21
0
        /*private void upload_file_Click(object sender, EventArgs e)
         * {
         *  OpenFileDialog open = new OpenFileDialog();
         *  open.Filter = " Archivos|*.jpg;*.jpeg;*.png;*.pdf;*.doc;*.docx;*.xls;*.xlsx;*.ppt;*.pptx";
         *  open.Title = "Archivos";
         *  if (open.ShowDialog() == DialogResult.OK)
         *  {
         *      archivoText.Text = open.FileName;
         *  }
         *  open.Dispose();
         * }*/

        private void btnAceptar_Click(object sender, EventArgs e)
        {
            string          id_articulo;
            string          nombre_original;
            MySqlConnection conexion = new MySqlConnection();

            conexion.ConnectionString = "server=localhost; pasword=;" + "database=MASHUP_PROYECTO; User id= root; SslMode=none";
            conexion.Open();

            string          sql      = "select ID_CONTENIDO + 1 as id from registro_objetos order by ID_CONTENIDO desc limit 1";
            MySqlCommand    query    = new MySqlCommand(sql, conexion);
            MySqlDataReader myReader = query.ExecuteReader();

            myReader.Read();
            id_articulo = myReader["id"].ToString();
            conexion.Close();


            OpenFileDialog open = new OpenFileDialog();

            if (open.ShowDialog() != System.Windows.Forms.DialogResult.OK)
            {
                return;
            }
            //nombre_original = open.FileName;
            oldName   = Path.GetFileName(open.FileName);
            extension = Path.GetExtension(open.FileName);


            // send file

            newFile = open.FileName.Replace(oldName, id_articulo + extension);
            File.Copy(open.FileName, newFile, true);
            var fs = new FileStream(newFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            //renombrar archivo



            long   fileSize = fs.Length;
            string fileName = fs.Name;
            // get file length for progressbar

            var fileInfo = UniValue.Empty;

            fileInfo["path"] = (String.IsNullOrEmpty(this.CurrentPath) ? "/" : "") + Path.Combine(this.CurrentPath, Path.GetFileName(newFile)).Replace("\\", "/");
            //MessageBox.Show(fileInfo["path"].ToString());
            fileInfo["mode"]       = "add";
            fileInfo["autorename"] = true;
            fileInfo["mute"]       = false;
            this.Authorization     = new HttpAuthorization(AuthorizationType.Bearer, Properties.Settings.Default.AccessToken);

            OAuthUtility.PostAsync
            (
                "https://content.dropboxapi.com/2/files/upload",
                new HttpParameterCollection
            {
                { fs } // content of the file
            },
                headers: new NameValueCollection {
                { "Dropbox-API-Arg", fileInfo.ToString() }
            },
                contentType: "application/octet-stream",
                authorization: this.Authorization,
                // handler of result
                callback: this.Upload_Result
                // handler of uploading
                //streamWriteCallback: this.Upload_Processing
            );



            MySqlConnection conexion2 = new MySqlConnection();

            conexion2.ConnectionString = "server=localhost; pasword=;" + "database=MASHUP_PROYECTO; User id= root; SslMode=none";
            conexion2.Open();

            string sentencia = "INSERT INTO REGISTRO_OBJETOS(ID_TEMA,NOMBRE_OBJETO,FECHA,AUTOR,DESCRIPCION,CANTIDAD_MB,TIPO,Ext_Archivo,Nom_Origen)VALUES(@1,@2,@3,@4,@5,@6,@7,@8,@9)";

            MySqlCommand comando = new MySqlCommand(sentencia, conexion2);

            //comando.Parameters.AddWithValue("@1", txtcdarticulo.Text);
            comando.Parameters.AddWithValue("@1", txtctema.Text);
            comando.Parameters.AddWithValue("@2", txtnobjeto.Text);
            comando.Parameters.AddWithValue("@3", bunifuDatepicker1.Value.ToString());
            comando.Parameters.AddWithValue("@4", txtautor.Text);
            comando.Parameters.AddWithValue("@5", txtdescripcion.Text);
            comando.Parameters.AddWithValue("@6", fileSize / 1024);
            comando.Parameters.AddWithValue("@7", txttipo.Text);
            comando.Parameters.AddWithValue("@8", extension);
            comando.Parameters.AddWithValue("@9", oldName);
            comando.ExecuteNonQuery();
            conexion2.Close();
            //txtcdarticulo.Text = "";
            txtctema.Text          = "";
            txtnobjeto.Text        = "";
            bunifuDatepicker1.Text = "";
            txtautor.Text          = "";
            txtdescripcion.Text    = "";
            //archivoText.Text = "";
            txttipo.Text = "";
        }
Exemplo n.º 22
0
        private void bunifuCustomDataGrid1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            this.Authorization = new HttpAuthorization(AuthorizationType.Bearer, Properties.Settings.Default.AccessToken);

            DataGridView dvg = (DataGridView)sender;

            if (e.ColumnIndex == 9 && e.RowIndex != -1)
            {
                // Inicializar variables
                string id = (string)dvg["Codigo del articulo", e.RowIndex].Value.ToString();
                string ext;
                string file;
                int    id_int = Convert.ToInt32(id);

                //Conexión a la base de datos
                MySqlConnection conexion = new MySqlConnection();
                conexion.ConnectionString = "server=localhost; pasword=;" + "database=MASHUP_PROYECTO; User id= root; SslMode=none";
                conexion.Open();
                string          sql      = "select Ext_archivo,Nom_Origen from registro_objetos where ID_CONTENIDO = " + id;
                MySqlCommand    query    = new MySqlCommand(sql, conexion);
                MySqlDataReader myReader = query.ExecuteReader();
                myReader.Read();

                //construcción del nombre del archivo a descargar
                ext  = myReader["Ext_Archivo"].ToString();
                file = id + ext;



                SaveFileDialog save = new SaveFileDialog();
                //this.save.FileName = Path.GetFileName(file["path_display"].ToString());
                save.FileName = myReader["Nom_Origen"].ToString();
                conexion.Close();
                if (save.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                {
                    return;
                }
                string path2 = save.FileName;

                // token = Properties.Settings.Default.AccessToken

                /*var dbx = new DropboxClient(Properties.Settings.Default.AccessToken);
                 *
                 *
                 * using (var response = dbx.Files.DownloadAsync("/8.gif"))
                 * {
                 *  (await response.getGetContentAsStreamAsync()).CopyTo(fileStream);
                 * }
                 * MessageBox.Show(response.);*/
                this.DownloadFileStream = new FileStream(save.FileName, FileMode.Create, FileAccess.Write);
                this.DownloadWriter     = new BinaryWriter(this.DownloadFileStream);


                var req = WebRequest.Create("https://content.dropboxapi.com/2/files/download");
                req.Method = "POST";

                req.Headers.Add(HttpRequestHeader.Authorization, this.Authorization.ToString());
                req.Headers.Add("Dropbox-API-Arg", UniValue.Create(new { path = "/" + file }).ToString());

                req.BeginGetResponse(result =>
                {
                    var resp = req.EndGetResponse(result);

                    // get response stream
                    this.DownloadReader = resp.GetResponseStream();

                    // read async
                    this.DownloadReader.BeginRead(this.DownloadReadBuffer, 0, this.DownloadReadBuffer.Length, this.DownloadReadCallback, null);
                }, null);

                //MessageBox.Show((e.RowIndex+1).ToString() + " Row clicked");
            }
        }