public FormWithAttachedDpiHandler()
        {
            FormDpiHandler = this.AttachDpiHandler();
            InitializeComponent();

            var initialMenuStripSize = menuStrip1.ImageScalingSize;

            FormDpiHandler.OnDpiChanged.Subscribe(dpiChangeInfo =>
            {
                menuStrip1.ImageScalingSize = DpiHandler.ScaleWithDpi(initialMenuStripSize, dpiChangeInfo.NewDpi);
            });

            _scaleHandler = BitmapScaleHandler.WithComponentResourceManager <Bitmap>(FormDpiHandler, GetType(), BitmapScaleHandler.SimpleBitmapScaler)
                            .AddTarget(somethingMenuItem, "somethingMenuItem.Image", b => b)
                            .AddTarget(something2MenuItem, "something2MenuItem.Image", b => b);

            // This can be used to do something with DPI changes, subscription should be disposed!
            _dpiChangeSubscription = FormDpiHandler.OnDpiChanged.Subscribe(dpi =>
            {
                Log.Info().WriteLine("New DPI: {0}", dpi);
            });

            EnvironmentMonitor.EnvironmentUpdateEvents.Subscribe(args =>
            {
                Log.Info().WriteLine("{0} - {1}", args.SystemParametersInfoAction, args.Area);
                MessageBox.Show(this, $@"{args.SystemParametersInfoAction} - {args.Area}", @"Change!");
            });
        }
Ejemplo n.º 2
0
        public async Task TestRunOn()
        {
            var taskSchedulerId = TaskScheduler.Current.Id;

            Log.Info().WriteLine("Current id: {0}", taskSchedulerId);
            UiContext.Initialize();

            var window = new Window
            {
                Width  = 200,
                Height = 200
            };

            window.Show();

            // Should not throw anything
            window.Focus();

            // Make sure the current task scheduler is not for the UI thread
            await Task.Delay(10).ConfigureAwait(false);

            // Should throw
            Assert.Throws <InvalidOperationException>(() => window.Focus());

            // This should also not throw anything
            await UiContext.RunOn(() =>
            {
                var taskSchedulerIdInside = TaskScheduler.Current.Id;
                Log.Info().WriteLine("Current id inside: {0}", taskSchedulerIdInside);
                Assert.NotEqual(taskSchedulerId, taskSchedulerIdInside);
                window.Close();
            });
        }
Ejemplo n.º 3
0
        /// <summary>
        ///     Load an image from file
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        public static Bitmap LoadBitmap(string filename)
        {
            if (string.IsNullOrEmpty(filename))
            {
                return(null);
            }
            if (!File.Exists(filename))
            {
                return(null);
            }
            Bitmap fileBitmap;

            Log.Info().WriteLine("Loading image from file {0}", filename);
            // Fixed lock problem Bug #3431881
            using (Stream imageFileStream = File.OpenRead(filename))
            {
                fileBitmap = FromStream(imageFileStream, Path.GetExtension(filename));
            }
            if (fileBitmap != null)
            {
                Log.Info().WriteLine("Information about file {0}: {1}x{2}-{3} Resolution {4}x{5}", filename, fileBitmap.Width, fileBitmap.Height, fileBitmap.PixelFormat,
                                     fileBitmap.HorizontalResolution, fileBitmap.VerticalResolution);
            }
            return(fileBitmap);
        }
Ejemplo n.º 4
0
 public void Startup()
 {
     _log.Info().WriteLine("Before");
     StartupOrder = _orderProvider.TakeStartupNumber();
     DidStartup   = true;
     _log.Info().WriteLine("After");
 }
Ejemplo n.º 5
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);
     }
 }
