Пример #1
0
        public static string CaptureCodeLocation(this StackTrace source, int indentationLevel = 0)
        {
            var frame = source?.GetFrames()?.First();

            return((frame != null
                ? $"FileName: {frame.GetFileName()}\tClass Name: {frame.GetMethod()?.DeclaringType?.FullName}\tMethod Name: {frame.GetMethod().Name}\tLine Number: {frame.GetFileLineNumber()}"
                : "Location unknown").Indent(indentLevel: indentationLevel));
        }
Пример #2
0
    public static void Main()
    {
        StackTrace stackTrace = new StackTrace();           // get call stack
        StackFrame[] stackFrames = stackTrace.GetFrames();  // get method calls (frames)

        // write call stack method names
        foreach (StackFrame stackFrame in stackFrames)
        {
          Console.WriteLine(stackFrame.GetMethod().Name);   // write method name
        }
    }
Пример #3
0
        public ExceptionInfo(Exception exception, bool isNestedException = false)
        {
            if (exception == null)
            {
                throw new ArgumentNullException(nameof(exception));
            }

            ErrorType    = exception.GetType().Name;
            ErrorMessage = exception.Message;

            if (!string.IsNullOrEmpty(exception.StackTrace))
            {
                StackTrace stackTrace = new StackTrace(exception, true);
                StackTrace = stackTrace.ToString();

                // Only extract the stack frames like this for the top-level exception
                // This is used for Xray Exception serialization
                if (isNestedException || stackTrace?.GetFrames() == null)
                {
                    StackFrames = new StackFrameInfo[0];
                }
                else
                {
                    StackFrames = (
                        from sf in stackTrace.GetFrames()
                        where sf != null
                        select new StackFrameInfo(sf)
                        ).ToArray();
                }
            }

            if (exception.InnerException != null)
            {
                InnerException = new ExceptionInfo(exception.InnerException, true);
            }

            AggregateException aggregateException = exception as AggregateException;

            if (aggregateException != null && aggregateException.InnerExceptions != null)
            {
                foreach (var innerEx in aggregateException.InnerExceptions)
                {
                    InnerExceptions.Add(new ExceptionInfo(innerEx, true));
                }
            }
        }
Пример #4
0
    private void InserirErro(Exception e)
    {
        string sDiretorio = ConfigurationSettings.AppSettings["LogDirectory"].ToString();

        if (!Directory.Exists(@sDiretorio))
            Directory.CreateDirectory(@sDiretorio);

        StackTrace stacktrace = new StackTrace();
        StackFrame[] stackframes = stacktrace.GetFrames();

        string Classe = stacktrace.GetFrame(1).GetMethod().ReflectedType.Name;
        string Metodo = stacktrace.GetFrame(1).GetMethod().Name;

        StreamWriter oSw = File.AppendText(@sDiretorio + "\\" + DateTime.Now.ToString("yyyyMMdd") + ".txt");
        oSw.WriteLine(DateTime.Now.ToString("dd-MM-yyyy HH:mm.ss") + " > Class{ " + Classe + " } : Listar{ " + Metodo + " } - Message{ " + e.Message + " }");
        oSw.Flush();
        oSw.Close();
        oSw = null;
    }
Пример #5
0
        public static string DescInfo(this StackTrace stackTrace)
        {
            var sb  = new StringBuilder();
            var sfs = stackTrace?.GetFrames();

            if (sfs != null)
            {
                foreach (var sf in sfs)
                {
                    var method   = (MethodInfo)sf.GetMethod();
                    var fileName = sf.GetFileName();
                    if (string.IsNullOrWhiteSpace(fileName))
                    {
                        sb.AppendFormat("{0}{1}", method.DescInfo(), Environment.NewLine);
                    }
                    else
                    {
                        sb.AppendFormat("{0} in file:line:column {1}:{2}:{3}{4}", method.DescInfo(), sf.GetFileName(), sf.GetFileLineNumber(), sf.GetFileColumnNumber(), Environment.NewLine);
                    }
                }
            }
            return(sb.ToString().TrimEnd(Environment.NewLine.ToArray()));
        }
Пример #6
0
        public Section(string name, int iColCt, SystemObject sys, object caller)
        {
            Name        = name;
            ColumnCount = iColCt;
            _controls   = new Dictionary <string, object>();
            Sys         = sys;
            string myClass = caller.GetType().ToString();

            StackTrace stackTrace = new StackTrace();

            StackFrame[] stackFrames  = stackTrace.GetFrames();
            StackFrame   callingFrame = stackFrames[1];
            MethodInfo   method       = (MethodInfo)callingFrame.GetMethod();

            if (method.Name == "RenderSection")
            {
                callingFrame = stackFrames[2];
                method       = (MethodInfo)callingFrame.GetMethod();
            }
            string sMyMethod = method.Name;

            sys.ActiveSection = name;
            Expanded          = Sys.GetObjectValue(Name, "ExpandableSection" + myClass + sMyMethod) == "UNEXPANDED" ? false : true;
        }
Пример #7
0
        public static string LogExceptionMessage(Exception Ex, string MESSAGEST, bool ImportantLogFlag = true)
        {
            StackTrace st = new StackTrace(Ex, true);

            StackFrame[] frames  = st.GetFrames();
            string       messstr = "";

            // Iterate over the frames extracting the information you need
            foreach (StackFrame frame in frames)
            {
                messstr += String.Format("{0}:{1}({2},{3})", frame.GetFileName(), frame.GetMethod().Name, frame.GetFileLineNumber(), frame.GetFileColumnNumber());
            }

            string FullMessage = MESSAGEST + Environment.NewLine;

            FullMessage += Environment.NewLine + Environment.NewLine + "Debug information:" + Environment.NewLine + "Exception source: " + Ex.Data + " " + Ex.Message
                           + Environment.NewLine + Environment.NewLine + messstr;
            //MessageBox.Show(this, FullMessage, "Invalid value", MessageBoxButtons.OK);

            Logging.AddLog(MESSAGEST + ", exception: " + Ex.Message, (ImportantLogFlag ? LogLevel.Important : LogLevel.Debug), Highlight.Error);
            Logging.AddLog(FullMessage, LogLevel.Debug, Highlight.Error);

            return(FullMessage);
        }
Пример #8
0
        protected static string CreateStackTrace(string str)
        {
            StringBuilder stringBuilder = new StringBuilder();

            stringBuilder.Append(str);
            stringBuilder.Append("\n");
            StackTrace stackTrace = new StackTrace(true);

            StackFrame[] frames = stackTrace.GetFrames();
            for (int i = 0; i < frames.Length; i++)
            {
                stringBuilder.Append(string.Concat(new object[]
                {
                    frames[i].GetFileName(),
                    "__",
                    frames[i].GetFileLineNumber(),
                    "__",
                    frames[i].GetMethod().get_Name(),
                    "\n"
                }));
            }
            stringBuilder.Append("=========================================");
            return(stringBuilder.ToString());
        }
Пример #9
0
        public static void NotNull <T>(Expression <Func <T> > parameter)
        {
            var memberExpression = parameter.Body as MemberExpression;

            if (memberExpression == null)
            {
                throw new ApplicationException("Can only use a member expression with Argument.NotNull.");
            }

            var value = parameter.Compile().Invoke();

            if (value == null)
            {
                var parameterName = memberExpression.Member.Name;
                var stackTrace    = new StackTrace(true);
                var stackFrames   = stackTrace.GetFrames();
                var msg           = "Parameter type: " + memberExpression.Type.Name + ", Function: " + stackFrames[1].GetMethod().Name;
                //if (Debugger.IsAttached)
                //{
                //    Debugger.Break();
                //}
                throw new ArgumentNullException(parameterName, msg);
            }
        }
        public static void BlockingMethodCalled(this ILogger logger, StackTrace stackTrace)
        {
            var frames = stackTrace?.GetFrames();
            //Whitelist Selz Code as recommended - many core packages use valid locking
            //https://github.com/benaadams/Ben.BlockingDetector/issues/5
            bool?isInternalCode = false;

            if (frames != null)
            {
                foreach (var frame in frames)
                {
                    if (AssemblyWhiteList.Any(wl => frame.GetMethod().ToString().Contains(wl)))
                    {
                        isInternalCode = true;
                        break;
                    }
                }
            }

            if (isInternalCode.Value)
            {
                _blockingMethodCalled(logger, stackTrace, null);
            }
        }
