/// <summary> /// Do the actual upload to OneDrive /// </summary> /// <param name="oAuth2Settings">OAuth2Settings</param> /// <param name="surfaceToUpload">ISurface to upload</param> /// <param name="progress">IProgress</param> /// <param name="token">CancellationToken</param> /// <returns>OneDriveUploadResponse with details</returns> private async Task <OneDriveUploadResponse> UploadToOneDriveAsync(OAuth2Settings oAuth2Settings, ISurface surfaceToUpload, IProgress <int> progress = null, CancellationToken token = default) { var filename = surfaceToUpload.GenerateFilename(CoreConfiguration, _oneDriveConfiguration); var uploadUri = OneDriveUri.AppendSegments("root:", "Screenshots", filename + ":", "content"); var localBehaviour = _oneDriveHttpBehaviour.ShallowClone(); if (progress != null) { localBehaviour.UploadProgress = percent => { UiContext.RunOn(() => progress.Report((int)(percent * 100)), token); }; } var oauthHttpBehaviour = OAuth2HttpBehaviourFactory.Create(oAuth2Settings, localBehaviour); using (var imageStream = new MemoryStream()) { surfaceToUpload.WriteToStream(imageStream, CoreConfiguration, _oneDriveConfiguration); imageStream.Position = 0; using (var content = new StreamContent(imageStream)) { content.Headers.Add("Content-Type", surfaceToUpload.GenerateMimeType(CoreConfiguration, _oneDriveConfiguration)); oauthHttpBehaviour.MakeCurrent(); return(await uploadUri.PutAsync <OneDriveUploadResponse>(content, token)); } } }
public async Task TestRunOn() { var taskSchedulerId = TaskScheduler.Current.Id; Log.Info().WriteLine("Current id: {0}", taskSchedulerId); UiContext.Initialize(); var window = new Window { Width = 200, Height = 200 }; window.Show(); // Should not throw anything window.Focus(); // Make sure the current task scheduler is not for the UI thread await Task.Delay(10).ConfigureAwait(false); // Should throw Assert.Throws <InvalidOperationException>(() => window.Focus()); // This should also not throw anything await UiContext.RunOn(() => { var taskSchedulerIdInside = TaskScheduler.Current.Id; Log.Info().WriteLine("Current id inside: {0}", taskSchedulerIdInside); Assert.NotEqual(taskSchedulerId, taskSchedulerIdInside); window.Close(); }); }
/// <summary> /// Do the actual upload to OneDrive /// </summary> /// <param name="oAuth2Settings">OAuth2Settings</param> /// <param name="surfaceToUpload">ISurface to upload</param> /// <param name="outputSettings">OutputSettings for the image file format</param> /// <param name="title">Title</param> /// <param name="filename">Filename</param> /// <param name="progress">IProgress</param> /// <param name="token">CancellationToken</param> /// <returns>ImgurInfo with details</returns> public static async Task <OneDriveUploadResponse> UploadToOneDriveAsync(OAuth2Settings oAuth2Settings, ISurface surfaceToUpload, SurfaceOutputSettings outputSettings, string title, string filename, IProgress <int> progress = null, CancellationToken token = default) { var uploadUri = new Uri(UrlUtils.GetUploadUrl(filename)); var localBehaviour = Behaviour.ShallowClone(); if (progress != null) { localBehaviour.UploadProgress = percent => { UiContext.RunOn(() => progress.Report((int)(percent * 100)), token); }; } var oauthHttpBehaviour = OAuth2HttpBehaviourFactory.Create(oAuth2Settings, localBehaviour); using (var imageStream = new MemoryStream()) { ImageOutput.SaveToStream(surfaceToUpload, imageStream, outputSettings); imageStream.Position = 0; using (var content = new StreamContent(imageStream)) { content.Headers.Add("Content-Type", "image/" + outputSettings.Format); oauthHttpBehaviour.MakeCurrent(); return(await uploadUri.PostAsync <OneDriveUploadResponse>(content, token)); } } }
/// <summary> /// Upload the HttpContent to dropbox /// </summary> /// <param name="filename">Name of the file</param> /// <param name="content">HttpContent</param> /// <param name="progress">IProgress</param> /// <param name="cancellationToken">CancellationToken</param> /// <returns>Url as string</returns> private async Task <string> UploadAsync(string filename, HttpContent content, IProgress <int> progress = null, CancellationToken cancellationToken = default(CancellationToken)) { var oAuthHttpBehaviour = _oAuthHttpBehaviour.ShallowClone(); // Use UploadProgress if (progress != null) { oAuthHttpBehaviour.UploadProgress = percent => { UiContext.RunOn(() => progress.Report((int)(percent * 100))); }; } oAuthHttpBehaviour.MakeCurrent(); // Build the upload content together var uploadContent = new Upload { Content = content }; // This is needed if (!filename.StartsWith("/")) { filename = "/" + filename; } // Create the upload request parameters var parameters = new UploadRequest { Path = filename }; // Add it to the headers uploadContent.Headers.Add("Dropbox-API-Arg", JsonConvert.SerializeObject(parameters, Formatting.None)); _oAuthHttpBehaviour.MakeCurrent(); // Post everything, and return the upload reply or an error var response = await DropboxContentUri.PostAsync <HttpResponse <UploadReply, Error> >(uploadContent, cancellationToken).ConfigureAwait(false); if (response.HasError) { throw new ApplicationException(response.ErrorResponse.Summary); } // Take the response from the upload, and use the information to request dropbox to create a link var createLinkRequest = new CreateLinkRequest { Path = response.Response.PathDisplay }; var reply = await DropboxApiUri .AppendSegments("2", "sharing", "create_shared_link_with_settings") .PostAsync <HttpResponse <CreateLinkReply, Error> >(createLinkRequest, cancellationToken).ConfigureAwait(false); if (reply.HasError) { throw new ApplicationException(reply.ErrorResponse.Summary); } return(reply.Response.Url); }
/// <summary> /// As soon as it's activated, the items that are imported are add to the Observable Items collection. /// </summary> protected override void OnActivate() { base.OnActivate(); var lang = DemoConfiguration.Language; // Add all the imported settings controls // TODO: Sort them for a tree view, somehow... Items.AddRange(SettingsControls); // Create the TrayIcon WindowsManager.ShowPopup(TrayIconVm); TrayIconVm.TrayIcon.Show(); TrayIconVm.TrayIcon.ShowBalloonTip("Hello", "This is a message", BalloonIcon.Warning); UiContext.RunOn(async() => await LanguageLoader.Current.ChangeLanguageAsync(lang)).Wait(); }
public async Task <ImgurImage> AnnonymousUploadToImgurAsync(ISurface surfaceToUpload, IDictionary <string, string> otherParameters, IProgress <int> progress = null, CancellationToken token = default) { var uploadUri = new Uri(_imgurConfiguration.ApiUrl).AppendSegments("upload.json").ExtendQuery(otherParameters); var localBehaviour = Behaviour.ShallowClone(); if (progress != null) { localBehaviour.UploadProgress = percent => { UiContext.RunOn(() => progress.Report((int)(percent * 100)), token); }; } using (var imageStream = new MemoryStream()) { surfaceToUpload.WriteToStream(imageStream, _coreConfiguration, _imgurConfiguration); imageStream.Position = 0; using (var content = new StreamContent(imageStream)) { content.Headers.Add("Content-Type", surfaceToUpload.GenerateMimeType(_coreConfiguration, _imgurConfiguration)); localBehaviour.MakeCurrent(); return(await uploadUri.PostAsync <ImgurImage>(content, token).ConfigureAwait(false)); } } }
/// <summary> /// Do the actual upload to Picasa /// </summary> /// <param name="oAuth2Settings">OAuth2Settings</param> /// <param name="surfaceToUpload">ICapture</param> /// <param name="outputSettings">SurfaceOutputSettings</param> /// <param name="otherParameters">IDictionary</param> /// <param name="progress">IProgress</param> /// <param name="token"></param> /// <returns>PicasaResponse</returns> public static async Task <ImgurImage> AuthenticatedUploadToImgurAsync(OAuth2Settings oAuth2Settings, ISurface surfaceToUpload, SurfaceOutputSettings outputSettings, IDictionary <string, string> otherParameters, IProgress <int> progress = null, CancellationToken token = default) { var uploadUri = new Uri(_imgurConfiguration.ApiUrl).AppendSegments("upload.json").ExtendQuery(otherParameters); var localBehaviour = Behaviour.ShallowClone(); if (progress != null) { localBehaviour.UploadProgress = percent => { UiContext.RunOn(() => progress.Report((int)(percent * 100)), token); }; } var oauthHttpBehaviour = OAuth2HttpBehaviourFactory.Create(oAuth2Settings, localBehaviour); using (var imageStream = new MemoryStream()) { ImageOutput.SaveToStream(surfaceToUpload, imageStream, outputSettings); imageStream.Position = 0; using (var content = new StreamContent(imageStream)) { content.Headers.Add("Content-Type", "image/" + outputSettings.Format); oauthHttpBehaviour.MakeCurrent(); return(await uploadUri.PostAsync <ImgurImage>(content, token)); } } }
/// <summary> /// /// </summary> /// <param name="surface"></param> /// <param name="progress"></param> /// <param name="token"></param> /// <returns></returns> public async Task <string> UploadToPicasa(ISurface surface, IProgress <int> progress = null, CancellationToken token = default) { string filename = Path.GetFileName(FilenameHelper.GetFilename(_googlePhotosConfiguration.UploadFormat, surface.CaptureDetails)); var outputSettings = new SurfaceOutputSettings(_googlePhotosConfiguration.UploadFormat, _googlePhotosConfiguration.UploadJpegQuality); // Fill the OAuth2Settings var oAuthHttpBehaviour = HttpBehaviour.Current.ShallowClone(); // Use UploadProgress if (progress != null) { oAuthHttpBehaviour.UploadProgress = percent => { UiContext.RunOn(() => progress.Report((int)(percent * 100))); }; } oAuthHttpBehaviour.OnHttpMessageHandlerCreated = httpMessageHandler => new OAuth2HttpMessageHandler(_oAuth2Settings, oAuthHttpBehaviour, httpMessageHandler); if (_googlePhotosConfiguration.AddFilename) { oAuthHttpBehaviour.OnHttpClientCreated = httpClient => httpClient.AddDefaultRequestHeader("Slug", Uri.EscapeDataString(filename)); } string response; var uploadUri = new Uri("https://picasaweb.google.com/data/feed/api/user").AppendSegments(_googlePhotosConfiguration.UploadUser, "albumid", _googlePhotosConfiguration.UploadAlbum); using (var imageStream = new MemoryStream()) { ImageOutput.SaveToStream(surface, imageStream, outputSettings); imageStream.Position = 0; using (var content = new StreamContent(imageStream)) { content.Headers.Add("Content-Type", "image/" + outputSettings.Format); oAuthHttpBehaviour.MakeCurrent(); response = await uploadUri.PostAsync <string>(content, token); } } return(ParseResponse(response)); }
/// <summary> /// Do the actual update check /// </summary> /// <param name="cancellationToken">CancellationToken</param> /// <returns>Task</returns> private async Task UpdateCheck(CancellationToken cancellationToken = default) { Log.Info().WriteLine("Checking for updates"); var updateFeed = await UpdateFeed.GetAsAsync <SyndicationFeed>(cancellationToken); if (updateFeed == null) { return; } _coreConfiguration.LastUpdateCheck = DateTime.Now; ProcessFeed(updateFeed); if (IsUpdateAvailable) { await UiContext.RunOn(() => { // TODO: Show update more nicely... MainForm.Instance.NotifyIcon.BalloonTipClicked += HandleBalloonTipClick; MainForm.Instance.NotifyIcon.BalloonTipClosed += CleanupBalloonTipClick; MainForm.Instance.NotifyIcon.ShowBalloonTip(10000, "Greenshot", string.Format(_greenshotLanguage.UpdateFound, LatestVersion), ToolTipIcon.Info); }, cancellationToken).ConfigureAwait(false); } }
/// <inheritdoc /> public void ShowAdaptiveCard(AdaptiveCard adaptiveCard) { UiContext.RunOn(() => _toastConductor.ActivateItem(new AdaptiveCardViewModel(adaptiveCard))); }
/// <summary> /// Do the actual upload to Box /// For more details on the available parameters, see: /// http://developers.box.net/w/page/12923951/ApiFunction_Upload%20and%20Download /// </summary> /// <param name="surface">ICapture</param> /// <param name="progress">IProgress</param> /// <param name="cancellationToken">CancellationToken</param> /// <returns>url to uploaded image</returns> public async Task <string> UploadToBoxAsync(ICaptureDetails captureDetails, ISurface surface, IProgress <int> progress = null, CancellationToken cancellationToken = default) { string filename = Path.GetFileName(FilenameHelper.GetFilename(_boxConfiguration.UploadFormat, captureDetails)); var outputSettings = new SurfaceOutputSettings(_boxConfiguration.UploadFormat, _boxConfiguration.UploadJpegQuality, false); var oauthHttpBehaviour = HttpBehaviour.Current.ShallowClone(); // Use UploadProgress if (progress != null) { oauthHttpBehaviour.UploadProgress = percent => { UiContext.RunOn(() => progress.Report((int)(percent * 100))); }; } oauthHttpBehaviour.OnHttpMessageHandlerCreated = httpMessageHandler => new OAuth2HttpMessageHandler(_oauth2Settings, oauthHttpBehaviour, httpMessageHandler); // TODO: See if the PostAsync<Bitmap> can be used? Or at least the HttpContentFactory? using (var imageStream = new MemoryStream()) { var multiPartContent = new MultipartFormDataContent(); var parentIdContent = new StringContent(_boxConfiguration.FolderId); parentIdContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = "\"parent_id\"" }; multiPartContent.Add(parentIdContent); ImageOutput.SaveToStream(surface, imageStream, outputSettings); imageStream.Position = 0; BoxFile response; using (var streamContent = new StreamContent(imageStream)) { streamContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); //"image/" + outputSettings.Format); streamContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = "\"file\"", FileName = "\"" + filename + "\"" }; // the extra quotes are important here multiPartContent.Add(streamContent); oauthHttpBehaviour.MakeCurrent(); response = await UploadFileUri.PostAsync <BoxFile>(multiPartContent, cancellationToken); } if (response == null) { return(null); } if (_boxConfiguration.UseSharedLink) { if (response.SharedLink?.Url == null) { var uriForSharedLink = FilesUri.AppendSegments(response.Id); var updateAccess = new { shared_link = new { access = "open" } }; oauthHttpBehaviour.MakeCurrent(); response = await uriForSharedLink.PostAsync <BoxFile>(updateAccess, cancellationToken); } return(response.SharedLink.Url); } return($"http://www.box.com/files/0/f/0/1/f_{response.Id}"); } }
/// <summary> /// Do the actual upload to Photobucket /// For more details on the available parameters, see: http://api.Photobucket.com/resources_anon /// </summary> /// <returns>PhotobucketResponse</returns> public async Task <PhotobucketInfo> UploadToPhotobucket(ISurface surfaceToUpload, SurfaceOutputSettings outputSettings, string albumPath, string title, string filename, IProgress <int> progress = null, CancellationToken token = default) { string responseString; var oAuthHttpBehaviour = _oAuthHttpBehaviour.ShallowClone(); // Use UploadProgress if (progress != null) { oAuthHttpBehaviour.UploadProgress = percent => { UiContext.RunOn(() => progress.Report((int)(percent * 100)), token); }; } _oAuthHttpBehaviour.MakeCurrent(); if (_photobucketConfiguration.Username == null || _photobucketConfiguration.SubDomain == null) { await PhotobucketApiUri.AppendSegments("users").ExtendQuery("format", "json").GetAsAsync <object>(token); } if (_photobucketConfiguration.Album == null) { _photobucketConfiguration.Album = _photobucketConfiguration.Username; } var uploadUri = PhotobucketApiUri.AppendSegments("album", _photobucketConfiguration.Album, "upload"); var signedParameters = new Dictionary <string, object> { { "type", "image" } }; // add type // add title if (title != null) { signedParameters.Add("title", title); } // add filename if (filename != null) { signedParameters.Add("filename", filename); } // Add image using (var imageStream = new MemoryStream()) { ImageOutput.SaveToStream(surfaceToUpload, imageStream, outputSettings); imageStream.Position = 0; using (var streamContent = new StreamContent(imageStream)) { streamContent.Headers.ContentType = new MediaTypeHeaderValue("image/" + outputSettings.Format); streamContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = "\"uploadfile\"", FileName = "\"" + filename + "\"" }; HttpBehaviour.Current.SetConfig(new HttpRequestMessageConfiguration { Properties = signedParameters }); try { responseString = await uploadUri.PostAsync <string>(streamContent, token); } catch (Exception ex) { Log.Error().WriteLine(ex, "Error uploading to Photobucket."); throw; } } } if (responseString == null) { return(null); } Log.Info().WriteLine(responseString); var photobucketInfo = PhotobucketInfo.FromUploadResponse(responseString); Log.Debug().WriteLine("Upload to Photobucket was finished"); return(photobucketInfo); }