Ejemplo n.º 6
0
        /// <inheritdoc />
        public void Start()
        {
            if (!IsClickOnce)
            {
                Log.Info().WriteLine("Application is not deployed via ClickOnce, there will be no checks for updates.");
                return;
            }
            Log.Info().WriteLine("Configuring ClickOnce update handling.");

            CurrentVersion = ApplicationDeployment.CurrentDeployment.CurrentVersion;

            IObservable <long> updateObservable = null;

            var checkInBackground = _clickOnceConfiguration.EnableBackgroundUpdateCheck && _clickOnceConfiguration.CheckInterval > 0;

            if (checkInBackground)
            {
                // Check in background
                updateObservable = Observable.Interval(TimeSpan.FromMinutes(_clickOnceConfiguration.CheckInterval));
            }

            if (_clickOnceConfiguration.CheckOnStart)
            {
                Log.Info().WriteLine("Starting application update check.");
                var updateCheckInfo = CheckForUpdate();
                HandleUpdateCheck(updateCheckInfo);
            }
            // Register the check, if there is an update observable
            updateObservable?.ObserveOn(_uiSynchronizationContext).Select(l => CheckForUpdate())
            .Where(updateCheckInfo => updateCheckInfo != null)
            .Subscribe(HandleUpdateCheck);
        }
Ejemplo n.º 7
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");
        }
Ejemplo n.º 8
0
        public async Task TestPost_Bitmap()
        {
            var testUri         = RequestBinUri.AppendSegments("post");
            var uploadBehaviour = HttpBehaviour.Current.ShallowClone();

            bool hasProgress = false;

            uploadBehaviour.UseProgressStream = true;
            uploadBehaviour.UploadProgress   += progress =>
            {
                Log.Info().WriteLine("Progress {0}", (int)(progress * 100));
                hasProgress = true;
            };
            uploadBehaviour.MakeCurrent();
            var testObject = new MyMultiPartRequest <Bitmap>
            {
                BitmapContentName = "MyBitmapContent",
                BitmapFileName    = "MyBitmapFilename",
                OurBitmap         = new Bitmap(10, 10),
                JsonInformation   = new GitHubError {
                    DocumentationUrl = "http://test.de", Message = "Hello"
                }
            };

            testObject.Headers.Add("Name", "Dapplo");
            var result = await testUri.PostAsync <dynamic>(testObject);

            Assert.NotNull(result);
            Assert.True(hasProgress);
        }
Ejemplo n.º 9
0
        public FormExtendsDpiAwareForm()
        {
            InitializeComponent();

            _contextMenuDpiHandler = contextMenuStrip1.AttachDpiHandler();

            _dpiChangeSubscription = _contextMenuDpiHandler.OnDpiChanged.Subscribe(dpi =>
            {
                Log.Info().WriteLine("ContextMenuStrip DPI: {0}", dpi.NewDpi);
            });

            // TODO: Create a "SizeScaleHandler" or something
            var initialMenuStripSize = menuStrip1.ImageScalingSize;

            FormDpiHandler.OnDpiChanged.Subscribe(dpiChangeInfo =>
            {
                menuStrip1.ImageScalingSize = DpiHandler.ScaleWithDpi(initialMenuStripSize, dpiChangeInfo.NewDpi);
            });

            _scaleHandler = BitmapScaleHandler.WithComponentResourceManager <Bitmap>(FormDpiHandler, GetType(), BitmapScaleHandler.SimpleBitmapScaler)
                            .AddTarget(somethingMenuItem, "somethingMenuItem.Image", b => b)
                            .AddTarget(something2MenuItem, "something2MenuItem.Image", b => b);

            EnvironmentMonitor.EnvironmentUpdateEvents.Subscribe(args =>
            {
                Log.Info().WriteLine("{0} - {1}", args.SystemParametersInfoAction, args.Area);
                MessageBox.Show(this, $@"{args.SystemParametersInfoAction} - {args.Area}", @"Change!");
            });
        }
Ejemplo n.º 10
0
        public async Task StartupAsync(CancellationToken cancellationToken = default)
        {
            _log.Info().WriteLine("Before");
            await Task.Delay(100, cancellationToken).ConfigureAwait(false);

            StartupOrder = _orderProvider.TakeStartupNumber();
            DidStartup   = true;
            _log.Info().WriteLine("After");
        }
