System.Diagnostics.StackFrame.GetMethod()

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 7

19 Source : Fuzzer.cs
with Apache License 2.0
from 42skillz

private static string FindTheNameOfTheTestInvolved()
        {
            var testName = "(not found)";
            try
            {
                var stackTrace = new StackTrace();

                var testMethod = stackTrace.GetFrames().Select(sf => sf.GetMethod()).First(IsATestMethod);

                testName = $"{testMethod.DeclaringType.Name}.{testMethod.Name}";
            }
            catch
            {
            }

            return testName;
        }

19 Source : MethodCapture.cs
with Apache License 2.0
from 42skillz

[MethodImpl(MethodImplOptions.NoInlining)]
        public static MethodBase CaptureCurrentMethod()
        {
            var st = new StackTrace();
            var sf = st.GetFrame(1);

            var method = sf.GetMethod();

            return method;
        }

19 Source : AppLogger.cs
with MIT License
from adrianmteo

public static ILogger GetLoggerForCurrentClreplaced()
        {
            ILogger logger = new MultiLogger(
                new FileLogger("application.log") { MinimumLevel = LogLevel.Info },
                new FileLogger("error.log") { MinimumLevel = LogLevel.Error },
                new ConsoleLogger() { MaximumLevel = LogLevel.Error }
            );

            StackTrace trace = new StackTrace();

            if (trace.FrameCount > 1)
            {
                logger.Tag = trace.GetFrame(1).GetMethod().DeclaringType.Name;
            }

            return logger;
        }

19 Source : BeatmapDataTransformHelper.cs
with MIT License
from Aeroluna

private static void Postfix(IReadonlyBeatmapData __result)
        {
            // Skip if calling clreplaced is MultiplayerConnectPlayerInstaller
            StackTrace stackTrace = new StackTrace();
            if (!stackTrace.GetFrame(2).GetMethod().Name.Contains("MultiplayerConnectedPlayerInstaller"))
            {
                NoodleObjectDataManager.DeserializeBeatmapData(__result);
                Animation.NoodleEventDataManager.DeserializeBeatmapData(__result);
            }
        }

19 Source : BeatmapDataTransformHelper.cs
with MIT License
from Aeroluna

[HarmonyPriority(Priority.High)]
        private static void Postfix(IReadonlyBeatmapData __result)
        {
            if (__result is CustomBeatmapData customBeatmapData)
            {
                TrackBuilder trackManager = new TrackBuilder(customBeatmapData);
                foreach (BeatmapLineData beatmapLineData in customBeatmapData.beatmapLinesData)
                {
                    foreach (BeatmapObjectData beatmapObjectData in beatmapLineData.beatmapObjectsData)
                    {
                        Dictionary<string, object?> dynData;
                        switch (beatmapObjectData)
                        {
                            case CustomObstacleData obstacleData:
                                dynData = obstacleData.customData;
                                break;

                            case CustomNoteData noteData:
                                dynData = noteData.customData;
                                break;

                            default:
                                continue;
                        }

                        // for epic tracks thing
                        object? trackNameRaw = dynData.Get<object>(TRACK);
                        if (trackNameRaw != null)
                        {
                            IEnumerable<string> trackNames;
                            if (trackNameRaw is List<object> listTrack)
                            {
                                trackNames = listTrack.Cast<string>();
                            }
                            else
                            {
                                trackNames = new string[] { (string)trackNameRaw };
                            }

                            foreach (string trackName in trackNames)
                            {
                                trackManager.AddTrack(trackName);
                            }
                        }
                    }
                }

                customBeatmapData.customData["tracks"] = trackManager.Tracks;

                PointDefinitionBuilder pointDataManager = new PointDefinitionBuilder();
                IEnumerable<Dictionary<string, object?>>? pointDefinitions = customBeatmapData.customData.Get<List<object>>(POINTDEFINITIONS)?.Cast<Dictionary<string, object?>>();
                if (pointDefinitions != null)
                {
                    foreach (Dictionary<string, object?> pointDefintion in pointDefinitions)
                    {
                        string pointName = pointDefintion.Get<string>(NAME) ?? throw new InvalidOperationException("Failed to retrieve point name.");
                        PointDefinition pointData = PointDefinition.ListToPointDefinition(pointDefintion.Get<List<object>>(POINTS) ?? throw new InvalidOperationException("Failed to retrieve point array."));
                        pointDataManager.AddPoint(pointName, pointData);
                    }
                }

                customBeatmapData.customData["pointDefinitions"] = pointDataManager.PointData;

                // EVENT DATA STUFF HERE
                // Skip if calling clreplaced is MultiplayerConnectPlayerInstaller
                StackTrace stackTrace = new StackTrace();
                if (!stackTrace.GetFrame(2).GetMethod().Name.Contains("MultiplayerConnectedPlayerInstaller"))
                {
                    HeckEventDataManager.DeserializeBeatmapData(customBeatmapData);
                }
            }
        }

19 Source : MenuTransitionsHelper.cs
with MIT License
from Aeroluna

