Esempio n. 1
0
        public async Task <string> Upload(ICaptureDetails captureDetails, ISurface surfaceToUpload)
        {
            try
            {
                string url;
                using (var pleaseWaitForm = new PleaseWaitForm("GooglePhotos", _googlePhotosLanguage.CommunicationWait))
                {
                    pleaseWaitForm.Show();
                    try
                    {
                        url = await UploadToPicasa(surfaceToUpload);
                    }
                    finally
                    {
                        pleaseWaitForm.Close();
                    }
                }

                if (url != null && _googlePhotosConfiguration.AfterUploadLinkToClipBoard)
                {
                    ClipboardHelper.SetClipboardData(url);
                }
                return(url);
            }
            catch (Exception e)
            {
                Log.Error().WriteLine(e, "Error uploading.");
                MessageBox.Show(_googlePhotosLanguage.UploadFailure + " " + e.Message);
            }
            return(null);
        }
Esempio n. 2
0
        /// <summary>
        ///     displays options dialog (if not disabled via settings) and windows
        ///     print dialog.
        /// </summary>
        /// <returns>printer settings if actually printed, or null if print was cancelled or has failed</returns>
        public PrinterSettings PrintTo(string printerName)
        {
            PrinterSettings returnPrinterSettings = null;
            var             printOptionsResult    = ShowPrintOptionsDialog();

            try
            {
                if (printOptionsResult == null || printOptionsResult == DialogResult.OK)
                {
                    _printDocument.PrinterSettings.PrinterName = printerName;
                    if (!IsColorPrint())
                    {
                        _printDocument.DefaultPageSettings.Color = false;
                    }
                    _printDocument.Print();
                    returnPrinterSettings = _printDocument.PrinterSettings;
                }
            }
            catch (Exception e)
            {
                Log.Error().WriteLine(e, "An error ocurred while trying to print");
                MessageBox.Show(Language.GetString(LangKey.print_error), Language.GetString(LangKey.error));
            }
            return(returnPrinterSettings);
        }
Esempio n. 3
0
        public void Start()
        {
            if (_gcHandle != null)
            {
                return;
            }

            try
            {
                var resources = new ResourceManager("Greenshot.Sounds", Assembly.GetExecutingAssembly());
                _soundBuffer = (byte[])resources.GetObject("camera");

                if (_coreConfiguration.NotificationSound != null && _coreConfiguration.NotificationSound.EndsWith(".wav"))
                {
                    try
                    {
                        if (File.Exists(_coreConfiguration.NotificationSound))
                        {
                            _soundBuffer = File.ReadAllBytes(_coreConfiguration.NotificationSound);
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Warn().WriteLine("couldn't load {0}: {1}", _coreConfiguration.NotificationSound, ex.Message);
                    }
                }
                // Pin sound so it can't be moved by the Garbage Collector, this was the cause for the bad sound
                _gcHandle = GCHandle.Alloc(_soundBuffer, GCHandleType.Pinned);
            }
            catch (Exception e)
            {
                Log.Error().WriteLine(e, "Error initializing.");
            }
        }
Esempio n. 4
0
 /// <summary>
 ///     The SetDataObject will lock/try/catch clipboard operations making it save and not show exceptions.
 ///     The bool "copy" is used to decided if the information stays on the clipboard after exit.
 /// </summary>
 /// <param name="ido"></param>
 /// <param name="copy"></param>
 private static void SetDataObject(IDataObject ido, bool copy)
 {
     lock (ClipboardLockObject)
     {
         // Clear first, this seems to solve some issues
         try
         {
             Clipboard.Clear();
         }
         catch (Exception clearException)
         {
             Log.Warn().WriteLine(clearException.Message);
         }
         try
         {
             // For BUG-1935 this was changed from looping ourselfs, or letting MS retry...
             Clipboard.SetDataObject(ido, copy, 15, 200);
         }
         catch (Exception clipboardSetException)
         {
             string messageText;
             var    clipboardOwner = GetClipboardOwner();
             if (clipboardOwner != null)
             {
                 messageText = Language.GetFormattedString("clipboard_inuse", clipboardOwner);
             }
             else
             {
                 messageText = Language.GetString("clipboard_error");
             }
             Log.Error().WriteLine(clipboardSetException, messageText);
         }
     }
 }
Esempio n. 5
0
        protected override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails)
        {
            var exportInformation = new ExportInformation(Designation, Description);

            if (_page == null)
            {
                try
                {
                    exportInformation.ExportMade = OneNoteExporter.ExportToNewPage(surface);
                }
                catch (Exception ex)
                {
                    exportInformation.ErrorMessage = ex.Message;
                    Log.Error().WriteLine(ex);
                }
            }
            else
            {
                try
                {
                    exportInformation.ExportMade = OneNoteExporter.ExportToPage(surface, _page);
                }
                catch (Exception ex)
                {
                    exportInformation.ErrorMessage = ex.Message;
                    Log.Error().WriteLine(ex);
                }
            }
            return(exportInformation);
        }