Пример #11
0
        public static void ArrayIndex(Expression <Func <int> > parameter)
        {
            var memberExpression = parameter.Body as MemberExpression;

            if (memberExpression == null)
            {
                throw new ApplicationException("Can only use a member expression with Argument.ArrayIndex.");
            }

            if (memberExpression.Type != typeof(int))
            {
                throw new ApplicationException("ArrayIndex can only be used with int arguments, type was " + memberExpression.Type.Name);
            }

            var value = parameter.Compile().Invoke();

            if (value < 0)
            {
                var parameterName = memberExpression.Member.Name;
                var stackTrace    = new StackTrace(true);
                var stackFrames   = stackTrace.GetFrames();
                throw new ArgumentException("Negative array index is invalid. Function: " + stackFrames[1].GetMethod().Name, parameterName);
            }
        }
Пример #12
0
        private static void Write(string logType, string strLog, bool isHour = false)
        {
            var logStr = new StringBuilder(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff | "));

            try
            {
                var trace  = new StackTrace();
                var frames = trace.GetFrames().Reverse().ToList();
                frames = frames.Skip(frames.FindLastIndex(a => a.GetMethod().ReflectedType.FullName.StartsWith("System.")) + 1).ToList();
                foreach (var frame in frames)
                {
                    var method = frame.GetMethod();
                    if (method.ReflectedType.FullName.StartsWith("Utility."))
                    {
                        continue;
                    }
                    logStr.Append(method.ReflectedType.FullName).Append(".").Append(method.Name).Append(" -> ");
                }
            }
            catch
            {
            }

            var    logDirectory = AppDomain.CurrentDomain.BaseDirectory + @"\App_Log\" + logType + @"\";
            string logFile;

            if (isHour)
            {
                logFile = logDirectory + DateTime.Now.ToString("yyyy-MM-dd-HH") + ".log";
            }
            else
            {
                logFile = logDirectory + DateTime.Now.ToString("yyyy-MM-dd") + ".log";
            }

            Mutex mutexFile = null;

            try
            {
                mutexFile = new Mutex(false, logFile);
                mutexFile.WaitOne();
            }
            catch
            {
            }

            try
            {
                if (strLog != null)
                {
                    logStr.Append(strLog);
                }
                if (!Directory.Exists(logDirectory))
                {
                    Directory.CreateDirectory(logDirectory);
                }
                using (var fs = new FileStream(logFile, FileMode.Append, FileAccess.Write))
                {
                    using (var writer = new StreamWriter(fs, Encoding.UTF8))
                    {
                        writer.WriteLine(logStr.ToString());
                    }
                }
            }
            catch
            {
            }

            if (mutexFile != null)
            {
                try
                {
                    mutexFile.ReleaseMutex();
                    mutexFile.Close();
                }
                catch
                {
                }
            }
        }
Пример #13
0
    /// <summary>
    /// _s the get method stack trace.
    /// </summary>
    /// <returns>
    /// The get method stack trace.
    /// </returns>
    /// <param name='aMessage_string'>
    /// A message_string.
    /// </param>
    private static string _GetMethodStackTrace(string aMessage_string)
    {
        StackTrace stackTrace = new StackTrace();
        StackFrame[] stackFrames = stackTrace.GetFrames();
        string output_string = "";
        output_string += aMessage_string;
        string spaces_string = "  ";
        StackFrame stackFrame;
        for (int count_int = 2 ; count_int < stackFrames.Length; count_int ++ ) {

            stackFrame = stackFrames[count_int];
            output_string += "\n" + (spaces_string + stackFrame.GetMethod());
            spaces_string += "  ";
        }
        return output_string;
    }
 public static StackFrame GetFrame(this StackTrace strackTrace, int number)
 {
     return(strackTrace.GetFrames()[number]);
 }
Пример #15
0
        public void subir()
        {
            if (GvSubir.Rows.Count < 1)
            {
                String mensajeScriptnm = @"<script type='text/javascript'>
                swal({
                title: ""Seleccione  Txt"",
                icon: ""warning"",
                dangerMode: false,
                })
                </script>";
                ScriptManager.RegisterStartupScript(this, typeof(Page), "mensaje", mensajeScriptnm, false);
                FileUpload1.Focus();
                return;
            }

            Int32  IdUsuario = Convert.ToInt32(Request.Cookies["WebNestle"]["DLIdUsuario"]);
            String Msj       = "";

            try {
                foreach (GridViewRow row in GvSubir.Rows)
                {
                    Msj = obj.SubirPedidoSugeridoCliente(row.Cells[0].Text.ToString(), Convert.ToDouble(row.Cells[1].Text.ToString()), IdUsuario);
                }
            }
            catch (Exception ex)
            {
                StackTrace st    = new StackTrace(ex, true);
                StackFrame frame = st.GetFrames().Where(f => !String.IsNullOrEmpty(f.GetFileName()) &&
                                                        f.GetILOffset() != StackFrame.OFFSET_UNKNOWN &&
                                                        f.GetNativeOffset() != StackFrame.OFFSET_UNKNOWN &&
                                                        !f.GetMethod().Module.Assembly.GetName().Name.Contains("mscorlib")).First();

                string        MachineName = System.Environment.MachineName;
                string        UserName    = System.Environment.UserName.ToUpper();
                string        Mensaje     = ex.Message;
                StringBuilder builder     = new StringBuilder(Mensaje);
                builder.Replace("'", "");
                int    LineaError     = frame.GetFileLineNumber();
                string Proyecto       = frame.GetMethod().Module.Assembly.GetName().Name;
                string Clase          = frame.GetMethod().DeclaringType.Name;
                string metodo         = frame.GetMethod().Name;
                String M              = "Formato Incorrecto";
                string menssajeScript = "<script type='text/javascript'>"
                                        + " swal({" +

                                        "title: '" + M.ToString() + "'," +
                                        " icon: 'warning'," +
                                        "  dangerMode: false," +
                                        "   })  </script>";
                ScriptManager.RegisterStartupScript(this, typeof(Page), "mensaje", menssajeScript, false);
                return;
            }
            if (Msj != "")
            {
                string menssajeScript = "<script type='text/javascript'>"
                                        + " swal({" +

                                        "title: '" + Msj + "'," +
                                        " icon: 'success'," +
                                        "  dangerMode: false," +
                                        "   })  </script>";
                ScriptManager.RegisterStartupScript(this, typeof(Page), "mensaje", menssajeScript, false);
                PanelListar.Visible = true;
                PanelSubir.Visible  = false;
                ListarClienteSugerido();
                LblTotal.Text = "";
            }
            else
            {
                string menssajeScript = "<script type='text/javascript'>"
                                        + " swal({" +

                                        "title: 'ocurrio un error'," +
                                        " icon: 'warning'," +
                                        "  dangerMode: true," +
                                        "   })  </script>";
                ScriptManager.RegisterStartupScript(this, typeof(Page), "mensaje", menssajeScript, false);
            }
            DataTable dt = new DataTable();

            GvSubir.DataSource = dt;
            GvSubir.DataBind();
            ListarClienteSugerido();
        }
Пример #16
0
            /// <summary>
            /// Commands the executing.
            /// </summary>
            /// <param name="command">The command.</param>
            /// <param name="interceptionContext">The interception context.</param>
            /// <param name="userState">State of the user.</param>
            /// <inheritdoc />
            private void CommandExecuting(DbCommand command, DbCommandInterceptionContext interceptionContext, out object userState)
            {
                userState = null;
                if (!interceptionContext.DbContexts.Any(a => this.DbContextList.Contains(a) || this.EnableForAllDbContexts))
                {
                    return;
                }

                DebugHelper._callCounts++;

                StringBuilder sbDebug = new StringBuilder();

                sbDebug.AppendLine("\n");

                StackTrace st     = new StackTrace(2, true);
                var        frames = st.GetFrames().Where(a => a.GetFileName() != null);

                sbDebug.AppendLine(string.Format("/* Call# {0}*/", DebugHelper._callCounts));

                sbDebug.AppendLine(string.Format("/*\n{0}*/", frames.ToList().AsDelimited("")));

                sbDebug.AppendLine("BEGIN\n");

                var declares = command.Parameters.OfType <System.Data.SqlClient.SqlParameter>()
                               .Select(p =>
                {
                    if (p.SqlDbType == System.Data.SqlDbType.NVarChar)
                    {
                        var sqlString   = ( SqlString )p.SqlValue;
                        string sqlValue = sqlString.IsNull ? "null" : sqlString.Value?.Truncate(255);

                        return(string.Format("@{0} {1}({2}) = '{3}'", p.ParameterName, p.SqlDbType, p.Size, sqlValue?.Replace("'", "''")));
                    }

                    if (p.SqlDbType == System.Data.SqlDbType.Int)
                    {
                        return(string.Format("@{0} {1} = {2}", p.ParameterName, p.SqlDbType, p.SqlValue ?? "null"));
                    }
                    else if (p.SqlDbType == System.Data.SqlDbType.Udt)
                    {
                        return(string.Format("@{0} {1} = '{2}'", p.ParameterName, p.UdtTypeName, p.SqlValue));
                    }
                    else if (p.SqlDbType == System.Data.SqlDbType.Bit)
                    {
                        return(string.Format("@{0} {1} = {2}", p.ParameterName, p.SqlDbType, ((System.Data.SqlTypes.SqlBoolean)p.SqlValue).ByteValue));
                    }
                    else if (p.SqlDbType == System.Data.SqlDbType.Decimal)
                    {
                        return(string.Format("@{0} {1} = {2}", p.ParameterName, p.SqlDbType, p.SqlValue ?? "null"));
                    }
                    else
                    {
                        return(string.Format("@{0} {1} = '{2}'", p.ParameterName, p.SqlDbType, p.SqlValue));
                    }
                }).ToList().AsDelimited(",\n");

                if (!string.IsNullOrEmpty(declares))
                {
                    sbDebug.AppendLine("DECLARE\n" + declares + "\n\n");
                }

                sbDebug.AppendLine(command.CommandText);

                sbDebug.AppendLine("\nEND\nGO\n\n");

                System.Diagnostics.Debug.Write(sbDebug.ToString());

                var sqlConnection = command.Connection as System.Data.SqlClient.SqlConnection;

                sqlConnection.StatisticsEnabled = true;
                sqlConnection.ResetStatistics();

                if (userState == null)
                {
                    userState = new DebugHelperUserState {
                        CallNumber = DebugHelper._callCounts, Stopwatch = Stopwatch.StartNew()
                    };
                }
            }
Пример #17
0
        private static void FirstChanceExceptionHandler(object sender, FirstChanceExceptionEventArgs args)
        {
            if (handlerActive.Value)
            {
                return;
            }

            bool oom = args.Exception is OutOfMemoryException;

            //In case of OOM, unload the Main.tile array and do immediate garbage collection.
            //If we don't do this, there will be a big chance that this method will fail to even quit the game, due to another OOM exception being thrown.
            if (oom)
            {
                Main.tile = null;

                GC.Collect();
            }

            try {
                handlerActive.Value = true;

                if (!oom)
                {
                    if (args.Exception == previousException ||
                        args.Exception is ThreadAbortException ||
                        ignoreSources.Contains(args.Exception.Source) ||
                        ignoreMessages.Any(str => args.Exception.Message?.Contains(str) ?? false) ||
                        ignoreThrowingMethods.Any(str => args.Exception.StackTrace?.Contains(str) ?? false))
                    {
                        return;
                    }
                }

                var stackTrace = new StackTrace(true);
                PrettifyStackTraceSources(stackTrace.GetFrames());
                var traceString = stackTrace.ToString();

                if (!oom && ignoreContents.Any(traceString.Contains))
                {
                    return;
                }

                traceString = traceString.Substring(traceString.IndexOf('\n'));
                var exString = args.Exception.GetType() + ": " + args.Exception.Message + traceString;
                lock (pastExceptions) {
                    if (!pastExceptions.Add(exString))
                    {
                        return;
                    }
                }

                previousException = args.Exception;
                var msg = args.Exception.Message + " " + Language.GetTextValue("tModLoader.RuntimeErrorSeeLogsForFullTrace", Path.GetFileName(LogPath));
        #if CLIENT
                if (ModCompile.activelyModding)
                {
                    AddChatMessage(msg, Color.OrangeRed);
                }
        #else
                Console.ForegroundColor = ConsoleColor.DarkMagenta;
                Console.WriteLine(msg);
                Console.ResetColor();
        #endif
                tML.Warn(Language.GetTextValue("tModLoader.RuntimeErrorSilentlyCaughtException") + '\n' + exString);

                if (oom)
                {
                    const string error = "Game ran out of memory. You'll have to find which mod is consuming lots of memory, and contact the devs or remove it.";
                    Logging.tML.Fatal(error);
                    Interface.MessageBoxShow(error);
                    Environment.Exit(1);
                }
            }
            catch (Exception e) {
                tML.Warn("FirstChanceExceptionHandler exception", e);
            }
            finally {
                handlerActive.Value = false;
            }
        }
Пример #18
0
        protected override void Write(LogEventInfo logEvent)
        {
            var record = new Dictionary <string, object> {
                { "level", logEvent.Level.Name },
                { "message", Layout.Render(logEvent) },
                { "logger_name", logEvent.LoggerName },
                { "sequence_id", logEvent.SequenceID },
            };

            if (this.EmitStackTraceWhenAvailable && logEvent.HasStackTrace)
            {
                var        transcodedFrames = new List <Dictionary <string, object> >();
                StackTrace stackTrace       = logEvent.StackTrace;
                foreach (StackFrame frame in stackTrace.GetFrames())
                {
                    var transcodedFrame = new Dictionary <string, object>
                    {
                        { "filename", frame.GetFileName() },
                        { "line", frame.GetFileLineNumber() },
                        { "column", frame.GetFileColumnNumber() },
                        { "method", frame.GetMethod().ToString() },
                        { "il_offset", frame.GetILOffset() },
                        { "native_offset", frame.GetNativeOffset() },
                    };
                    transcodedFrames.Add(transcodedFrame);
                }
                record.Add("stacktrace", transcodedFrames);
            }
            if (this.IncludeAllProperties && logEvent.Properties.Count > 0)
            {
                foreach (var property in logEvent.Properties)
                {
                    var propertyKey = property.Key.ToString();
                    if (string.IsNullOrEmpty(propertyKey))
                    {
                        continue;
                    }

                    record[propertyKey] = SerializePropertyValue(propertyKey, property.Value);
                }
            }

            try
            {
                EnsureConnected();
            }
            catch (Exception ex)
            {
                NLog.Common.InternalLogger.Warn("Fluentd Connect - " + ex.ToString());
                throw;  // Notify NLog of failure
            }

            try
            {
                this.emitter?.Emit(logEvent.TimeStamp, this.Tag, record);
            }
            catch (Exception ex)
            {
                NLog.Common.InternalLogger.Warn("Fluentd Emit - " + ex.ToString());
                throw;  // Notify NLog of failure
            }
        }
Пример #19
0
        // Return the source code location of the caller located callDepth frames up the stack.
        // ICU4N NOTE: In order for this to work in .NET Standard 1.x in Release mode, the
        // [MethodImpl(MethodImplOptions.NoInlining)] attribute must be added to each method/property this
        // searches for.
        protected static string SourceLocation()
        {
#if !FEATURE_STACKTRACE
            var sourceLines =
                Environment.StackTrace
                .Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).Reverse().ToList();

            using (var iter = sourceLines.GetEnumerator())
            {
                while (iter.MoveNext())
                {
                    var line = iter.Current;

                    if (line.Contains("System.Environment.GetStackTrace") || line.Contains("get_StackTrace"))
                    {
                        continue;
                    }

                    if (line.TrimStart().StartsWith("at NUnit.", StringComparison.Ordinal) || line.TrimStart().StartsWith("at Microsoft.VisualStudio", StringComparison.Ordinal) || line.Contains("Invoke"))
                    {
                        continue;
                    }

                    if (line.Contains("TestFmwk.cs") || line.Contains("AbstractTestLog.cs"))
                    {
                        continue;
                    }

                    var match = MethodNameRegex.Match(line);

                    if (match.Success)
                    {
                        var methodName = match.Groups["method"].Value;
                        if (methodName.StartsWith("Test", StringComparison.Ordinal) || methodName.StartsWith("test", StringComparison.Ordinal) || methodName.Equals("Main"))
                        {
                            var matchFileName = FileNameRegex.Match(line);
                            if (matchFileName.Success)
                            {
                                return(matchFileName.Groups["filename"].Value);
                            }

                            // If the regex fails, just return the line as is.
                            return(line);
                        }
                    }
                }
            }
#else
            // Walk up the stack to the first call site outside this file
            StackTrace trace = new StackTrace(true);
            foreach (var frame in trace.GetFrames())
            {
                string source = frame.GetFileName();
                if (source != null && !source.EndsWith("TestFmwk.cs", StringComparison.Ordinal) && !source.EndsWith("AbstractTestLog.cs", StringComparison.Ordinal))
                {
                    string methodName = frame.GetMethod().Name;
                    if (methodName != null &&
                        (methodName.StartsWith("Test", StringComparison.Ordinal) || methodName.StartsWith("test", StringComparison.Ordinal) || methodName.Equals("Main")))
                    {
                        return("(" + source + ":" + frame.GetFileLineNumber() + ") ");
                    }
                }
            }
#endif
            throw new Exception();
        }
        /// <summary>
        /// Appends the exception.
        /// </summary>
        /// <param name="title">The title.</param>
        /// <param name="ex">The ex.</param>
        /// <param name="exceptionLevel">The exception level.</param>
        public void AppendException(String title, Exception ex, Int32 exceptionLevel = 0)
        {
            lock (AppendExceptionLock)
            {
                throw new aceGeneralException("Exception: " + ex.Message, ex, this, title);

                open("Exception", title);

                if (ex == null)
                {
                    AppendLine("Exception: [null]");
                    return;
                }

                ex.describe(this, "");
                callerInfo   ci     = null;
                StackFrame[] frames = null;

                if (ex is aceGeneralException)
                {
                    aceGeneralException axe = (aceGeneralException)ex;
                    ci = axe.callInfo;
                }
                else
                {
                    StackTrace st = new StackTrace(ex, true);
                    StackFrame sf = st.GetFrame(0);
                    if (sf == null)
                    {
                        aceGeneralException axe = new aceGeneralException("WrapperException for " + ex.GetType().Name, ex, this, title);
                        ci = axe.callInfo;
                    }
                    else
                    {
                        ci = callerInfo.getCallerInfo(sf, true);
                    }

                    frames = st.GetFrames();
                }

                if (exceptionLevel == 0)
                {
                    AppendTable(ci.AppendDataFields());
                }

                AppendTable(ci.AppendDataFieldsOfMethod());

                open("parents", "Parent StackFrames");

                List <String> sfi_strings = new List <string>();
                Int32         c           = 0;
                if (frames != null)
                {
                    foreach (StackFrame sfi in frames)
                    {
                        if (c != 0)
                        {
                            open("frame", "StackFrame(" + c.ToString() + ")");

                            callerInfo sfi_ci = callerInfo.getCallerInfo(sfi, true);

                            AppendTable(sfi_ci.AppendDataFieldsOfMethod());
                            close();
                        }
                        c++;

                        //sfi.GetFileLineNumb
                    }
                }
                close();

                if (ex.InnerException != null)
                {
                    AppendException("InnerException [level:" + exceptionLevel + "]", ex.InnerException, exceptionLevel + 1);
                }

                close();
            }
        }