private static bool Prefix(
            MenuTransitionsHelper __instance,
            string gameMode,
            IDifficultyBeatmap difficultyBeatmap,
            IPreviewBeatmapLevel previewBeatmapLevel,
            OverrideEnvironmentSettings overrideEnvironmentSettings,
            ColorScheme overrideColorScheme,
            GameplayModifiers gameplayModifiers,
            PlayerSpecificSettings playerSpecificSettings,
            PracticeSettings practiceSettings,
            string backButtonText,
            bool useTestNoteCutSoundEffects,
            Action beforeSceneSwitchCallback,
            Action<StandardLevelScenesTransitionSetupDataSO, LevelCompletionResults> levelFinishedCallback)
        {
            // When in doubt, wrap everything in one big try catch statement!
            try
            {
                // In a perfect world I would patch SingePlayerLevelSelectionFlowCoordinator instead, but im a lazy mf
                // SO WEIRD STACK TRACE JANKINESS WE GO!!!
                StackTrace stackTrace = new StackTrace();
                if (stackTrace.GetFrame(2).GetMethod().Name.Contains("SinglePlayerLevelSelectionFlowCoordinator"))
                {
                    SettingsSetterViewController.StartStandardLevelParameters startStandardLevelParameters = new SettingsSetterViewController.StartStandardLevelParameters(
                        gameMode,
                        difficultyBeatmap,
                        previewBeatmapLevel,
                        overrideEnvironmentSettings,
                        overrideColorScheme,
                        gameplayModifiers,
                        playerSpecificSettings,
                        practiceSettings,
                        backButtonText,
                        useTestNoteCutSoundEffects,
                        beforeSceneSwitchCallback,
                        levelFinishedCallback);

                    SettingsSetterViewController.Instance.Init(startStandardLevelParameters, __instance);
                    return !SettingsSetterViewController.Instance.DoPresent;
                }
                else
                {
                    Plugin.Logger.Log("Level started outside of SinglePlayerLevelSelectionFlowCoordinator, skipping settable settings.", IPA.Logging.Logger.Level.Trace);
                }
            }
            catch (Exception e)
            {
                Plugin.Logger.Log($"Could not setup settable settings!", IPA.Logging.Logger.Level.Error);
                Plugin.Logger.Log(e, IPA.Logging.Logger.Level.Error);
            }

            return true;
        }

19 Source : Debug.cs
with The Unlicense
from aeroson

static void Log(object obj, bool canRepeat)
        {
            var s = obj.ToString();
            if (canRepeat || !alreadyShown.Contains(s))
            {
                var t=new StackTrace(2);
                var f = t.GetFrame(0);
                var m = f.GetMethod();
                
                if(!canRepeat) alreadyShown.Add(s);
                Console.WriteLine("["+m.DeclaringType.Name+"."+m.Name+"] "+s);
            }
        }

19 Source : TraceLogger.cs
with GNU General Public License v3.0
from aiportal

private string GetFunctionFullName(int aSkipFrames)
        {
            string str = string.Empty;
            try
            {
                StackFrame frame = new StackFrame(aSkipFrames);
                StackTrace trace = new StackTrace(frame);
                string name = frame.GetMethod().Name;
                string[] strArray = trace.ToString().Split(new char[] { '.' });
                string str3 = strArray[strArray.Length - 2];
                str = string.Format("{0}::{1}", name, str3);
            }
            catch (Exception)
            {
            }
            return str;
        }

19 Source : DebugLog.cs
with GNU General Public License v3.0
from aiportal

private static string GetFunctionFullName(int skipFrames)
		{
			string str = string.Empty;
			try
			{
				StackFrame frame = new StackFrame(skipFrames);
				var method = frame.GetMethod();
				str = string.Format("{0}::{1}", method.Name, method.DeclaringType.Name);
			}
			catch (Exception) { }
			return str;
		}

19 Source : MapboxUnitTests_SQLiteCache.cs
with MIT License
from alen-smajic

[Test, Order(1)]
		public void InsertSameTileNoOverwrite()
		{
			string methodName = _clreplacedName + "." + new StackFrame().GetMethod().Name;
			List<long> elapsed = simpleInsert(TS_NO_OVERWRITE, false);
			logTime(methodName, elapsed);
			cacheItemreplacederts(TS_NO_OVERWRITE, new CanonicalTileId(0, 0, 0));
			replacedert.AreEqual(1, _cache.TileCount(TS_NO_OVERWRITE), "tileset {0}: unexpected number of tiles", TS_NO_OVERWRITE);
		}

19 Source : MapboxUnitTests_SQLiteCache.cs
with MIT License
from alen-smajic

[Test, Order(2)]
		public void InsertSameTileForceOverwrite()
		{
			string methodName = _clreplacedName + "." + new StackFrame().GetMethod().Name;
			List<long> elapsed = simpleInsert(TS_FORCE_OVERWRITE, true);
			logTime(methodName, elapsed);
			cacheItemreplacederts(TS_FORCE_OVERWRITE, new CanonicalTileId(0, 0, 0));
			replacedert.AreEqual(1, _cache.TileCount(TS_FORCE_OVERWRITE), "tileset {0}: unexpected number of tiles", TS_FORCE_OVERWRITE);
		}

19 Source : MapboxUnitTests_SQLiteCache.cs
with MIT License
from alen-smajic

[Test, Order(5)]
		public void Prune()
		{
			string methodName = _clreplacedName + "." + new StackFrame().GetMethod().Name;
			HashSet<CanonicalTileId> tileIds = new HashSet<CanonicalTileId>();

			int tiles2Insert = (int)_maxCacheTileCount + (int)_cache.PruneCacheDelta + 1;
			ued.Log(string.Format("about to insert {0} tiles", tiles2Insert));
			for (int x = 0; x < tiles2Insert; x++)
			{
				tileIds.Add(new CanonicalTileId(x, 131205, 18));
			}

			List<long> elapsed = simpleInsert(TS_PRUNE, false, tileIds);
			logTime(methodName, elapsed);
			replacedert.AreEqual(_maxCacheTileCount, _cache.TileCount(TS_PRUNE), _cache.PruneCacheDelta, "tileset [{0}]: pruning did not work as expected", TS_PRUNE);
		}

19 Source : TempDir.cs
with GNU General Public License v3.0
from Alois-xx

[MethodImpl(MethodImplOptions.NoInlining)]
        public static ITempDir Create()
        {
            var stack = new StackTrace(1);
            var sf = stack.GetFrame(0);
            return new TempDir(sf.GetMethod().Name);
        }

19 Source : Logger.cs
with MIT License
from AlternateLife

