Example #1
0
        public Client(IHttpClientFactory clientFactory, IRequestGenerator requestGenerator, Options options)
        {
            _options = options;
            IRequestExecuter requestExecuter = new RequestExecuter(
                clientFactory.CreateHttpClient(new HttpClientOptions
                    {
                        AddTokenToRequests = true,
                        TokenRetriever = () => _options.AccessToken,
                        ReadRequestsPerSecond = options.ReadRequestsPerSecond,
                        WriteRequestsPerSecond = options.WriteRequestsPerSecond,
                    }),
                clientFactory.CreateHttpClient(new HttpClientOptions()));

            if (options.AutoRetry)
            {
                requestExecuter = new AutoRetryRequestExecuter(requestExecuter)
                    {
                        NumberOfRetries = options.NumberOfRetries
                    };
            }

            RequestGenerator = requestGenerator;

            Core = new Core(requestExecuter, requestGenerator.Core, options);
            Business = new Business(requestExecuter, requestGenerator, options);
        }
Example #2
0
        private Client GetClient()
        {
            if (string.IsNullOrWhiteSpace(this._sessionService.DropboxAccessToken))
                return null;

            var options = new Options
            {
                ClientId = this._settings.DropboxClientId,
                ClientSecret = this._settings.DropboxClientSecret,
                AccessToken = this._sessionService.DropboxAccessToken,
            };

            return new Client(new SavvyHttpClientFactory(), new RequestGenerator(), options);
        }
        private static void RegisterTypes(IUnityContainer container)
        {
            var appSettings = ConfigurationManager.AppSettings;

            var options = new Options
            {
                ClientId = appSettings["ClientId"],
                ClientSecret = appSettings["ClientSecret"],
                RedirectUri = appSettings["RedirectUri"],
               // AccessToken = appSettings["AccessToken"]
            };

            container.RegisterType<IDropboxService, DropboxService>();
            container.RegisterType<IClient, Client>(new InjectionConstructor(options));
        }
Example #4
0
        public DropboxConnector(string clientId, string clientSecret, IUserTokenRepository repository)
        {
            if (repository == null) throw new ArgumentNullException("repository");

            _repository = repository;

            var token = _repository.TryRetrieveTokenFromDatabase(HardcodedUser.Id);

            _accessToken = token.DropboxAccessToken;

            var options = new Options
            {
                ClientId = clientId,
                ClientSecret = clientSecret,
                RedirectUri = "http://localhost:52110/dropbox/oauth",
                UseSandbox = true,
                AccessToken = _accessToken
            };

            _client = new Client(options);
        }
Example #5
0
 public Client(Options options)
     : this(new HttpClientFactory(), new RequestGenerator(), options)
 {
 }