Пример #21
0
        private void AddToTraceResult(Stopwatch watch)
        {
            int CurrentThreadID = Thread.CurrentThread.ManagedThreadId;
            int TraceResultThreadIndex;

            lock (_locker)
            {
                TraceResultThreadIndex = GetTraceResultThreadIndex(CurrentThreadID);
                if (TraceResultThreadIndex == -1)
                {
                    _result.Add(new ThreadItem(CurrentThreadID));
                    TraceResultThreadIndex = _result.Count - 1;
                }
            }

            StackTrace st   = new StackTrace();
            StackFrame sf   = st.GetFrame(2);
            var        item = new MethodItem()
            {
                MethodName          = sf.GetMethod().Name,
                MethodClassName     = sf.GetMethod().DeclaringType.Name,
                ElapsedMilliseconds = 0,
                SubMethods          = null,
            };

            lock (_locker)
            {
                if (_stacks.ContainsKey(CurrentThreadID))
                {
                    _stacks[CurrentThreadID].TraceWatches.Push((watch, item));
                }
                else
                {
                    var stack = new ThreadStack();
                    stack.TraceWatches.Push((watch, item));
                    _stacks.Add(CurrentThreadID, stack);
                }

                InsertIntoTree((_result[TraceResultThreadIndex] as ThreadItem).SubMethods, item, st.GetFrames());
            }
        }
    /// <summary>
    /// _s the get method stack trace.
    /// </summary>
    /// <returns>
    /// The get method stack trace.
    /// </returns>
    /// <param name='aMessage_string'>
    /// A message_string.
    /// </param>
    private static string _GetMethodStackTrace(string aMessage_string)
    {
        StackTrace stackTrace = new StackTrace();
        StackFrame[] stackFrames = stackTrace.GetFrames();
        string output_string = "";
        output_string += aMessage_string;
        string spaces_string = "  ";
        StackFrame stackFrame;

        //WE don't show'Debug.LogStackTrace()' in result by controlling 'for' loop
        for (int count_int = stackFrames.Length -1 ; count_int > 1; count_int -- ) {

            stackFrame = stackFrames[count_int];
            output_string += "\n" + (spaces_string + stackFrame.GetMethod().DeclaringType.Name + "." + stackFrame.GetMethod().Name + "()");
            spaces_string += "     ";
        }
        return output_string;
    }