private string GetCallerType()
        {
            string clreplacedName;
            var framesToSkip = FramesToSkip;
            var lastClreplaced = string.Empty;

            do
            {
                var frame = new StackFrame(framesToSkip, false);
                var method = frame.GetMethod();

                if (method == null)
                {
                    clreplacedName = lastClreplaced;

                    break;
                }

                var declaringType = method.DeclaringType;
                if (declaringType == null)
                {
                    clreplacedName = method.Name;

                    break;
                }


                framesToSkip++;
                clreplacedName = declaringType.FullName;
                lastClreplaced = clreplacedName;
            } while (clreplacedName.StartsWith("System.", StringComparison.Ordinal));

            return clreplacedName;
        }

19 Source : GlobalDebug.cs
with MIT License
from ambid17

public static void Error(string message)
    {
        var callingMethod = new StackTrace().GetFrame(1).GetMethod();
        string callingMethodName = callingMethod.Name;
        string callingClreplacedName = callingMethod.ReflectedType.Name;
        string debugMessage = (">" + callingClreplacedName + "." + callingMethodName + "(): " + message + "\n");

        //debugText.text += debugMessage;
        UnityEngine.Debug.Log(debugMessage);
    }

19 Source : GlobalDebug.cs
with MIT License
from ambid17

public static void Debug(string message)
    {
        if (LogLevel.Debug == logLevel)
        {
            var callingMethod = new StackTrace().GetFrame(1).GetMethod();
            string callingMethodName = callingMethod.Name;
            string callingClreplacedName = callingMethod.ReflectedType.Name;
            string debugMessage = (">" + callingClreplacedName + "." + callingMethodName + "(): " + message + "\n");

            //debugText.text += debugMessage;
            UnityEngine.Debug.Log(debugMessage);
        }
    }

19 Source : ModSocketOutput.cs
with MIT License
from amazingalek

private string GetCallingType(StackTrace frame)
		{
			try
			{
				return frame.GetFrame(1).GetMethod().DeclaringType.Name;
			}
			catch (Exception ex)
			{
				var message = new ModSocketMessage
				{
					SenderName = Constants.Owmlreplacedle,
					SenderType = nameof(ModSocketOutput),
					Type = MessageType.Error,
					Message = $"Error while getting calling type : {ex.Message}"
				};
				_socket.WriteToSocket(message);
				return string.Empty;
			}
		}

19 Source : IResultExtensions.cs
with Apache License 2.0
from AndcultureCode

public static IError AddError<T>(this IResult<T> result, string message)
        {
            var frame = new StackFrame(1);
            var method = frame.GetMethod();
            var clreplacedName = method.DeclaringType.Name;
            var methodName = Regex.Replace(method.Name, "<|>.*", ""); // Method name without wrapper
            var key = $"{clreplacedName}.{methodName}";

            return result.AddError(ErrorType.Error, key, message);
        }

19 Source : IResultExtensions.cs
with Apache License 2.0
from AndcultureCode

public static void AddErrorAndLog<T>(this IResult<T> result, ILogger logger, string errorKey, string errorMessage, long? resourceIdentifier = null)
        {
            var methodName = new StackTrace().GetFrame(1).GetMethod().Name;
            var logMessage = errorMessage;
            result.AddErrorsAndLog<T>(logger, errorKey, errorMessage, logMessage, resourceIdentifier?.ToString(), null, methodName);
        }

19 Source : IResultExtensions.cs
with Apache License 2.0
from AndcultureCode

public static void AddErrorsAndLog<T>(this IResult<T> result, ILogger logger, string errorKey, string errorMessage, long resourceIdentifier, IEnumerable<IError> errors = null)
        {
            var methodName = new StackTrace().GetFrame(1).GetMethod().Name;
            var logMessage = errorMessage;
            result.AddErrorsAndLog<T>(logger, errorKey, errorMessage, logMessage, resourceIdentifier.ToString(), errors, methodName);
        }

19 Source : IResultExtensions.cs
with Apache License 2.0
from AndcultureCode

public static void AddErrorsAndLog<T>(this IResult<T> result, ILogger logger, string errorKey, string errorMessage, IEnumerable<IError> errors = null)
        {
            var methodName = new StackTrace().GetFrame(1).GetMethod().Name;
            var logMessage = errorMessage;
            result.AddErrorsAndLog<T>(logger, errorKey, errorMessage, logMessage, null, errors, methodName);
        }

19 Source : IResultExtensions.cs
with Apache License 2.0
from AndcultureCode

public static void AddErrorsAndLog<T>(this IResult<T> result, ILogger logger, string errorKey, string errorMessage, string logMessage, string resourceIdentifier, IEnumerable<IError> errors = null, string methodName = null)
        {
            if (string.IsNullOrWhiteSpace(errorMessage))
            {
                errorMessage = "";
            }

            // Add singular error
            if (!string.IsNullOrWhiteSpace(errorKey))
            {
                result.AddError(errorKey, errorMessage);
            }

            // Add error list
            if (errors != null && errors.Any())
            {
                result.AddErrors(errors);
            }

            var identifierText = !string.IsNullOrWhiteSpace(resourceIdentifier) ? $" ({resourceIdentifier}) -" : "";

            // If not provided, try to detect method name
            if (string.IsNullOrWhiteSpace(methodName))
            {
                methodName = new StackTrace().GetFrame(1).GetMethod().Name;
            }

            // Log all of the above
            logger.LogError($"[{methodName}]{identifierText} {logMessage}");
        }

19 Source : IResultExtensions.cs
with Apache License 2.0
from AndcultureCode

public static void AddErrorAndLog<T>(this IResult<T> result, ILogger logger, IStringLocalizer localizer, string errorKey, params object[] arguments)
        {
            var errorMessage = localizer[errorKey, arguments];
            var logMessage = localizer.Default(errorKey, arguments);
            var methodName = new StackTrace().GetFrame(1).GetMethod().Name;
            result.AddErrorsAndLog<T>(logger, errorKey, errorMessage, logMessage, null, null, methodName);
        }

