/// <summary> /// Initializes a new instance of Siege client /// </summary> /// <param name="name">Name.</param> /// <param name="tags">Tags.</param> public Siege(string name = null, params string[] tags) { this.server = Module.Find<SiegeServer>(); this.Name = name; this.Tags = new ReadOnlyCollection<string>(tags); creatorStackTrace = Diagnostic.GetStackTrace(1); }
static void LogFunc(string logDomain, GLib.LogLevelFlags logLevel, string message) { System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace (2, true); string msg = string.Format ("{0}-{1}: {2}\nStack trace: {3}{4}", logDomain, logLevel, message, Environment.NewLine, trace.ToString ()); switch (logLevel) { case GLib.LogLevelFlags.Debug: Log.Debug (msg); break; case GLib.LogLevelFlags.Info: Log.Info (msg); break; case GLib.LogLevelFlags.Warning: Log.Warn (msg); break; case GLib.LogLevelFlags.Error: Log.Error (msg); break; case GLib.LogLevelFlags.Critical: default: Log.Fatal (msg); break; } }
/// <summary> /// Public scanner method. Test scanner input for this parser's patterns. /// </summary> /// <remarks>Most parsers won't need to override this method</remarks> /// <param name="scan">Scanner to parse from</param> /// <returns>Match (success of failure) of the parser against the scanne</returns> public virtual ParserMatch Parse(IScanner scan) { scan.Normalise(); var st = new System.Diagnostics.StackTrace(); scan.StackStats(st.FrameCount); if (scan.RecursionCheck(this, scan.Offset)) if (!(this is Recursion)) return scan.NoMatch; ParserMatch m; if (this is IMatchingParser) m = ((IMatchingParser) this).TryMatch(scan); else m = Parse(scan); if (m.Success) { scan.ClearFailures(); } else { scan.AddFailure(this, scan.Offset); } return m; }
public static void HealthCheck(Action healthyBehaviour) { var currentStack = new System.Diagnostics.StackTrace(); Application.Current.Dispatcher.BeginInvoke((Action)delegate { try { foreach (var server in SERVERS) server.ok = false; checkServers(); int attempts = 0; const int MILIS_BETWEEN_TRIES = 500; var timer = new DispatcherTimer(TimeSpan.FromMilliseconds(MILIS_BETWEEN_TRIES), DispatcherPriority.Normal, (sender, args) => { var brokenServers = SERVERS.Where(s => !s.ok); attempts++; if (brokenServers.Count() == 0) { self.Visibility = Visibility.Collapsed; ((DispatcherTimer)sender).Stop(); healthyBehaviour(); } }, Application.Current.Dispatcher); timer.Start(); } catch (Exception e) { throw new Exception(currentStack.ToString(), e); } }); }
/* * Gets a stamp for debug messages that contains the time and the calling method. * * The calling method is judged to be the lowest frame in the stack that's * *not* in the FLog class. If depth is set, we will walk further up the * stack. */ public static string GetStamp(int extraDepth=0) { string rv = ""; System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(); // Walk up the stack to the first frame that's *not* in this class (i.e., the lowest caller) and append it. System.Diagnostics.StackFrame sf = null; int i = 0; for ( ; i<trace.FrameCount; i++) { sf = trace.GetFrame(i); if (sf.GetMethod().DeclaringType != typeof(FLog)) break; } // Walk up some extra frames as needed. i += extraDepth; sf = trace.GetFrame(i); if (sf != null) { string m = sf.GetMethod().DeclaringType.ToString(); rv += System.String.Format("{0}:{1}.{2}", Time.realtimeSinceStartup.ToString("F1"), m, sf.GetMethod().Name); } else { rv = Time.realtimeSinceStartup.ToString("F1"); } return rv; }
public static void Log(string message, bool writeToConsole = true) { if (message == null) return; string assembly = ""; try { System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace(); if (stackTrace.FrameCount != 0) assembly = stackTrace.GetFrame(1).GetMethod().DeclaringType.Assembly.GetName().Name; if ((assembly.StartsWith("Rocket.") || assembly == "Assembly-CSharp" || assembly == "UnityEngine") && stackTrace.FrameCount > 2) { assembly = stackTrace.GetFrame(2).GetMethod().DeclaringType.Assembly.GetName().Name; } if (assembly == "" || assembly == typeof(Logger).Assembly.GetName().Name || assembly == lastAssembly || assembly.StartsWith("Rocket.") || assembly == "Assembly-CSharp" || assembly == "UnityEngine") { assembly = ""; } else { assembly = assembly + " >> "; } lastAssembly = assembly; message = assembly + message; } catch (Exception) { throw; } ProcessInternalLog(ELogType.Info, message, writeToConsole); }
/// <summary> /// Opens the specified filename /// </summary> protected void Open(string filename, string fileMode) { // sanity check if (IsOpen) { throw new ApplicationException("ERROR: The Open method was called even though the file is already open."); } FileStreamPointer = SafeNativeMethods.gzopen(filename, fileMode); if (FileStreamPointer == IntPtr.Zero) { //for some reason throwing an exception here can hang. Possibly from the managed to native transition? //if you encounter that you should check for the complicating condition before trying to open the gzip file and handle it accordingly //you may have to call Environment.Exit(-1) as throwing an exception may hang //interestingly enabling native code debugging is a workaround but that won't work outside Visual Studio Console.Error.WriteLine(string.Format("ERROR: Unable to open the file ({0}) for reading", filename)); Console.Error.WriteLine("This process will now exit"); System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace(); Console.Error.WriteLine(t.ToString()); System.Environment.Exit(-1); } FilePath = filename; IsOpen = true; CurrentOffset = 0; BufferOffset = 0; }
public Message() { TypeLog = Enums.TypeLog.Error; Thread = string.Format(", CurrentThreadName:{0}, CurrentThreadManagedThreadId:{1}, CurrentThreadCurrentCulture:{2}, CurrentThreadPriority:{3}", System.Threading.Thread.CurrentContext, System.Threading.Thread.CurrentThread.Name, System.Threading.Thread.CurrentThread.ManagedThreadId, System.Threading.Thread.CurrentThread.CurrentCulture, System.Threading.Thread.CurrentThread.Priority); Domain = Environment.UserDomainName; Username = Environment.UserName; Hostname = Environment.MachineName; try { Ips = string.Join(", ", Dns.GetHostEntry(Dns.GetHostName()).AddressList.Select(ip => ip.ToString())); } catch (Exception ex) { } System.Diagnostics.StackTrace stack = new System.Diagnostics.StackTrace(); ApplicationMode = Params.ApplicationMode; Stacktrace = string.Empty; foreach (var item in stack.GetFrames()) { Stacktrace += string.Format("{0}: Class: {1}; Method: {2}; Line: {3}; Collumn: {4}; \r\n", item.GetFileName(), item.GetMethod().DeclaringType.FullName, item.GetMethod().Name, item.GetFileLineNumber(), item.GetFileColumnNumber()); } }
private ExceptionDispatchInfo(Exception exception) { // Copy over the details we need to save. m_Exception = exception; #if MONO var count = exception.captured_traces == null ? 0 : exception.captured_traces.Length; var stack_traces = new System.Diagnostics.StackTrace [count + 1]; if (count != 0) Array.Copy (exception.captured_traces, 0, stack_traces, 0, count); stack_traces [count] = new System.Diagnostics.StackTrace (exception, 0, true); m_stackTrace = stack_traces; #else m_remoteStackTrace = exception.RemoteStackTrace; // NOTE: don't be tempted to pass the fields for the out params; the containing object // might be relocated during the call so the pointers will no longer be valid. object stackTrace; object dynamicMethods; m_Exception.GetStackTracesDeepCopy(out stackTrace, out dynamicMethods); m_stackTrace = stackTrace; m_dynamicMethods = dynamicMethods; m_IPForWatsonBuckets = exception.IPForWatsonBuckets; m_WatsonBuckets = exception.WatsonBuckets; #endif }
//------------------------------------------------------------------------------------------------------------------------ #endregion #region Constructors //------------------------------------------------------------------------------------------------------------------------ static TypeCache() { #if NETFX //add entry assembly var EntryAssembly = Assembly.GetEntryAssembly(); if (EntryAssembly != null) EntryAssemblies.Add(EntryAssembly); //Add as many assemblies as we can //add from stack try { var frameAssemblies = new System.Diagnostics.StackTrace().GetFrames().Select(t => t.GetMethod().Module.Assembly).ToHashSet(); foreach (var entry in frameAssemblies) EntryAssemblies.Add(entry); } catch (Exception ex) { DebugEx.TraceError(ex, "Unhandled exception during Stack Frame assembly examination"); } //add from domain try { EntryAssemblies.AddFromSource(AppDomain.CurrentDomain.GetAssemblies()); } catch (Exception ex) { DebugEx.TraceError(ex, "Unhandled exception during AppDomain assembly examination"); } #elif UNIVERSAL EntryAssemblies.Add(Windows.UI.Xaml.Application.Current.GetType().GetTypeInfo().Assembly); #endif }
public static void DisplayForm(params string[] testSteps) { using (ManualTestForm form = new ManualTestForm()) { int i = 0; Console.WriteLine("Steps:"); foreach (string step in testSteps) { string message = String.Format("{0} {1}", i, step); Console.WriteLine(message); form.TestStepList.Items.Add(message); ++i; } System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(1); form.Text = trace.GetFrame(0).GetMethod().DeclaringType.FullName + trace.GetFrame(0).GetMethod().Name; DialogResult result = form.ShowDialog(); // dumping comments Console.WriteLine("Manual Test"); Console.WriteLine(form.Comments); Console.WriteLine("Success: {0}", result); Assert.AreEqual(result, DialogResult.Yes, "Manual Test failed"); } }
static void LogFunc (string logDomain, GLib.LogLevelFlags logLevel, string message) { if (RemainingBytes < 0) return; System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace (2, true); string msg = string.Format ("{0}-{1}: {2}\nStack trace: \n{3}", logDomain, logLevel, message, trace.ToString ()); switch (logLevel) { case GLib.LogLevelFlags.Debug: LoggingService.LogDebug (msg); break; case GLib.LogLevelFlags.Info: LoggingService.LogInfo (msg); break; case GLib.LogLevelFlags.Warning: LoggingService.LogWarning (msg); break; case GLib.LogLevelFlags.Error: case GLib.LogLevelFlags.Critical: default: LoggingService.LogError (msg); break; } RemainingBytes -= msg.Length; if (RemainingBytes < 0) LoggingService.LogError ("Disabling glib logging for the rest of the session"); }
public static bool append(String message, MessageType mt) { try { // get name of calling module and function System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace(); System.Reflection.MethodBase mb = stackTrace.GetFrame(0).GetMethod(); // =this function String name = mb.Name; for(int i = 1; i < stackTrace.FrameCount; i++) { mb = stackTrace.GetFrame(i).GetMethod(); if(mb.Name != name) break; } //Build and then write the (CSV formatted) line to todays log file String logName = getLogName(); String dateStamp = DateTime.Today.ToString("yyyyMMdd"); String timeStamp = DateTime.Now.ToString("HH:mm:ss.fff"); String line = String.Format("{0},{1},{2},{3},{4},\"{5}\"{6}", dateStamp, timeStamp, mb.Module, mb.Name, mt.ToString(), message.Replace(',',';').Replace('"','\''), Environment.NewLine); System.IO.File.AppendAllText(logName, line); } catch(Exception ex) { // Log errors for testing, but ignore when live System.Diagnostics.Debug.WriteLine(ex.Message); return false; } return true; }
/// <summary> /// To Log exception informations /// Stream witer is replaced with enterprise library /// </summary> /// <param name="ex"></param> public static void Error(string message, Exception ex) { LogEntry logEntry = null; try { logEntry = new LogEntry(); logEntry.Categories.Clear(); logEntry.TimeStamp = DateTime.Now; logEntry.Severity = System.Diagnostics.TraceEventType.Error; logEntry.Message = message; logEntry.Categories.Add("General Category"); Logger.Write(logEntry); System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true); Logger.Write("Method: " + trace.GetFrame(trace.FrameCount - 1).GetMethod().Name); Logger.Write("Line: " + trace.GetFrame(trace.FrameCount - 1).GetFileLineNumber()); Logger.Write("Column: " + trace.GetFrame(trace.FrameCount - 1).GetFileColumnNumber()); } catch { throw; } finally { logEntry = null; } }
public FMEJobManager() { try { // Let the User know that the FME Session is being established. if (ProcessMessage != null) { ProcessMessage(" - Opening the FME Session in which the specified FME Job will be run..."); } // Attempt to instantiate the FME Session. // Initiate an FME Session. _fmeSession = Safe.FMEObjects.FMEObjects.CreateSession(); _fmeSession.Init(null); // Exit this method. return; } catch (Safe.FMEObjects.FMEOException fmeException) { // Determine the Line Number from which the exception was thrown. System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace(fmeException, true); System.Diagnostics.StackFrame stackFrame = stackTrace.GetFrame(stackTrace.FrameCount - 1); int lineNumber = stackFrame.GetFileLineNumber(); // Let the User know that the Session Could not be created. if (ErrorMessage != null) { ErrorMessage(""); ErrorMessage(""); ErrorMessage("Failed to open the FME Session with error - " + fmeException.FmeErrorMessage + " (Line: " + lineNumber.ToString() + ")!"); } // Exit this method. return; } catch (System.Exception caught) { // Determine the Line Number from which the exception was thrown. System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace(caught, true); System.Diagnostics.StackFrame stackFrame = stackTrace.GetFrame(stackTrace.FrameCount - 1); int lineNumber = stackFrame.GetFileLineNumber(); // Let the User know that the Session Could not be created. if (ErrorMessage != null) { ErrorMessage(""); ErrorMessage(""); ErrorMessage("Failed to open the FME Session with error - " + caught.Message + " (Line: " + lineNumber.ToString() + ")!"); } // Exit this method. return; } }
public PlayException() { // 读取到堆栈上一帧内容 var frame = new System.Diagnostics.StackTrace(this).GetFrame(-1); MethodBase = frame.GetMethod(); m_message = frame.GetMethod().Name; }
public void Debug(String v) { if (LEVEL == L_DEBUG) { System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(1, true); string message = "[" + DateUtil.GetNowDate() + "][" + this.tag + "][" + st.GetFrame(0).GetFileLineNumber() + "] - " + v; this.write(message); } }
private static string GetMethodName(int depth) { var stackTrace = new System.Diagnostics.StackTrace(); var stackFrame = stackTrace.GetFrame(depth); var methodBase = stackFrame.GetMethod(); string n = methodBase.DeclaringType.Name + "." + methodBase.Name; return n; }
public void AppLog(string message) { System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace(); var outputMessage = string.Format("caller:{0}\n", t.GetFrames()[1]); outputMessage += string.Format("class:{0}\n", this.GetType().ToString()); outputMessage += string.Format("message:{0}\n", message); Log.Debug("FragmentNavEx", outputMessage); }
private static void ThrowWhenNoAppStartupsFixtureRuns() { var frames = new System.Diagnostics.StackTrace().GetFrames(); if (frames != null && frames.Select(f => f.GetMethod().DeclaringType).Any(t => t == typeof(NoAppStartupsFixture))) { throw new Exception(); } }
public static void SaveFromADO(LogPerformance logPerformance) { var st = new System.Diagnostics.StackTrace(); if (String.IsNullOrEmpty(logPerformance.Accion)) logPerformance.Accion = st.GetFrame(1).GetMethod().Name; if (String.IsNullOrEmpty(logPerformance.Modulo)) logPerformance.Modulo = st.GetFrame(1).GetMethod().ReflectedType.FullName; Save(logPerformance); }
public static void Write(string format, params object[] args) { #if TRACE System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace(); System.Diagnostics.StackFrame stackFrame = stackTrace.GetFrame(1); System.Reflection.MethodBase methodBase = stackFrame.GetMethod(); Console.WriteLine("[thread " + System.Threading.Thread.CurrentThread.ManagedThreadId + ", " + methodBase.DeclaringType.Name + "." + methodBase.Name + "] " + string.Format(format, args)); #endif }
internal void Log(params object[] parameters) { var st = new System.Diagnostics.StackTrace(); var method = st.GetFrame(1).GetMethod(); Log(method.Name, method.GetParameters().Select((param, index) => { var tmp = param.ToString().Split(' '); return string.Format("{0} {1} = {2}", GetName(tmp.First()), tmp.Last(), parameters[index]); }).ToArray()); }
public InvocationInfo(IInvocationInfo info) { target = info.Target; targetMethod = info.TargetMethod.Name; stackTrace = info.StackTrace; returnType = info.ReturnType; parameterTypes = info.ParameterTypes; typeArguments = info.TypeArguments; arguments = info.Arguments; }
public static void LogMethod(params object[] toLog) { System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(); System.Diagnostics.StackFrame callerFrame = trace.GetFrame(1); MethodBase method = callerFrame.GetMethod(); indent++; Debug.Log(string.Format("{0}.{1}\n{2}", method.DeclaringType, method.Name, LogToString(toLog))); indent--; }
// When targeting 4.5/C# 5: // public void LogWrapper(log4net.ILog Log, [CallerMemberName] string Caller = null) // The compiler will add the caller name at compile-time, so will have zero cost // as far as execution goes. public FunctionLogger(log4net.ILog Log) { this.Log = Log; if (!this.Log.IsDebugEnabled) // StackTrace, below, is expensive... return; Name = new System.Diagnostics.StackTrace(1, false).GetFrame(0).GetMethod().ToString(); this.Log.DebugFormat("[ Top of {0} ]", this.Name); }
public static void Check(bool express) { if (express) return; System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(1, true); System.Diagnostics.StackFrame sf = st.GetFrame(0); string msg = "Assert Excpetion, file:" + sf.GetFileName() + "method:" + sf.GetMethod().Name + "line:" + sf.GetFileLineNumber(); throw new Exception(msg); }
internal static StackFrame[] GetStackTrace(this Exception e) { StackTrace trace = new StackTrace(e, true); StackFrame[] frames = trace.GetFrames(); if (frames == null) { // don't include this helper function in the trace frames = new StackTrace(true).GetFrames().Skip(1).ToArray(); } return frames; }
/// <summary> /// Initializes a new instance of the ClientAccountLock class. /// </summary> public ClientAccountLock(int id) { var stackTrace = new System.Diagnostics.StackTrace(); var callingMethod = stackTrace.GetFrame(1).GetMethod().Name; base.ClientAccountId = id; base.MethodCalled = callingMethod; StateManager.LockClientAccount(this); }
public static void PrintStackTrace() { System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(); for (int frameIndex = 0; frameIndex < trace.FrameCount; frameIndex++) { System.Diagnostics.StackFrame frame = trace.GetFrame(frameIndex); Console.WriteLine(" ".PadLeft(frameIndex) // indention + frame.GetMethod().ReflectedType.FullName // method's object + "." + frame.GetMethod().Name); // method name } }
/************************************************************************************************************************/ #pragma warning disable IDE0079 // Remove unnecessary suppression. #pragma warning disable CS1587 // XML comment is not placed on a valid language element. #pragma warning restore IDE0079 // Remove unnecessary suppression. // Copy this #region into a class which implements IOwnedState to give it the state extension methods as regular members. // This will avoid any issues with the compiler inferring the wrong generic argument in the extension methods. ///************************************************************************************************************************/ //#region State Extensions ///************************************************************************************************************************/ ///// <summary> ///// Checks if this state is the <see cref="StateMachine{TState}.CurrentState"/> in its ///// <see cref="IOwnedState{TState}.OwnerStateMachine"/>. ///// </summary> //public bool IsCurrentState() => OwnerStateMachine.CurrentState == this; ///************************************************************************************************************************/ ///// <summary> ///// Calls <see cref="StateMachine{TState}.TrySetState(TState)"/> on the ///// <see cref="IOwnedState{TState}.OwnerStateMachine"/>. ///// </summary> //public bool TryEnterState() => OwnerStateMachine.TrySetState(this); ///************************************************************************************************************************/ ///// <summary> ///// Calls <see cref="StateMachine{TState}.TryResetState(TState)"/> on the ///// <see cref="IOwnedState{TState}.OwnerStateMachine"/>. ///// </summary> //public bool TryReEnterState() => OwnerStateMachine.TryResetState(this); ///************************************************************************************************************************/ ///// <summary> ///// Calls <see cref="StateMachine{TState}.ForceSetState(TState)"/> on the ///// <see cref="IOwnedState{TState}.OwnerStateMachine"/>. ///// </summary> //public void ForceEnterState() => OwnerStateMachine.ForceSetState(this); ///************************************************************************************************************************/ //#endregion ///************************************************************************************************************************/ #if UNITY_ASSERTIONS /// <summary>[Internal] Returns an error message explaining that the wrong type of change is being accessed.</summary> internal static string GetChangeError(Type stateType, Type machineType, string changeType = "State") { Type previousType = null; Type baseStateType = null; System.Collections.Generic.HashSet <Type> activeChangeTypes = null; var stackTrace = new System.Diagnostics.StackTrace(1, false).GetFrames(); for (int i = 0; i < stackTrace.Length; i++) { var type = stackTrace[i].GetMethod().DeclaringType; if (type != previousType && type.IsGenericType && type.GetGenericTypeDefinition() == machineType) { var argument = type.GetGenericArguments()[0]; if (argument.IsAssignableFrom(stateType)) { baseStateType = argument; break; } else { if (activeChangeTypes == null) { activeChangeTypes = new System.Collections.Generic.HashSet <Type>(); } if (!activeChangeTypes.Contains(argument)) { activeChangeTypes.Add(argument); } } } previousType = type; } var text = new System.Text.StringBuilder() .Append("Attempted to access ") .Append(changeType) .Append("Change<") .Append(stateType.FullName) .Append($"> but no {nameof(StateMachine<IState>)} of that type is currently changing its ") .Append(changeType) .AppendLine("."); if (baseStateType != null) { text.Append(" - ") .Append(changeType) .Append(" changes must be accessed using the base ") .Append(changeType) .Append(" type, which is ") .Append(changeType) .Append("Change<") .Append(baseStateType.FullName) .AppendLine("> in this case."); var caller = stackTrace[1].GetMethod(); if (caller.DeclaringType == typeof(StateExtensions)) { var propertyName = stackTrace[0].GetMethod().Name; propertyName = propertyName.Substring(4, propertyName.Length - 4);// Remove the "get_". text.Append(" - This may be caused by the compiler incorrectly inferring the generic argument of the Get") .Append(propertyName) .Append(" method, in which case it must be manually specified like so: state.Get") .Append(propertyName) .Append('<') .Append(baseStateType.FullName) .AppendLine(">()"); } } else { if (activeChangeTypes == null) { text.Append(" - No other ") .Append(changeType) .AppendLine(" changes are currently occurring either."); } else { if (activeChangeTypes.Count == 1) { text.Append(" - There is 1 ") .Append(changeType) .AppendLine(" change currently occurring:"); } else { text.Append(" - There are ") .Append(activeChangeTypes.Count) .Append(' ') .Append(changeType) .AppendLine(" changes currently occurring:"); } foreach (var type in activeChangeTypes) { text.Append(" - ") .AppendLine(type.FullName); } } } text.Append(" - ") .Append(changeType) .Append("Change<") .Append(stateType.FullName) .AppendLine($">.{nameof(StateChange<IState>.IsActive)} can be used to check if a change of that type is currently occurring.") .AppendLine(" - See the documentation for more information: " + "https://kybernetik.com.au/animancer/docs/manual/fsm/changing-states"); return(text.ToString()); }
/// <summary> /// Logs native function's call to file. If that file exists, it is overwritten. One file is maintained for each thread. /// Note: This method is being called by dynamically generated code. Be careful when changing its signature. /// </summary> private static void WriteNativeCrashLog(NativeFunction nativeFunction, object[] arguments) { var threadId = Thread.CurrentThread.ManagedThreadId; var filePath = Path.Combine(ApplyDirectoryPathMacros(Options.crashLogsDir), $"{CRASH_FILE_NAME_PREFIX}tid{threadId}.log"); using (var file = File.Open(filePath, FileMode.Create, FileAccess.Write, FileShare.Read)) //Truncates file if exists { using (var writer = new StreamWriter(file)) { writer.Write("function: "); writer.WriteLine(nativeFunction.identity.symbol); writer.Write($"from DLL: "); writer.WriteLine(nativeFunction.containingDll.name); writer.Write($" at path: "); writer.WriteLine(nativeFunction.containingDll.path); writer.Write("arguments: "); if (arguments.Length == 0) { writer.WriteLine("no arguments"); } else { writer.WriteLine(); for (int i = 0; i < arguments.Length; i++) { writer.Write($" {i}:".PadRight(5)); var param = arguments[i]; if (param == null) { writer.Write("null"); } else { switch (param) { case string _: writer.Write($"\"{param}\""); break; //For float types use InvariantCulture, as so to use dot decimal separator over comma case float f: writer.Write(f.ToString(System.Globalization.CultureInfo.InvariantCulture)); break; case double f: writer.Write(f.ToString(System.Globalization.CultureInfo.InvariantCulture)); break; case decimal f: writer.Write(f.ToString(System.Globalization.CultureInfo.InvariantCulture)); break; default: writer.Write(param); break; } } writer.WriteLine(); } } writer.Write("thread: "); if (threadId == _unityMainThreadId) { writer.WriteLine("unity main thread"); } else { writer.WriteLine($"{Thread.CurrentThread.Name}({threadId})"); } var nativeCallIndex = Interlocked.Increment(ref _lastNativeCallIndex) - 1; writer.Write("call index: "); writer.WriteLine(nativeCallIndex); if (Options.crashLogsStackTrace) { var stackTrace = new System.Diagnostics.StackTrace(1); //Skip this frame writer.WriteLine("stack trace:"); writer.Write(stackTrace.ToString()); } } } }
private static string GetStackTrace(Thread thread) { StringBuilder text = new StringBuilder(); try { System.Diagnostics.StackTrace stackTrace; if (thread != System.Threading.Thread.CurrentThread) { thread.Suspend(); int retryCount = 0; System.Threading.ThreadState state; while (true) { state = System.Threading.ThreadState.Suspended; if ((thread.ThreadState & state) == state) { break; } state = ThreadState.WaitSleepJoin | ThreadState.SuspendRequested; if ((thread.ThreadState & state) == state) { break; } Thread.Sleep(10); retryCount++; if (retryCount > 50) { return("Failed to suspend thread: " + thread.ThreadState.ToString()); } } stackTrace = new System.Diagnostics.StackTrace(thread, true); } else { stackTrace = new System.Diagnostics.StackTrace(1, true); } //string fullTrace = stackTrace.ToString(); int currFrameID = 0; if (thread == System.Threading.Thread.CurrentThread) { currFrameID = 1; } while (currFrameID < stackTrace.FrameCount) { System.Diagnostics.StackFrame sf = stackTrace.GetFrame(currFrameID); MethodBase method = sf.GetMethod(); string declaringType = "<unknown>"; if (method.DeclaringType != null) { declaringType = method.DeclaringType.FullName; } StringBuilder methodName = new StringBuilder(declaringType + "." + method.Name + "("); ParameterInfo[] parameters = method.GetParameters(); foreach (ParameterInfo param in parameters) { if (!methodName.ToString().EndsWith("(")) { methodName.Append(", "); } if (param.IsOptional) { methodName.Append("Optional "); } methodName.Append(param.ParameterType.Name); } methodName.Append(")"); text.Append(" " + methodName); int lineNumber = sf.GetFileLineNumber(); if (lineNumber > 0) { text.Append(" : " + lineNumber.ToString()); } text.Append(Environment.NewLine); currFrameID += 1; } } catch (Exception e) { return("Exception getting stack trace. Thread: " + thread.Name + ", Error: " + e.Message); } finally { try { thread.Resume(); } catch { } } return(text.ToString()); }
internal static void ModCallAddPortrait(object[] args) { //args[0] should be "Portrait" //args[1] should be the mod it's coming from if (!(args[1] is Mod)) { var stack = new System.Diagnostics.StackTrace(true); SpiritMod.Instance.Logger.Error("Call Error: Mod.Call Portrait does not contain valid Mod value:\n" + stack.ToString()); return; } var callerMod = args[1] as Mod; //args[2] should the portrait NPC's internal name string name = args[2].ToString(); int id = callerMod.NPCType(name); //args[3] should be the portrait's texture if (!(args[3] is Texture2D)) { var stack = new System.Diagnostics.StackTrace(true); SpiritMod.Instance.Logger.Error("Call Error: Mod.Call Portrait does not contain valid Texture value:\n" + stack.ToString()); return; } var texture = args[3] as Texture2D; Func <string, NPC, Rectangle> getFrame = delegate { return(new Rectangle(0, 0, 108, 108)); }; //Default to a basic, single frame portrait if (args.Length > 4) //Optional argument { //args[4] should be the portrait's Get Frame alias if (args[4] != null && !(args[4] is Func <string, NPC, Rectangle>)) { var stack = new System.Diagnostics.StackTrace(true); SpiritMod.Instance.Logger.Error("Call Error: Mod.Call Portrait does not contain valid GetFrame delegate:\n" + stack.ToString()); return; } if (args[4] != null) //Allow end user to ignore this argument { getFrame = args[4] as Func <string, NPC, Rectangle>; } } var size = new Point(108, 108); if (args.Length > 5) //Optional argument { //args[5] should be the portrait's BaseSize if (args[5] != null && !(args[5] is Point)) { var stack = new System.Diagnostics.StackTrace(true); SpiritMod.Instance.Logger.Error("Call Error: Mod.Call Portrait does not contain valid Point value:\n" + stack.ToString()); return; } if (args[5] != null) //Allow end user to ignore this argument { size = (Point)args[5]; } } var portrait = new ModCallPortrait(id, texture, getFrame, size); callPortraits.Add(portrait); // args[0] should be "Portrait" (string) // args[1] should be the mod it's coming from // args[2] should the portrait NPC's internal name // args[3] should be the portrait's texture // args[4] should be the portrait's Get Frame hook, if any (defaults to a single frame portrait) // args[5] should be the portrait's BaseSize, if any defaults to (108, 108) // So calling this would be // spiritMod.Call("Portrait", myMod, "MyTownNPC", ModContent.GetTexture("SomeTexture")); for a default, single frame portrait. // // Or, // // spiritMod.Call("Portrait", myMod, "MyTownNPC", ModContent.GetTexture("SomeTexture"), // (string text, NPC talkNPC) => // { // if (text.ToUpper() == "USE THAT ONE COOL FRAME PLEASE") // return new Rectangle(110, 0, 108, 108); // return new Rectangle(0, 0, 108, 108); // }); //For a portrait with two frames. Etc. }
static void Main(string[] args) { dynamic var1; var1 = "Teste"; Console.WriteLine(String.Format("Valor de var1: {0}", var1)); Console.WriteLine(String.Format("Tipo de var1: {0}", var1.GetType())); dynamic mutableVar = 1; Console.WriteLine(String.Format("Tipo de mutableVar: {0}", mutableVar.GetType())); mutableVar = "Texto"; Console.WriteLine(String.Format("Tipo de mutableVar: {0}", mutableVar.GetType())); mutableVar = DateTime.Now; Console.WriteLine(String.Format("Tipo de mutableVar: {0}", mutableVar.GetType())); mutableVar = new StringBuilder(); Console.WriteLine(String.Format("Tipo de mutableVar: {0}", mutableVar.GetType())); dynamic dynamicVar = new StringBuilder(); //dynamicVar.MetodoInexistente(); // Compila mas gera erro de execução //string teste = dynamicVar.PropriedadeInexistente; // Compila mas gera erro de execução object mensagem = "C# é fortemente tipado"; //mensagem += 999; Console.WriteLine(mensagem); dynamic novaMensagem = "C# é fortemente tipado"; novaMensagem += 999; // Resultado: C# é fortemente tipado999 Console.WriteLine(novaMensagem); // Conversão implicita de objetos dynamic dynamic dynamicInt = 999; Console.WriteLine(String.Format("Valor de dynamicInt: {0}", dynamicInt)); Console.WriteLine(String.Format("Tipo de dynamicInt: {0}", dynamicInt.GetType())); dynamic dynamicString = "texto"; Console.WriteLine(String.Format("Valor de dynamicString: {0}", dynamicString)); Console.WriteLine(String.Format("Tipo de dynamicString: {0}", dynamicString.GetType())); dynamic dynamicDate = DateTime.Now; Console.WriteLine(String.Format("Valor de dynamicDate: {0}", dynamicDate)); Console.WriteLine(String.Format("Tipo de dynamicDate: {0}", dynamicDate.GetType())); dynamic dynamicStackTrace = new System.Diagnostics.StackTrace(); Console.WriteLine(String.Format("Valor de dynamicStackTrace: {0}", dynamicStackTrace)); Console.WriteLine(String.Format("Tipo de dynamicStackTrace: {0}", dynamicStackTrace.GetType())); int intVar = dynamicInt; Console.WriteLine(String.Format("Valor de intVar: {0}", intVar)); Console.WriteLine(String.Format("Tipo de intVar: {0}", intVar.GetType())); string stringVar = dynamicString; Console.WriteLine(String.Format("Valor de stringVar: {0}", stringVar)); Console.WriteLine(String.Format("Tipo de stringVar: {0}", stringVar.GetType())); DateTime dateTimeVar = dynamicDate; Console.WriteLine(String.Format("Valor de dateTimeVar: {0}", dateTimeVar)); Console.WriteLine(String.Format("Tipo de dateTimeVar: {0}", dateTimeVar.GetType())); System.Diagnostics.StackTrace stackTraceObject = dynamicStackTrace; Console.WriteLine(String.Format("Valor de dynamicStackTrace: {0}", dynamicStackTrace)); Console.WriteLine(String.Format("Tipo de dynamicStackTrace: {0}", dynamicStackTrace.GetType())); // DateTime DateTime d1 = new DateTime(); // Data "zero": 01/01/0001 00:00:00 Console.WriteLine($"new DateTime(): {d1.ToString()}"); DateTime d2 = new DateTime(9999, 12, 31, 23, 59, 59); // Data "final": 31/12/9999 23:59:59 Console.WriteLine($"new DateTime(9999, 12, 31, 23, 59, 59): {d2.ToString()}"); DateTime d3 = new DateTime(2020, 8, 6); // 06/08/2020 00:00:00 Console.WriteLine($"new DateTime(2020, 8, 6): {d3.ToString()}"); DateTime d4 = new DateTime(2020, 8, 6, 8, 30, 0); // 06/08/2020 08:30:00 Console.WriteLine($"new DateTime(2020, 8, 6, 8, 30, 0): {d4.ToString()}"); //DateTime d5 = new DateTime(10000, 12, 31); // Data inválida - Ano inválido //DateTime d6 = new DateTime(2020, 02, 30); // Data inválida - Dia/Mês inválido // Ticks DateTime d7 = new DateTime(637329492389433409); // 13 / 08 / 2020 21:00:38 Console.WriteLine($"new DateTime(637329492389433409): {d7.ToString()}"); Console.WriteLine($"DateTime.MinValue.Ticks: {DateTime.MinValue.Ticks.ToString()}"); Console.WriteLine($"DateTime.MaxValue.Ticks: {DateTime.MaxValue.Ticks.ToString()}"); // Campos estáticos Console.WriteLine($"DateTime.Now: {DateTime.Now.ToString()}"); Console.WriteLine($"DateTime.Today: {DateTime.Today.ToString()}"); Console.WriteLine($"DateTime.UtcNow: {DateTime.UtcNow.ToString()}"); // TimeSpan DateTime d8 = DateTime.Now; TimeSpan ts1 = new TimeSpan(48, 30, 30); DateTime d9 = d8.Add(ts1); Console.WriteLine($"Now Add TimeSpan(48, 30, 30): {d9.ToString()}"); DateTime d10 = d8.Subtract(ts1); Console.WriteLine($"Now Subtract TimeSpan(48, 30, 30): {d10.ToString()}"); DateTime data1 = new DateTime(2020, 3, 22, 22, 55, 43, 422); DateTime data2 = new DateTime(2020, 8, 6, 14, 39, 10, 942); // Espaço de tempo entras as duas datas TimeSpan intervalo = data2 - data1; Console.WriteLine($"{data2} - {data1} = {intervalo.ToString()}"); Console.WriteLine($"Dias no intervalo: {intervalo.Days}"); Console.WriteLine($"Total de dias: {intervalo.TotalDays}"); Console.WriteLine($"Horas no intervalo: {intervalo.Hours}"); Console.WriteLine($"Total de horas: {intervalo.TotalHours}"); Console.WriteLine($"Minutos no intervalo: {intervalo.Minutes}"); Console.WriteLine($"Total de minutos: {intervalo.TotalMinutes}"); Console.WriteLine($"Segundos no intervalo: {intervalo.Seconds}"); Console.WriteLine($"Total de segundos: {intervalo.TotalSeconds}"); Console.WriteLine($"Milisegundos no intervalo: {intervalo.Milliseconds}"); Console.WriteLine($"Total de milisegundos: {intervalo.TotalMilliseconds}"); Console.WriteLine($"Ticks no intervalo: {intervalo.Ticks}"); // Criação de TimeSpan TimeSpan newTS = new TimeSpan(19, 55, 23); Console.WriteLine($"new TimeSpan(19, 55, 23): {newTS.ToString()}"); TimeSpan tsZero = TimeSpan.Zero; Console.WriteLine($"TimeSpan.Zero: {tsZero.ToString()}"); // Operações com DateTime e TimeSpan DateTime data_1 = new DateTime(2020, 3, 29); DateTime data_2 = new DateTime(2020, 11, 2, 14, 55, 2); TimeSpan timeSpan = new TimeSpan(14, 2, 55, 3); Console.WriteLine($"data_1: {data_1} - data_2: {data_2} - TimeSpan: {timeSpan}"); Console.WriteLine($"data_2 - data_1: {data_2 - data_1}"); Console.WriteLine($"data_1 == data_2: {data_1 == data_2}"); Console.WriteLine($"data_1 != data_2: {data_1 != data_2}"); Console.WriteLine($"data_1 < data_2: {data_1 < data_2}"); Console.WriteLine($"data_1 <= data_2: {data_1 <= data_2}"); Console.WriteLine($"data_1 > data_2: {data_1 > data_2}"); Console.WriteLine($"data_1 >= data_2: {data_1 >= data_2}"); Console.WriteLine($"data_2 + timeSpan: {data_2 + timeSpan}"); // Conversão de Date, Time e DateTime para String DateTime dataHora = DateTime.Now; Console.WriteLine("Data/Hora atual: " + dataHora.ToString()); Console.WriteLine("Formato MM/dd/yyyy: " + dataHora.ToString("MM/dd/yyyy")); Console.WriteLine("Formato dddd, dd MMMM yyyy: " + dataHora.ToString("dddd, dd MMMM yyyy")); Console.WriteLine("Formato MM/dd/yyyy h:mm: " + dataHora.ToString("MM/dd/yyyy h:mm")); Console.WriteLine("Formato MMMM dd:" + dataHora.ToString("MMMM dd")); Console.WriteLine("Formato HH:mm:ss: " + dataHora.ToString("HH:mm:ss")); Console.WriteLine("Short Date: " + dataHora.ToShortDateString()); Console.WriteLine("Long Date: " + dataHora.ToLongDateString()); Console.WriteLine("Short Time: " + dataHora.ToShortTimeString()); Console.WriteLine("Long Time: " + dataHora.ToLongTimeString()); // Conversão de String para Date, Time e DateTime string strDate1 = "06/08/2020"; Console.WriteLine(DateTime.Parse(strDate1).ToString()); string strDate2 = "31/02/2020"; if (DateTime.TryParse(strDate2, out dataHora)) { Console.WriteLine($"Data válida: {strDate2}"); } else { Console.WriteLine($"Data inválida: {strDate2}"); } // Outros métodos e propriedades de Date, Time e DateTime DateTime dateTime = DateTime.Now; Console.WriteLine($"Now AddDays(10): {dateTime.AddDays(10)}"); // Adicionar dias Console.WriteLine($"Now AddHours(72) {dateTime.AddHours(72)}"); // Adicionar horas Console.WriteLine($"Now AddMinutes(20): {dateTime.AddMinutes(20)}"); // Adicionar minutos Console.WriteLine($"Now AddSeconds(150): {dateTime.AddSeconds(150)}"); // Adicionar segundos Console.WriteLine($"Now AddTicks(9999999999): {dateTime.AddTicks(9999999999)}"); // Adicionar ticks Console.WriteLine($"dateTime.Hour: {dateTime.Hour}"); Console.WriteLine($"dateTime.Minute: {dateTime.Minute}"); Console.WriteLine($"dateTime.Second: {dateTime.Second}"); Console.WriteLine($"dateTime.Day: {dateTime.Day}"); Console.WriteLine($"dateTime.Month: {dateTime.Month}"); Console.WriteLine($"dateTime.Year: {dateTime.Year}"); Console.WriteLine($"dateTime.Ticks: {dateTime.Ticks}"); Console.WriteLine($"dateTime.DayOfWeek: {dateTime.DayOfWeek}"); // Dia da semana Console.WriteLine($"dateTime.DayOfYear: {dateTime.DayOfYear}"); // Dia do ano Console.WriteLine($"dateTime.TimeOfDay: {dateTime.TimeOfDay}"); // Hora atual Console.WriteLine($"dateTime.ToUniversalTime: {dateTime.ToUniversalTime()}"); // Obtém horário UTC Console.WriteLine($"dateTime.IsLeapYear(2020): {DateTime.IsLeapYear(2020)}"); // Verifica se é ano bisexto Console.WriteLine($"DateTime.DaysInMonth(2020, 8): {DateTime.DaysInMonth(2022, 2)}"); // Quantidade de dias em um ano/mês // Nullable DateTime DateTime?nullableDateTime = null; if (!nullableDateTime.HasValue) { Console.WriteLine("nullableDateTime sem valor atribuído"); } nullableDateTime = DateTime.Now; if (nullableDateTime.HasValue) { Console.WriteLine($"nullableDateTime: {nullableDateTime}"); } // Math Console.WriteLine($"Math.PI: {Math.PI}"); // Constante PI Console.WriteLine($"Math.E: {Math.E}"); // Constante E Console.WriteLine($"Math.Abs(-10): {Math.Abs(-10)}"); // Valor absoluto Console.WriteLine($"Math.Round(99.99): {Math.Round(99.99)}"); // Arredondamento Console.WriteLine($"Math.Round(99.98765, 2): {Math.Round(99.98765, 2)}"); // Arredondamento Console.WriteLine($"Math.DivRem(200, 30): {Math.DivRem(200, 30, out int resto)} - Resto: {resto}"); // Divisão e resto no mesmo método Console.WriteLine($"Math.Sqrt(196): {Math.Sqrt(196)}"); // Raiz quadrada Console.WriteLine($"Math.Max(300, 301): {Math.Max(300, 301)}"); // Maior valor Console.WriteLine($"Math.Min(300, 301): {Math.Min(300, 301)}"); // Menor valor Console.WriteLine($"Math.Truncate(99.99): {Math.Truncate(99.99)}"); // Parte integral Console.WriteLine($"Math.Pow(2, 10): {Math.Pow(2, 10)}"); // Exponenciação Console.WriteLine($"Math.Sin(50): {Math.Sin(50)}"); // Seno Console.WriteLine($"Math.Cos(200): {Math.Cos(200)}"); // Cosseno Console.WriteLine($"Math.Tan(150): {Math.Tan(150)}"); // Tangente Console.WriteLine($"Math.Exp(5): {Math.Exp(5)}"); // Exponenciação de E Console.WriteLine($"Math.Log(100): {Math.Log(100)}"); // Logaritmo Console.WriteLine($"Math.Log10(100): {Math.Log10(100)}"); // Logaritmo base 10 Console.ReadLine(); }
/// <summary> /// Retrieves a clean working directory for use by a testing method /// </summary> /// <param name="baseDirectory">The root folder where the Test subdirectory will be created</param> /// <param name="depth">Frame depth used to retrieve the name of the test directory</param> /// <param name="setWorkingDirectory">Should the current working directory be changed?</param> /// <returns>A full directory path pointing to the root location on disk suitable for a unit test</returns> protected string GetMethodSpecificWorkingDirectory(string baseDirectory, int depth, bool setWorkingDirectory) { var stackTrace = new System.Diagnostics.StackTrace(); // This handles anonymous method invokation and the two frames added by using it var method = stackTrace.GetFrame(depth).GetMethod(); if (method.DeclaringType.FullName.IndexOf("<>") >= 0) { method = stackTrace.GetFrame(depth + 2).GetMethod(); } // handle any number of nested lambda functions if (System.Text.RegularExpressions.Regex.IsMatch(method.Name, "\\<.*\\>", System.Text.RegularExpressions.RegexOptions.IgnoreCase)) { var tmpDepth = depth; while (System.Text.RegularExpressions.Regex.IsMatch(method.Name, "\\<.*\\>", System.Text.RegularExpressions.RegexOptions.IgnoreCase)) { tmpDepth += 2; method = stackTrace.GetFrame(tmpDepth).GetMethod(); } } var methodEncapsulatingClass = method.DeclaringType; var methodEncapsulatingClassName = TrimStringFromEnd(methodEncapsulatingClass.Name, "Method", true); var encapsulatingClass = methodEncapsulatingClass.BaseType; var encapsulatingClassName = TrimStringFromEnd(encapsulatingClass.Name, "Tests", true); // SystemTests // calculate a shortened file structure path when the folder path exceeds OS limits // NOTE: It is still possible the base directory location is too long and failure could still occur var finalBase = System.IO.Path.Combine(baseDirectory, "Tests", encapsulatingClassName); var md5hash = string.Empty; if (finalBase.Length + methodEncapsulatingClassName.Length + method.Name.Length + 3 >= 247) { using (var hash = System.Security.Cryptography.MD5.Create()) { var tmp = methodEncapsulatingClassName + "\\" + method.Name; var bytes = hash.ComputeHash(System.Text.Encoding.UTF8.GetBytes(tmp)); md5hash = new System.Guid(bytes).ToString(); } } var finalDirectory = string.IsNullOrWhiteSpace(md5hash) ? System.IO.Path.Combine(finalBase, methodEncapsulatingClassName, method.Name) : System.IO.Path.Combine(finalBase, md5hash); // https://social.technet.microsoft.com/Forums/windows/en-US/43945b2c-f123-46d7-9ba9-dd6abc967dd4/maximum-path-length-limitation-on-windows-is-255-or-247?forum=w7itprogeneral if (finalDirectory.Length >= 247) { throw new ArgumentException("Unable to create testing directory because it is too long: " + finalDirectory); } if (setWorkingDirectory) { System.IO.Directory.CreateDirectory(finalDirectory); System.IO.Directory.SetCurrentDirectory(finalDirectory); } return(finalDirectory); }
public MessagePacket(string message, LogType logType, Dictionary <string, string> tags, System.Diagnostics.StackTrace stackTrace) : base(message, tags) { this.m_level = ToLogLevelFromLogType(logType); if (stackTrace != null) { m_stacktrace = new RavenStackTrace(stackTrace); } }
public ExceptionPacket(string message, System.Diagnostics.StackTrace stackTrace, Dictionary <string, string> tags) : base(message, tags) { this.m_exception = new RavenException(message, stackTrace); }
private void PrintLog() { System.Diagnostics.StackTrace pTrace = new System.Diagnostics.StackTrace(); UnityEngine.Debug.Log(string.Format("{0} - CObjectBaseTest", pTrace.GetFrame(1).GetMethod())); }
public long InsertDB(object[] dataList, string[] tableCols, string tableName, bool autoTrun = true) { Dictionary <string, int> colInfo = new Dictionary <string, int> { }; int eachRound; bool proceed = false; logMsg = new List <string> { }; List <int> overlongRow = new List <int> { }; long id = 0; eachRound = Convert.ToInt32(2099 / (tableCols.Length)); if ((eachRound - (2099 / tableCols.Length)) > 0) { eachRound = eachRound - 1; } GetColumns(tableName, colInfo); for (int i = 0; i < dataList.Length; i = i + eachRound) { string sSQL = "INSERT INTO " + tableName + " ("; try { SqlCommand objCmd = new SqlCommand(); objCmd.Connection = objConn; //loop table column foreach (var col in tableCols) { sSQL += "[" + col.Trim() + "],"; } sSQL = sSQL.Substring(0, sSQL.Length - 1); sSQL += ") VALUES "; //loop data for (int j = 0; j < eachRound; j++) { if (i + j >= dataList.Length) { break; } PropertyInfo[] properties = dataList[i + j].GetType().GetProperties(); //check if too long bool valid = true; if (!autoTrun || true) { for (int k = 0; k < tableCols.Length; k++) { string col = tableCols[k].Trim(); foreach (PropertyInfo property in properties) { if (col == property.Name && colInfo.ContainsKey(col)) { if (property.PropertyType == typeof(String)) { string value = (string)(property.GetValue(dataList[i + j])); if (!string.IsNullOrEmpty(value)) { if (value.Length > colInfo[col]) { Logger.Logger.WriteLog(value + " is too long for " + col); logMsg.Add(value + " is too long for " + col); if (!autoTrun) { valid = false; } else { string cutValue = value.Substring(0, colInfo[col] - 1); property.SetValue(dataList[i + j], cutValue); } } } } } } } } if (!valid) { continue; } proceed = true; //add sql sSQL += "("; foreach (var col in tableCols) { sSQL += "@" + col + "_" + j.ToString() + ","; } sSQL = sSQL.Substring(0, sSQL.Length - 1); sSQL += "),"; //bind parameters for (int k = 0; k < tableCols.Length; k++) { foreach (PropertyInfo property in properties) { if (tableCols[k] == property.Name) { object value = property.GetValue(dataList[i + j]); if (value != null) { objCmd.Parameters.AddWithValue((tableCols[k] + "_" + j.ToString()), value); } else { objCmd.Parameters.AddWithValue((tableCols[k] + "_" + j.ToString()), DBNull.Value); } } } } } //execute if (proceed) { sSQL = sSQL.Substring(0, sSQL.Length - 1); objCmd.CommandText = sSQL; objCmd.ExecuteNonQuery(); if (i == 0) { id = objCmd.LastInsertedId; } } } catch (Exception e) { // Get stack trace for the exception with source file information var st = new System.Diagnostics.StackTrace(e, true); // Get the top stack frame var frame = st.GetFrame(0); // Get the line number from the stack frame var line = frame.GetFileLineNumber(); Logger.Logger.WriteLog(e); } } return(id); }
public static IEnumerable <CodeInstruction> PatchBySequence(IEnumerable <CodeInstruction> instructions, IEnumerable <CodeInstruction> targetSequence, IEnumerable <CodeInstruction> patchSequence, PatchMode patchMode = PatchMode.AFTER, CheckMode checkMode = CheckMode.ALWAYS, bool showDebugOutput = false) { List <CodeInstruction> Instructions = instructions.ToList(); //create new list to be modified and returned. CodeInstruction targetStart = targetSequence.ElementAt(0); int targetSize = targetSequence.Count(); for (int i = 0; i < Instructions.Count; i++) //Check every Instruction in the given list if it is the correct Instruction set { bool targetSequenceStillFits = i + targetSize <= Instructions.Count; //calculate if target sequence fits in Instructions. if (targetSequenceStillFits) //stop if not enough lines capable of fitting target sequence { bool foundTargetSequence = true; for (int x = 0; x < targetSize && foundTargetSequence; x++) //compare each element of the new sequence to the old to see if it is the same. stop for loop early if the targetsequence { foundTargetSequence = Instructions[i + x].opcode.Equals(targetSequence.ElementAt(x).opcode); if (checkMode != CheckMode.NEVER)//if specified checking params are set appropriately, check opperand. CheckMode enum comes into play here. { foundTargetSequence = foundTargetSequence && ( ((Instructions[i + x].operand == null || checkMode == CheckMode.NONNULL) && targetSequence.ElementAt(x).operand == null) || Instructions[i + x].operand.Equals(targetSequence.ElementAt(x).operand) ); } if (showDebugOutput && foundTargetSequence) { Logger.Info($"Found {targetSequence.ElementAt(x).opcode} at {i + x}"); } } if (foundTargetSequence) //If the TargetSequence was found in the Instructions, Replace at the i index. { if (patchMode == PatchMode.BEFORE || patchMode == PatchMode.AFTER) { int indexToInsertAt = patchMode == PatchMode.AFTER ? i + targetSize : i; Instructions.InsertRange(indexToInsertAt, patchSequence.Select(c => c.FullClone())); } else if (patchMode == PatchMode.REPLACE) { Instructions.RemoveRange(i, targetSize); Instructions.InsertRange(i, patchSequence.Select(c => c.FullClone())); } else { throw new ArgumentException($"Argument PatchMode patchMode == {patchMode}; invalid value!"); } break; } } else //if targetsequence didn't fit in what was left of array (couldn't find target sequence) { StringBuilder sb = new StringBuilder(); sb.AppendLine($"Failed to patch by sequence: couldn't find target sequence. This might be okay in certain cases."); // Cut down the stack trace because it's 20 lines of unhelpful reflection internals. // Show enough to figure out which mod + transpiler method is causing this: sb.AppendLine($"Stack Trace:"); string[] stackTrace = new System.Diagnostics.StackTrace().ToString().Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None); for (int lineNumber = 0; lineNumber < 2; lineNumber++) { sb.AppendLine(stackTrace[lineNumber]); } Logger.Info(sb.ToString()); break; } } return(Instructions.AsEnumerable()); }
protected void RenderInformation() { Client.Session session = MercuryApplication.Session; Page.Title = session.UserDisplayName + " [" + session.UserAccountId + " : " + session.UserAccountName + "]"; DebugWriteLine("Security Authority: " + session.SecurityAuthorityName + " (" + session.SecurityAuthorityId.ToString() + ")"); DebugWriteLine("User: "******" [" + session.UserAccountId + " : " + session.UserAccountName + "]"); DebugWriteLine("Environment Name: " + session.EnvironmentName); DebugWriteLine(String.Empty); DebugWriteLine("Client Version: " + MercuryApplication.VersionClient); DebugWriteLine("Server Version: " + MercuryApplication.VersionServer); DebugWriteLine(String.Empty); DebugWriteLine("Enterprise Permissions: "); foreach (String currentPermission in session.EnterprisePermissionSet.Keys) { DebugWriteLine(currentPermission); } DebugWriteLine(String.Empty); DebugWriteLine("Environment Permissions: "); foreach (String currentPermission in session.EnvironmentPermissionSet.Keys) { DebugWriteLine(currentPermission); } DebugWriteLine(String.Empty); DebugWriteLine("Work Teams: "); foreach (Client.Core.Work.WorkTeam currentWorkTeam in MercuryApplication.WorkTeamsForSession(false)) { DebugWriteLine(currentWorkTeam.Name); } DebugWriteLine(String.Empty); DebugWriteLine("Work Queues: "); foreach (Int64 currentWorkQueueId in MercuryApplication.Session.WorkQueuePermissions.Keys) { Client.Core.Work.WorkQueue currentWorkQueue = MercuryApplication.WorkQueueGet(currentWorkQueueId, false); DebugWriteLine(currentWorkQueue.Name + " (" + MercuryApplication.Session.WorkQueuePermissions[currentWorkQueueId].ToString() + ")"); } DebugWriteLine(String.Empty); DebugWriteLine("Role Membership: "); foreach (String currentMembership in session.RoleMembership) { DebugWriteLine(currentMembership); } DebugWriteLine(String.Empty); DebugWriteLine("Security Group Membership: "); foreach (String currentMembership in session.GroupMembership) { DebugWriteLine(currentMembership); } DebugWriteLine(String.Empty); if (MercuryApplication.LastException != null) { Exception lastException = MercuryApplication.LastException; if (lastException != null) { DebugWriteLine("Client.Application [" + lastException.Source + "] " + lastException.Message); if (lastException.InnerException != null) { DebugWriteLine("Client.Application [" + lastException.InnerException.Source + "] " + lastException.InnerException.Message); } DebugWriteLine("** Stack Trace **"); System.Diagnostics.StackTrace debugStack = new System.Diagnostics.StackTrace(); foreach (System.Diagnostics.StackFrame currentStackFrame in debugStack.GetFrames()) { DebugWriteLine(" [" + currentStackFrame.GetMethod().Module.Assembly.FullName + "] " + currentStackFrame.GetMethod().Name); } } // if (lastException != null) } return; }
private bool HidingAllowed(object sender) { System.Diagnostics.StackTrace callStack = new System.Diagnostics.StackTrace(); bool HidingAllowed = true; string m = string.Empty; foreach (var timer in m_OtherTimers) { if ((timer.Value != null) && (timer.Value == sender)) { HidingAllowed = false; m = timer.Key; break; } } if (HidingAllowed) { for (int i = 0; i < callStack.FrameCount; i++) { System.Reflection.MethodBase mbMethod = callStack.GetFrame(i).GetMethod(); string methodname = mbMethod.Name; HidingAllowed &= methodname != "ShowExpiredEntries"; if (!Config.ProgressiveHidingAllowedCheck) { HidingAllowed &= !methodname.StartsWith("OnPwList"); } HidingAllowed &= !methodname.StartsWith("OnFind"); HidingAllowed &= methodname != "PerformQuickFind"; //KeePass <= 2.46 HidingAllowed &= !methodname.StartsWith("PerformSearch"); //KeePass >= 2.47 HidingAllowed &= methodname != "ShowSearchResults"; //KeePass >= 2.47 if ((mbMethod.DeclaringType.FullName == "GlobalSearch.GlobalSearchExt") && methodname.StartsWith("OnClickFindEntry")) { HidingAllowed = false; methodname = mbMethod.DeclaringType.Namespace + "-" + methodname; } if ((mbMethod.Name == "RefreshEntriesList") && (mbMethod.DeclaringType.FullName == "PluginTools.Tools") && Tools.PreserveEntriesShown) { HidingAllowed = false; methodname = mbMethod.DeclaringType.Namespace + "-" + methodname; } //HidingAllowed &= methodname != "OpenDatabase"; //HidingAllowed &= methodname != "OnFileLock"; if (methodname == "UpdateUIState") { if ((mbMethod.DeclaringType.FullName == "PluginTools.Tools") && Program.Config.CustomConfig.GetBool("Rookiestyle.PreserveEntriesShown", true)) { HidingAllowed = false; methodname = mbMethod.DeclaringType.Namespace + "-" + methodname; } else if (i < callStack.FrameCount - 1) { methodname = callStack.GetFrame(i + 1).GetMethod().Name; if (methodname == "WndProc") { HidingAllowed = false; methodname = "WndProc - message: m_nTaskbarButtonMessage"; } } } if (!HidingAllowed) { m = methodname; break; } } } List <string> lMsg = new List <string>(); lMsg.Add("Active:" + Config.HideExpired.ToString()); lMsg.Add("Progressive hiding check:" + Config.ProgressiveHidingAllowedCheck.ToString()); //Progressive = Remember setting //Reset only if current callstack does not allow hiding expired entries if (Config.ProgressiveHidingAllowedCheck) { if (!HidingAllowed) { Config.ProgressiveHidingAllowed = Config.HidingStatus.NotAllowed; if (!string.IsNullOrEmpty(m)) { lMsg.Add("Found method: " + m); } else { lMsg.Add("Reuse previous check result: " + true.ToString()); } } //Set hiding status if not yet defined if (Config.ProgressiveHidingAllowed == Config.HidingStatus.Unknown) { if (HidingAllowed) { Config.ProgressiveHidingAllowed = Config.HidingStatus.Allowed; } else { Config.ProgressiveHidingAllowed = Config.HidingStatus.NotAllowed; lMsg.Add("Found method: " + m); } } lMsg.Add("Hiding possible: " + (Config.ProgressiveHidingAllowed == Config.HidingStatus.Allowed).ToString() + " - " + HidingAllowed.ToString()); PluginDebug.AddInfo("Hiding of expired entries", 0, lMsg.ToArray()); return(Config.ProgressiveHidingAllowed == Config.HidingStatus.Allowed); } if (!HidingAllowed) { lMsg.Add("Found method: " + m); } lMsg.Add("Hiding possible:" + HidingAllowed.ToString()); PluginDebug.AddInfo("Hiding of expired entries", 0, lMsg.ToArray()); return(HidingAllowed); }
public static void Benchmark(Action codeToTest) { // Up the thread priority. var priorPriority = System.Threading.Thread.CurrentThread.Priority; System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Highest; try { // Get the test name from a stack trace. var testName = new System.Diagnostics.StackTrace().GetFrame(1).GetMethod().Name; // Measure the test overhead. Action emptyAction = () => { }; var stopWatch = System.Diagnostics.Stopwatch.StartNew(); for (int i = 0; i < 100; i++) { emptyAction(); } long overheadInTicks = stopWatch.ElapsedTicks / 100; // Make sure the code is jitted. codeToTest(); // Run the test a number of times. long totalTimeRemaining = System.Diagnostics.Stopwatch.Frequency * 2; var elapsedTimes = new List <long>(); while (totalTimeRemaining > 0) { // Reset the stopwatch. stopWatch.Reset(); stopWatch.Start(); // Run the code to test. codeToTest(); // Record the time taken. long elapsed = Math.Max(stopWatch.ElapsedTicks - overheadInTicks, 0); elapsedTimes.Add(elapsed); // Collect all garbage. System.GC.Collect(); // Check if we have run for the required amount of time. totalTimeRemaining -= stopWatch.ElapsedTicks; } double average = elapsedTimes.Average(); //double variance = elapsedTimes.Select(e => Math.Pow(average - e, 2)).Average(); //double deviation = Math.Sqrt(variance); double min = Math.Sqrt(elapsedTimes.Where(e => e <= average).Select(e => Math.Pow(average - e, 2)).Average()); double max = Math.Sqrt(elapsedTimes.Where(e => e >= average).Select(e => Math.Pow(average - e, 2)).Average()); // Convert to milliseconds. double ticksToMilliseconds = 1000.0 / (double)System.Diagnostics.Stopwatch.Frequency; average *= ticksToMilliseconds; //variance *= ticksToMilliseconds; //deviation *= ticksToMilliseconds; min *= ticksToMilliseconds; max *= ticksToMilliseconds; // Output the time taken. //Console.WriteLine("Performance test '{0}' took {1:f1} ± {2:f1} milliseconds.", testName, average, deviation * 2); for (int i = 0; i < elapsedTimes.Count; i++) { Console.WriteLine("Test #{0}: {1:f1} milliseconds.", i + 1, elapsedTimes[i] * ticksToMilliseconds); } // Show the results in the unit test error message column. #if !NUNIT throw new AssertInconclusiveException(string.Format("{0}: {1:f1} operations/sec (± {2:f1})", testName, 1000.0 / average, (1000.0 / (average - min) - 1000.0 / (average + max)) / 2)); #endif //if (testName != null) //{ // string outputDir = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(typeof(AssertUtils).Assembly.Location), @"..\..\..\Performance Tests\"); // if (System.IO.Directory.Exists(outputDir) == false) // System.IO.Directory.CreateDirectory(outputDir); // string outputPath = System.IO.Path.Combine(outputDir, testName + ".csv"); // if (System.IO.File.Exists(outputPath) == false) // System.IO.File.WriteAllText(outputPath, "Time,Sample,Variance"); // System.IO.File.AppendAllText(outputPath, string.Format("\r\n{0:yyyy'-'MM'-'dd HH':'mm':'ss},{1:f1},{2:f1}", DateTime.Now, average, deviation)); //} } finally { // Revert the thread priority. System.Threading.Thread.CurrentThread.Priority = priorPriority; } }
/// <summary> /// Utility method that retrieves a method-specific logger at the specified frame /// </summary> /// <param name="frame">The frame level to name the logger</param> /// <returns>A log4net logging object named for the specified stack frame method</returns> protected log4net.ILog GetMethodLogger(int frame) { var stackTrace = new System.Diagnostics.StackTrace(); return(log4net.LogManager.GetLogger(stackTrace.GetFrame(frame).GetMethod().Name)); }
public void EndLog() { try { string componentName = new System.Diagnostics.StackTrace().GetFrames()[1].GetMethod().DeclaringType.FullName.Split('.')[1]; componentName = Path.GetFileNameWithoutExtension(componentName); DateTime finishTime = DateTime.Now; if (finalResult == true) { this.AddTag("TEXT", "<TESTCASERESULT>PASS</TESTCASERESULT>"); } else { this.AddTag("TEXT", "<TESTCASERESULT>FAIL</TESTCASERESULT>"); } this.AddTag("TESTCASEEXECUTIONTIME", (finishTime - startTime).ToString() + " (hh:mm:ss.MSec)"); this.AddTag("TESTCASEFINISHTIME", finishTime.ToString("G", CultureInfo.InvariantCulture)); this.AddTag("TEXT", "</TESTCASE>"); this.AddTag("TEXT", "</TESTCASES>"); #region Add Test case execution summary in the log if (File.Exists(resultLogFile)) { // Figure out PASS,FAIL,ERROR and EXCEPTION test cases in the existing log int tcCounter = 0; int passCounter = 0; int failCounter = 0; int errorCounter = 0; int exceptionCounter = 0; // Set to maximum DateTime firstTcStartTime = DateTime.MaxValue; TimeSpan totalExecutionTime = TimeSpan.Zero; StreamReader sr = new StreamReader(resultLogFile); string line = string.Empty; while ((line = sr.ReadLine()) != null) { if (line.Equals("")) { continue; } else if (line.Equals("</TESTCASE>")) { tcCounter++; } else if (line.StartsWith("<TESTCASERESULT>")) { if (line.IndexOf("PASS") > 0) { passCounter++; } else if (line.IndexOf("FAIL") > 0) { failCounter++; } } else if (line.StartsWith("<ERROR>")) { errorCounter++; } else if (line.StartsWith("<EXCEPTION>")) { exceptionCounter++; } else if (line.IndexOf("<EXECUTIONTIME>") > -1) { string[] tmp = line.Split('>'); tmp = tmp[1].Split('<'); tmp = tmp[0].Split(' '); TimeSpan currentTimeSpan = TimeSpan.Parse(tmp[0]); totalExecutionTime += currentTimeSpan; } } sr.Close(); // Now add the counts in the log file string tmpFile = Path.Combine(Environment.GetEnvironmentVariable("TMP"), "tmpfile"); StreamWriter sw = new StreamWriter(tmpFile, false); sr = new StreamReader(resultLogFile); line = string.Empty; string f = componentName; string[] strTmp = null; if (f.IndexOf("_") > -1) { strTmp = f.Split('_'); } while ((line = sr.ReadLine()) != null) { sw.WriteLine(line); if (line.Equals("<TESTCASES>") || line.Equals("<TestExecutionDetails>")) { sw.WriteLine("<TESTCASESUMMARY>"); if (strTmp != null) { f = string.Empty; foreach (string t in strTmp) { if (t.IndexOf("TestExecution") > -1) { f += t.Substring("TestExecution".Length); } else { f += t; } f += " "; } } sw.WriteLine("<COMPONENTNAME>" + f.Trim() + "</COMPONENTNAME>"); sw.WriteLine("<DATETIME>" + DateTime.Now.ToString("dd-MMM-yyyy hh:mm:ss") + "</DATETIME>"); sw.WriteLine("<TOTAL>" + Convert.ToInt32(tcCounter) + "</TOTAL>"); sw.WriteLine("<ALLPASS>" + Convert.ToInt32(passCounter) + "</ALLPASS>"); sw.WriteLine("<ALLFAIL>" + Convert.ToInt32(failCounter) + "</ALLFAIL>"); sw.WriteLine("<ALLERROR>" + Convert.ToInt32(errorCounter) + "</ALLERROR>"); sw.WriteLine("<ALLEXCEPTION>" + Convert.ToInt32(exceptionCounter) + "</ALLEXCEPTION>"); sw.WriteLine("<TOTALEXECUTION>" + totalExecutionTime.ToString() + " (hh:mm:ss.MSec)" + "</TOTALEXECUTION>"); sw.WriteLine("<BUILDVersion>" + buildNumber + "</BUILDVersion>"); sw.WriteLine("<SITEVersion>" + buildNumber + "</SITEVersion>"); //sw.WriteLine("<BINDING>" + bindingName + "</BINDING>"); sw.WriteLine("<HOSTPLATFORM>" + hostPlatform + "</HOSTPLATFORM>"); sw.WriteLine("<CLIENTPLATFORM>" + clientPlatform + "</CLIENTPLATFORM>"); sw.WriteLine("<HOSTIP>" + hostIp + "</HOSTIP>"); sw.WriteLine("<CLIENTIP>" + clientIp + "</CLIENTIP>"); sw.WriteLine("</TESTCASESUMMARY>"); while ((line = sr.ReadLine()) != null) { if (line.Equals("<TESTCASE>")) { sw.WriteLine(line); break; } else { continue; } } } } sw.Close(); sr.Close(); File.Delete(resultLogFile); File.Move(tmpFile, resultLogFile); } #endregion this.AddTag("PLAIN", "========================================================================"); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
private void btOK_Click(object sender, EventArgs e) { try { if (rbExclude.Checked) { //добавление причины отчисления если ее нет и сохранение if (cbList.Text != String.Empty) { Cause currentCause; if (cbList.SelectedIndex == -1 && cbList.Text != String.Empty) { cbList.Text = cbList.Text.Substring(0, 1).ToUpper() + cbList.Text.Substring(1); currentCause = db.Causes.FirstOrDefault(a => a.Name == cbList.Text && a.IsRemoved == false); if (currentCause == null) { var newCause = new Cause() { Name = cbList.Text }; db.Causes.Add(newCause); db.SaveChanges(); } currentCause = db.Causes.FirstOrDefault(a => a.Name == cbList.Text && a.IsRemoved == false); enroll.CauseId = currentCause.Id; } else { enroll.CauseId = Convert.ToInt32(cbList.SelectedValue); } enroll.ExclusionId = CurrentSession.CurrentUser.Id; enroll.DateExclusion = DateTime.Now; enroll.MonthExclusionId = Convert.ToInt32(cbMonths.SelectedValue); enroll.Note = "Отчислен"; db.Entry(enroll).State = System.Data.Entity.EntityState.Modified; int i = db.SaveChanges(); Close(); } else { MessageBox.Show("Не указана причина отчисления", "Внимание", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } else { //добавление записи о старой группе var oldEnrollment = new Enrollment { DateEnrollment = enroll.DateEnrollment, Transfer = true, DateExclusion = DateTime.Now, ExclusionId = CurrentSession.CurrentUser.Id, Note = string.Format("Переведен в группу {0}", cbGroups.Text), StudentId = enroll.StudentId, GroupId = enroll.GroupId, EnrollId = enroll.EnrollId, NumberDocument = enroll.NumberDocument, PrivilegeId = enroll.PrivilegeId }; db.Enrollments.Add(oldEnrollment); //обновление текущей записи о группе (переписываем данные о группе при переводе, чтобы платежи сохранились) var oldGroup = db.Groups.Find(enroll.GroupId); enroll.Note = string.Format("Переведен из группы {0}", oldGroup.Name); //enroll.DateEnrollment = DateTime.Now; enroll.EnrollId = CurrentSession.CurrentUser.Id; enroll.GroupId = Convert.ToInt32(cbGroups.SelectedValue); enroll.ExclusionId = null; enroll.DateExclusion = null; enroll.PrivilegeId = null; enroll.NumberDocument = null; db.Entry(enroll).State = System.Data.Entity.EntityState.Modified; db.SaveChanges(); //обновление занятий и оценок при переводе if (chbSaveGrades.Checked) { //Получение списка занятий из новой группы var lessonsNew = db.Lessons.Where(a => a.GroupId == enroll.GroupId).OrderBy(a => a.Number).ToList(); //получение оценок из старой группы var gradesOld = db.Studies.Include("Lesson").Where(a => a.GroupId == oldEnrollment.GroupId && a.StudentId == enroll.StudentId) .OrderBy(a => a.Lesson.Number).ToList(); //замена занятий в списке оценок for (var j = 0; j < lessonsNew.Count; j++) { for (var i = 0; i < gradesOld.Count; i++) { if (gradesOld[i].Lesson.Number == lessonsNew[j].Number) { gradesOld[i].LessonId = lessonsNew[j].Id; gradesOld[i].GroupId = Convert.ToInt32(enroll.GroupId); break; } } } } //////////удаление старого и добавление нового графика платежей/////////// //получение старого графика var scheds = db.Schedules.Where(a => a.EnrollmentId == enroll.Id).ToList(); //перезапись id записи в группу для старого графика платежей foreach (var s in scheds) { s.EnrollmentId = oldEnrollment.Id; db.Entry(s).State = System.Data.Entity.EntityState.Modified; } //добавление нового графика происходит в форме студента при записи в группу db.SaveChanges(); Close(); } } catch (Exception ex) { var m = new System.Diagnostics.StackTrace(false).GetFrame(0).GetMethod(); string methodName = m.DeclaringType.ToString() + ";" + m.Name; CurrentSession.ReportError(methodName, ex.Message); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
/// <summary> /// Save BCF 1.0 as BCF 2.0 /// </summary> /// <param name="bcf1">BCF 1.0 file</param> public static void SaveBcf2FromBcf1(BCF bcf1) { try { BCF2.BcfFile bcf2 = new BCF2.BcfFile(); bcf2.TempPath = bcf1.path; // replace temp path with BCF 1.0's // bcf2.ProjectName = ; // from Jira? // bcf2.ProjectId = ; // from Jira? // Add issues (markups) foreach (IssueBCF bcf1Issue in bcf1.Issues) { // Convert header files List <BCF2.HeaderFile> bcf2Headers = new List <BCF2.HeaderFile>(); if (bcf1Issue.markup.Header != null) { foreach (HeaderFile bcf1Header in bcf1Issue.markup.Header) { bcf2Headers.Add(new BCF2.HeaderFile() { Date = bcf1Header.Date, Filename = bcf1Header.Filename, IfcProject = bcf1Header.IfcProject, IfcSpatialStructureElement = bcf1Header.IfcSpatialStructureElement, isExternal = true, // default true for now Reference = "" // default empty for now }); } } // Convert Comments ObservableCollection <BCF2.Comment> bcf2Comments = new ObservableCollection <BCF2.Comment>(); if (bcf1Issue.markup.Comment != null) { foreach (CommentBCF bcf1Comment in bcf1Issue.markup.Comment) { if (bcf1Comment != null) { bcf2Comments.Add(new BCF2.Comment() { Author = bcf1Comment.Author, Comment1 = bcf1Comment.Comment1, Date = bcf1Comment.Date, Guid = bcf1Comment.Guid, ModifiedAuthor = bcf1Comment.Author, // default the same as author for now //ModifiedDate = null, // mismatch attribute ReplyToComment = null, // mismatch attribute Status = bcf1Comment.Status.ToString(), Topic = new BCF2.CommentTopic() { Guid = bcf1Issue.markup.Topic.Guid }, // all referenced to markup's topic VerbalStatus = bcf1Comment.VerbalStatus, Viewpoint = null // mismatch attribute }); } } } // Convert Topic BCF2.Topic bcf2Topic = new BCF2.Topic() { AssignedTo = null, // mismatch attribute BimSnippet = null, // mismatch attribute CreationAuthor = null, // mismatch attribute //CreationDate = null, // mismatch attribute Description = null, // mismatch attribute DocumentReferences = null, // mismatch attribute Guid = bcf1Issue.markup.Topic.Guid, Index = null, // mismatch attribute Labels = null, // mismatch attribute ModifiedAuthor = null, // mismatch attribute //ModifiedDate = , // mismatch attribute Priority = null, // mismatch attribute ReferenceLink = bcf1Issue.markup.Topic.ReferenceLink, RelatedTopics = null, // mismatch attribute Title = bcf1Issue.markup.Topic.Title, TopicStatus = null, // mismatch attribute TopicType = null // mismatch attribute }; // Convert ClippingPlane List <BCF2.ClippingPlane> bcf2ClippingPlanes = new List <BCF2.ClippingPlane>(); if (bcf1Issue.viewpoint.ClippingPlanes != null) { foreach (ClippingPlane bcf1ClippingPlane in bcf1Issue.viewpoint.ClippingPlanes) { if (bcf1ClippingPlane != null) { bcf2ClippingPlanes.Add(new BCF2.ClippingPlane() { Direction = new BCF2.Direction() { X = bcf1ClippingPlane.Direction.X, Y = bcf1ClippingPlane.Direction.Y, Z = bcf1ClippingPlane.Direction.Z }, Location = new BCF2.Point() { X = bcf1ClippingPlane.Location.X, Y = bcf1ClippingPlane.Location.Y, Z = bcf1ClippingPlane.Location.Z } }); } } } // Convert Components List <BCF2.Component> bcf2Components = new List <BCF2.Component>(); if (bcf1Issue.viewpoint.Components != null) { foreach (Component bcf1Component in bcf1Issue.viewpoint.Components) { if (bcf1Component != null) { bcf2Components.Add(new BCF2.Component() { AuthoringToolId = bcf1Component.AuthoringToolId, // Color = bcf1Component, // mismatch attribute IfcGuid = bcf1Component.IfcGuid, OriginatingSystem = bcf1Component.OriginatingSystem // Selected = bcf1Component, // mismatch attribute // Visible = bcf1Component // mismatch attribute }); } } } // Convert Lines List <BCF2.Line> bcf2Lines = new List <BCF2.Line>(); if (bcf1Issue.viewpoint.Lines != null) { foreach (Line bcf1Line in bcf1Issue.viewpoint.Lines) { if (bcf1Line != null) { bcf2Lines.Add(new BCF2.Line() { StartPoint = new BCF2.Point() { X = bcf1Line.StartPoint.X, Y = bcf1Line.StartPoint.Y, Z = bcf1Line.StartPoint.Z }, EndPoint = new BCF2.Point() { X = bcf1Line.EndPoint.X, Y = bcf1Line.EndPoint.Y, Z = bcf1Line.EndPoint.Z } }); } } } // Convert VisualizationInfo BCF2.VisualizationInfo bcf2VizInfo = new BCF2.VisualizationInfo() { Bitmaps = null, // default null ClippingPlanes = bcf2ClippingPlanes.ToArray(), Components = bcf2Components, Lines = bcf2Lines.ToArray(), OrthogonalCamera = bcf1Issue.viewpoint.OrthogonalCamera == null ? null : new BCF2.OrthogonalCamera() { CameraDirection = new BCF2.Direction() { X = bcf1Issue.viewpoint.OrthogonalCamera.CameraDirection.X, Y = bcf1Issue.viewpoint.OrthogonalCamera.CameraDirection.Y, Z = bcf1Issue.viewpoint.OrthogonalCamera.CameraDirection.Z }, CameraUpVector = new BCF2.Direction() { X = bcf1Issue.viewpoint.OrthogonalCamera.CameraUpVector.X, Y = bcf1Issue.viewpoint.OrthogonalCamera.CameraUpVector.Y, Z = bcf1Issue.viewpoint.OrthogonalCamera.CameraUpVector.Z }, CameraViewPoint = new BCF2.Point() { X = bcf1Issue.viewpoint.OrthogonalCamera.CameraViewPoint.X, Y = bcf1Issue.viewpoint.OrthogonalCamera.CameraViewPoint.Y, Z = bcf1Issue.viewpoint.OrthogonalCamera.CameraViewPoint.Z }, ViewToWorldScale = bcf1Issue.viewpoint.OrthogonalCamera.ViewToWorldScale }, PerspectiveCamera = bcf1Issue.viewpoint.PerspectiveCamera == null ? null : new BCF2.PerspectiveCamera() { CameraDirection = new BCF2.Direction() { X = bcf1Issue.viewpoint.PerspectiveCamera.CameraDirection.X, Y = bcf1Issue.viewpoint.PerspectiveCamera.CameraDirection.Y, Z = bcf1Issue.viewpoint.PerspectiveCamera.CameraDirection.Z }, CameraUpVector = new BCF2.Direction() { X = bcf1Issue.viewpoint.PerspectiveCamera.CameraUpVector.X, Y = bcf1Issue.viewpoint.PerspectiveCamera.CameraUpVector.Y, Z = bcf1Issue.viewpoint.PerspectiveCamera.CameraUpVector.Z }, CameraViewPoint = new BCF2.Point() { X = bcf1Issue.viewpoint.PerspectiveCamera.CameraViewPoint.X, Y = bcf1Issue.viewpoint.PerspectiveCamera.CameraViewPoint.Y, Z = bcf1Issue.viewpoint.PerspectiveCamera.CameraViewPoint.Z }, FieldOfView = bcf1Issue.viewpoint.PerspectiveCamera.FieldOfView }, SheetCamera = bcf1Issue.viewpoint.SheetCamera == null ? null : new BCF2.SheetCamera() { SheetID = bcf1Issue.viewpoint.SheetCamera.SheetID, SheetName = null, // default null TopLeft = new BCF2.Point() { X = bcf1Issue.viewpoint.SheetCamera.TopLeft.X, Y = bcf1Issue.viewpoint.SheetCamera.TopLeft.Y, Z = bcf1Issue.viewpoint.SheetCamera.TopLeft.Z }, BottomRight = new BCF2.Point() { X = bcf1Issue.viewpoint.SheetCamera.BottomRight.X, Y = bcf1Issue.viewpoint.SheetCamera.BottomRight.Y, Z = bcf1Issue.viewpoint.SheetCamera.BottomRight.Z } } }; // Convert viewpoints // BCF 1.0 can only have one viewpoint ObservableCollection <BCF2.ViewPoint> bcf2ViewPoints = new ObservableCollection <BCF2.ViewPoint>(); bcf2ViewPoints.Add(new BCF2.ViewPoint() { //Guid = null, // no guid for viewpoint Snapshot = bcf1Issue.snapshot, Viewpoint = "viewpoint.bcfv", VisInfo = bcf2VizInfo }); // Add BCF 2.0 issues/markups bcf2.Issues.Add(new BCF2.Markup() { Header = bcf2Headers, Comment = bcf2Comments, Topic = bcf2Topic, Viewpoints = bcf2ViewPoints }); } // Save BCF 2.0 file BCF2.BcfContainer.SaveBcfFile(bcf2); bcf1.HasBeenSaved = true; } catch (Exception ex) { // Get stack trace for the exception with source file information var st = new System.Diagnostics.StackTrace(ex, true); // Get the top stack frame var frame = st.GetFrame(0); // Get the line number from the stack frame var line = frame.GetFileLineNumber(); System.Windows.MessageBox.Show("Exception:" + line + "=====" + ex.ToString()); } }
public virtual bool TestStart(string tcId, string component, string function) { if ((component == null) || (tcId == null) || (function == null) || (tcWriter != null )) { return(false); } string tcFileName = component + ".dbt"; System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace(true); System.Diagnostics.StackFrame[] frames = stackTrace.GetFrames(); string file; if (frames.Length > 3) { file = frames[3].GetFileName() + ":" + frames[3].GetFileLineNumber(); } else { file = frames[frames.Length - 1].GetFileName() + ":" + frames[frames.Length - 1].GetFileLineNumber(); } try { tcWriter = new StreamWriter(tcFileName, true); } catch (System.IO.IOException e) { //File could not be created. //Sharpen.Runtime.printStackTrace(e); return(false); } string userName = Environment.UserName; string osName = Environment.OSVersion.Platform.ToString(); string osArch = "Running On Other"; Type t = Type.GetType("Mono.Runtime"); if (t != null) { osArch = "Running On Mono"; } string osVersion = Environment.OSVersion.VersionString; DateTime time = DateTime.Now; try { WriteLine("################"); WriteLine("TESTCASE ID\t: " + tcId); WriteLine("COMPONENT\t: " + component); WriteLine("FUNCTION\t: " + function); WriteLine("FILE\t\t: " + file); WriteLine("USER\t\t: " + userName); WriteLine("PLATFORM\t: " + osName + " " + osVersion + " " + osArch); WriteLine(string.Format("DATE\t\t: {0:yyyy/MM/dd}", time)); WriteLine(string.Format("TIME\t\t: {0:HH:mm:ss}", time)); } catch (System.IO.IOException) { return(false); } return(true); }
/// <summary> /// Save Jira issues as BCF 2.0 /// </summary> /// <param name="jiraPan"></param> public static void SaveBcf2FromJira(UserControls.MainPanel mainPan) { try { BCF2.BcfFile bcf2 = new BCF2.BcfFile(); string ReportFolder = Path.Combine(Path.GetTempPath(), "BCFtemp", Path.GetRandomFileName()); bcf2.TempPath = ReportFolder; bcf2.ProjectName = ((Project)(mainPan.jiraPan.projCombo.SelectedItem)).name; //bcf2.ProjectId = ; // Is there a guid for a Jira project? int errors = 0; // Add issues (markups) foreach (object t in mainPan.jiraPan.issueList.SelectedItems) { int index = mainPan.jiraPan.issueList.Items.IndexOf(t); Issue issue = mainPan.jira.IssuesCollection[index]; if (issue.viewpoint == "" || issue.snapshotFull == "") { errors++; continue; } // Create temp. folder string issueGuid = issue.fields.guid; if (!Directory.Exists(Path.Combine(ReportFolder, issueGuid))) { Directory.CreateDirectory(Path.Combine(ReportFolder, issueGuid)); } // Convert header files List <BCF2.HeaderFile> bcf2Headers = new List <BCF2.HeaderFile>(); bcf2Headers.Add(new BCF2.HeaderFile() { Date = issue.fields.created == null ? new DateTime() : DateTime.Parse(issue.fields.created), Filename = "Jira Export " + DateTime.Now.ToShortDateString().Replace("/", "-"), isExternal = true, // default true for now Reference = "" // default empty for now }); // Convert Comments ObservableCollection <BCF2.Comment> bcf2Comments = new ObservableCollection <BCF2.Comment>(); foreach (var comm in issue.fields.comment.comments) { if (comm != null) { bcf2Comments.Add(new BCF2.Comment() { Author = comm.author == null ? null : comm.author.displayName, Comment1 = comm.body == null ? null : comm.body, Date = comm.created == null ? new DateTime() : DateTime.Parse(comm.created), Guid = Guid.NewGuid().ToString(), ModifiedAuthor = comm.updateAuthor == null ? null : comm.updateAuthor.displayName, ModifiedDate = comm.updated == null ? new DateTime() : DateTime.Parse(comm.updated), ReplyToComment = null, // default null Status = "Unknown", Topic = new BCF2.CommentTopic() { Guid = issueGuid }, // all referenced to markup's topic VerbalStatus = issue.fields.status == null ? null : issue.fields.status.name, Viewpoint = null }); } } // Convert Topic BCF2.Topic bcf2Topic = new BCF2.Topic() { AssignedTo = issue.fields.assignee == null ? null : issue.fields.assignee.displayName, BimSnippet = null, CreationAuthor = issue.fields.creator == null ? null : issue.fields.creator.displayName, CreationDate = issue.fields.created == null ? new DateTime() : DateTime.Parse(issue.fields.created), Description = issue.fields.description == null ? null : issue.fields.description, DocumentReferences = null, Guid = issueGuid, Index = null, Labels = null, ModifiedAuthor = null, ModifiedDate = issue.fields.updated == null ? new DateTime() : DateTime.Parse(issue.fields.updated), Priority = issue.fields.priority == null ? null : issue.fields.priority.name, ReferenceLink = null, RelatedTopics = null, Title = issue.fields.summary == null ? null : issue.fields.summary, TopicStatus = issue.fields.status == null ? null : issue.fields.status.name, TopicType = issue.fields.issuetype == null ? null : issue.fields.issuetype.name }; // Add BCF 2.0 issues/markups bcf2.Issues.Add(new BCF2.Markup() { Header = bcf2Headers, Comment = bcf2Comments, Topic = bcf2Topic, // Viewpoints = bcf2ViewPoints // use the one saved on Jira }); // Save viewpoint and snapshot try { mainPan.saveSnapshotViewpoint(issue.viewpoint, Path.Combine(ReportFolder, issueGuid, "viewpoint.bcfv")); mainPan.saveSnapshotViewpoint(issue.snapshotFull, Path.Combine(ReportFolder, issueGuid, "snapshot.png")); } catch (Exception ex) { MessageBox.Show("Failed to download viewpoint.bcfv and snapshot.png on Jira", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning); return; } } if (errors != 0) { MessageBox.Show(errors + " Issue/s were not exported because not formatted correctly.", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning); if (errors == mainPan.jiraPan.issueList.SelectedItems.Count) { mainPan.DeleteDirectory(ReportFolder); return; } } // Save BCF 2.0 file BCF2.BcfContainer.SaveBcfFile(bcf2); } catch (Exception ex) { // Get stack trace for the exception with source file information var st = new System.Diagnostics.StackTrace(ex, true); // Get the top stack frame var frame = st.GetFrame(0); // Get the line number from the stack frame var line = frame.GetFileLineNumber(); MessageBox.Show("Exception:" + line + "=====" + ex.ToString()); } }
protected void gridUsuarios_RowCommand(object sender, GridViewCommandEventArgs e) { // Logger variables System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace(true); System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame(); string className = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name; string methodName = stackFrame.GetMethod().Name; if (e.CommandName == "InsertNew") { GridViewRow row = gridUsuarios.FooterRow; TextBox txb1 = row.FindControl("txbNew1") as TextBox; TextBox txb2 = row.FindControl("txbNew2") as TextBox; TextBox txb3 = row.FindControl("txbNew3") as TextBox; if (txb1 != null && txb2 != null && txb3 != null) { if (!string.IsNullOrWhiteSpace(txb1.Text) && !string.IsNullOrWhiteSpace(txb2.Text)) { using (ChevacaDB context = new ChevacaDB()) { usuarios obj = new usuarios(); obj.Usuario = txb1.Text; obj.Clave = txb2.Text; int Rol_usuario_ID = 0; if (!int.TryParse(txb3.Text, out Rol_usuario_ID)) { Rol_usuario_ID = 0; Logs.AddErrorLog("Excepcion. Convirtiendo int. ERROR:", className, methodName, txb3.Text); } obj.Rol_usuario_ID = Rol_usuario_ID; context.usuarios.Add(obj); context.SaveChanges(); #region Guardar log try { int id = 1; usuarios usuarios = (usuarios)context.usuarios.OrderByDescending(p => p.Usuario_ID).FirstOrDefault(); if (usuarios != null) { id = usuarios.Usuario_ID; } string userID1 = HttpContext.Current.Session["UserID"].ToString(); string username = HttpContext.Current.Session["UserName"].ToString(); Global_Objects.Logs.AddUserLog("Agrega usuarios", usuarios.GetType().Name + ": " + id, userID1, username); } catch (Exception ex) { Global_Objects.Logs.AddErrorLog("Excepcion. Guardando log. ERROR:", className, methodName, ex.Message); } #endregion lblMessage.Text = "Agregado correctamente."; BindGrid(); } } else { ScriptManager.RegisterStartupScript(this, typeof(Page), "alert", "alert('Por favor ingrese el Nombre');", true); } } } else if (e.CommandName == "View") { string[] values = e.CommandArgument.ToString().Split(new char[] { ',' }); if (values.Length > 1) { string tabla = values[0]; string dato = values[1]; if (!string.IsNullOrWhiteSpace(tabla) && !string.IsNullOrWhiteSpace(dato)) { Response.Redirect("Listados.aspx?tabla=" + tabla + "&dato=" + dato); } } } else { //BindGrid(); } }
/// <summary> /// Populates the <see cref="Rock.Model.ExceptionLog" /> entity with the exception data. /// </summary> /// <param name="ex">The <see cref="System.Exception" /> to log.</param> /// <param name="context">The <see cref="System.Web.HttpContext" />.</param> /// <param name="pageId">An <see cref="System.Int32" /> containing the Id of the <see cref="Rock.Model.Page" /> where the exception occurred. /// This value is nullable.</param> /// <param name="siteId">An <see cref="System.Int32" /> containing the Id the <see cref="Rock.Model.Site" /> where the exception occurred. /// This value is nullable.</param> /// <param name="personAlias">The person alias.</param> /// <returns></returns> private static ExceptionLog PopulateExceptionLog(Exception ex, HttpContext context, int?pageId, int?siteId, PersonAlias personAlias) { int?personAliasId = null; if (personAlias != null) { personAliasId = personAlias.Id; } string exceptionMessage = ex.Message; if (ex is System.Data.SqlClient.SqlException) { var sqlEx = ex as System.Data.SqlClient.SqlException; var sqlErrorList = sqlEx.Errors.OfType <System.Data.SqlClient.SqlError>().ToList().Select(a => string.Format("{0}: Line {1}", a.Procedure, a.LineNumber)); if (sqlErrorList.Any()) { exceptionMessage += string.Format("[{0}]", sqlErrorList.ToList().AsDelimited(", ")); } } var exceptionLog = new ExceptionLog { SiteId = siteId, PageId = pageId, HasInnerException = ex.InnerException != null, ExceptionType = ex.GetType().ToString(), Description = exceptionMessage, Source = ex.Source, StackTrace = ex.StackTrace, Guid = Guid.NewGuid(), CreatedByPersonAliasId = personAliasId, ModifiedByPersonAliasId = personAliasId, CreatedDateTime = RockDateTime.Now, ModifiedDateTime = RockDateTime.Now, ModifiedAuditValuesAlreadyUpdated = true }; if (exceptionLog.StackTrace == null) { try { // if the Exception didn't include a StackTrace, manually grab it var stackTrace = new System.Diagnostics.StackTrace(2); exceptionLog.StackTrace = stackTrace.ToString(); } catch { } } try { ex.Data.Add("ExceptionLogGuid", exceptionLog.Guid); } catch { } try { // If current HttpContext is null, return early. if (context == null) { return(exceptionLog); } // If current HttpContext is available, populate its information as well. var request = context.Request; StringBuilder cookies = new StringBuilder(); var cookieList = request.Cookies; if (cookieList.Count > 0) { cookies.Append("<table class=\"cookies exception-table\">"); foreach (string cookie in cookieList) { var httpCookie = cookieList[cookie]; if (httpCookie != null) { cookies.Append("<tr><td><b>" + cookie + "</b></td><td>" + httpCookie.Value.EncodeHtml() + "</td></tr>"); } } cookies.Append("</table>"); } StringBuilder formItems = new StringBuilder(); var formList = request.Form; if (formList.Count > 0) { formItems.Append("<table class=\"form-items exception-table\">"); foreach (string formItem in formList) { if (formItem.IsNotNullOrWhiteSpace()) { string formValue = formList[formItem].EncodeHtml(); string lc = formItem.ToLower(); if (lc.Contains("nolog") || lc.Contains("creditcard") || lc.Contains("cc-number") || lc.Contains("cvv") || lc.Contains("ssn") || lc.Contains("accountnumber") || lc.Contains("account-number")) { formValue = "***obfuscated***"; } formItems.Append("<tr><td><b>" + formItem + "</b></td><td>" + formValue + "</td></tr>"); } } formItems.Append("</table>"); } StringBuilder serverVars = new StringBuilder(); var serverVarList = request.ServerVariables; if (serverVarList.Count > 0) { serverVars.Append("<table class=\"server-variables exception-table\">"); foreach (string serverVar in serverVarList) { string val = string.Empty; try { // 'serverVarList[serverVar]' throws an exception if the value is empty, even if the key exists. Was not able to find a more elegant way to avoid an exception. val = serverVarList[serverVar].ToStringSafe().EncodeHtml(); } catch { } serverVars.Append($"<tr><td><b>{serverVar}</b></td><td>{val}</td></tr>"); } serverVars.Append("</table>"); } exceptionLog.Cookies = cookies.ToString(); exceptionLog.StatusCode = context.Response.StatusCode.ToString(); exceptionLog.PageUrl = request.Url.ToString(); exceptionLog.ServerVariables = serverVars.ToString(); exceptionLog.QueryString = request.Url.Query; exceptionLog.Form = formItems.ToString(); } catch { } return(exceptionLog); }
/// <summary> /// Warning 로그를 작성한다. /// </summary> /// <param name="_strWarningLog">Warning 로그</param> /// <param name="_arrFileInfo">파일 정보</param> private static void CreateWarningLog(string _strWarningLog, string[] _arrFileInfo) { try { /*▩▩▩▩▩▩▩▩▩▩▩▩▩▩▩▩▩▩▩▩▩▩ * [0] 파일명 - 일자_순번.log * [1] 기존 로그파일에 덮어쓰기 여부 *▩▩▩▩▩▩▩▩▩▩▩▩▩▩▩▩▩▩▩▩▩▩*/ string strDirFileName = _arrFileInfo[0]; // 로그 작성 폴더/파일명 string strOverWriteYN = _arrFileInfo[1]; // 기존 로그 파일에 쓰기 여부 using (System.IO.FileStream fs = new System.IO.FileStream(strDirFileName, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite)) { using (System.IO.StreamWriter sw = new System.IO.StreamWriter(fs)) { } } // 에러 로그를 작성한다. using (System.IO.FileStream fs = new System.IO.FileStream(strDirFileName, System.IO.FileMode.Append, System.IO.FileAccess.Write)) { using (System.IO.StreamWriter sw = new System.IO.StreamWriter(fs)) { if (strOverWriteYN == "Y") { sw.Write(Microsoft.VisualBasic.ControlChars.CrLf); sw.Write(Microsoft.VisualBasic.ControlChars.CrLf); sw.Write(Microsoft.VisualBasic.ControlChars.CrLf); } System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(); string strTrace = string.Empty; for (int i = st.FrameCount - 1; i > 2; i--) { System.Diagnostics.StackFrame sf = new System.Diagnostics.StackFrame(); string strType = sf.GetMethod().ReflectedType.FullName; string strMethod = sf.GetMethod().ToString(); string strSource = sf.GetFileName(); int iLine = sf.GetFileLineNumber(); if (!((strType.IndexOf("Microsoft.") > -1) || (strType.IndexOf("System.") > -1))) { strTrace += string.Format("\r\n at {0}.{1} in {2}:line {3}", strType, strMethod, strSource, iLine); } } //sw.Write(string.Format("Date/Time : [{0}]", System.DateTime.Now.ToString())); sw.Write(string.Format($"Date/Time : {g_strCurrentDateTime}")); sw.Write(Microsoft.VisualBasic.ControlChars.CrLf); sw.Write("Message : " + _strWarningLog); sw.Write(Microsoft.VisualBasic.ControlChars.CrLf); sw.Write("StackTrace : " + strTrace); sw.Write("===================================================================================================="); sw.Write("StackTrace : " + strTrace); } } } catch (System.Exception err) { throw err; } }
/// <summary> /// 获取网络数据 /// </summary> public static string RequestUrl(string url, Dictionary <string, string> requestParams = null, bool isPost = false, bool hasFile = false) { string postData = string.Empty; if (requestParams != null) { postData = string.Join("&", requestParams.Select(c => c.Key + "=" + c.Value)); } String responseFromServer = string.Empty; try { // Create a request using a URL that can receive a post. if (!isPost) { url += string.IsNullOrEmpty(postData) ? string.Empty : url.IndexOf("?") > -1 ? "&" : "?" + postData; } Console.WriteLine(url); WebRequest webRequest = HttpWebRequest.Create(url); { try { ((HttpWebRequest)webRequest).KeepAlive = false; webRequest.Timeout = 1000 * 30; // if (isPost) { // Set the Method property of the request to POST. webRequest.Method = "POST"; webRequest.Proxy = null; // Create POST data and convert it to a byte array. byte[] byteArray = System.Text.Encoding.ASCII.GetBytes(postData); // Set the ContentType property of the WebRequest. webRequest.ContentType = "application/x-www-form-urlencoded"; // Set the ContentLength property of the WebRequest. webRequest.ContentLength = byteArray.Length; // Get the request stream. using (System.IO.Stream dataStream = webRequest.GetRequestStream()) { dataStream.Write(byteArray, 0, byteArray.Length); } } } catch { } // Get the response. using (WebResponse response = webRequest.GetResponse()) { //Console.WriteLine(((HttpWebResponse)response).StatusDescription); // Get the stream containing content returned by the server. using (System.IO.Stream responseStream = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(responseStream)) { responseFromServer = reader.ReadToEnd(); } } } } } catch (Exception ex) { String error = ex.Message; System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace(); String method = stackTrace.GetFrame(0).GetMethod().Name; } return(responseFromServer); }
public void LogInfo(string recorder, string message) { System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace(); write.BeginInvoke("Info", System.Threading.Thread.CurrentThread.ManagedThreadId.ToString(), _ips, recorder, stackTrace.GetFrame(1).GetMethod().ReflectedType.ToString(), message, null, null); }
private void Filter(int?directionId, int?groupId, DateTime dateBegin, DateTime dateEnd, int?teacherId, int?housingId, string column, SortOrder?sortOrder) { try { dateEnd = dateEnd.AddDays(1).Date; var listLessons = from lessons in db.Lessons join teachers in db.Workers on lessons.TeacherId equals teachers.Id into outerTeacher from teachers in outerTeacher.DefaultIfEmpty() join groups in db.Groups on lessons.GroupId equals groups.Id join courses in db.Courses on groups.CourseId equals courses.Id join directions in db.Directions on courses.DirectionId equals directions.Id join classes in db.Classes on lessons.ClassId equals classes.Id into outerClass from classes in outerClass.DefaultIfEmpty() join branches in db.Housings on classes.HousingId equals branches.Id into outerBranch from branches in outerBranch.DefaultIfEmpty() join topics in db.Topics on lessons.TopicId equals topics.Id into outerTopics from topics in outerTopics.DefaultIfEmpty() where lessons.Date >= dateBegin && lessons.Date < dateEnd select new ListLessons { GroupId = groups.Id, DirectionId = directions.Id, TeacherId = teachers.Id, HousingId = branches.Id, Teacher = teachers.Lastname + " " + teachers.Firstname.Substring(0, 1) + "." + teachers.Middlename.Substring(0, 1) + ".", DateLesson = lessons.Date, Number = lessons.Number, GroupName = groups.Name, Students = db.Enrollments.Where(a => a.GroupId == groups.Id && a.DateExclusion == null).Count(), DurationLesson = lessons.DurationLesson, CourseName = courses.Name, DirectionName = directions.Name, Branch = branches.Name, Class = classes.Name, Topic = topics.Name, }; if (directionId != null) { listLessons = listLessons.Where(d => d.DirectionId == directionId); } if (teacherId != null) { listLessons = listLessons.Where(d => d.TeacherId == teacherId); } if (groupId != null) { listLessons = listLessons.Where(d => d.GroupId == groupId); } if (housingId != null) { listLessons = listLessons.Where(d => d.HousingId == housingId); } //сортировка if (column != null) { switch (column) { case "Teacher": { if (sortOrder == SortOrder.Ascending) { listLessons = listLessons.OrderBy(x => x.Teacher); } else { listLessons = listLessons.OrderByDescending(x => x.Teacher); } break; } case "DateLesson": { if (sortOrder == SortOrder.Ascending) { listLessons = listLessons.OrderBy(x => x.DateLesson); } else { listLessons = listLessons.OrderByDescending(x => x.DateLesson); } break; } case "Number": { if (sortOrder == SortOrder.Ascending) { listLessons = listLessons.OrderBy(x => x.Number); } else { listLessons = listLessons.OrderByDescending(x => x.Number); } break; } case "GroupName": { if (sortOrder == SortOrder.Ascending) { listLessons = listLessons.OrderBy(x => x.GroupName); } else { listLessons = listLessons.OrderByDescending(x => x.GroupName); } break; } case "CourseName": { if (sortOrder == SortOrder.Ascending) { listLessons = listLessons.OrderBy(x => x.CourseName); } else { listLessons = listLessons.OrderByDescending(x => x.CourseName); } break; } case "DirectionName": { if (sortOrder == SortOrder.Ascending) { listLessons = listLessons.OrderBy(x => x.DirectionName); } else { listLessons = listLessons.OrderByDescending(x => x.DirectionName); } break; } case "Branch": { if (sortOrder == SortOrder.Ascending) { listLessons = listLessons.OrderBy(x => x.Branch); } else { listLessons = listLessons.OrderByDescending(x => x.Branch); } break; } case "Class": { if (sortOrder == SortOrder.Ascending) { listLessons = listLessons.OrderBy(x => x.Class); } else { listLessons = listLessons.OrderByDescending(x => x.Class); } break; } case "Topic": { if (sortOrder == SortOrder.Ascending) { listLessons = listLessons.OrderBy(x => x.Topic); } else { listLessons = listLessons.OrderByDescending(x => x.Topic); } break; } } } else { listLessons = listLessons.OrderBy(f => f.DateLesson); } dgvListLessons.DataSource = listLessons.ToList(); if (sortOrder != SortOrder.None) { dgvListLessons.Columns[sortColumn].HeaderCell.SortGlyphDirection = (SortOrder)sortOrder; } } catch (Exception ex) { var m = new System.Diagnostics.StackTrace(false).GetFrame(0).GetMethod(); string methodName = m.DeclaringType.ToString() + ";" + m.Name; CurrentSession.ReportError(methodName, ex.Message); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private void ListLessonForm_Load(object sender, EventArgs e) { try { //загрузка фильтра направлений var direction = db.Directions.Where(a => a.IsRemoved == false).ToList(); cbDirectionOfTraining.DataSource = direction; cbDirectionOfTraining.DisplayMember = "Name"; cbDirectionOfTraining.ValueMember = "Id"; cbDirectionOfTraining.SelectedIndex = -1; //загрузка фильтра групп var actGroups = db.Groups.Where(a => a.Activity.Name != "Закрытые" && a.Individual == false).OrderBy(a => a.Name).ToList(); cbGroups.DataSource = actGroups; cbGroups.DisplayMember = "Name"; cbGroups.ValueMember = "Id"; cbGroups.SelectedIndex = -1; //загрузка фильтра преподавателей var teachers = db.Workers.Where(a => a.Role.Name == "Преподаватель") .OrderBy(a => a.Lastname).ThenBy(a => a.Firstname).ToList(); cbTeachers.DataSource = teachers; cbTeachers.DisplayMember = "LastnameFM"; cbTeachers.ValueMember = "Id"; cbTeachers.SelectedIndex = -1; //загрузка фильтра корпусов var housing = db.Housings.Where(a => a.IsRemoved == false).ToList(); cbHousings.DataSource = housing; cbHousings.DisplayMember = "Name"; cbHousings.ValueMember = "Id"; cbHousings.SelectedIndex = -1; //установка дат var date = dtpBegin.Value = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1); date = date.AddMonths(1).AddDays(-1); dtpEnd.Value = new DateTime(DateTime.Now.Year, DateTime.Now.Month, date.Day); //добавление программной сортировки foreach (DataGridViewColumn col in dgvListLessons.Columns) { col.SortMode = DataGridViewColumnSortMode.Programmatic; } //загрузка списка занятий Filter(null, null, dtpBegin.Value.Date, dtpEnd.Value.Date, null, null, sortColumn, sortOrder); //оформление таблицы dgvListLessons.Columns["GroupId"].Visible = dgvListLessons.Columns["DirectionId"].Visible = dgvListLessons.Columns["TeacherId"].Visible = dgvListLessons.Columns["HousingId"].Visible = dgvListLessons.Columns["Wage"].Visible = dgvListLessons.Columns["Wages"].Visible = false; dgvListLessons.Columns["DirectionName"].HeaderText = "Направление"; dgvListLessons.Columns["GroupName"].HeaderText = "Группа"; dgvListLessons.Columns["Branch"].HeaderText = "Корпус"; dgvListLessons.Columns["Students"].HeaderText = "Учащихся"; dgvListLessons.Columns["Class"].HeaderText = "Класс"; dgvListLessons.Columns["DateLesson"].HeaderText = "Дата"; dgvListLessons.Columns["DateLesson"].DefaultCellStyle.Format = "dd/MM/yyyy"; dgvListLessons.Columns["Number"].HeaderText = "Номер"; dgvListLessons.Columns["DurationLesson"].HeaderText = "Продолж."; dgvListLessons.Columns["CourseName"].HeaderText = "Курс"; dgvListLessons.Columns["Teacher"].HeaderText = "Преподаватель"; dgvListLessons.Columns["Topic"].HeaderText = "Тема"; dgvListLessons.Columns["Topic"].Width = 300; dgvListLessons.Focus(); dgvListLessons.Select(); } catch (Exception ex) { var m = new System.Diagnostics.StackTrace(false).GetFrame(0).GetMethod(); string methodName = m.DeclaringType.ToString() + ";" + m.Name; CurrentSession.ReportError(methodName, ex.Message); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private MondValue Run() { var functionAddress = PeekCall(); var program = functionAddress.Program; var code = program.Bytecode; var initialCallDepth = _callStackSize - 1; // "- 1" to not include values pushed by Call() var initialLocalDepth = _localStackSize - 1; var initialEvalDepth = _evalStackSize; var ip = functionAddress.Address; var errorIp = 0; var args = functionAddress.Arguments; Frame locals = null; try { while (true) { if (Debugger != null) { var skip = _debugSkip; _debugSkip = false; var shouldStopAtStmt = (_debugAction == MondDebugAction.StepInto) || (_debugAction == MondDebugAction.StepOver && _debugDepth == 0); var shouldBreak = (_debugAlign && program.DebugInfo == null) || (_debugAlign && program.DebugInfo.IsStatementStart(ip)) || (Debugger.ShouldBreak(program, ip)) || (shouldStopAtStmt && program.DebugInfo != null && program.DebugInfo.IsStatementStart(ip)); if (!skip && shouldBreak) { DebuggerBreak(program, locals, args, ip, initialCallDepth); } } errorIp = ip; switch (code[ip++]) { #region Stack Manipulation case (int)InstructionType.Dup: { Push(Peek()); break; } case (int)InstructionType.Dup2: { var value2 = Pop(); var value1 = Pop(); Push(value1); Push(value2); Push(value1); Push(value2); break; } case (int)InstructionType.Drop: { Pop(); break; } case (int)InstructionType.Swap: { var value1 = Pop(); var value2 = Pop(); Push(value1); Push(value2); break; } case (int)InstructionType.Swap1For2: { var one = Pop(); var two2 = Pop(); var two1 = Pop(); Push(one); Push(two1); Push(two2); break; } #endregion #region Constants case (int)InstructionType.LdUndef: { Push(MondValue.Undefined); break; } case (int)InstructionType.LdNull: { Push(MondValue.Null); break; } case (int)InstructionType.LdTrue: { Push(MondValue.True); break; } case (int)InstructionType.LdFalse: { Push(MondValue.False); break; } case (int)InstructionType.LdNum: { var numId = ReadInt32(code, ref ip); Push(program.Numbers[numId]); break; } case (int)InstructionType.LdStr: { var strId = ReadInt32(code, ref ip); Push(program.Strings[strId]); break; } case (int)InstructionType.LdGlobal: { Push(Global); break; } #endregion #region Storables case (int)InstructionType.LdLocF: { var index = ReadInt32(code, ref ip); Push(locals.Values[index]); break; } case (int)InstructionType.StLocF: { var index = ReadInt32(code, ref ip); locals.Values[index] = Pop(); break; } case (int)InstructionType.LdLoc: { var depth = ReadInt32(code, ref ip); var index = ReadInt32(code, ref ip); if (depth < 0) { Push(args.Get(-depth, index)); } else { Push(locals.Get(depth, index)); } break; } case (int)InstructionType.StLoc: { var depth = ReadInt32(code, ref ip); var index = ReadInt32(code, ref ip); if (depth < 0) { args.Set(-depth, index, Pop()); } else { locals.Set(depth, index, Pop()); } break; } case (int)InstructionType.LdFld: { var obj = Pop(); Push(obj[program.Strings[ReadInt32(code, ref ip)]]); break; } case (int)InstructionType.StFld: { var obj = Pop(); var value = Pop(); obj[program.Strings[ReadInt32(code, ref ip)]] = value; break; } case (int)InstructionType.LdArr: { var index = Pop(); var array = Pop(); Push(array[index]); break; } case (int)InstructionType.StArr: { var index = Pop(); var array = Pop(); var value = Pop(); array[index] = value; break; } case (int)InstructionType.LdState: { var depth = ReadInt32(code, ref ip); var frame = locals.GetFrame(depth); locals = frame.StoredFrame; PopLocal(); PushLocal(locals); var evals = frame.StoredEvals; if (evals != null) { for (var i = evals.Count - 1; i >= 0; i--) { Push(evals[i]); } evals.Clear(); } break; } case (int)InstructionType.StState: { var depth = ReadInt32(code, ref ip); var frame = locals.GetFrame(depth); frame.StoredFrame = locals; var initialEvals = _callStackSize > 0 ? PeekCall().EvalDepth : 0; var currentEvals = _evalStackSize; if (currentEvals != initialEvals) { var evals = frame.StoredEvals ?? (frame.StoredEvals = new List <MondValue>()); while (currentEvals != initialEvals) { evals.Add(Pop()); currentEvals--; } } break; } #endregion #region Object Creation case (int)InstructionType.NewObject: { var obj = MondValue.Object(_state); Push(obj); break; } case (int)InstructionType.NewArray: { var count = ReadInt32(code, ref ip); var array = MondValue.Array(); array.ArrayValue.Capacity = count; for (var i = 0; i < count; i++) { array.ArrayValue.Add(default(MondValue)); } Push(array); break; } case (int)InstructionType.Slice: { var step = Pop(); var end = Pop(); var start = Pop(); var array = Pop(); Push(array.Slice(start, end, step)); break; } #endregion #region Math case (int)InstructionType.Add: { var right = Pop(); var left = Pop(); Push(left + right); break; } case (int)InstructionType.Sub: { var right = Pop(); var left = Pop(); Push(left - right); break; } case (int)InstructionType.Mul: { var right = Pop(); var left = Pop(); Push(left * right); break; } case (int)InstructionType.Div: { var right = Pop(); var left = Pop(); Push(left / right); break; } case (int)InstructionType.Mod: { var right = Pop(); var left = Pop(); Push(left % right); break; } case (int)InstructionType.Exp: { var right = Pop(); var left = Pop(); Push(left.Pow(right)); break; } case (int)InstructionType.BitLShift: { var right = Pop(); var left = Pop(); Push(left.LShift(right)); break; } case (int)InstructionType.BitRShift: { var right = Pop(); var left = Pop(); Push(left.RShift(right)); break; } case (int)InstructionType.BitAnd: { var right = Pop(); var left = Pop(); Push(left & right); break; } case (int)InstructionType.BitOr: { var right = Pop(); var left = Pop(); Push(left | right); break; } case (int)InstructionType.BitXor: { var right = Pop(); var left = Pop(); Push(left ^ right); break; } case (int)InstructionType.Neg: { Push(-Pop()); break; } case (int)InstructionType.BitNot: { Push(~Pop()); break; } #endregion #region Logic case (int)InstructionType.Eq: { var right = Pop(); var left = Pop(); Push(left == right); break; } case (int)InstructionType.Neq: { var right = Pop(); var left = Pop(); Push(left != right); break; } case (int)InstructionType.Gt: { var right = Pop(); var left = Pop(); Push(left > right); break; } case (int)InstructionType.Gte: { var right = Pop(); var left = Pop(); Push(left >= right); break; } case (int)InstructionType.Lt: { var right = Pop(); var left = Pop(); Push(left < right); break; } case (int)InstructionType.Lte: { var right = Pop(); var left = Pop(); Push(left <= right); break; } case (int)InstructionType.Not: { Push(!Pop()); break; } case (int)InstructionType.In: { var right = Pop(); var left = Pop(); Push(right.Contains(left)); break; } case (int)InstructionType.NotIn: { var right = Pop(); var left = Pop(); Push(!right.Contains(left)); break; } #endregion #region Functions case (int)InstructionType.Closure: { var address = ReadInt32(code, ref ip); Push(new MondValue(new Closure(program, address, args, locals))); break; } case (int)InstructionType.Call: { var argCount = ReadInt32(code, ref ip); var unpackCount = code[ip++]; var function = Pop(); List <MondValue> unpackedArgs = null; if (unpackCount > 0) { unpackedArgs = UnpackArgs(code, ref ip, argCount, unpackCount); } var returnAddress = ip; if (function.Type == MondValueType.Object) { MondValue[] argArr; if (unpackedArgs == null) { argArr = new MondValue[argCount + 1]; for (var i = argCount; i >= 1; i--) { argArr[i] = Pop(); } argArr[0] = function; } else { unpackedArgs.Insert(0, function); argArr = unpackedArgs.ToArray(); } if (function.TryDispatch("__call", out var result, argArr)) { Push(result); break; } } if (function.Type != MondValueType.Function) { var ldFldBase = ip - 1 - 4 - 1 - 4 - 1; if (ldFldBase >= 0 && code[ldFldBase] == (int)InstructionType.LdFld) { var ldFldIdx = ldFldBase + 1; var fieldNameIdx = ReadInt32(code, ref ldFldIdx); if (fieldNameIdx >= 0 && fieldNameIdx < program.Strings.Count) { var fieldName = program.Strings[fieldNameIdx]; throw new MondRuntimeException(RuntimeError.FieldNotCallable, (string)fieldName); } } throw new MondRuntimeException(RuntimeError.ValueNotCallable, function.Type.GetName()); } var closure = function.FunctionValue; var argFrame = function.FunctionValue.Arguments; var argFrameCount = unpackedArgs?.Count ?? argCount; if (argFrame == null) { argFrame = new Frame(1, null, argFrameCount); } else { argFrame = new Frame(argFrame.Depth + 1, argFrame, argFrameCount); } // copy arguments into frame if (unpackedArgs == null) { for (var i = argFrameCount - 1; i >= 0; i--) { argFrame.Values[i] = Pop(); } } else { for (var i = 0; i < argFrameCount; i++) { argFrame.Values[i] = unpackedArgs[i]; } } switch (closure.Type) { case ClosureType.Mond: PushCall(new ReturnAddress(program, returnAddress, argFrame, _evalStackSize)); PushLocal(closure.Locals); program = closure.Program; code = program.Bytecode; ip = closure.Address; args = argFrame; locals = closure.Locals; if (Debugger != null) { DebuggerCheckCall(); } break; case ClosureType.Native: var result = closure.NativeFunction(_state, argFrame.Values); Push(result); break; default: throw new MondRuntimeException(RuntimeError.UnhandledClosureType); } break; } case (int)InstructionType.TailCall: { var argCount = ReadInt32(code, ref ip); var address = ReadInt32(code, ref ip); var unpackCount = code[ip++]; List <MondValue> unpackedArgs = null; if (unpackCount > 0) { unpackedArgs = UnpackArgs(code, ref ip, argCount, unpackCount); } var returnAddress = PopCall(); var argFrame = returnAddress.Arguments; var argFrameCount = unpackedArgs?.Count ?? argCount; // make sure we have the correct number of values if (argFrameCount != argFrame.Values.Length) { argFrame.Values = new MondValue[argFrameCount]; } // copy arguments into frame if (unpackedArgs == null) { for (var i = argFrameCount - 1; i >= 0; i--) { argFrame.Values[i] = Pop(); } } else { for (var i = 0; i < argFrameCount; i++) { argFrame.Values[i] = unpackedArgs[i]; } } // get rid of old locals PushLocal(PopLocal().Previous); PushCall(new ReturnAddress(returnAddress.Program, returnAddress.Address, argFrame, _evalStackSize)); ip = address; break; } case (int)InstructionType.Enter: { var localCount = ReadInt32(code, ref ip); var frame = PopLocal(); frame = new Frame(frame?.Depth + 1 ?? 0, frame, localCount); PushLocal(frame); locals = frame; break; } case (int)InstructionType.Leave: { var frame = PopLocal(); frame = frame.Previous; PushLocal(frame); locals = frame; break; } case (int)InstructionType.Ret: { var returnAddress = PopCall(); PopLocal(); program = returnAddress.Program; code = program.Bytecode; ip = returnAddress.Address; args = _callStackSize > 0 ? PeekCall().Arguments : null; locals = _localStackSize > 0 ? PeekLocal() : null; if (_callStackSize == initialCallDepth) { return(Pop()); } if (Debugger != null && DebuggerCheckReturn()) { DebuggerBreak(program, locals, args, ip, initialCallDepth); } break; } case (int)InstructionType.VarArgs: { var fixedCount = ReadInt32(code, ref ip); var varArgs = MondValue.Array(); for (var i = fixedCount; i < args.Values.Length; i++) { varArgs.ArrayValue.Add(args.Values[i]); } args.Set(args.Depth, fixedCount, varArgs); break; } #endregion #region Branching case (int)InstructionType.Jmp: { var address = ReadInt32(code, ref ip); ip = address; break; } case (int)InstructionType.JmpTrueP: { var address = ReadInt32(code, ref ip); if (Peek()) { ip = address; } break; } case (int)InstructionType.JmpFalseP: { var address = ReadInt32(code, ref ip); if (!Peek()) { ip = address; } break; } case (int)InstructionType.JmpTrue: { var address = ReadInt32(code, ref ip); if (Pop()) { ip = address; } break; } case (int)InstructionType.JmpFalse: { var address = ReadInt32(code, ref ip); if (!Pop()) { ip = address; } break; } case (int)InstructionType.JmpTable: { var start = ReadInt32(code, ref ip); var count = ReadInt32(code, ref ip); var endIp = ip + count * 4; var value = Pop(); if (value.Type == MondValueType.Number) { var number = (double)value; var numberInt = (int)number; if (number >= start && number < start + count && Math.Abs(number - numberInt) <= double.Epsilon) { ip += (numberInt - start) * 4; ip = ReadInt32(code, ref ip); break; } } ip = endIp; break; } #endregion case (int)InstructionType.Breakpoint: { if (Debugger == null) { break; } DebuggerBreak(program, locals, args, ip, initialCallDepth); // we stop for the statement *after* the debugger statement so we // skip the next break opportunity, otherwise we break twice _debugSkip = true; break; } default: throw new MondRuntimeException(RuntimeError.UnhandledOpcode); } } } catch (Exception e) { var message = e.Message.Trim(); // we skip the OOB checks in the stack methods because the CLR has issues eliminating // its own checks, so we let it throw and check here for a bit of a speed boost if (e is IndexOutOfRangeException) { if (_callStackSize >= CallStackCapacity || _localStackSize >= CallStackCapacity || _evalStackSize >= EvalStackCapacity) { message = RuntimeError.StackOverflow; } else if (_callStackSize < 0 || _localStackSize < 0 || _evalStackSize < 0) { message = RuntimeError.StackEmpty; } } StringBuilder stackTraceBuilder; if (e is MondRuntimeException runtimeException && runtimeException.MondStackTrace != null) { stackTraceBuilder = new StringBuilder(runtimeException.MondStackTrace); // check if we are running in a wrapped function var stackTrace = new System.Diagnostics.StackTrace(e, false); var frames = stackTrace.GetFrames(); var foundWrapper = false; // skip the first frame because it's this method? need to verify for (var i = 1; i < frames.Length; i++) { var method = frames[i].GetMethod(); if (method == null) { continue; // ??? } var type = method.DeclaringType; // stop at the next call to Machine.Run because it can be recursive if (type == typeof(Machine) && method.Name == "Run") { break; } // the wrapper is a lambda so it's in a compiler generated type, which will be nested var parentType = type.DeclaringType; if (parentType == null) { continue; } // the type and method are compiler generated so they have a weird (and compiler specific) name const string wrapperMagic = "<CheckWrapFunction>"; // make sure the type is nested in MondValue and check both the type and method name if (parentType == typeof(MondValue) && (method.Name.Contains(wrapperMagic) || type.Name.Contains(wrapperMagic))) { foundWrapper = true; break; } } // don't show a native transition for wrappers if (!foundWrapper) { stackTraceBuilder.AppendLine("[... native ...]"); } }
public void ErrorWithStack(string str) { System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace(); this.Error(str + "[" + t.ToString() + "]"); }
protected void gridFleteros_RowCommand(object sender, GridViewCommandEventArgs e) { // Logger variables System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace(true); System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame(); string className = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name; string methodName = stackFrame.GetMethod().Name; if (e.CommandName == "InsertNew") { GridViewRow row = gridFleteros.FooterRow; TextBox txb1 = row.FindControl("txbNew1") as TextBox; TextBox txb2 = row.FindControl("txbNew2") as TextBox; TextBox txb3 = row.FindControl("txbNew3") as TextBox; TextBox txb4 = row.FindControl("txbNew4") as TextBox; TextBox txb5 = row.FindControl("txbNew5") as TextBox; TextBox txb23 = row.FindControl("txbNew23") as TextBox; TextBox txb24 = row.FindControl("txbNew24") as TextBox; if (txb1 != null && txb2 != null && txb3 != null && txb4 != null && txb5 != null && txb23 != null && txb24 != null) { using (bonisoftEntities context = new bonisoftEntities()) { fletero obj = new fletero(); obj.Nombre = txb1.Text; obj.Comentarios = txb2.Text; obj.Direccion = txb3.Text; obj.Telefono = txb4.Text; obj.Email = txb23.Text; obj.Nro_cuenta = txb24.Text; obj.Depto_empresa = txb5.Text; context.fleteros.Add(obj); context.SaveChanges(); #region Guardar log try { int id = 1; fletero fletero = (fletero)context.fleteros.OrderByDescending(p => p.Fletero_ID).FirstOrDefault(); if (fletero != null) { id = fletero.Fletero_ID; } string userID1 = HttpContext.Current.Session["UserID"].ToString(); string username = HttpContext.Current.Session["UserName"].ToString(); Global_Objects.Logs.AddUserLog("Agrega fletero", fletero.GetType().Name + ": " + id, userID1, username); } catch (Exception ex) { Global_Objects.Logs.AddErrorLog("Excepcion. Guardando log. ERROR:", className, methodName, ex.Message); } #endregion lblMessage.Text = "Agregado correctamente."; BindGrid(); } } } else { //BindGrid(); } }