Пример #23
0
    public Promise()
    {
        Fulfilled = false;
        var stackTrace = new StackTrace();
        var stackFrames = stackTrace.GetFrames();

        From = stackFrames.Aggregate("", (s, frame) => s + " -> " + frame.GetMethod().Name);
    }
Пример #24
0
    public void LogSessionTimeOut(Hashtable State, string page)
    {
        if (State == null)
        {
            throw new Exception("Timeout with no State or Session");
        }
        StackTrace stackTrace = new StackTrace();           // get call stack
        StackFrame[] stackFrames = stackTrace.GetFrames();  // get method calls (frames)

        // write call stack method names
        StringBuilder stack = new StringBuilder();
        bool isFirst = true;
        foreach (StackFrame stackFrame in stackFrames)
        {
            if (isFirst)
                isFirst = false;
            else
                stack.Append("<-");
            stack.Append(stackFrame.GetMethod().Name);   // write method name
        }

        StringBuilder values = new StringBuilder();
        if (State.Keys.Count > 0)
        {
            isFirst = true;
            foreach (string key in State.Keys)
            {
                if (isFirst)
                    isFirst = false;
                else
                    values.Append(", ");
                if (State[key] != null)
                    values.Append(key + "=" + State[key].ToString());
                else
                    values.Append(key + "=null");
            }
        }
        string info = "cache values: " + values.ToString();

        string trace = "timeout: " + info + "; stack: " + stack.ToString();
        UpdateSessionLog(State, trace, page);
    }