19 Source : IResultExtensions.cs
with Apache License 2.0
from AndcultureCode

public static void AddErrorAndLog<T>(this IResult<T> result, ILogger logger, IStringLocalizer localizer, string errorKey, long resourceIdentifier, params object[] arguments)
        {
            var errorMessage = localizer[errorKey, arguments];
            var logMessage = localizer.Default(errorKey, arguments);
            var methodName = new StackTrace().GetFrame(1).GetMethod().Name;
            result.AddErrorsAndLog<T>(logger, errorKey, errorMessage, logMessage, resourceIdentifier.ToString(), null, methodName);
        }

19 Source : IResultExtensions.cs
with Apache License 2.0
from AndcultureCode

public static void AddErrorsAndLog<T>(this IResult<T> result, ILogger logger, IStringLocalizer localizer, string errorKey, long resourceIdentifier, IEnumerable<IError> errors = null, params object[] arguments)
        {
            var errorMessage = localizer[errorKey, arguments];
            var logMessage = localizer.Default(errorKey, arguments);
            var methodName = new StackTrace().GetFrame(1).GetMethod().Name;
            result.AddErrorsAndLog<T>(logger, errorKey, errorMessage, logMessage, resourceIdentifier.ToString(), errors, methodName);
        }

19 Source : Do.cs
with Apache License 2.0
from AndcultureCode

public static Do<T> TrySeed<TContext>(
            SeedsBase<TContext> seeds,
            Func<IResult<T>, T> workload,
            string seedName = null
        )
            where TContext : clreplaced, IContext
        {
            var d = new Do<T>(workload);

            // Default seedName to invoking method name
            if (string.IsNullOrWhiteSpace(seedName))
            {
                seedName = new StackTrace().GetFrame(1).GetMethod().Name;
            }

            try
            {
                seeds.LogStart(seedName);
                d.Result.ResultObject = workload(d.Result);
            }
            catch (Exception ex)
            {
                d.Exception = ex;

                // Add the exception to the IResult object by default
                d.Result.AddExceptionError(ex.GetType().Name, ex);
                seeds.Log(seedName, d.Result.ListErrors());
            }

            seeds.LogEnd(seedName);

            return d;
        }

19 Source : ILogger.cs
with GNU General Public License v3.0
from AndreiFedarets

private static string GenerateStack()
        {
            StringBuilder builder = new StringBuilder();
            builder.AppendLine("StackTrace:");
            StackTrace stackTrace = new StackTrace();
            StackFrame[] frames = stackTrace.GetFrames();
            for (int i = 2; i < frames.Length; i++)
            {
                StackFrame frame = frames[i];
                builder.AppendLine("     " + frame.GetMethod().GetFullName());
            }
            return builder.ToString();
        }

19 Source : LogData.cs
with MIT License
from andruzzzhka

public override string ToString ()
    {
      var header = String.Format ("{0}|{1,-5}|", _date, _level);
      var method = _caller.GetMethod ();
      var type = method.DeclaringType;
#if DEBUG
      var lineNum = _caller.GetFileLineNumber ();
      var headerAndCaller =
        String.Format ("{0}{1}.{2}:{3}|", header, type.Name, method.Name, lineNum);
#else
      var headerAndCaller = String.Format ("{0}{1}.{2}|", header, type.Name, method.Name);
#endif
      var msgs = _message.Replace ("\r\n", "\n").TrimEnd ('\n').Split ('\n');
      if (msgs.Length <= 1)
        return String.Format ("{0}{1}", headerAndCaller, _message);

      var buff = new StringBuilder (String.Format ("{0}{1}\n", headerAndCaller, msgs[0]), 64);

      var fmt = String.Format ("{{0,{0}}}{{1}}\n", header.Length);
      for (var i = 1; i < msgs.Length; i++)
        buff.AppendFormat (fmt, "", msgs[i]);

      buff.Length--;
      return buff.ToString ();
    }

19 Source : BaseTestCase.cs
with Apache License 2.0
from apache

protected string GetMethodName()
        {
            StackTrace stackTrace = new StackTrace();
            return stackTrace.GetFrame(1).GetMethod().Name;
        }

19 Source : ZipFile.Save.cs
with Apache License 2.0
from Appdynamics

