/// <summary> /// Returns the content, specified by the Uri from the JIRA server. /// This is used internally, but can also be used to get e.g. the icon for an issue type. /// </summary> /// <typeparam name="TResponse"></typeparam> /// <param name="jiraClient">IServerDomain to bind the extension method to</param> /// <param name="contentUri">Uri</param> /// <param name="cancellationToken">CancellationToken</param> /// <returns>TResponse</returns> public static async Task <TResponse> GetUriContentAsync <TResponse>(this IServerDomain jiraClient, Uri contentUri, CancellationToken cancellationToken = default) where TResponse : class { Log.Debug().WriteLine("Retrieving content from {0}", contentUri); jiraClient.Behaviour.MakeCurrent(); var response = await contentUri.GetAsAsync <HttpResponse <TResponse, string> >(cancellationToken).ConfigureAwait(false); response.HandleStatusCode(); return(response.Response); }
/// <summary> /// Get worklogs information /// </summary> /// <param name="jiraClient">IWorkDomain to bind the extension method to</param> /// <param name="issueKey">the issue key</param> /// <param name="cancellationToken">CancellationToken</param> /// <returns>Worklogs</returns> public static async Task <Worklogs> GetAsync(this IWorkDomain jiraClient, string issueKey, CancellationToken cancellationToken = default) { if (issueKey == null) { throw new ArgumentNullException(nameof(issueKey)); } Log.Debug().WriteLine("Retrieving worklogs information for {0}", issueKey); var worklogUri = jiraClient.JiraRestUri.AppendSegments("issue", issueKey, "worklog"); jiraClient.Behaviour.MakeCurrent(); var response = await worklogUri.GetAsAsync <HttpResponse <Worklogs, Error> >(cancellationToken).ConfigureAwait(false); return(response.HandleErrors()); }
public MpdTest(ITestOutputHelper testOutputHelper) { LogSettings.RegisterDefaultLogger <XUnitLogger>(LogLevels.Verbose, testOutputHelper); Task.Run(async() => { var mpdInstances = (await MpdSocketClient.FindByZeroConfAsync()).ToList(); foreach (var mpdInstance in mpdInstances) { Log.Debug().WriteLine("Found {0} at {1}", mpdInstance.Key, mpdInstance.Value.AbsoluteUri); } _port = mpdInstances.First().Value.Port; _host = mpdInstances.First().Value.Host; }).Wait(); }
/// <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."); } using ( var memoryStream = (MemoryStream) await StreamHttpContentConverter.Instance.Value.ConvertFromHttpContentAsync(typeof(MemoryStream), httpContent, cancellationToken) .ConfigureAwait(false)) { Log.Debug().WriteLine("Creating a BitmapImage from the MemoryStream."); var bitmap = new BitmapImage(); bitmap.BeginInit(); bitmap.StreamSource = memoryStream; bitmap.CacheOption = BitmapCacheOption.OnLoad; bitmap.EndInit(); // This is very important to make the bitmap usable in the UI thread: bitmap.Freeze(); return(bitmap); } }
private bool Upload(ISurface surfaceToUpload, Page page, string filename, out string errorMessage) { var outputSettings = new SurfaceOutputSettings(_confluenceConfiguration.UploadFormat, _confluenceConfiguration.UploadJpegQuality, _confluenceConfiguration.UploadReduceColors); errorMessage = null; try { new PleaseWaitForm().ShowAndWait(Description, Language.GetString("confluence", LangKey.communication_wait), () => _confluenceConnector.AddAttachment(page.Id, "image/" + _confluenceConfiguration.UploadFormat.ToString().ToLower(), null, filename, new SurfaceContainer(surfaceToUpload, outputSettings, filename)) ); Log.Debug().WriteLine("Uploaded to Confluence."); if (!_confluenceConfiguration.CopyWikiMarkupForImageToClipboard) { return(true); } var retryCount = 2; while (retryCount >= 0) { try { Clipboard.SetText("!" + filename + "!"); break; } catch (Exception ee) { if (retryCount == 0) { Log.Error().WriteLine(ee); } else { Thread.Sleep(100); } } finally { --retryCount; } } return(true); } catch (Exception e) { errorMessage = e.Message; } return(false); }
/// <summary> /// Initialize the MpdSocketClient /// </summary> /// <param name="hostname"></param> /// <param name="port"></param> /// <returns>Task too await</returns> protected async Task InitAsync(string hostname, int port) { Log.Verbose().WriteLine("Connecting to {0}:{1}", hostname, port); _tcpClient = new TcpClient(); await _tcpClient.ConnectAsync(hostname, port).ConfigureAwait(false); _networkStream = _tcpClient.GetStream(); var mpdResponse = await ReadResponseAsync().ConfigureAwait(false); if (!mpdResponse.IsOk) { throw new Exception(mpdResponse.ErrorMessage); } Version = mpdResponse.ResponseLines[0]; Log.Debug().WriteLine("Connected to MPD version {0}", Version); }
public List <OfdbSearchTitleResult> SearchByTitle(string Title) { Log.Debug().Write($"Title: {Title}"); var searchNames = new XPathSelectionName[] { XPathSelectionName.SearchTitleResultTitle, XPathSelectionName.SearchTitleResultEngineId, XPathSelectionName.SearchTitleResultYear, XPathSelectionName.SearchTitleResultCoverImage }; var searchSelections = from s in OfdbXPathSelections.GetSelections() where searchNames.Contains(s.Name) select s; var url = SubstitutePlaceHolder(searchSelections.FirstOrDefault().Url, Title); var request = new XPathAgilityPackSelector(url); var searchResults = request.GetXPathValues(searchSelections.FirstOrDefault().XPath); List <OfdbSearchTitleResult> result = new List <OfdbSearchTitleResult>(); Log.Debug().Write($"Found {searchResults.Count()} entries."); foreach (var searchResult in searchResults) { OfdbSearchTitleResult titleResult = new OfdbSearchTitleResult(); var titleGetter = searchSelections.Where(s => s.Name == XPathSelectionName.SearchTitleResultTitle).FirstOrDefault(); titleResult.Title = titleGetter.Resolver.Resolve(searchResult); var yearGetter = searchSelections.Where(s => s.Name == XPathSelectionName.SearchTitleResultYear).FirstOrDefault(); titleResult.Year = yearGetter.Resolver.Resolve(searchResult); var engineIdGetter = searchSelections.Where(s => s.Name == XPathSelectionName.SearchTitleResultEngineId).FirstOrDefault(); titleResult.EngineId = engineIdGetter.Resolver.Resolve(searchResult); var coverGetter = searchSelections.Where(s => s.Name == XPathSelectionName.SearchTitleResultCoverImage).FirstOrDefault(); titleResult.CoverImage = coverGetter.Resolver.Resolve(searchResult); result.Add(titleResult); } return(result); }
/// <summary> /// This creates the capture form /// </summary> /// <param name="coreConfiguration">ICoreConfiguration</param> /// <param name="capture">ICapture</param> /// <param name="windows">IList of IInteropWindow</param> public CaptureForm(ICoreConfiguration coreConfiguration, ICapture capture, IList <IInteropWindow> windows) : base(coreConfiguration, null) { _coreConfiguration = coreConfiguration; _isZoomerTransparent = _coreConfiguration.ZoomerOpacity < 1; ManualLanguageApply = true; ManualStoreFields = true; // Enable the AnimatingForm EnableAnimation = true; _capture = capture; _windows = windows; UsedCaptureMode = capture.CaptureDetails.CaptureMode; // // The InitializeComponent() call is required for Windows Forms designer support. // InitializeComponent(); Text = "Greenshot capture form"; // Log at close if (Log.IsDebugEnabled()) { FormClosing += (s, e) => Log.Debug().WriteLine("Closing captureform"); } // set cursor location _cursorPos = _mouseMovePos = WindowCapture.GetCursorLocationRelativeToScreenBounds(); // Initialize the animations, the window capture zooms out from the cursor to the window under the cursor if (UsedCaptureMode == CaptureMode.Window) { _windowAnimator = new RectangleAnimator(new NativeRect(_cursorPos, NativeSize.Empty), _captureRect, FramesForMillis(700), EasingTypes.Quintic, EasingModes.EaseOut); } // Set the zoomer animation InitializeZoomer(_coreConfiguration.ZoomerEnabled); Bounds = capture.ScreenBounds; // Fix missing focus ToFront = true; TopMost = true; }
/// <summary> /// Load the complete history of the Lutim uploads, with the corresponding information /// </summary> private async Task LoadHistory(CancellationToken cancellationToken = default) { bool saveNeeded = false; // Load the ImUr history foreach (string hash in LutimConfiguration.LutimUploadHistory.Keys) { if (LutimConfiguration.RuntimeLutimHistory.ContainsKey(hash)) { // Already loaded, only add it to the view LutimHistory.Add(LutimConfiguration.RuntimeLutimHistory[hash]); continue; } try { var lutimInfo = await LutimUtils.RetrieveLutimInfoAsync(hash, LutimConfiguration.LutimUploadHistory[hash], cancellationToken); if (lutimInfo != null) { await LutimUtils.RetrieveLutimThumbnailAsync(lutimInfo, cancellationToken); LutimConfiguration.RuntimeLutimHistory.Add(hash, lutimInfo); // Already loaded, only add it to the view LutimHistory.Add(lutimInfo); } else { Log.Debug().WriteLine("Deleting not found Lutim {0} from config.", hash); LutimConfiguration.LutimUploadHistory.Remove(hash); saveNeeded = true; } } catch (Exception e) { Log.Error().WriteLine(e, "Problem loading Lutim history for hash {0}", hash); } } if (saveNeeded) { // Save needed changes // IniConfig.Save(); } }
/// <summary> /// Add comment to the specified issue /// See: https://docs.atlassian.com/jira/REST/latest/#d2e1139 /// </summary> /// <param name="jiraClient">IIssueDomain to bind the extension method to</param> /// <param name="issueKey">key for the issue</param> /// <param name="body">the body of the comment</param> /// <param name="visibility">Visibility with optional visibility group or role</param> /// <param name="cancellationToken">CancellationToken</param> /// <returns>Comment</returns> public static async Task <Comment> AddCommentAsync(this IIssueDomain jiraClient, string issueKey, string body, Visibility visibility = null, CancellationToken cancellationToken = default) { if (issueKey == null) { throw new ArgumentNullException(nameof(issueKey)); } Log.Debug().WriteLine("Adding comment to {0}", issueKey); var comment = new Comment { Body = body, Visibility = visibility }; jiraClient.Behaviour.MakeCurrent(); var attachUri = jiraClient.JiraRestUri.AppendSegments("issue", issueKey, "comment"); var response = await attachUri.PostAsync <HttpResponse <Comment, Error> >(comment, cancellationToken).ConfigureAwait(false); return(response.HandleErrors(HttpStatusCode.Created)); }
/// <summary> /// This takes the height and width of the Popup and will return the location where it should be displayed /// </summary> /// <param name="actualPopupWidth">double</param> /// <param name="actualPopupHeight">double</param> /// <returns>Point</returns> public Point GetPosition(double actualPopupWidth, double actualPopupHeight) { var taskbar = Shell32Api.TaskbarPosition; var taskbarBounds = taskbar.Bounds; var actualSize = new NativeSize((int)actualPopupWidth, (int)actualPopupHeight); // Use the DPI of the desktop var dpi = NativeDpiMethods.GetDpi(InteropWindowQuery.GetDesktopWindow().Handle); actualSize = DpiHandler.ScaleWithDpi(actualSize, dpi); int x, y; // Define the new position switch (taskbar.AppBarEdge) { case AppBarEdges.Left: x = taskbarBounds.Right + _xOffset; y = taskbarBounds.Bottom - _yOffset - actualSize.Height; break; case AppBarEdges.Top: x = taskbarBounds.Right - _xOffset - actualSize.Width; y = taskbarBounds.Bottom + _yOffset; break; case AppBarEdges.Right: x = taskbarBounds.Left - _xOffset - actualSize.Width; y = taskbarBounds.Bottom - _yOffset - actualSize.Height; break; case AppBarEdges.Bottom: default: x = taskbarBounds.Right - _xOffset - actualSize.Width; y = taskbarBounds.Top - _yOffset - actualSize.Height; break; } var position = DpiHandler.UnscaleWithDpi(new NativePoint(x, y), dpi); Log.Debug().WriteLine("Taskbar location {0} at {1}, calculate popup position: {2}", taskbar.AppBarEdge, taskbarBounds, position); return(position); }
public SomeWindowMenuItems( IWindowManager windowManager, IContextMenuTranslations contextMenuTranslations, WindowWithMenuViewModel windowWithMenuViewModel) { // automatically update the DisplayName contextMenuTranslations.CreateDisplayNameBinding(this, nameof(IContextMenuTranslations.SomeWindow)); Icon = new PackIconMaterial { Kind = PackIconMaterialKind.ViewList }; ClickAction = clickedItem => { Log.Debug().WriteLine("SomeWindow"); windowManager.ShowWindow(windowWithMenuViewModel); }; this.VisibleOnPermissions("Admin"); }
/// <inheritdoc /> public async Task <object> ConvertFromHttpContentAsync(Type resultType, HttpContent httpContent, CancellationToken cancellationToken = default(CancellationToken)) { if (!CanConvertFromHttpContent(resultType, httpContent)) { throw new NotSupportedException("CanConvertFromHttpContent resulted in false, this is not supposed to be called."); } Log.Debug().WriteLine("Retrieving the content as MemoryStream, Content-Type: {0}", httpContent.Headers.ContentType); var httpBehaviour = HttpBehaviour.Current; var memoryStream = new MemoryStream(); using (var contentStream = await httpContent.GetContentStream().ConfigureAwait(false)) { await contentStream.CopyToAsync(memoryStream, httpBehaviour.ReadBufferSize, cancellationToken).ConfigureAwait(false); } // Make sure the memory stream position is at the beginning, // so the processing code can read right away. memoryStream.Position = 0; return(memoryStream); }
/// <summary> /// Get the details for a job /// </summary> /// <param name="jenkinsClient">IJobDomain to bind the extension method to</param> /// <param name="jobName">the name of the job</param> /// <param name="cancellationToken">CancellationToken</param> /// <returns>JobDetails</returns> public static async Task <JobDetails> GetAsync(this IJobDomain jenkinsClient, string jobName, CancellationToken cancellationToken = default(CancellationToken)) { if (jobName == null) { throw new ArgumentNullException(nameof(jobName)); } Log.Debug().WriteLine("Retrieving job details for {0}", jobName); var jobDetailsUri = jenkinsClient.JenkinsBaseUri.AppendSegments("job", jobName, "api", "json"); jenkinsClient.Behaviour.MakeCurrent(); var response = await jobDetailsUri.GetAsAsync <HttpResponse <JobDetails> >(cancellationToken).ConfigureAwait(false); return(response.HandleErrors()); }
private void Combobox_languageSelectedIndexChanged(object sender, EventArgs e) { // Get the combobox values BEFORE changing the language //EmailFormat selectedEmailFormat = GetSelected<EmailFormat>(combobox_emailformat); var selectedWindowCaptureMode = GetSelected <WindowCaptureModes>(combobox_window_capture_mode); if (combobox_language.SelectedItem != null) { Log.Debug().WriteLine("Setting language to: " + (string)combobox_language.SelectedValue); Language.CurrentLanguage = (string)combobox_language.SelectedValue; } // Reflect language changes to the settings form UpdateUi(); // Reflect Language changes form ApplyLanguage(); // Update the email & windows capture mode //SetEmailFormat(selectedEmailFormat); SetWindowCaptureMode(selectedWindowCaptureMode); }
public void TestLoggerVisibility() { var stringWriterLogger = LogSettings.RegisterDefaultLogger <StringWriterLogger>(); Assert.NotNull(stringWriterLogger); Log.Verbose().WriteLine("This is a test, should NOT be visible"); Log.Debug().WriteLine("This is a test, should NOT be visible"); Log.Info().WriteLine("This is a test"); Log.Warn().WriteLine("This is a test"); Log.Error().WriteLine("This is a test"); Log.Fatal().WriteLine("This is a test"); Log.Error().WriteLine(new Exception(nameof(stringWriterLogger)), "This is a test exception"); Assert.DoesNotContain("should NOT be visible", stringWriterLogger.Output); var lines = stringWriterLogger.Output.Count(x => x.ToString() == Environment.NewLine); // Info + Warn + Error + Fatal = 4 Assert.False(lines == 4); }
public ToastMenuItem( IEventAggregator eventAggregator, Func <Owned <ToastExampleViewModel> > toastExampleViewModelFactory, IContextMenuTranslations contextMenuTranslations) { // automatically update the DisplayName contextMenuTranslations.CreateDisplayNameBinding(this, nameof(IContextMenuTranslations.Toast)); Icon = new PackIconMaterial { Kind = PackIconMaterialKind.MessageText }; ClickAction = clickedItem => { Log.Debug().WriteLine("Toast"); ShowToast(eventAggregator, toastExampleViewModelFactory); }; this.VisibleOnPermissions("Admin"); }
public virtual void AddField(IField field) { fields.Add(field); if (_fieldsByType == null) { return; } if (_fieldsByType.ContainsKey(field.FieldType)) { Log.Debug().WriteLine("A field with of type '{0}' already exists in this {1}, will overwrite.", field.FieldType, GetType()); } _fieldsByType[field.FieldType] = field; _handlers[field] = (sender, args) => { _fieldChanged?.Invoke(this, new FieldChangedEventArgs(field)); }; field.PropertyChanged += _handlers[field]; }
private async Task TestWinEventHook() { // This takes care of having a WinProc handler, to make sure the messages arrive var winProcHandler = WinProcHandler.Instance; // This buffers the observable var replaySubject = new ReplaySubject <IInteropWindow>(); var winEventObservable = WinEventHook.WindowTileChangeObservable() .Select(info => InteropWindowFactory.CreateFor(info.Handle).Fill()) .Where(interopWindow => !string.IsNullOrEmpty(interopWindow?.Caption)) .Subscribe(interopWindow => { Log.Debug().WriteLine("Window title change: Process ID {0} - Title: {1}", interopWindow.Handle, interopWindow.Caption); replaySubject.OnNext(interopWindow); }, exception => Log.Error().WriteLine("An error occured", exception)); await Task.Delay(100); // Start a process to test against using (var process = Process.Start("notepad.exe")) { try { // Make sure it's started Assert.NotNull(process); // Wait until the process started it's message pump (listening for input) process.WaitForInputIdle(); User32Api.SetWindowText(process.MainWindowHandle, "TestWinEventHook - Test"); // Find the belonging window var notepadWindow = await replaySubject.Where(info => info != null && info.ProcessId == process.Id).FirstAsync(); Assert.Equal(process.Id, notepadWindow?.ProcessId); } finally { winEventObservable.Dispose(); process?.Kill(); } } }
/// <summary> /// Load the complete history of the imgur uploads, with the corresponding information /// </summary> private async Task LoadHistory(CancellationToken cancellationToken = default) { // Load the ImUr history foreach (var hash in ImgurConfiguration.ImgurUploadHistory.Keys) { if (ImgurHistory.Any(imgurInfo => imgurInfo.Data.Id == hash)) { continue; } if (ImgurConfiguration.RuntimeImgurHistory.ContainsKey(hash)) { // Already loaded, only add it to the view ImgurHistory.Add(ImgurConfiguration.RuntimeImgurHistory[hash]); continue; } try { var imgurInfo = await ImgurApi.RetrieveImgurInfoAsync(hash, ImgurConfiguration.ImgurUploadHistory[hash], cancellationToken).ConfigureAwait(true); if (imgurInfo != null) { await ImgurApi.RetrieveImgurThumbnailAsync(imgurInfo, cancellationToken).ConfigureAwait(true); ImgurConfiguration.RuntimeImgurHistory.Add(hash, imgurInfo); // Already loaded, only add it to the view ImgurHistory.Add(imgurInfo); } else { Log.Debug().WriteLine("Deleting not found ImgUr {0} from config.", hash); ImgurConfiguration.ImgurUploadHistory.Remove(hash); } } catch (Exception e) { Log.Error().WriteLine(e, "Problem loading ImgUr history for hash {0}", hash); } } }
public async Task TestINotifyPropertyChanged() { var languageLoaderTest = new LanguageLoaderTestImpl(); var languageContainer = await CreateContainer(languageLoaderTest); var hasChanges = false; var propChanged = new PropertyChangedEventHandler((sender, eventArgs) => { Log.Debug().WriteLine($"Change for {eventArgs.PropertyName}"); hasChanges = true; }); // Test event handler languageLoaderTest.PropertyChanged += propChanged; await languageContainer.ChangeLanguageAsync("nl-NL").ConfigureAwait(false); // Make sure the events are handled await Task.Yield(); Assert.True(hasChanges); }
public static async Task <int> Main(string[] args) { LogSettings.RegisterDefaultLogger <DebugLogger>(LogLevels.Verbose); var applicationConfig = ApplicationConfigBuilder.Create() .WithApplicationName("DemoConsoleApp") .WithScanDirectories( #if DEBUG @"..\..\..\..\Dapplo.Addons.TestAddonWithCostura\bin\Debug\netstandard2.0", #else @"..\..\..\..\Dapplo.Addons.TestAddonWithCostura\bin\Release\netstandard2.0", #endif FileLocations.StartupDirectory, @"MyOtherLibs" ) .WithAssemblyNames("Dapplo.HttpExtensions", "Dapplo.Addons.TestAddonWithCostura").BuildApplicationConfig(); using (var bootstrapper = new ApplicationBootstrapper(applicationConfig)) { #if DEBUG bootstrapper.EnableActivationLogging = true; #endif bootstrapper.Configure(); await bootstrapper.InitializeAsync().ConfigureAwait(false); bootstrapper.Container.Resolve <ServiceStartupShutdown>(); // Find all, currently, available assemblies if (Log.IsDebugEnabled()) { foreach (var resource in bootstrapper.Resolver.EmbeddedAssemblyNames()) { Log.Debug().WriteLine("Available embedded assembly {0}", resource); } } Assembly.Load("Dapplo.HttpExtensions"); } return(0); }
/// <summary> /// Create a IWebProxy Object which can be used to access the Internet /// This method will check the configuration if the proxy is allowed to be used. /// Usages can be found in the DownloadFavIcon or Jira and Confluence plugins /// </summary> /// <param name="uri"></param> /// <returns>IWebProxy filled with all the proxy details or null if none is set/wanted</returns> public static IWebProxy CreateProxy(Uri uri) { if (!Config.UseProxy) { return(null); } IWebProxy proxyToUse = WebRequest.DefaultWebProxy; if (proxyToUse != null) { proxyToUse.Credentials = CredentialCache.DefaultCredentials; if (!Log.IsDebugEnabled()) { return(proxyToUse); } // check the proxy for the Uri if (!proxyToUse.IsBypassed(uri)) { var proxyUri = proxyToUse.GetProxy(uri); if (proxyUri != null) { Log.Debug().WriteLine("Using proxy: " + proxyUri + " for " + uri); } else { Log.Debug().WriteLine("No proxy found!"); } } else { Log.Debug().WriteLine("Proxy bypass for: " + uri); } } else { Log.Debug().WriteLine("No proxy found!"); } return(proxyToUse); }
/// <summary> /// Append the information to the Dapplo log /// </summary> /// <param name="loggingEvent">LoggingEvent</param> protected override void Append(LoggingEvent loggingEvent) { if (loggingEvent.Level < _minimalLog4NetLevel) { // Ignore log return; } var locationInformation = loggingEvent.LocationInformation; var log = new LogSource(locationInformation.FullInfo); // Map the Log4NET level, including the method and line number, to Dapplo.Log.LogInfo var number = int.Parse(locationInformation.LineNumber); var logInfo = log.Info(number, locationInformation.MethodName); if (LevelIn(loggingEvent.Level, Level.Error)) { logInfo = log.Error(number, locationInformation.MethodName); } if (LevelIn(loggingEvent.Level, Level.Fatal, Level.Critical, Level.Alert, Level.Emergency)) { logInfo = log.Fatal(number, locationInformation.MethodName); } if (LevelIn(loggingEvent.Level, Level.Warn, Level.Severe)) { logInfo = log.Warn(number, locationInformation.MethodName); } if (LevelIn(loggingEvent.Level, Level.Debug)) { logInfo = log.Debug(number, locationInformation.MethodName); } if (LevelIn(loggingEvent.Level, Level.Verbose, Level.Fine, Level.Finer, Level.Finest, Level.Trace)) { logInfo = log.Verbose(number, locationInformation.MethodName); } // Log the actual message, use Log4Net for the rendering logInfo.WriteLine(loggingEvent.RenderedMessage); }
/// <returns> /// URL of help file in selected ietf, or (if not present) default ietf, or null (if not present, too. probably /// indicating that there is no internet connection) /// </returns> private static string FindOnlineHelpUrl(string currentIetf) { string ret = null; var extHelpUrlForCurrrentIETF = ExtHelpUrl; if (!currentIetf.Equals("en-US")) { extHelpUrlForCurrrentIETF += currentIetf.ToLower() + "/"; } var httpStatusCode = GetHttpStatus(extHelpUrlForCurrrentIETF); if (httpStatusCode == HttpStatusCode.OK) { ret = extHelpUrlForCurrrentIETF; } else if (httpStatusCode != null && !extHelpUrlForCurrrentIETF.Equals(ExtHelpUrl)) { Log.Debug().WriteLine("Localized online help not found at {0}, will try {1} as fallback", extHelpUrlForCurrrentIETF, ExtHelpUrl); httpStatusCode = GetHttpStatus(ExtHelpUrl); if (httpStatusCode == HttpStatusCode.OK) { ret = ExtHelpUrl; } else { Log.Warn().WriteLine("{0} returned status {1}", ExtHelpUrl, httpStatusCode); } } else if (httpStatusCode == null) { Log.Info().WriteLine("Internet connection does not seem to be available, will load help from file system."); } return(ret); }
/// <summary> /// Try to resolve the requested assembly via Nuget, locally and remote. /// </summary> internal Assembly NugetResolveEventHandler(object sender, ResolveEventArgs resolveEventArgs) { if (resolveEventArgs.Name.Contains("resources")) { return(null); } var assemblyName = new AssemblyName(resolveEventArgs.Name); Log.Debug().WriteLine("Trying to resolve {0}", assemblyName.Name); try { var remoteRepository = PackageRepositoryFactory.Default.CreateRepository(RemotePackageSource); // Create a package manager for managing our local repository IPackageManager packageManager = new PackageManager(remoteRepository, LocalPackageSource); var localRepository = packageManager.LocalRepository; var localPackages = localRepository.FindPackagesById(assemblyName.Name); var locatedPackage = FindPackage(assemblyName, localPackages); if (locatedPackage == null) { // Search package via NuGet remote var remotePackages = remoteRepository.FindPackagesById(assemblyName.Name); locatedPackage = FindPackage(assemblyName, remotePackages); if (locatedPackage != null) { packageManager.InstallPackage(locatedPackage.Id, locatedPackage.Version, true, false); } } return(ReturnAssemblyFromRepository(packageManager, assemblyName)); } catch (Exception ex) { Log.Warn().WriteLine(ex, "Problem using NuGet find an unresolved assembly"); } return(null); }
#pragma warning restore IDE0090 // Use 'new(...)' /// <summary> /// Get projects information /// See: https://docs.atlassian.com/jira/REST/latest/#d2e2779 /// </summary> /// <param name="jiraClient">IProjectDomain to bind the extension method to</param> /// <param name="projectKey">key of the project</param> /// <param name="cancellationToken">CancellationToken</param> /// <returns>ProjectDetails</returns> public static async Task <Project> GetAsync(this IProjectDomain jiraClient, string projectKey, CancellationToken cancellationToken = default) { if (projectKey == null) { throw new ArgumentNullException(nameof(projectKey)); } Log.Debug().WriteLine("Retrieving project {0}", projectKey); var projectUri = jiraClient.JiraRestUri.AppendSegments("project", projectKey); // Add the configurable expand values, if the value is not null or empty if (JiraConfig.ExpandGetProject?.Length > 0) { projectUri = projectUri.ExtendQuery("expand", string.Join(",", JiraConfig.ExpandGetProject)); } jiraClient.Behaviour.MakeCurrent(); var response = await projectUri.GetAsAsync <HttpResponse <Project, Error> >(cancellationToken).ConfigureAwait(false); return(response.HandleErrors()); }
/// <summary> /// Default constructor, this opens the input destop with GENERIC_ALL /// This is needed to support marshalling!! /// </summary> public SafeCurrentInputDesktopHandle() : base(true) { var hDesktop = User32Api.OpenInputDesktop(0, true, DesktopAccessRight.GENERIC_ALL); if (hDesktop != IntPtr.Zero) { // Got desktop, store it as handle for the ReleaseHandle SetHandle(hDesktop); if (User32Api.SetThreadDesktop(hDesktop)) { Log.Debug().WriteLine("Switched to desktop {0}", hDesktop); } else { Log.Warn().WriteLine("Couldn't switch to desktop {0}", hDesktop); Log.Error().WriteLine(User32Api.CreateWin32Exception("SetThreadDesktop")); } } else { Log.Warn().WriteLine("Couldn't get current desktop."); Log.Error().WriteLine(User32Api.CreateWin32Exception("OpenInputDesktop")); } }
/// <summary> /// Authorize the token by showing the authorization uri of the oauth service /// </summary> /// <param name="cancellationToken">CancellationToken</param> private async Task GetAuthorizeTokenAsync(CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrEmpty(_oAuth1Settings.RequestToken)) { throw new ArgumentNullException(nameof(_oAuth1Settings.RequestToken), "The request token is not set"); } IOAuthCodeReceiver codeReceiver; if (!CodeReceivers.TryGetValue(_oAuth1Settings.AuthorizeMode, out codeReceiver)) { throw new NotImplementedException($"Authorize mode '{_oAuth1Settings.AuthorizeMode}' is not implemented/registered."); } Log.Debug().WriteLine("Calling code receiver : {0}", _oAuth1Settings.AuthorizeMode); var result = await codeReceiver.ReceiveCodeAsync(_oAuth1Settings.AuthorizeMode, _oAuth1Settings, cancellationToken).ConfigureAwait(false); if (result != null) { string tokenValue; if (result.TryGetValue(OAuth1Parameters.Token.EnumValueOf(), out tokenValue)) { _oAuth1Settings.AuthorizeToken = tokenValue; } string verifierValue; if (result.TryGetValue(OAuth1Parameters.Verifier.EnumValueOf(), out verifierValue)) { _oAuth1Settings.Token.OAuthTokenVerifier = verifierValue; } } if (_oAuth1Settings.CheckVerifier) { if (!string.IsNullOrEmpty(_oAuth1Settings.Token.OAuthTokenVerifier)) { throw new Exception("Token verifier is not set, while CheckVerifier is set to true"); } } }
private void FormLoad(object sender, EventArgs e) { // Initialize the Language ComboBox comboBoxLanguage.DisplayMember = "Value"; comboBoxLanguage.ValueMember = "Key"; // Set datasource last to prevent problems // See: http://www.codeproject.com/KB/database/scomlistcontrolbinding.aspx?fid=111644 comboBoxLanguage.DataSource = LanguageLoader.Current.AvailableLanguages.ToList(); var currentLanguage = LanguageLoader.Current.CurrentLanguage; if (currentLanguage != null) { Log.Debug().WriteLine("Selecting {0}", currentLanguage); comboBoxLanguage.SelectedValue = currentLanguage; } else { comboBoxLanguage.SelectedValue = Thread.CurrentThread.CurrentUICulture.Name; } // Close again when there is only one language, this shows the form briefly! // But the use-case is not so interesting, only happens once, to invest a lot of time here. if (LanguageLoader.Current.AvailableLanguages.Count != 1) { return; } comboBoxLanguage.SelectedValue = LanguageLoader.Current.AvailableLanguages.Keys.FirstOrDefault(); // TODO: Check var ignoreTask = LanguageLoader.Current.ChangeLanguageAsync(SelectedLanguage); _properOkPressed = true; Close(); }