Пример #25
0
        /// <summary>
        /// Create .lnk to ClickOnce shortcut with autostart parameters
        /// </summary>
        public static void CreateAutoStartLink()
        {
            Logging.AddLog("CreateAutoStartLink enter", LogLevel.Debug);

            try
            {
                ApplicationDeployment ad = ApplicationDeployment.CurrentDeployment;

                if (ad.IsFirstRun)
                {
                    Logging.AddLog("Creating autostart link file", LogLevel.Debug);

                    Assembly assembly = Assembly.GetEntryAssembly();

                    string company               = string.Empty;
                    string description           = string.Empty;
                    string productname           = string.Empty;
                    string StartMenuShortcutName = string.Empty;

                    // Get company name
                    if (Attribute.IsDefined(assembly, typeof(AssemblyCompanyAttribute)))
                    {
                        AssemblyCompanyAttribute ascompany = (AssemblyCompanyAttribute)Attribute.GetCustomAttribute(assembly, typeof(AssemblyCompanyAttribute));
                        company = ascompany.Company;
                    }

                    // Get shortcut description
                    if (Attribute.IsDefined(assembly, typeof(AssemblyDescriptionAttribute)))
                    {
                        AssemblyDescriptionAttribute asdescription = (AssemblyDescriptionAttribute)Attribute.GetCustomAttribute(assembly, typeof(AssemblyDescriptionAttribute));
                        description = asdescription.Description;
                    }

                    // Get shortcut product name
                    if (Attribute.IsDefined(assembly, typeof(AssemblyProductAttribute)))
                    {
                        AssemblyProductAttribute asproduct = (AssemblyProductAttribute)Attribute.GetCustomAttribute(assembly, typeof(AssemblyProductAttribute));
                        productname = asproduct.Product;
                    }
                    Logging.AddLog(company + " | " + description + " | " + productname, LogLevel.Debug);

                    // Concat clickonce shortcut full path
                    if (!string.IsNullOrEmpty(company))
                    {
                        StartMenuShortcutName = string.Concat(
                            Environment.GetFolderPath(Environment.SpecialFolder.Programs),
                            "\\",
                            company,
                            "\\",
                            productname,
                            ".appref-ms");
                    }


                    //if everything is ok - create shortcut
                    if (!string.IsNullOrEmpty(StartMenuShortcutName))
                    {
                        string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
                        Utils.CreateLink(_PROGRAM_AUTOSTART_SHORTCUT_NAME, desktopPath, StartMenuShortcutName, "-start");
                    }
                    else
                    {
                        Logging.AddLog("Couldn't locate ClickOnce shortcut in start menu", LogLevel.Debug);
                    }
                }
            }
            catch (Exception ex)
            {
                StackTrace   st      = new StackTrace(ex, true);
                StackFrame[] frames  = st.GetFrames();
                string       messstr = "";

                // Iterate over the frames extracting the information you need
                foreach (StackFrame frame in frames)
                {
                    messstr += String.Format("{0}:{1}({2},{3})", frame.GetFileName(), frame.GetMethod().Name, frame.GetFileLineNumber(), frame.GetFileColumnNumber());
                }

                string FullMessage = "Error in creating Autostart link. ";
                FullMessage += "IOException source: " + ex.Data + " | " + ex.Message + " | " + messstr;

                Logging.AddLog(FullMessage, LogLevel.Important);
            }

            Logging.AddLog("CreateAutoStartLink exit", LogLevel.Trace);
        }
        public void TestDMD()
        {
            Counter = 0;

            // Run the original method.
            Assert.Equal(Tuple.Create(StringOriginal, 1), ExampleMethod(1));

            MethodInfo original = typeof(DynamicMethodDefinitionTest).GetMethod(nameof(ExampleMethod));
            MethodBase patched;

            using (DynamicMethodDefinition dmd = new DynamicMethodDefinition(original)) {
                Assert.Equal("i", dmd.Definition.Parameters[0].Name);

                // Modify the MethodDefinition.
                foreach (Instruction instr in dmd.Definition.Body.Instructions)
                {
                    if (instr.Operand as string == StringOriginal)
                    {
                        instr.Operand = StringPatched;
                    }
                    else if (instr.MatchCallOrCallvirt <DynamicMethodDefinitionTest>(nameof(ExampleMethod)))
                    {
                        instr.Operand = dmd.Definition;
                    }
                }

                // Generate a DynamicMethod from the modified MethodDefinition.
                patched = dmd.Generate();
            }

            // Generate an entirely new method that just returns a stack trace for further testing.
            DynamicMethod stacker;

            using (DynamicMethodDefinition dmd = new DynamicMethodDefinition("Stacker", typeof(StackTrace), new Type[0])) {
                using (ILContext il = new ILContext(dmd.Definition))
                    il.Invoke(_ => {
                        ILCursor c = new ILCursor(il);
                        for (int i = 0; i < 32; i++)
                        {
                            c.Emit(OpCodes.Nop);
                        }
                        c.Emit(OpCodes.Newobj, typeof(StackTrace).GetConstructor(new Type[0]));
                        for (int i = 0; i < 32; i++)
                        {
                            c.Emit(OpCodes.Nop);
                        }
                        c.Emit(OpCodes.Ret);
                    });
                stacker = (DynamicMethod)DMDEmitDynamicMethodGenerator.Generate(dmd, null);
            }

            using (DynamicMethodDefinition dmd = new DynamicMethodDefinition(typeof(ExampleGenericClass <int>).GetMethod(nameof(ExampleMethod)))) {
                Assert.Equal(0, ((Func <int>)dmd.Generate().CreateDelegate(typeof(Func <int>)))());
                Assert.Equal(0, ((Func <int>)DMDCecilGenerator.Generate(dmd).CreateDelegate(typeof(Func <int>)))());
                Assert.Equal(dmd.Name = "SomeManualDMDName", dmd.Generate().Name);
                Counter -= 2;

                // This was indirectly provided by Pathoschild (SMAPI).
                // Microsoft.GeneratedCode can be loaded multiple times and have different contents.
                // This tries to recreate that scenario... and this is the best place to test it at the time of writing.
#if NETFRAMEWORK && true
                AssemblyBuilder abDupeA = AppDomain.CurrentDomain.DefineDynamicAssembly(
                    new AssemblyName()
                {
                    Name = "MonoMod.UnitTest.AssemblyDupe"
                },
                    AssemblyBuilderAccess.RunAndSave
                    );
                ModuleBuilder mbDupeA = abDupeA.DefineDynamicModule($"{abDupeA.GetName().Name}.dll");
                TypeBuilder   tbDupeA = mbDupeA.DefineType(
                    "DupeA",
                    System.Reflection.TypeAttributes.Public | System.Reflection.TypeAttributes.Abstract | System.Reflection.TypeAttributes.Sealed | System.Reflection.TypeAttributes.Class
                    );
                Type tDupeA = tbDupeA.CreateType();

                AssemblyBuilder abDupeB = AppDomain.CurrentDomain.DefineDynamicAssembly(
                    new AssemblyName()
                {
                    Name = abDupeA.GetName().Name
                },
                    AssemblyBuilderAccess.RunAndSave
                    );
                ModuleBuilder mbDupeB = abDupeB.DefineDynamicModule($"{abDupeB.GetName().Name}.dll");
                TypeBuilder   tbDupeB = mbDupeB.DefineType(
                    "DupeB",
                    System.Reflection.TypeAttributes.Public | System.Reflection.TypeAttributes.Abstract | System.Reflection.TypeAttributes.Sealed | System.Reflection.TypeAttributes.Class
                    );
                Type tDupeB = tbDupeB.CreateType();

                Assert.Equal(tDupeA.Assembly.FullName, tDupeB.Assembly.FullName);
                Assert.NotEqual(tDupeA.Assembly, tDupeB.Assembly);

                TypeReference trDupeA = dmd.Module.ImportReference(tDupeA);
                TypeReference trDupeB = dmd.Module.ImportReference(tDupeB);
                Assert.Equal(trDupeA.Scope.Name, trDupeB.Scope.Name);
                // "Fun" fact: both share matching AssemblyNames, so the first scope gets reused!
                // Assert.NotEqual(trDupeA.Scope, trDupeB.Scope);

                Assert.Equal(tDupeA, trDupeA.ResolveReflection());
                Assert.Equal(tDupeB, trDupeB.ResolveReflection());
#endif
            }

            // Run the DynamicMethod.
            Assert.Equal(Tuple.Create(StringPatched, 3), patched.Invoke(null, new object[] { 2 }));
            Assert.Equal(Tuple.Create(StringPatched, 3), patched.Invoke(null, new object[] { 1337 }));

            // Detour the original method to the patched DynamicMethod, then run the patched method.
            using (new Detour(original, patched)) {
                // The detour is only active in this block.
                Assert.Equal(Tuple.Create(StringPatched, 6), ExampleMethod(3));
            }

            // Run the original method again.
            Assert.Equal(Tuple.Create(StringOriginal, 10), ExampleMethod(4));

            // Verify that we can still obtain the real DynamicMethod.
            // .NET uses a wrapping RTDynamicMethod to avoid leaking the mutable DynamicMethod.
            // Mono uses RuntimeMethodInfo without any link to the original DynamicMethod.
            if (Type.GetType("Mono.Runtime") != null)
            {
                stacker.Pin();
            }
            StackTrace stack   = ((Func <StackTrace>)stacker.CreateDelegate(typeof(Func <StackTrace>)))();
            MethodBase stacked = stack.GetFrames().First(f => f.GetMethod()?.IsDynamicMethod() ?? false).GetMethod();
            Assert.NotEqual(stacker, stacked);
            Assert.Equal(stacker, stacked.GetIdentifiable());
            Assert.Equal(stacker.GetNativeStart(), stacked.GetNativeStart());
            // This will always be true on .NET and only be true on Mono if the method is still pinned.
            Assert.IsAssignableFrom <DynamicMethod>(stacked.GetIdentifiable());
            if (Type.GetType("Mono.Runtime") != null)
            {
                stacker.Unpin();
            }
        }