public static bool WriteCentralDirectoryStructure(Stream s,
                                                          ICollection<ZipEntry> entries,
                                                          uint numSegments,
                                                          Zip64Option zip64,
                                                          String comment,
                                                          ZipContainer container)
        {
            var zss = s as ZipSegmentedStream;
            if (zss != null)
                zss.ContiguousWrite = true;

            // write to a memory stream in order to keep the
            // CDR contiguous
            Int64 aLength = 0;
            using (var ms = new MemoryStream())
            {
                foreach (ZipEntry e in entries)
                {
                    if (e.IncludedInMostRecentSave)
                    {
                        // this writes a ZipDirEntry corresponding to the ZipEntry
                        e.WriteCentralDirectoryEntry(ms);
                    }
                }
                var a = ms.ToArray();
                s.Write(a, 0, a.Length);
                aLength = a.Length;
            }


            // We need to keep track of the start and
            // Finish of the Central Directory Structure.

            // Cannot always use WriteStream.Length or Position; some streams do
            // not support these. (eg, ASP.NET Response.OutputStream) In those
            // cases we have a CountingStream.

            // Also, we cannot just set Start as s.Position bfore the write, and Finish
            // as s.Position after the write.  In a split zip, the write may actually
            // flip to the next segment.  In that case, Start will be zero.  But we
            // don't know that til after we know the size of the thing to write.  So the
            // answer is to compute the directory, then ask the ZipSegmentedStream which
            // segment that directory would fall in, it it were written.  Then, include
            // that data into the directory, and finally, write the directory to the
            // output stream.

            var output = s as CountingStream;
            long Finish = (output != null) ? output.ComputedPosition : s.Position;  // BytesWritten
            long Start = Finish - aLength;

            // need to know which segment the EOCD record starts in
            UInt32 startSegment = (zss != null)
                ? zss.CurrentSegment
                : 0;

            Int64 SizeOfCentralDirectory = Finish - Start;

            int countOfEntries = CountEntries(entries);

            bool needZip64CentralDirectory =
                zip64 == Zip64Option.Always ||
                countOfEntries >= 0xFFFF ||
                SizeOfCentralDirectory > 0xFFFFFFFF ||
                Start > 0xFFFFFFFF;

            byte[] a2 = null;

            // emit ZIP64 extensions as required
            if (needZip64CentralDirectory)
            {
                if (zip64 == Zip64Option.Never)
                {
#if NETCF || Core
                    throw new ZipException("The archive requires a ZIP64 Central Directory. Consider enabling ZIP64 extensions.");
#else
                    System.Diagnostics.StackFrame sf = new System.Diagnostics.StackFrame(1);
                    if (sf.GetMethod().DeclaringType == typeof(ZipFile))
                        throw new ZipException("The archive requires a ZIP64 Central Directory. Consider setting the ZipFile.UseZip64WhenSaving property.");
                    else
                        throw new ZipException("The archive requires a ZIP64 Central Directory. Consider setting the ZipOutputStream.EnableZip64 property.");
#endif

                }

                var a = GenZip64EndOfCentralDirectory(Start, Finish, countOfEntries, numSegments);
                a2 = GenCentralDirectoryFooter(Start, Finish, zip64, countOfEntries, comment, container);
                if (startSegment != 0)
                {
                    UInt32 thisSegment = zss.ComputeSegment(a.Length + a2.Length);
                    int i = 16;
                    // number of this disk
                    Array.Copy(BitConverter.GetBytes(thisSegment), 0, a, i, 4);
                    i += 4;
                    // number of the disk with the start of the central directory
                    //Array.Copy(BitConverter.GetBytes(startSegment), 0, a, i, 4);
                    Array.Copy(BitConverter.GetBytes(thisSegment), 0, a, i, 4);

                    i = 60;
                    // offset 60
                    // number of the disk with the start of the zip64 eocd
                    Array.Copy(BitConverter.GetBytes(thisSegment), 0, a, i, 4);
                    i += 4;
                    i += 8;

                    // offset 72
                    // total number of disks
                    Array.Copy(BitConverter.GetBytes(thisSegment), 0, a, i, 4);
                }
                s.Write(a, 0, a.Length);
            }
            else
                a2 = GenCentralDirectoryFooter(Start, Finish, zip64, countOfEntries, comment, container);


            // now, the regular footer
            if (startSegment != 0)
            {
                // The replacedumption is the central directory is never split across
                // segment boundaries.

                UInt16 thisSegment = (UInt16) zss.ComputeSegment(a2.Length);
                int i = 4;
                // number of this disk
                Array.Copy(BitConverter.GetBytes(thisSegment), 0, a2, i, 2);
                i += 2;
                // number of the disk with the start of the central directory
                //Array.Copy(BitConverter.GetBytes((UInt16)startSegment), 0, a2, i, 2);
                Array.Copy(BitConverter.GetBytes(thisSegment), 0, a2, i, 2);
                i += 2;
            }

            s.Write(a2, 0, a2.Length);

            // reset the contiguous write property if necessary
            if (zss != null)
                zss.ContiguousWrite = false;

            return needZip64CentralDirectory;
        }

19 Source : ModelBuilderExtensions.cs
with MIT License
from ardalis

public static void ApplyAllConfigurationsFromCurrentreplacedembly(this ModelBuilder modelBuilder, replacedembly replacedembly = null, string configNamespace = "")
        {
            var applyGenericMethods = typeof(ModelBuilder).GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy);
            var applyGenericApplyConfigurationMethods = applyGenericMethods.Where(m => m.IsGenericMethod && m.Name.Equals("ApplyConfiguration", StringComparison.OrdinalIgnoreCase));
            var applyGenericMethod = applyGenericApplyConfigurationMethods.Where(m => m.GetParameters().FirstOrDefault().ParameterType.Name == "IEnreplacedyTypeConfiguration`1").FirstOrDefault();

            var callingreplacedembly = new StackFrame(1).GetMethod().DeclaringType.replacedembly;
            var replacedemblyToUse = replacedembly ?? callingreplacedembly;
            var applicableTypes = replacedemblyToUse
                .GetTypes()
                .Where(c => c.IsClreplaced && !c.IsAbstract && !c.ContainsGenericParameters);

            if (!string.IsNullOrEmpty(configNamespace))
            {
                applicableTypes = applicableTypes.Where(c => c.Namespace == configNamespace);
            }

            foreach (var type in applicableTypes)
            {
                foreach (var iface in type.GetInterfaces())
                {
                    // if type implements interface IEnreplacedyTypeConfiguration<SomeEnreplacedy>
                    if (iface.IsConstructedGenericType && iface.GetGenericTypeDefinition() == typeof(IEnreplacedyTypeConfiguration<>))
                    {
                        // make concrete ApplyConfiguration<SomeEnreplacedy> method
                        var applyConcreteMethod = applyGenericMethod.MakeGenericMethod(iface.GenericTypeArguments[0]);
                        // and invoke that with fresh instance of your configuration type
                        applyConcreteMethod.Invoke(modelBuilder, new object[] { Activator.CreateInstance(type) });
                        Console.WriteLine("applied model " + type.Name);
                        break;
                    }
                }
            }
        }

19 Source : UnityDebugViewerLogger.cs
with Apache License 2.0
from AsanCai

