示例#1
0
        private DropNetClient GetClient(StorageCredentials credentials)
        {
            var client = new DropNetClient(credentials.Key, credentials.Secret);

            client.GetAccessToken();
            return(client);
        }
示例#2
0
        public void Autorize(Action afterAction = null)
        {
            var redirectUri = "http://localhost:8080/";
            Process.Start(_client.BuildAuthorizeUrl(OAuth2AuthorizationFlow.Code, redirectUri));
            var http = new HttpListener { Prefixes = { redirectUri } };
            http.Start();
            http.BeginGetContext(result => {
                var context = http.EndGetContext(result);
                var response =
                    Encoding.UTF8.GetBytes(
                        "<script>window.onload=function(){open('http://dropbox.com', '_self');};</script>");
                context.Response.ContentLength64 = response.Length;
                context.Response.OutputStream.Write(response, 0, response.Length);
                context.Response.OutputStream.Flush();
                var ul = _client.GetAccessToken(context.Request.QueryString["code"], redirectUri);

                http.Stop();
                http.Close();

                _registyKey.SetValue(RegistryKey, ul.Token);
                _client.UserLogin = ul;
                _isAutorized = true;
                if (afterAction != null)
                    afterAction();
            }, null);
        }
        public string SaveAttachment(AttachmentRequest request)
        {
            try
            {
                DropNetClient _client = new DropNetClient(AppConstants.DropboxClientId, AppConstants.DropboxClientSecret);


                _client.UserLogin = Storage.Dropbox.Token;

                DropNet.Models.UserLogin login = _client.GetAccessToken();



                Attachment attachment = AppUtility.GetAttachment(request.AttachmentId, request.AuthToken, request.EwsUrl);

                _client.UploadFile("/", attachment.AttachmentName, attachment.AttachmentBytes);
                return("Uploaded Sucessfully.");
            }
            catch (Exception s)
            {
                return(s.Message);
            }

            //return "";
        }
示例#4
0
        public static void Main()
        {
            var client = new DropNetClient(DropboxAppKey, DropboxAppSecret);

            var token = client.GetToken();
            var url   = client.BuildAuthorizeUrl();

            Console.WriteLine("COPY?PASTE Link: {0}", url);
            Console.WriteLine("Press enter when clicked allow");
            Process.Start(@"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe", url);

            Console.ReadLine();
            var accessToken = client.GetAccessToken();

            client.UseSandbox = true;
            var metaData = client.CreateFolder("NewUpload" + DateTime.Now.ToString());

            string[] dir = Directory.GetFiles("../../images/", "*.JPG");
            foreach (var item in dir)
            {
                Console.WriteLine("Reading file.....");
                FileStream stream = File.Open(item, FileMode.Open);
                var        bytes  = new byte[stream.Length];
                stream.Read(bytes, 0, (int)stream.Length);
                Console.WriteLine(bytes.Length + " bytes uploading...");
                client.UploadFile("/" + metaData.Name.ToString(), item.Substring(6), bytes);
                Console.WriteLine("{0} uploaded!", item);

                stream.Close();
            }
            Console.WriteLine("Job Done!");
            var picUrl = client.GetShare(metaData.Path);

            Process.Start(@"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe", picUrl.Url);
        }
示例#5
0
        public void GetAccessToken()
        {
            var userLogin = _dropBoxClient.GetAccessToken();

            ApiSecret   = userLogin.Secret;
            AccessToken = userLogin.Token;
        }