Пример #27
0
        public static ExceptionInfo GetExceptionInfo(Exception exception, ExtensionFactory extensions)
        {
            try
            {
                var playniteStackCalls = 0;
                var stack        = new StackTrace(exception);
                var crashModules = new List <Module>();
                foreach (var frame in stack.GetFrames())
                {
                    var module = frame.GetMethod().Module;
                    if (module.Name.StartsWith("Playnite"))
                    {
                        playniteStackCalls++;
                    }

                    crashModules.AddMissing(module);
                }

                if (exception.InnerException != null)
                {
                    stack = new StackTrace(exception.InnerException);
                    foreach (var frame in stack.GetFrames())
                    {
                        var module = frame.GetMethod().Module;
                        if (module.Name.StartsWith("Playnite"))
                        {
                            playniteStackCalls++;
                        }

                        crashModules.AddMissing(module);
                    }
                }

                var extDesc = extensions?.Plugins?.FirstOrDefault(a =>
                                                                  crashModules.FirstOrDefault(m => m.Name ==
                                                                                              a.Value.Description.Module ||
                                                                                              Paths.AreEqual(a.Value.Description.DirectoryPath, Path.GetDirectoryName(m.Assembly.Location))) != null).Value;
                if (extDesc != null)
                {
                    return(new ExceptionInfo
                    {
                        IsExtensionCrash = true,
                        CrashExtension = extDesc.Description
                    });
                }
                else
                {
                    // This usually happens if an exception occurs in XAML because of faulty custom theme.
                    // The only stack entry would be Playnite's entry point or no entry at all.
                    if (playniteStackCalls == 0 || playniteStackCalls == 1)
                    {
                        return(new ExceptionInfo {
                            IsExtensionCrash = true
                        });
                    }
                    else
                    {
                        return(new ExceptionInfo());
                    }
                }
            }
            catch (Exception e) when(!PlayniteEnvironment.ThrowAllErrors)
            {
                logger.Error(e, "Failed check crash stack trace.");
                return(new ExceptionInfo());
            }
        }
Пример #28
0
        private AirbrakeTraceLine[] BuildBacktrace(Exception exception, out MethodBase catchingMethod)
        {
            Assembly assembly = Assembly.GetExecutingAssembly();

            if (assembly.EntryPoint == null)
            {
                assembly = Assembly.GetCallingAssembly();
            }

            if (assembly.EntryPoint == null)
            {
                assembly = Assembly.GetEntryAssembly();
            }

            catchingMethod = assembly == null
                                 ? null
                                 : assembly.EntryPoint;

            List <AirbrakeTraceLine> lines = new List <AirbrakeTraceLine>();
            var stackTrace = new StackTrace(exception);

            StackFrame[] frames = stackTrace.GetFrames();

            if (frames == null || frames.Length == 0)
            {
                // Airbrake requires that at least one line is present in the XML.
                AirbrakeTraceLine line = new AirbrakeTraceLine("none", 0);
                lines.Add(line);
                return(lines.ToArray());
            }

            foreach (StackFrame frame in frames)
            {
                MethodBase method = frame.GetMethod();

                catchingMethod = method;

                int lineNumber = frame.GetFileLineNumber();

                if (lineNumber == 0)
                {
                    this.log.Debug(f => f("No line number found in {0}, using IL offset instead.", method));
                    lineNumber = frame.GetILOffset();
                }

                string file = frame.GetFileName();

                if (String.IsNullOrEmpty(file))
                {
                    // ReSharper disable ConditionIsAlwaysTrueOrFalse
                    file = method.ReflectedType != null
                               ? method.ReflectedType.FullName
                               : "(unknown)";
                    // ReSharper restore ConditionIsAlwaysTrueOrFalse
                }

                AirbrakeTraceLine line = new AirbrakeTraceLine(file, lineNumber)
                {
                    Method = method.Name
                };

                lines.Add(line);
            }

            return(lines.ToArray());
        }
Пример #29
0
        public static DynamicStackFrame[] GetDynamicStackFrames(Exception e, bool filter)
        {
            List <DynamicStackFrame> frames = e.Data[typeof(DynamicStackFrame)] as List <DynamicStackFrame>;

            if (frames == null)
            {
                // we may have missed a dynamic catch, and our host is looking
                // for the exception...
                frames = ExceptionHelpers.AssociateDynamicStackFrames(e);
                ExceptionHelpers.DynamicStackFrames = null;
            }

            if (frames == null)
            {
                return(new DynamicStackFrame[0]);
            }

            if (!filter)
            {
                return(frames.ToArray());
            }

#if !SILVERLIGHT
            frames = new List <DynamicStackFrame>(frames);
            List <DynamicStackFrame> res = new List <DynamicStackFrame>();

            // the list of _stackFrames we build up in ScriptingRuntimeHelpers can have
            // too many frames if exceptions are thrown from script code and
            // caught outside w/o calling GetDynamicStackFrames.  Therefore we
            // filter down to only script frames which we know are associated
            // w/ the exception here.
            try {
                StackTrace         outermostTrace = new StackTrace(e);
                IList <StackTrace> otherTraces    = ExceptionHelpers.GetExceptionStackTraces(e) ?? new List <StackTrace>();
                List <StackFrame>  clrFrames      = new List <StackFrame>();
                foreach (StackTrace trace in otherTraces)
                {
                    clrFrames.AddRange(trace.GetFrames() ?? new StackFrame[0]);      // rare, sometimes GetFrames returns null
                }
                clrFrames.AddRange(outermostTrace.GetFrames() ?? new StackFrame[0]); // rare, sometimes GetFrames returns null

                int lastFound = 0;
                foreach (StackFrame clrFrame in InterpretedFrame.GroupStackFrames(clrFrames))
                {
                    MethodBase method = clrFrame.GetMethod();

                    for (int j = lastFound; j < frames.Count; j++)
                    {
                        MethodBase other = frames[j].GetMethod();
                        // method info's don't always compare equal, check based
                        // upon name/module/declaring type which will always be a correct
                        // check for dynamic methods.
                        if (method.Module == other.Module &&
                            method.DeclaringType == other.DeclaringType &&
                            method.Name == other.Name)
                        {
                            res.Add(frames[j]);
                            frames.RemoveAt(j);
                            lastFound = j;
                            break;
                        }
                    }
                }
            } catch (MemberAccessException) {
                // can't access new StackTrace(e) due to security
            }
            return(res.ToArray());
#else
            return(frames.ToArray());
#endif
        }
Пример #30
0
        /// <summary>
        /// Gets all static rules defined on the specified types.
        /// </summary>
        /// <param name="types"></param>
        /// <returns></returns>
        public static IEnumerable <Rule> GetRules(IEnumerable <Type> types)
        {
            // Fetch the set of rules declared on the specified types
            List <Rule> rules = new List <Rule>();

            foreach (Type type in types
                     .Where(type => type.IsClass)
                     .SelectMany(type => type.BaseType.IsGenericType ? new Type[] { type, type.BaseType } : new Type[] { type }))
            {
                rules.AddRange(
                    type.GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
                    .Where(field => typeof(IRuleProvider).IsAssignableFrom(field.FieldType))
                    .SelectMany(field =>
                {
                    IRuleProvider ruleProvider = (IRuleProvider)field.GetValue(null);

                    if (ruleProvider != null)
                    {
                        return(ruleProvider.GetRules(type, field.Name));
                    }
                    else
                    {
                        StackTrace stackTrace = new StackTrace();
                        List <MethodBase> callStackMethods = stackTrace.GetFrames()
                                                             .Select(f => f.GetMethod())
                                                             .ToList();

                        Type currentType = callStackMethods.First().DeclaringType;

                        callStackMethods.Reverse();
                        MethodBase ruleProviderCall = callStackMethods.FirstOrDefault(method => currentType != method.DeclaringType && typeof(IRuleProvider).IsAssignableFrom(method.DeclaringType));

                        if (ruleProviderCall != null)
                        {
                            string errorMessage = string.Format(
                                "'{0}'.'{1}' is null, declared as a '{2}', and '{3}'.'{4}' is creating/accessing rules. As such, it appears that the '{2}' is still initializing and rules will not register properly. Please see the call stack.",
                                type.Name, field.Name, typeof(IRuleProvider).Name, ruleProviderCall.DeclaringType.Name, ruleProviderCall.Name
                                );
                            throw new ApplicationException(errorMessage);
                        }
                    }

                    return(new Rule[] { });
                })
                    .Where(rule => rule != null)
                    );

                // Ensure the error code has been set on all statically declared condition types
                foreach (ConditionType error in
                         type.GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
                         .Where(field => typeof(ConditionType).IsAssignableFrom(field.FieldType))
                         .Select(field =>
                {
                    ConditionType error = (ConditionType)field.GetValue(null);
                    if (error != null && error.Code == null)
                    {
                        error.Code = field.DeclaringType.Name + "." + field.Name;
                    }
                    return(error);
                }))
                {
                }
            }
            return(rules);
        }