[IgnoreStackTrace]
        private static List<StackFrame> ParseSystemStackTrace(ref string extraInfo)
        {
            List<StackFrame> stackFrameList = new List<StackFrame>();

            StackTrace stackTrace = new StackTrace(true);
            StackFrame[] stackFrames = stackTrace.GetFrames();

            for (int i = 0; i < stackFrames.Length; i++)
            {
                StackFrame stackFrame = stackFrames[i];
                var method = stackFrame.GetMethod();

                if (!method.IsDefined(typeof(IgnoreStackTrace), true))
                {
                    /// ignore all the stack message generated by Unity internal method
                    if (method.Name.Equals("InternalInvoke"))
                    {
                        break;
                    }

                    stackFrameList.Add(stackFrame);
                }
                else
                {
                    foreach (object attributes in method.GetCustomAttributes(false))
                    {
                        IgnoreStackTrace ignoreAttr = (IgnoreStackTrace)attributes;
                        /// check and display corresponding method as extraInfo
                        if (ignoreAttr != null && ignoreAttr.showAsExtraInfo)
                        {
                            string methodParam = string.Empty;
                            var paramArray = method.GetParameters();
                            if (paramArray != null)
                            {
                                string[] paramType = new string[paramArray.Length];
                                for (int index = 0; index < paramArray.Length; index++)
                                {
                                    paramType[index] = paramArray[index].ParameterType.Name;
                                }
                                methodParam = string.Join(", ", paramType);
                            }

                            extraInfo = string.Format("{0}:{1}({2})", method.DeclaringType.FullName, method.Name, methodParam);
                        }
                    }
                }
            }

            return stackFrameList;
        }

19 Source : Program.cs
with MIT License
from askguanyu

public static string GetStackFrameInfo(int skipFrames)
        {
            StackFrame stackFrame = new StackFrame(skipFrames < 1 ? 1 : skipFrames + 1, true);

            MethodBase method = stackFrame.GetMethod();

            if (method != null)
            {
                StringBuilder result = new StringBuilder();

                result.Append(method.Name);

                if (method is MethodInfo && ((MethodInfo)method).IsGenericMethod)
                {
                    Type[] genericArguments = ((MethodInfo)method).GetGenericArguments();

                    result.Append("<");

                    int i = 0;

                    bool flag = true;

                    while (i < genericArguments.Length)
                    {
                        if (!flag)
                        {
                            result.Append(",");
                        }
                        else
                        {
                            flag = false;
                        }

                        result.Append(genericArguments[i].Name);

                        i++;
                    }

                    result.Append(">");
                }

                result.Append(" in ");
                result.Append(Path.GetFileName(stackFrame.GetFileName()) ?? "<unknown>");
                result.Append(":");
                result.Append(stackFrame.GetFileLineNumber());

                return result.ToString();
            }
            else
            {
                return "<null>";
            }
        }

19 Source : AsposeGisConversion.cs
with MIT License
from aspose-gis

private Response ProcessTask(string fileName, string folderName, string outFileExtension, bool createZip, bool checkNumberofPages, ActionDelegate action)
		{
			Aspose.GIS.Live.Demos.UI.Models.License.SetAsposeGisLicense();
			return  Process(this.GetType().Name, fileName, folderName, outFileExtension, createZip, checkNumberofPages,  (new StackTrace()).GetFrame(5).GetMethod().Name, action);

		}

19 Source : AsposePdfWatermark.cs
with MIT License
from aspose-pdf

private Response ProcessTask(string fileName, string folderName, string outFileExtension, bool createZip,  bool checkNumberofPages, ActionDelegate action)
		{
			License.SetAsposePdfLicense();
			return  Process(this.GetType().Name, fileName, folderName, outFileExtension, createZip, checkNumberofPages, (new StackTrace()).GetFrame(5).GetMethod().Name, action);
		}

19 Source : CallerEnricher.cs
with GNU General Public License v3.0
from atomex-me

public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
        {
            var skip = 3;

            while (true)
            {
                var stack = new StackFrame(skip);
                if (!stack.HasMethod()) {
                    logEvent.AddPropertyIfAbsent(new LogEventProperty(CallerPropertyName, new ScalarValue("<unknown method>")));
                    logEvent.AddPropertyIfAbsent(new LogEventProperty(ClreplacedPropertyName, new ScalarValue("<unknown clreplaced>")));
                    return;
                }

                var method = stack.GetMethod();
                if (method.DeclaringType != null && method.DeclaringType.replacedembly != typeof(Log).replacedembly)
                {
                    var methodName = method.Name;
                    var clreplacedName = method.DeclaringType.FullName;

                    var shortClreplacedName = method.DeclaringType.DeclaringType != null
                        ? method.DeclaringType.DeclaringType.Name
                        : method.DeclaringType.Name;
                    
                    var caller = $"{clreplacedName}.{methodName}";

                    logEvent.AddPropertyIfAbsent(new LogEventProperty(CallerPropertyName, new ScalarValue(caller)));
                    logEvent.AddPropertyIfAbsent(new LogEventProperty(ClreplacedPropertyName, new ScalarValue(shortClreplacedName)));
                    return;
                }

                skip++;
            }
        }

19 Source : PageSettings.cs
with Microsoft Public License
from atrenton

protected bool SetField<T>(ref T field, T value,
           [CallerMemberName] string propertyName = "")
        {
            if (EqualityComparer<T>.Default.Equals(field, value)) return false;

            // Check if object is being deserialized
            var callingMethod = new StackTrace().GetFrame(2).GetMethod();
            if (callingMethod.Module.Name == "<In Memory Module>")
            {
                field = value;
                return false;
            }

            DisplayStateChange(field, value, propertyName);
            field = value;
            return (_modified = true);
        }

19 Source : DefaultOutputWriter.cs
with Microsoft Public License
from atrenton

protected internal MethodBase GetDefaultMethodBase()
        {
#if DEBUG
            return new StackFrame(3, false).GetMethod();
#else
            return new StackFrame(2, false).GetMethod();
#endif
        }

