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); }
private MultiplexingConverter _GetConverter() { var obj = new MultiplexingConverter(); obj.Begin += (s, e) => _Log.DebugFormat("Conversion begin, phase count: {0}", e.Value); obj.Error += (s, e) => _Log.Error(e.Value); obj.Warning += (s, e) => _Log.Warn(e.Value); obj.PhaseChanged += (s, e) => _Log.InfoFormat("PhaseChanged: {0} - {1}", e.Value, e.Value2); obj.ProgressChanged += (s, e) => _Log.InfoFormat("ProgressChanged: {0} - {1}", e.Value, e.Value2); obj.Finished += (s, e) => _Log.InfoFormat("Finished: {0}", e.Value ? "success" : "failed!"); return(obj); }
private void DispatchOnError(CommonErrorEventArgs e) { if (OnError != null) { try { OnError(this, e); } catch (Exception ex) { _Log.Error("Unhandled exception thrown OnError event handler.", ex); } } }
public static string FromHexString(string hexString) { try { string ascii = string.Empty; for (int i = 2; i < hexString.Length - 1; i += 2) { var hs = string.Empty; hs = hexString.Substring(i, 2); uint decval = Convert.ToUInt32(hs, 16); char character = Convert.ToChar(decval); ascii += character; } return(ascii); } catch (Exception ex) { _Log.Error(ex.Message); } return(string.Empty); }
public WkHtmlToPdfConverter() { bool useX11 = false; try { useX11 = SysConvert.ToBoolean(ConfigurationManager.AppSettings["WkHtmlToXSharp.UseX11"]); } catch (Exception ex) { _Log.Error("Unable to parse 'WkHtmlToXSharp.UseX11' app. setting.", ex); } // Try to deploy native libraries bundles. WkHtmlToXLibrariesManager.InitializeNativeLibrary(); var version = NativeCalls.WkHtmlToPdfVersion(); if (NativeCalls.wkhtmltopdf_init(useX11 ? 1 : 0) == 0) { throw new InvalidOperationException(string.Format("wkhtmltopdf_init failed! (version: {0}, useX11 = {1})", version, useX11)); } _Log.DebugFormat("Initialized new converter instance (Version: {0}, UseX11 = {1})", version, useX11); }
/// <summary> /// Callback method called by the NetworkStream's thread when a message /// arrives. /// </summary> /// <param name="state">The state object holding information about /// the connection.</param> private void ReceiveComplete(IAsyncResult state) { try { int bytesReceived = 0; using (new ReadOnlyLock(_socketLock)) { if (_TcpClient != null) { bytesReceived = _TcpClient.GetStream().EndRead(state); } } //if there are bytes to process, do so. Otherwise, the //connection has been lost, so clean it up if (bytesReceived > 0) { try { //send the incoming message to the message handler _MessageHandler(this); } catch (Exception ex) { _Log.Error(string.Format("Instance {0} - {1} => Receive message handler failed.", this.GetHashCode(), _ThreadId), ex); } } // XXX: If readBytesCount == 0 --> Connection has been closed. // XXX: Access _TcpClient.Client.Available to ensure socket is still working.. //start listening again Receive(); } catch (Exception ex) { _Log.Warn("Receive failed.", ex); //the connection has been dropped so call the CloseHandler try { _SocketCloseHandler(this); } finally { _Log.WarnFormat("Instance {0} - {1} => Connection terminated, disposing..", this.GetHashCode(), _ThreadId); Dispose(); } } }
private static void SendMessage(string command) { var parts = command.Split(' '); var dest = parts[1]; var msgTxt = string.Join(" ", parts, 2, parts.Length - 2); if (string.IsNullOrEmpty(msgTxt)) { msgTxt = @"السلام عليكم ورحمة الله وبركاته هذه رسالة عربية متعددة الاسطر"; } TextMessage msg = new TextMessage(); msg.DestinationAddress = dest; //Receipient number msg.SourceAddress = smppConfig.SourceAddress; //Originating number //msg.Text = "Hello, this is my test message!"; msg.Text = msgTxt; msg.RegisterDeliveryNotification = true; //I want delivery notification for this message msg.UserMessageReference = GenerateUserMessageReference(smppConfig.UserMessageReferenceType); _Log.DebugFormat($"msg.UserMessageReference: {msg.UserMessageReference}"); try { client.SendMessage(msg); } catch (SmppException smppEx) { _Log.ErrorFormat("smppEx.ErrorCode:({0}) {1} ", (int)smppEx.ErrorCode, smppEx.ErrorCode); _Log.Error(smppEx); } catch (Exception e) { _Log.Error("SendMessage:" + e.Message, e); } //client.BeginSendMessage(msg, SendMessageCompleteCallback, client); }
public static string DumpStringWithTry(object obj, SmppEncodingService encodingService = null) { try { return(DumpStringDefault(obj, encodingService)); } catch (Exception ex) { if (_Log.IsErrorEnabled) { _Log.Error(ex); } return(null); } }
public ResponsePDU SendPdu(RequestPDU pdu, int timeout) { SendPduBase(pdu); if (pdu.HasResponse) { try { return(vRespHandler.WaitResponse(pdu, timeout)); } catch (SmppResponseTimedOutException) { _Log.Error("200016:PDU send operation timed out;"); if (vTraceSwitch.TraceWarning) { Trace.WriteLine("200016:PDU send operation timed out;"); } throw; } } else { return(null); } }
public void CanConvertConcurrently() { var error = false; var threads = new List <ThreadData>(); for (int i = 0; i < 8; i++) { var tmp = new ThreadData() { Thread = new Thread(ThreadStart), WaitHandle = new ManualResetEvent(false) }; threads.Add(tmp); tmp.Thread.Start(tmp); } var handles = threads.Select(x => x.WaitHandle).ToArray(); Assert.IsTrue(WaitHandle.WaitAll(handles, ConcurrentTimeout), "At least one thread timeout"); //WaitAll(handles); threads.ForEach(x => x.Thread.Abort()); var exceptions = threads.Select(x => x.Exception).Where(x => x != null); foreach (var tmp in threads) { if (tmp.Exception != null) { error = true; var tid = tmp.Thread.ManagedThreadId; _Log.Error("Thread-" + tid + " failed!", tmp.Exception); } } Assert.IsFalse(error, "At least one thread failed!"); }
public WkHtmlToPdfConverter() { bool useX11 = false; try { useX11 = SysConvert.ToBoolean(ConfigurationManager.AppSettings["WkHtmlToXSharp.UseX11"]); } catch (Exception ex) { _Log.Error("Unable to parse 'WkHtmlToXSharp.UseX11' app. setting.", ex); } var ptr = wkhtmltopdf_version(); var version = Marshal.PtrToStringAnsi(ptr); if (!wkhtmltopdf_init(useX11 ? 1 : 0)) { throw new InvalidOperationException(string.Format("wkhtmltopdf_init failed! (version: {0}, useX11 = {1})", version, useX11)); } _Log.DebugFormat("Initialized new converter instance (Version: {0}, UseX11 = {1})", version, useX11); }
public void Error(Object message, Exception exception) { _log.Error(message, exception); }
public GitResult MergeAndPush(GitRepository repository, string branchName, string mergeInto, string mergeAuthor) { // should never happen, but check anyways if (!repository.Exists()) { Logger.Error(m => m("[{0}] Non-existing/initialized repository: Tried to merge branch '{1}' into '{2}'.", repository.RepositoryIdentifier, branchName, mergeInto)); // TODO: maybe initialize anyways? Not supposed to happen, but meh. return(repository.MakeFailureResult(string.Format( "Tried to perform a merge on a Non-existing/initialized repository '{0}' (merging '{1}' into '{2}')", repository.RepositoryIdentifier, branchName, mergeInto))); } string remoteName = repository.RemoteName; if (!repository.Checkout(mergeInto)) { return(repository.MakeFailureResult($"Failed to switch to branch '{mergeInto}' before merge.")); } // retry at most 3 times. having bad luck once during the push is one thing, but twice is unlikely. // more than that is probably not worth it and will just take up extra time we don't want to waste here. const int maxRetryCount = 3; int retryCount = maxRetryCount; // not an actual infinite loop; it will only run multiple times when the push fails. // everything else will exit the loop and method at the same time with a return. while (true) { if (!repository.Pull(mergeInto)) { return(repository.MakeFailureResult($"Failed to update '{mergeInto}' from '{remoteName}' before merge.")); } string oldHeadRev = repository.GetHashFor("HEAD"); if (string.IsNullOrWhiteSpace(oldHeadRev)) { return(repository.MakeFailureResult("Pre-Merge: Failed to retrieve current HEAD. This is probably a bad thing and needs to be fixed by a human.")); } if (!repository.Merge(branchName)) { repository.MergeAbort(); return(repository.MakeFailureResult($"Failed to merge '{branchName}' into '{mergeInto}'.")); } string newHeadRef = repository.GetHashFor("HEAD"); if (string.IsNullOrWhiteSpace(newHeadRef)) { repository.MergeAbort(); return(repository.MakeFailureResult("Post-Merge: Failed to retrieve current HEAD. This is probably a bad thing and needs to be fixed by a human.")); } bool branchAlreadyMerged = newHeadRef == oldHeadRev; if (branchAlreadyMerged) { Logger.Info(m => m("[{0}] Merge did not create a new commit; this branch has been merged already.", repository.RepositoryIdentifier)); } else { if (!repository.MergeAmendAuthor(branchName, mergeAuthor)) { return(repository.MakeFailureResult("Failed to update commit message after merge.")); } if (!repository.Push(mergeInto)) { // see if reached our retry count; if not we'll just try again under the assumption someone else pushed to the // remote in the meantime. if (retryCount-- > 0) { // TODO: technically we should check if git told us to "fetch first" (ie. our merge simply had bad timing and // someone else push their changes in the meantime. but since we only retry 3 times, it's easier to just ignore that. Logger.Info(m => m("Failed to push the merge; retrying {0}/{1}", (maxRetryCount - retryCount), maxRetryCount)); // try to reset our target branch back; or we might run into issues when trying to re-do the merge if (!repository.Reset(mergeInto)) { // add some wait time before retrying. the first retry will wait for 0 seconds (which effectively turns into a yield) // while all following retries wait for 5 seconds times the retry counter (so, 0s -> 5s -> 10s at most). Thread.Sleep(TimeSpan.FromSeconds((maxRetryCount - retryCount - 1) * 5)); continue; } } return(repository.MakeFailureResult(string.Format( "Failed to push branch '{0}' to '{1}' after merge. This was attempted {2} times, all of them unsuccessful.", mergeInto, remoteName, maxRetryCount))); } } var pushDeleteResult = repository.PushDelete(branchName); if (!pushDeleteResult) { string message; if (branchAlreadyMerged) { message = string.Format("Branch '{0}' was already merged, and deleting the remote branch '{1}/{0}' failed.", branchName, remoteName); } else { message = string.Format("Successfully merged '{0}' into '{1}', but deleting the remote branch '{2}/{0}' failed.", branchName, mergeInto, remoteName); } return(repository.MakeSuccessResultIncludingOutput(message)); } if (branchAlreadyMerged) { return(repository.MakeSuccessResult(string.Format( "Branch '{0}' was already merged, but we deleted the left-over remote branch '{1}/{0}' for you.", branchName, remoteName))); } else { return(repository.MakeSuccessResult(string.Format( "Successfully merged '{0}' into '{1}' and deleted remote branch '{2}/{0}'.", branchName, mergeInto, remoteName))); } } }
/// <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, }); }