Пример #31
0
        // Обработка HTTP исключений
        protected void Application_Error(object sender, EventArgs e)
        {
            var httpContext       = ((MvcApplication)sender).Context;
            var currentController = " ";
            var currentAction     = " ";
            var currentRouteData  = RouteTable.Routes.GetRouteData(new HttpContextWrapper(httpContext));

            if (currentRouteData != null)
            {
                if (currentRouteData.Values["controller"] != null && !String.IsNullOrEmpty(currentRouteData.Values["controller"].ToString()))
                {
                    currentController = currentRouteData.Values["controller"].ToString();
                }

                if (currentRouteData.Values["action"] != null && !String.IsNullOrEmpty(currentRouteData.Values["action"].ToString()))
                {
                    currentAction = currentRouteData.Values["action"].ToString();
                }
            }

            var ex         = Server.GetLastError();
            var controller = new ErrorController();
            var routeData  = new RouteData();
            var action     = "Error";

            if (ex is HttpException)
            {
                var httpEx = ex as HttpException;

                switch (httpEx.GetHttpCode())
                {
                case 400:
                    action = "BadRequest";
                    break;

                case 404:
                    action = "NotFound";
                    break;

                    // и т.д.
                }
            }

            var stackTrace = new StackTrace(ex, true);
            var frames     = stackTrace.GetFrames();
            var source     = frames != null?frames.FirstOrDefault() : null;

            var declaringType = source != null?source.GetMethod().DeclaringType : this.GetType();

            var logger = LogManager.GetLogger(declaringType.FullName);

            logger.ErrorException(ex.Message, ex);

            httpContext.ClearError();
            httpContext.Response.Clear();
            httpContext.Response.StatusCode = ex is HttpException ? ((HttpException)ex).GetHttpCode() : 500;
            Response.Headers.Add("Content-Type", "text/html");
            httpContext.Response.TrySkipIisCustomErrors = true;

            routeData.Values["controller"] = "Error";
            routeData.Values["action"]     = action;

            controller.ViewData.Model = new HandleErrorInfo(ex, currentController, currentAction);
            ((IController)controller).Execute(new RequestContext(new HttpContextWrapper(httpContext), routeData));
        }
Пример #32
0
        protected void GVCLIENTESUGERIDO_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            String      IdCliente = Convert.ToString(GVCLIENTESUGERIDO.DataKeys[e.RowIndex].Values["IdCliente"].ToString());
            GridViewRow row       = GVCLIENTESUGERIDO.Rows[e.RowIndex];
            TextBox     TxtMonto  = row.FindControl("TxtMonto") as TextBox;

            if (TxtMonto.Text == "")
            {
                String mensajeScript = @"<script type='text/javascript'>
                       swal({
                title: ""Ingrese Monto"",
                icon: ""warning"",
                dangerMode: false,
            })
                  </script>";
                ScriptManager.RegisterStartupScript(this, typeof(Page), "mensaje", mensajeScript, false);
                TxtMonto.Focus();
                return;
            }


            String Msj = "";

            try
            {
                Msj = obj.ModificarClienteSugerido(IdCliente, Double.Parse(TxtMonto.Text.ToString().Replace(".", ",")),
                                                   Convert.ToInt32(Request.Cookies["WebNestle"]["DLIdUsuario"]));
            }
            catch (Exception ex)
            {
                StackTrace st    = new StackTrace(ex, true);
                StackFrame frame = st.GetFrames().Where(f => !String.IsNullOrEmpty(f.GetFileName()) &&
                                                        f.GetILOffset() != StackFrame.OFFSET_UNKNOWN &&
                                                        f.GetNativeOffset() != StackFrame.OFFSET_UNKNOWN &&
                                                        !f.GetMethod().Module.Assembly.GetName().Name.Contains("mscorlib")).First();

                string        MachineName = System.Environment.MachineName;
                string        UserName    = System.Environment.UserName.ToUpper();
                string        Mensaje     = ex.Message;
                StringBuilder builder     = new StringBuilder(Mensaje);
                builder.Replace("'", "");
                int    LineaError     = frame.GetFileLineNumber();
                string Proyecto       = frame.GetMethod().Module.Assembly.GetName().Name;
                string Clase          = frame.GetMethod().DeclaringType.Name;
                string metodo         = frame.GetMethod().Name;
                String M              = "Formato Incorrecto";
                string menssajeScript = "<script type='text/javascript'>"
                                        + " swal({" +

                                        "title: '" + M.ToString() + "'," +
                                        " icon: 'warning'," +
                                        "  dangerMode: false," +
                                        "   })  </script>";
                ScriptManager.RegisterStartupScript(this, typeof(Page), "mensaje", menssajeScript, false);
                return;
            }
            if (Msj != "")
            {
                string menssajeScript = "<script type='text/javascript'>"
                                        + " swal({" +

                                        "title: '" + Msj.ToString() + "'," +
                                        " icon: 'success'," +
                                        "  dangerMode: false," +
                                        "   })  </script>";
                ScriptManager.RegisterStartupScript(this, typeof(Page), "mensaje", menssajeScript, false);
            }
            GVCLIENTESUGERIDO.EditIndex = -1;
            ListarClienteSugerido();
        }
Пример #33
0
        /// <summary>
        /// Utility method providing a culture invariant stack trace string.
        /// </summary>
        /// <remarks>
        /// Since <see cref="Exception.StackTrace"/> will translate certains
        /// words depending on the UI culture, an invariant version is required.
        /// The implementation is actually taken from the MS reference code, without
        /// the culture dependent features.
        /// </remarks>
        /// <returns>Culture invariant stack trace string</returns>
        private string GetInvariantStackTrace()
        {
#if NETSTANDARD1_1
            // required classes were introduced with .NET Standard 2.0
            return(exception.StackTrace);
#else
            var stackTrace  = new StackTrace(exception, true);
            var stackFrames = stackTrace.GetFrames();
            if (stackFrames == null || stackFrames.Length == 0)
            {
                return(string.Empty);
            }

            var displayFilenames  = true;  // we'll try, but demand may fail
            var firstFrame        = true;
            var stackTraceBuilder = new StringBuilder();

            foreach (var stackFrame in stackFrames)
            {
                // ensure the current frame has a method
                var method = stackFrame.GetMethod();
                if (method == null)
                {
                    continue;
                }

                // append a newline for every stack frame, except the first one
                if (firstFrame)
                {
                    firstFrame = false;
                }
                else
                {
                    stackTraceBuilder.Append(NewLine);
                }

                // prefix for stack frame
                stackTraceBuilder.Append(StackFramePrefix);

                // append type name + method name
                var type = method.DeclaringType;
                if (type != null)
                {
                    stackTraceBuilder.Append(type.FullName.Replace('+', '.')).Append('.');
                }
                stackTraceBuilder.Append(method.Name);

                // deal with the generic portion of the method
                if (method is MethodInfo methodInfo && methodInfo.IsGenericMethod)
                {
                    stackTraceBuilder.Append("[");
                    var genericArguments     = methodInfo.GetGenericArguments();
                    var firstGenericArgument = true;

                    foreach (var genericArgument in genericArguments)
                    {
                        if (!firstGenericArgument)
                        {
                            stackTraceBuilder.Append(",");
                        }
                        else
                        {
                            firstGenericArgument = false;
                        }

                        stackTraceBuilder.Append(genericArgument.Name);
                    }

                    stackTraceBuilder.Append("]");
                }

                // append method arguments
                stackTraceBuilder.Append("(");
                var parameters     = method.GetParameters();
                var firstParameter = true;

                foreach (var parameter in parameters)
                {
                    if (!firstParameter)
                    {
                        stackTraceBuilder.Append(", ");
                    }
                    else
                    {
                        firstParameter = false;
                    }

                    stackTraceBuilder.Append(parameter.ParameterType?.Name ?? "<UnknownType>")
                    .Append(" ")
                    .Append(parameter.Name);
                }

                stackTraceBuilder.Append(")");

                // check if we can add a location
                if (!displayFilenames || stackFrame.GetILOffset() == -1)
                {
                    // don't  display filename - continue with next frame
                    continue;
                }

                string filename = null;
                try
                {
                    filename = stackFrame.GetFileName();
                }
                catch (Exception)
                {
                    // If the demand for displaying filenames fails, then it won't
                    // succeed later in the loop.  Avoid repeated exceptions by not trying again.
                    displayFilenames = false;
                }

                if (filename != null)
                {
                    // tack on " in c:\tmp\MyFile.cs:line 5"
                    stackTraceBuilder.Append(' ');
                    stackTraceBuilder.AppendFormat(CultureInfo.InvariantCulture, InFileLineNum, filename, stackFrame.GetFileLineNumber());
                }
            }

            return(stackTraceBuilder.ToString());
#endif // !NETSTANDARD1_1
        }