19 Source : TraceOutputWriter.cs
with Microsoft Public License
from atrenton

protected internal MethodBase GetTraceMethodBase()
        {
#if DEBUG
            return new StackFrame(4, false).GetMethod();
#else
            return new StackFrame(3, false).GetMethod();
#endif
        }

19 Source : BugReportingContextService.cs
with Apache License 2.0
from AutomateThePlanet

public void AddMethodreplacedtep(params string[] parameters)
        {
            var stackTrace = new StackTrace();
            var methodInfo = stackTrace.GetFrame(1).GetMethod() as MethodInfo;
            var description = MethodToSentence(methodInfo.Name);
            if (parameters.Any())
            {
                description += " using data: " + parameters.Stringify();
            }

            Context.Value.TestSteps.Add(new TestStep(description));
        }

19 Source : BaseBenchmark.cs
with Apache License 2.0
from AutomateThePlanet

public void CoreIterationSetup()
        {
            if (_thrownException?.Value != null)
            {
                _thrownException.Value = null;
            }

            var stackTrace = new StackTrace();
            var benchmarkMethodMemberInfo = stackTrace.GetFrame(1).GetMethod() as MethodInfo;
            var benchmarkClreplacedType = benchmarkMethodMemberInfo?.DeclaringType;
            var categories = _categories;
            var authors = _authors;
            var descriptions = _descriptions;
            try
            {
                _currentBenchmarkExecutionProvider.PreTestInit(benchmarkMethodMemberInfo?.Name, benchmarkMethodMemberInfo, benchmarkClreplacedType, new List<object>(), categories, authors, descriptions);
                IterationInitialize();
                _currentBenchmarkExecutionProvider.PostTestInit(benchmarkMethodMemberInfo?.Name, benchmarkMethodMemberInfo, benchmarkClreplacedType, new List<object>(), categories, authors, descriptions);
            }
            catch (Exception ex)
            {
                _currentBenchmarkExecutionProvider.TestInitFailed(ex, benchmarkMethodMemberInfo?.Name, benchmarkMethodMemberInfo, benchmarkClreplacedType, new List<object>(), categories, authors, descriptions);
                throw;
            }
        }

19 Source : BaseBenchmark.cs
with Apache License 2.0
from AutomateThePlanet

public void CoreIterationCleanup()
        {
            var exceptionStackTrace = _thrownException?.Value?.ToString();
            var stackTrace = new StackTrace();
            var benchmarkMethodMemberInfo = stackTrace.GetFrame(1).GetMethod() as MethodInfo;
            var benchmarkClreplacedType = benchmarkMethodMemberInfo?.DeclaringType;

            try
            {
                _currentBenchmarkExecutionProvider.PreTestCleanup(TestOutcome.Preplaceded, benchmarkMethodMemberInfo?.Name, benchmarkMethodMemberInfo, benchmarkClreplacedType, new List<object>(), _categories, _authors, _descriptions, string.Empty, exceptionStackTrace, _thrownException?.Value);
                IterationCleanup();
                _currentBenchmarkExecutionProvider.PostTestCleanup(TestOutcome.Preplaceded, benchmarkMethodMemberInfo?.Name, benchmarkMethodMemberInfo, benchmarkClreplacedType, new List<object>(), _categories, _authors, _descriptions, string.Empty, exceptionStackTrace, _thrownException?.Value);
            }
            catch (Exception ex)
            {
                _currentBenchmarkExecutionProvider.TestCleanupFailed(ex, benchmarkMethodMemberInfo?.Name, benchmarkMethodMemberInfo, benchmarkClreplacedType, new List<object>(), _categories, _authors, _descriptions);
                throw;
            }
        }

19 Source : BaseBenchmark.cs
with Apache License 2.0
from AutomateThePlanet

public void CoreExecuteActArrangePhases()
        {
            try
            {
                var stackTrace = new StackTrace();
                var benchmarkMethodMemberInfo = stackTrace.GetFrame(1).GetMethod() as MethodInfo;
                var benchmarkClreplacedType = benchmarkMethodMemberInfo?.DeclaringType;

                if (!TypeForAlreadyExecutedBenchmarkInits.Contains(benchmarkClreplacedType?.FullName))
                {
                    TypeForAlreadyExecutedBenchmarkInits.Add(benchmarkClreplacedType?.FullName);
                    _currentBenchmarkExecutionProvider.PreTestsArrange(benchmarkClreplacedType, new List<object>());
                    BenchmarkArrange();
                    _currentBenchmarkExecutionProvider.PostTestsArrange(benchmarkClreplacedType);
                    _currentBenchmarkExecutionProvider.PreTestsAct(benchmarkClreplacedType, new List<object>());
                    BenchmarkAct();
                    _currentBenchmarkExecutionProvider.PostTestsAct(benchmarkClreplacedType, new List<object>());
                }
            }
            catch (Exception ex)
            {
                _currentBenchmarkExecutionProvider.TestsArrangeFailed(ex);
            }
        }

19 Source : AssemblyFacade.cs
with Apache License 2.0
from AutomateThePlanet

public List<replacedembly> GetreplacedembliesCallChain()
        {
            var trace = new StackTrace();
            var replacedemblies = new List<replacedembly>();
            var frames = trace.GetFrames();

            if (frames == null)
            {
                throw new Exception("Couldn't get the stack trace");
            }

            foreach (var frame in frames)
            {
                var method = frame.GetMethod();
                var declaringType = method.DeclaringType;

                if (declaringType == null)
                {
                    continue;
                }

                var declaringTypereplacedembly = declaringType.replacedembly;
                var lastreplacedembly = replacedemblies.LastOrDefault();

                if (declaringTypereplacedembly != lastreplacedembly)
                {
                    replacedemblies.Add(declaringTypereplacedembly);
                }
            }

            foreach (var currentreplacedembly in replacedemblies)
            {
                Debug.WriteLine(currentreplacedembly.ManifestModule.Name);
            }

            return replacedemblies;
        }