Example #6
0
        public async Task<ActionResult> Index()
        {
                //initialize dropbox auth options
            var options = new Options
            {
                ClientId = "rnizd2wt4vhv4cn",
                ClientSecret = "k8exfknbce45n5g",
                RedirectUri = "https://fedup.azurewebsites.net/Incident"
                //RedirectUri = "http://localhost:49668/Incident"
            };

                // Initialize a new Client (without an AccessToken)
            var dropboxClient = new Client(options);

                // Get the OAuth Request Url
            var authRequestUrl = await dropboxClient.Core.OAuth2.AuthorizeAsync("code");

            if (Request.QueryString["code"] == null)
            {
                    // Navigate to authRequestUrl using the browser, and retrieve the Authorization Code from the response
                Response.Redirect(authRequestUrl.ToString());
            }
                //get authcode from querstring param
            var authCode = Request.QueryString["code"];

            // Exchange the Authorization Code with Access/Refresh tokens
            var token = await dropboxClient.Core.OAuth2.TokenAsync(authCode);

            // Get account info
            var accountInfo = await dropboxClient.Core.Accounts.AccountInfoAsync();
            Console.WriteLine("Uid: " + accountInfo.uid);
            Console.WriteLine("Display_name: " + accountInfo.display_name);
            Console.WriteLine("Email: " + accountInfo.email);

            // Get root folder without content
            var rootFolder = await dropboxClient.Core.Metadata.MetadataAsync("/", list: false);
            Console.WriteLine("Root Folder: {0} (Id: {1})", rootFolder.Name, rootFolder.path);

            // Get root folder with content
            rootFolder = await dropboxClient.Core.Metadata.MetadataAsync("/", list: true);
            foreach (var folder in rootFolder.contents)
            {
                Console.WriteLine(" -> {0}: {1} (Id: {2})",
                    folder.is_dir ? "Folder" : "File", folder.Name, folder.path);
            }

            // Initialize a new Client (with an AccessToken)
            var client2 = new Client(options);

            // Find a file in the root folder
            var file = rootFolder.contents.FirstOrDefault(x => x.is_dir == false);
            var files = rootFolder.contents.ToList();

            // Download a file
            
            foreach (var item in files)
            {
                var tempFile = Path.GetTempFileName();
                if (item.path.Substring(item.path.Length - 4) == ".mp3")
                {
                    using (var fileStream = System.IO.File.OpenWrite(tempFile))
                    {

                        await client2.Core.Metadata.FilesAsync(item.path, fileStream);

                        fileStream.Flush();
                        fileStream.Close();
                    }

                    int length = item.path.Length;
                    string destination = item.path.Substring(0, length - 4) + ".mp3";
                    destination = AppDomain.CurrentDomain.BaseDirectory + destination.Substring(1);
                    System.IO.File.Copy(tempFile, destination, true);
                }
            }


            List<incident> Incidents = new List<incident>();

            IFirebaseConfig config = new FirebaseConfig
            {
                AuthSecret = "0dwRwB8V2QmJTM9NbKtWfqlys91LwZguvE67oS1f",
                BasePath = "https://fedup.firebaseio.com/"
            };

                //initialize new firebase client
            IFirebaseClient client = new FirebaseClient(config);

            bool hasNext = true;
            int counter = 1;
            do
            {
                try
                {
                    //pull current row
                    FirebaseResponse response = await client.GetAsync(counter.ToString());

                    //parse our json object
                    incident jsonObject = JsonConvert.DeserializeObject<incident>(response.Body);

                    System.DateTime dtDateTime = new DateTime(1970,1,1,0,0,0,0,System.DateTimeKind.Utc);
                    dtDateTime = dtDateTime.AddSeconds(jsonObject.timestamp).ToLocalTime();

                    jsonObject.newTimeStamp = dtDateTime;

                    Incidents.Add(jsonObject);
                }
                catch
                {
                    hasNext = false;
                    break;
                }
                counter++;
            }
            while (hasNext);

            ViewBag.Incidents = Incidents;

            return View();
        }
Example #7
0
        public ActionResult UpdateSpreadsheet()
        {
            var success = false;
            var message = "";
            try {
                // Get necessary settings
                var dropboxToken = Service.UserSettings.GetByUserKey(BaseUserSettingService.SettingKeys.DropboxToken, GetCurrentUserGuid());
                if (dropboxToken == null) {
                    throw new Exception("Dropbox is not connected. Cannot update spreadsheet. Check your dropbox settings anad make sure you are connected.");
                }
                var dbPath = Service.UserSettings.GetByUserKey(BaseUserSettingService.SettingKeys.DropboxPath, GetCurrentUserGuid());
                var dbFile = Service.UserSettings.GetByUserKey(BaseUserSettingService.SettingKeys.DropboxFile, GetCurrentUserGuid());
                if (dbPath == null || dbFile == null) {
                    throw new Exception("Dropbox is not setup. Cannot update spreadsheet. Check your dropbox settings anad make sure you are connected.");
                }

                // Get the transactions
                var logins = BankDataService.Logins.GetHouseholdLoginIds(GetHouseholdIdForCurrentUser());
                var transactions = BankDataService.Transactions.GetThisMonthsTransactions(logins);

                // Get the xls file
                var options = new Options();
                options.AccessToken = dropboxToken.SettingValue;
                var client = new Client(options);

                byte[] budgetFile;
                var results = client.Core.Metadata.SearchAsync(dbPath.SettingValue, dbFile.SettingValue).Result;
                foreach (var searchResult in results) {
                    budgetFile = new byte[searchResult.bytes];
                    using (var stream = new MemoryStream()) {
                        client.Core.Metadata.FilesAsync(searchResult.path, stream).Wait();
                        budgetFile = stream.ToArray();
                    }

                    budgetFile = WorkingBudgetUpdater.Update(budgetFile, transactions);

                    // Replace file after update
                    using (var stream = new MemoryStream(budgetFile)) {
                        client.Core.Metadata.FilesPutAsync(stream, Path.Combine(dbPath.SettingValue, dbFile.SettingValue)).Wait();
                    }
                    break;
                }

                success = true;
                message = "Spreadsheet Update was successful";
            } catch (Exception ex) {
                message = ex.Message;
            }

            return PartialView("CallbackStatus", new CallbackStatusViewModel() {
                Success = success,
                Message = message
            });
        }