Ejemplo n.º 11
0
        /// <summary>
        ///     Get all Bitmaps (multiple if filenames are available) from the dataObject
        ///     Returned bitmap must be disposed by the calling code!
        /// </summary>
        /// <param name="dataObject"></param>
        /// <returns>IEnumerable of Bitmap</returns>
        public static IEnumerable <Bitmap> GetBitmaps(IDataObject dataObject)
        {
            // Get single image, this takes the "best" match
            var singleImage = GetBitmap(dataObject);

            if (singleImage != null)
            {
                Log.Info().WriteLine("Got image from clipboard with size {0} and format {1}", singleImage.Size, singleImage.PixelFormat);
                yield return(singleImage);
            }
            else
            {
                // check if files are supplied
                foreach (var imageFile in GetImageFilenames(dataObject))
                {
                    Bitmap returnBitmap = null;
                    try
                    {
                        returnBitmap = BitmapHelper.LoadBitmap(imageFile);
                    }
                    catch (Exception streamImageEx)
                    {
                        Log.Error().WriteLine(streamImageEx, "Problem retrieving Bitmap from clipboard.");
                    }
                    if (returnBitmap == null)
                    {
                        continue;
                    }
                    Log.Info().WriteLine("Got bitmap from clipboard with size {0} and format {1}", returnBitmap.Size, returnBitmap.PixelFormat);
                    yield return(returnBitmap);
                }
            }
        }
Ejemplo n.º 12
0
        public void TestParse()
        {
            const string iPhoneDeviceName            = @"\?\USB#VID_05AC&PID_1294&MI_00#0#{6bdd1fc6-810f-11d0-bec7-08002be2092f}";
            var          devBroadcastDeviceInterface = DevBroadcastDeviceInterface.Test(iPhoneDeviceName, DeviceInterfaceClass.StillImage);

            Assert.Equal("1294", devBroadcastDeviceInterface.ProductId);
            Assert.Equal("05AC", devBroadcastDeviceInterface.VendorId);
            Assert.Equal("6bdd1fc6-810f-11d0-bec7-08002be2092f", devBroadcastDeviceInterface.DeviceClassGuid.ToString(), StringComparer.OrdinalIgnoreCase);
            Assert.True(devBroadcastDeviceInterface.IsUsb);
            Log.Info().WriteLine("More information: {0}", devBroadcastDeviceInterface.UsbDeviceInfoUri);
        }
Ejemplo n.º 13
0
        public async Task TestGetAsAsyncBitmap()
        {
            var downloadBehaviour = HttpBehaviour.Current.ShallowClone();

            downloadBehaviour.UseProgressStream = true;
            downloadBehaviour.DownloadProgress += progress => { Log.Info().WriteLine("Progress {0}", (int)(progress * 100)); };
            downloadBehaviour.MakeCurrent();

            var bitmap = await _bitmapUri.GetAsAsync <Bitmap>();

            Assert.NotNull(bitmap);
            Assert.True(bitmap.Width > 0);
            Assert.True(bitmap.Height > 0);
        }
Ejemplo n.º 14
0
        /// <summary>
        ///     Delete an imgur image, this is done by specifying the delete hash
        /// </summary>
        /// <param name="imgurImage"></param>
        /// <param name="token"></param>
        public static async Task <string> DeleteImgurImageAsync(ImgurImage imgurImage, CancellationToken token = default)
        {
            Log.Info().WriteLine("Deleting Imgur image for {0}", imgurImage.Data.Deletehash);
            var    deleteUri = new Uri(string.Format(_imgurConfiguration.ApiUrl + "/image/{0}", imgurImage.Data.Deletehash));
            string responseString;

            Behaviour.MakeCurrent();
            using (var client = HttpClientFactory.Create(deleteUri))
            {
                var response = await client.DeleteAsync(deleteUri, token).ConfigureAwait(false);

                if ((response.StatusCode != HttpStatusCode.NotFound) && (response.StatusCode != HttpStatusCode.BadRequest))
                {
                    await response.HandleErrorAsync().ConfigureAwait(false);
                }
                responseString = await response.GetAsAsync <string>(token).ConfigureAwait(false);

                Log.Info().WriteLine("Delete result: {0}", responseString);
            }
            // Make sure we remove it from the history, if no error occured
            _imgurConfiguration.RuntimeImgurHistory.Remove(imgurImage.Data.Id);
            _imgurConfiguration.ImgurUploadHistory.Remove(imgurImage.Data.Id);

            // dispose is called inside the imgurInfo object
            imgurImage.Image = null;
            return(responseString);
        }