19 Source : App.cs
with Apache License 2.0
from AutomateThePlanet

private string DetermineTestClreplacedFullNameAttributes()
        {
            string fullClreplacedName = string.Empty;
            var callStackTrace = new StackTrace();
            var currentreplacedembly = GetType().replacedembly;

            foreach (var frame in callStackTrace.GetFrames())
            {
                var frameMethodInfo = frame.GetMethod() as MethodInfo;
                if (!frameMethodInfo?.ReflectedType?.replacedembly.Equals(currentreplacedembly) == true &&
                    frameMethodInfo.Name.Equals("TestsArrange") || frameMethodInfo.Name.Equals("ScenarioInitialize"))
                {
                    fullClreplacedName = frameMethodInfo.DeclaringType.FullName;
                    break;
                }
            }

            return fullClreplacedName;
        }

19 Source : ComponentsRepository.cs
with Apache License 2.0
from AutomateThePlanet

private void DetermineComponentAttributes(out string elementName, out string pageName)
        {
            elementName = string.Empty;
            pageName = string.Empty;
            try
            {
                var callStackTrace = new StackTrace();
                var currentreplacedembly = GetType().replacedembly;

                foreach (var frame in callStackTrace.GetFrames())
                {
                    var frameMethodInfo = frame.GetMethod() as MethodInfo;
                    if (!frameMethodInfo?.ReflectedType?.replacedembly.Equals(currentreplacedembly) == true &&
                        !frameMethodInfo.IsStatic &&
                        frameMethodInfo.ReturnType.IsSubclreplacedOf(typeof(Component)))
                    {
                        elementName = frame.GetMethod().Name.Replace("get_", string.Empty);
                        if (frameMethodInfo.ReflectedType.IsSubclreplacedOf(typeof(DesktopPage)))
                        {
                            pageName = frameMethodInfo.ReflectedType.Name;
                        }

                        break;
                    }
                }
            }
            catch (Exception e)
            {
                e.PrintStackTrace();
            }
        }

19 Source : ComponentRepository.cs
with Apache License 2.0
from AutomateThePlanet

private void DetermineComponentAttributes<TDriver, TDriverElement>(out string elementName, out string pageName)
            where TDriver : AppiumDriver<TDriverElement>
            where TDriverElement : AppiumWebElement
        {
            elementName = string.Empty;
            pageName = string.Empty;
            var callStackTrace = new StackTrace();
            var currentreplacedembly = GetType().replacedembly;

            foreach (var frame in callStackTrace.GetFrames())
            {
                var frameMethodInfo = frame.GetMethod() as MethodInfo;
                if (!frameMethodInfo?.ReflectedType?.replacedembly.Equals(currentreplacedembly) == true &&
                    !frameMethodInfo.IsStatic &&
                    frameMethodInfo.ReturnType.IsSubclreplacedOf(typeof(Component<TDriver, TDriverElement>)))
                {
                    elementName = frame.GetMethod().Name.Replace("get_", string.Empty);
                    if (frameMethodInfo.ReflectedType.IsSubclreplacedOf(typeof(MobilePage)))
                    {
                        pageName = frameMethodInfo.ReflectedType.Name;
                    }

                    break;
                }
            }
        }

19 Source : ComponentRepository.cs
with Apache License 2.0
from AutomateThePlanet

private void DetermineComponentAttributes(out string elementName, out string pageName)
        {
            elementName = string.Empty;
            pageName = string.Empty;
            try
            {
                var callStackTrace = new StackTrace();
                var currentreplacedembly = GetType().replacedembly;

                foreach (var frame in callStackTrace.GetFrames())
                {
                    var frameMethodInfo = frame.GetMethod() as MethodInfo;
                    if (!frameMethodInfo?.ReflectedType?.replacedembly.Equals(currentreplacedembly) == true &&
                        !frameMethodInfo.IsStatic &&
                        frameMethodInfo.ReturnType.IsSubclreplacedOf(typeof(Component)))
                    {
                        elementName = frame.GetMethod().Name.Replace("get_", string.Empty);
                        if (frameMethodInfo.ReflectedType.IsSubclreplacedOf(typeof(Page)))
                        {
                            pageName = frameMethodInfo.ReflectedType.Name;
                        }

                        break;
                    }
                }
            }
            catch (Exception e)
            {
                e.PrintStackTrace();
            }
        }

19 Source : App.cs
with Apache License 2.0
from AutomateThePlanet

private string DetermineTestClreplacedFullNameAttributes()
        {
            string fullClreplacedName = string.Empty;
            var callStackTrace = new StackTrace();
            var currentreplacedembly = GetType().replacedembly;

            foreach (var frame in callStackTrace.GetFrames())
            {
                var frameMethodInfo = frame.GetMethod() as MethodInfo;
                if (!frameMethodInfo?.ReflectedType?.replacedembly.Equals(currentreplacedembly) == true &&
                    (frameMethodInfo.Name.Equals("TestsArrange") || frameMethodInfo.Name.Equals("ScenarioInitialize")))
                {
                    fullClreplacedName = frameMethodInfo.DeclaringType.FullName;
                    break;
                }
            }

            return fullClreplacedName;
        }

19 Source : DynamicTestCasesService.cs
with Apache License 2.0
from AutomateThePlanet

public void AddMethodreplacedtep(params string[] parameters)
        {
            var stackTrace = new StackTrace();
            var methodInfo = stackTrace.GetFrame(1).GetMethod() as MethodInfo;
            string description = MethodToSentence(methodInfo.Name);
            if (parameters.Any())
            {
                description += " using data: " + parameters.Stringify();
            }

            Context.Value.TestSteps.Add(new TestStep(description));
        }

See More Examples