Esempio n. 6
0
        /// <summary>
        ///     Show the "please wait" form, execute the code from the delegate and wait until execution finishes.
        ///     The supplied delegate will be wrapped with a try/catch so this method can return any exception that was thrown.
        /// </summary>
        /// <param name="title">The title of the form (and Thread)</param>
        /// <param name="text">The text in the form</param>
        /// <param name="waitDelegate">delegate { with your code }</param>
        public void ShowAndWait(string title, string text, ThreadStart waitDelegate)
        {
            _title = title;
            Text   = title;
            label_pleasewait.Text = text;
            cancelButton.Text     = Language.GetString("CANCEL");

            // Make sure the form is shown.
            Show();

            // Variable to store the exception, if one is generated, from inside the thread.
            Exception threadException = null;

            try
            {
                // Wrap the passed delegate in a try/catch which makes it possible to save the exception
                _waitFor = new Thread(() =>
                {
                    try
                    {
                        waitDelegate.Invoke();
                    }
                    catch (Exception ex)
                    {
                        Log.Error().WriteLine(ex, "invoke error:");
                        threadException = ex;
                    }
                }
                                      )
                {
                    Name         = title,
                    IsBackground = true
                };
                _waitFor.SetApartmentState(ApartmentState.STA);
                _waitFor.Start();

                // Wait until finished
                while (!_waitFor.Join(TimeSpan.FromMilliseconds(100)))
                {
                    Application.DoEvents();
                }
                Log.Debug().WriteLine("Finished {0}", title);
            }
            catch (Exception ex)
            {
                Log.Error().WriteLine(ex);
                throw;
            }
            finally
            {
                Close();
            }
            // Check if an exception occured, if so throw it
            if (threadException != null)
            {
                throw threadException;
            }
        }
Esempio n. 7
0
        /// <summary>
        ///     Helper Method to get the IHTMLDocument2
        /// </summary>
        /// <param name="mainWindow"></param>
        /// <returns></returns>
        private static IHTMLDocument2 GetHtmlDocument(IInteropWindow mainWindow)
        {
            var ieServer = "Internet Explorer_Server".Equals(mainWindow.GetClassname())
                                ? mainWindow
                                : mainWindow.GetChildren().FirstOrDefault(window => window.GetClassname() == "Internet Explorer_Server");

            if (ieServer == null)
            {
                Log.Warn().WriteLine("No Internet Explorer_Server for {0}", mainWindow.Text);
                return(null);
            }

            var windowMessage = WindowsMessage.RegisterWindowsMessage("WM_HTML_GETOBJECT");

            if (windowMessage == 0)
            {
                Log.Warn().WriteLine("Couldn't register WM_HTML_GETOBJECT");
                return(null);
            }

            Log.Debug().WriteLine("Trying WM_HTML_GETOBJECT on {0}", ieServer.Classname);
            if (User32Api.TrySendMessage(ieServer.Handle, windowMessage, IntPtr.Zero, out UIntPtr response))
            {
                var document2 = (IHTMLDocument2)Accessible.ObjectFromLresult(response, typeof(IHTMLDocument).GUID, IntPtr.Zero);
                if (document2 != null)
                {
                    return(document2);
                }
                Log.Error().WriteLine(null, "No IHTMLDocument2 found");
                return(null);
            }
            Log.Error().WriteLine(null, "No answer on WM_HTML_GETOBJECT.");
            return(null);
        }
Esempio n. 8
0
        /// <inheritdoc />
        public async Task <object> ConvertFromHttpContentAsync(Type resultType, HttpContent httpContent, CancellationToken cancellationToken = default)
        {
            if (!CanConvertFromHttpContent(resultType, httpContent))
            {
                throw new NotSupportedException("CanConvertFromHttpContent resulted in false, this is not supposed to be called.");
            }

            var jsonString = await httpContent.ReadAsStringAsync().ConfigureAwait(false);

            // Check if verbose is enabled, if so log but only up to a certain size
            if (Log.IsVerboseEnabled())
            {
                var defaultJsonHttpContentConverterConfiguration = HttpBehaviour.Current.GetConfig <DefaultJsonHttpContentConverterConfiguration>();
                var logThreshold = defaultJsonHttpContentConverterConfiguration.LogThreshold;

                if (logThreshold > 0)
                {
                    Log.Verbose()
                    .WriteLine("Read Json content: {0}{1}", jsonString.Substring(0, Math.Min(jsonString.Length, logThreshold)),
                               jsonString.Length > logThreshold ? defaultJsonHttpContentConverterConfiguration.AppendedWhenCut : string.Empty);
                }
                else
                {
                    Log.Verbose().WriteLine("Read Json content: {0}", jsonString);
                }
            }
            // Check if we can just pass it back, as the target is string
            if (resultType == typeof(string))
            {
                return(jsonString);
            }
            // empty json should return the default of the resultType
            if (string.IsNullOrEmpty(jsonString))
            {
                if (resultType.GetTypeInfo().IsValueType)
                {
                    return(Activator.CreateInstance(resultType));
                }
                return(null);
            }
            var httpBehaviour = HttpBehaviour.Current;

            try
            {
                return(httpBehaviour.JsonSerializer.Deserialize(resultType == typeof(object) ? null : resultType, jsonString));
            }
            catch (SerializationException sEx)
            {
                // Make sure that the content which can't be deserialized is visible in the log.
                Log.Error().WriteLine(sEx, "Can't deserialize the JSON from the server.");
                Log.Error().WriteLine(jsonString);
                throw;
            }
        }