Example #8
0
        private static async Task Run()
        {
            var options = new Options
                {
                    ClientId = "...",
                    ClientSecret = "...",
                    RedirectUri = "..."
                };

            // Initialize a new Client (without an AccessToken)
            var client = new Client(options);

            // Get the OAuth Request Url
            var authRequestUrl = await client.Core.OAuth2.AuthorizeAsync("code");

            // TODO: Navigate to authRequestUrl using the browser, and retrieve the Authorization Code from the response
            var authCode = "...";

            // Exchange the Authorization Code with Access/Refresh tokens
            var token = await client.Core.OAuth2.TokenAsync(authCode);

            // Get account info
            var accountInfo = await client.Core.Accounts.AccountInfoAsync();
            Console.WriteLine("Uid: " + accountInfo.uid);
            Console.WriteLine("Display_name: " + accountInfo.display_name);
            Console.WriteLine("Email: " + accountInfo.email);

            // Get root folder without content
            var rootFolder = await client.Core.Metadata.MetadataAsync("/", list: false);
            Console.WriteLine("Root Folder: {0} (Id: {1})", rootFolder.Name, rootFolder.path);

            // Get root folder with content
            rootFolder = await client.Core.Metadata.MetadataAsync("/", list: true);
            foreach (var folder in rootFolder.contents)
            {
                Console.WriteLine(" -> {0}: {1} (Id: {2})", 
                    folder.is_dir ? "Folder" : "File", folder.Name, folder.path);
            }

            // Initialize a new Client (with an AccessToken)
            var client2 = new Client(options);

            // Create a new folder
            var newFolder = await client2.Core.FileOperations.CreateFolderAsync("/New Folder");

            // Find a file in the root folder
            var file = rootFolder.contents.FirstOrDefault(x => x.is_dir == false);

            // Download a file
            var tempFile = Path.GetTempFileName();
            using (var fileStream = System.IO.File.OpenWrite(tempFile))
            {
                await client2.Core.Metadata.FilesAsync(file.path, fileStream);
            }

            //Upload the downloaded file to the new folder

            using (var fileStream = System.IO.File.OpenRead(tempFile))
            {
                var uploadedFile =await client2.Core.Metadata.FilesPutAsync(fileStream, newFolder.path + "/" + file.Name);
            }

            // Search file based on name
            var searchResults = await client2.Core.Metadata.SearchAsync("/", file.Name);
            foreach (var searchResult in searchResults)
            {
                Console.WriteLine("Found: " + searchResult.path);
            }
        }
Example #9
0
        private async Task<bool> TestAccessToken(string accessToken)
        {
            var options = new Options
            {
                AccessToken = accessToken,
                ClientId = this._settings.DropboxClientId,
                ClientSecret = this._settings.DropboxClientSecret,
            };

            var client = new Client(new SavvyHttpClientFactory(), new RequestGenerator(),  options);

            try
            {
                await client.Core.Accounts.AccountInfoAsync();
                return true;
            }
            // ReSharper disable once CatchAllClause
            catch
            {
                return false;
            }
        }
Example #10
0
        /// <summary>
        /// Creates a new dropbox client.
        /// </summary>
        private Client GetClient()
        {
            var options = new Options
            {
                ClientId = this._settings.DropboxClientId,
                ClientSecret = this._settings.DropboxClientSecret,
                RedirectUri = this._settings.RedirectUrl.ToString(),

            };

            return new Client(new SavvyHttpClientFactory(), new RequestGenerator(), options);
        }