示例#6
0
        static void Main(string[] args)
        {
            Console.WriteLine("You must first login in your dropbox account.");

            string        currentDir = Directory.GetCurrentDirectory();
            DirectoryInfo info       = new DirectoryInfo(currentDir).Parent.Parent;

            FileInfo[] pictures = info.GetFiles("*.jpg");

            List <int> indexesOfChosen = new List <int>();

            PrintAndChoosePictures(pictures, indexesOfChosen);

            DropNetClient client = new DropNetClient("8lc93q5ybq85syv", "nt6wrs7m0maixnl");

            var token = client.GetToken();
            var url   = client.BuildAuthorizeUrl();

            Clipboard.SetText(url);

            Console.WriteLine("\n\nUrl copied to clipboard. Paste in browser and allow.\nPress any key to continue", url);
            Console.ReadKey(true);

            var accessToken = client.GetAccessToken();

            client.UserLogin.Secret = accessToken.Secret;
            client.UserLogin.Token  = accessToken.Token;

            client.UseSandbox = true;


            Console.Write("Enter album name: ");
            var albumName = Console.ReadLine();

            var folder = client.CreateFolder(albumName);

            Console.WriteLine("\nUploading...\n");

            foreach (var i in indexesOfChosen)
            {
                MemoryStream sr = new MemoryStream((int)pictures[i].Length);
                FileStream   fs = File.Open(pictures[i].FullName, FileMode.Open);

                var bytes = new byte[fs.Length];

                fs.Read(bytes, 0, Convert.ToInt32(fs.Length));

                client.UploadFile(folder.Path, pictures[i].Name, bytes);

                fs.Close();
            }

            var shareUrl = client.GetShare(folder.Path);

            Clipboard.SetText(shareUrl.Url);

            Console.WriteLine(shareUrl.Url);
            Console.WriteLine("Share Url is also in clipboard");
        }
        public string SendResponse(HttpListenerRequest request)
        {
            var accessToken = _client.GetAccessToken();

            Application.Current.Dispatcher.Invoke(new Action(() => ((Window)ServiceProvider.PluginManager.SelectedWindow).Activate()));
            Secret      = accessToken.Secret;
            AccessToken = accessToken.Token;

            return("<HTML><BODY>OK</br><h3>Logis succeed. Please return to digiCamControl</br><a href=\"javascript:window.open('','_self').close();\">close</a></BODY></HTML>");
        }
示例#8
0
    public Dictionary <string, string> GetAccessToken(string tok, string secret)
    {
        _client = new DropNetClient("token", "secret", tok, secret);
        var token = _client.GetAccessToken();
        var dic   = new Dictionary <string, string> {
            { "token", token.Token }, { "secret", token.Secret }
        };

        return(dic);
    }
示例#9
0
        public async Task Get_Access_Token_Test()
        {
            var client = new DropNetClient(AppKey, AppSecret);

            var userToken = await client.GetRequestToken();

            //Open the url in browser and login
            string url  = client.BuildAuthorizeUrl(userToken, "http://cloudyboxapp.com");
            var    user = await client.GetAccessToken();

            Assert.NotNull(user);
        }
示例#10
0
        /// <summary>
        /// Use a breakpoint to set-up a connection to your DropBox app and follow the described
        /// steps
        /// </summary>
        public void SetUp()
        {
            _dropBoxClient.GetToken();

            // copy URL into the browser and log into dropbox
            var url = _dropBoxClient.BuildAuthorizeUrl();

            // save token information into the config
            var token = _dropBoxClient.GetAccessToken();

            _dropBoxClient.UserLogin = token;
        }
示例#11
0
        public async Task Authenticate(UserLogin storedRequestToken)
        {
            //var storedRequestToken = await LoadObject<UserLogin>(TokenKind.Request);
            dropnet.SetUserToken(storedRequestToken);
            accessToken = await dropnet.GetAccessToken();

            Debug.WriteLine(accessToken.Secret);
            Debug.WriteLine(accessToken.Token);
            await SaveObject(TokenKind.Access, accessToken);

            SignIn();
        }
示例#12
0
 public bool CheckLogin(BrowserStatus status)
 {
     if (status.Url.OriginalString.StartsWith("http://localhost"))
     {
         if (status.Url.OriginalString.Contains("oauth_token"))
         {
             AccessToken = _client.GetAccessToken();
         }
         return(true);
     }
     return(false);
 }
示例#13
0
        public static void Main()
        {
            var client = new DropNetClient(apiKey, apiSecret);

            client.GetToken();
            var url = client.BuildAuthorizeUrl();

            Console.WriteLine("Open \"{0}\" in browser.", url);
            Console.WriteLine("Press [Enter] when you click on [Allow]");
            OpenBrowser(url);

            Console.ReadLine();
            client.GetAccessToken();

            client.UseSandbox = true;
            var metaData = client.CreateFolder("HW-Pictures - " + date);

            string[] dir = Directory.GetFiles("../../images/", "*.jpg");
            foreach (var file in dir)
            {
                Console.Write("Uploading");
                while (true)
                {
                    FileStream stream = File.Open(file, FileMode.Open);
                    var        bytes  = new byte[stream.Length];
                    stream.Read(bytes, 0, (int)stream.Length);

                    client.UploadFile("/" + metaData.Name, file.Substring(6), bytes);

                    for (var i = 0; i < 10; i++)
                    {
                        Console.Write(".");
                        Thread.Sleep(300);
                    }

                    stream.Close();

                    Console.WriteLine();
                    break;
                }
            }

            Console.WriteLine("Done!");
            var pictureUrl = client.GetShare(metaData.Path);

            OpenBrowser(pictureUrl.Url);
        }
