Here are the examples of the csharp api System.Diagnostics.StackFrame.GetMethod() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
523 Examples
19
Source : Signal.cs
with GNU General Public License v2.0
from ensoulsharp-io
with GNU General Public License v2.0
from ensoulsharp-io
public void Raise(string reason, params object[] format)
{
reason = string.Format(reason, format);
// Get the caller of the this method.
var callFrame = new StackFrame(1);
var declaringType = callFrame.GetMethod().DeclaringType;
if (declaringType == null)
{
return;
}
var caller = declaringType.FullName + "." + callFrame.GetMethod().Name;
this.TriggerSignal(caller, reason);
}
19
Source : Signal.cs
with GNU General Public License v2.0
from ensoulsharp-io
with GNU General Public License v2.0
from ensoulsharp-io
public void Raise(Exception exception)
{
// Get the caller of the this method.
var callFrame = new StackFrame(1);
var declaringType = callFrame.GetMethod().DeclaringType;
if (declaringType == null)
{
return;
}
var caller = declaringType.FullName + "." + callFrame.GetMethod().Name;
this.TriggerSignal(caller, exception.Message);
}
19
Source : GhostModule.cs
with MIT License
from EverestAPI
with MIT License
from EverestAPI
public PlayerDeadBody OnDie(On.Celeste.Player.orig_Die orig, Player player, Vector2 direction, bool evenIfInvincible, bool registerDeathInStats) {
PlayerDeadBody corpse = orig(player, direction, evenIfInvincible, registerDeathInStats);
if (GhostRecorder == null || GhostRecorder.Data == null)
return corpse;
// This is hacky, but it works:
// Check the stack trace for Celeste.Level+* <Pause>*
// and throw away the data when we're just retrying.
foreach (StackFrame frame in new StackTrace().GetFrames()) {
MethodBase method = frame?.GetMethod();
if (method == null || method.DeclaringType == null)
continue;
if (!method.DeclaringType.FullName.StartsWith("Celeste.Level+") ||
!method.Name.StartsWith("<Pause>"))
continue;
GhostRecorder.Data = null;
return corpse;
}
GhostRecorder.Data.Dead = true;
return corpse;
}
19
Source : ErrorHandler.cs
with MIT License
from Excel-projects
with MIT License
from Excel-projects
public static void DisplayMessage(Exception ex, Boolean isSilent = false)
{
var sf = new System.Diagnostics.StackFrame(1);
var caller = sf.GetMethod();
var errorDescription = ex.ToString().Replace("\r\n", " ");
var currentProcedure = caller.Name.Trim();
var currentFileName = replacedemblyInfo.GetCurrentFileName();
var logMessage = string.Concat(new Dictionary<string, string>
{
["PROCEDURE"] = currentProcedure,
["USER NAME"] = Environment.UserName,
["MACHINE NAME"] = Environment.MachineName,
["FILE NAME"] = currentFileName,
["DESCRIPTION"] = errorDescription,
}.Select(x => $"[{x.Key}]=|{x.Value}|"));
log.Error(logMessage);
var userMessage = new StringBuilder()
.AppendLine("Contact your system administrator. A record has been created in the log file.")
.AppendLine("Procedure: " + currentProcedure)
.AppendLine("Description: " + errorDescription)
.ToString();
if (isSilent == false)
{
MessageBox.Show(userMessage, "Unexpected Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
19
Source : ErrorHandler.cs
with MIT License
from Excel-projects
with MIT License
from Excel-projects
public static void DisplayMessage(Exception ex, Boolean isSilent = false)
{
// gather context
var sf = new System.Diagnostics.StackFrame(1);
var caller = sf.GetMethod();
var errorDescription = ex.ToString().Replace("\r\n", " "); // the carriage returns were messing up my log file
var currentProcedure = caller.Name.Trim();
var currentFileName = replacedemblyInfo.GetCurrentFileName();
// handle log record
var logMessage = string.Concat(new Dictionary<string, string>
{
["PROCEDURE"] = currentProcedure,
["USER NAME"] = Environment.UserName,
["MACHINE NAME"] = Environment.MachineName,
["FILE NAME"] = currentFileName,
["DESCRIPTION"] = errorDescription,
}.Select(x => $"[{x.Key}]=|{x.Value}|"));
log.Error(logMessage);
// format message
var userMessage = new StringBuilder()
.AppendLine("Contact your system administrator. A record has been created in the log file.")
.AppendLine("Procedure: " + currentProcedure)
.AppendLine("Description: " + errorDescription)
.ToString();
// handle message
if (isSilent == false)
{
MessageBox.Show(userMessage, "Unexpected Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
19
Source : ErrorHandler.cs
with MIT License
from Excel-projects
with MIT License
from Excel-projects
public static void CreateLogRecord()
{
try
{
// gather context
var sf = new System.Diagnostics.StackFrame(1);
var caller = sf.GetMethod();
var currentProcedure = caller.Name.Trim();
// handle log record
var logMessage = string.Concat(new Dictionary<string, string>
{
["PROCEDURE"] = currentProcedure,
["USER NAME"] = Environment.UserName,
["MACHINE NAME"] = Environment.MachineName
}.Select(x => $"[{x.Key}]=|{x.Value}|"));
log.Info(logMessage);
}
catch (Exception ex)
{
ErrorHandler.DisplayMessage(ex);
}
}
19
Source : ErrorHandler.cs
with MIT License
from Excel-projects
with MIT License
from Excel-projects
public static void CreateLogRecord()
{
try
{
var sf = new System.Diagnostics.StackFrame(1);
var caller = sf.GetMethod();
var currentProcedure = caller.Name.Trim();
var logMessage = string.Concat(new Dictionary<string, string>
{
["PROCEDURE"] = currentProcedure,
["USER NAME"] = Environment.UserName,
["MACHINE NAME"] = Environment.MachineName
}.Select(x => $"[{x.Key}]=|{x.Value}|"));
log.Info(logMessage);
}
catch (Exception ex)
{
ErrorHandler.DisplayMessage(ex);
}
}
19
Source : AssemblyLookupSet.cs
with MIT License
from ExRam
with MIT License
from ExRam
public IreplacedemblyLookupSet IncludereplacedembliesFromStackTrace()
{
return Includereplacedemblies(new StackTrace().GetFrames()
.Select(frame => frame.GetMethod()?.DeclaringType?.replacedembly)
.Where(replacedembly => replacedembly != null)
.Select(replacedembly => replacedembly!));
}
19
Source : Logger.cs
with Mozilla Public License 2.0
from faintpixel
with Mozilla Public License 2.0
from faintpixel
[MethodImpl(MethodImplOptions.NoInlining)] // This prevents the compiler from inlining the function to optimize things. Doing so would alter our stack trace so we might not get the right frame.
private string GetSource()
{
StackTrace stackTrace = new StackTrace();
StackFrame frame = stackTrace.GetFrame(STACK_FRAME); // 0 would be this function, 1 is the one that called it (eg, Log), and 2 should be whatever called log.
var method = frame.GetMethod();
var methodName = method.Name;
var clreplacedName = method.ReflectedType.Name;
var source = String.Format("{0} {1}.{2}", APPLICATION_NAME, clreplacedName, methodName);
return source;
}
19
Source : SqlLog.cs
with GNU General Public License v3.0
from Fe7n
with GNU General Public License v3.0
from Fe7n
public void Write(string message, TraceLevel level)
{
if (!MayWriteType(level))
return;
var caller = "TShock";
var frame = new StackTrace().GetFrame(2);
if (frame != null)
{
var meth = frame.GetMethod();
if (meth != null && meth.DeclaringType != null)
caller = meth.DeclaringType.Name;
}
try
{
if (_useTextLog)
{
_backupLog.Write(message, level);
return;
}
_database.Query("INSERT INTO Logs (TimeStamp, Caller, LogLevel, Message) VALUES (@0, @1, @2, @3)",
DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture), caller, (int)level, message);
var success = true;
while (_failures.Count > 0 && success)
{
var info = _failures.First();
try
{
_database.Query("INSERT INTO Logs (TimeStamp, Caller, LogLevel, Message) VALUES (@0, @1, @2, @3)",
info.timestamp, info.caller, (int)info.logLevel, info.message);
}
catch (Exception ex)
{
success = false;
_failures.Add(new LogInfo
{
caller = "TShock",
logLevel = TraceLevel.Error,
message = string.Format("SQL Log insert query failed: {0}", ex),
timestamp = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture)
});
}
if (success)
_failures.RemoveAt(0);
}
}
catch (Exception ex)
{
_backupLog.ConsoleError("SQL Log insert query failed: {0}", ex);
_failures.Add(new LogInfo
{
logLevel = level,
message = message,
caller = caller,
timestamp = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture)
});
}
if (_failures.Count >= TShock.Config.RevertToTextLogsOnSqlFailures)
{
_useTextLog = true;
_backupLog.ConsoleError("SQL Logging disabled due to errors. Reverting to text logging.");
foreach (var logInfo in _failures)
{
_backupLog.Write(string.Format("SQL log failed at: {0}. {1}", logInfo.timestamp, logInfo),
TraceLevel.Error);
}
_failures.Clear();
}
}
19
Source : TextLog.cs
with GNU General Public License v3.0
from Fe7n
with GNU General Public License v3.0
from Fe7n
public void Write(string message, TraceLevel level)
{
if (!MayWriteType(level))
return;
var caller = "TShock";
var frame = new StackTrace().GetFrame(2);
if (frame != null)
{
var meth = frame.GetMethod();
if (meth != null && meth.DeclaringType != null)
caller = meth.DeclaringType.Name;
}
var logEntry = string.Format("{0} - {1}: {2}: {3}",
DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture),
caller, level.ToString().ToUpper(), message);
try
{
_logWriter.WriteLine(logEntry);
_logWriter.Flush();
}
catch (ObjectDisposedException)
{
ServerApi.LogWriter.PluginWriteLine(TShock.instance, logEntry, TraceLevel.Error);
Console.WriteLine("Unable to write to log as log has been disposed.");
Console.WriteLine("{0} - {1}: {2}: {3}",
DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture),
caller, level.ToString().ToUpper(), message);
}
}
19
Source : CommandStack.cs
with BSD 3-Clause "New" or "Revised" License
from FireFox2000000
with BSD 3-Clause "New" or "Revised" License
from FireFox2000000
public void Push(ICommand command)
{
#if DEBUG_METHOD_CALL
System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace(true);
System.Diagnostics.StackFrame frame = stackTrace.GetFrame(1);
Debug.LogFormat("Command Stack Push: {0} in file {1} at line {2}", frame.GetMethod().Name, System.IO.Path.GetFileName(frame.GetFileName()), frame.GetFileLineNumber());
#endif
OnPush(command);
ResetTail();
++currentStackIndex;
command.Invoke();
commands.Add(command);
}
19
Source : CommandStack.cs
with BSD 3-Clause "New" or "Revised" License
from FireFox2000000
with BSD 3-Clause "New" or "Revised" License
from FireFox2000000
public void Pop()
{
#if DEBUG_METHOD_CALL
System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace(true);
System.Diagnostics.StackFrame frame = stackTrace.GetFrame(1);
Debug.LogFormat("Command Stack Pop: {0} in file {1} at line {2}", frame.GetMethod().Name, System.IO.Path.GetFileName(frame.GetFileName()), frame.GetFileLineNumber());
#endif
if (!isAtStart)
{
OnPop(commands[currentStackIndex]);
commands[currentStackIndex--].Revoke();
}
}
19
Source : StackFrameExtensions.cs
with BSD 3-Clause "New" or "Revised" License
from fluffynuts
with BSD 3-Clause "New" or "Revised" License
from fluffynuts
internal static bool IsFromOrReferencesThisreplacedembly(
this StackFrame frame
)
{
var methodInfo = frame.GetMethod();
if (Equals(methodInfo?.DeclaringType?.Getreplacedembly(), Thisreplacedembly))
return true;
var parameters = methodInfo?.GetParameters() ?? new ParameterInfo[0];
return parameters.Any(
p => Equals(p.ParameterType.Getreplacedembly(), Thisreplacedembly)
);
}
19
Source : ServiceHandler.cs
with MIT License
from fooberichu150
with MIT License
from fooberichu150
private static void LogTimeout(string loggingHint, int frameLevel, ref int waitAttempt, ref System.Diagnostics.Stopwatch profiler, ILogger logger = null)
{
if (profiler == null)
{
profiler = new System.Diagnostics.Stopwatch();
profiler.Start();
}
StringBuilder builder = new StringBuilder();
builder.AppendLine(string.Format("Thread {0}: Request timeout #{1}", Thread.CurrentThread.ManagedThreadId, ++waitAttempt));
// On the first timeout, log the stack trace
if (waitAttempt == 1)
{
StackTrace stackTrace = new StackTrace(); // get call stack
StackFrame[] stackFrames = stackTrace.GetFrames();
// The frameLevel is going to be one deeper than whatever it was coming in. So skip frameLevel + 1 to get the originating method call
builder.AppendFormat("*** Call from {0}", stackFrames.Skip(frameLevel + 1).First().GetMethod().Name);
if (!string.IsNullOrEmpty(loggingHint))
builder.AppendLine(string.Format(". Caller hint: {0}", loggingHint));
else
builder.AppendLine();
}
logger?.LogInformation(builder.ToString());
}
19
Source : report.cs
with MIT License
from fuse-open
with MIT License
from fuse-open
static string FriendlyStackTrace (StackTrace t)
{
StringBuilder sb = new StringBuilder ();
bool foundUserCode = false;
for (int i = 0; i < t.FrameCount; i++) {
StackFrame f = t.GetFrame (i);
var mb = f.GetMethod ();
if (!foundUserCode && mb.ReflectedType == typeof (Report))
continue;
foundUserCode = true;
sb.Append ("\tin ");
if (f.GetFileLineNumber () > 0)
sb.AppendFormat ("(at {0}:{1}) ", f.GetFileName (), f.GetFileLineNumber ());
sb.AppendFormat ("{0}.{1} (", mb.ReflectedType.Name, mb.Name);
bool first = true;
foreach (var pi in mb.GetParameters ()) {
if (!first)
sb.Append (", ");
first = false;
sb.Append (pi.ParameterType.FullName);
}
sb.Append (")\n");
}
return sb.ToString ();
}
19
Source : TestBase.cs
with MIT License
from fuse-open
with MIT License
from fuse-open
protected void TestPerformance(string code, [CallerMemberName] string testName = "")
{
ConfigureProjectReferences();
//get calling method info
StackTrace stackTrace = new StackTrace();
var callingMethod = stackTrace.GetFrame(1).GetMethod();
var testAttribute = (PerformanceTestAttribute)callingMethod.GetCustomAttributes(typeof(PerformanceTestAttribute), true)[0];
var caret = GetCaret(ref code);
var filePath = AbsoluteDirectoryPath.Parse(Directory.GetCurrentDirectory()) / new FileName(testName);
var log = new DummyLogger();
var context = Context.CreateContext(filePath, code, caret, new DummySourcePackage());
var mainPackage = PackageCache.GetPackage(new Log(log.TextWriter), _project);
mainPackage.SetCacheDirectory((AbsoluteDirectoryPath.Parse(mainPackage.CacheDirectory) / new DirectoryName("UxCompletion")).NativePath);
var build = new CodeNinjaBuild(log, _project, _editors, mainPackage, mainPackage.References.ToList(), code, filePath);
build.Execute();
Stopwatch sw = new Stopwatch();
sw.Start();
SuggestionParser.GetSuggestions(build.Compiler, context, caret, new DummyReader());
sw.Stop();
if (_context == null)
throw new ArgumentNullException("_context");
_context.Logger.LogTimeEvent(testName, testAttribute.Description, sw.ElapsedMilliseconds / 1000f);
}
19
Source : Dbug.cs
with MIT License
from genesisdotnet
with MIT License
from genesisdotnet
public static void Dump(object sender, string message = "")
{
Debug.WriteLine($@"{sender.GetType().Name}.{new StackTrace().GetFrame(1).GetMethod().Name}|{message}");
}
19
Source : SentryStackTraceFactory.cs
with MIT License
from getsentry
with MIT License
from getsentry
protected virtual MethodBase? GetMethod(StackFrame stackFrame)
=> stackFrame.GetMethod();
19
Source : Logger.cs
with MIT License
from ghost1372
with MIT License
from ghost1372
private static MethodBase GetCallingMethodBase(StackFrame stackFrame)
{
return stackFrame == null
? MethodBase.GetCurrentMethod() : stackFrame.GetMethod();
}
19
Source : Logger.cs
with MIT License
from ghost1372
with MIT License
from ghost1372
private static StackFrame FindStackFrame()
{
var stackTrace = new StackTrace();
for (var i = 0; i < stackTrace.GetFrames().Count(); i++)
{
var methodBase = stackTrace.GetFrame(i).GetMethod();
var name = MethodBase.GetCurrentMethod().Name;
if (!methodBase.Name.Equals("Log") && !methodBase.Name.Equals(name))
return new StackFrame(i, true);
}
return null;
}
19
Source : ExampleRunner.cs
with Apache License 2.0
from googleads
with Apache License 2.0
from googleads
public void Run(string exampleName, IEnumerable<string> args)
{
SystemType codeExampleType = GetCodeExampleType(exampleName);
if (codeExampleType != null)
{
Console.WriteLine($"Requested: '{exampleName}', Loaded: '" +
$"{ExampleBase.GetVersionedName(codeExampleType)}'.");
}
else
{
throw new KeyNotFoundException($"Code example not found: '{exampleName}'.");
}
MethodBase method = codeExampleType.GetMethod("Main",
BindingFlags.Static | BindingFlags.Public);
if (method == null)
{
throw new MissingMethodException($"Main method not found in example: " +
$"'{exampleName}'.");
}
try
{
method.Invoke(null, new object[] { args.ToArray() });
}
catch (Exception e)
{
StackTrace stackTrace = new StackTrace(e.InnerException);
StackFrame frame = stackTrace.GetFrame(0);
if (frame.GetMethod() == method)
{
// The site of the exception was the main method itself. So there was an error
// calling the Run() method, typically due to argument errors.
throw new ArgumentException("Could not call the Run() method from Main(). " +
"Check your arguments.");
}
throw e.InnerException;
}
}
19
Source : ExceptionRecorderExtensions.cs
with Apache License 2.0
from googlestadia
with Apache License 2.0
from googlestadia
static void Record(IExceptionRecorder recorder, Exception ex, StackTrace stackTrace)
{
if (ex == null)
{
throw new ArgumentNullException(nameof(ex));
}
if (stackTrace.FrameCount > 0)
{
var callerInfo = stackTrace.GetFrame(0).GetMethod();
recorder.Record(callerInfo, ex);
}
else
{
RecordNoCaller(recorder, ex);
}
}
19
Source : ExceptionRecorder.cs
with Apache License 2.0
from googlestadia
with Apache License 2.0
from googlestadia
List<VSIExceptionData.Types.Exception.Types.StackTraceFrame> GetStackTraceFrames(
Exception ex)
{
var frames = new List<VSIExceptionData.Types.Exception.Types.StackTraceFrame>();
var stackTrace = new StackTrace(ex, true);
for (int curIndex = 0;
curIndex < stackTrace.GetFrames()?.Length && curIndex < _maxStackTraceFrames;
curIndex++)
{
var curFrame = stackTrace.GetFrame(curIndex);
var curTransformedFrame =
new VSIExceptionData.Types.Exception.Types.StackTraceFrame();
curTransformedFrame.AllowedNamespace =
IsMethodInAllowedNamespace(curFrame.GetMethod());
if (curTransformedFrame.AllowedNamespace.Value)
{
curTransformedFrame.Method = curFrame.GetMethod().GetProto();
curTransformedFrame.Filename = Path.GetFileName(curFrame.GetFileName());
curTransformedFrame.LineNumber = (uint?) curFrame.GetFileLineNumber();
}
frames.Add(curTransformedFrame);
}
return frames;
}
19
Source : ExceptionRecorderTests.cs
with Apache License 2.0
from googlestadia
with Apache License 2.0
from googlestadia
[Test]
public void RecordWithStackTrace()
{
var ex = new TestException2();
// Throw exception to capture the stack trace
try
{
throw ex;
}
catch (TestException2)
{
}
_exceptionRecorder.Record(TestClreplaced.MethodInfo1, ex);
var exceptionData = new VSIExceptionData
{
CatchSite = TestClreplaced.MethodInfo1.GetProto()
};
var firstExceptionInChain = new VSIExceptionData.Types.Exception
{
ExceptionType = typeof(TestException2).GetProto()
};
var stackTraceFrame = new StackTrace(ex, true).GetFrame(0);
firstExceptionInChain.ExceptionStackTraceFrames.Add(
new VSIExceptionData.Types.Exception.Types.StackTraceFrame
{
AllowedNamespace = true,
Method = stackTraceFrame.GetMethod().GetProto(),
Filename = Path.GetFileName(stackTraceFrame.GetFileName()),
LineNumber = (uint?) stackTraceFrame.GetFileLineNumber()
});
exceptionData.ExceptionsChain.Add(firstExceptionInChain);
var logEvent = new DeveloperLogEvent
{
StatusCode = DeveloperEventStatus.Types.Code.InternalError
};
logEvent.ExceptionsData.Add(exceptionData);
_fakeMetrics.Received()
.RecordEvent(DeveloperEventType.Types.Type.VsiException, logEvent);
}
19
Source : RegisterInfo.cs
with MIT License
from hadashiA
with MIT License
from hadashiA
public string GetHeadline()
{
if (headLineStackFrame == null)
return "";
var method = headLineStackFrame.GetMethod();
var filename = GetFilename();
if (filename != null)
{
var lineNumber = GetFileLineNumber();
return $"{method.DeclaringType?.FullName}.{method.Name} (at {Path.GetFileName(filename)}:{lineNumber})";
}
var ilOffset = headLineStackFrame.GetILOffset();
if (ilOffset != -1)
{
return $"{method.DeclaringType?.FullName}.{method.Name}(offset: {ilOffset})";
}
return $"{method.DeclaringType?.FullName}.{method.Name}";
}
19
Source : RegisterInfo.cs
with MIT License
from hadashiA
with MIT License
from hadashiA
StackFrame GetHeadlineFrame(StackTrace stackTrace)
{
for (var i = 0; i < stackTrace.FrameCount; i++)
{
var sf = stackTrace.GetFrame(i);
if (sf == null) continue;
var m = sf.GetMethod();
if (m == null) continue;
if (m.DeclaringType == null) continue;
if (m.DeclaringType.Namespace == null || !m.DeclaringType.Namespace.StartsWith("VContainer"))
{
return sf;
}
}
return stackTrace.FrameCount > 0 ? stackTrace.GetFrame(0) : null;
}
19
Source : LogHelper.cs
with GNU Affero General Public License v3.0
from hamflx
with GNU Affero General Public License v3.0
from hamflx
public static void WriteErrorByCurrentMethod(Exception ex)
{
StackFrame frame = new StackFrame(1, false);
StringBuilder sb = new StringBuilder();
sb.AppendLine("DateTime:" + DateTime.Now.ToString());
sb.AppendLine("Method:" + frame.GetMethod().Name);
sb.AppendLine("Exception Message:" + ex.Message);
sb.AppendLine("StackTrace:" + ex.StackTrace);
_logQueue.Enqueue(sb.ToString());
_event.Set();
}
19
Source : LogHelper.cs
with GNU Affero General Public License v3.0
from hamflx
with GNU Affero General Public License v3.0
from hamflx
public static void WriteErrorByCurrentMethod(string log)
{
StackFrame frame = new StackFrame(1, false);
StringBuilder sb = new StringBuilder();
sb.AppendLine("DateTime:" + DateTime.Now.ToString());
sb.AppendLine("Method:" + frame.GetMethod().Name);
sb.AppendLine("Log:" + log);
_logQueue.Enqueue(sb.ToString());
_event.Set();
}
19
Source : AwaitAutoResetEvent.cs
with GNU Affero General Public License v3.0
from hamflx
with GNU Affero General Public License v3.0
from hamflx
public void SetOneData(byte[] data = null)
{
StackFrame frame = new StackFrame(1, false);
LogHelper.DebugWriteLog(frame.GetMethod().Name + " SetOneData version:" + _version);
if (Interlocked.Increment(ref _version) >= 0)
{
_buffer = data;
_event.Set();
LogHelper.DebugWriteLog(frame.GetMethod().Name + " SetOneData finish version:" + _version);
}
}
19
Source : AwaitAutoResetEvent.cs
with GNU Affero General Public License v3.0
from hamflx
with GNU Affero General Public License v3.0
from hamflx
public byte[] AwaitOneData()
{
StackFrame frame = new StackFrame(1, false);
LogHelper.DebugWriteLog(frame.GetMethod().Name + " AwaitOneData version:" + _version);
var re = Interlocked.Decrement(ref _version);
LogHelper.DebugWriteLog("re:" + re);
if (re <= 0)
{
LogHelper.DebugWriteLog(frame.GetMethod().Name + " AwaitOneData ----wait version:" + _version);
_event.Reset();
_event.WaitOne();
LogHelper.DebugWriteLog(frame.GetMethod().Name + " AwaitOneData ----wait finish version:" + _version);
}
return this._buffer;
}
19
Source : PerformanceTracer.cs
with Apache License 2.0
from HanJunJun
with Apache License 2.0
from HanJunJun
public static void InvokeAsync(Action action, Action callback, string traceName = null)
{
if (performanceTracer >= 0)
{
if (string.IsNullOrWhiteSpace(traceName))
{
var method = new StackTrace().GetFrames()[1].GetMethod();
traceName = string.Format("{0}.{1}", method.ReflectedType.FullName, method.Name);
}
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
action.BeginInvoke(delegate
{
callback();
stopwatch.Stop();
if (stopwatch.Elapsed.TotalMilliseconds > performanceTracer)
{
if (!Debugger.IsAttached)
{
WriteDeviceLog.WriteLog("Log\\" + traceName, "性能问题(" + traceName + ")" + stopwatch.Elapsed.TotalMilliseconds + "ms");
}
Debug.WriteLine("性能问题({0}),耗时{1}毫秒。", traceName, stopwatch.Elapsed.TotalMilliseconds);
}
}
, null);
}
else
{
action.BeginInvoke(null, null);
}
}
19
Source : PerformanceTracer.cs
with Apache License 2.0
from HanJunJun
with Apache License 2.0
from HanJunJun
public static TResult Invoke<TResult>(Func<TResult> func, string traceName = null)
{
if (performanceTracer >= 0)
{
if (string.IsNullOrWhiteSpace(traceName))
{
var method = new StackTrace().GetFrames()[1].GetMethod();
traceName = string.Format("{0}.{1}", method.ReflectedType.FullName, method.Name);
}
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
TResult result = func();
stopwatch.Stop();
if (stopwatch.Elapsed.TotalMilliseconds > performanceTracer)
{
if (!Debugger.IsAttached)
{
WriteDeviceLog.WriteLog("Log\\"+ traceName, "性能问题(" + traceName + ")" + stopwatch.Elapsed.TotalMilliseconds + "ms");
}
Debug.WriteLine("性能问题({0}),耗时{1}毫秒。", traceName, stopwatch.Elapsed.TotalMilliseconds);
}
return result;
}
else
{
return func();
}
}
19
Source : PerformanceTracer.cs
with Apache License 2.0
from HanJunJun
with Apache License 2.0
from HanJunJun
public static void Invoke(Action action, string traceName = null, bool enableThrow = true)
{
if (performanceTracer >= 0)
{
if (string.IsNullOrWhiteSpace(traceName))
{
var method = new StackTrace().GetFrames()[1].GetMethod();
traceName = string.Format("{0}.{1}", method.ReflectedType.FullName, method.Name);
}
try
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
action();
stopwatch.Stop();
if (stopwatch.Elapsed.TotalMilliseconds > performanceTracer)
{
if (!Debugger.IsAttached)
{
WriteDeviceLog.WriteLog("Log\\" + traceName, "性能问题(" + traceName + ")" + stopwatch.Elapsed.TotalMilliseconds + "ms");
}
Debug.WriteLine("性能问题({0}),耗时{1}毫秒。", traceName, stopwatch.Elapsed.TotalMilliseconds);
}
}
catch (Exception ex)
{
if (enableThrow)
{
throw;
}
//LogHelper.HandleError(ex, traceName ?? ex.Message);
WriteDeviceLog.WriteLog("Log\\" + traceName, ex.Message);
}
}
else
{
try
{
action();
}
catch (Exception ex)
{
if (enableThrow)
{
throw;
}
WriteDeviceLog.WriteLog("Log\\" + traceName, ex.Message);
}
}
}
19
Source : PerformanceTracer.cs
with Apache License 2.0
from HanJunJun
with Apache License 2.0
from HanJunJun
public static void InvokeAsync(Action action, string traceName = null)
{
if (performanceTracer >= 0)
{
if (string.IsNullOrWhiteSpace(traceName))
{
var method = new StackTrace().GetFrames()[1].GetMethod();
traceName = string.Format("{0}.{1}", method.ReflectedType.FullName, method.Name);
}
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
action.BeginInvoke(delegate
{
stopwatch.Stop();
if (stopwatch.Elapsed.TotalMilliseconds > performanceTracer)
{
if (!Debugger.IsAttached)
{
WriteDeviceLog.WriteLog("Log\\" + traceName, "性能问题(" + traceName + ")" + stopwatch.Elapsed.TotalMilliseconds + "ms");
}
Debug.WriteLine("性能问题({0}),耗时{1}毫秒。", traceName, stopwatch.Elapsed.TotalMilliseconds);
}
}, null);
}
else
{
action.BeginInvoke(null, null);
}
}
19
Source : CooperateRimming.cs
with GNU Lesser General Public License v3.0
from havietisov
with GNU Lesser General Public License v3.0
from havietisov
[HarmonyAfter]
public static void postfix(Pawn p)
{
StackTrace st = new StackTrace();
RimLog.Message("==========");
foreach (var a in st.GetFrames())
{
RimLog.Message(a.GetMethod().Name + "::" + a.GetMethod().DeclaringType);
}
RimLog.Message("pawn added to world : " + p);
RimLog.Message("///==========");
}
19
Source : getValuePatch.cs
with GNU Lesser General Public License v3.0
from havietisov
with GNU Lesser General Public License v3.0
from havietisov
[HarmonyPostfix]
public static void get_Value(ref uint ___iterations, ref float __result, RandomNumberGenerator ___random)
{
if(!diagnostics)
{
return;
}
if (Current.Game != null && Find.TickManager.TicksGame > 0)
{
//if (RandContextCounter.currentContextName == null)
{
/*
StackTrace st = new StackTrace();
Utilities.RimLog.Message("=========== outside of context rand!==========");
foreach (var a in st.GetFrames())
{
Utilities.RimLog.Message(a.GetMethod().Name + "::" + a.GetMethod().DeclaringType);
}
Utilities.RimLog.Message("===========\\outside of context rand!==========");*/
}
//else
{
if (RandContextCounter.currentContextName != typeof(CooperateRimming.MoteBullreplaced_placeholder))
{
StackTrace st = new StackTrace();
string str = "";
string mtbstr = "";
foreach (StackFrame sf in st.GetFrames())
{
str += sf.GetMethod().Name + "::" + sf.GetMethod().DeclaringType + "\r\n";
}
foreach (var sf in MTBEventOccurs_patch.mtb_dump)
{
mtbstr += "=============[" + sf.ctx + "]=============\r\n";
foreach (StackFrame sf_ in sf.context)
{
mtbstr += sf_.GetMethod().Name + "::" + sf_.GetMethod().DeclaringType + "\r\n";
}
mtbstr += sf.mtb + ":" + sf.mtbUnit + ":" + sf.checkDuration + ":" + sf.__result + "\r\n";
mtbstr += "\\===========\r\n";
}
framelistForTicks.Add(new diagdata() { clientID = SyncTickData.cliendID, result = __result, context = RandContextCounter.currentContextName, frame = Find.TickManager.TicksGame, iteration = ___iterations, trace = str });
//framelistForTicks.Add(new diagdata() { clientID = SyncTickData.cliendID, result = -1, context = typeof(MTBEventOccurs_patch), frame = Find.TickManager.TicksGame, iteration = ___iterations, trace = mtbstr });
MTBEventOccurs_patch.mtb_dump.Clear();
//RimLog.Message("framelistForTicks " + framelistForTicks.Count);
//System.IO.File.WriteAllText("C:/CoopReplays/" + SyncTickData.cliendID + "/" + RandContextCounter.currentContextName + "__" + "_" + ___random.seed + "_" + ___iterations + ".txt", str);
}
}
//int tick = Current.Game == null ? -1 : Find.TickManager.TicksGame;
//StackTrace tr = new StackTrace();
//string s = "";
bool bb = false;
{
//foreach (var b in tr.GetFrames())
{
//System.IO.File.AppendAllText("G:\\CoopReplays\\" + (SyncTickData.cliendID + "_tick_" + Find.TickManager.TicksGame) + ".txt", b.GetMethod().Name + "::" + b.GetMethod().ReflectedType + " || " + "\r\n");
}
}
/*
foreach (var frame in tr.GetFrames())
{
streamholder.WriteLine(frame.GetMethod().ReflectedType + "::" + frame.GetMethod().Name, "state");
}*/
//Utilities.RimLog.Message(">>>>>>>>>>>>>>> FOUL RAND CALL");
}
//if (CooperateRimming.dumpRand)
{
/*
int tick = Current.Game == null ? -1 : Find.TickManager.TicksGame;
StackTrace tr = new StackTrace();
streamholder.WriteLine("====STACK====", "state");
foreach (var frame in tr.GetFrames())
{
streamholder.WriteLine(frame.GetMethod().ReflectedType + "::" + frame.GetMethod().Name, "state");
}
streamholder.WriteLine("====END====", "state");
streamholder.WriteLine(__result + " at iter " + ___iterations + " at tick " + tick, "state");*/
}
}
19
Source : LoggerHelper.cs
with MIT License
from HenJigg
with MIT License
from HenJigg
public static void WriteLog(string msg, string errorMessage, Exception e = null)
{
StackTrace st = new StackTrace(true);
Log.GetLog().WriteLogToFile(st.GetFrame(1).GetMethod().ReflectedType.Name, st.GetFrame(1).GetMethod().Name, st.GetFrame(1).GetFileLineNumber().ToString(), msg, e, errorMessage);
}
19
Source : LoggerHelper.cs
with MIT License
from HenJigg
with MIT License
from HenJigg
public static void WriteLog(string msg, Exception e = null)
{
StackTrace st = new StackTrace(true);
Log.GetLog().WriteLogToFile(st.GetFrame(1).GetMethod().ReflectedType.Name, st.GetFrame(1).GetMethod().Name, st.GetFrame(1).GetFileLineNumber().ToString(), msg, e);
}
19
Source : ProcessTaskArgumentTests.cs
with GNU General Public License v3.0
from HicServices
with GNU General Public License v3.0
from HicServices
[Test]
[TestCase(true)]
[TestCase(false)]
public void TypeOfTableInfo(bool declareAsInterface)
{
string tableInfoName = "TableInfoFor_" + new StackTrace().GetFrame(0).GetMethod().Name;
TableInfo toCleanup = CatalogueRepository.GetAllObjects<TableInfo>().SingleOrDefault(t => t.Name.Equals(tableInfoName));
if(toCleanup != null)
toCleanup.DeleteInDatabase();
var loadMetadata = new LoadMetadata(CatalogueRepository);
try
{
var pt = new ProcessTask(CatalogueRepository, loadMetadata, LoadStage.AdjustStaging);
var pta = new ProcessTaskArgument(CatalogueRepository, pt);
if(declareAsInterface)
pta.SetType(typeof(ITableInfo));
else
pta.SetType(typeof (TableInfo));
var tableInfo = new TableInfo(CatalogueRepository, tableInfoName);
try
{
pta.SetValue(tableInfo);
pta.SaveToDatabase();
var newInstanceOfPTA = CatalogueRepository.GetObjectByID<ProcessTaskArgument>(pta.ID);
replacedert.AreEqual(newInstanceOfPTA.Value,pta.Value);
TableInfo t1 = (TableInfo) pta.GetValuereplacedystemType();
TableInfo t2 = (TableInfo)newInstanceOfPTA.GetValuereplacedystemType();
replacedert.AreEqual(t1.ID,t2.ID);
}
finally
{
tableInfo.DeleteInDatabase();
}
}
finally
{
loadMetadata.DeleteInDatabase();
}
}
19
Source : ProcessTaskArgumentTests.cs
with GNU General Public License v3.0
from HicServices
with GNU General Public License v3.0
from HicServices
[Test]
public void TypeOfPreLoadDiscardedColumn()
{
string methodName = new StackTrace().GetFrame(0).GetMethod().Name;
string tableInfoName = "TableInfoFor_" + methodName;
string preLoadDiscardedColumnName = "PreLoadDiscardedColumnFor_" + methodName;
TableInfo toCleanup = CatalogueRepository.GetAllObjects<TableInfo>().SingleOrDefault(t => t.Name.Equals(tableInfoName));
PreLoadDiscardedColumn toCleanupCol = CatalogueRepository.GetAllObjects<PreLoadDiscardedColumn>()
.SingleOrDefault(c => c.RuntimeColumnName.Equals(preLoadDiscardedColumnName));
//must delete pre load discarded first
if (toCleanupCol != null)
toCleanupCol.DeleteInDatabase();
if (toCleanup != null)
toCleanup.DeleteInDatabase();
var lmd = new LoadMetadata(CatalogueRepository);
try
{
var pt = new ProcessTask(CatalogueRepository, lmd, LoadStage.AdjustStaging);
var pta = new ProcessTaskArgument(CatalogueRepository, pt);
pta.SetType(typeof(PreLoadDiscardedColumn));
var tableInfo = new TableInfo(CatalogueRepository, tableInfoName);
PreLoadDiscardedColumn preloadDiscardedColumn = new PreLoadDiscardedColumn(CatalogueRepository, tableInfo, preLoadDiscardedColumnName);
try
{
pta.SetValue(preloadDiscardedColumn);
pta.SaveToDatabase();
var newInstanceOfPTA = CatalogueRepository.GetObjectByID<ProcessTaskArgument>(pta.ID);
replacedert.AreEqual(newInstanceOfPTA.Value, pta.Value);
PreLoadDiscardedColumn p1 = (PreLoadDiscardedColumn)pta.GetValuereplacedystemType();
PreLoadDiscardedColumn p2 = (PreLoadDiscardedColumn)newInstanceOfPTA.GetValuereplacedystemType();
replacedert.AreEqual(p1.ID, p2.ID);
}
finally
{
preloadDiscardedColumn.DeleteInDatabase();
tableInfo.DeleteInDatabase();
}
}
finally
{
lmd.DeleteInDatabase();
}
}
19
Source : ProcessTaskArgumentTests.cs
with GNU General Public License v3.0
from HicServices
with GNU General Public License v3.0
from HicServices
[Test]
public void TableInfoType_FetchAfterDelete_ReturnsNull()
{
string tableInfoName = "TableInfoFor_" + new StackTrace().GetFrame(0).GetMethod().Name;
TableInfo toCleanup = CatalogueRepository.GetAllObjects<TableInfo>().SingleOrDefault(t => t.Name.Equals(tableInfoName));
if (toCleanup != null)
toCleanup.DeleteInDatabase();
var lmd = new LoadMetadata(CatalogueRepository);
try
{
var pt = new ProcessTask(CatalogueRepository, lmd, LoadStage.AdjustStaging);
var pta = new ProcessTaskArgument(CatalogueRepository, pt);
//Prepare to receive a TableInfo object
pta.SetType(typeof(TableInfo));
var tableInfo = new TableInfo(CatalogueRepository, tableInfoName);
//Heres the TableInfo object
pta.SetValue(tableInfo);
pta.SaveToDatabase();
//Lolz I just deleted it out of the database
tableInfo.DeleteInDatabase();
//give the object back now please? - returns null because it's gone (new behaviour)
replacedert.IsNull(pta.GetValuereplacedystemType());
//old behaviour
/*var ex = replacedert.Throws<KeyNotFoundException>(()=>pta.GetValuereplacedystemType());
Stringreplacedert.Contains("Could not find TableInfo with ID",ex.Message);*/
}
finally
{
lmd.DeleteInDatabase();
}
}
19
Source : ProcessTaskArgumentTests.cs
with GNU General Public License v3.0
from HicServices
with GNU General Public License v3.0
from HicServices
[Test]
public void LieToProcessTaskArgumentAboutWhatTypeIs_Throws()
{
string tableInfoName = "TableInfoFor_" + new StackTrace().GetFrame(0).GetMethod().Name;
TableInfo toCleanup = CatalogueRepository.GetAllObjects<TableInfo>().SingleOrDefault(t => t.Name.Equals(tableInfoName));
if (toCleanup != null)
toCleanup.DeleteInDatabase();
var lmd = new LoadMetadata(CatalogueRepository);
try
{
var pt = new ProcessTask(CatalogueRepository, lmd, LoadStage.AdjustStaging);
var pta = new ProcessTaskArgument(CatalogueRepository, pt);
var tableInfo = new TableInfo(CatalogueRepository, tableInfoName);
try
{
//tell it that we are going to give it a PreLoadDiscardedColumn
pta.SetType(typeof(PreLoadDiscardedColumn));
//then surprise! heres a TableInfo!
var ex = replacedert.Throws<Exception>(()=>pta.SetValue(tableInfo));
Stringreplacedert.Contains("has an incompatible Type specified (Rdmp.Core.Curation.Data.DataLoad.PreLoadDiscardedColumn)",ex.Message);
}
finally
{
tableInfo.DeleteInDatabase();
}
}
finally
{
lmd.DeleteInDatabase();
}
}
19
Source : ProcessTaskArgumentTests.cs
with GNU General Public License v3.0
from HicServices
with GNU General Public License v3.0
from HicServices
[Test]
public void LieToProcessTaskArgumentAboutWhatTypeIs_Throws()
{
string tableInfoName = "TableInfoFor_" + new StackTrace().GetFrame(0).GetMethod().Name;
TableInfo toCleanup = CatalogueRepository.GetAllObjects<TableInfo>().SingleOrDefault(t => t.Name.Equals(tableInfoName));
if (toCleanup != null)
toCleanup.DeleteInDatabase();
var lmd = new LoadMetadata(CatalogueRepository);
try
{
var pt = new ProcessTask(CatalogueRepository, lmd, LoadStage.AdjustStaging);
var pta = new ProcessTaskArgument(CatalogueRepository, pt);
var tableInfo = new TableInfo(CatalogueRepository, tableInfoName);
try
{
//tell it that we are going to give it a PreLoadDiscardedColumn
pta.SetType(typeof(PreLoadDiscardedColumn));
//then surprise! heres a TableInfo!
var ex = replacedert.Throws<Exception>(()=>pta.SetValue(tableInfo));
Stringreplacedert.Contains("has an incompatible Type specified (CatalogueLibrary.Data.DataLoad.PreLoadDiscardedColumn)",ex.Message);
}
finally
{
tableInfo.DeleteInDatabase();
}
}
finally
{
lmd.DeleteInDatabase();
}
}
19
Source : AdapterTestsBase.cs
with MIT License
from HighEncryption
with MIT License
from HighEncryption
[MethodImpl(MethodImplOptions.NoInlining)]
private string GetCurrentMethod()
{
var st = new StackTrace();
var sf = st.GetFrame(1);
return sf.GetMethod().Name;
}
19
Source : Logger.cs
with GNU General Public License v3.0
from hitchao
with GNU General Public License v3.0
from hitchao
public static string GetAllFootprints(Exception x)
{
if (x == null) return "";
try
{
var st = new StackTrace(x, true);
var frames = st.GetFrames();
var traceString = new StringBuilder();
foreach (var frame in new StackTrace(x, true).GetFrames())
{
if (frame.GetFileLineNumber() < 1)
continue;
traceString.Append($" {Jvedio.Language.Resources.File}: {frame.GetFileName()}");
traceString.Append($" {Jvedio.Language.Resources.Method}: {frame.GetMethod().Name}");
traceString.Append($" {Jvedio.Language.Resources.RowNumber}: {frame.GetFileLineNumber()}{Environment.NewLine}");
}
return traceString.ToString();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return "";
}
19
Source : InterceptStaticCallTests.cs
with MIT License
from Hitmasu
with MIT License
from Hitmasu
private static MethodBase GetSourceTest()
{
StackTrace trace = new();
return trace.GetFrames()
.Select(w => w.GetMethod())
.FirstOrDefault(w => w.GetCustomAttribute<FactAttribute>() != null || w.GetCustomAttribute<TheoryAttribute>() != null);
}
19
Source : InterceptCallTests.cs
with MIT License
from Hitmasu
with MIT License
from Hitmasu
private static MethodBase GetSourceTest()
{
StackTrace trace = new StackTrace(false);
return trace.GetFrames()
.Select(w => w.GetMethod())
.FirstOrDefault(w => w.GetCustomAttribute<FactAttribute>() != null || w.GetCustomAttribute<TheoryAttribute>() != null);
}
19
Source : Logging.cs
with GNU General Public License v3.0
from HMBSbige
with GNU General Public License v3.0
from HMBSbige
private static string ToString(IEnumerable<StackFrame> stacks)
{
return stacks.Aggregate(string.Empty, (current, stack) => current + $@"{stack.GetMethod()}{Environment.NewLine}");
}
19
Source : AppRestart.cs
with GNU General Public License v3.0
from Hofknecht
with GNU General Public License v3.0
from Hofknecht
[MethodImpl(MethodImplOptions.NoInlining)]
private static string GetCurrentMethod()
{
StackTrace st = new();
StackFrame sf = st.GetFrame(1);
return sf.GetMethod().Name;
}
See More Examples