public GetFrame ( int index ) : System.Diagnostics.StackFrame | ||
index | int | |
return | System.Diagnostics.StackFrame |
/** * Retorna o nome do metodo e da classe chamada * param frame: Indice do frame na pilha de execucao do qual se deseja extrair o nome do metodo e da classe * Obs: o indice 0 representa o metodo atual, 1 representa quem chamou este metodo e assim por diante */ public static void GetCalledMethod(out string MethodName, out string ClassName, int frame = 2) { StackTrace stackTrace = new StackTrace(); MethodName = stackTrace.GetFrame(frame).GetMethod().Name; ClassName = stackTrace.GetFrame(frame).GetMethod().DeclaringType.Name; }
/// <summary> /// Writes error to error log file. /// </summary> /// <param name="x"></param> /// <param name="stackTrace"></param> public static void DumpError(Exception x,StackTrace stackTrace) { try { string source = stackTrace.GetFrame(0).GetMethod().DeclaringType.FullName + "." + stackTrace.GetFrame(0).GetMethod().Name + "()"; string errorText = ""; errorText += "//------------- function:" + source + " " + DateTime.Now.ToString() + "------------//\r\n"; errorText += x.Source + ":" + x.Message + "\r\n"; errorText += x.StackTrace; if(x is System.Data.SqlClient.SqlException) { System.Data.SqlClient.SqlException sX = (System.Data.SqlClient.SqlException)x; errorText += "\r\n\r\nSql errors:\r\n"; foreach(System.Data.SqlClient.SqlError sErr in sX.Errors) { errorText += "\n"; errorText += "Procedure: '" + sErr.Procedure + "' line: " + sErr.LineNumber.ToString() + " error: " + sErr.Number.ToString() + "\r\n"; errorText += "Message: " + sErr.Message + "\r\n"; } } SCore.WriteLog(m_Path + "mailServiceError.log",errorText); } catch { } }
/// <summary> /// Walk through stack until you encounter the first class that is not to be ignored and /// whose method does not have the <> /// </summary> /// <param name="typeToIgnore">Type to ignore as you travel the stack</param> /// <returns></returns> public static MethodBase FirstNonWrappedMethod(Type typeToIgnore) { // Go at least one up to ignore this method. int index = 1; StackTrace st = new StackTrace(); MethodBase mb = st.GetFrame(index).GetMethod(); while (true) { if ((typeToIgnore == null) || mb.DeclaringType.Name != typeToIgnore.Name && !mb.Name.Contains("<")) { return mb; } ++index; StackFrame sf = st.GetFrame(index); if (sf == null) { return mb; } MethodBase tmp = sf.GetMethod(); if (tmp == null) { return mb; } mb = tmp; } }
/// <summary> /// Writes error to error log file. /// </summary> /// <param name="virtualServer">Virtual server name.</param> /// <param name="x"></param> /// <param name="stackTrace"></param> public static void DumpError(string virtualServer,Exception x,StackTrace stackTrace) { try{ string source = stackTrace.GetFrame(0).GetMethod().DeclaringType.FullName + "." + stackTrace.GetFrame(0).GetMethod().Name + "()"; string errorText = x.Message + "\r\n"; errorText += "//------------- function: " + source + " " + DateTime.Now.ToString() + "------------//\r\n"; errorText += x.Source + " : " + x.Message + "\r\n"; errorText += x.StackTrace; if(x is System.Data.SqlClient.SqlException){ System.Data.SqlClient.SqlException sX = (System.Data.SqlClient.SqlException)x; errorText += "\r\n\r\nSql errors:\r\n"; foreach(System.Data.SqlClient.SqlError sErr in sX.Errors){ errorText += "\n"; errorText += "Procedure: '" + sErr.Procedure + "' line: " + sErr.LineNumber.ToString() + " error: " + sErr.Number.ToString() + "\r\n"; errorText += "Message: " + sErr.Message + "\r\n"; } } if(x.InnerException != null){ errorText += "\r\n\r\n//------------- Innner Exception ----------\r\n" + x.Message + "\r\n"; errorText += x.InnerException.ToString(); } DumpError(virtualServer,errorText); } catch{ } }
public static void TraceCaller(string msg) { // puts out the callstack and the msg try { StackTrace trace = new StackTrace(); if (trace != null && trace.GetFrame(1) != null) { MethodBase method = trace.GetFrame(1).GetMethod(); string line = ExtractInfo(method) + ": " + msg + "\n" + " caller is:"; if (trace.GetFrame(2) != null) { method = trace.GetFrame(2).GetMethod(); line += ExtractInfo(method); } LogLine(line); } else { LogLine("Method Unknown: " + msg); } } catch (Exception e) { Console.WriteLine(e.StackTrace); } }
internal static void FRIEND(string ns) { StackTrace trace = new StackTrace(); string text1 = trace.GetFrame(1).GetMethod().DeclaringType.Namespace; string str = trace.GetFrame(2).GetMethod().DeclaringType.Namespace; Assert(str.Equals(str) || str.Equals(ns), Environment.GetResourceString("RtType.InvalidCaller"), trace.ToString()); }
//this function is called inside AddData(string testDataPath, string testCase) public void AddData(string testDataPath, string testCase) { try { testData.GetTestData(testDataPath, testCase); AddData(0); } catch (Exception ex) { var st = new StackTrace(ex, true); var testFrame = st.GetFrame(0); for (int i = 0; i < st.FrameCount; i++) { testFrame = st.GetFrame(i); if (testFrame.GetFileName() != null) { if (testFrame.GetFileName().ToString().Contains("CUITFramework.cs") == true) { break; } } } // Get the top stack frame var frame = testFrame; // Get the line number from the stack frame var line = frame.GetFileLineNumber(); logTofile(_eLogPtah, "Error in AddData and in line: " + line); throw new Exception(ex.Message); } }
/** * 向日志文件写入调试信息 * @param className 类名 * @param content 写入内容 */ public static void Debug(string message) { StackTrace st = new StackTrace(true); String className = st.GetFrame(1).GetMethod().DeclaringType.FullName; String methodName = st.GetFrame(1).GetMethod().Name; Debug(className, methodName, message); }
// find first frame that is not "Trace" /// <summary> /// Searches through the stack trace, and locates the first method in the frames NOT matching the <see cref="Log"/> methods /// </summary> /// <param name="caller"> /// A <see cref="System.String"/> which upon success will contain the name of the caller /// </param> /// <param name="callerClass"> /// A <see cref="System.String"/> which upon success will contain the class name of the calling method /// </param> /// <param name="callerName"> /// A <see cref="System.String"/> which upon success will contain the full assembly name of the caller. /// </param> /// <param name="fullName"> /// A <see cref="System.String"/> which upon success will contain the fully qualified name of the caller /// </param> /// <returns> /// A <see cref="System.Boolean"/> which is <c>true</c> if a match was found, <c>false</c> otherwise /// </returns> public static bool FindFrame(out string caller, out string callerClass, out string callerName, out string fullName, out string callerNamespace) { string ignoredCallers = "Trace,Debug,Information,Warning,Error,Fatal,SetCallerInContext,ToLog"; StackTrace stackTrace = new StackTrace(); for (int i=1; i<=stackTrace.FrameCount; i++) { caller = stackTrace.GetFrame(i).GetMethod().Name; callerClass = stackTrace.GetFrame(i).GetMethod().DeclaringType.Name; callerName = stackTrace.GetFrame(i).GetMethod().DeclaringType.Assembly.GetName().Name; fullName = stackTrace.GetFrame(i).GetMethod().DeclaringType.FullName; callerNamespace = stackTrace.GetFrame(i).GetMethod().DeclaringType.Namespace; if (!ignoredCallers.Contains(caller)) { return true; } } caller = String.Empty; callerClass = String.Empty; callerName = String.Empty; fullName = String.Empty; callerNamespace = String.Empty; return false; }
static void Main(string[] args) { try { TwitterSearch.TwitterMain(); } catch (Exception ex) { var st = new StackTrace(ex, true); var frame = st.GetFrame(0); var line = st.GetFrame(0).GetFileLineNumber(); MethodBase site = ex.TargetSite; string sMethodName = site == null ? null : site.Name; Console.WriteLine("------------------"); Console.WriteLine(DateTime.Now.ToString()); Console.WriteLine("Line: " + line.ToString()); Console.WriteLine("Method: " + sMethodName); Console.WriteLine("Exception: " + ex.Message); Console.Write(ex.StackTrace.ToString()); Console.WriteLine(""); } catch { } }
/// <summary> /// Generates the HTML page with exception information /// </summary> /// <param name="e">Exception to get information from.</param> /// <param name="hideExceptionDetails">if set to <c>true</c> then exception details will not be shown.</param> /// <returns></returns> public static string Generate(Exception e, bool hideExceptionDetails = false) { if (e == null) return null; var tpl = Template.FromManifest("Diagnostics.ExceptionInfoPage.html"); tpl.Set("AcspNetVersion", new AssemblyInfo(Assembly.GetCallingAssembly()).Version); if (hideExceptionDetails) { tpl.Set("ExceptionDetails", ""); return tpl.Get(); } var detailsTpl = Template.FromManifest("Diagnostics.ExceptionIDetails.html"); var trace = new StackTrace(e, true); if (trace.FrameCount == 0) return null; var fileLineNumber = trace.GetFrame(0).GetFileLineNumber(); var fileColumnNumber = trace.GetFrame(0).GetFileColumnNumber(); var positionPrefix = fileLineNumber == 0 && fileColumnNumber == 0 ? "" : String.Format("[{0}:{1}]", fileLineNumber, fileColumnNumber); detailsTpl.Set("StackTrace", String.Format("{0} {1} : {2}{3}{4}{5}", positionPrefix, e.GetType(), e.Message, Environment.NewLine + Environment.NewLine, trace, GetInnerExceptionData(1, e.InnerException)).Replace(Environment.NewLine, "<br />")); tpl.Set("ExceptionDetails", detailsTpl); return tpl.Get(); }
// 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()); }
public static void Print(String str) { var trace = new StackTrace(); _mainWindow.PrintLine(string.Format("[{0} - {1}.{2}]: {3}", DateTime.Now.ToShortTimeString(), trace.GetFrame(1).GetMethod().DeclaringType.Name, trace.GetFrame(1).GetMethod().Name, str)); }
/// <summary> /// Generates the HTML page with exception information /// </summary> /// <param name="e">Exception to get information from.</param> /// <param name="hideExceptionDetails">if set to <c>true</c> then exception details will not be shown.</param> /// <returns></returns> public static string Generate(Exception e, bool hideExceptionDetails = false) { if (e == null) return null; var tpl = Template.FromManifest("Diagnostics.ExceptionInfoPage.html"); tpl.Set("Simplify.Web.Version", new AssemblyInfo(Assembly.GetCallingAssembly()).Version); if (hideExceptionDetails) { tpl.Set("ExceptionDetails", ""); return tpl.Get(); } var detailsTpl = Template.FromManifest("Diagnostics.ExceptionIDetails.html"); var trace = new StackTrace(e, true); if (trace.FrameCount == 0) return null; var fileLineNumber = trace.GetFrame(0).GetFileLineNumber(); var fileColumnNumber = trace.GetFrame(0).GetFileColumnNumber(); var positionPrefix = fileLineNumber == 0 && fileColumnNumber == 0 ? "" : $"[{fileLineNumber}:{fileColumnNumber}]"; detailsTpl.Set("StackTrace", $"<b>{positionPrefix} {e.GetType()} : {e.Message}</b>{Environment.NewLine}{trace}{GetInnerExceptionData(1, e.InnerException)}" .Replace(Environment.NewLine, "<br />")); tpl.Set("ExceptionDetails", detailsTpl); return tpl.Get(); }
private static string GetPosition() { var st = new StackTrace(new StackFrame(2, true)); var currentFile = st.GetFrame(0).GetFileName(); var currentLine = st.GetFrame(0).GetFileLineNumber(); return "File:" + currentFile + " Line:" + currentLine + "\t\n"; }
public static void InsideMethod() { // get call stack StackTrace stackTrace = new StackTrace(); // get calling method name Debug("Inside method '" + stackTrace.GetFrame(1).GetMethod().DeclaringType.FullName + "." + stackTrace.GetFrame(1).GetMethod().Name + "'."); }
public static void DisplayCurrentMethodName() { StackTrace stackTrace = new StackTrace(); Console.WriteLine("{0} - {1}", stackTrace.GetFrame(0).GetType().Name, stackTrace.GetFrame(1).GetMethod().Name); }
public static SecurityService._Log log() { SecurityService._Log _log = new SecurityService._Log(); StackTrace st = new StackTrace(); _log.className = st.GetFrame(1).GetMethod().DeclaringType.FullName; _log.functionName = st.GetFrame(1).GetMethod().Name; return _log; }
internal static string GetMethodName() { var stackTrace = new StackTrace(); if (stackTrace.FrameCount > 2) return stackTrace.GetFrame(2).GetMethod().Name; else return stackTrace.GetFrame(1).GetMethod().Name; }
internal static MethodBase GetCallInformation() { var stackTrace = new StackTrace(); if (stackTrace.FrameCount > 2) return stackTrace.GetFrame(2).GetMethod(); else return stackTrace.GetFrame(1).GetMethod(); }
/// <summary> /// Instantiate location information based on the current thread /// </summary> /// <param name="fullNameOfCallingClass">the fully name of the calling class (not assembly qualified)</param> public LocationInfo(string fullNameOfCallingClass) { // Initialise all fields m_className = NA; m_fileName = NA; m_lineNumber = NA; m_methodName = NA; m_fullInfo = NA; #if !NETCF try { StackTrace st = new StackTrace(true); int frameIndex = 0; // skip frames not from fqnOfCallingClass while (frameIndex < st.FrameCount) { StackFrame frame = st.GetFrame(frameIndex); if (frame.GetMethod().DeclaringType.FullName == fullNameOfCallingClass) { break; } frameIndex++; } // skip frames from fqnOfCallingClass while (frameIndex < st.FrameCount) { StackFrame frame = st.GetFrame(frameIndex); if (frame.GetMethod().DeclaringType.FullName != fullNameOfCallingClass) { break; } frameIndex++; } if (frameIndex < st.FrameCount) { // now frameIndex is the first 'user' caller frame StackFrame locationFrame = st.GetFrame(frameIndex); m_className = locationFrame.GetMethod().DeclaringType.FullName; m_fileName = locationFrame.GetFileName(); m_lineNumber = locationFrame.GetFileLineNumber().ToString(System.Globalization.NumberFormatInfo.InvariantInfo); m_methodName = locationFrame.GetMethod().Name; m_fullInfo = m_className+'.'+m_methodName+'('+m_fileName+':'+m_lineNumber+')'; } } catch(System.Security.SecurityException) { // This security exception will occur if the caller does not have // some undefined set of SecurityPermission flags. LogLog.Debug("LocationInfo: Security exception while trying to get caller stack frame. Error Ingnored. Location Information Not Available."); } #endif }
/// <summary> /// Warnings the specified message. /// </summary> /// <param name="message">The message.</param> public static void Warning(string message) { var stackTrace = new StackTrace(); WriteLog(message, "warning", stackTrace.GetFrame(1).GetMethod().Module.Name, stackTrace.GetFrame(1).GetMethod().ReflectedType?.FullName, stackTrace.GetFrame(1).GetMethod().Name); }
/// <summary> /// Only gets written in debug mode /// </summary> /// <param name="message">The message.</param> public static void Debug(string message) { #if DEBUG var stackTrace = new StackTrace(); WriteLog(message, "debug", stackTrace.GetFrame(1).GetMethod().Module.Name, stackTrace.GetFrame(1).GetMethod().ReflectedType.FullName, stackTrace.GetFrame(1).GetMethod().Name); #endif }
public static SecurityService._Exception error(Exception ex) { StackTrace st = new StackTrace(); SecurityService._Exception _ex = new SecurityService._Exception(); _ex.className = st.GetFrame(1).GetMethod().DeclaringType.FullName; _ex.functionName = st.GetFrame(1).GetMethod().Name; _ex.ExceptionTarget = ex.TargetSite.Name; _ex.ExceptionMessage = ex.Message; _ex.ExceptionStackTrace = ex.StackTrace; return _ex; }
public static void Error(string format, params Object[] args) { var stackTrace = new StackTrace(true); string error = string.Format(format, args); error = stackTrace.GetFrame(1).GetFileName() + "[" + stackTrace.GetFrame(1).GetMethod().Name + "] " + error + "\nIgnore the error and continue running the application?"; if (MessageBox.Show(error, "Rose GUI Editor - Error", MessageBoxButtons.YesNo, MessageBoxIcon.Error) == DialogResult.No) Environment.Exit(-1); #if DEBUG //throw new Exception(error); #endif }
/// <summary> /// Write to file /// </summary> static public void Write(LogLevel lvl, string s) { StackTrace stackTrace = new StackTrace(); MethodBase method = stackTrace.GetFrame(2).GetMethod(); //if (instance.streamWriter != null && lvl <= instance.level) { instance.streamWriter.WriteLine( "[" + method.Name + "@" + method.ReflectedType.Name + ":" + stackTrace.GetFrame(2).GetFileLineNumber() + "] " + s); instance.streamWriter.Flush(); //} }
public TestMethodInfo GetTestMethodInfo(StackTrace stackTrace, int startAt = 0) { var i = startAt; StackFrame callingFrame; do { callingFrame = stackTrace.GetFrame(i++); } while (callingFrame.GetMethod().IsShouldlyMethod() || IsCompilerGenerated(callingFrame.GetMethod())); callingFrame = stackTrace.GetFrame(i + Offset - 1); return new TestMethodInfo(callingFrame); }
protected override void ControllerException(ExceptionContext filterContext) { filterContext.ExceptionHandled = true; string content = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\"><html xmlns=\"http://www.w3.org/1999/xhtml\"><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">"; content = (content + string.Format("<title>系统发生错误 MaticsoftFK {0}{1}</title>", MvcApplication.Version, MvcApplication.IsAuthorize ? "" : ControllerBaseAbs.P_DATA) + "<style>body{\tfont-family: 'Microsoft Yahei', Verdana, arial, sans-serif;\tfont-size:14px;}a{text-decoration:none;color:#174B73;}a:hover{ text-decoration:none;color:#FF6600;}h2{\tborder-bottom:1px solid #DDD;\tpadding:8px 0; font-size:25px;}.title{\tmargin:4px 0;\tcolor:#F60;\tfont-weight:bold;}.message,#trace{\tpadding:1em;\tborder:solid 1px #000;\tmargin:10px 0;\tbackground:#FFD;\tline-height:150%;}.message{\tbackground:#FFD;\tcolor:#2E2E2E;\t\tborder:1px solid #E0E0E0;}#trace{\tbackground:#E7F7FF;\tborder:1px solid #E0E0E0;\tcolor:#535353;\tword-wrap: break-word;}.notice{ padding:10px;\tmargin:5px;\tcolor:#666;\tbackground:#FCFCFC;\tborder:1px solid #E0E0E0;}.red{\tcolor:red;\tfont-weight:bold;}</style></head>") + "<body><div class=\"notice\"><h2>系统发生错误 </h2>" + "<div>您可以选择 [ <a href=\"javascript:location.reload();\" >重试</a> ] [ <a href=\"javascript:history.back()\">返回</a> ] 或者 [ <a target=\"_blank\" href=\"http://bbs.maticsoft.com/\">去官方论坛找找答案</a> ]</div>"; Maticsoft.Model.SysManage.ErrorLog model = new Maticsoft.Model.SysManage.ErrorLog(); Exception e = filterContext.Exception; HttpContextBase httpContext = filterContext.HttpContext; httpContext.Response.Clear(); StackTrace trace = new StackTrace(e, true); int fileLineNumber = trace.GetFrame(0).GetFileLineNumber(); int fileColumnNumber = trace.GetFrame(0).GetFileColumnNumber(); string fileName = trace.GetFrame(0).GetFileName(); object obj2 = content; content = string.Concat(new object[] { obj2, "<p><strong>错误位置:</strong> File: <span class=\"red\">", fileName, "</span> Line: <span class=\"red\">", fileLineNumber, "</span> Column: <span class=\"red\">", fileColumnNumber, "</span></p>" }) + "<p class=\"title\">[ 错误信息 ]</p>"; if (e is SqlException) { SqlException exception2 = (SqlException) e; if (exception2 != null) { string sqlExceptionMessage = this.GetSqlExceptionMessage(exception2.Number); if (exception2.Number == 0x223) { content = content + "<p class=\"message\">" + sqlExceptionMessage + "</p>"; } else { content = content + "<p class=\"message\">" + sqlExceptionMessage + "</p>"; model.Loginfo = sqlExceptionMessage; model.StackTrace = e.ToString(); model.Url = httpContext.Request.Url.AbsoluteUri; } } } else { content = (((content + "<p class=\"message\">" + e.Message + "</p>") + "<p class=\"title\">[ StackTrace ]</p><p id=\"trace\">" + e.StackTrace + "</p></div>") + string.Format("<div align=\"center\" style=\"color:#FF3300;margin:5pt;font-family:Verdana\"> MaticsoftFK <sup style=\"color:gray;font-size:9pt\">{0}</sup>", MvcApplication.Version)) + "<span style=\"color:silver\"> { Building & OOP MVC Maticsoft Framework } -- [ WE CAN DO IT JUST HAPPY WORKING ]</span></div>" + "</body><style type=\"text/css\"></style></html>"; model.Loginfo = e.Message; model.StackTrace = e.ToString(); model.Url = httpContext.Request.Url.AbsoluteUri; } Maticsoft.BLL.SysManage.ErrorLog.Add(model); if (!base.HttpContext.IsDebuggingEnabled && e.TargetSite.ToString().StartsWith("System.Web.Mvc.ViewEngineResult FindView")) { filterContext.Result = new HttpNotFoundResult(); httpContext.Server.ClearError(); } else { filterContext.Result = base.Content(content); httpContext.Server.ClearError(); } }
// avoid replication of tests on all constructors (this is no // problem because the stack is already set correctly). The // goal is to call every property and methods to see if they // have any* security requirements (*except for LinkDemand and // InheritanceDemand). private void Check (StackTrace st) { if (st.FrameCount > 0) Assert.IsNotNull (st.GetFrame (0), "GetFrame"); else Assert.IsNull (st.GetFrame (0), "GetFrame"); if (st.FrameCount > 0) Assert.IsNotNull (st.GetFrames (), "GetFrames"); else Assert.IsNull (st.GetFrames (), "GetFrames"); Assert.IsNotNull (st.ToString (), "ToString"); }
/// <summary> /// Initializes a new instance of the <see cref="TypeNameResolver"/> class. /// </summary> internal TypeNameResolver( ) { StackTrace st = new StackTrace( System.Threading.Thread.CurrentThread, false ); for( int i = 1; i < st.FrameCount; i++ ) { if ( !st.GetFrame( i ).GetMethod( ).Name.Contains( "CallDelegatorByAsync" ) ) { mCallerTypeName = st.GetFrame( i ).GetMethod( ).ReflectedType.FullName; break; } } }
protected static string StackInfo() { StackTrace t = new System.Diagnostics.StackTrace(true); StackFrame sf = t.GetFrame(2); if (sf != null) { string filename = sf.GetFileName(); if (filename != null) { filename = Regex.Replace(filename, @".*?Assets\/(.*)", "$1"); int line = sf.GetFileLineNumber(); return(filename + ":" + line); } } return(""); }
/// <summary> /// 执行HTTP GET请求,增加超时时间参数,内部已加try、catch /// xqy 20151112 /// </summary> /// <param name="url">请求地址</param> /// <param name="parameters">请求参数</param> /// <returns>HTTP响应</returns> public static string DoGet1(string url, IDictionary <string, string> parameters) { String responseFromServer = string.Empty; try { if (parameters != null && parameters.Count > 0) { if (url.Contains("?")) { url = url + "&" + BuildPostData(parameters); } else { url = url + "?" + BuildPostData(parameters); } } Console.WriteLine(url); WebRequest webRequest = HttpWebRequest.Create(url); { ((HttpWebRequest)webRequest).KeepAlive = false; webRequest.Timeout = 1000 * 30; // // 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); }
public static string ClassMethodString() { System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(); string _s = ""; for (int i = 0; i < trace.FrameCount; i++) { StackFrame f = trace.GetFrame(i); _s += i + "<" + f.GetMethod().ReflectedType.ToString(); _s += ">" + f.GetMethod().Name + " "; _s += "\n FILE " + f.GetFileName(); _s += "\n LINE " + f.GetFileLineNumber().ToString(); _s += "\n\n"; } UnityEngine.Debug.Log(_s); return(_s); }
public static void SaveImage(Plot plt, int width = 600, int height = 400, string subName = "", bool artifact = false) { var stackTrace = new System.Diagnostics.StackTrace(); StackFrame frame = stackTrace.GetFrame(1) ?? throw new InvalidOperationException("bad caller"); MethodBase method = frame.GetMethod() ?? throw new InvalidDataException("bad method"); string callingMethod = method.Name; if (!string.IsNullOrWhiteSpace(subName)) { subName = "_" + subName; } string fileName = callingMethod + subName + ".png"; string filePath = Path.GetFullPath(fileName); plt.SaveImage(width, height, filePath); Console.WriteLine($"Saved: {filePath}"); }
public void IsDirectoryNameCorrect() { var stackTrace = new System.Diagnostics.StackTrace(); var clazz = this.GetType(); var category = clazz.BaseType; var method = stackTrace.GetFrame(0).GetMethod(); var expected_directoryName = System.IO.Path.Combine(System.Environment.CurrentDirectory, "Tests", TrimStringFromEnd(category.Name, "Tests", true), TrimStringFromEnd(clazz.Name, "Method", true), method.Name); // cananicalize the local directory path var expected = new System.Uri(expected_directoryName).LocalPath; var generated_directoryName = GetMethodSpecificWorkingDirectory(); // cananicalize the local directory path var actual = new System.Uri(generated_directoryName).LocalPath; Assert.AreEqual(expected, actual, "The generated path is not consistent with the expected value"); Assert.IsTrue(System.IO.Directory.Exists(actual), "The default method should have created the directory"); Assert.AreEqual(0, System.IO.Directory.GetFiles(actual).Length, "The default method should have created an empty directory"); }
public static void ProcessStackTrace() { // пока не используется System.Diagnostics.StackTrace callStack = new System.Diagnostics.StackTrace(); System.Diagnostics.StackFrame frame = null; System.Reflection.MethodBase calledMethod = null; System.Reflection.ParameterInfo[] passedParams = null; for (int x = 0; x < callStack.FrameCount; x++) { frame = callStack.GetFrame(x); calledMethod = frame.GetMethod(); passedParams = calledMethod.GetParameters(); foreach (System.Reflection.ParameterInfo param in passedParams) { HttpContext.Current.Response.Write(param.ToString() + " " + param.DefaultValue + " " + param.RawDefaultValue + "<br />"); } } }
/// <summary> /// Logs the message and the assembly, class, and method that called Trace to the log file. /// </summary> public void Trace(string message) { //The stack trace is used to get the class and assembly name of the method that called this Trace method. //I've tested it and in my tests the additional time of doing reflection was negligible. System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(); string className; string methodName; string assemblyName; for (int i = 0; i < st.FrameCount; i++) { MethodBase methodBase = st.GetFrame(i).GetMethod(); if (methodBase.DeclaringType == typeof(Ogresoft.Diagnostics)) { continue; } if (methodBase.DeclaringType.BaseType == typeof(Ogresoft.Diagnostics)) { continue; } className = methodBase.DeclaringType.FullName; methodName = methodBase.Name; assemblyName = methodBase.DeclaringType.Assembly.GetName().Name; //string traceMessage = assemblyName + "." + className + "." + methodName + " " + message; string traceMessage = className + "." + methodName + " " + message; System.Diagnostics.Trace.WriteLine(traceMessage); // if (_settings.Trace) // _traceLogger.Write(traceMessage); return; } //unreachable. Debug.Assert(false); }
private void AssertCode(string testName, uint opcode, string sExp, string sActual) { if (sExp == sActual) { return; } var trace = new System.Diagnostics.StackTrace(); var caller = trace.GetFrame(1); var callerName = caller.GetMethod().Name; Debug.Print( @" public void {0}() {{ var instr = DisassembleWord({1:X8}); AssertCode(""{2}"", instr.ToString()); }} ", testName, opcode, sActual.Replace("\t", "\\t")); }
public static string ClassMethodString(int frame) { System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(); string _s = ""; StackFrame f = trace.GetFrame(frame); try { _s += frame + " " + f.GetMethod().ReflectedType.ToString(); _s += " " + f.GetMethod().Name + " "; } catch (Exception ex) { } //if (dump) _s += ClassMethodString(); return(_s); }
public static LogException ShowDebugInfo(Exception ownException) { LogException exceptionInfo = new LogException(); try { System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ownException, true); StackFrame stackFrame = trace.GetFrame(0); MethodBase method = stackFrame.GetMethod(); exceptionInfo.MethodName = method.DeclaringType.FullName; exceptionInfo.ExceptionLine = stackFrame.GetFileLineNumber(); exceptionInfo.ExceptionMessage = ownException.Message; exceptionInfo.ExceptionStackTrace = ownException.StackTrace; } catch (System.Exception x) { } return(exceptionInfo); }
private static bool CheckIgnorableError(Exception ex) { #if DEBUG return(false); #else if (ex is AggregateException aggregated) { if (aggregated.InnerExceptions.Count != 1) { return(false); } ex = aggregated.InnerExceptions.Single(); } switch (ex) { case System.Net.WebException webEx: // SSL/TLS のネゴシエーションに失敗した場合に発生する。なぜかキャッチできない例外 // https://osdn.net/ticket/browse.php?group_id=6526&tid=37432 if (webEx.Status == System.Net.WebExceptionStatus.SecureChannelFailure) { return(true); } break; case System.Threading.Tasks.TaskCanceledException cancelEx: // ton.twitter.com の画像でタイムアウトした場合、try-catch で例外がキャッチできない // https://osdn.net/ticket/browse.php?group_id=6526&tid=37433 var stackTrace = new System.Diagnostics.StackTrace(cancelEx); var lastFrameMethod = stackTrace.GetFrame(stackTrace.FrameCount - 1).GetMethod(); if (lastFrameMethod.ReflectedType == typeof(Connection.TwitterApiConnection) && lastFrameMethod.Name == nameof(Connection.TwitterApiConnection.GetStreamAsync)) { return(true); } break; } return(false); #endif }
public void TraceCallers(int Depth) { 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(System.Globalization.CultureInfo.InvariantCulture)); } Unindent(); } }
/// <summary> /// Gets the line number where exception has occurred. /// </summary> /// <param name="exception">Exception object</param> /// <param name="className">Class Name where exception occur</param> /// <param name="methodName">Name of the method.</param> /// <param name="logTableName">Name of the log table.</param> /// <returns>Error logged in event viewer</returns> public static string LogError(Exception exception, string className, string methodName, string logTableName) { string result = string.Empty; try { System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(exception, true); int lineNumber = trace.GetFrame(trace.FrameCount - 1).GetFileLineNumber(); string MCException = MatterCenterExceptions(exception, className, methodName, logTableName, lineNumber); result = MCException; } catch (Exception ex) { System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true); int lineNumber = trace.GetFrame(trace.FrameCount - 1).GetFileLineNumber(); string MCException = MatterCenterExceptions(ex, className, methodName, logTableName, lineNumber); result = MCException; } return(result); }
public void IsDirectoryNameCorrectWithinNestedLambda() { AssertDelegateSuccess(() => { Action nested1 = () => { var stackTrace = new System.Diagnostics.StackTrace(); var clazz = this.GetType(); var category = clazz.BaseType; var method = stackTrace.GetFrame(6).GetMethod(); var expected_directoryName = System.IO.Path.Combine(System.Environment.CurrentDirectory, "Tests", TrimStringFromEnd(category.Name, "Tests", true), TrimStringFromEnd(clazz.Name, "Method", true), method.Name); // cananicalize the local directory path var expected = new System.Uri(expected_directoryName).LocalPath; var generated_directoryName = GetMethodSpecificWorkingDirectory(); // cananicalize the local directory path var actual = new System.Uri(generated_directoryName).LocalPath; Assert.AreEqual(expected, actual, "The generated path is not consistent with the expected value"); Assert.IsTrue(System.IO.Directory.Exists(actual), "The default method should have created the directory"); Assert.AreEqual(0, System.IO.Directory.GetFiles(actual).Length, "The default method should have created an empty directory"); }; Action nested2 = () => { nested1(); }; Action nested3 = () => { nested2(); }; Action nested4 = () => { nested3(); }; // attempt a heavily nested series of lambda functions nested4(); }, "No exception should have been thrown"); }
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(); }
protected virtual void OnBeforeNotify(Report report) { var exception = report.Event.Exceptions[0].OriginalException; var stackTrace = new StackTrace(exception, true); if (stackTrace.FrameCount <= 0) { return; } var frame = stackTrace.GetFrame(0); // // During development the line number probably changes frequently, but we want // // to treat all errors with the same exception in the same method as being the // // same, even when the line numbers differ, so we set it to 0. For releases // // we can assume the line number to be constant for a released build. // var linenumber = Configuration.ReleaseStage == "development" ? 0 : frame.GetFileLineNumber(); var linenumber = frame.GetFileLineNumber(); report.Event.GroupingHash = string.Format("{0} {1} {2} {3}", report.Event.Exceptions[0].OriginalException.GetType().Name, RemoveFileNamePrefix(frame.GetFileName()), frame.GetMethod().Name, linenumber); }
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); }
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> /// 指定された内容をログに出力します。 /// </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(); } }
/// <summary> /// 获得文件名函数 /// </summary> /// <returns></returns> public static string GetFileName() { System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(1, 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); }
private void OnLoad(LoginView Window) { try { XMLCentros(); //Asignamos usuarios temporales UsuarioBaseDatos(); //Validamos si esta habilitado el biometrico de la pantalla ValidacionesBiometrico(); ObtenerPassWord(); #region Comentado //GlobalVar.gArea = Convert.ToInt16(ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).AppSettings.Settings["EquipoArea"].Value); //LstCentro = LstCentro ?? new ObservableCollection<CENTRO>(new cCentro().ObtenerTodos()); //LstCentro.Insert(0, new CENTRO() { ID_CENTRO = -1, DESCR = Resources.General.seleccione }); #endregion TBPwd = Window.tbPassword; OriginalHeight = Window.Height; if (CurrentReader != null) { CurrentReader.Dispose(); CurrentReader = null; } CurrentReader = Readers[0]; if (CurrentReader == null) { return; } Window.Closed += (s, e) => { try { OnProgress.Abort(); CancelCaptureAndCloseReader(OnCaptured); } catch (Exception ex) { var trace = new System.Diagnostics.StackTrace(ex, true); Trace.WriteLine("\n>>>[Ubicación del Problema]"); Trace.WriteLine("Clase: " + trace.GetFrame((trace.FrameCount - 1)).GetMethod().ReflectedType.FullName); Trace.WriteLine("Metodo: " + trace.GetFrame((trace.FrameCount - 1)).GetMethod().Name); Trace.WriteLine("Linea: " + trace.GetFrame((trace.FrameCount - 1)).GetFileLineNumber()); Trace.WriteLine("Columna: " + trace.GetFrame((trace.FrameCount - 1)).GetFileColumnNumber()); Trace.WriteLine(ex.Message + " " + (ex.InnerException != null ? ex.InnerException.InnerException.Message : "")); } }; if (!OpenReader()) { Window.Close(); } if (!StartCaptureAsync(OnCaptured)) { Window.Close(); } OnProgress = new Thread(() => InvokeDelegate(Window)); } catch (Exception ex) { var trace = new System.Diagnostics.StackTrace(ex, true); Trace.WriteLine("\n>>>[Ubicación del Problema]"); Trace.WriteLine("Clase: " + trace.GetFrame((trace.FrameCount - 1)).GetMethod().ReflectedType.FullName); Trace.WriteLine("Metodo: " + trace.GetFrame((trace.FrameCount - 1)).GetMethod().Name); Trace.WriteLine("Linea: " + trace.GetFrame((trace.FrameCount - 1)).GetFileLineNumber()); Trace.WriteLine("Columna: " + trace.GetFrame((trace.FrameCount - 1)).GetFileColumnNumber()); Trace.WriteLine(ex.Message + " " + (ex.InnerException != null ? ex.InnerException.InnerException.Message : "")); StaticSourcesViewModel.ShowMessageError(res.General.algo_paso, res.ControlPenales.Login.LoginViewModel.error_login, ex); } }
public static void SyncTickets() { bool ProcessEnabled = true; Boolean.TryParse(System.Configuration.ConfigurationManager.AppSettings["Jobs.EnabledJobs"], out ProcessEnabled); int definitionId = 0; if (!Int32.TryParse(System.Configuration.ConfigurationManager.AppSettings["DefinitionId"], out definitionId)) { throw new Exception("DefinitionId no existe en el web config"); } string pipelineId = System.Configuration.ConfigurationManager.AppSettings["PipelineId"]; string pipelineStageId = System.Configuration.ConfigurationManager.AppSettings["PipelineStageId"]; IHubspotService apiService = new HubspotService(); Trace.TraceInformation(string.Format("[TicketsSyncJob.SyncTickets] Executing at {0}", DateTime.Now)); IDBService dbService = new DBService(); DBProceso procesoInfo = dbService.GetProcessInfo("SINCRONIZACION_TICKETS"); StringBuilder strResultado = new StringBuilder("Iniciando proceso..."); if (Monitor.TryEnter(thisLock)) { try { if (!executing && ProcessEnabled) { executing = true; //SI ESTA HABILITADO Y NO SE ESTA EJECUTANDO if (!procesoInfo.EstatusEjecucion && procesoInfo.EstatusProceso) { procesoInfo.EstatusEjecucion = true; procesoInfo.UltimaEjecucion = DateTime.Now; procesoInfo.Resultado = strResultado.ToString(); dbService.ActualizarEstatusProceso(procesoInfo); DBProcesoEjecucion procesoDetalle = new DBProcesoEjecucion() { ProcesoId = procesoInfo.ProcesoId, Estatus = true, Resultado = "Procesando..." }; int ProcesoDetalleId = dbService.CreateProcesoEjecucion(procesoDetalle); #region SINCRONIZACION DE COMPANIAS EN MEMORIA Dictionary <string, long> CompanyDictionary = new Dictionary <string, long>(); long offset = 0; bool hasMoreCompanies = true; int totalCompanies = 0; strResultado.Append(" * Paso 1 "); while (hasMoreCompanies) { strResultado.Append(" * Paso 1.1 "); CompaniesHubSpotResult companiesHubSpotResult = apiService.GetAllCompanies(250, offset); Trace.TraceInformation(string.Format("HasMore: {0} Offset: {1}", companiesHubSpotResult.HasMore, companiesHubSpotResult.Offset)); hasMoreCompanies = companiesHubSpotResult.HasMore; offset = companiesHubSpotResult.Offset; strResultado.Append(" * Paso 1.2 "); totalCompanies += companiesHubSpotResult.Companies.Count(); strResultado.Append(" * Paso 1.3 "); foreach (Company company in companiesHubSpotResult.Companies) { //TODO: Cambiar por RFC if (company.Properties.RFC != null && !string.IsNullOrEmpty(company.Properties.RFC.Value)) { string rfcCompany = company.Properties.RFC.Value.Trim().ToUpper(); if (!CompanyDictionary.ContainsKey(rfcCompany)) { CompanyDictionary.Add(rfcCompany, company.CompanyId); } } } } Trace.TraceInformation(string.Format("Total Companies: {0}", totalCompanies)); Trace.TraceInformation(string.Format("Total Companies in Dic: {0}", CompanyDictionary.Count())); #endregion strResultado.Append(" * Paso 2 "); dbService.UpdateTicketsToProcess(); strResultado.Append(" * Paso 3 "); IEnumerable <DBTicketModel> tickets = dbService.GetTickets(); strResultado.Append(" * Paso 4 "); int ticketsSyncronized = 0; foreach (DBTicketModel ticket in tickets) { long companyId = 0; strResultado.Append(" * Paso 4.1 "); string rfc = ticket.RFC.Trim().ToUpper(); if (!CompanyDictionary.TryGetValue(rfc, out companyId)) { strResultado.Append(String.Format("No existe el rfc {0} en el hubspot", rfc)); continue; } strResultado.Append(" * Paso 4.2 "); CompanyTicketHubspotSave ticketHubspotSave = new CompanyTicketHubspotSave { CompanyId = companyId, Content = ticket.Descripcion, Monto = ticket.Monto, NumeroOperacion = ticket.NumeroOperacion, Subject = ticket.TipoActividad, DefinitionId = definitionId, PipelineId = pipelineId, PipelineStageId = pipelineStageId }; strResultado.Append(" * Paso 4.3 "); CompanyTicketCreateHubspotResponse apiResponse = apiService.CreateTicketToCompany(ticketHubspotSave); strResultado.Append(" * Paso 4.4 "); if (apiResponse.IsCreated) { strResultado.Append(" * Paso 4.5 "); ticket.TicketId = apiResponse.TicketId; dbService.UpdateSyncTicket(ticket); ticketsSyncronized++; } } Trace.TraceInformation(string.Format("[TicketsSyncJob.SyncTickets] Finishing at {0}", DateTime.Now)); int total = tickets.Count(); procesoDetalle.FechaFin = DateTime.Now; procesoDetalle.Estatus = false; procesoDetalle.Resultado = string.Format("Se sincronizaron {0} de {1} tickets", ticketsSyncronized, total); strResultado.Append(string.Format("|Se sincronizaron {0} de {1} tickets", ticketsSyncronized, total)); dbService.ActualizarProcesoEjecucion(procesoDetalle); } } } catch (Exception exception) { Debug.WriteLine(exception.Message); Trace.TraceInformation(exception.Message); strResultado.Append("|" + exception.Message); if (exception.Source != null) { strResultado.Append("|" + exception.Source); } if (exception.StackTrace != null) { strResultado.Append("|" + exception.StackTrace); } try { System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(exception, true); strResultado.Append("|" + String.Format("<p>Error Detail Message :{0} => Error In :{1} => Line Number :{2} => Error Method:{3}</p>", HttpUtility.HtmlEncode(exception.Message), trace.GetFrame(0).GetFileName(), trace.GetFrame(0).GetFileLineNumber(), trace.GetFrame(0).GetMethod().Name)); } catch (Exception ex) { } } finally { procesoInfo.EstatusEjecucion = false; procesoInfo.UltimaEjecucion = DateTime.Now; procesoInfo.Resultado = strResultado.ToString(); dbService.ActualizarEstatusProceso(procesoInfo); executing = false; Monitor.Exit(thisLock); } } Trace.TraceInformation(string.Format("[TicketsSyncJob.SyncTickets] Finishing at {0}", DateTime.Now)); }
/// <summary> /// 获得当前函数名 /// </summary> /// <returns></returns> public static string GetFuncName() { System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(1, true); return(st.GetFrame(0).GetMethod().ToString()); }
public static void ExceptionHandler(Exception ex) { System.Text.StringBuilder Texto = new System.Text.StringBuilder(); Texto.AppendLine("Lugar : " + ex.Source); try { System.Diagnostics.StackTrace Traza = new System.Diagnostics.StackTrace(ex, true); Texto.AppendLine("Línea : " + Traza.GetFrame(0).GetFileLineNumber()); Texto.AppendLine("Columna : " + Traza.GetFrame(0).GetFileColumnNumber()); } catch { //Nada } Texto.AppendLine("Equipo : " + Lfx.Environment.SystemInformation.MachineName); Texto.AppendLine("Plataf. : " + Lfx.Environment.SystemInformation.Platform); Texto.AppendLine("RunTime : " + Lfx.Environment.SystemInformation.RunTime); Texto.AppendLine("Excepción no controlada: " + ex.ToString()); Texto.AppendLine(""); Texto.AppendLine("Gestion versión " + System.Diagnostics.FileVersionInfo.GetVersionInfo(Lfx.Environment.Folders.ApplicationFolder + "Gestión777.exe").ProductVersion + " del " + new System.IO.FileInfo(Lfx.Environment.Folders.ApplicationFolder + "Gestión777.exe").LastWriteTime.ToString()); System.IO.DirectoryInfo Dir = new System.IO.DirectoryInfo(Lfx.Environment.Folders.ApplicationFolder); foreach (System.IO.FileInfo DirItem in Dir.GetFiles("*.dll")) { Texto.AppendLine(DirItem.Name + " versión " + System.Diagnostics.FileVersionInfo.GetVersionInfo(DirItem.FullName).ProductVersion + " del " + new System.IO.FileInfo(DirItem.FullName).LastWriteTime.ToString()); } Dir = new System.IO.DirectoryInfo(Lfx.Environment.Folders.ComponentsFolder); foreach (System.IO.FileInfo DirItem in Dir.GetFiles("*.dll")) { Texto.AppendLine(DirItem.Name + " versión " + System.Diagnostics.FileVersionInfo.GetVersionInfo(DirItem.FullName).ProductVersion + " del " + new System.IO.FileInfo(DirItem.FullName).LastWriteTime.ToString()); } Texto.AppendLine("Traza:"); Texto.AppendLine(ex.StackTrace); MailMessage Mensaje = new MailMessage(); Mensaje.To.Add(new MailAddress("*****@*****.**")); Mensaje.From = new MailAddress(Lbl.Sys.Config.Actual.UsuarioConectado.Id.ToString() + "@" + Lfx.Environment.SystemInformation.MachineName, Lbl.Sys.Config.Actual.UsuarioConectado.Nombre + " en " + Lbl.Sys.Config.Empresa.Nombre); try { //No sé por qué, pero una vez dió un error al poner el asunto Mensaje.Subject = ex.Message; } catch { Mensaje.Subject = "Excepción no controlada"; Texto.Insert(0, ex.Message + System.Environment.NewLine); } Mensaje.Body = Texto.ToString(); SmtpClient Cliente = new SmtpClient("smtp.gmail.com", 587); Cliente.EnableSsl = true; Cliente.Credentials = new System.Net.NetworkCredential("*****@*****.**", "donjuan2e"); try { Cliente.Send(Mensaje); } catch { // Nada } }
private async void autentificacion() { try { string MsjError = string.Empty; ErrorLogin = string.Empty; BandError = false; ///TODO:Quitar despues de pruebas if (SelectedCentro == -1) { ErrorLogin = res.ControlPenales.Login.LoginViewModel.seleccione_centro; BandError = true; return; } //GlobalVariables.gPass = UBD; //User.Password = //User.Password.ToUpper(); //User.Username = "******"; //User.Password = "******"; if (string.IsNullOrEmpty(User.Username) ? false : string.IsNullOrEmpty(User.Password) && huella == false ? false : true) //if (!string.IsNullOrEmpty(User.Username) || User.Username == "SYS" || User.Username == "TONGOLELE") { // if (User.Username == "SYSTEM" || User.Username == "SYS" || User.Username == "TONGOLELE") // User.Password = "******"; GlobalVariables.gUser = User.Username; //GlobalVariables.gPass = User.Password; //validar usuario LoginLoading = Visibility.Visible; USUARIO usr = null; if (await Task.Factory.StartNew <bool>(() => { usr = new cUsuario().ObtenerUsuario(User.Username); return(usr == null); })) { ErrorLogin = res.ControlPenales.Login.LoginViewModel.usuario_contrasena_incorrecto; BandError = true; return; } #region Valida Sesion if (!await Task.Factory.StartNew <bool>(() => { return(ValidarSesion()); })) { ErrorLogin = "******"; BandError = true; TBPwd.Focus(); return; } #endregion //OBTENEMOS usuario if (User.Username.Equals(usr.ID_USUARIO.Trim()) && (huella == true ? true : !string.IsNullOrEmpty(usr.PASSWORD) ? cEncriptacion.IsEquals(User.Password.ToUpper(), usr.PASSWORD) : false)) { huella = false; if ((!string.IsNullOrEmpty(usr.ESTATUS) ? usr.ESTATUS : string.Empty) == "S") { var hoy = Fechas.GetFechaDateServer; TimeSpan ts; if (User.Username == "SYSTEM") { ts = hoy.AddDays(100) - hoy; } else { ts = usr.VENCE_PASS.Value - hoy; } if (Math.Floor(ts.TotalDays) > 0) { Application.Current.MainWindow.Hide(); var _view = new ControlPenales.PrincipalView(); User.Nombre = User.Username == "SYSTEM" ? "SYSTEM" : string.Format("{0} {1} {2}", !string.IsNullOrEmpty(usr.EMPLEADO.PERSONA.NOMBRE) ? usr.EMPLEADO.PERSONA.NOMBRE.Trim() : string.Empty, !string.IsNullOrEmpty(usr.EMPLEADO.PERSONA.PATERNO) ? usr.EMPLEADO.PERSONA.PATERNO.Trim() : string.Empty, !string.IsNullOrEmpty(usr.EMPLEADO.PERSONA.MATERNO) ? usr.EMPLEADO.PERSONA.MATERNO.Trim() : string.Empty); User.Password = usr.PASSWORD; User.VigenciaPassword = usr.VENCE_PASS; User.CentroNombre = SelectCentro.DESCR; var _viewModel = new PrincipalViewModel(User); _view.DataContext = _viewModel; //centro GlobalVar.gCentro = GlobalVariables.gCentro = SelectedCentro.Value; Application.Current.MainWindow.Close(); var metro = Application.Current.Windows[0] as MahApps.Metro.Controls.MetroWindow; ((ContentControl)metro.FindName("contentControl")).Content = new BandejaEntradaView(); ((ContentControl)metro.FindName("contentControl")).DataContext = new BandejaEntradaViewModel(); //Validar permisos del equipo Splasher.Splash = new ControlPenales.Login.SplashScreen(); Splasher.ShowSplash(); var _error_validacion = true; CATALOGO_EQUIPOS _mac_valida = null; MessageListener.Instance.ReceiveMessage(res.General.verificando_crendenciales); ///Eliminar cuando se implemente la verificacion de equipo //await TaskEx.Delay(1500); ///Eliminar cuando se implemente la verificacion de equipo //esteban //if(!string.IsNullOrEmpty(GlobalVar.gIP) && !string.IsNullOrEmpty(GlobalVar.gMAC_ADDRESS)) //{ // _error_validacion = false; //} #region comentado await Task.Factory.StartNew(() => { var _nics = VerificacionDispositivo.GetMacAddress(); foreach (var item in _nics) { //borrar foreach (var item2 in item.ips) { Trace.WriteLine("\n>IP:" + item2 + " ,MAC:" + item.mac); } //hasta aqui _mac_valida = new cCatalogoEquipos().ValidarEquipoMAC(item.ips, item.mac); if (_mac_valida != null) { GlobalVar.gIP = _mac_valida.IP; GlobalVar.gMAC_ADDRESS = _mac_valida.MAC_ADDRESS; _error_validacion = false; break; } } }); #endregion //hasta aqui if (Parametro.VERIFICA_HD_SERIAL && _mac_valida != null) { _error_validacion = true; MessageListener.Instance.ReceiveMessage(res.General.revisando_disco_duro); await Task.Factory.StartNew(() => { var hds = VerificacionDispositivo.GETHDSerial(); foreach (var item in hds) { if (new cCatalogoEquipos().ValidarHD(item.SerialNo, _mac_valida.IP, _mac_valida.MAC_ADDRESS)) { _error_validacion = false; break; } else { MsjError = "Error al validar HD"; } } }); } //Validar si tiene permisos para entrar al centro await Task.Factory.StartNew(() => { var procesos = new cProcesoUsuario().ObtenerTodos(GlobalVariables.gUser, null, SelectCentro.ID_CENTRO).FirstOrDefault(); if (procesos == null) { Trace.WriteLine("no pudo validar procesos"); _error_validacion = true; } }); MessageListener.Instance.ReceiveMessage(res.General.esperando_validacion); await TaskEx.Delay(1500); //if (!_error_validacion) //_error_validacion = false; if (_error_validacion == false) { Splasher.CloseSplash(); CrearSesion(); _view.Show(); } else { MessageListener.Instance.ReceiveMessage("ACCESO DENEGADO"); await TaskEx.Delay(7500); Splasher.CloseSplash(); Application.Current.Shutdown(); } ///Eliminar cuando se implemente la verificacion de equipo //Splasher.CloseSplash(); //_view.Show(); ///Eliminar cuando se implemente la verificacion de equipo } else { ErrorLogin = res.ControlPenales.Login.LoginViewModel.password_caducado; BandError = true; await TaskEx.Delay(500); TBPwd.Focus(); } } else { ErrorLogin = res.ControlPenales.Login.LoginViewModel.usuario_inactivo; BandError = true; await TaskEx.Delay(500); TBPwd.Focus(); } } else { ErrorLogin = res.ControlPenales.Login.LoginViewModel.usuario_contrasena_incorrecto; BandError = true; await TaskEx.Delay(500); TBPwd.Focus(); } } else { ErrorLogin = res.ControlPenales.Login.LoginViewModel.usuario_contrasena_incorrecto; BandError = true; await TaskEx.Delay(500); TBPwd.Focus(); } } catch (Exception ex) { var trace = new System.Diagnostics.StackTrace(ex, true); Trace.WriteLine("\n>>>[Ubicación del Problema]"); Trace.WriteLine("Clase: " + trace.GetFrame((trace.FrameCount - 1)).GetMethod().ReflectedType.FullName); Trace.WriteLine("Metodo: " + trace.GetFrame((trace.FrameCount - 1)).GetMethod().Name); Trace.WriteLine("Linea: " + trace.GetFrame((trace.FrameCount - 1)).GetFileLineNumber()); Trace.WriteLine("Columna: " + trace.GetFrame((trace.FrameCount - 1)).GetFileColumnNumber()); Trace.WriteLine(ex.Message + " " + (ex.InnerException != null ? ex.InnerException.InnerException.Message : "")); StaticSourcesViewModel.ShowMessageError(res.General.algo_paso, res.ControlPenales.Login.LoginViewModel.error_login, ex); } }
/// <summary> /// 获取代码行号的函数 /// </summary> /// <returns></returns> public static int GetLineNum() { System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(1, true); return(st.GetFrame(0).GetFileLineNumber()); }
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() + ")"); }
private async void Identify(object Huella = null) { try { if (FingerPrintData == null) { return; } LoginLoading = Visibility.Visible; var Service = new BiometricoServiceClient(); var CompareResult = Service.CompararHuellaPersona(new ComparationRequest { BIOMETRICO = FeatureExtraction.CreateFmdFromFid(FingerPrintData, Constants.Formats.Fmd.ANSI).Data.Bytes, ID_TIPO_PERSONA = enumTipoPersona.PERSONA_EMPLEADO, ID_TIPO_BIOMETRICO = DD_Dedo.HasValue ? DD_Dedo.Value : enumTipoBiometrico.INDICE_DERECHO, ID_TIPO_FORMATO = enumTipoFormato.FMTO_DP });//.CompararHuellaImputado(new ComparationRequest { BIOMETRICO = FeatureExtraction.CreateFmdFromFid(FingerPrintData, Constants.Formats.Fmd.ANSI).Data.Bytes, ID_TIPO_BIOMETRICO = DD_Dedo.HasValue ? DD_Dedo.Value : enumTipoBiometrico.INDICE_DERECHO, ID_TIPO_FORMATO = enumTipoFormato.FMTO_DP }); if (CompareResult.Identify) { ///TODO: cambiar usuario login ERNESTO var result = CompareResult.Result[0]; GlobalVariables.gUser = "******"; //"QPERSONA"; GlobalVariables.gPass = "******"; //"QUADRO"; var persona = await StaticSourcesViewModel.CargarDatosAsync(() => new cPersona().ObtenerPersona(result.ID_PERSONA)); GlobalVariables.gUser = string.Empty; GlobalVariables.gPass = string.Empty; if (persona != null) { if (persona.EMPLEADO.USUARIO.Count > 0) { var u = persona.EMPLEADO.USUARIO.FirstOrDefault(); //persona.USUARIO.FirstOrDefault().ID_USUARIO.Trim(); User.Username = u.ID_USUARIO.Trim(); User.Password = string.Empty; huella = true; Application.Current.Dispatcher.Invoke((System.Action)(delegate { autentificacion(); })); } } //var NombreLogin = await StaticSourcesViewModel.CargarDatosAsync(() => new SSP.Controlador.Catalogo.Justicia.cImputado().GetData().Where(w => w.ID_ANIO == result.ID_ANIO && w.ID_CENTRO == result.ID_CENTRO && w.ID_IMPUTADO == result.ID_IMPUTADO).FirstOrDefault()); //User.Username = "******"; //User.Username = NombreLogin.NOMBRE.Trim() + " " + NombreLogin.PATERNO.Trim() + " " + NombreLogin.MATERNO.Trim(); //OnProgress.Start(); } else { ErrorLogin = res.ControlPenales.Login.LoginViewModel.usuario_contrasena_incorrecto; } FingerPrintData = null; } catch (Exception ex) { var trace = new System.Diagnostics.StackTrace(ex, true); Trace.WriteLine("\n>>>[Ubicación del Problema]"); Trace.WriteLine("Clase: " + trace.GetFrame((trace.FrameCount - 1)).GetMethod().ReflectedType.FullName); Trace.WriteLine("Metodo: " + trace.GetFrame((trace.FrameCount - 1)).GetMethod().Name); Trace.WriteLine("Linea: " + trace.GetFrame((trace.FrameCount - 1)).GetFileLineNumber()); Trace.WriteLine("Columna: " + trace.GetFrame((trace.FrameCount - 1)).GetFileColumnNumber()); Trace.WriteLine(ex.Message + " " + (ex.InnerException != null ? ex.InnerException.InnerException.Message : "")); ErrorLogin = res.ControlPenales.Login.LoginViewModel.error_sesion; } }