示例#14
0
        /// <summary>
        /// Constructor to make calls to Dropbox. After authorization the access is not yet granted to the user. Granting is also
        /// done in this constructor.
        /// </summary>
        /// <param name="token">Authentication token or access token</param>
        /// <param name="isAccessToken">Indicate whether the token is the authentication token or the access token</param>
        public Dropbox(UserLogin token, bool isAccessToken = false)
        {
            string apiKey = ConfigurationManager.AppSettings["dropboxApiKey"], appSecret = ConfigurationManager.AppSettings["dropboxAppSecret"];
            _dropboxClient = new DropNetClient(apiKey, appSecret, token.Token, token.Secret);

            _isAccessToken = isAccessToken;

            if (!isAccessToken)
            {
                Token = _dropboxClient.GetAccessToken();
                _dropboxClient = new DropNetClient(apiKey, appSecret, Token.Token, Token.Secret);
                _isAccessToken = true;
            }

            // Force the root directory to Apps/ExactDocumentUploader
            _dropboxClient.UseSandbox = true;
        }
示例#15
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.Params["dropboxcallback"] == "1")
            {
                //Its a callback from dropbox!
                if (Session["DropNetUserLogin"] != null)
                {
                    _client.UserLogin           = Session["DropNetUserLogin"] as DropNet.Models.UserLogin;
                    Session["DropNetUserLogin"] = _client.GetAccessToken();

                    var accountinfo = _client.Account_Info();
                    litOutput.Text = accountinfo.quota_info.quota.ToString();
                }
                else
                {
                    litOutput.Text = "Session expired...";
                }
            }
        }
示例#16
0
        public DropStorage(Action <string> webViewCallback)
        {
            _webViewCallback = webViewCallback;

            _client = new DropNetClient(DROPBOX_APP_KEY, DROPBOX_APP_SECRET);

            //Get Request Token
            _client.GetToken();

            var authUri = _client.BuildAuthorizeUrl();

            //Process.Start(authUri);
            _webViewCallback(authUri);

            //don't need it, web view callback is blocking
            //var dlg = new AuthDlg(StorageType.Dropbox);
            //dlg.ShowDialog();

            _accessToken = _client.GetAccessToken(); //Store this token for "remember me" function
        }
示例#17
0
 public Task <Tokens> Create(string url)
 {
     return(Task.Run(() =>
     {
         var accessToken = _client.GetAccessToken();
         _client.UserLogin = accessToken;
         return new Tokens {
             AccessToken = accessToken.Token, Token = accessToken.Secret
         };
     }));
     //// step 3
     //_client.GetAccessTokenAsync((accessToken) =>
     //{
     //    //Store this token for "remember me" function
     //},
     //(error) =>
     //{
     //    //Handle error
     //});
 }
示例#18
0
        protected void Page_Load(object sender, EventArgs e)
        {
            get_totals();

            DropNetClient _client = new DropNetClient(_settings.dropbox_api_key(), _settings.dropbox_api_secret());

            permissions();

            if (Session["request_token"] != null)
            {
                Event ev = _events.@select(Convert.ToInt32(Session["dropbox_event_id"] as string));

                _client.UserLogin = Session["request_token"] as DropNet.Models.UserLogin;

                var access_token = _client.GetAccessToken();

                var account_info = _client.AccountInfo();

                ev.request_token    = access_token.Token.ToString();
                ev.access_token     = access_token.Secret.ToString();
                ev.dropbox_country  = account_info.country;
                ev.dropbox_email    = account_info.email;
                ev.dropbox_quota    = account_info.quota_info.quota.ToString();
                ev.dropbox_referral = account_info.referral_link;
                ev.dropbox_uid      = account_info.uid;
                ev.dropbox_username = account_info.display_name;

                ev = _events.update(ev);

                username.Attributes.Add("placeholder", account_info.display_name);
                email.Attributes.Add("placeholder", ev.dropbox_email);
                quota.Attributes.Add("placeholder", ev.dropbox_quota);
                referral.Attributes.Add("placeholder", ev.dropbox_referral);
                uid.Attributes.Add("placeholder", ev.dropbox_uid.ToString());
                country.Attributes.Add("placeholder", ev.dropbox_country);
            }
            else
            {
                Response.Redirect("/events");
            }
        }