Ejemplo n.º 15
0
        /// <summary>
        ///     Return true if the supplied window has a sub-window which covers more than the supplied percentage
        /// </summary>
        /// <param name="someWindow">InteropWindow to check</param>
        /// <param name="minimumPercentage">min percentage</param>
        /// <returns></returns>
        public static bool IsMostlyIeWindow(IInteropWindow someWindow, int minimumPercentage)
        {
            var ieWindow = someWindow.GetChildren().FirstOrDefault(window => window.GetClassname() == "Internet Explorer_Server");

            if (ieWindow == null)
            {
                return(false);
            }
            var wholeClient = someWindow.GetInfo().ClientBounds;
            var partClient  = ieWindow.GetInfo().ClientBounds;
            var percentage  = (int)(100 * (float)(partClient.Width * partClient.Height) / (wholeClient.Width * wholeClient.Height));

            Log.Info().WriteLine("Window {0}, ie part {1}, percentage {2}", wholeClient, partClient, percentage);
            return(percentage > minimumPercentage);
        }
Ejemplo n.º 16
0
 /// <summary>
 ///     Export the capture to the specified page
 /// </summary>
 /// <param name="oneNoteApplication">IOneNoteApplication</param>
 /// <param name="surfaceToUpload">ISurface</param>
 /// <param name="page">OneNotePage</param>
 /// <returns>bool true if everything worked</returns>
 private static bool ExportToPage(IOneNoteApplication oneNoteApplication, ISurface surfaceToUpload, OneNotePage page)
 {
     if (oneNoteApplication == null)
     {
         return(false);
     }
     using (var pngStream = new MemoryStream())
     {
         var pngOutputSettings = new SurfaceOutputSettings(OutputFormats.png, 100, false);
         ImageOutput.SaveToStream(surfaceToUpload, pngStream, pngOutputSettings);
         var base64String   = Convert.ToBase64String(pngStream.GetBuffer());
         var imageXmlStr    = string.Format(XmlImageContent, base64String, surfaceToUpload.Screenshot.Width, surfaceToUpload.Screenshot.Height);
         var pageChangesXml = string.Format(XmlOutline, imageXmlStr, page.ID, OnenoteNamespace2010, page.Name);
         Log.Info().WriteLine("Sending XML: {0}", pageChangesXml);
         oneNoteApplication.UpdatePageContent(pageChangesXml, DateTime.MinValue, XMLSchema.xs2010, false);
         try
         {
             oneNoteApplication.NavigateTo(page.ID, null, false);
         }
         catch (Exception ex)
         {
             Log.Warn().WriteLine(ex, "Unable to navigate to the target page");
         }
         return(true);
     }
 }
Ejemplo n.º 17
0
        public async Task TestIdleAsync()
        {
            var taskCompletionSource = new TaskCompletionSource <bool>();

            using (var statusClient = await MpdStateMonitor.CreateAsync(_host, _port))
            {
                statusClient.StateChanged += (sender, args) =>
                {
                    Log.Info().WriteLine("Subsystem changed {0}", args.ChangedSubsystem);
                    taskCompletionSource.SetResult(true);
                };
                using (var controlClient = await MpdClient.CreateAsync(_host, _port))
                {
                    var status = await controlClient.StatusAsync();

                    await controlClient.PauseAsync(status.PlayState == PlayStates.Playing);

                    status = await controlClient.StatusAsync();

                    await controlClient.PauseAsync(status.PlayState == PlayStates.Playing);
                }
                // Using the delay with the token causes a TaskCanceledException
                await taskCompletionSource.Task;
            }
        }