Esempio n. 9
0
        /// <summary>
        ///     Create an observable for the INotifyPropertyChanged
        /// </summary>
        /// <param name="source">INotifyPropertyChanged</param>
        /// <param name="propertyNamePattern">Optional property name / pattern</param>
        /// <typeparam name="T">INotifyPropertyChanged</typeparam>
        /// <returns>IObservable with PropertyChangedEventArgs</returns>
        public static IObservable <PropertyChangedEventArgs> OnPropertyChanged <T>(this T source, string propertyNamePattern = null)
            where T : INotifyPropertyChanged
        {
            var observable = Observable.Create <PropertyChangedEventArgs>(observer =>
            {
                PropertyChangedEventHandler handler = (s, e) => observer.OnNext(e);
                source.PropertyChanged += handler;
                return(Disposable.Create(() => source.PropertyChanged -= handler));
            });

            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }

            // Create predicate
            Func <PropertyChangedEventArgs, bool> predicate;

            if (!string.IsNullOrEmpty(propertyNamePattern) && propertyNamePattern != "*")
            {
                predicate = propertyChangedEventArgs =>
                {
                    try
                    {
                        var propertyName = propertyChangedEventArgs.PropertyName;
                        if (string.IsNullOrEmpty(propertyName))
                        {
                            return(true);
                        }
                        if (propertyNamePattern.Contains("*") || propertyNamePattern.Contains("."))
                        {
                            if (Regex.IsMatch(propertyName, propertyNamePattern))
                            {
                                return(true);
                            }
                        }

                        return(propertyName == "*" || propertyNamePattern == propertyName);
                    }
                    catch (Exception ex)
                    {
                        Log.Error().WriteLine(ex, "Error in predicate for OnPropertyChangedPattern");
                    }
                    return(false);
                };
            }
            else
            {
                predicate = args => true;
            }

            return(observable.Where(predicate));
        }
Esempio n. 10
0
 /// <summary>
 ///     Helper method which returns the directory relative to the current directory
 /// </summary>
 /// <param name="directory">directory name</param>
 /// <returns>string directory</returns>
 private static string DirectoryRelativeToCurrentWorkingDirectory(string directory)
 {
     try
     {
         return(Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, directory)).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar));
     }
     catch (Exception ex)
     {
         Log.Error().WriteLine(ex, "Couldn't get the directory {1} relative to the current working directory {0}", Environment.CurrentDirectory, directory);
     }
     return(null);
 }
Esempio n. 11
0
 /// <summary>
 ///     This method will be called by the regexp.replace as a MatchEvaluator delegate!
 ///     Will delegate this to the MatchVarEvaluatorInternal and catch any exceptions
 /// </summary>
 /// <param name="match">What are we matching?</param>
 /// <param name="captureDetails">The detail, can be null</param>
 /// <param name="processVars">Variables from the process</param>
 /// <param name="userVars">Variables from the user</param>
 /// <param name="machineVars">Variables from the machine</param>
 /// <param name="filenameSafeMode"></param>
 /// <returns>string with the match replacement</returns>
 private static string MatchVarEvaluator(Match match, ICaptureDetails captureDetails, IDictionary processVars, IDictionary userVars, IDictionary machineVars,
                                         bool filenameSafeMode)
 {
     try
     {
         return(MatchVarEvaluatorInternal(match, captureDetails, processVars, userVars, machineVars, filenameSafeMode));
     }
     catch (Exception e)
     {
         Log.Error().WriteLine(e, "Error in MatchVarEvaluatorInternal");
     }
     return(string.Empty);
 }
