protected virtual void SendImage(Photo photo, Stream stream) { string path = photo.DefaultVersion.Uri.LocalPath; FileInfo file_info = new FileInfo(path); if (!file_info.Exists) { SendError(stream, "404 The file is not on the disk"); return; } FilterSet filters = new FilterSet(); filters.Add(new JpegFilter()); filters.Add(new ResizeFilter(1600)); using (FilterRequest request = new FilterRequest(photo.DefaultVersion.Uri)) { filters.Convert(request); file_info = new FileInfo(request.Current.LocalPath); SendFile(file_info, photo, stream); } if (stats != null) { stats.PhotoViews++; } }
void Upload() { IPhoto [] items = dialog.Items; string [] captions = dialog.Captions; dialog.StoreCaption(); long sent_bytes = 0; FilterSet filters = new FilterSet(); filters.Add(new JpegFilter()); filters.Add(new ResizeFilter((uint)size)); for (int i = 0; i < items.Length; i++) { try { IPhoto item = items [i]; FileInfo file_info; Log.DebugFormat("uploading {0}", i); progress_dialog.Message = string.Format(Catalog.GetString("Uploading picture \"{0}\" ({1} of {2})"), item.Name, i + 1, items.Length); progress_dialog.ProgressText = string.Empty; progress_dialog.Fraction = i / (double)items.Length; FilterRequest request = new FilterRequest(item.DefaultVersion.Uri); filters.Convert(request); file_info = new FileInfo(request.Current.LocalPath); album.Upload(captions [i] ?? "", request.Current.LocalPath); sent_bytes += file_info.Length; } catch (Exception e) { progress_dialog.Message = string.Format(Catalog.GetString("Error Uploading To Facebook: {0}"), e.Message); progress_dialog.ProgressText = Catalog.GetString("Error"); Log.DebugException(e); if (progress_dialog.PerformRetrySkip()) { i--; } } } progress_dialog.Message = Catalog.GetString("Done Sending Photos"); progress_dialog.Fraction = 1.0; progress_dialog.ProgressText = Catalog.GetString("Upload Complete"); progress_dialog.ButtonLabel = Gtk.Stock.Ok; var li = new LinkButton("http://www.facebook.com/group.php?gid=158960179844&ref=mf", Catalog.GetString("Visit F-Spot group on Facebook")); progress_dialog.VBoxPackEnd(li); li.ShowAll(); }
/// <summary> /// FilterSet speichern /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void saveFilterSet_Click(object sender, RoutedEventArgs e) { // Prüfe ob für das Statistiken/Listen-Modul if (this.useForListModule && string.IsNullOrEmpty(tbName.Text)) { MessageBoxEnhanced.Error(IniParser.GetSetting("FORMLETTER", "noSetNameSpecified")); return; } // Keine leeren Filtersets zulassen if (!(listBox1.Items.Count > 0)) { return; } // Lese Filter aus Filter-Liste foreach (var subitem in listBox1.Items) { currentFilterSet.addFilter(subitem as FilterModel); } // Wenn nicht für Listen-Modul, lege FilterSet im Speicher ab if (!this.useForListModule) { allFilterSets.Add(currentFilterSet); } // Für das Listen/Statistiken-Modul wird das FilterSet direkt in die Datenbank gespeichert if (this.useForListModule) { string name = tbName.Text; try { int filterSetID = FilterSet.Add(name, currentFilterSet.linkingType); // Bearbeite alle Filter zu jedem Set foreach (var filter in currentFilterSet.filterList) { string table = filter.group.ToString(); string type = filter.criterion.ToString(); string operation = filter.operation.ToString(); string value = filter.value; int filterID = Filter.Add(filterSetID, table, type, operation, value); } } catch { } } listBox1.IsEnabled = false; listBox2.IsEnabled = true; btDeleteSetButton.IsEnabled = true; refreshListBoxWithAllFilterSets(); currentFilterSet = null; clearForm(); tbName.Clear(); deactivateForm(); }
private void Intersect(FilterSet result, IFilterSet filtered, ref bool inited) { if (inited) { result.IntersectWith(filtered); } else { result.Add(filtered); inited = true; } }
/// <summary> /// Button-Klick-Funktion für "Serienbrief-Vorlage speichern"-Button /// </summary> /// <param name="senderButton">die Instanz des sendenden Buttons</param> private void saveFormletterTemplate(Button senderButton) { try { // When using tabs, you can retrieve a page instance included in a tab using this function, giving the page type pFormletterFilterSelection pageFilter = getPageFromTabs <pFormletterFilterSelection>(); pFormletterFileLinking pageFile = getPageFromTabs <pFormletterFileLinking>(); pFormletterTextFields pageText = getPageFromTabs <pFormletterTextFields>(); // Prüfe ob alle Eingaben richtig sind if (pageFilter.allFilterSets.Count == 0) { MessageBoxEnhanced.Error(IniParser.GetSetting("ERRORMSG", "noFilterSet")); pageFilter.parentTabControl.SelectedIndex = 0; return; } if (pageFile.lbFileName.Content.Equals("")) { MessageBoxEnhanced.Error(IniParser.GetSetting("ERRORMSG", "noFormletter")); pageFile.parentTabControl.SelectedIndex = 1; return; } if (!pageFile.validateLinkings()) { MessageBoxEnhanced.Error(IniParser.GetSetting("ERRORMSG", "noAssignment")); pageFile.parentTabControl.SelectedIndex = 1; return; } if (!pageText.validateTextFields()) { MessageBoxEnhanced.Error(IniParser.GetSetting("ERRORMSG", "noTextField")); pageText.parentTabControl.SelectedIndex = 2; return; } // Hole alle Filter-Sets List <FilterSetModel> filterSets = pageFilter.allFilterSets; // Neues FormletterPatternModelDB (Serienbriefvorlage) anlegen string pName = pageText.tbPatternName.Text; string saluationM = pageText.tbSaluationM.Text; string saluationF = pageText.tbSaluationF.Text; string saluationN = pageText.tbSaluationN.Text; string filename = pageFile.tbFileName.Text.Replace(System.IO.Directory.GetCurrentDirectory(), "%PROGRAMPATH%"); string text = ""; int frmltrPatternID = FormletterPattern.Add(pName, saluationM, saluationF, saluationN, filename, text); // Bearbeite alle FilterSets foreach (var set in filterSets) { string name = ""; // Für Filter-Sets leer, nur von Listen/Statistiken verwendet string linking = set.linkingType; int filterSetID = FilterSet.Add(name, linking, frmltrPatternID); // Bearbeite alle Filter zu jedem Set foreach (var filter in set.filterList) { string table = filter.group.ToString(); string type = filter.criterion.ToString(); string operation = filter.operation.ToString(); string value = filter.value; int filterID = Filter.Add(filterSetID, table, type, operation, value); } } // Hole alle Spaltenzuordnungen List <FormletterColumnCsvDocumentAssignment> list = pageFile.getAssignments(); // Schreibe Spaltenzuordnungen in die Datenbank foreach (var assignment in list) { string csvColumn = assignment.csv_col_name; string databaseTable = assignment.formletterTableAssignment.group.ToString(); string databaseColumn = assignment.formletterTableAssignment.field.ToString(); ColumnAssignment.Add(frmltrPatternID, csvColumn, databaseTable, databaseColumn); } //Leere Formular pageFilter.resetEverything(); pageFile.resetEverything(); pageText.resetEverything(); KPage pageFormletterAdmin = new KöTaf.WPFApplication.Views.Formletter.pFormletterAdministration(); SinglePage singlePage = new SinglePage(IniParser.GetSetting("FORMLETTER", "formletterAdmin"), pageFormletterAdmin); } catch { MessageBoxEnhanced.Error(IniParser.GetSetting("ERRORMSG", "formletterCreate")); } }
void create_mosaics() { //Prepare the query Db db = App.Instance.Database; FSpot.PhotoQuery mini_query = new FSpot.PhotoQuery(db.Photos); Photo [] photos; if (tags_radio.Active) { //Build tag array List <Tag> taglist = new List <Tag> (); foreach (string tag_name in miniatures_tags.GetTypedTagNames()) { Tag t = db.Tags.GetTagByName(tag_name); if (t != null) { taglist.Add(t); } } mini_query.Terms = FSpot.OrTerm.FromTags(taglist.ToArray()); photos = mini_query.Photos; } else { photos = App.Instance.Organizer.Query.Photos; } if (photos.Length == 0) { //There is no photo for the selected tags! :( InfoDialog(Catalog.GetString("No photos for the selection"), Catalog.GetString("The tags selected provided no pictures. Please select different tags"), Gtk.MessageType.Error); return; } //Create minis ProgressDialog progress_dialog = null; progress_dialog = new ProgressDialog(Catalog.GetString("Creating miniatures"), ProgressDialog.CancelButtonType.Stop, photos.Length, metapixel_dialog); minidir_tmp = System.IO.Path.GetTempFileName(); System.IO.File.Delete(minidir_tmp); System.IO.Directory.CreateDirectory(minidir_tmp); minidir_tmp += "/"; //Call MetaPixel to create the minis foreach (Photo p in photos) { if (progress_dialog.Update(String.Format(Catalog.GetString("Preparing photo \"{0}\""), p.Name))) { progress_dialog.Destroy(); DeleteTmp(); return; } //FIXME should switch to retry/skip if (!GLib.FileFactory.NewForUri(p.DefaultVersion.Uri).Exists) { Log.WarningFormat(String.Format("Couldn't access photo {0} while creating miniatures", p.DefaultVersion.Uri.LocalPath)); continue; } //FIXME Check if the picture's format is supproted (jpg, gif) FilterSet filters = new FilterSet(); filters.Add(new JpegFilter()); FilterRequest freq = new FilterRequest(p.DefaultVersion.Uri); filters.Convert(freq); //We use photo id for minis, instead of photo names, to avoid duplicates string minifile = minidir_tmp + p.Id.ToString() + System.IO.Path.GetExtension(p.DefaultVersion.Uri.ToString()); string prepare_command = String.Format("--prepare -w {0} -h {1} {2} {3} {4}tables.mxt", icon_x_size.Text, //Minis width icon_y_size.Text, //Minis height GLib.Shell.Quote(freq.Current.LocalPath), //Source image GLib.Shell.Quote(minifile), //Dest image minidir_tmp); //Table file Log.Debug("Executing: metapixel " + prepare_command); System.Diagnostics.Process mp_prep = System.Diagnostics.Process.Start("metapixel", prepare_command); mp_prep.WaitForExit(); if (!System.IO.File.Exists(minifile)) { Log.DebugFormat("No mini? No party! {0}", minifile); continue; } } //Finished preparing! if (progress_dialog != null) { progress_dialog.Destroy(); } progress_dialog = null; progress_dialog = new ProgressDialog(Catalog.GetString("Creating photomosaics"), ProgressDialog.CancelButtonType.Stop, App.Instance.Organizer.SelectedPhotos().Length, metapixel_dialog); //Now create the mosaics! uint error_count = 0; foreach (Photo p in App.Instance.Organizer.SelectedPhotos()) { if (progress_dialog.Update(String.Format(Catalog.GetString("Processing \"{0}\""), p.Name))) { progress_dialog.Destroy(); DeleteTmp(); return; } //FIXME should switch to retry/skip if (!GLib.FileFactory.NewForUri(p.DefaultVersion.Uri).Exists) { Log.WarningFormat(String.Format("Couldn't access photo {0} while creating mosaics", p.DefaultVersion.Uri.LocalPath)); error_count++; continue; } //FIXME Check if the picture's format is supproted (jpg, gif) FilterSet filters = new FilterSet(); filters.Add(new JpegFilter()); FilterRequest freq = new FilterRequest(p.DefaultVersion.Uri); filters.Convert(freq); string name = GetVersionName(p); System.Uri mosaic = GetUriForVersionName(p, name); string mosaic_command = String.Format("--metapixel -l {0} {1} {2}", minidir_tmp, GLib.Shell.Quote(freq.Current.LocalPath), GLib.Shell.Quote(mosaic.LocalPath)); Log.Debug("Executing: metapixel " + mosaic_command); System.Diagnostics.Process mp_exe = System.Diagnostics.Process.Start("metapixel", mosaic_command); mp_exe.WaitForExit(); if (!GLib.FileFactory.NewForUri(mosaic).Exists) { Log.Warning("Error in processing image " + p.Name); error_count++; continue; } p.DefaultVersionId = p.AddVersion(mosaic, name, true); p.Changes.DataChanged = true; Core.Database.Photos.Commit(p); } //Finished creating mosaics if (progress_dialog != null) { progress_dialog.Destroy(); } string final_message = "Your mosaics have been generated as new versions of the pictures you selected"; if (error_count > 0) { final_message += String.Format(".\n{0} images out of {1} had errors", error_count, App.Instance.Organizer.SelectedPhotos().Length); } InfoDialog(Catalog.GetString("PhotoMosaics generated!"), Catalog.GetString(final_message), (error_count == 0 ? Gtk.MessageType.Info : Gtk.MessageType.Warning)); DeleteTmp(); }
async Task <ReceivingAmqpLink> CreateLinkAsync(TimeSpan timeout) { var amqpEventHubClient = ((AmqpEventHubClient)this.EventHubClient); var timeoutHelper = new TimeoutHelper(timeout); AmqpConnection connection = await amqpEventHubClient.ConnectionManager.GetOrCreateAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false); // Authenticate over CBS var cbsLink = connection.Extensions.Find <AmqpCbsLink>(); ICbsTokenProvider cbsTokenProvider = amqpEventHubClient.CbsTokenProvider; Uri address = new Uri(amqpEventHubClient.ConnectionStringBuilder.Endpoint, this.Path); string audience = address.AbsoluteUri; string resource = address.AbsoluteUri; var expiresAt = await cbsLink.SendTokenAsync(cbsTokenProvider, address, audience, resource, new[] { ClaimConstants.Listen }, timeoutHelper.RemainingTime()).ConfigureAwait(false); AmqpSession session = null; try { // Create our Session var sessionSettings = new AmqpSessionSettings { Properties = new Fields() }; session = connection.CreateSession(sessionSettings); await session.OpenAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false); FilterSet filterMap = null; var filters = this.CreateFilters(); if (filters != null && filters.Count > 0) { filterMap = new FilterSet(); foreach (var filter in filters) { filterMap.Add(filter.DescriptorName, filter); } } // Create our Link var linkSettings = new AmqpLinkSettings { Role = true, TotalLinkCredit = (uint)this.PrefetchCount, AutoSendFlow = this.PrefetchCount > 0 }; linkSettings.AddProperty(AmqpClientConstants.EntityTypeName, (int)MessagingEntityType.ConsumerGroup); linkSettings.Source = new Source { Address = address.AbsolutePath, FilterSet = filterMap }; linkSettings.Target = new Target { Address = this.ClientId }; linkSettings.SettleType = SettleMode.SettleOnSend; // Receiver metrics enabled? if (this.ReceiverRuntimeMetricEnabled) { linkSettings.DesiredCapabilities = new Multiple <AmqpSymbol>(new List <AmqpSymbol> { AmqpClientConstants.EnableReceiverRuntimeMetricName }); } if (this.Epoch.HasValue) { linkSettings.AddProperty(AmqpClientConstants.AttachEpoch, this.Epoch.Value); } if (!string.IsNullOrWhiteSpace(this.Identifier)) { linkSettings.AddProperty(AmqpClientConstants.ReceiverIdentifierName, this.Identifier); } var link = new ReceivingAmqpLink(linkSettings); linkSettings.LinkName = $"{amqpEventHubClient.ContainerId};{connection.Identifier}:{session.Identifier}:{link.Identifier}"; link.AttachTo(session); await link.OpenAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false); var activeClientLink = new ActiveClientLink( link, audience, // audience this.EventHubClient.ConnectionStringBuilder.Endpoint.AbsoluteUri, // endpointUri new[] { ClaimConstants.Listen }, true, expiresAt); this.clientLinkManager.SetActiveLink(activeClientLink); return(link); } catch { // Cleanup any session (and thus link) in case of exception. session?.SafeClose(); throw; } }
private void Upload() { account.Gallery.Progress = new ProgressItem(); account.Gallery.Progress.Changed += HandleProgressChanged; Log.Debug("Starting upload"); FilterSet filters = new FilterSet(); if (account.Version == GalleryVersion.Version1) { filters.Add(new WhiteListFilter(new string [] { ".jpg", ".jpeg", ".png", ".gif" })); } if (scale) { filters.Add(new ResizeFilter((uint)size)); } while (photo_index < items.Length) { IPhoto item = items [photo_index]; Log.DebugFormat("uploading {0}", photo_index); progress_dialog.Message = string.Format(Catalog.GetString("Uploading picture \"{0}\""), item.Name); progress_dialog.Fraction = photo_index / (double)items.Length; photo_index++; progress_dialog.ProgressText = string.Format(Catalog.GetString("{0} of {1}"), photo_index, items.Length); FilterRequest req = new FilterRequest(item.DefaultVersion.Uri); filters.Convert(req); try { int id = album.Add(item, req.Current.LocalPath); if (item != null && item is Photo && App.Instance.Database != null && id != 0) { App.Instance.Database.Exports.Create((item as Photo).Id, (item as Photo).DefaultVersionId, ExportStore.Gallery2ExportType, string.Format("{0}:{1}", album.Gallery.Uri, id.ToString())); } } catch (Exception e) { progress_dialog.Message = string.Format(Catalog.GetString("Error uploading picture \"{0}\" to Gallery: {1}"), item.Name, e.Message); progress_dialog.ProgressText = Catalog.GetString("Error"); Log.Exception(e); if (progress_dialog.PerformRetrySkip()) { photo_index--; } } } progress_dialog.Message = Catalog.GetString("Done Sending Photos"); progress_dialog.Fraction = 1.0; progress_dialog.ProgressText = Catalog.GetString("Upload Complete"); progress_dialog.ButtonLabel = Gtk.Stock.Ok; if (browser) { GtkBeans.Global.ShowUri(export_dialog.Screen, album.GetUrl()); } }
/// <summary> /// Creates an AMQP link for use with receiving operations. /// </summary> /// <param name="entityPath"></param> /// /// <param name="connection">The active and opened AMQP connection to use for this link.</param> /// <param name="endpoint">The fully qualified endpoint to open the link for.</param> /// <param name="prefetchCount">Controls the number of events received and queued locally without regard to whether an operation was requested.</param> /// <param name="receiveMode">The <see cref="ReceiveMode"/> used to specify how messages are received. Defaults to PeekLock mode.</param> /// <param name="sessionId"></param> /// <param name="isSessionReceiver"></param> /// <param name="timeout">The timeout to apply when creating the link.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param> /// /// <returns>A link for use for operations related to receiving events.</returns> /// protected virtual async Task <ReceivingAmqpLink> CreateReceivingLinkAsync( string entityPath, AmqpConnection connection, Uri endpoint, TimeSpan timeout, uint prefetchCount, ReceiveMode receiveMode, string sessionId, bool isSessionReceiver, CancellationToken cancellationToken) { Argument.AssertNotDisposed(IsDisposed, nameof(AmqpConnectionScope)); cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>(); var session = default(AmqpSession); var stopWatch = Stopwatch.StartNew(); try { // Perform the initial authorization for the link. string[] authClaims = new string[] { ServiceBusClaim.Send }; var audience = new[] { endpoint.AbsoluteUri }; DateTime authExpirationUtc = await RequestAuthorizationUsingCbsAsync( connection, TokenProvider, endpoint, audience, authClaims, timeout.CalculateRemaining(stopWatch.Elapsed)).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>(); // Create and open the AMQP session associated with the link. var sessionSettings = new AmqpSessionSettings { Properties = new Fields() }; session = connection.CreateSession(sessionSettings); await OpenAmqpObjectAsync(session, timeout).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>(); var filters = new FilterSet(); // even if supplied sessionId is null, we need to add the Session filter if it is a session receiver if (isSessionReceiver) { filters.Add(AmqpClientConstants.SessionFilterName, sessionId); } var linkSettings = new AmqpLinkSettings { Role = true, TotalLinkCredit = prefetchCount, AutoSendFlow = prefetchCount > 0, SettleType = (receiveMode == ReceiveMode.PeekLock) ? SettleMode.SettleOnDispose : SettleMode.SettleOnSend, Source = new Source { Address = endpoint.AbsolutePath, FilterSet = filters }, Target = new Target { Address = Guid.NewGuid().ToString() } }; var link = new ReceivingAmqpLink(linkSettings); linkSettings.LinkName = $"{connection.Settings.ContainerId};{connection.Identifier}:{session.Identifier}:{link.Identifier}:{linkSettings.Source.ToString()}"; link.AttachTo(session); stopWatch.Stop(); // Configure refresh for authorization of the link. var refreshTimer = default(Timer); TimerCallback refreshHandler = CreateAuthorizationRefreshHandler ( entityPath, connection, link, TokenProvider, endpoint, audience, authClaims, AuthorizationRefreshTimeout, () => (ActiveLinks.ContainsKey(link) ? refreshTimer : null) ); refreshTimer = new Timer(refreshHandler, null, CalculateLinkAuthorizationRefreshInterval(authExpirationUtc), Timeout.InfiniteTimeSpan); // Track the link before returning it, so that it can be managed with the scope. BeginTrackingLinkAsActive(entityPath, link, refreshTimer); return(link); } catch (Exception exception) { // Aborting the session will perform any necessary cleanup of // the associated link as well. session?.Abort(); throw AmqpExceptionHelper.TranslateException( exception, null, session.GetInnerException(), connection.IsClosing()); } }
/// <summary> /// Creates an AMQP link for use with receiving operations. /// </summary> /// /// <param name="connection">The active and opened AMQP connection to use for this link.</param> /// <param name="endpoint">The fully qualified endpoint to open the link for.</param> /// <param name="prefetchCount">Controls the number of events received and queued locally without regard to whether an operation was requested.</param> /// <param name="ownerLevel">The relative priority to associate with the link; for a non-exclusive link, this value should be <c>null</c>.</param> /// <param name="sessionId"></param> /// <param name="timeout">The timeout to apply when creating the link.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param> /// /// <returns>A link for use for operations related to receiving events.</returns> /// protected virtual async Task <ReceivingAmqpLink> CreateReceivingLinkAsync(AmqpConnection connection, Uri endpoint, TimeSpan timeout, uint prefetchCount, long?ownerLevel, string sessionId, CancellationToken cancellationToken) { Argument.AssertNotDisposed(IsDisposed, nameof(AmqpConnectionScope)); cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>(); var session = default(AmqpSession); var stopWatch = Stopwatch.StartNew(); try { // Perform the initial authorization for the link. var authClaims = new[] { ServiceBusClaim.Listen }; var authExpirationUtc = await RequestAuthorizationUsingCbsAsync(connection, TokenProvider, endpoint, endpoint.AbsoluteUri, endpoint.AbsoluteUri, authClaims, timeout.CalculateRemaining(stopWatch.Elapsed)).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>(); // Create and open the AMQP session associated with the link. var sessionSettings = new AmqpSessionSettings { Properties = new Fields() }; session = connection.CreateSession(sessionSettings); await OpenAmqpObjectAsync(session, timeout).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>(); // Create and open the link. var filters = new FilterSet(); if (sessionId != null) { filters.Add(AmqpClientConstants.SessionFilterName, sessionId); } //if (this.isSessionReceiver) //{ // filterMap = new FilterSet { { AmqpClientConstants.SessionFilterName, this.SessionIdInternal } }; //} var linkSettings = new AmqpLinkSettings { Role = true, TotalLinkCredit = prefetchCount, AutoSendFlow = prefetchCount > 0, SettleType = SettleMode.SettleOnSend, Source = new Source { Address = endpoint.AbsolutePath, FilterSet = filters }, Target = new Target { Address = Guid.NewGuid().ToString() } }; //linkSettings.AddProperty(AmqpProperty.EntityType, "0,1,2,3");//(int)AmqpProperty.Entity.ConsumerGroup); if (ownerLevel.HasValue) { linkSettings.AddProperty(AmqpProperty.OwnerLevel, ownerLevel.Value); } var link = new ReceivingAmqpLink(linkSettings); linkSettings.LinkName = $"{connection.Settings.ContainerId};{connection.Identifier}:{session.Identifier}:{link.Identifier}:{linkSettings.Source.ToString()}:test"; //linkSettings.LinkName = $"{ Id };{ connection.Identifier }:{ session.Identifier }:{ link.Identifier }"; link.AttachTo(session); stopWatch.Stop(); // Configure refresh for authorization of the link. var refreshTimer = default(Timer); var refreshHandler = CreateAuthorizationRefreshHandler ( connection, link, TokenProvider, endpoint, endpoint.AbsoluteUri, endpoint.AbsoluteUri, authClaims, AuthorizationRefreshTimeout, () => (ActiveLinks.ContainsKey(link) ? refreshTimer : null) ); refreshTimer = new Timer(refreshHandler, null, CalculateLinkAuthorizationRefreshInterval(authExpirationUtc), Timeout.InfiniteTimeSpan); // Track the link before returning it, so that it can be managed with the scope. BeginTrackingLinkAsActive(link, refreshTimer); return(link); } catch { // Aborting the session will perform any necessary cleanup of // the associated link as well. session?.Abort(); throw; } }
public void ProcessImage(int image_num, FilterSet filter_set) { IPhoto photo = Collection [image_num]; string path; ScaleRequest req; req = requests [0]; MakeDir(SubdirPath(req.Name)); path = SubdirPath(req.Name, ImageName(image_num)); using (FilterRequest request = new FilterRequest(photo.DefaultVersion.Uri)) { filter_set.Convert(request); if (request.Current.LocalPath == path) { request.Preserve(request.Current); } else { System.IO.File.Copy(request.Current.LocalPath, path, true); } if (photo != null && photo is Photo && App.Instance.Database != null) { App.Instance.Database.Exports.Create((photo as Photo).Id, (photo as Photo).DefaultVersionId, ExportStore.FolderExportType, // FIXME this is wrong, the final path is the one // after the Xfer. new SafeUri(path).ToString()); } for (int i = 1; i < requests.Length; i++) { req = requests [i]; if (scale && req.AvoidScale(Size)) { continue; } FilterSet req_set = new FilterSet(); req_set.Add(new ResizeFilter((uint)Math.Max(req.Width, req.Height))); bool sharpen; try { sharpen = Preferences.Get <bool> (FolderExport.SHARPEN_KEY); } catch (NullReferenceException) { sharpen = true; Preferences.Set(FolderExport.SHARPEN_KEY, true); } if (sharpen) { if (req.Name == "lq") { req_set.Add(new SharpFilter(0.1, 2, 4)); } if (req.Name == "thumbs") { req_set.Add(new SharpFilter(0.1, 2, 5)); } } using (FilterRequest tmp_req = new FilterRequest(photo.DefaultVersion.Uri)) { req_set.Convert(tmp_req); MakeDir(SubdirPath(req.Name)); path = SubdirPath(req.Name, ImageName(image_num)); System.IO.File.Copy(tmp_req.Current.LocalPath, path, true); } } } }
private void Upload() { Album album = null; if (create_album_radiobutton.Active) { string name = album_name_entry.Text; if (name.Length == 0) { HigMessageDialog mbox = new HigMessageDialog(Dialog, Gtk.DialogFlags.DestroyWithParent | Gtk.DialogFlags.Modal, Gtk.MessageType.Error, Gtk.ButtonsType.Ok, Catalog.GetString("Album must have a name"), Catalog.GetString("Please name your album or choose an existing album.")); mbox.Run(); mbox.Destroy(); return; } string description = album_description_entry.Text; string location = album_location_entry.Text; try { album = account.Facebook.CreateAlbum(name, description, location); } catch (FacebookException fe) { HigMessageDialog mbox = new HigMessageDialog(Dialog, Gtk.DialogFlags.DestroyWithParent | Gtk.DialogFlags.Modal, Gtk.MessageType.Error, Gtk.ButtonsType.Ok, Catalog.GetString("Creating a new album failed"), String.Format(Catalog.GetString("An error occurred creating a new album.\n\n{0}"), fe.Message)); mbox.Run(); mbox.Destroy(); return; } } else { AlbumStore store = (AlbumStore)existing_album_combobox.Model; album = store.Albums [existing_album_combobox.Active]; } long sent_bytes = 0; FilterSet filters = new FilterSet(); filters.Add(new JpegFilter()); filters.Add(new ResizeFilter((uint)size)); for (int i = 0; i < items.Length; i++) { try { IBrowsableItem item = items [i]; FileInfo file_info; Console.WriteLine("uploading {0}", i); progress_dialog.Message = String.Format(Catalog.GetString("Uploading picture \"{0}\" ({1} of {2})"), item.Name, i + 1, items.Length); progress_dialog.ProgressText = string.Empty; progress_dialog.Fraction = i / (double)items.Length; FilterRequest request = new FilterRequest(item.DefaultVersionUri); filters.Convert(request); file_info = new FileInfo(request.Current.LocalPath); Mono.Facebook.Photo photo = album.Upload(captions [i] ?? "", request.Current.LocalPath); sent_bytes += file_info.Length; } catch (Exception e) { progress_dialog.Message = String.Format(Catalog.GetString("Error Uploading To Facebook: {0}"), e.Message); progress_dialog.ProgressText = Catalog.GetString("Error"); Console.WriteLine(e); if (progress_dialog.PerformRetrySkip()) { i--; } } } progress_dialog.Message = Catalog.GetString("Done Sending Photos"); progress_dialog.Fraction = 1.0; progress_dialog.ProgressText = Catalog.GetString("Upload Complete"); progress_dialog.ButtonLabel = Gtk.Stock.Ok; Dialog.Destroy(); }
private void HandleResponse(object sender, Gtk.ResponseArgs args) { int size = 0; bool UserCancelled = false; // Lets remove the mail "create mail" dialog Destroy(); if (args.ResponseId != Gtk.ResponseType.Ok) { return; } ProgressDialog progress_dialog = null; progress_dialog = new ProgressDialog(Catalog.GetString("Preparing email"), ProgressDialog.CancelButtonType.Stop, selection.Count, parent_window); size = GetScaleSize(); // Which size should we scale to. 0 --> Original // evaluate mailto command and define attachment args for cli System.Text.StringBuilder attach_arg = new System.Text.StringBuilder(); switch (Preferences.Get <string> (Preferences.GNOME_MAILTO_COMMAND)) { case "thunderbird %s": case "mozilla-thunderbird %s": case "seamonkey -mail -compose %s": case "icedove %s": attach_arg.Append(","); break; case "kmail %s": attach_arg.Append(" --attach "); break; default: //evolution falls into default, since it supports mailto uri correctly attach_arg.Append("&attach="); break; } // Create a tmp directory. tmp_mail_dir = System.IO.Path.GetTempFileName(); // Create a tmp file System.IO.File.Delete(tmp_mail_dir); // Delete above tmp file System.IO.Directory.CreateDirectory(tmp_mail_dir); // Create a directory with above tmp name System.Text.StringBuilder mail_attach = new System.Text.StringBuilder(); FilterSet filters = new FilterSet(); if (size != 0) { filters.Add(new ResizeFilter((uint)size)); } filters.Add(new UniqueNameFilter(new SafeUri(tmp_mail_dir))); for (int i = 0; i < selection.Count; i++) { var photo = selection [i]; if ((photo != null) && (!UserCancelled)) { if (progress_dialog != null) { UserCancelled = progress_dialog.Update(String.Format (Catalog.GetString("Exporting picture \"{0}\""), photo.Name)); } if (UserCancelled) { break; } try { // Prepare a tmp_mail file name FilterRequest request = new FilterRequest(photo.DefaultVersion.Uri); filters.Convert(request); request.Preserve(request.Current); mail_attach.Append(((i == 0 && attach_arg.ToString() == ",") ? "" : attach_arg.ToString()) + request.Current.ToString()); } catch (Exception e) { Hyena.Log.ErrorFormat("Error preparing {0}: {1}", selection[i].Name, e.Message); HigMessageDialog md = new HigMessageDialog(parent_window, DialogFlags.DestroyWithParent, MessageType.Error, ButtonsType.Close, Catalog.GetString("Error processing image"), String.Format(Catalog.GetString("An error occurred while processing \"{0}\": {1}"), selection[i].Name, e.Message)); md.Run(); md.Destroy(); UserCancelled = true; } } } // foreach if (progress_dialog != null) { progress_dialog.Destroy(); // No need to keep this window } if (UserCancelled) { return; } // Send the mail :) string mail_subject = Catalog.GetString("My Photos"); switch (Preferences.Get <string> (Preferences.GNOME_MAILTO_COMMAND)) { // openSuSE case "thunderbird %s": System.Diagnostics.Process.Start("thunderbird", " -compose \"subject=" + mail_subject + ",attachment='" + mail_attach + "'\""); break; case "icedove %s": System.Diagnostics.Process.Start("icedove", " -compose \"subject=" + mail_subject + ",attachment='" + mail_attach + "'\""); break; case "mozilla-thunderbird %s": System.Diagnostics.Process.Start("mozilla-thunderbird", " -compose \"subject=" + mail_subject + ",attachment='" + mail_attach + "'\""); break; case "seamonkey -mail -compose %s": System.Diagnostics.Process.Start("seamonkey", " -mail -compose \"subject=" + mail_subject + ",attachment='" + mail_attach + "'\""); break; case "kmail %s": System.Diagnostics.Process.Start("kmail", " --composer --subject \"" + mail_subject + "\"" + mail_attach); break; case "evolution %s": //evo doesn't urldecode the subject GtkBeans.Global.ShowUri(Screen, "mailto:?subject=" + mail_subject + mail_attach); break; default: GtkBeans.Global.ShowUri(Screen, "mailto:?subject=" + System.Web.HttpUtility.UrlEncode(mail_subject) + mail_attach); break; } }
private void Upload() { album.UploadProgress += HandleUploadProgress; sent_bytes = 0; approx_size = 0; Log.Debug("Starting Upload to Picasa"); FilterSet filters = new FilterSet(); filters.Add(new JpegFilter()); if (scale) { filters.Add(new ResizeFilter((uint)size)); } Array.Sort(items, new DateComparer()); while (photo_index < items.Length) { try { IPhoto item = items [photo_index]; FileInfo file_info; Log.Debug("Picasa uploading " + photo_index); progress_dialog.Message = String.Format(Catalog.GetString("Uploading picture \"{0}\" ({1} of {2})"), item.Name, photo_index + 1, items.Length); photo_index++; PicasaPicture picture; using (FilterRequest request = new FilterRequest(item.DefaultVersion.Uri)) { filters.Convert(request); file_info = new FileInfo(request.Current.LocalPath); if (approx_size == 0) //first image { approx_size = file_info.Length * items.Length; } else { approx_size = sent_bytes * items.Length / (photo_index - 1); } picture = album.UploadPicture(request.Current.LocalPath, Path.ChangeExtension(item.Name, "jpg"), item.Description); sent_bytes += file_info.Length; } if (App.Instance.Database != null && item is Photo) { App.Instance.Database.Exports.Create((item as Photo).Id, (item as Photo).DefaultVersionId, ExportStore.PicasaExportType, picture.Link); } //tagging if (item.Tags != null && export_tag) { foreach (Tag tag in item.Tags) { picture.AddTag(tag.Name); } } } catch (System.Threading.ThreadAbortException te) { Log.Exception(te); System.Threading.Thread.ResetAbort(); } catch (System.Exception e) { progress_dialog.Message = String.Format(Catalog.GetString("Error Uploading To Gallery: {0}"), e.Message); progress_dialog.ProgressText = Catalog.GetString("Error"); Log.DebugException(e); if (progress_dialog.PerformRetrySkip()) { photo_index--; if (photo_index == 0) { approx_size = 0; } } } } progress_dialog.Message = Catalog.GetString("Done Sending Photos"); progress_dialog.Fraction = 1.0; progress_dialog.ProgressText = Catalog.GetString("Upload Complete"); progress_dialog.ButtonLabel = Gtk.Stock.Ok; if (browser) { GtkBeans.Global.ShowUri(Dialog.Screen, album.Link); } }
public SendEmail(IBrowsableCollection selection) : base("mail_dialog") { this.selection = selection; for (int i = 0; i < selection.Count; i++) { Photo p = selection[i] as Photo; if (Gnome.Vfs.MimeType.GetMimeTypeForUri(p.DefaultVersionUri.ToString()) != "image/jpeg") { force_original = true; } } if (force_original) { original_size.Active = true; tiny_size.Sensitive = false; small_size.Sensitive = false; medium_size.Sensitive = false; large_size.Sensitive = false; x_large_size.Sensitive = false; } else { switch (Preferences.Get <int> (Preferences.EXPORT_EMAIL_SIZE)) { case 0: original_size.Active = true; break; case 1: tiny_size.Active = true; break; case 2: small_size.Active = true; break; case 3: medium_size.Active = true; break; case 4: large_size.Active = true; break; case 5: x_large_size.Active = true; break; default: break; } } rotate_check.Active = Preferences.Get <bool> (Preferences.EXPORT_EMAIL_ROTATE); rotate_check.Sensitive = original_size.Active && tiny_size.Sensitive; tray_scrolled.Add(new TrayView(selection)); Dialog.Modal = false; // Calculate total original filesize for (int i = 0; i < selection.Count; i++) { Photo photo = selection[i] as Photo; try { Orig_Photo_Size += (new Gnome.Vfs.FileInfo(photo.DefaultVersionUri.ToString())).Size; } catch { } } for (int k = 0; k < avg_scale_ref.Length; k++) { avg_scale[k] = avg_scale_ref[k]; } // Calculate approximate size shrinking, use first photo, and shrink to medium size as base. Photo scalephoto = selection [0] as Photo; if (scalephoto != null && !force_original) { // Get first photos file size long orig_size = (new Gnome.Vfs.FileInfo(scalephoto.DefaultVersionUri.ToString())).Size; FilterSet filters = new FilterSet(); filters.Add(new ResizeFilter((uint)(sizes [3]))); long new_size; using (FilterRequest request = new FilterRequest(scalephoto.DefaultVersionUri)) { filters.Convert(request); new_size = (new Gnome.Vfs.FileInfo(request.Current.ToString())).Size; } if (orig_size > 0) { // Get the factor (scale) between original and resized medium size. scale_percentage = 1 - ((float)(orig_size - new_size) / orig_size); // What is the relation between the estimated medium scale factor, and reality? double scale_scale = scale_percentage / avg_scale_ref[3]; //System.Console.WriteLine ("scale_percentage {0}, ref {1}, relative {2}", // scale_percentage, avg_scale_ref[3], scale_scale ); // Re-Calculate the proper relation per size for (int k = 0; k < avg_scale_ref.Length; k++) { avg_scale[k] = avg_scale_ref[k] * scale_scale; // System.Console.WriteLine ("avg_scale[{0}]={1} (was {2})", // k, avg_scale[k], avg_scale_ref[k] ); } } } NumberOfPictures.Text = selection.Count.ToString(); TotalOriginalSize.Text = SizeUtil.ToHumanReadable(Orig_Photo_Size); UpdateEstimatedSize(); Dialog.ShowAll(); //LoadHistory (); Dialog.Response += HandleResponse; }
private void HandleResponse(object sender, Gtk.ResponseArgs args) { int size = 0; bool UserCancelled = false; bool rotate = true; // Lets remove the mail "create mail" dialog Dialog.Destroy(); if (args.ResponseId != Gtk.ResponseType.Ok) { return; } ProgressDialog progress_dialog = null; progress_dialog = new ProgressDialog(Catalog.GetString("Preparing email"), ProgressDialog.CancelButtonType.Stop, selection.Count, parent_window); size = GetScaleSize(); // Which size should we scale to. 0 --> Original // evaluate mailto command and define attachment args for cli System.Text.StringBuilder attach_arg = new System.Text.StringBuilder(); switch (Preferences.Get <string> (Preferences.GNOME_MAILTO_COMMAND)) { case "thunderbird %s": case "mozilla-thunderbird %s": case "seamonkey -mail -compose %s": case "icedove %s": attach_arg.Append(","); break; case "kmail %s": attach_arg.Append(" --attach "); break; default: //evolution falls into default, since it supports mailto uri correctly attach_arg.Append("&attach="); break; } rotate = rotate_check.Active; // Should we automatically rotate original photos. Preferences.Set(Preferences.EXPORT_EMAIL_ROTATE, rotate); // Initiate storage for temporary files to be deleted later tmp_paths = new System.Collections.ArrayList(); // Create a tmp directory. tmp_mail_dir = System.IO.Path.GetTempFileName(); // Create a tmp file System.IO.File.Delete(tmp_mail_dir); // Delete above tmp file System.IO.Directory.CreateDirectory(tmp_mail_dir); // Create a directory with above tmp name System.Text.StringBuilder mail_attach = new System.Text.StringBuilder(); FilterSet filters = new FilterSet(); if (size != 0) { filters.Add(new ResizeFilter((uint)size)); } else if (rotate) { filters.Add(new OrientationFilter()); } filters.Add(new UniqueNameFilter(tmp_mail_dir)); for (int i = 0; i < selection.Count; i++) { Photo photo = selection [i] as Photo; if ((photo != null) && (!UserCancelled)) { if (progress_dialog != null) { UserCancelled = progress_dialog.Update(String.Format (Catalog.GetString("Exporting picture \"{0}\""), photo.Name)); } if (UserCancelled) { break; } try { // Prepare a tmp_mail file name FilterRequest request = new FilterRequest(photo.DefaultVersionUri); filters.Convert(request); request.Preserve(request.Current); mail_attach.Append(attach_arg.ToString() + request.Current.ToString()); // Mark the path for deletion tmp_paths.Add(request.Current.LocalPath); } catch (Exception e) { Console.WriteLine("Error preparing {0}: {1}", selection[photo_index].Name, e.Message); HigMessageDialog md = new HigMessageDialog(parent_window, DialogFlags.DestroyWithParent, MessageType.Error, ButtonsType.Close, Catalog.GetString("Error processing image"), String.Format(Catalog.GetString("An error occured while processing \"{0}\": {1}"), selection[photo_index].Name, e.Message)); md.Run(); md.Destroy(); UserCancelled = true; } } } // foreach if (progress_dialog != null) { progress_dialog.Destroy(); // No need to keep this window } if (UserCancelled) { DeleteTempFile(); } else { // Send the mail :) string mail_subject = Catalog.GetString("my photos"); switch (Preferences.Get <string> (Preferences.GNOME_MAILTO_COMMAND)) { // openSuSE case "thunderbird %s": System.Diagnostics.Process.Start("thunderbird", " -compose \"subject=" + mail_subject + ",attachment='" + mail_attach + "'\""); break; case "icedove %s": System.Diagnostics.Process.Start("icedove", " -compose \"subject=" + mail_subject + ",attachment='" + mail_attach + "'\""); break; case "mozilla-thunderbird %s": System.Diagnostics.Process.Start("mozilla-thunderbird", " -compose \"subject=" + mail_subject + ",attachment='" + mail_attach + "'\""); break; case "seamonkey -mail -compose %s": System.Diagnostics.Process.Start("seamonkey", " -mail -compose \"subject=" + mail_subject + ",attachment='" + mail_attach + "'\""); break; case "kmail %s": System.Diagnostics.Process.Start("kmail", " --composer --subject \"" + mail_subject + "\"" + mail_attach); break; default: GnomeUtil.UrlShow("mailto:?subject=" + System.Web.HttpUtility.UrlEncode(mail_subject) + mail_attach); break; } // Check if we have any temporary files to be deleted if (tmp_paths.Count > 0) { // Fetch timeout value from preferences. In seconds. Needs to be multiplied with 1000 to get msec uint delete_timeout; delete_timeout = (uint)(Preferences.Get <int> (Preferences.EXPORT_EMAIL_DELETE_TIMEOUT_SEC)); delete_timeout = delete_timeout * 1000; // to get milliseconds. // Start a timer and when it occurs, delete the temp files. GLib.Timeout.Add(delete_timeout, new GLib.TimeoutHandler(DeleteTempFile)); } } }
private void HandleResponse(object sender, Gtk.ResponseArgs args) { long new_size = 0; // long orig_size = 0; long actual_total_size = 0; int size = 0; System.IO.FileInfo file_info; bool UserCancelled = false; bool rotate = true; // Lets remove the mail "create mail" dialog Dialog.Destroy(); if (args.ResponseId != Gtk.ResponseType.Ok) { return; } ProgressDialog progress_dialog = null; actual_total_size = 0; progress_dialog = new ProgressDialog(Catalog.GetString("Preparing email"), ProgressDialog.CancelButtonType.Stop, selection.Items.Length, parent_window); size = GetScaleSize(); // Which size should we scale to. 0 --> Original // evaluate mailto command and define attachment args for cli System.Text.StringBuilder attach_arg = new System.Text.StringBuilder(); switch (Preferences.Get(Preferences.GNOME_MAILTO_COMMAND) as string) { case "thunderbird %s": case "mozilla-thunderbird %s": case "seamonkey -mail -compose %s": case "icedove %s": attach_arg.Append(","); break; case "kmail %s": attach_arg.Append(" --attach "); break; default: //evolution falls into default, since it supports mailto uri correctly attach_arg.Append("&attach="); break; } rotate = rotate_check.Active; // Should we automatically rotate original photos. Preferences.Set(Preferences.EXPORT_EMAIL_ROTATE, rotate); // Initiate storage for temporary files to be deleted later tmp_paths = new System.Collections.ArrayList(); // Create a tmp directory. tmp_mail_dir = System.IO.Path.GetTempFileName(); // Create a tmp file System.IO.File.Delete(tmp_mail_dir); // Delete above tmp file System.IO.Directory.CreateDirectory(tmp_mail_dir); // Create a directory with above tmp name System.Text.StringBuilder mail_attach = new System.Text.StringBuilder(); FilterSet filters = new FilterSet(); if (size != 0) { filters.Add(new ResizeFilter((uint)size)); } else if (rotate) { filters.Add(new OrientationFilter()); } filters.Add(new UniqueNameFilter(tmp_mail_dir)); foreach (Photo photo in selection.Items) { if ((photo != null) && (!UserCancelled)) { if (progress_dialog != null) { UserCancelled = progress_dialog.Update(String.Format (Catalog.GetString("Exporting picture \"{0}\""), photo.Name)); } if (UserCancelled) { break; } file_info = new System.IO.FileInfo(photo.GetVersionPath(photo.DefaultVersionId)); // orig_size = file_info.Length; // Prepare a tmp_mail file name FilterRequest request = new FilterRequest(photo.DefaultVersionUri); filters.Convert(request); request.Preserve(request.Current); mail_attach.Append(attach_arg.ToString() + System.Web.HttpUtility.UrlEncode(request.Current.ToString())); // Mark the path for deletion tmp_paths.Add(request.Current.LocalPath); // Update the running total of the actual file sizes. file_info = new System.IO.FileInfo(request.Current.LocalPath); new_size = file_info.Length; actual_total_size += new_size; // Update dialog to indicate Actual size! // This is currently disabled, since the dialog box is not visible at this stage. // string approxresult = SizeUtil.ToHumanReadable (actual_total_size); // ActualMailSize.Text = approxresult; //System.Console.WriteLine ("Orig file size {0}, New file size {1}, % {4}, Scaled to size {2}, new name {3}", //orig_size, new_size, size, tmp_path, 1 - ((orig_size-new_size)/orig_size)); } } // foreach if (progress_dialog != null) { progress_dialog.Destroy(); // No need to keep this window } if (UserCancelled) { DeleteTempFile(); } else { // Send the mail :) switch (Preferences.Get(Preferences.GNOME_MAILTO_COMMAND) as string) { // openSuSE case "thunderbird %s": System.Diagnostics.Process.Start("thunderbird", " -compose \"subject=my photos,attachment='" + mail_attach + "'\""); break; case "icedove %s": System.Diagnostics.Process.Start("thunderbird", " -compose \"subject=my photos,attachment='" + mail_attach + "'\""); break; case "mozilla-thunderbird %s": System.Diagnostics.Process.Start("mozilla-thunderbird", " -compose \"subject=my photos,attachment='" + mail_attach + "'\""); break; case "seamonkey -mail -compose %s": System.Diagnostics.Process.Start("seamonkey", " -mail -compose \"subject=my photos,attachment='" + mail_attach + "'\""); break; case "kmail %s": System.Diagnostics.Process.Start("kmail", " --composer --subject \"my photos\"" + mail_attach); break; default: GnomeUtil.UrlShow(parent_window, "mailto:?subject=my%20photos" + mail_attach); break; } // Check if we have any temporary files to be deleted if (tmp_paths.Count > 0) { // Fetch timeout value from preferences. In seconds. Needs to be multiplied with 1000 to get msec uint delete_timeout; delete_timeout = (uint)((int)Preferences.Get(Preferences.EXPORT_EMAIL_DELETE_TIMEOUT_SEC)); delete_timeout = delete_timeout * 1000; // to get milliseconds. // Start a timer and when it occurs, delete the temp files. GLib.Timeout.Add(delete_timeout, new GLib.TimeoutHandler(DeleteTempFile)); } } }
public SendEmail(IBrowsableCollection selection, Window parent_window) : base("mail_dialog.ui", "mail_dialog") { this.selection = selection; this.parent_window = parent_window; foreach (var p in selection.Items) { if (FileFactory.NewForUri(p.DefaultVersion.Uri).QueryInfo("standard::content-type", FileQueryInfoFlags.None, null).ContentType != "image/jpeg") { force_original = true; } } if (force_original) { original_size.Active = true; tiny_size.Sensitive = false; small_size.Sensitive = false; medium_size.Sensitive = false; large_size.Sensitive = false; x_large_size.Sensitive = false; } else { switch (Preferences.Get <int> (Preferences.EXPORT_EMAIL_SIZE)) { case 0: original_size.Active = true; break; case 1: tiny_size.Active = true; break; case 2: small_size.Active = true; break; case 3: medium_size.Active = true; break; case 4: large_size.Active = true; break; case 5: x_large_size.Active = true; break; default: break; } } tray_scrolled.Add(new TrayView(selection)); Modal = false; // Calculate total original filesize foreach (var photo in selection.Items) { try { Orig_Photo_Size += FileFactory.NewForUri(photo.DefaultVersion.Uri).QueryInfo("standard::size", FileQueryInfoFlags.None, null).Size; } catch { } } for (int k = 0; k < avg_scale_ref.Length; k++) { avg_scale[k] = avg_scale_ref[k]; } // Calculate approximate size shrinking, use first photo, and shrink to medium size as base. var scalephoto = selection [0]; if (scalephoto != null && !force_original) { // Get first photos file size long orig_size = FileFactory.NewForUri(scalephoto.DefaultVersion.Uri).QueryInfo("standard::size", FileQueryInfoFlags.None, null).Size; FilterSet filters = new FilterSet(); filters.Add(new ResizeFilter((uint)(sizes [3]))); long new_size; using (FilterRequest request = new FilterRequest(scalephoto.DefaultVersion.Uri)) { filters.Convert(request); new_size = FileFactory.NewForUri(request.Current).QueryInfo("standard::size", FileQueryInfoFlags.None, null).Size; } if (orig_size > 0) { // Get the factor (scale) between original and resized medium size. scale_percentage = 1 - ((float)(orig_size - new_size) / orig_size); // What is the relation between the estimated medium scale factor, and reality? double scale_scale = scale_percentage / avg_scale_ref[3]; //System.Console.WriteLine ("scale_percentage {0}, ref {1}, relative {2}", // scale_percentage, avg_scale_ref[3], scale_scale ); // Re-Calculate the proper relation per size for (int k = 0; k < avg_scale_ref.Length; k++) { avg_scale[k] = avg_scale_ref[k] * scale_scale; // System.Console.WriteLine ("avg_scale[{0}]={1} (was {2})", // k, avg_scale[k], avg_scale_ref[k] ); } } } NumberOfPictures.Text = selection.Count.ToString(); TotalOriginalSize.Text = GLib.Format.SizeForDisplay(Orig_Photo_Size); UpdateEstimatedSize(); ShowAll(); //LoadHistory (); Response += HandleResponse; }
private void Upload() { album.UploadProgress += HandleUploadProgress; sent_bytes = 0; approx_size = 0; System.Console.WriteLine("Starting Upload to Picasa"); FilterSet filters = new FilterSet(); filters.Add(new JpegFilter()); if (scale) { filters.Add(new ResizeFilter((uint)size)); } if (rotate) { filters.Add(new OrientationFilter()); } while (photo_index < items.Length) { try { IBrowsableItem item = items[photo_index]; FileInfo file_info; Console.WriteLine("uploading {0}", photo_index); progress_dialog.Message = String.Format(Catalog.GetString("Uploading picture \"{0}\" ({1} of {2})"), item.Name, photo_index + 1, items.Length); photo_index++; FilterRequest request = new FilterRequest(item.DefaultVersionUri); filters.Convert(request); file_info = new FileInfo(request.Current.LocalPath); if (approx_size == 0) //first image { approx_size = file_info.Length * items.Length; } else { approx_size = sent_bytes * items.Length / (photo_index - 1); } PicasaPicture picture = album.UploadPicture(request.Current.LocalPath, Path.ChangeExtension(item.Name, "jpg"), item.Description); if (Core.Database != null && item is Photo) { Core.Database.Exports.Create((item as Photo).Id, (item as Photo).DefaultVersionId, ExportStore.PicasaExportType, picture.Link); } sent_bytes += file_info.Length; request.Dispose(); //tagging if (item.Tags != null) { foreach (Tag tag in item.Tags) { picture.AddTag(tag.Name); } } } catch (System.Exception e) { progress_dialog.Message = String.Format(Catalog.GetString("Error Uploading To Gallery: {0}"), e.Message); progress_dialog.ProgressText = Catalog.GetString("Error"); System.Console.WriteLine(e); if (progress_dialog.PerformRetrySkip()) { photo_index--; } } } progress_dialog.Message = Catalog.GetString("Done Sending Photos"); progress_dialog.Fraction = 1.0; progress_dialog.ProgressText = Catalog.GetString("Upload Complete"); progress_dialog.ButtonLabel = Gtk.Stock.Ok; if (browser) { GnomeUtil.UrlShow(null, album.Link); } }
void zip() { System.Uri dest = new System.Uri(uri_chooser.Uri); Crc32 crc = new Crc32(); string filedest = dest.LocalPath + "/" + filename.Text; Log.DebugFormat("Creating zip file {0}", filedest); ZipOutputStream s = new ZipOutputStream(File.Create(filedest)); if (scale_check.Active) { Log.DebugFormat("Scaling to {0}", scale_size.ValueAsInt); } ProgressDialog progress_dialog = new ProgressDialog(Catalog.GetString("Exporting files"), ProgressDialog.CancelButtonType.Stop, photos.Length, zipdiag); //Pack up for (int i = 0; i < photos.Length; i++) { if (progress_dialog.Update(string.Format(Catalog.GetString("Preparing photo \"{0}\""), photos[i].Name))) { progress_dialog.Destroy(); return; } string f = null; // FIXME: embed in a try/catch if (scale_check.Active) { FilterSet filters = new FilterSet(); filters.Add(new JpegFilter()); filters.Add(new ResizeFilter((uint)scale_size.ValueAsInt)); FilterRequest freq = new FilterRequest(photos [i].DefaultVersion.Uri); filters.Convert(freq); f = freq.Current.LocalPath; } else { f = photos [i].DefaultVersion.Uri.LocalPath; } FileStream fs = File.OpenRead(f); byte [] buffer = new byte [fs.Length]; fs.Read(buffer, 0, buffer.Length); ZipEntry entry = new ZipEntry(System.IO.Path.GetFileName(photos [i].DefaultVersion.Uri.LocalPath)); entry.DateTime = DateTime.Now; entry.Size = fs.Length; fs.Close(); crc.Reset(); crc.Update(buffer); entry.Crc = crc.Value; s.PutNextEntry(entry); s.Write(buffer, 0, buffer.Length); } s.Finish(); s.Close(); if (progress_dialog != null) { progress_dialog.Destroy(); } }
public void Upload() { // FIXME: use mkstemp try { ThreadAssist.ProxyToMain(Dialog.Hide); GLib.File source = GLib.FileFactory.NewForPath(Path.Combine(gallery_path, gallery_name)); GLib.File target = GLib.FileFactory.NewForPath(Path.Combine(dest.Path, source.Basename)); if (dest.IsNative) { gallery_path = dest.Path; } progress_dialog.Message = Catalog.GetString("Building Gallery"); progress_dialog.Fraction = 0.0; FolderGallery gallery; if (static_radio.Active) { gallery = new HtmlGallery(selection, gallery_path, gallery_name); } else if (original_radio.Active) { gallery = new OriginalGallery(selection, gallery_path, gallery_name); } else { gallery = new FolderGallery(selection, gallery_path, gallery_name); } if (scale) { Log.DebugFormat("Resize Photos to {0}.", size); gallery.SetScale(size); } else { Log.Debug("Exporting full size."); } if (exportTags) { gallery.ExportTags = true; } if (exportTagIcons) { gallery.ExportTagIcons = true; } gallery.Description = description; gallery.GenerateLayout(); FilterSet filter_set = new FilterSet(); if (scale) { filter_set.Add(new ResizeFilter((uint)size)); } filter_set.Add(new ChmodFilter()); filter_set.Add(new UniqueNameFilter(new SafeUri(gallery_path))); for (int photo_index = 0; photo_index < selection.Count; photo_index++) { try { progress_dialog.Message = System.String.Format(Catalog.GetString("Exporting \"{0}\"..."), selection[photo_index].Name); progress_dialog.Fraction = photo_index / (double)selection.Count; gallery.ProcessImage(photo_index, filter_set); progress_dialog.ProgressText = System.String.Format(Catalog.GetString("{0} of {1}"), (photo_index + 1), selection.Count); } catch (Exception e) { Log.Error(e.ToString()); progress_dialog.Message = String.Format(Catalog.GetString("Error Copying \"{0}\" to Gallery:{2}{1}"), selection[photo_index].Name, e.Message, Environment.NewLine); progress_dialog.ProgressText = Catalog.GetString("Error"); if (progress_dialog.PerformRetrySkip()) { photo_index--; } } } // create the zip tarballs for original if (gallery is OriginalGallery) { bool include_tarballs; try { include_tarballs = Preferences.Get <bool> (INCLUDE_TARBALLS_KEY); } catch (NullReferenceException) { include_tarballs = true; Preferences.Set(INCLUDE_TARBALLS_KEY, true); } if (include_tarballs) { (gallery as OriginalGallery).CreateZip(); } } // we've created the structure, now if the destination was local (native) we are done // otherwise we xfer if (!dest.IsNative) { Log.DebugFormat("Transferring \"{0}\" to \"{1}\"", source.Path, target.Path); progress_dialog.Message = String.Format(Catalog.GetString("Transferring to \"{0}\""), target.Path); progress_dialog.ProgressText = Catalog.GetString("Transferring..."); source.CopyRecursive(target, GLib.FileCopyFlags.Overwrite, new GLib.Cancellable(), Progress); } // No need to check result here as if result is not true, an Exception will be thrown before progress_dialog.Message = Catalog.GetString("Export Complete."); progress_dialog.Fraction = 1.0; progress_dialog.ProgressText = Catalog.GetString("Exporting Photos Completed."); progress_dialog.ButtonLabel = Gtk.Stock.Ok; if (open) { Log.DebugFormat(String.Format("Open URI \"{0}\"", target.Uri.ToString())); ThreadAssist.ProxyToMain(() => { GtkBeans.Global.ShowUri(Dialog.Screen, target.Uri.ToString()); }); } // Save these settings for next time Preferences.Set(SCALE_KEY, scale); Preferences.Set(SIZE_KEY, size); Preferences.Set(OPEN_KEY, open); Preferences.Set(EXPORT_TAGS_KEY, exportTags); Preferences.Set(EXPORT_TAG_ICONS_KEY, exportTagIcons); Preferences.Set(METHOD_KEY, static_radio.Active ? "static" : original_radio.Active ? "original" : "folder"); Preferences.Set(URI_KEY, uri_chooser.Uri); } catch (System.Exception e) { Log.Error(e.ToString()); progress_dialog.Message = e.ToString(); progress_dialog.ProgressText = Catalog.GetString("Error Transferring"); } finally { // if the destination isn't local then we want to remove the temp directory we // created. if (!dest.IsNative) { System.IO.Directory.Delete(gallery_path, true); } ThreadAssist.ProxyToMain(() => { Dialog.Destroy(); }); } }
/// <summary> /// Creates an AMQP link for use with receiving operations. /// </summary> /// /// <param name="connection">The active and opened AMQP connection to use for this link.</param> /// <param name="endpoint">The fully qualified endpoint to open the link for.</param> /// <param name="eventPosition">The position of the event in the partition where the link should be filtered to.</param> /// <param name="consumerOptions">The set of active options for the consumer that will make use of the link.</param> /// <param name="timeout">The timeout to apply when creating the link.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param> /// /// <returns>A link for use for operations related to receiving events.</returns> /// protected virtual async Task <ReceivingAmqpLink> CreateReceivingLinkAsync(AmqpConnection connection, Uri endpoint, EventPosition eventPosition, EventHubConsumerOptions consumerOptions, TimeSpan timeout, CancellationToken cancellationToken) { Argument.AssertNotDisposed(IsDisposed, nameof(AmqpConnectionScope)); cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>(); var session = default(AmqpSession); var stopWatch = Stopwatch.StartNew(); try { // Perform the initial authorization for the link. var authClaims = new[] { EventHubsClaim.Listen }; var authExpirationUtc = await RequestAuthorizationUsingCbsAsync(connection, TokenProvider, endpoint, endpoint.AbsoluteUri, endpoint.AbsoluteUri, authClaims, timeout.CalculateRemaining(stopWatch.Elapsed)).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>(); // Create and open the AMQP session associated with the link. var sessionSettings = new AmqpSessionSettings { Properties = new Fields() }; session = connection.CreateSession(sessionSettings); await OpenAmqpObjectAsync(session, timeout).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>(); // Create and open the link. var filters = new FilterSet(); filters.Add(AmqpFilter.ConsumerFilterName, AmqpFilter.CreateConsumerFilter(AmqpFilter.BuildFilterExpression(eventPosition))); var linkSettings = new AmqpLinkSettings { Role = true, TotalLinkCredit = (uint)consumerOptions.PrefetchCount, AutoSendFlow = consumerOptions.PrefetchCount > 0, SettleType = SettleMode.SettleOnSend, Source = new Source { Address = endpoint.AbsolutePath, FilterSet = filters }, Target = new Target { Address = Guid.NewGuid().ToString() } }; linkSettings.AddProperty(AmqpProperty.EntityType, (int)AmqpProperty.Entity.ConsumerGroup); if (!string.IsNullOrEmpty(consumerOptions.Identifier)) { linkSettings.AddProperty(AmqpProperty.ConsumerIdentifier, consumerOptions.Identifier); } if (consumerOptions.OwnerLevel.HasValue) { linkSettings.AddProperty(AmqpProperty.OwnerLevel, consumerOptions.OwnerLevel.Value); } if (consumerOptions.TrackLastEnqueuedEventInformation) { linkSettings.DesiredCapabilities = new Multiple <AmqpSymbol>(new List <AmqpSymbol> { AmqpProperty.TrackLastEnqueuedEventInformation }); } var link = new ReceivingAmqpLink(linkSettings); linkSettings.LinkName = $"{ Id };{ connection.Identifier };{ session.Identifier };{ link.Identifier }"; link.AttachTo(session); stopWatch.Stop(); // Configure refresh for authorization of the link. var refreshTimer = default(Timer); var refreshHandler = CreateAuthorizationRefreshHandler ( connection, link, TokenProvider, endpoint, endpoint.AbsoluteUri, endpoint.AbsoluteUri, authClaims, AuthorizationRefreshTimeout, () => refreshTimer ); refreshTimer = new Timer(refreshHandler, null, CalculateLinkAuthorizationRefreshInterval(authExpirationUtc), Timeout.InfiniteTimeSpan); // Track the link before returning it, so that it can be managed with the scope. BeginTrackingLinkAsActive(link, refreshTimer); return(link); } catch { // Aborting the session will perform any necessary cleanup of // the associated link as well. session?.Abort(); throw; } }
private void Upload() { sent_bytes = 0; approx_size = 0; System.Uri album_uri = null; System.Console.WriteLine("Starting Upload to Smugmug, album {0} - {1}", album.Title, album.AlbumID); FilterSet filters = new FilterSet(); filters.Add(new JpegFilter()); if (scale) { filters.Add(new ResizeFilter((uint)size)); } if (rotate) { filters.Add(new OrientationFilter()); } while (photo_index < items.Length) { try { IBrowsableItem item = items[photo_index]; FileInfo file_info; Console.WriteLine("uploading {0}", photo_index); progress_dialog.Message = String.Format(Catalog.GetString("Uploading picture \"{0}\" ({1} of {2})"), item.Name, photo_index + 1, items.Length); progress_dialog.ProgressText = string.Empty; progress_dialog.Fraction = ((photo_index) / (double)items.Length); photo_index++; FilterRequest request = new FilterRequest(item.DefaultVersionUri); filters.Convert(request); file_info = new FileInfo(request.Current.LocalPath); if (approx_size == 0) //first image { approx_size = file_info.Length * items.Length; } else { approx_size = sent_bytes * items.Length / (photo_index - 1); } int image_id = account.SmugMug.Upload(request.Current.LocalPath, album.AlbumID); if (Core.Database != null) { Core.Database.Exports.Create((item as Photo).Id, (item as Photo).DefaultVersionId, ExportStore.SmugMugExportType, account.SmugMug.GetAlbumUrl(image_id).ToString()); } sent_bytes += file_info.Length; if (album_uri == null) { album_uri = account.SmugMug.GetAlbumUrl(image_id); } } catch (System.Exception e) { progress_dialog.Message = String.Format(Mono.Unix.Catalog.GetString("Error Uploading To Gallery: {0}"), e.Message); progress_dialog.ProgressText = Mono.Unix.Catalog.GetString("Error"); System.Console.WriteLine(e); if (progress_dialog.PerformRetrySkip()) { photo_index--; } } } progress_dialog.Message = Catalog.GetString("Done Sending Photos"); progress_dialog.Fraction = 1.0; progress_dialog.ProgressText = Mono.Unix.Catalog.GetString("Upload Complete"); progress_dialog.ButtonLabel = Gtk.Stock.Ok; if (browser && album_uri != null) { GnomeUtil.UrlShow(null, album_uri.ToString()); } }
void Upload() { progress_item = new ProgressItem(); progress_item.Changed += HandleProgressChanged; fr.Connection.OnUploadProgress += HandleFlickrProgress; var ids = new List <string> (); IPhoto [] photos = selection.Items.ToArray(); Array.Sort(photos, new DateComparer()); for (int index = 0; index < photos.Length; index++) { try { IPhoto photo = photos [index]; progress_dialog.Message = string.Format( Catalog.GetString("Uploading picture \"{0}\""), photo.Name); progress_dialog.Fraction = photo_index / (double)selection.Count; photo_index++; progress_dialog.ProgressText = string.Format( Catalog.GetString("{0} of {1}"), photo_index, selection.Count); info = new FileInfo(photo.DefaultVersion.Uri.LocalPath); var stack = new FilterSet(); if (scale) { stack.Add(new ResizeFilter((uint)size)); } string id = fr.Upload(photo, stack, is_public, is_family, is_friend); ids.Add(id); if (App.Instance.Database != null && photo is Photo) { App.Instance.Database.Exports.Create((photo as Photo).Id, (photo as Photo).DefaultVersionId, ExportStore.FlickrExportType, token.UserId + ":" + token.Username + ":" + current_service.Name + ":" + id); } } catch (Exception e) { progress_dialog.Message = string.Format(Catalog.GetString("Error Uploading To {0}: {1}"), current_service.Name, e.Message); progress_dialog.ProgressText = Catalog.GetString("Error"); Log.Exception(e); if (progress_dialog.PerformRetrySkip()) { index--; photo_index--; } } } progress_dialog.Message = Catalog.GetString("Done Sending Photos"); progress_dialog.Fraction = 1.0; progress_dialog.ProgressText = Catalog.GetString("Upload Complete"); progress_dialog.ButtonLabel = Gtk.Stock.Ok; if (open && ids.Count != 0) { string view_url; if (current_service.Name == "Zooomr.com") { view_url = string.Format("http://www.{0}/photos/{1}/", current_service.Name, token.Username); } else { view_url = string.Format("http://www.{0}/tools/uploader_edit.gne?ids", current_service.Name); bool first = true; foreach (string id in ids) { view_url = view_url + (first ? "=" : ",") + id; first = false; } } GtkBeans.Global.ShowUri(Dialog.Screen, view_url); } }
void CreatePhotoWall() { dir_tmp = System.IO.Path.GetTempFileName(); System.IO.File.Delete(dir_tmp); System.IO.Directory.CreateDirectory(dir_tmp); dir_tmp += "/"; //Prepare the pictures ProgressDialog progress_dialog = null; progress_dialog = new ProgressDialog(Catalog.GetString("Preparing selected pictures"), ProgressDialog.CancelButtonType.Stop, App.Instance.Organizer.SelectedPhotos().Length, picturetile_dialog); FilterSet filters = new FilterSet(); filters.Add(new JpegFilter()); uint counter = 0; List <Tag> all_tags = new List <Tag> (); foreach (Photo p in App.Instance.Organizer.SelectedPhotos()) { if (progress_dialog.Update(String.Format(Catalog.GetString("Processing \"{0}\""), p.Name))) { progress_dialog.Destroy(); DeleteTmp(); return; } //Store photo tags, to attach them later on import foreach (Tag tag in p.Tags) { if (!all_tags.Contains(tag)) { all_tags.Add(tag); } } //FIXME should switch to retry/skip if (!GLib.FileFactory.NewForUri(p.DefaultVersion.Uri).Exists) { Log.WarningFormat("Couldn't access photo {0} while creating mosaics", p.DefaultVersion.Uri.LocalPath); continue; } using (FilterRequest freq = new FilterRequest(p.DefaultVersion.Uri)) { filters.Convert(freq); File.Copy(freq.Current.LocalPath, String.Format("{0}{1}.jpg", dir_tmp, counter++)); } } if (progress_dialog != null) { progress_dialog.Destroy(); } photo_tags = all_tags.ToArray(); string uniform = ""; if (uniform_images.Active) { uniform = "--uniform"; } string output_format = "jpeg"; if (tiff_radio.Active) { output_format = "tiff"; } string scale = String.Format(CultureInfo.InvariantCulture, "{0,4}", (double)image_scale.Value / (double)100); destfile_tmp = String.Format("{0}.{1}", System.IO.Path.GetTempFileName(), output_format); //Execute picturetile string picturetile_command = String.Format("--size {0}x{1} " + "--directory {2} " + "--scale {3} " + "--margin {4} " + "--border {5} " + "--background {6} " + "--pages {7} " + "{8} " + "{9}", x_max_size.Text, y_max_size.Text, dir_tmp, scale, space_between_images.Text, outside_border.Text, colors [background_color.Active], pages.Text, uniform, destfile_tmp); Log.Debug("Executing: picturetile.pl " + picturetile_command); System.Diagnostics.Process pt_exe = System.Diagnostics.Process.Start("picturetile.pl", picturetile_command); pt_exe.WaitForExit(); // Handle multiple files generation (pages). // If the user wants 2 pages (images), and the output filename is out.jpg, picturetile will create // /tmp/out1.jpg and /tmp/out2.jpg. System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(System.IO.Path.GetDirectoryName(destfile_tmp)); string filemask = System.IO.Path.GetFileNameWithoutExtension(destfile_tmp) + "*" + System.IO.Path.GetExtension(destfile_tmp); FileInfo [] fi = di.GetFiles(filemask); // Move generated files to f-spot photodir string [] photo_import_list = new string [fi.Length]; counter = 0; foreach (FileInfo f in fi) { string orig = System.IO.Path.Combine(f.DirectoryName, f.Name); photo_import_list [counter++] = MoveFile(orig); } //Add the pic(s) to F-Spot! Db db = App.Instance.Database; ImportCommand command = new ImportCommand(null); if (command.ImportFromPaths(db.Photos, photo_import_list, photo_tags) > 0) { InfoDialog(Catalog.GetString("PhotoWall generated!"), Catalog.GetString("Your photo wall have been generated and imported in F-Spot. Select the last roll to see it"), Gtk.MessageType.Info); } else { InfoDialog(Catalog.GetString("Error importing photowall"), Catalog.GetString("An error occurred while importing the newly generated photowall to F-Spot"), Gtk.MessageType.Error); } DeleteTmp(); }