Ejemplo n.º 18
0
        /// <summary>
        ///     Helper method to cleanly register a hotkey
        /// </summary>
        /// <param name="failedKeys"></param>
        /// <param name="functionName"></param>
        /// <param name="hotkeyString"></param>
        /// <param name="handler"></param>
        /// <returns></returns>
        private static bool RegisterHotkey(StringBuilder failedKeys, string functionName, string hotkeyString, HotKeyHandler handler)
        {
            var modifierKeyCode = HotkeyControl.HotkeyModifiersFromString(hotkeyString);
            var virtualKeyCode  = HotkeyControl.HotkeyFromString(hotkeyString);

            if (!Keys.None.Equals(virtualKeyCode))
            {
                if (HotkeyControl.RegisterHotKey(modifierKeyCode, virtualKeyCode, handler) < 0)
                {
                    Log.Debug().WriteLine("Failed to register {0} to hotkey: {1}", functionName, hotkeyString);
                    if (failedKeys.Length > 0)
                    {
                        failedKeys.Append(", ");
                    }
                    failedKeys.Append(hotkeyString);
                    return(false);
                }
                Log.Debug().WriteLine("Registered {0} to hotkey: {1}", functionName, hotkeyString);
            }
            else
            {
                Log.Info().WriteLine("Skipping hotkey registration for {0}, no hotkey set!", functionName);
            }
            return(true);
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Load a named assembly
        /// </summary>
        /// <param name="assemblyName">string</param>
        /// <returns>Assembly</returns>
        public Assembly LoadAssembly(string assemblyName)
        {
            // Check if the simple name can be found in the cache
            if (LoadedAssemblies.TryGetValue(assemblyName, out var assembly))
            {
                Log.Info().WriteLine("Returned {0} from cache.", assemblyName);
                return(assembly);
            }

            if (AvailableAssemblies.TryGetValue(assemblyName, out var assemblyLocationInformation))
            {
                return(LoadAssembly(assemblyLocationInformation));
            }

            return(Assembly.Load(assemblyName));
        }
Ejemplo n.º 20
0
        public ConnectionViewModel(
            INetworkConfiguration networkConfiguration,
            IConnectionTranslations connectionTranslations,
            IConnectionConfiguration connectionConfiguration)
        {
            _networkConfiguration   = networkConfiguration;
            ConnectionTranslations  = connectionTranslations;
            ConnectionConfiguration = connectionConfiguration;
#if DEBUG
            // For the designer
            if (!Execute.InDesignMode)
            {
                return;
            }

            LogSettings.RegisterDefaultLogger <TraceLogger>(LogLevels.Verbose);
            Log.Info().WriteLine("Running in designer");
            LoadDesignData();
#endif
            // Make sure the settings from the configuration file are used.
            HttpExtensionsGlobals.HttpSettings = _networkConfiguration;

            if (IsConfigured)
            {
                // Make the "connection"
                Task.Run(async() => await Connect());
            }
            ConnectionConfiguration.OnPropertyChanged().Subscribe(propertyChangedEventArgs =>
            {
                NotifyOfPropertyChange(nameof(IsConnected));
            });
        }
Ejemplo n.º 21
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);
            }
        }
Ejemplo n.º 22
0
        public async Task TestAttachment()
        {
            const string filename    = "test.txt";
            const string testContent = "Testing 1 2 3";
            var          attachment  = await _jiraApi.AttachAsync("FEATURE-746", testContent, filename);

            Assert.NotNull(attachment);
            Assert.StartsWith("text/plain", attachment.MimeType);

            if (attachment.ThumbnailUri != null)
            {
                var attachmentThumbnail = await _jiraApi.GetAttachmentThumbnailAsAsync <Bitmap>(attachment);

                Assert.NotNull(attachmentThumbnail);
                Assert.True(attachmentThumbnail.Width > 0);
            }

            var returnedContent = await _jiraApi.GetAttachmentContentAsAsync <string>(attachment);

            Assert.Equal(testContent, returnedContent);

            bool hasBeenRemoved = false;
            var  issue          = await _jiraApi.GetIssueAsync("FEATURE-746");

            foreach (var attachment2Delete in issue.Fields.Attachments.Where(x => x.Filename == filename))
            {
                Log.Info().WriteLine("Deleting {0} from {1}", attachment2Delete.Filename, attachment2Delete.Created);
                await _jiraApi.DeleteAttachmentAsync(attachment2Delete);

                hasBeenRemoved = true;
            }

            Assert.True(hasBeenRemoved);
        }
