/// <summary> /// Logwriters the specified source. /// </summary> /// <param name="source">object that wrote the logentry.</param> /// <param name="prio">Importance of the log message</param> /// <param name="message">The message.</param> public void Write(object source, LogPrio prio, string message) { StringBuilder sb = new StringBuilder(); sb.Append(DateTime.Now.ToString()); sb.Append(" "); sb.Append(prio.ToString().PadRight(10)); sb.Append(" | "); #if DEBUG StackTrace trace = new StackTrace(); StackFrame[] frames = trace.GetFrames(); int endFrame = frames.Length > 4 ? 4 : frames.Length; int startFrame = frames.Length > 0 ? 1 : 0; for (int i = startFrame; i < endFrame; ++i) { sb.Append(frames[i].GetMethod().Name); sb.Append(" -> "); } #else sb.Append(System.Reflection.MethodBase.GetCurrentMethod().Name); sb.Append(" | "); #endif sb.Append(message); Console.ForegroundColor = GetColor(prio); Console.WriteLine(sb.ToString()); Console.ForegroundColor = ConsoleColor.Gray; }
public string GetCurrentMethod() { var st = new StackTrace(); StackFrame sf = st.GetFrame(1); return sf.GetMethod().Name; }
// Copied from NLog static string GetClassFullName() { string className; Type declaringType; int framesToSkip = 2; do { #if SILVERLIGHT StackFrame frame = new StackTrace().GetFrame(framesToSkip); #else StackFrame frame = new StackFrame(framesToSkip, false); #endif MethodBase method = frame.GetMethod(); declaringType = method.DeclaringType; if (declaringType == null) { className = method.Name; break; } framesToSkip++; className = declaringType.FullName; } while (declaringType.Module.Name.Equals("mscorlib.dll", StringComparison.OrdinalIgnoreCase)); return className; }
private static string findCallToLoadPackages() { var trace = new StackTrace(Thread.CurrentThread, false); var frame = trace.GetFrame(2); return "{0}.{1}(), {2} line {3}".ToFormat(frame.GetMethod().DeclaringType.FullName, frame.GetMethod().Name, frame.GetFileName(), frame.GetFileLineNumber()); }
public static string CallerMethodName() { StackTrace stackTrace = new StackTrace(); StackFrame stackFrame = stackTrace.GetFrame(2); MethodBase methodBase = stackFrame.GetMethod(); return methodBase.Name; }
private SqlConnectionLifetimeTracker(SqlConnection sqlConnection) { this.con = sqlConnection; stateChangeListener = new System.Data.StateChangeEventHandler(con_StateChange); sqlConnection.StateChange += stateChangeListener; responsibleStack = new StackTrace(2); }
//************************************************** // 関数名 :LogInfo // 機能説明 :ログ情報をログファイルに書き込む。 // 引数 :logInfo ログ情報 // 引数 :args ログ詳細情報 // 修正履歴 :2010/04/13 //************************************************** public void LogInfo(string logInfo, params object[] args) { string cHeader = ""; string cLogTime = ""; cLogTime = System.DateTime.Now.ToString(); if (args != null && args.Length > 0) { logInfo = String.Format(logInfo, args); } StackTrace st = new StackTrace(true); StackFrame sf = st.GetFrame(1); //cHeader = sf.GetMethod cHeader = sf.GetMethod().ReflectedType.FullName + "." + sf.GetMethod().Name + "()"; cHeader = cLogTime + " [" + cHeader + "] "; //ログ情報 logInfo = cHeader + logInfo + Environment.NewLine; try { //'ログ情報はログファイルに書き込む。 File.AppendAllText(LogFileName, logInfo); } catch (Exception ex) { logInfo = String.Format("異常が発生しました。{0}", ex); //'ログ情報はログファイルに書き込む。 File.AppendAllText(LogFileName, logInfo); } }
private bool AddTrace(string Type, int Length, string Label) { bool flag = !this.Tracing; checked { bool result; if (flag) { result = (this.Ptr + Length >= this.Buffer.Length); } else { Parser.BufferedReader.xTraceStruc xTraceStruc = default(Parser.BufferedReader.xTraceStruc); StackTrace stackTrace = new StackTrace(); xTraceStruc.Type = Type; xTraceStruc.Length = Length; xTraceStruc.Label = Label; xTraceStruc.Caller = stackTrace.GetFrame(2).GetMethod().Name; xTraceStruc.Value = "[NULL]"; this.xTraceInfo.Add(xTraceStruc); flag = (this.Ptr + Length > this.Buffer.Length); if (flag) { this.DebugDump("Read past end", Parser.ParserReturns.Failed); result = true; } else { result = false; } } return result; } }
/// <summary> /// Converts an Exception to a verbose string /// </summary> public static string ExceptionToString(Exception e) { string message; if (object.ReferenceEquals(FormatException, null)) { var trace = new StackTrace(e, true); var frame = trace.GetFrame(0); var file = frame.GetFileName(); var line = frame.GetFileLineNumber(); StringBuilder sb = new StringBuilder(String.Format("{0} line {1}", file, line)); sb.AppendLine(""); sb.AppendLine(String.Format("[Source] {0} : [Message] {1}", e.Source, e.Message)); sb.AppendLine(""); sb.AppendLine(e.ToString()); message = sb.ToString(); } else { message = FormatException(e); } return message; }
public static string GetTestMethodName() { StackTrace st = new StackTrace(); StackFrame sf = st.GetFrame(2); return sf.GetMethod().Name; }
public override void Eval(MockDirectoryWrapper dir) { if (DoFail && TestThread()) { bool isDoFlush = false; bool isClose = false; var trace = new StackTrace(); foreach (var frame in trace.GetFrames()) { var method = frame.GetMethod(); if (isDoFlush && isClose) { break; } if ("flush".Equals(method.Name)) { isDoFlush = true; } if ("close".Equals(method.Name)) { isClose = true; } } if (isDoFlush && !isClose && Random().NextBoolean()) { HitExc = true; throw new IOException(Thread.CurrentThread.Name + ": now failing during flush"); } } }
public PagerState(AbstractPager pager) { _pager = pager; #if DEBUG_PAGER_STATE Instances[this] = new StackTrace(true); #endif }
// Methods public ErrorEvent() { base.m_Severity = EventSeverity.Error; base.m_EventID = 0x3e8; base.m_Message = string.Format("Error in '{0}'", base.m_CallingMethod.ToString()); StringBuilder builder1 = new StringBuilder(0x3e8); try { StackTrace trace1 = new StackTrace(true); int num1 = 2; Type type1 = null; do { num1++; type1 = trace1.GetFrame(num1).GetMethod().DeclaringType; } while ((num1 < trace1.FrameCount) && type1.IsSubclassOf(typeof (BaseEvent))); for (int num2 = num1; num2 < trace1.FrameCount; num2++) { StackFrame frame1 = trace1.GetFrame(num2); if (num2 > num1) { builder1.Append('|'); } builder1.AppendFormat("{{{0}}}:{1}:{2}", ReflectionHelper.MethodSignature(frame1.GetMethod()), frame1.GetFileName(), frame1.GetFileLineNumber()); } } catch { } base.AddProperty("StackTrace", builder1.ToString()); }
private void LoadReport(int memberid, string fromDate, string toDate) { try { List<ReportParameter> rp = new List<ReportParameter>(); rp.Add(new ReportParameter("MemberID", memberid.ToString())); rp.Add(new ReportParameter("StartDate", fromDate)); rp.Add(new ReportParameter("RunDate", toDate)); //ReportViewer1.ServerReport.ReportPath = "/APT.Reports/BenefitStatement"; ReportViewer1.ServerReport.ReportPath = "/APT.Reports/APTARFInvestmentStatementWeb"; ReportViewer1.ServerReport.ReportServerUrl = new Uri(ConfigurationManager.AppSettings["ReportServerUrl"]); ReportViewer1.ServerReport.ReportServerCredentials = new ReportCredentials(ConfigurationManager.AppSettings["ReportServerUser"], ConfigurationManager.AppSettings["ReportServerPassword"], ConfigurationManager.AppSettings["ReportServerDomain"]); ReportViewer1.ServerReport.SetParameters(rp); ReportViewer1.ShowParameterPrompts = false; ReportViewer1.ServerReport.Refresh(); } catch (Exception ex) { StackTrace stackTrace = new StackTrace(); APTLog.LogException(ex, stackTrace.GetFrame(0).GetMethod().Name, APT2012AssemblyInfo.AssemblyInfo, APT2012AssemblyInfo.SUBSYSTEM); //throw ex; } }
public static string OutputStack() { StackTrace stackTrace = new StackTrace(); StackFrame stackFrame; MethodBase stackFrameMethod; string typeName = string.Empty; string newTypeName; StringBuilder sb = null; sb = new StringBuilder(); int position = 0; for (int x = position; x < stackTrace.FrameCount; x++) { stackFrame = stackTrace.GetFrame(x); stackFrameMethod = stackFrame.GetMethod(); newTypeName = stackFrameMethod.ReflectedType.FullName; if (newTypeName != typeName) { sb.AppendLine(); sb.AppendLine(newTypeName); typeName = newTypeName; } sb.Append(stackFrameMethod); sb.Append(" "); } return sb.ToString(); }
/// <summary> /// 全スレッドのスタックトレースを出力します。 /// </summary> public void WriteStackTrace() { var threads = Process.GetCurrentProcess().Threads; foreach (var th in threads) { var thread = th as Thread; if (thread == null) { continue; } var stackTrace = new StackTrace(thread, true); var strBuilder = new StringBuilder(); strBuilder.AppendLine("StackTrace:"); foreach (var frame in StackTraceUtil.ToStackTraceString(stackTrace)) { strBuilder.AppendFormat( " {0}", frame); strBuilder.AppendLine(); } Log.Info("begin lock {0}{1}{2}", this.lockId, Environment.NewLine, strBuilder.ToString()); } }
public void OnGUI() { ICollection<MethodReport> failedTests = Suite.FailedTests; if (failedTests.Count != 0) { int i = 0; foreach (MethodReport failedTest in failedTests) { string filePath = null; int lineNumber = -1; StackTrace trace = new StackTrace(failedTest.RaisedException, true); foreach (StackFrame frame in trace.GetFrames()) { if (frame.GetMethod().DeclaringType.GetCustomAttribute<JUUTTestClassAttribute>() != null) { string fullPath = frame.GetFileName(); if (fullPath != null) { filePath = fullPath.Substring(fullPath.IndexOf("Assets", System.StringComparison.Ordinal)); lineNumber = frame.GetFileLineNumber(); } break; } } if (filePath != null) { if (GUI.Button(new Rect(10, 10 + i * 25, 600, 20), failedTest.ShortText)) { JUUTUnityUtil.OpenTestFile(filePath, lineNumber); } } i++; } } }
protected void gvContributions_RowDataBound(object sender, GridViewRowEventArgs e) { try { if (e.Row.RowType != DataControlRowType.Header) { DataRowView drv = e.Row.DataItem as DataRowView; if (drv != null) { Object dateVal = drv["DateReceived"]; if (!Convert.IsDBNull(dateVal)) { e.Row.Attributes.Add("onclick", "GetContributions('" + dateVal.ToString() + "');"); } } e.Row.Attributes.Add("onmouseover", "highlight(this, true);"); e.Row.Attributes.Add("onmouseout", "highlight(this, false);"); e.Row.Attributes.Add("onmouseup", "selectedRow(this);"); } } catch (Exception ex) { StackTrace stackTrace = new StackTrace(); APTLog.LogException(ex, stackTrace.GetFrame(0).GetMethod().Name, APT2012AssemblyInfo.AssemblyInfo, APT2012AssemblyInfo.SUBSYSTEM); //throw ex; } }
/// <summary> /// The object to lock. /// </summary> /// <param retval="o">The object to lock.</param> /// <param retval="timeout">The timeout.</param> /// <returns></returns> /// <exception cref="LockTimeoutException"> /// </exception> public static TimedLock Lock(object o, TimeSpan timeout) { var tl = new TimedLock(o); if (!Monitor.TryEnter(o, timeout)) { #if DEBUG GC.SuppressFinalize(tl._leakDetector); StackTrace blockingTrace; lock (Sentinel.StackTraces) { blockingTrace = Sentinel.StackTraces[o] as StackTrace; } throw new LockTimeoutException(blockingTrace); #else throw new LockTimeoutException(); #endif } #if DEBUG // Lock acquired. Store the stack trace. var trace = new StackTrace(); lock (Sentinel.StackTraces) { Sentinel.StackTraces.Add(o, trace); } #endif return tl; }
/// <summary> /// Converts an exception stack to a sarif code location list. /// </summary> public static IList<AnnotatedCodeLocation> ToCodeLocations(this Exception exception) { List<AnnotatedCodeLocation> codeLocations = new List<AnnotatedCodeLocation>(); StackTrace stack = new StackTrace(exception); foreach (StackFrame frame in stack.GetFrames()) { AnnotatedCodeLocation codeLocation = new AnnotatedCodeLocation(); MemberInfo member = frame.GetMethod(); if (member != null) { codeLocation.Message = member.ReflectedType.FullName + "." + member.Name; } PhysicalLocationComponent physicalLocation = new PhysicalLocationComponent(); string filename = frame.GetFileName(); if (!String.IsNullOrWhiteSpace(filename)) { physicalLocation.Uri = new Uri(filename); } physicalLocation.Region = new Region(); physicalLocation.Region.StartLine = frame.GetFileLineNumber(); physicalLocation.Region.EndLine = frame.GetFileLineNumber(); physicalLocation.Region.StartColumn = frame.GetFileColumnNumber(); physicalLocation.Region.EndColumn = frame.GetFileColumnNumber(); codeLocation.PhysicalLocation = new List<PhysicalLocationComponent>() { physicalLocation }; codeLocations.Add(codeLocation); } return codeLocations; }
public LogEventArgs(string message, MessageType messageType, StackTrace st) { this.message = message; this.dateTime = DateTime.Now; this.messageType = messageType; this.stackTrace = st; }
protected void Page_Load(object sender, EventArgs e) { try { if (!IsPostBack) { int selectedSchemeId = (int)Session["SelectedSchemeId"]; int selectedEmployeeId = (int)Session["SelectedEmployeeId"]; List<ReportParameter> rp = new List<ReportParameter>(); rp.Add(new ReportParameter("SchemeId", selectedSchemeId.ToString())); rp.Add(new ReportParameter("Currency", Employer.GetCurrency(selectedEmployeeId))); ReportViewer1.ServerReport.ReportPath = "/APT.Reports/TrusteeSchemeMemberContributionRates"; ReportViewer1.ServerReport.ReportServerUrl = new Uri(ConfigurationManager.AppSettings["ReportServerUrl"]); ReportViewer1.ServerReport.ReportServerCredentials = new ReportCredentials(ConfigurationManager.AppSettings["ReportServerUser"], ConfigurationManager.AppSettings["ReportServerPassword"], ConfigurationManager.AppSettings["ReportServerDomain"]); ReportViewer1.ServerReport.SetParameters(rp); ReportViewer1.ShowParameterPrompts = false; ReportViewer1.ServerReport.Refresh(); } } catch (Exception ex) { StackTrace stackTrace = new StackTrace(); APTLog.LogException(ex, stackTrace.GetFrame(0).GetMethod().Name, APT2012AssemblyInfo.AssemblyInfo, APT2012AssemblyInfo.SUBSYSTEM); //throw ex; } }
/// <summary> /// Initializes a new instance of the <see cref="Tracer"/> class. /// Results in a method entry trace being output. /// </summary> public Tracer() { if (!_isTracingEnabled) { return; } // Due to optimizations during JIT compilation the StackTrace and its properties are not reliable // especially when the following code is in a separate method // http://www.smelser.net/blog/2008/11/default.aspx _numberOfCallingMethodParams = 0; _callingMethodName = "Not available"; StackTrace stackTrace = new StackTrace(); StackFrame callingMethodFrame = stackTrace.GetFrame(1); if (callingMethodFrame != null) { MethodBase methodInfo = callingMethodFrame.GetMethod(); if (methodInfo != null) { ParameterInfo[] parameterInfo = methodInfo.GetParameters(); _numberOfCallingMethodParams = parameterInfo.Count(); Type declaringType = methodInfo.DeclaringType; if (declaringType != null) { _callingMethodName = declaringType.Name + "." + methodInfo.Name; } } } TraceMethodEntry(null); }
public bool Parse(StackTrace stackTrace) { foreach (IStackTraceParser p in GetParsers()) { if (p.Parse(stackTrace)) { parser = p; return true; } } var helpLink = @"http://blog.approvaltests.com/2012/01/creating-namers.html"; throw new Exception( string.Format("Approvals is not set up to use your test framework.{0}" + "It currently supports {1}{0}" + "To add one use {2}.AddParser() method to add implementation of {3} with support for your testing framework.{0}" + "To learn how to implement one see {4}", Environment.NewLine, ForTestingFramework, GetType(), typeof (IStackTraceParser), helpLink)) { HelpLink = helpLink }; }
public override void Fail (string message, string detailMessage) { var frames = new StackTrace (1, true).GetFrames (); //find the stack frame that actually called into the trace system int callerFrame = 0; for (; (callerFrame < frames.Length && IsInfrastructureMethod (frames [callerFrame])); callerFrame++) continue; if (callerFrame == frames.Length - 1) callerFrame = 0; var sb = new StringBuilder (); if (IsRealMessage (message)) { if (!string.IsNullOrEmpty (detailMessage)) { sb.AppendFormat ("Failed assertion: {0} - {1}", message, detailMessage); } else { sb.AppendFormat ("Failed assertion: {0}", message); } } else { sb.Append ("Failed assertion at "); FormatStackFrame (sb, frames [callerFrame]); callerFrame++; } sb.Append ("\n"); FormatStackTrace (sb, frames, callerFrame); LoggingService.LogError (sb.ToString ()); }
public static string GetCurrentMethod(int frame) { StackTrace st = new StackTrace(); StackFrame sf = st.GetFrame(frame); return sf.GetMethod().Name; }
public LocalizationManager(string resourceName, string baseDir = "") { _resourcePath = Path.Combine(baseDir, resourceName); if (!File.Exists(_resourcePath + ".lang")) { Stream stream = null; var st = new StackTrace(); var mb = st.GetFrame(1).GetMethod(); if (mb.DeclaringType != null) { var namesp = mb.DeclaringType.Namespace; var ass = mb.DeclaringType.Assembly; stream = ass.GetManifestResourceStream(namesp + "." + resourceName + ".lang"); } if (stream == null) throw new IOException(); _defaultStrings = ParseLangStream(stream); stream.Dispose(); } else { _defaultStrings = ParseLangFile(_resourcePath + ".lang"); } LoadLangPack(); }
public GraphDBError() { Message = default(String); #if DEBUG StackTrace = new StackTrace(true); #endif }
public static void LogInfo(Exception ex) { try { //Writes error information to the log file including name of the file, line number & error message description //Console.WriteLine("Start"); stackTrace = new StackTrace(ex, true); //Console.WriteLine("Frames: {0}", stackTrace.FrameCount); //Console.WriteLine("Frame 0: {0}", stackTrace.GetFrame(0).GetFileName()); //string fileNames = stackTrace.GetFrame((stackTrace.FrameCount - 1)).GetFileName(); //Console.WriteLine(fileNames); //fileNames = fileNames.Substring(fileNames.LastIndexOf(Application.ProductName)); //Console.WriteLine("Rawr"); //Int32 lineNumber = stackTrace.GetFrame((stackTrace.FrameCount - 1)).GetFileLineNumber(); //Console.WriteLine(lineNumber); methodBase = stackTrace.GetFrame((stackTrace.FrameCount - 1)).GetMethod(); //These two lines are respnsible to find out name of the method String methodName = methodBase.Name; Info("Error in method " + methodName + ". Message: " + ex.Message); //Info("Error in " + fileNames + ". Method name is " + methodName + ", at line number " + lineNumber.ToString() + ". Error Message: " + ex.Message); } catch (Exception genEx) { Info(genEx.Message); Log.LogInfo(genEx); } finally { Dispose(); } }
/// <summary> /// Runs an appropriate Action method. /// Uses the class this call lives in as target type and command line arguments from Environment /// </summary> public static void Run() { Type declaringType = new StackTrace().GetFrame(1).GetMethod().DeclaringType; string[] args = new string[Environment.GetCommandLineArgs().Length - 1]; new List<string>(Environment.GetCommandLineArgs()).CopyTo(1, args, 0, Environment.GetCommandLineArgs().Length - 1); Run(declaringType, args); }
} //end SetMultiple public static unsafe bool CopyFast(ref byte[] destination, ref byte[] src, int iDestByte, int iSrcByte, int iBytes) { try { fixed(byte *lpDest = destination, lpSrc = src) //keeps GC at bay { byte *lpDestNow = lpDest; byte *lpSrcNow = lpSrc; lpSrcNow += iSrcByte; lpDestNow += iDestByte; for (int i = iBytes >> 3; i != 0; i--) { *((ulong *)lpDestNow) = *((ulong *)lpSrcNow); //64bit chunks lpDestNow += 8; lpSrcNow += 8; } //remainder<64bits: for (iBytes &= 7; iBytes != 0; iBytes--) { *lpDestNow = *lpSrcNow; lpDestNow++; lpSrcNow++; } } } catch (Exception e) { StackTrace stacktraceNow = new System.Diagnostics.StackTrace(); StackFrame[] stackframesNow = stacktraceNow.GetFrames(); string sStackFrames = ""; for (int i = 0; i < stackframesNow.Length; i++) { sStackFrames += (i != 0?" via ":"") + stackframesNow[i].GetMethod().Name; } RReporting.ShowExn(e, "copying data", "RMemory CopyFast(destination=" + (destination != null?"non-null":"null") + ";src=" + (src != null?"non-null":"null") + ", iDestByte=" + iDestByte.ToString() + ", iSrcByte=" + iSrcByte.ToString() + ", iBytes=" + iBytes.ToString() + ") {Called-By:" + sStackFrames + "}"); return(false); } return(true); }
private void CollectStackTraceInfo(System.Diagnostics.StackTrace _stackTrace) { // Gathering information related to stackoverflow StringBuilder _desciptionBuilder = new StringBuilder(); int _totalFrames = _stackTrace.FrameCount; int _totalFramesMinus1 = _totalFrames - 1; // Append stacktrace info for (int _iter = 0; _iter < _totalFrames; _iter++) { StackFrame _stackFrame = _stackTrace.GetFrame(_iter); // Method info MethodBase _method = _stackFrame.GetMethod(); string _methodName = _method.ToString(); string _className = _method.DeclaringType.FullName; _desciptionBuilder.AppendFormat("{0}:{1}", _className, _methodName); // File info string _fileAbsolutePath = _stackFrame.GetFileName(); if (!string.IsNullOrEmpty(_fileAbsolutePath)) { string _fileRelativePath = GetRelativePath(_fileAbsolutePath); // Following unity standard stacktrace output "class-name:method-definition() (at relative-path:10)" _desciptionBuilder.AppendFormat("(at {0}:{1})", _fileRelativePath, _stackFrame.GetFileLineNumber()); } if (_iter < _totalFramesMinus1) { _desciptionBuilder.AppendLine(); } } // Set value StackTrace = _desciptionBuilder.ToString(); }
static string GetStackTrace(Exception e) { string stackTrace = ""; try { StackTrace st = new System.Diagnostics.StackTrace(e); foreach (StackFrame frame in st.GetFrames()) { stackTrace = "at " + frame.GetMethod().Module.Name + "." + frame.GetMethod().ReflectedType.Name + "." + frame.GetMethod().Name + " (IL offset: 0x" + frame.GetILOffset().ToString("x") + ")\n" + stackTrace; } Console.Write(stackTrace); Console.WriteLine("Message: " + e.Message); } catch { } return(stackTrace); }
public virtual int Bulk <T>(DataContext dataContext, IEnumerable <T> entities, BulkQuery query) { var result = 0; var command = query.GetCommandTransactional(true); WriteLog(dataContext, command.Command.CommandText); foreach (var item in entities) { try { query.SetParameterValues(item, command.Command); command.Command.ExecuteNonQuery(); result++; } catch (Exception ex) { var caller = new System.Diagnostics.StackTrace().GetFrame(1).GetMethod().Name; WriteLog(dataContext, string.Format("Error in {0}:\t {1}", caller, ParametersToString <T>(command))); throw ex; } } Commit(command); return(result); }
public void TraceCallers(int Depth) { #if DEBUG if (_switch.Enabled) { System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(1); if (Depth < 0) { Depth = st.FrameCount; } Indent(); for (int i = 0; i < st.FrameCount && i < Depth; i++) { System.Diagnostics.StackFrame sf = st.GetFrame(i); Trace(sf.GetMethod() + "+" + sf.GetILOffset().ToString()); } Unindent(); } #endif }
}//processFile //=============================================================== private void _LogTest() { //Trace|Debug|Info|Warn|Error|Fatal { System.Diagnostics.StackTrace StackTraceTmp = new System.Diagnostics.StackTrace(true); System.Diagnostics.StackFrame StackFrameTmp = null; int count = StackTraceTmp.FrameCount; for (int i = 0; i < count; i++) { StackFrameTmp = StackTraceTmp.GetFrame(i); //Console.WriteLine(StackFrameTmp.ToString() + StackFrameTmp.GetFileLineNumber() + StackFrameTmp.GetFileName()); //NLog.LogManager.GetCurrentClassLogger().Trace("StackFrameTmp.ToString={0} StackFrameTmp.GetFileName={1} StackFrameTmp.GetFileLineNumber={2}", // StackFrameTmp.ToString(), StackFrameTmp.GetFileName(), StackFrameTmp.GetFileLineNumber()); } } // <!--None,Fatal,ERROR,WARN,DEBUG,INFO,ALL--> log4net.LogManager.GetLogger("ExeLogger").Info(System.String.Format("Info")); log4net.LogManager.GetLogger("ExeLogger").Debug(System.String.Format("Debug")); log4net.LogManager.GetLogger("ExeLogger").Warn(System.String.Format("Warn")); log4net.LogManager.GetLogger("ExeLogger").Error(System.String.Format("Error")); //log4net.LogManager.GetLogger("Fatal").Fatal(System.String.Format("Fatal")); }
/// <summary> /// Logs the current stack so that in the event of a desync we have some stack traces. /// </summary> /// <param name="info">Any additional message to be logged with the stack</param> public void TryAddStackTraceForDesyncLog(string info = null) { if (!ShouldCollect) { return; } CurrentOpinion.TryMarkSimulating(); //Get the current stack trace var trace = new System.Diagnostics.StackTrace(2, true); var hash = trace.Hash() ^ (info?.GetHashCode() ?? 0); CurrentOpinion.desyncStackTraces.Add(new StackTraceLogItem { stackTrace = trace, tick = TickPatch.Timer, hash = hash, additionalInfo = info, }); // Track & network trace hash, for comparison with other opinions. currentOpinion.desyncStackTraceHashes.Add(hash); }
public static void log(string astrlog, LOG_LEVEL aenumLogLevel = LOG_LEVEL.INFO, Boolean abPrintStack = true) { try { lock (m_strLogLocker) { if (ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None) != null && (ThreadUiController.m_nlogLevel <= (int)aenumLogLevel) && astrlog != null && (InitLog() || !IsLogExceedLength()) ) { FileInfo info = new FileInfo(GetlogFileName()); m_logger = new StreamWriter(info.Open(FileMode.Append, FileAccess.Write, FileShare.ReadWrite)); string format = "{0} | [{1}] | {2} \r\n"; StringBuilder builder = new StringBuilder(); string str2 = DateTime.Now.ToString("yyyy'-'MM'-'dd' 'HH':'mm':'ss"); builder.AppendFormat(format, str2, aenumLogLevel, astrlog); if (aenumLogLevel == LOG_LEVEL.FATAL || aenumLogLevel == LOG_LEVEL.ERROR || abPrintStack) { var l_CurrentStack = new System.Diagnostics.StackTrace(true); String lstrData = l_CurrentStack.ToString(); builder.Append(lstrData); } m_logger.Write(builder.ToString()); m_logger.Flush(); m_logger.Close(); m_logger = null; } } } catch (Exception) { } }
/// <summary> /// 指定された内容をログに出力します。 /// </summary> /// <param name="msg">ログに出力する内容</param> public void Print(String msg) { try { FileOpen(); FileWrite(msg); if (TraceTriggerText.Length > 0) { if (msg.IndexOf(TraceTriggerText) >= 0) { // 情報 FileWrite("Track trace ==>"); System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(); for (int i = 0; i < st.FrameCount; i++) { System.Diagnostics.StackFrame sf = st.GetFrame(i); FileWrite(" - " + sf.ToString().Replace("\r\n", "")); } } } } catch (Exception es) { try { FileWrite(EXCEPTION_MESSAGE + es.Message); } catch { } } finally { FileClose(); } }
//====================================================== public static DataTable MySQL_Retrieve(SQLTypedef SQL) { MySqlDataAdapter mysql_adapter; MySqlCommand cmd; DataTable dt = new DataTable(); string sqlstring = "SELECT * FROM " + SQL.FROM; //SHOW FULL FIELDS FROM 資料庫.資料表 看註解用 cmd = new MySqlCommand(sqlstring, SQL.SQLConnection); try { MySQL_Disconnection(SQL); MySQL_Connection(SQL); mysql_adapter = new MySqlDataAdapter(cmd); mysql_adapter.Fill(dt); MySQL_Disconnection(SQL); //CLEAR DT return(dt); } catch (Exception ex) { if (Debug == iOPEN) { //錯誤行數 StackTrace trace = new System.Diagnostics.StackTrace(ex, true); int line = trace.GetFrame(trace.FrameCount - 1).GetFileLineNumber(); //string filename = My.computer.FileSystem.GetName(trace.GetFrame(trace.FrameCount - 1).GetFileName); string functionName = trace.GetFrame(trace.FrameCount - 1).GetMethod().Name; errormsg = "錯誤發生於 " + functionName + " 函式中的第 " + Convert.ToString(line) + " 行\n" + "錯誤信息: " + ex.Message + "發生錯誤"; } return(dt); } }
public VulcanMessage(Severity severity, Exception innerException, string message, params object[] formatParmeters) { _innerException = innerException; _severity = severity; System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(); System.Diagnostics.StackFrame[] stackFrames = st.GetFrames(); MethodBase method = null; foreach (System.Diagnostics.StackFrame sf in stackFrames) { method = sf.GetMethod(); if (method.ReflectedType.Equals(typeof(VulcanEngine.Common.MessageEngine)) || method.ReflectedType.Equals(typeof(VulcanEngine.Common.VulcanMessage))) { continue; } else { break; } } this._message = String.Format("{0}: {1}: {2}", severity, method.ReflectedType.Name, String.Format(message, formatParmeters)); }
public static void WriteException(Exception ex, string Controller, string Method, int Uid = 0, string ServerURl = "", string Ip = "", string UserIdentity = "", string Parameters = "") { try { var mth = new System.Diagnostics.StackTrace().GetFrame(1).GetMethod(); Controller = Controller + " / " + mth.ReflectedType.Name; Method = Method + " / " + mth.Name; AngleDBDataContext context = new AngleDBDataContext(); //string na = this.GetType().Name; while (ex != null) { TblException Ex = new TblException { Controller = Controller, Method = Method, DateTime = CustDateTime.GetCurrentDateTime(), TypeName = ex.GetType().FullName, Message = ex.Message, StackTrace = Parameters == "" ? ex.StackTrace : Parameters, C_Id = Uid, ServerUrl = ServerURl, Ip = Ip, userIdentity = UserIdentity, Website = "Dx" }; ex = ex.InnerException; context.TblExceptions.InsertOnSubmit(Ex); } context.SubmitChanges(); } catch (Exception ex1) { WriteExceptionInFile(ex, Controller, Method); WriteExceptionInFile(ex1, "UtilityClass", "WriteException"); } }
public static bool IsIdleWorkerPoolThread(System.Diagnostics.StackTrace trace) { // not blocked? if (trace.GetFrame(0).GetMethod().Name != "WaitOneNative" && trace.GetFrame(0).GetMethod().Name != "WaitOne" && trace.GetFrame(1).GetMethod().Name != "InternalWaitOne") { return(false); } // skip more blocking functions int frame = 2; while (trace.GetFrame(frame).GetMethod().Name == "WaitOne" || trace.GetFrame(frame).GetMethod().Name == "InternalWaitOne" || trace.GetFrame(frame).GetMethod().Name.StartsWith("<WaitForWork>") || trace.GetFrame(frame).GetMethod().Name == "WaitForWork" || trace.GetFrame(frame).GetMethod().Name == "RunWithLogException" || trace.GetFrame(frame).GetMethod().Name.StartsWith("<WorkerFunc>")) { ++frame; } // worker function or worker pool master? if ((trace.GetFrame(frame).GetMethod().Name == "WorkerFunc" && trace.GetFrame(frame).GetMethod().DeclaringType.ToString() == "Agilix.Shared.Worker") || (trace.GetFrame(frame).GetMethod().Name == "PoolMaster" && trace.GetFrame(frame).GetMethod().DeclaringType.ToString() == "Agilix.Shared.WorkerPool")) { return(true); } return(false); }
/// <summary> /// Notify a Unity log message if it the client has been configured to /// notify at the specified level, if not leave a breadcrumb with the log /// message. /// </summary> /// <param name="condition"></param> /// <param name="stackTrace"></param> /// <param name="logType"></param> void Notify(string condition, string stackTrace, LogType logType) { if (Configuration.AutoNotify && logType.IsGreaterThanOrEqualTo(Configuration.NotifyLevel)) { var logMessage = new UnityLogMessage(condition, stackTrace, logType); var shouldSend = Exception.ShouldSend(logMessage) && UniqueCounter.ShouldSend(logMessage) && LogTypeCounter.ShouldSend(logMessage); if (shouldSend) { var severity = Configuration.LogTypeSeverityMapping.Map(logType); var backupStackFrames = new System.Diagnostics.StackTrace(1, true).GetFrames(); var forceUnhandled = logType == LogType.Exception && !Configuration.ReportUncaughtExceptionsAsHandled; var exception = Exception.FromUnityLogMessage(logMessage, backupStackFrames, severity, forceUnhandled); Notify(new Exception[] { exception }, exception.HandledState, null, logType); } } else { Breadcrumbs.Leave(logType.ToString(), BreadcrumbType.Log, new Dictionary <string, string> { { "message", condition }, }); } }
public static string GetStack() { string str = ""; str += "\r\n"; System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(1, true); #if false string file_name; file_name = st.GetFrame(0).GetFileName(); str += " File:" + file_name; #endif string func_name; func_name = st.GetFrame(0).GetMethod().Name; str += " Func:" + func_name; int line; line = st.GetFrame(0).GetFileLineNumber(); str += " Line:" + line.ToString(); return(str); }
private static void CurrentDomain_UnhadledException(object sender, UnhandledExceptionEventArgs e) { var exception = e.ExceptionObject as Exception; var message = string.Empty; var stackTrace = string.Empty; if (exception != null) { var stack = new System.Diagnostics.StackTrace(exception, true); message = exception.GetFlattenInnerMessage(); stackTrace = stack.ToString(); } Log.Fatal("* CurrentDomain_UnhadledException:{0}\r\n{1}", message, stackTrace); //if (ExceptionHandler.DoUnhandledException(exception) == DialogResult.Abort) //{ // // Application.ThreadException은 해당 Exception을 처리하여 다음으로 진행하는데 // // CurrentDomain.UnhandledException은 종료 후에도 해당 Exception이 지속되어서 문제 발생 // // 다음으로 진행하는 버튼은 제거한다. // System.Diagnostics.Process.GetCurrentProcess().Kill(); //} }
/// <summary> /// Gets the stack trace with IL offsets /// </summary> public static string StackTraceIL(this Exception ex) { // Need to use IL offsets as proxy for line numbers in stack trace in Silverlight. Taken from // http://liviutrifoi.wordpress.com/2011/04/21/silverlight-stack-trace-line-numbers/ string stackTrace = null; try { StackTrace st = new System.Diagnostics.StackTrace(ex); if (st != null) { foreach (StackFrame frame in st.GetFrames()) { stackTrace = "at " + frame.GetMethod().Module.Name + "." + frame.GetMethod().ReflectedType.Name + "." + frame.GetMethod().Name + " (IL offset: 0x" + frame.GetILOffset().ToString("x") + ")\n" + stackTrace; } } } catch { } return(stackTrace); }
/// <summary> /// Produces an instance. /// </summary> /// <remarks> /// Search strategy is a simple linear probing which is chosen for it cache-friendliness. /// Note that Free will try to store recycled objects close to the start thus statistically /// reducing how far we will typically search. /// </remarks> internal T Allocate() { // PERF: Examine the first element. If that fails, AllocateSlow will look at the remaining elements. // Note that the initial read is optimistically not synchronized. That is intentional. // We will interlock only when we have a candidate. in a worst case we may miss some // recently returned objects. Not a big deal. T inst = firstItem; if (inst == null || inst != Interlocked.CompareExchange(ref firstItem, null, inst)) { inst = AllocateSlow(); } #if DETECT_LEAKS var tracker = new LeakTracker(); leakTrackers.Add(inst, tracker); #if TRACE_LEAKS var frame = new System.Diagnostics.StackTrace(false); tracker.Trace = frame; #endif #endif return(inst); }
//===================================================================== public static Boolean MySQL_Disconnection(SQLTypedef SQL) { try { if (SQL.SQLConnection.State == ConnectionState.Open) { SQL.SQLConnection.Close(); } return(true); } catch (Exception ex) { if (Debug == iOPEN) { //錯誤行數 StackTrace trace = new System.Diagnostics.StackTrace(ex, true); int line = trace.GetFrame(trace.FrameCount - 1).GetFileLineNumber(); //string filename = My.computer.FileSystem.GetName(trace.GetFrame(trace.FrameCount - 1).GetFileName); string functionName = trace.GetFrame(trace.FrameCount - 1).GetMethod().Name; errormsg = "錯誤發生於 " + functionName + " 函式中的第 " + Convert.ToString(line) + " 行\n" + "錯誤信息: " + ex.Message + "發生錯誤"; return(false); } } }
/// <summary> /// Создает и возвращает строковое представление текущего исключения, при этом выводится только указанное количество фреймов. /// </summary> /// <param name="exception">Текущее исключение.</param> /// <param name="stackLimit">Количество фреймов из стека вызовов, которое необходимо вставить в вывод.</param> /// <returns>Строковое представление текущего исключения.</returns> public static string ToString(this Exception exception, int stackLimit) { string text = exception.Message; string text2; if (text == null || text.Length <= 0) { text2 = exception.GetType().ToString(); } else { text2 = exception.GetType().ToString() + ": " + text; } if (exception.InnerException != null) { text2 = string.Concat(new string[] { text2, " ---> ", exception.InnerException.ToString(stackLimit), Environment.NewLine, " ", Environment_GetResourceString("Exception_EndOfInnerExceptionStack") }); } var trace = new System.Diagnostics.StackTrace(exception, true); string stackTrace = StackTrace_ToString(trace, stackLimit); if (stackTrace != null) { text2 = text2 + Environment.NewLine + stackTrace; } return(text2); }
public static string GetCurSourceFileName() { System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(1, true); return(st.GetFrame(0).GetFileName()); }
private void PrintLog() { System.Diagnostics.StackTrace pTrace = new System.Diagnostics.StackTrace(); UnityEngine.Debug.Log(string.Format("{0} - CObjectBaseTest", pTrace.GetFrame(1).GetMethod())); }
public static void Trace(System.Exception exception) { System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(exception, true); Debug.LogError("\"" + exception.Message + "\" " + trace.GetFrame(0).GetMethod().ReflectedType.FullName + "(" + trace.GetFrame(0).GetFileLineNumber() + ", " + trace.GetFrame(0).GetFileColumnNumber() + ")"); }
public static bool GetGoalie(string League, string Trigger, int HistoricalSeasonID, string SeasonTypeId, string Command) { var st = new StackTrace(); var sf = st.GetFrame(0); var currentMethod = sf.GetMethod(); var thisFile = new System.Diagnostics.StackTrace(true).GetFrame(0).GetFileName(); var web = new HtmlWeb(); var psnDoc = web.Load(Fetch.GetURL(League, Trigger, HistoricalSeasonID, SeasonTypeId)); #region Player total calculator var countPlayers = psnDoc.DocumentNode.SelectNodes(("//*[@id='lgtable_goaliestats51']/tbody/tr")); if (countPlayers == null) { return(false); } var playerTotal = countPlayers.Count; #endregion try { for (int i = 1; i <= playerTotal; i++) { var findPlayerNodes = psnDoc.DocumentNode.SelectNodes($"//*[@id='lgtable_goaliestats51']/tbody/tr[1]"); if (findPlayerNodes == null) { break; } foreach (var player in findPlayerNodes) { #region parse variables var position = ""; var lgRank = ""; var teamIconShort = ""; var playerName = ""; var gamesPlayed = ""; var record = ""; var goalsAgainst = ""; var shotsAgainst = ""; var saves = ""; var savePercentage = ""; var goalsAgainstAvg = ""; var cleanSheets = ""; var manOfTheMatch = ""; var avgMatchRating = ""; var playerShortURL = ""; #endregion position = WebUtility.HtmlDecode(player .SelectSingleNode($"//*[@id='lgtable_memberstats51']/tbody/tr[{i}]/td[2]/span").InnerText); teamIconShort = WebUtility.HtmlDecode(player.SelectSingleNode($"//*[@id='lgtable_goaliestats51']/tbody/tr[{i}]/td[2]/img").Attributes["src"].Value); playerName = WebUtility.HtmlDecode(player.SelectSingleNode($"//*[@id='lgtable_goaliestats51']/tbody/tr[{i}]/td[2]/a").InnerText); gamesPlayed = WebUtility.HtmlDecode(player.SelectSingleNode($"//*[@id='lgtable_goaliestats51']/tbody/tr[{i}]/td[4]").InnerText); record = WebUtility.HtmlDecode(player.SelectSingleNode($"//*[@id='lgtable_goaliestats51']/tbody/tr[{i}]/td[5]").InnerText); goalsAgainst = WebUtility.HtmlDecode(player.SelectSingleNode($"//*[@id='lgtable_goaliestats51']/tbody/tr[{i}]/td[6]").InnerText); shotsAgainst = WebUtility.HtmlDecode(player.SelectSingleNode($"//*[@id='lgtable_goaliestats51']/tbody/tr[{i}]/td[7]").InnerText); saves = WebUtility.HtmlDecode(player.SelectSingleNode($"//*[@id='lgtable_goaliestats51']/tbody/tr[{i}]/td[8]").InnerText); savePercentage = WebUtility.HtmlDecode(player.SelectSingleNode($"//*[@id='lgtable_goaliestats51']/tbody/tr[{i}]/td[9]").InnerText); goalsAgainstAvg = WebUtility.HtmlDecode(player.SelectSingleNode($"//*[@id='lgtable_goaliestats51']/tbody/tr[{i}]/td[10]").InnerText); cleanSheets = WebUtility.HtmlDecode(player.SelectSingleNode($"//*[@id='lgtable_goaliestats51']/tbody/tr[{i}]/td[11]").InnerText); manOfTheMatch = WebUtility.HtmlDecode(player.SelectSingleNode($"//*[@id='lgtable_goaliestats51']/tbody/tr[{i}]/td[12]").InnerText); avgMatchRating = WebUtility.HtmlDecode(player.SelectSingleNode($"//*[@id='lgtable_goaliestats51']/tbody/tr[{i}]/td[13]").InnerText); playerShortURL = WebUtility.HtmlDecode(player.SelectSingleNode($"//*[@id='lgtable_goaliestats51']/tbody/tr[{i}]/td[2]/a").Attributes["href"].Value); var playerURL = string.Join(string.Empty, "https://www.leaguegaming.com/forums/" + playerShortURL); var temp = HttpUtility.ParseQueryString(new Uri(playerURL).Query); var playerID = int.Parse(temp.Get("userid")); var iconEnlarge = teamIconShort.Replace("p16", "p100"); var iconURL = string.Join(string.Empty, "https://www.leaguegaming.com" + iconEnlarge); if (SeasonTypeId == "pre") { SeasonTypeId = "pre-season"; } else if (SeasonTypeId == "reg") { SeasonTypeId = "regular"; } if (savePercentage == String.Empty) { savePercentage = "0"; } Tools.DataSaver.SavePlayerUrl(playerID, playerName, playerURL); //Console.WriteLine($"Saved {playerName} url. GoaliEngine"); CareerEngine.GetCareer(playerID, playerName, League); //Console.WriteLine($"{playerName}, career saved. GoalieEngine"); DataSaver.SaveGoalie(playerID, League, playerName, gamesPlayed, record, goalsAgainst, shotsAgainst, saves, savePercentage, goalsAgainstAvg, cleanSheets, manOfTheMatch, avgMatchRating, playerURL, iconURL, Command, HistoricalSeasonID, SeasonTypeId); GC.Collect(); } } return(true); } catch (Exception e) { Log.Logger.Error(e, $"Error processing PSN Goalie Stats {currentMethod}"); return(false); } }
public static string GetStackTrace() { System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace(true); return(stackTrace.ToString()); }
public static void stackdump(string msg, params object[] @params) { Log.detail(msg, @params); System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace(); Log.trace("Called by {0}", t); }
public static int getLineNum(int preFrameCount = 1) { System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(preFrameCount, true); return(st.GetFrame(0).GetFileLineNumber()); }
// Load a CSV file into an array of rows and columns. // Assume there may be blank lines but every line has public static bool LoadCsv(string filename, out string[] _csvHeaders, out double[][] _csvData) { // Get the file's text. string [] csvHeaders = new string[0]; double [][] csvData = new double[0][]; try { string whole_file = System.IO.File.ReadAllText(filename); // Split into lines. whole_file = whole_file.Replace('\n', '\r'); string[] lines = whole_file.Split(new char[] { '\r' }, StringSplitOptions.RemoveEmptyEntries); //Check if empty if (lines.Length < 2) { MessageBox.Show("CSV file requires at least one entry", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return(false); } if (string.IsNullOrEmpty(lines[0])) { MessageBox.Show("CSV file missing header", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } int headerRow = 0; int firstDataRow = 1; if (lines[0].Contains("HP Tuners CSV Log File")) { //We have a HPL file for (int i = 0; i < lines.Length; i++) { if (lines[i].Equals("[Channel Data]")) { firstDataRow = i + 1; } if (lines[i].Equals("[Channel Information]")) { headerRow = i + 2; } if (firstDataRow != 1 && headerRow != 0) { break; } if (i == lines.Length - 2) { MessageBox.Show("Could not find [Channel Data] Or [Channel Information] within HPT CSV log file, giving up.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return(false); } } } // See how many rows and columns there are. int num_rows = lines.Length - firstDataRow - 1; int num_cols = lines[headerRow].Split(',').Length; // Allocate the data array. csvHeaders = new string[num_cols]; csvData = new double[num_rows - 1][]; // Load the array. string[] headerLine = lines[headerRow].Split(','); if (headerLine.Length < 3) { MessageBox.Show("Not enough headers in CSV file! Need at least three, possibly wrong file format? I'm giving up, sorry bro.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return(false); } csvHeaders = headerLine; Parallel.For(firstDataRow, num_rows, r => { string[] line_r = lines[r].Split(','); csvData[r - 1] = new double[num_cols]; for (int c = 0; c < num_cols; c++) { double result; if (String.IsNullOrEmpty(line_r[c])) { continue; } if (Double.TryParse(line_r[c], out result)) { csvData[r - 1][c] = result; } else { csvData[r - 1][c] = double.NaN; } } }); return(true); } catch (Exception e) { var currentStack = new System.Diagnostics.StackTrace(true); string stackTrace = currentStack.ToString(); FlexibleMessageBox.Show("Failed to open file due to error: " + e.Message + Environment.NewLine + "Stacktrace: " + Environment.NewLine + stackTrace, "Error", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2); return(false); } finally { _csvHeaders = csvHeaders; _csvData = csvData; } }
public static string getCurSourceFileName(int preFrameCount = 1) { System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(preFrameCount, true); return(st.GetFrame(0).GetFileName()); }
/// <summary> /// 获取网络数据 /// </summary> public static string RequestUrl(string url, Dictionary <string, string> requestParams = null, bool isPost = false, bool hasFile = false) { string postData = string.Empty; if (requestParams != null) { postData = string.Join("&", requestParams.Select(c => c.Key + "=" + c.Value)); } String responseFromServer = string.Empty; try { // Create a request using a URL that can receive a post. if (!isPost) { url += string.IsNullOrEmpty(postData) ? string.Empty : url.IndexOf("?") > -1 ? "&" : "?" + postData; } Console.WriteLine(url); WebRequest webRequest = HttpWebRequest.Create(url); { try { ((HttpWebRequest)webRequest).KeepAlive = false; webRequest.Timeout = 1000 * 30; // if (isPost) { // Set the Method property of the request to POST. webRequest.Method = "POST"; webRequest.Proxy = null; // Create POST data and convert it to a byte array. byte[] byteArray = System.Text.Encoding.ASCII.GetBytes(postData); // Set the ContentType property of the WebRequest. webRequest.ContentType = "application/x-www-form-urlencoded"; // Set the ContentLength property of the WebRequest. webRequest.ContentLength = byteArray.Length; // Get the request stream. using (System.IO.Stream dataStream = webRequest.GetRequestStream()) { dataStream.Write(byteArray, 0, byteArray.Length); } } } catch { } // Get the response. using (WebResponse response = webRequest.GetResponse()) { //Console.WriteLine(((HttpWebResponse)response).StatusDescription); // Get the stream containing content returned by the server. using (System.IO.Stream responseStream = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(responseStream)) { responseFromServer = reader.ReadToEnd(); } } } } } catch (Exception ex) { String error = ex.Message; System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace(); String method = stackTrace.GetFrame(0).GetMethod().Name; } return(responseFromServer); }