Esempio n. 12
0
        /// <summary>
        ///     Tries to save the changes we just made
        /// </summary>
        /// <param name="mailItem"></param>
        /// <returns></returns>
        public static bool SaveChanges(IMailItem mailItem)
        {
            // Pointer to IUnknown Interface
            var IUnknown = IntPtr.Zero;
            // Pointer to IMAPIProp Interface
            var IMAPIProp = IntPtr.Zero;

            // if we have no MAPIObject everything is senseless...
            if (mailItem == null)
            {
                return(false);
            }

            try
            {
                // We can pass NULL here as parameter, so we do it.
                MAPIInitialize(IntPtr.Zero);
                // retrive the IUnknon Interface from our MAPIObject comming from Outlook.
                IUnknown = Marshal.GetIUnknownForObject(mailItem.MAPIOBJECT);

                // create a Guid that we pass to retreive the IMAPIProp Interface.
                var guidIMAPIProp = new Guid(IID_IMAPIProp);

                // try to retrieve the IMAPIProp interface from IMessage Interface, everything else is sensless.
                if (Marshal.QueryInterface(IUnknown, ref guidIMAPIProp, out IMAPIProp) != 0)
                {
                    return(false);
                }
                var mapiProp = (IMAPIProp)Marshal.GetTypedObjectForIUnknown(IUnknown, typeof(IMAPIProp));
                return(mapiProp.SaveChanges(KEEP_OPEN_READWRITE) == 0);
            }
            catch (Exception ex)
            {
                Log.Error().WriteLine(ex);
                return(false);
            }
            finally
            {
                // cleanup all references to COM Objects
                if (IMAPIProp != IntPtr.Zero)
                {
                    Marshal.Release(IMAPIProp);
                }
                //if (IMessage != IntPtr.Zero) Marshal.Release(IMessage);
                if (IUnknown != IntPtr.Zero)
                {
                    Marshal.Release(IUnknown);
                }
            }
        }