Ejemplo n.º 23
0
        /// <summary>
        ///     Retrieve the assembly for the supplied package, or null
        /// </summary>
        private static Assembly ReturnAssemblyFromRepository(IPackageManager packageManager, AssemblyName assemblyName)
        {
            if (assemblyName == null)
            {
                return(null);
            }
            var basePath = Path.GetFullPath(packageManager.LocalRepository.Source);

            if (!Directory.Exists(basePath))
            {
                return(null);
            }

            var dllPath = Directory.EnumerateFiles(basePath, assemblyName.Name + ".dll", SearchOption.AllDirectories).OrderBy(path => path).LastOrDefault();

            if (string.IsNullOrEmpty(dllPath))
            {
                return(null);
            }

            Log.Info().WriteLine("Dll found in Package {0}, installed here {1}", assemblyName.Name, dllPath);
            if (File.Exists(dllPath))
            {
                // The following doesn't work, as Fusion isn't called. See: http://blogs.msdn.com/b/suzcook/archive/2003/09/19/loadfile-vs-loadfrom.aspx
                // return Assembly.LoadFile(dllPath);
                return(Assembly.LoadFrom(dllPath));
            }
            return(null);
        }
Ejemplo n.º 24
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;
            }
        }
Ejemplo n.º 25
0
        /// <summary>
        /// </summary>
        /// <param name="webRequest"></param>
        /// <param name="alsoReturnContentOnError"></param>
        /// <returns></returns>
        public static string GetResponseAsString(HttpWebRequest webRequest, bool alsoReturnContentOnError)
        {
            string          responseData = null;
            HttpWebResponse response     = null;
            var             isHttpError  = false;

            try
            {
                response = (HttpWebResponse)webRequest.GetResponse();
                Log.Info().WriteLine("Response status: {0}", response.StatusCode);
                isHttpError = (int)response.StatusCode >= 300;
                if (isHttpError)
                {
                    Log.Error().WriteLine("HTTP error {0}", response.StatusCode);
                }
                DebugHeaders(response);
                responseData = GetResponseAsString(response);
                if (isHttpError)
                {
                    Log.Error().WriteLine("HTTP response {0}", responseData);
                }
            }
            catch (WebException e)
            {
                response = (HttpWebResponse)e.Response;
                var statusCode = HttpStatusCode.Unused;
                if (response != null)
                {
                    statusCode = response.StatusCode;
                    Log.Error().WriteLine("HTTP error {0}", statusCode);
                    var errorContent = GetResponseAsString(response);
                    if (alsoReturnContentOnError)
                    {
                        return(errorContent);
                    }
                    Log.Error().WriteLine("Content: {0}", errorContent);
                }
                Log.Error().WriteLine(e, "WebException: ");
                if (statusCode == HttpStatusCode.Unauthorized)
                {
                    throw new UnauthorizedAccessException(e.Message);
                }
                throw;
            }
            finally
            {
                if (response != null)
                {
                    if (isHttpError)
                    {
                        Log.Error().WriteLine("HTTP error {0} with content: {1}", response.StatusCode, responseData);
                    }
                    response.Close();
                }
            }
            return(responseData);
        }
Ejemplo n.º 26
0
        public async Task Test_ContentVersion()
        {
            var query         = Where.And(Where.Space.Is("TEST"), Where.Type.IsPage, Where.Title.Contains("Test Home"));
            var searchResults = await _confluenceClient.Content.SearchAsync(query);

            var searchResult = searchResults.First();

            Log.Info().WriteLine("Version = {0}", searchResult.Version.Number);
            query         = Where.Title.Contains("Test Home");
            searchResults = await _confluenceClient.Content.SearchAsync(query);

            searchResult = searchResults.First();
            Log.Info().WriteLine("Version = {0}", searchResult.Version.Number);

            var content = await _confluenceClient.Content.GetAsync(searchResult, ConfluenceClientConfig.ExpandGetContentWithStorage);

            Log.Info().WriteLine("Version = {0}", content.Version.Number);
        }
