public IssueDetails GetIssueDetails(string issueKey) { var baseUri = new Uri(_jiraSettings.BaseUrl); var requestUri = new Uri(baseUri, $"rest/api/2/issue/{issueKey}"); var request = WebRequest.CreateHttp(requestUri); request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes($"{_jiraSettings.UserName}:{_jiraSettings.Password}")); request.Accept = "application/json"; request.Method = "GET"; try { var response = request.GetResponse(); using (var streamReader = new StreamReader(response.GetResponseStream())) { string responseString = streamReader.ReadToEnd(); Logger.Debug(m => m("Response for IssueDetails: {0}", responseString)); var httpResponse = response as HttpWebResponse; if (httpResponse?.StatusCode == HttpStatusCode.OK) { // TODO: maybe check for Json? return(IssueDetails.ParseFromJson(responseString)); } } } catch (WebException ex) { using (var streamReader = new StreamReader(ex.Response.GetResponseStream())) Logger.Error(m => m("Request to '{0}' apparently failed: {1}\r\n{2}", requestUri, ex.Message, streamReader.ReadToEnd()), ex); } return(null); }
public void QueueRequest(MergeRequest mergeRequest) { // initially update the merge request with information from the POST request (or wherever it came from). // we might do another update later to make sure the data is still relevant. UpdateIssueDetails(mergeRequest, mergeRequest.IssueDetails); if (!ShouldTryToMerge(mergeRequest)) { return; } Task.Run(() => { bool shouldMerge; if (mergeRequest.IssueDetails == null) { Logger.Info(m => m("Got a merge request without associated Jira issue. Guess we should merge that one either way.")); shouldMerge = true; } else { Logger.Debug(m => m("Waiting a bit before queuing merge request for '{0}'", mergeRequest.IssueDetails.Key)); // wait a bit before actually queuing the request; someone might have accidentally closed the Jira issue Thread.Sleep(_gitSettings.MergeDelay); var issueDetails = _jira.GetIssueDetails(mergeRequest.IssueDetails.Key); if (issueDetails == null) { Logger.Warn(m => m("Jira didn't return any issue information while trying to check if we should still merge '{0}'; not doing a merge.", mergeRequest.IssueDetails.Key)); shouldMerge = false; } else if (!_jiraSettings.ClosedStatus.Contains(issueDetails.Status)) { Logger.Info(m => m("Related Jira issue is NOT closed; not doing a merge.")); shouldMerge = false; } else { shouldMerge = !ShouldPreventAutomerge(issueDetails); Logger.Info(m => m("Related Jira issue indicates it should {0}be merged, {0}preceding with merge.", shouldMerge ? "" : "not ")); if (shouldMerge) { UpdateIssueDetails(mergeRequest, issueDetails); } } } if (shouldMerge) { // HandleMergeRequests should only get valid ones, so check if the request is still valid _mergeRequests.Add(mergeRequest); } }); }
public static async System.Threading.Tasks.Task<System.IO.Stream> GetWorkflowAttachmentData(int attachmentid) { //... Setup SqlCommand 1st return Blob or SQLFileStream // The reader needs to be executed with the SequentialAccess behavior to enable network streaming // Otherwise ReadAsync will buffer the entire BLOB into memory which can cause scalability issues or even OutOfMemoryExceptions SqlDataReader reader = await cmd.ExecuteReaderAsync(System.Data.CommandBehavior.SequentialAccess); if (await reader.ReadAsync()) { if (!(await reader.IsDBNullAsync(0))) { return new Lib.OnEventStream(reader.GetStream(0), OnClosed: (Lib.OnEventStream stream) => { Log.Debug("Stream Close; Disposing DB items."); reader.Dispose(); cmd.Dispose(); db.Dispose(); } ); } } }
/// <summary> /// Sends a user-specified Pdu(see the RoaminSMPP base library for /// Pdu types). This allows complete flexibility for sending Pdus. /// </summary> /// <param name="packet">The Pdu to send.</param> /// <returns>The sequence number of the sent PDU, or null if failed.</returns> public uint SendPdu(Pdu packet) { _Log.DebugFormat("Sending PDU: {0}", packet); if (packet.SequenceNumber == 0) { packet.SequenceNumber = GenerateSequenceNumber(); } var bytes = packet.GetEncodedPdu(); try { if (asClient == null || !asClient.Connected) { throw new InvalidOperationException("Session not connected to remote party."); } if (!(packet is SmppBind) && !_Bound) { throw new InvalidOperationException("Session not bound to remote party."); } asClient.Send(bytes); return(packet.SequenceNumber); } catch { lock (_bindingLock) { _Log.Debug("SendPdu failed, scheduling a re-bind operation."); _ReBindRequired = true; } throw; // Let the exception flow.. } }
private byte[] _Convert(string inputHtml) { var converter = IntPtr.Zero; var errorCb = new NativeCalls.wkhtmltopdf_str_callback(OnError); var warnCb = new NativeCalls.wkhtmltopdf_str_callback(OnWarning); var phaseCb = new NativeCalls.wkhtmltopdf_void_callback(OnPhaseChanged); var progressCb = new NativeCalls.wkhtmltopdf_int_callback(OnProgressChanged); var finishCb = new NativeCalls.wkhtmltopdf_bool_callback(OnFinished); try { var gSettings = _BuildGlobalSettings(); var oSettings = _BuildObjectsettings(); converter = _BuildConverter(gSettings, oSettings, inputHtml); _errorString = new StringBuilder(); NativeCalls.wkhtmltopdf_set_error_callback(converter, errorCb); NativeCalls.wkhtmltopdf_set_warning_callback(converter, warnCb); NativeCalls.wkhtmltopdf_set_phase_changed_callback(converter, phaseCb); NativeCalls.wkhtmltopdf_set_progress_changed_callback(converter, progressCb); NativeCalls.wkhtmltopdf_set_finished_callback(converter, finishCb); OnBegin(NativeCalls.wkhtmltopdf_phase_count(converter)); if (NativeCalls.wkhtmltopdf_convert(converter) == 0) { var msg = string.Format("HtmlToPdf conversion failed: {0}", _errorString.ToString()); throw new ConverterException(msg); } if (!string.IsNullOrEmpty(GlobalSettings.Out)) { return(null); } _Log.Debug("CONVERSION DONE.. getting output."); // Get output from internal buffer.. IntPtr tmp = IntPtr.Zero; var ret = NativeCalls.wkhtmltopdf_get_output(converter, out tmp); var output = new byte[ret.ToInt32()]; Marshal.Copy(tmp, output, 0, output.Length); return(output); } catch { // Dispose un-managed resources.. try { NativeCalls.wkhtmltopdf_deinit(); } catch (DllNotFoundException) { // We may not be initialized yet } throw; } finally { if (converter != IntPtr.Zero) { NativeCalls.wkhtmltopdf_set_error_callback(converter, null); NativeCalls.wkhtmltopdf_set_warning_callback(converter, null); NativeCalls.wkhtmltopdf_set_phase_changed_callback(converter, null); NativeCalls.wkhtmltopdf_set_progress_changed_callback(converter, null); NativeCalls.wkhtmltopdf_set_finished_callback(converter, null); NativeCalls.wkhtmltopdf_destroy_converter(converter); converter = IntPtr.Zero; } } }
private byte[] _Convert(string inputHtml) { var converter = IntPtr.Zero; var inputHtmlUtf8Ptr = IntPtr.Zero; var errorCb = new wkhtmltopdf_str_callback(OnError); var warnCb = new wkhtmltopdf_str_callback(OnWarning); var phaseCb = new wkhtmltopdf_void_callback(OnPhaseChanged); var progressCb = new wkhtmltopdf_int_callback(OnProgressChanged); var finishCb = new wkhtmltopdf_bool_callback(OnFinished); try { var gSettings = _BuildGlobalSettings(); var oSettings = _BuildObjectsettings(); inputHtmlUtf8Ptr = Marshaller.StringToUtf8Ptr(inputHtml); converter = _BuildConverter(gSettings, oSettings, inputHtmlUtf8Ptr); _errorString = new StringBuilder(); wkhtmltopdf_set_error_callback(converter, errorCb); wkhtmltopdf_set_warning_callback(converter, warnCb); wkhtmltopdf_set_phase_changed_callback(converter, phaseCb); wkhtmltopdf_set_progress_changed_callback(converter, progressCb); wkhtmltopdf_set_finished_callback(converter, finishCb); OnBegin(wkhtmltopdf_phase_count(converter)); if (!wkhtmltopdf_convert(converter)) { var msg = string.Format("HtmlToPdf conversion failed: {0}", _errorString.ToString()); throw new ApplicationException(msg); } if (!string.IsNullOrEmpty(GlobalSettings.Out)) { return(null); } _Log.Debug("CONVERSION DONE.. getting output."); // Get output from internal buffer.. IntPtr tmp = IntPtr.Zero; var len = wkhtmltopdf_get_output(converter, out tmp); var output = new byte[len]; Marshal.Copy(tmp, output, 0, output.Length); return(output); } finally { if (converter != IntPtr.Zero) { wkhtmltopdf_set_error_callback(converter, null); wkhtmltopdf_set_warning_callback(converter, null); wkhtmltopdf_set_phase_changed_callback(converter, null); wkhtmltopdf_set_progress_changed_callback(converter, null); wkhtmltopdf_set_finished_callback(converter, null); wkhtmltopdf_destroy_converter(converter); } if (inputHtmlUtf8Ptr != IntPtr.Zero) { Marshaller.FreeUtf8Ptr(inputHtmlUtf8Ptr); } } }
public void Debug(Object message, Exception exception) { _log.Debug(message, exception); }
public IEnumerable <GitRepositoryBranch> FindBranch(string branchName, bool isExactBranchName) { Logger.Debug(m => m("Trying to find matching repositories for '{0}' (exact match: {1})", branchName, isExactBranchName)); foreach (var repositoryInfo in _gitSettings.Repositories) { var repository = Get(repositoryInfo); if (!repository.Exists()) { if (!repository.Initialize()) { // TODO: notify someone that the repository couldn't be initialized? continue; } } else { if (!repository.Fetch()) { // TODO: notify someone that the fetch failed? continue; } } string[] branches = repository.Branches(); Logger.Debug(m => m("Found {0} branches: {1}", branches.Length, string.Join(", ", branches))); if (isExactBranchName) { // assume an exact branch match is always intentional, and must never be ignored. // might happen that a review/testing/whatever branch supersedes the real one, // and the lazy developer simply inputs their branch name as source. if (branches.Contains(branchName)) { Logger.Info(m => m("Got an exact branch name match for '{0}' in '{1}'.", branchName, repository.RepositoryIdentifier)); yield return(new GitRepositoryBranch(repository, branchName)); } // else: no such branch. probably, nothing to do for this repository // TODO: maybe check if theres a matching branch of different casing? } else { // since its not an exact match, we can assume it is a Jira issue key. // they follow the pattern "<project key>-<issue number>", where the issue number is strictly numeric; // and the project key only contains letters, numbers or the underscore (always starting with a letter). // append a negative look-ahead for digits, which should prevent matching partial issue numbers. // we cannot use word-boundaries here, since it will not match names such as JRA-123b or JRA-123_fixed. // NOTE: this is mostly convention being used in practise; this might not match all configurations on all systems. // FIXME: this does not account for the beginning of the branch name; but in practise we do not have overlap // (and therefore don't need to check for it right now) var jiraIssueKey = new Regex(branchName + @"(?!\d)", RegexOptions.IgnoreCase); var matchingBranches = branches.Where(branch => jiraIssueKey.IsMatch(branch)); var nonIgnoredBranches = matchingBranches.Where(IsEligibleBranchForMerging).ToArray(); var ignoredBranches = matchingBranches.Except(nonIgnoredBranches).Select(b => $"{b} (ignored)").ToArray(); if (nonIgnoredBranches.Count() == 1) { Logger.Info(m => m("Found a branch name match for '{0}' (exact spelling is '{1}') in '{2}'.", branchName, matchingBranches.First(), repository.RepositoryIdentifier)); yield return(new GitRepositoryBranch(repository, matchingBranches.First())); } else if (nonIgnoredBranches.Count() + ignoredBranches.Count() > 0) { var branchesToLog = nonIgnoredBranches.Concat(ignoredBranches); Logger.Warn(m => m("Found {0} branches matching '{1}' in repository '{2}', cannot decide which one they wanted: {3}", matchingBranches.Count(), branchName, repository.RepositoryIdentifier, string.Join(", ", branchesToLog))); foreach (string matchingBranchName in nonIgnoredBranches) { yield return(new GitRepositoryBranch(repository, matchingBranchName)); } foreach (string matchingBranchName in ignoredBranches) { yield return new GitRepositoryBranch(repository, matchingBranchName) { IsIgnored = true } } ; } } } }
private byte[] _Convert(string inputHtml) { var converter = IntPtr.Zero; _errorCallback = OnError; _warnCallback = OnWarning; _phaseCallback = OnPhaseChanged; _progressCallback = OnProgressChanged; _finishCallback = OnFinished; try { var gSettings = _BuildGlobalSettings(); var oSettings = _BuildObjectsettings(); converter = _BuildConverter(gSettings, oSettings, inputHtml); _errorString = new StringBuilder(); NativeCalls.wkhtmltopdf_set_error_callback(converter, _errorCallback); NativeCalls.wkhtmltopdf_set_warning_callback(converter, _warnCallback); NativeCalls.wkhtmltopdf_set_phase_changed_callback(converter, _phaseCallback); NativeCalls.wkhtmltopdf_set_progress_changed_callback(converter, _progressCallback); NativeCalls.wkhtmltopdf_set_finished_callback(converter, _finishCallback); OnBegin(NativeCalls.wkhtmltopdf_phase_count(converter)); if (NativeCalls.wkhtmltopdf_convert(converter) == 0) { var msg = string.Format("HtmlToPdf conversion failed: {0}", _errorString.ToString()); throw new ConverterException(msg); } if (!string.IsNullOrEmpty(GlobalSettings.Out)) { return(null); } _Log.Debug("CONVERSION DONE.. getting output."); // Get output from internal buffer.. IntPtr tmp = IntPtr.Zero; var ret = NativeCalls.wkhtmltopdf_get_output(converter, out tmp); var output = new byte[ret.ToInt32()]; Marshal.Copy(tmp, output, 0, output.Length); return(output); } finally { if (converter != IntPtr.Zero) { NativeCalls.wkhtmltopdf_set_error_callback(converter, null); NativeCalls.wkhtmltopdf_set_warning_callback(converter, null); NativeCalls.wkhtmltopdf_set_phase_changed_callback(converter, null); NativeCalls.wkhtmltopdf_set_progress_changed_callback(converter, null); NativeCalls.wkhtmltopdf_set_finished_callback(converter, null); NativeCalls.wkhtmltopdf_destroy_converter(converter); converter = IntPtr.Zero; } } }
/// <summary> /// Executes the given command without storing the result as <see cref="LastResult"/> /// </summary> public ExecuteResult ExecuteSilent(string workingDirectory, string format, params object[] args) { string arguments = string.Format(format, args); var p = new Process { StartInfo = new ProcessStartInfo(_gitSettings.GitExecutable, arguments) { UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true, RedirectStandardInput = false, WorkingDirectory = workingDirectory, } }; Logger.Debug(m => m("Running command '{0}' with command line arguments (working directory is: '{1}'):\r\n{2}", p.StartInfo.FileName, p.StartInfo.WorkingDirectory ?? "not set", p.StartInfo.Arguments)); var stdout = new List <string>(); var stderr = new List <string>(); var stdoutEvent = new ManualResetEvent(false); var stderrEvent = new ManualResetEvent(false); var exited = new ManualResetEvent(false); p.OutputDataReceived += (s, e) => { if (string.IsNullOrEmpty(e.Data)) { stdoutEvent.Set(); } else { stdout.Add(e.Data); } }; p.ErrorDataReceived += (s, e) => { if (string.IsNullOrEmpty(e.Data)) { stderrEvent.Set(); } else { stderr.Add(e.Data); } }; p.Exited += (s, e) => exited.Set(); p.EnableRaisingEvents = true; try { p.Start(); p.BeginOutputReadLine(); p.BeginErrorReadLine(); WaitHandle.WaitAll(new[] { stdoutEvent, stderrEvent, exited }); } catch (Exception ex) { Logger.Error(m => m("Running '{0}' failed with exception: {1}", p.StartInfo.FileName, ex.Message), ex); if (!p.HasExited) { p.Kill(); } } return(new ExecuteResult(p.ExitCode, stdout, stderr) { StartInfo = p.StartInfo, }); }