Esempio n. 13
0
        /// <summary>
        ///     Download the FavIcon as a Bitmap
        /// </summary>
        /// <param name="baseUri"></param>
        /// <returns>Bitmap with the FavIcon</returns>
        public static Bitmap DownloadFavIcon(Uri baseUri)
        {
            var url = new Uri(baseUri, new Uri("favicon.ico"));

            try
            {
                var request = CreateWebRequest(url);
                using (var response = (HttpWebResponse)request.GetResponse())
                {
                    if (request.HaveResponse)
                    {
                        using (var responseStream = response.GetResponseStream())
                        {
                            if (responseStream != null)
                            {
                                using (var image = BitmapHelper.FromStream(responseStream))
                                {
                                    return(image.Height > 16 && image.Width > 16 ? new Bitmap(image, 16, 16) : new Bitmap(image));
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Log.Error().WriteLine(e, "Problem downloading the FavIcon from: " + baseUri);
            }
            return(null);
        }
Esempio n. 14
0
        /// <inheritdoc />
        public async Task <object> ConvertFromHttpContentAsync(Type resultType, HttpContent httpContent, CancellationToken cancellationToken = default)
        {
            if (!CanConvertFromHttpContent(resultType, httpContent))
            {
                var exMessage = "CanConvertFromHttpContent resulted in false, ConvertFromHttpContentAsync is not supposed to be called.";
                Log.Error().WriteLine(exMessage);
                throw new NotSupportedException(exMessage);
            }
            var memoryStream =
                (MemoryStream)
                await StreamHttpContentConverter.Instance.Value.ConvertFromHttpContentAsync(typeof(MemoryStream), httpContent, cancellationToken).ConfigureAwait(false);

            Log.Debug().WriteLine("Creating a Bitmap from the MemoryStream.");
            return(new Bitmap(memoryStream));
        }
Esempio n. 15
0
        /// <summary>
        ///     This writes the supplied content to the response of the httpListenerContext
        ///     It's actually a bit overkill, as it convers to HttpContent and writes this to a stream
        ///     But performance and memory usage are currently not our main concern for the HttpListener
        /// </summary>
        /// <typeparam name="TContent">Type of the content</typeparam>
        /// <param name="httpListenerContext">HttpListenerContext</param>
        /// <param name="content">TContent object</param>
        /// <param name="cancellationToken">CancellationToken</param>
        /// <returns>Task</returns>
        public static async Task RespondAsync <TContent>(this HttpListenerContext httpListenerContext, TContent content,
                                                         CancellationToken cancellationToken = default)
            where TContent : class
        {
            HttpContent httpContent;

            if (typeof(HttpContent).IsAssignableFrom(typeof(TContent)))
            {
                httpContent = content as HttpContent;
            }
            else
            {
                httpContent = HttpContentFactory.Create(content);
            }

            using (var response = httpListenerContext.Response)
            {
                if (httpContent is null)
                {
                    Log.Error().WriteLine("Nothing to respond with...");
                    response.StatusCode = (int)HttpStatusCode.InternalServerError;
                    return;
                }
                // Write to response stream.
                response.ContentLength64 = httpContent.Headers?.ContentLength ?? 0;
                response.ContentType     = httpContent.GetContentType();
                response.StatusCode      = (int)HttpStatusCode.OK;
                Log.Debug().WriteLine("Responding with {0}", response.ContentType);
                using (var stream = response.OutputStream)
                {
                    await httpContent.CopyToAsync(stream).ConfigureAwait(false);
                }
            }
        }
Esempio n. 16
0
        /// <summary>
        ///     This method starts a HttpListener to make it possible to listen async for a SINGLE request.
        /// </summary>
        /// <param name="listenUri">
        ///     The Uri to listen to, use CreateFreeLocalHostUri (and add segments) if you don't have a
        ///     specific reason
        /// </param>
        /// <param name="httpListenerContextHandler">A function which gets a HttpListenerContext and returns a value</param>
        /// <param name="cancellationToken">CancellationToken</param>
        /// <returns>The value from the httpListenerContextHandler</returns>
        public static Task <T> ListenAsync <T>(this Uri listenUri, Func <HttpListenerContext, Task <T> > httpListenerContextHandler,
                                               CancellationToken cancellationToken = default)
        {
            var listenUriString = listenUri.AbsoluteUri.EndsWith("/") ? listenUri.AbsoluteUri : listenUri.AbsoluteUri + "/";

            Log.Debug().WriteLine("Start listening on {0}", listenUriString);
            var taskCompletionSource = new TaskCompletionSource <T>(TaskCreationOptions.RunContinuationsAsynchronously);

            // ReSharper disable once UnusedVariable
            var listenTask = Task.Factory.StartNew(async() =>
            {
                using (var httpListener = new HttpListener())
                {
                    try
                    {
                        // Add the URI to listen to, this SHOULD be localhost to prevent a lot of problemens with rights
                        httpListener.Prefixes.Add(listenUriString);
                        // Start listening
                        httpListener.Start();
                        Log.Debug().WriteLine("Started listening on {0}", listenUriString);

                        // Make the listener stop if the token is cancelled.
                        // This registratrion is disposed before the httpListener is disposed:
                        // ReSharper disable once AccessToDisposedClosure
                        var cancellationTokenRegistration = cancellationToken.Register(() => { httpListener.Stop(); });

                        // Get the context
                        var httpListenerContext = await httpListener.GetContextAsync().ConfigureAwait(false);

                        // Call the httpListenerContextHandler with the context we got for the result
                        var result = await httpListenerContextHandler(httpListenerContext).ConfigureAwait(false);

                        // Dispose the registration, so the stop isn't called on a disposed httpListener
                        cancellationTokenRegistration.Dispose();

                        // Set the result to the TaskCompletionSource, so the await on the task finishes
                        taskCompletionSource.TrySetResult(result);
                    }
                    catch (Exception ex)
                    {
                        Log.Error().WriteLine(ex, "Error while wait for or processing a request");

                        // Check if cancel was requested, is so set the taskCompletionSource as cancelled
                        if (cancellationToken.IsCancellationRequested)
                        {
                            taskCompletionSource.TrySetCanceled();
                        }
                        else
                        {
                            // Not cancelled, so we use the exception
                            taskCompletionSource.TrySetException(ex);
                        }
                        throw;
                    }
                }
            }, cancellationToken, TaskCreationOptions.LongRunning, TaskScheduler.Default).ConfigureAwait(false);

            // Return the taskCompletionSource.Task so the caller can await on it
            return(taskCompletionSource.Task);
        }
Esempio n. 17
0
        /// <summary>
        /// Load the complete history of the lutim uploads, with the corresponding information
        /// </summary>
        public static void LoadHistory()
        {
            if (!IsHistoryLoadingNeeded())
            {
                return;
            }

            // Load the ImUr history
            foreach (string key in Config.LutimUploadHistory.Keys.ToList())
            {
                if (Config.RuntimeLutimHistory.ContainsKey(key))
                {
                    // Already loaded
                    continue;
                }

                try
                {
                    var value = Config.LutimUploadHistory[key];
                    // TODO: Read from something
                    //LutimInfo lutimInfo = LutimInfo.FromIniString(key, value);
                    // Config.RuntimeLutimHistory[key] = lutimInfo;
                }
                catch (ArgumentException)
                {
                    Log.Info().WriteLine("Bad format of lutim history item for short {0}", key);
                    Config.LutimUploadHistory.Remove(key);
                    Config.RuntimeLutimHistory.Remove(key);
                }
                catch (Exception e)
                {
                    Log.Error().WriteLine(e, "Problem loading lutim history for short " + key);
                }
            }
        }
Esempio n. 18
0
        /// <inheritdoc />
        protected override async Task <BitmapSource> CreateAsync(string key, CancellationToken cancellationToken = new CancellationToken())
        {
            string path = Path.Combine("TestFiles", key);

            if (!File.Exists(path))
            {
                string location = Assembly.GetExecutingAssembly().Location;
                if (location != null)
                {
                    path = Path.Combine(Path.GetDirectoryName(location), "TestFiles", key);
                }
            }
            if (!File.Exists(path))
            {
                Log.Error().WriteLine("Couldn't find location {0}", path);
                // What is the default here?
                return(null);
            }

            using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                // ReSharper disable once AccessToDisposedClosure
                return(await Task.Run(() => stream.BitmapImageFromStream(), cancellationToken).ConfigureAwait(false));
            }
        }
Esempio n. 19
0
        private async Task ReadValuesAsync()
        {
            double usedHeap    = 0;
            double usedNonHeap = 0;

            try
            {
                var heapMemoryUsage = await _jolokia.ReadAsync <MemoryUsage>(_heapMemoryUsageAttribute);

                var nonHeapMemoryUsage = await _jolokia.ReadAsync <MemoryUsage>(_nonHeapMemoryUsageAttribute);

                usedNonHeap = nonHeapMemoryUsage.Used;
                usedHeap    = heapMemoryUsage.Used;
                Log.Info().WriteLine("heapMemoryUsage: {0}, nonHeapMemoryUsage: {1}", usedHeap, usedNonHeap);
            }
            catch (Exception ex)
            {
                // Ignore
                Log.Error().WriteLine(ex, "Problem retrieving heap usage");
            }
            HeapMemoryValues.Add(usedHeap);
            if (HeapMemoryValues.Count > 10)
            {
                HeapMemoryValues.RemoveAt(0);
            }
            NonHeapMemoryValues.Add(usedNonHeap);
            if (NonHeapMemoryValues.Count > 10)
            {
                NonHeapMemoryValues.RemoveAt(0);
            }
        }
Esempio n. 20
0
        /// <summary>
        ///     This will be called when the menu item in the Editor is clicked
        /// </summary>
        private async Task <string> UploadAsync(ICaptureDetails captureDetails, ISurface surfaceToUpload)
        {
            try
            {
                string url;
                using (var pleaseWaitForm = new PleaseWaitForm("Box", _boxLanguage.CommunicationWait))
                {
                    pleaseWaitForm.Show();
                    try
                    {
                        url = await UploadToBoxAsync(captureDetails, surfaceToUpload).ConfigureAwait(true);
                    }
                    finally
                    {
                        pleaseWaitForm.Close();
                    }
                }

                if (url != null && _boxConfiguration.AfterUploadLinkToClipBoard)
                {
                    ClipboardHelper.SetClipboardData(url);
                }

                return(url);
            }
            catch (Exception ex)
            {
                Log.Error().WriteLine(ex, "Error uploading.");
                MessageBox.Show(_boxLanguage.UploadFailure + " " + ex.Message);
                return(null);
            }
        }
Esempio n. 21
0
 private int GetDbVersion()
 {
     using (var context = new FirebirdContext(this.connectionString))
     {
         int dbVersion = 0;
         try
         {
             dbVersion = context.DbVersion.Max(d => d.Version);
         }
         catch (System.Data.Entity.Core.EntityCommandExecutionException e)
         {
             Log.Error().WriteLine(e.InnerException.ToString());
             if (e.InnerException.ToString().Contains("DBVERSION"))
             {
                 context.Database.ExecuteSqlCommand("CREATE TABLE DBVERSION (DBVERSION int, DESCRIPTION varchar(256))");
                 context.SaveChanges();
                 context.DbVersion.Add(new DbVersionModel()
                 {
                     Version = 1, Descripiton = "Inital Db Version with version table"
                 });
                 context.SaveChanges();
                 Log.Info().WriteLine("Created Table DBVERSION");
                 UpgradeDb();
             }
         }
         Log.Info().WriteLine("DB version is {0}", dbVersion.ToString());
         return(dbVersion);
     }
 }
Esempio n. 22
0
        /// <inheritdoc />
        public async Task <object> ConvertFromHttpContentAsync(Type resultType, HttpContent httpContent, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (!CanConvertFromHttpContent(resultType, httpContent))
            {
                var exMessage = "CanConvertFromHttpContent resulted in false, ConvertFromHttpContentAsync is not supposed to be called.";
                Log.Error().WriteLine(exMessage);
                throw new NotSupportedException(exMessage);
            }
            var httpBehaviour = HttpBehaviour.Current;
            var configuration = httpBehaviour.GetConfig <SvgConfiguration>();

            using (var memoryStream = (MemoryStream)await StreamHttpContentConverter.Instance.Value.ConvertFromHttpContentAsync(typeof(MemoryStream), httpContent, cancellationToken).ConfigureAwait(false))
            {
                Log.Debug().WriteLine("Creating a Bitmap from the SVG.");

                var bitmap = new Bitmap(configuration.Width, configuration.Height, PixelFormat.Format32bppArgb);
                // ImageHelper.CreateEmpty(Width, Height, PixelFormat.Format32bppArgb, Color.Transparent, 96, 96);
                using (var graphics = Graphics.FromImage(bitmap))
                {
                    graphics.Clear(Color.Transparent);
                }

                var svgDoc = SvgDocument.Open <SvgDocument>(memoryStream);
                svgDoc.Width  = configuration.Width;
                svgDoc.Height = configuration.Height;
                svgDoc.Draw(bitmap);
                return(bitmap);
            }
        }
Esempio n. 23
0
        /// <summary>
        /// Checks if this type builder already created the type, or return null if not
        /// </summary>
        /// <param name="fqTypeName">The name of the type</param>
        /// <param name="type">The out variable for the type</param>
        /// <returns>bool with true if found</returns>
        public bool TryGetType(string fqTypeName, out Type type)
        {
            try
            {
                type = _assemblyBuilder.GetTypes().FirstOrDefault(x => x.FullName == fqTypeName);
                if (type == null)
                {
                    type = Type.GetType(fqTypeName);
                    if (type != null)
                    {
                        Log.Verbose().WriteLine("Found Type for {0}", fqTypeName);
                    }
                }
                else
                {
                    Log.Verbose().WriteLine("Found cached instance of {0}", fqTypeName);
                }
            }
            catch (Exception ex)
            {
                Log.Error().WriteLine(ex, "Couldn't find type for {0}", fqTypeName);
                type = null;
            }

            return(type != null);
        }
Esempio n. 24
0
        /// <summary>
        ///     Read the RSS feed to see if there is a Greenshot update
        /// </summary>
        public static void CheckAndAskForUpdate()
        {
            lock (LockObject)
            {
                var currentVersion = Assembly.GetExecutingAssembly().GetName().Version;
                // Test like this:
                // currentVersion = new Version("0.8.1.1198");

                try
                {
                    _latestGreenshot = null;
                    ProcessRssInfo(currentVersion);
                    if (_latestGreenshot != null)
                    {
                        MainForm.Instance.NotifyIcon.BalloonTipClicked += HandleBalloonTipClick;
                        MainForm.Instance.NotifyIcon.BalloonTipClosed  += CleanupBalloonTipClick;
                        MainForm.Instance.NotifyIcon.ShowBalloonTip(10000, "Greenshot", Language.GetFormattedString(LangKey.update_found, "'" + _latestGreenshot.File + "'"),
                                                                    ToolTipIcon.Info);
                    }
                    CoreConfig.LastUpdateCheck = DateTime.Now;
                }
                catch (Exception e)
                {
                    Log.Error().WriteLine(e, "An error occured while checking for updates, the error will be ignored: ");
                }
            }
        }
Esempio n. 25
0
        /// <summary>
        ///     Parse the upload response
        /// </summary>
        /// <param name="response">XML</param>
        /// <returns>PhotobucketInfo object</returns>
        public static PhotobucketInfo FromUploadResponse(string response)
        {
            Log.Debug().WriteLine(response);
            var photobucketInfo = new PhotobucketInfo();

            try
            {
                var doc = new XmlDocument();
                doc.LoadXml(response);
                var nodes = doc.GetElementsByTagName("url");
                if (nodes.Count > 0)
                {
                    photobucketInfo.Original = nodes.Item(0)?.InnerText;
                }
                nodes = doc.GetElementsByTagName("browseurl");
                if (nodes.Count > 0)
                {
                    photobucketInfo.Page = nodes.Item(0)?.InnerText;
                }
                nodes = doc.GetElementsByTagName("thumb");
                if (nodes.Count > 0)
                {
                    photobucketInfo.Thumbnail = nodes.Item(0)?.InnerText;
                }
            }
            catch (Exception e)
            {
                Log.Error().WriteLine("Could not parse Photobucket response due to error {0}, response was: {1}", e.Message, response);
            }
            return(photobucketInfo);
        }
Esempio n. 26
0
        /// <summary>
        /// This runs a periodic task in the background
        /// </summary>
        /// <param name="intervalFactory">Func which returns a TimeSpan</param>
        /// <param name="reoccurringTask">Func which returns a task</param>
        /// <param name="cancellationToken">CancellationToken</param>
        /// <returns>Task</returns>
        private async Task BackgroundTask(Func <TimeSpan> intervalFactory, Func <CancellationToken, Task> reoccurringTask, CancellationToken cancellationToken = default)
        {
            Log.Info().WriteLine("Starting background task");
            await Task.Run(async() =>
            {
                while (true)
                {
                    var interval = intervalFactory();
                    var task     = reoccurringTask;
                    if (TimeSpan.Zero == interval)
                    {
                        interval = TimeSpan.FromMinutes(10);
                        task     = c => Task.FromResult(true);
                    }
                    try
                    {
                        await Task.WhenAll(Task.Delay(interval), task(cancellationToken)).ConfigureAwait(false);
                    }
                    catch (Exception ex)
                    {
                        Log.Error().WriteLine(ex, "Error occured when trying to check for updates.");
                    }
                    if (cancellationToken.IsCancellationRequested)
                    {
                        break;
                    }
                }
            }, cancellationToken).ConfigureAwait(false);

            Log.Info().WriteLine("Finished background task");
        }
Esempio n. 27
0
        private void Run(string[] args)
        {
            // We signal this to shut down the service.
            var cancel = new CancellationTokenSource();

            try
            {
                if (!ParseArguments(args))
                {
                    Environment.ExitCode = -1;
                    return;
                }

                _log.Info(GetVersionString());

                // Control+C will gracefully shut us down.
                Console.CancelKeyPress += (s, e) =>
                {
                    _log.Info("Canceling execution due to received signal.");
                    e.Cancel = true;
                    cancel.Cancel();
                };

                _logic.RunAsync(cancel.Token).WaitAndUnwrapExceptions();

                _log.Info("Application logic execution has completed.");
            }
            catch (OperationCanceledException)
            {
                if (cancel.IsCancellationRequested)
                {
                    // We really were cancelled. That's fine.
                }
                else
                {
                    _log.Error("Unexpected cancellation/timeout halted execution.");
                    Environment.ExitCode = -1;
                }
            }
            catch (Exception ex)
            {
                _log.Error(Helpers.Debug.GetAllExceptionMessages(ex));

                Environment.ExitCode = -1;
            }
        }
Esempio n. 28
0
        private void Contextmenu_capturewindowfromlist_Click(object sender, EventArgs e)
        {
            var clickedItem = (ToolStripMenuItem)sender;

            BeginInvoke((MethodInvoker) delegate
            {
                try
                {
                    var windowToCapture = (InteropWindow)clickedItem.Tag;
                    CaptureHelper.CaptureWindow(windowToCapture);
                }
                catch (Exception exception)
                {
                    Log.Error().WriteLine(exception);
                }
            });
        }
Esempio n. 29
0
        /// <summary>
        ///     Use the credentials dialog, this will show if there are not correct credentials.
        ///     If there are credentials, call the real login.
        /// </summary>
        /// <returns>Task</returns>
        public async Task LoginAsync(CancellationToken cancellationToken = default)
        {
            await LogoutAsync(cancellationToken);

            try
            {
                // Get the system name, so the user knows where to login to
                var credentialsDialog = new CredentialsDialog(_jiraConfiguration.Url)
                {
                    Name = null
                };
                while (credentialsDialog.Show(null, credentialsDialog.Name) == DialogResult.OK)
                {
                    if (await DoLoginAsync(credentialsDialog.Name, credentialsDialog.Password, cancellationToken))
                    {
                        if (credentialsDialog.SaveChecked)
                        {
                            credentialsDialog.Confirm(true);
                        }
                        IsLoggedIn    = true;
                        _loggedInTime = DateTime.Now;
                        return;
                    }
                    // Login failed, confirm this
                    try
                    {
                        credentialsDialog.Confirm(false);
                    }
                    catch (ApplicationException e)
                    {
                        // exception handling ...
                        Log.Error().WriteLine(e, "Problem using the credentials dialog");
                    }
                    // For every windows version after XP show an incorrect password baloon
                    credentialsDialog.IncorrectPassword = true;
                    // Make sure the dialog is display, the password was false!
                    credentialsDialog.AlwaysDisplay = true;
                }
            }
            catch (ApplicationException e)
            {
                // exception handling ...
                Log.Error().WriteLine(e, "Problem using the credentials dialog");
            }
        }
Esempio n. 30
0
 static ConfluenceDestination()
 {
     IsInitialized = false;
     try
     {
         var confluenceIconUri = new Uri("/Greenshot.Addon.Confluence;component/Images/Confluence.ico", UriKind.Relative);
         using (var iconStream = Application.GetResourceStream(confluenceIconUri)?.Stream)
         {
             // TODO: Check what to do with the IBitmap
             ConfluenceIcon = BitmapHelper.FromStream(iconStream);
         }
         IsInitialized = true;
     }
     catch (Exception ex)
     {
         Log.Error().WriteLine("Problem in the confluence static initializer: {0}", ex.Message);
     }
 }