Ejemplo n.º 27
0
        public async Task TestGetProjects()
        {
            Results <Project> projects = null;

            do
            {
                projects = await _bitbucketClient.Project.GetAllAsync(projects ?? new PagingInfo {
                    Limit = 5
                });

                Assert.NotNull(projects);
                Assert.True(projects.Size > 0);
                foreach (var project in projects)
                {
                    Log.Info().WriteLine("{0} : {1} - {2}", project.Id, project.Description, project.Type);
                }
            } while (!projects.IsLastPage);
        }
Ejemplo n.º 28
0
        public WebBrowserForm()
        {
            InternetExplorerVersion.ChangeEmbeddedVersion();

            InitializeComponent();
            extendedWebBrowser1.OnNavigating().Subscribe(args =>
            {
                Log.Info().WriteLine(args.Url.AbsoluteUri);
            });
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Start will register all needed services
        /// </summary>
        public void Startup()
        {
            bool firstClip = true;

            _clipboardMonitor = ClipboardNative
                                .OnUpdate
                                .SubscribeOn(_uiSynchronizationContext)
                                .Where(contents => contents.OwnerHandle != WinProcHandler.Instance.Handle)
                                .Synchronize().Subscribe(clipboardContents =>
            {
                // Ignore our own modifications
                if (clipboardContents.IsModifiedByDopy())
                {
                    Log.Info().WriteLine("Skipping clipboard id {0} as it was pasted by 'us'", clipboardContents.Id);
                    return;
                }

                // Ignore empty clips (e.g. if Dopy is started directly at windows startup)
                if (!clipboardContents.Formats.Any() && firstClip)
                {
                    firstClip = false;
                    Log.Info().WriteLine("Empty clipboard at startup, restoring latest from DB");
                    // Empty clipboard, Place the last stored on the clipboard
                    _clipRepository.Find().OrderByDescending(databaseClip => databaseClip.Timestamp).LastOrDefault()?.PlaceOnClipboard();
                    return;
                }
                firstClip = false;

                // Double detection, if there is already a clip with the same sequence and session, we already got it
                if (_clipRepository.Find(clip => clip.SequenceNumber == clipboardContents.Id && clip.SessionId == _currentSession.Id).Any())
                {
                    Log.Info().WriteLine("Clipboard with id {0} already stored.", clipboardContents.Id);
                    return;
                }

                // The clipboard contents are unique, so store them
                Log.Info().WriteLine("Processing clipboard id {0}.", clipboardContents.Id);
                var newClip = CreateClip(clipboardContents);

                // Store it in the repository
                _clipRepository.Create(newClip);
            });
        }
Ejemplo n.º 30
0
 /// <summary>
 ///     Wrapper method for the background and normal call, this does all the logic:
 ///     Call the external command, parse for URI, place to clipboard and set the export information
 /// </summary>
 /// <param name="exportInformation"></param>
 /// <param name="fullPath"></param>
 /// <param name="output"></param>
 /// <param name="error"></param>
 private void CallExternalCommand(ExportInformation exportInformation, string fullPath, out string output, out string error)
 {
     output = null;
     error  = null;
     try
     {
         if (CallExternalCommand(_presetCommand, fullPath, out output, out error) == 0)
         {
             exportInformation.ExportMade = true;
             if (!string.IsNullOrEmpty(output))
             {
                 var uriMatches = UriRegexp.Matches(output);
                 // Place output on the clipboard before the URI, so if one is found this overwrites
                 if (Config.OutputToClipboard)
                 {
                     ClipboardHelper.SetClipboardData(output);
                 }
                 if (uriMatches.Count > 0)
                 {
                     exportInformation.Uri = uriMatches[0].Groups[1].Value;
                     Log.Info().WriteLine("Got URI : {0} ", exportInformation.Uri);
                     if (Config.UriToClipboard)
                     {
                         ClipboardHelper.SetClipboardData(exportInformation.Uri);
                     }
                 }
             }
         }
         else
         {
             Log.Warn().WriteLine("Error calling external command: {0} ", output);
             exportInformation.ExportMade   = false;
             exportInformation.ErrorMessage = error;
         }
     }
     catch (Exception ex)
     {
         exportInformation.ExportMade   = false;
         exportInformation.ErrorMessage = ex.Message;
         Log.Warn().WriteLine("Error calling external command: {0} ", exportInformation.ErrorMessage);
     }
 }