示例#19
0
 public ActionResult ConnectCallBack()
 {
     try
     {
         dropNetClient.UserLogin = UserLoginInfo;
         var dropboxAccessToken = dropNetClient.GetAccessToken();
         var accountInfo        = dropNetClient.AccountInfo();
         CurrentUser.DropboxAccount = new DropboxAccount
         {
             ConnectingDate = DateTime.UtcNow,
             Enabled        = true,
             UserSecret     = dropboxAccessToken.Secret,
             UserToken      = dropboxAccessToken.Token,
             AccountName    = accountInfo.display_name
         };
         UnitOfWork.Commit();
     }
     catch
     {
         ModelState.AddModelError("", "Can't connect to DropBox.");
     }
     return(RedirectToAction <UserController>(c => c.Index()));
 }
示例#20
0
        public void RegisterAccount(int tempCredentialId)
        {
            AuthCredential partialCredential = this.repoAuthCredential.GetById(tempCredentialId);

            try
            {
                UserLogin lg = new UserLogin {
                    Token = partialCredential.Token, Secret = partialCredential.Secret
                };
                DropNetClient client = new DropNetClient(MogConstants.DROPBOX_KEY, MogConstants.DROPBOX_SECRET);
                client.UserLogin = lg;
                UserLogin accessToken = client.GetAccessToken();

                partialCredential.Token  = accessToken.Token;
                partialCredential.Secret = accessToken.Secret;
                partialCredential.Status = CredentialStatus.Approved;
                this.repoAuthCredential.SaveChanges(partialCredential);
            }
            catch (DropNet.Exceptions.DropboxException exc)
            {//
                this.repoAuthCredential.Delete(partialCredential);
                throw new Exception("failed to register accoutn", exc);
            }
        }
        public ActionResult AuthCallback(string uid, string oauth_token, string redirectUrl)
        {
            if (string.IsNullOrEmpty(uid) || string.IsNullOrEmpty(oauth_token))
            {
                return(new HttpUnauthorizedResult());
            }

            try {
                var settings  = _orchard.WorkContext.CurrentSite.As <DropboxSettingsPart>();
                var userLogin = _httpContext.Current().Session["DropnetUserLogin"] as UserLogin;

                var client = new DropNetClient(settings.ApiKey, settings.ApiSecret,
                                               userLogin.Token, userLogin.Secret);
                _httpContext.Current().Session["DropnetUserLogin"] = client.GetAccessToken();
                var userSettings = _orchard.WorkContext.CurrentUser.As <DropboxUserSettingsPart>();
                userSettings.UserToken  = client.UserLogin.Token;
                userSettings.UserSecret = client.UserLogin.Secret;
                return(View());
            }
            catch (DropboxException dbe) {
                Logger.Error(dbe, "Authorise");
                return(View("Index_SetupApi"));
            }
        }
示例#22
0
        static public void syncAcc(bool resync)
        {
            //Testing Connection

            try
            {
                Ping pSender = new Ping();

                PingReply pResult = pSender.Send("8.8.8.8");

                if (pResult.Status == IPStatus.Success)
                {
                    Console.WriteLine("Internet available");
                }
                else
                {
                    Exception exc = new Exception("no internetconnection");

                    throw exc;
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Please make sure your connection to the internet is available");
                return;
            }



            DropNetClient dbClient = new DropNetClient(Program.Config.AppKey, Program.Config.AppSecret);

#if DEBUG
            dbClient.UseSandbox = true;
#endif

            if (String.IsNullOrEmpty(Properties.Settings.Default.DropBoxUserToken) || resync)
            {
                try
                {
                    dbClient.GetToken();
                }
                catch (Exception)
                {
                    throw;
                }


                var url = dbClient.BuildAuthorizeUrl();

                Browser_frm browser = new Browser_frm(url);
                browser.ShowDialog();

                try
                {
                    var accessToken = dbClient.GetAccessToken();

                    MessageBox.Show(accessToken.Token);

                    Properties.Settings.Default.DropBoxUserSecret = accessToken.Secret;
                    Properties.Settings.Default.DropBoxUserToken  = accessToken.Token;
                    Properties.Settings.Default.Save();
                    MessageBox.Show("Login Saved");
                }
                catch (Exception)
                {
                    throw;
                }
            }
            else
            {
                MessageBox.Show("already synchronized");
            }
        }
        public async Task <UserLogin> VerifiedUserPermission()
        {
            var userLogin = await _client.GetAccessToken();

            return(userLogin);
        }