Пример #34
0
        /// <summary>
        /// Single point logoff
        /// </summary>
        /// <param name="urlToRedirect">
        /// The URL to redirect.
        /// </param>
        /// <param name="removeLogin">
        /// if set to <c>true</c> [remove login].
        /// </param>
        /// <remarks>
        /// </remarks>
        public static void SignOut(string urlToRedirect, bool removeLogin)
        {
            var st     = new StackTrace(new StackFrame(1, true));
            var frames = st.GetFrames();

            if (frames != null)
            {
                var stackString = frames.Aggregate(string.Empty, (current, frame) => current + ("> " + frame.GetMethod().Name));

                ErrorHandler.Publish(LogLevel.Info, "Hago signout: " + stackString);
            }

            // Log User Off from Cookie Authentication System
            FormsAuthentication.SignOut();

            // Invalidate roles token
            var hck = HttpContext.Current.Response.Cookies["portalroles"];

            if (hck != null)
            {
                hck.Value   = null;
                hck.Expires = new DateTime(1999, 10, 12);
                hck.Path    = "/";
            }

            if (removeLogin)
            {
                // Obtain PortalSettings from Current Context
                var PortalSettings = (PortalSettings)HttpContext.Current.Items[StringsPortalSettings];

                // Invalidate Portal Alias Cookie security
                var xhck = HttpContext.Current.Response.Cookies["Appleseed_" + PortalSettings.PortalAlias.ToLower()];
                if (xhck != null)
                {
                    xhck.Value   = null;
                    xhck.Expires = new DateTime(1999, 10, 12);
                    xhck.Path    = "/";
                }
            }

            // [START]  [email protected] remove user window information
            // User Information
            // valid user
            if (HttpContext.Current.User != null)
            {
                // Obtain PortalSettings from Current Context
                // Ender 4 July 2003: Added to support the Monitoring module by Paul Yarrow
                var PortalSettings = (PortalSettings)HttpContext.Current.Items[StringsPortalSettings];

                // User Information
                var            users = new UsersDB();
                MembershipUser user  = users.GetSingleUser(
                    HttpContext.Current.User.Identity.Name, PortalSettings.PortalAlias);

                if (user != null && user.ProviderUserKey != null)
                {
                    // get user id
                    var uid = (Guid)user.ProviderUserKey;

                    if (!uid.Equals(Guid.Empty))
                    {
                        try
                        {
                            if (Config.EnableMonitoring)
                            {
                                Monitoring.LogEntry(uid, PortalSettings.PortalID, -1, "Logoff", string.Empty);
                            }
                        }
                        catch
                        {
                        }
                    }
                }
            }

            // [END ]  [email protected] remove user window information

            // Redirect user back to the Portal Home Page
            if (urlToRedirect.Length > 0)
            {
                HttpContext.Current.Response.Redirect(urlToRedirect);
            }
        }
Пример #35
0
        public static void PrintExceptionData(object exceptionObj, bool writeToFile = false)
        {
            if (exceptionObj == null)
            {
                return;
            }
            Type actualType = exceptionObj.GetType();

            Exception exceptionObject = exceptionObj as Exception;

            var s       = new StackTrace(exceptionObject);
            var thisasm = Assembly.GetExecutingAssembly();

            var methodName       = s.GetFrames().Select(f => f.GetMethod()).First(m => m.Module.Assembly == thisasm).Name;
            var parameterInfo    = s.GetFrames().Select(f => f.GetMethod()).First(m => m.Module.Assembly == thisasm).GetParameters();
            var methodReturnType = s.GetFrame(1).GetMethod().GetType();

            var lineNumber = s.GetFrame(0).GetFileLineNumber();

            // string formatedMethodNameAndParameters = $"{methodReturnType} {methodName}(";
            string formatedMethodNameAndParameters = $"{methodName}(";

            if (parameterInfo.Length < 1)
            {
                formatedMethodNameAndParameters += ")";
            }
            else
            {
                for (int n = 0; n < parameterInfo.Length; n++)
                {
                    ParameterInfo param         = parameterInfo[n];
                    string        parameterName = param.Name;

                    if (n == parameterInfo.Length - 1)
                    {
                        formatedMethodNameAndParameters += $"{param.ParameterType} {parameterName})";
                    }
                    else
                    {
                        formatedMethodNameAndParameters += $"{param.ParameterType} {parameterName},";
                    }
                }
            }

            string formattedContent = $"[UNHANDLED_EXCEPTION] Caught Exception of type {actualType}\n\n" +
                                      $"Exception Message: {exceptionObject.Message}\n" +
                                      $"Exception Origin File/Module: {exceptionObject.Source}\n" +
                                      $"Method that threw the Exception: {formatedMethodNameAndParameters}\n";

            Console.WriteLine(formattedContent);

            if (exceptionObject.Data.Count > 0)
            {
                Console.WriteLine($"Exception Data Dictionary Results:");
                foreach (DictionaryEntry pair in exceptionObject.Data)
                {
                    Console.WriteLine("	* {0} = {1}", pair.Key, pair.Value);
                }
            }

            if (writeToFile)
            {
                WriteToFile(formattedContent);
            }
        }
Пример #36
0
        public async Task WriteException(Exception e)
        {
            StackTrace stackTrace = new StackTrace(e, true);

            await WriteException($"{stackTrace.GetFrames().ElementAt(0).GetMethod().DeclaringType?.Name} at {stackTrace.GetFrames().ElementAt(0).GetMethod().DeclaringType?.DeclaringType?.Name}", e);
        }
Пример #37
0
    private string FilterStackTrace(StackTrace t)
    {
        StackFrame[] frames = t.GetFrames();
        StringBuilder sb = new StringBuilder();
        foreach(StackFrame f in frames) {
          try {
        string fileName = f.GetFileName();
        // Filter out UnityTest itself...
        if(fileName.EndsWith("UnityTest.cs")) continue;

        // Shorten filenames down to the salient bits.  Would use
        // Application.dataPath, BUUUT that approach doesn't help unless we're
        // running in the editor.
        fileName = fileName.Replace(AssetDirectory, "");

        // Add output in roughly the standard stack trace format:
        //   at Class.Method(Params) in FileName:line LineNum
        // TODO: Make this follow Unity conventions.
        sb
          .Append("\tat ").Append(f.GetMethod().ToString()
            .Replace("System.", "")).Append(" in ")
          .Append(fileName).Append(":line ").Append(f.GetFileLineNumber())
          .Append("\n");
          } catch(NullReferenceException) {
        // GetFileName can throw an NRE.  Presumably from generates code that
        // has no corresponding file?
          }
        }
        return sb.ToString();
    }