Beispiel #1
0
        public static bool Write(SafeHandle fileHandle, Option options, ExceptionInfo exceptionInfo = ExceptionInfo.None)
        {
            Process currentProcess = Process.GetCurrentProcess();
            IntPtr currentProcessHandle = currentProcess.Handle;
            var currentProcessId = (uint)currentProcess.Id;

            MiniDumpExceptionInformation exp;
            exp.ThreadId = GetCurrentThreadId();
            exp.ClientPointers = false;
            exp.ExceptionPointers = IntPtr.Zero;
            if (exceptionInfo == ExceptionInfo.Present)
            {
                exp.ExceptionPointers = Marshal.GetExceptionPointers();
            }

            var result = false;
            if (exp.ExceptionPointers == IntPtr.Zero)
            {
                result = MiniDumpWriteDump(currentProcessHandle, currentProcessId, fileHandle, (uint)options, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
            }
            else
            {
                result = MiniDumpWriteDump(currentProcessHandle, currentProcessId, fileHandle, (uint)options, ref exp, IntPtr.Zero, IntPtr.Zero);
            }

            return result;
        }
Beispiel #2
0
        /// <summary>
        /// Writes dump file with the specified options and exception info.
        /// </summary>
        /// <param name="options">The options.</param>
        /// <param name="exceptionInfo">The exception information.</param>
        /// <returns></returns>
        public static bool Write(Option options, ExceptionInfo exceptionInfo)
        {
            Process currentProcess = Process.GetCurrentProcess();
            IntPtr currentProcessHandle = currentProcess.Handle;
            uint currentProcessId = (uint) currentProcess.Id;
            MiniDumpExceptionInformation exp;
            exp.ThreadId = GetCurrentThreadId();
            exp.ClientPointers = false;
            exp.ExceptionPointers = IntPtr.Zero;
            if (exceptionInfo == ExceptionInfo.Present)
            {
                exp.ExceptionPointers = System.Runtime.InteropServices.Marshal.GetExceptionPointers();
            }

            bool bRet = false;
            using (var fs = new FileStream(GenerateDumpFilename(), FileMode.Create, FileAccess.ReadWrite, FileShare.Write))
            {
                if (exp.ExceptionPointers == IntPtr.Zero)
                {
                    bRet = MiniDumpWriteDump(currentProcessHandle, currentProcessId, fs.SafeFileHandle, (uint) options,
                                             IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
                }
                else
                {
                    bRet = MiniDumpWriteDump(currentProcessHandle, currentProcessId, fs.SafeFileHandle, (uint) options,
                                             ref exp,
                                             IntPtr.Zero, IntPtr.Zero);
                }
            }
            return bRet;
        }
Beispiel #3
0
        private static XElement FormatExceptionInfoElement(ExceptionInfo exceptionInfo)
        {
            if (exceptionInfo == null)
                return null;

            return FormatExceptionInfoElement(exceptionInfo, false);
        }
        internal static void FormatException(ExceptionInfo exceptionInfo, StringBuilder builder)
        {
            if (exceptionInfo == null)
            {
                return;
            }

            if (builder.Length > 0)
            {
                builder.AppendLine("--------------------------------");
            }

            builder.AppendFormat("{0}: {1}", FormatValue(exceptionInfo.GetType().ToString()), FormatValue(exceptionInfo.Message));
            builder.AppendLine();

            //if (!String.IsNullOrEmpty(exceptionInfo.Source))
            //{
            //    builder.AppendFormat(" Source: {0}", FormatValue(exceptionInfo.Source));
            //    builder.AppendLine();
            //}

            if (!String.IsNullOrEmpty(exceptionInfo.StackTrace))
            {
                builder.AppendFormat(" Stack: {0}", FormatValue(exceptionInfo.StackTrace));
                builder.AppendLine();
            }

            if (exceptionInfo.InnerException != null)
            {
                FormatException(exceptionInfo.InnerException, builder);
            }
        }
        public ExceptionInfo[] GetExceptionInfos()
        {
            if (_exceptionInfo == null)
            {
                ILGenerator ilgen = _method.GetILGenerator();

                var n = (int)s_fiExceptionCount.GetValue(ilgen);
                if (n > 0)
                {
                    var exceptions = (Array)s_fiExceptions.GetValue(ilgen);

                    _exceptionInfo = new ExceptionInfo[n];
                    for (var i = 0; i < n; i++)
                    {
                        _exceptionInfo[i] = new ExceptionInfo(exceptions.GetValue(i));
                    }
                }
                else
                {
                    _exceptionInfo = Array.Empty<ExceptionInfo>();
                }
            }

            return _exceptionInfo;
        }
 public ExceptionInfo(Exception ex)
 {
     Source = ex.Source;
     StackTrace = ex.StackTrace;
     if (ex.TargetSite != null) TargetSite = ex.TargetSite.Name;
     HelpLink = ex.HelpLink;
     if (ex.InnerException != null) InnerException = new ExceptionInfo(ex.InnerException);
 }
        public ExceptionInfoDocument(ExceptionInfo exceptionInfo)
        {
            ExceptionType = exceptionInfo.ExceptionType;
            Message = exceptionInfo.Message;
            Source = exceptionInfo.Source;
            StackTrace = exceptionInfo.StackTrace;

            if (exceptionInfo.InnerException != null)
                InnerException = new ExceptionInfoDocument(exceptionInfo.InnerException);
        }
            public BugInfo(Exception ex)
            {
                Subject = ex.Message;

                var exceptionInfo = new ExceptionInfo(ex);
                string json = JSON.FromObject(exceptionInfo);
                Message = json;

                Timestamp = DateTime.UtcNow;
            }
 public ExceptionInfo(Exception ex)
 {
     Message = ex.Message;
     HResult = ex.HResult;
     Type = ex.GetType().FullName;
     Source = ex.Source;
     StackTrace = ex.StackTrace;
     if (ex.InnerException != null)
         InnerException = new ExceptionInfo(ex.InnerException);
 }
        public ActivityExceptionImpl(string activityName, HostInfo host, Guid executionId, DateTime timestamp, TimeSpan elapsed,
            ExceptionInfo exceptionInfo)
        {
            ExecutionId = executionId;

            Timestamp = timestamp;
            Elapsed = elapsed;
            Name = activityName;
            Host = host;
            ExceptionInfo = exceptionInfo;
        }
 public RoutingSlipActivityFaultedMessage(HostInfo host, Guid trackingNumber, string activityName, Guid activityTrackingNumber,
     DateTime timestamp, TimeSpan duration, ExceptionInfo exceptionInfo, IDictionary<string, object> variables,
     IDictionary<string, object> arguments)
 {
     Host = host;
     TrackingNumber = trackingNumber;
     Timestamp = timestamp;
     Duration = duration;
     ActivityTrackingNumber = activityTrackingNumber;
     ActivityName = activityName;
     Variables = variables;
     Arguments = arguments;
     ExceptionInfo = exceptionInfo;
 }
Beispiel #12
0
        private static XElement FormatExceptionInfoElement(ExceptionInfo exceptionInfo, bool isInnerException)
        {
            if (exceptionInfo == null)
                return null;

            string elementName = "exceptionInfo";

            if (isInnerException)
                elementName = "innerExceptionInfo";

            return new XElement(elementName
                            , new XElement("message", exceptionInfo.Message)
                            , new XElement("stackTrace", exceptionInfo.StackTrace)
                            , FormatExceptionInfoElement(exceptionInfo.InnerException, true)
                            );
        }
            protected override void Before_all_tests()
            {
                base.Before_all_tests();

                try
                {
                    throw new Exception("Hello");
                }
                catch (Exception ex2)
                {
                    exception = ex2;
                }

                beforeExceptionInfo = new ExceptionInfo(exception);

                afterExceptionInfo = beforeExceptionInfo.Serialize().Deserialize<ExceptionInfo>();
            }
        public CompensationFailed(HostInfo host, Guid trackingNumber, string activityName, Guid executionId,
            DateTime timestamp, TimeSpan duration, DateTime failureTimestamp, TimeSpan routingSlipDuration,
            ExceptionInfo exceptionInfo, IDictionary<string, object> variables, IDictionary<string, object> data)
        {
            _failureTimestamp = failureTimestamp;
            _routingSlipDuration = routingSlipDuration;
            Host = host;
            _duration = duration;
            _timestamp = timestamp;

            TrackingNumber = trackingNumber;
            ExecutionId = executionId;
            ActivityName = activityName;
            Data = data;
            Variables = variables;
            ExceptionInfo = exceptionInfo;
        }
Beispiel #15
0
            protected override void Before_all_tests()
            {
                base.Before_all_tests();

                try
                {
                    throw new Exception("Expected:&lt;1&gt;. Actual:&lt;2&gt;.");
                }
                catch (Exception ex2)
                {
                    exception = ex2;
                }

                beforeExceptionInfo = new ExceptionInfo(exception);

                afterExceptionInfo = beforeExceptionInfo.Serialize().Deserialize<ExceptionInfo>();
            }
        public RichILStringToTextWriter(TextWriter writer, ExceptionInfo[] exceptions)
            : base(writer)
        {
            foreach (var e in exceptions)
            {
                var startCount = 0;
                if (!_startCounts.TryGetValue(e.StartAddress, out startCount))
                {
                    _startCounts.Add(e.StartAddress, startCount);
                }

                _startCounts[e.StartAddress] += e.Handlers.Length;

                foreach (var c in e.Handlers)
                {
                    if (c.Kind == HandlerKind.Finally)
                    {
                        _startFinally.Add(c.StartAddress);
                    }
                    else if (c.Kind == HandlerKind.Fault)
                    {
                        _startFault.Add(c.StartAddress);
                    }
                    else if (c.Kind == HandlerKind.Filter)
                    {
                        _startFilter.Add(c.StartAddress);
                    }
                    else
                    {
                        _startCatch.Add(c.StartAddress, c.Type);
                    }

                    var endCount = 0;

                    if (!_endCounts.TryGetValue(c.EndAddress, out endCount))
                    {
                        _endCounts.Add(c.EndAddress, endCount);
                    }

                    _endCounts[c.EndAddress]++;
                }
            }
        }
Beispiel #17
0
        public static bool Write(SafeHandle fileHandle, Option options, ExceptionInfo exceptionInfo)
        {
            Process currentProcess = Process.GetCurrentProcess();

            IntPtr currentProcessHandle = currentProcess.Handle;

            uint currentProcessId = (uint)currentProcess.Id;

            MiniDumpExceptionInformation exp;

            exp.ThreadId = GetCurrentThreadId();

            exp.ClientPointers = false;

            exp.ExceptionPointers = IntPtr.Zero;

            if (exceptionInfo == ExceptionInfo.Present)
            {

                exp.ExceptionPointers = System.Runtime.InteropServices.Marshal.GetExceptionPointers();

            }

            bool bRet = false;

            if (exp.ExceptionPointers == IntPtr.Zero)
            {

                bRet = MiniDumpWriteDump(currentProcessHandle, currentProcessId, fileHandle, (uint)options, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);

            }

            else
            {

                bRet = MiniDumpWriteDump(currentProcessHandle, currentProcessId, fileHandle, (uint)options, ref exp, IntPtr.Zero, IntPtr.Zero);

            }

            return bRet;
        }
Beispiel #18
0
 /// <summary>
 /// Initializes a new instance of the <see cref="FaultStep1"/> class.
 /// </summary>
 /// <param name="info">
 /// The info.
 /// </param>
 /// <param name="message">
 /// The message.
 /// </param>
 public FaultStep1(ExceptionInfo info, string message)
     : base(info, message)
 {
 }
Beispiel #19
0
 public BufferReader(Buffer buffer)
     : base(ExceptionInfo.Return <IntPtr>(buffer.Handle, BufferReader_Create))
 {
 }
Beispiel #20
0
 public bool CanRemove(ExceptionInfo info)
 {
     return !info.IsOtherExceptions;
 }
Beispiel #21
0
        private void ShowErrorDialog(Exception ex, bool showStackTrace, bool internalError, ExceptionInfo info)
        {
            string stackTrace = ex.ToString();
            string message    = GetNestedMessages(ex);

            System.Collections.Specialized.StringDictionary additionalInfo =
                new System.Collections.Specialized.StringDictionary();

            IAnkhSolutionSettings ss = GetService <IAnkhSolutionSettings>();

            if (ss != null)
            {
                additionalInfo.Add("VS-Version", VSVersion.FullVersion.ToString());
            }

            if (info != null && info.CommandArgs != null)
            {
                additionalInfo.Add("Command", info.CommandArgs.Command.ToString());
            }

            IAnkhPackage pkg = GetService <IAnkhPackage>();

            if (pkg != null)
            {
                additionalInfo.Add("Ankh-Version", pkg.UIVersion.ToString());
            }

            additionalInfo.Add("SharpSvn-Version", SharpSvn.SvnClient.SharpSvnVersion.ToString());
            additionalInfo.Add("Svn-Version", SharpSvn.SvnClient.Version.ToString());
            additionalInfo.Add("OS-Version", Environment.OSVersion.Version.ToString());

            using (ErrorDialog dlg = new ErrorDialog())
            {
                dlg.ErrorMessage   = message;
                dlg.ShowStackTrace = showStackTrace;
                dlg.StackTrace     = stackTrace;
                dlg.InternalError  = internalError;

                if (dlg.ShowDialog(Context) == DialogResult.Retry)
                {
                    string subject = _errorReportSubject;

                    if (info != null && info.CommandArgs != null)
                    {
                        subject = string.Format("Error handling {0}", info.CommandArgs.Command);
                    }

                    SvnException sx = ex as SvnException;
                    SvnException ix;

                    while (sx != null &&
                           sx.SvnErrorCode == SvnErrorCode.SVN_ERR_BASE &&
                           (null != (ix = sx.InnerException as SvnException)))
                    {
                        sx = ix;
                    }

                    if (sx != null)
                    {
                        SvnException rc = sx.RootCause as SvnException;
                        if (rc == null || rc.SvnErrorCode == sx.SvnErrorCode)
                        {
                            subject += " (" + ErrorToString(sx) + ")";
                        }
                        else
                        {
                            subject += " (" + ErrorToString(sx) + "-" + ErrorToString(rc) + ")";
                        }
                    }

                    AnkhErrorMessage.SendByMail(_errorReportMailAddress,
                                                subject, ex, typeof(AnkhErrorHandler).Assembly, additionalInfo);
                }
            }
        }
Beispiel #22
0
 private void HandleRequestDispatcherException(ExceptionInfo exceptionInfo)
 {
     _userDialogService.ShowDialog(exceptionInfo.Message, "Error Loading Patient List", UserDialogServiceOptions.Ok);
     IsLoading = false;
 }
Beispiel #23
0
        private static void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
        {
            var ex      = e.Exception;
            var Message = Times.DateTimeUtcWithMillisecondsToString(DateTime.UtcNow) + "\r\n" + ExceptionInfo.GetExceptionInfo(ex);

            Console.WriteLine(Message);
            FileLoggerSync.WriteLog("Crash.log", Message);
            Environment.Exit(-1);
        }
Beispiel #24
0
        /// <summary>
        /// Constractor.。
        /// </summary>
        /// <param name="info">Infomation</param>
#else
        /// <summary>
        /// コンストラクタ。
        /// </summary>
        /// <param name="info">例外情報。</param>
#endif
        public FriendlyOperationException(ExceptionInfo info) : base(ExceptionInfoMessageFormat(info))
        {
            _exceptionInfo = info;
        }
 public Task PublishRoutingSlipActivityFaulted(string activityName, Guid executionId, DateTime timestamp, TimeSpan duration, ExceptionInfo exceptionInfo,
                                               IDictionary <string, object> variables, IDictionary <string, object> arguments)
 {
     return(PublishEvent <RoutingSlipActivityFaulted>(RoutingSlipEvents.ActivityFaulted, contents => new RoutingSlipActivityFaultedMessage(
                                                          _host,
                                                          _routingSlip.TrackingNumber,
                                                          activityName,
                                                          executionId,
                                                          timestamp,
                                                          duration,
                                                          exceptionInfo,
                                                          contents == RoutingSlipEventContents.All || contents.HasFlag(RoutingSlipEventContents.Variables)
             ? variables
             : GetEmptyObject(),
                                                          contents == RoutingSlipEventContents.All || contents.HasFlag(RoutingSlipEventContents.Arguments)
             ? arguments
             : GetEmptyObject())));
 }
Beispiel #26
0
		static int CompareExceptionInfos(ExceptionInfo a, ExceptionInfo b) {
			int res = a.ExceptionType.CompareTo(b.ExceptionType);
			if (res != 0)
				return res;
			if (a.IsOtherExceptions != b.IsOtherExceptions)
				return a.IsOtherExceptions ? -1 : 1;
			return StringComparer.CurrentCultureIgnoreCase.Compare(a.Name, b.Name);
		}
Beispiel #27
0
        public static void Run(Configuration c)
        {
            Console.WriteLine(Times.DateTimeUtcWithMillisecondsToString(DateTime.UtcNow) + @"  服务器进程启动。");

            var ProcessorCount  = Environment.ProcessorCount;
            var WorkThreadCount = c.NumThread.OnSome ? Math.Max(1, c.NumThread.Value) : ProcessorCount;

            Console.WriteLine(@"逻辑处理器数量: " + ProcessorCount.ToString());
            Console.WriteLine(@"工作线程数量: {0}".Formats(WorkThreadCount));

            using (var tp = new CountedThreadPool("Worker", WorkThreadCount))
                using (var tpPurifier = new CountedThreadPool("Purifier", 2))
                    using (var tpLog = new CountedThreadPool("Log", 1))
                        using (var ExitEvent = new AutoResetEvent(false))
                            using (var Logger = new ConsoleLogger(tpLog.QueueUserWorkItem))
                            {
                                Logger.Start();

                                LockedVariable <ConsoleCancelEventHandler> CancelKeyPressInner = null;
                                CancelKeyPressInner = new LockedVariable <ConsoleCancelEventHandler>((sender, e) =>
                                {
                                    CancelKeyPressInner.Update(v => { return(null); });
                                    e.Cancel = true;
                                    Console.WriteLine(Times.DateTimeUtcWithMillisecondsToString(DateTime.UtcNow) + @"  命令行中断退出。");
                                    ExitEvent.Set();
                                });
                                ConsoleCancelEventHandler CancelKeyPress = (sender, e) =>
                                {
                                    var f = CancelKeyPressInner.Check(v => v);
                                    if (f == null)
                                    {
                                        return;
                                    }
                                    f(sender, e);
                                };
                                Console.CancelKeyPress += CancelKeyPress;

                                var ChatContexts = new List <ServerContext>();

                                var ServerCloses = new List <Action>();

                                try
                                {
                                    foreach (var s in c.Servers)
                                    {
                                        if (s.OnChat)
                                        {
                                            var ss            = s.Chat;
                                            var ServerContext = new ServerContext();
                                            ChatContexts.Add(ServerContext);

                                            ServerContext.EnableLogNormalIn      = c.EnableLogNormalIn;
                                            ServerContext.EnableLogNormalOut     = c.EnableLogNormalOut;
                                            ServerContext.EnableLogUnknownError  = c.EnableLogUnknownError;
                                            ServerContext.EnableLogCriticalError = c.EnableLogCriticalError;
                                            ServerContext.EnableLogPerformance   = c.EnableLogPerformance;
                                            ServerContext.EnableLogSystem        = c.EnableLogSystem;
                                            ServerContext.EnableLogTransport     = c.EnableLogTransport;
                                            ServerContext.ServerDebug            = c.ServerDebug;
                                            ServerContext.ClientDebug            = c.ClientDebug;

                                            ServerContext.Shutdown += () =>
                                            {
                                                Console.WriteLine(Times.DateTimeUtcWithMillisecondsToString(DateTime.UtcNow) + @"  远程命令退出。");
                                                ExitEvent.Set();
                                            };
                                            if (c.EnableLogConsole)
                                            {
                                                ServerContext.SessionLog += Logger.Push;
                                            }

                                            var Protocols       = new List <IServer>();
                                            var Factory         = new TaskFactory(tp);
                                            var PurifierFactory = new TaskFactory(tp);
                                            foreach (var p in ss.Protocols)
                                            {
                                                if (System.Diagnostics.Debugger.IsAttached)
                                                {
                                                    Protocols.Add(StartProtocol(c, p, ServerContext, Factory, PurifierFactory));
                                                }
                                                else
                                                {
                                                    try
                                                    {
                                                        Protocols.Add(StartProtocol(c, p, ServerContext, Factory, PurifierFactory));
                                                    }
                                                    catch (Exception ex)
                                                    {
                                                        var Message = Times.DateTimeUtcWithMillisecondsToString(DateTime.UtcNow) + "\r\n" + ExceptionInfo.GetExceptionInfo(ex);
                                                        Console.WriteLine(Message);
                                                        FileLoggerSync.WriteLog("Error.log", Message);
                                                    }
                                                }
                                            }

                                            ServerCloses.Add(() =>
                                            {
                                                foreach (var Session in ServerContext.Sessions.AsParallel())
                                                {
                                                    Session.SessionLock.EnterReadLock();;
                                                    try
                                                    {
                                                        if (Session.EventPump != null)
                                                        {
                                                            Session.EventPump.ServerShutdown(new Communication.ServerShutdownEvent {
                                                            });
                                                        }
                                                    }
                                                    finally
                                                    {
                                                        Session.SessionLock.ExitReadLock();
                                                    }
                                                }

                                                foreach (var p in Protocols)
                                                {
                                                    if (System.Diagnostics.Debugger.IsAttached)
                                                    {
                                                        StopProtocol(p);
                                                    }
                                                    else
                                                    {
                                                        try
                                                        {
                                                            StopProtocol(p);
                                                        }
                                                        catch (Exception ex)
                                                        {
                                                            var Message = Times.DateTimeUtcWithMillisecondsToString(DateTime.UtcNow) + "\r\n" + ExceptionInfo.GetExceptionInfo(ex);
                                                            Console.WriteLine(Message);
                                                            FileLoggerSync.WriteLog("Error.log", Message);
                                                        }
                                                    }
                                                }

                                                if (c.EnableLogConsole)
                                                {
                                                    ServerContext.SessionLog -= Logger.Push;
                                                }

                                                Console.WriteLine(@"ChatServerContext.RequestCount = {0}".Formats(ServerContext.RequestCount));
                                                Console.WriteLine(@"ChatServerContext.ReplyCount = {0}".Formats(ServerContext.ReplyCount));
                                                Console.WriteLine(@"ChatServerContext.EventCount = {0}".Formats(ServerContext.EventCount));
                                            });
                                        }
                                        else
                                        {
                                            throw new InvalidOperationException("未知服务器类型: " + s._Tag.ToString());
                                        }
                                    }

                                    ExitEvent.WaitOne();
                                    Console.CancelKeyPress -= CancelKeyPress;
                                }
                                finally
                                {
                                    foreach (var a in ServerCloses)
                                    {
                                        a();
                                    }
                                }
                            }

            Console.WriteLine(Times.DateTimeUtcWithMillisecondsToString(DateTime.UtcNow) + @"  服务器进程退出完成。");
        }
Beispiel #28
0
        public void Start()
        {
            var Success = false;

            try
            {
                IsRunningValue.Update
                (
                    b =>
                {
                    if (b)
                    {
                        throw new InvalidOperationException();
                    }

                    if (BindingsValue.Length == 0)
                    {
                        throw new Exception("NoValidBinding");
                    }

                    ListeningTaskTokenSource = new CancellationTokenSource();

                    var ListeningTaskToken = ListeningTaskTokenSource.Token;

                    foreach (var Binding in BindingsValue)
                    {
                        Listener.Prefixes.Add(Binding);
                    }
                    if (UnauthenticatedSessionIdleTimeoutValue.HasValue)
                    {
                        SetTimer(Listener, UnauthenticatedSessionIdleTimeoutValue.Value);
                    }

                    Action <HttpListenerContext> PurifyContext = ListenerContext =>
                    {
                        try
                        {
                            ListenerContext.Response.Close();
                        }
                        catch
                        {
                        }
                    };
                    Action <HttpSession> Purify = StoppingSession =>
                    {
                        SessionSets.DoAction
                        (
                            ss =>
                        {
                            if (ss.Sessions.Contains(StoppingSession))
                            {
                                ss.Sessions.Remove(StoppingSession);
                                var IpAddress = StoppingSession.RemoteEndPoint.Address;
                                var isi       = ss.IpSessions[IpAddress];
                                if (isi.Authenticated.Contains(StoppingSession))
                                {
                                    isi.Authenticated.Remove(StoppingSession);
                                }
                                isi.Count -= 1;
                                if (isi.Count == 0)
                                {
                                    ss.IpSessions.Remove(IpAddress);
                                }
                                var SessionId = ss.SessionToId[StoppingSession];
                                ss.SessionIdToSession.Remove(SessionId);
                                ss.SessionToId.Remove(StoppingSession);
                            }
                        }
                        );
                        StoppingSession.Dispose();
                    };

                    Action <HttpListenerContext> Accept = a =>
                    {
                        IPEndPoint e = null;
                        try
                        {
                            e = (IPEndPoint)a.Request.RemoteEndPoint;
                            var XForwardedFor = a.Request.Headers["X-Forwarded-For"];
                            var Address       = e.Address;
                            if ((XForwardedFor != null) && (XForwardedFor != ""))
                            {
                                try
                                {
                                    IPAddress addr;
                                    if (IPAddress.TryParse(XForwardedFor.Split(',')[0].Trim(' '), out addr))
                                    {
                                        Address = addr;
                                    }
                                }
                                catch
                                {
                                }
                            }
                            var XForwardedPort = a.Request.Headers["X-Forwarded-Port"];
                            var Port           = e.Port;
                            if ((XForwardedPort != null) && (XForwardedPort != ""))
                            {
                                try
                                {
                                    int p;
                                    if (int.TryParse(XForwardedPort.Split(',')[0].Trim(' '), out p))
                                    {
                                        Port = p;
                                    }
                                }
                                catch
                                {
                                }
                            }
                            e = new IPEndPoint(Address, Port);

                            if (ServerContext.EnableLogSystem)
                            {
                                ServerContext.RaiseSessionLog(new SessionLogEntry {
                                    Token = "", RemoteEndPoint = e, Time = DateTime.UtcNow, Type = "Sys", Name = "RequestIn", Message = ""
                                });
                            }

                            if (a.Request.ContentLength64 < 0)
                            {
                                a.Response.StatusCode = 411;
                                NotifyListenerContextQuit(a);
                                return;
                            }

                            if (a.Request.ContentLength64 > ReadBufferSize)
                            {
                                a.Response.StatusCode = 413;
                                NotifyListenerContextQuit(a);
                                return;
                            }

                            if (!IsMatchBindingName(a.Request.Url))
                            {
                                a.Response.StatusCode = 404;
                                NotifyListenerContextQuit(a);
                                return;
                            }

                            var Headers = a.Request.Headers.AllKeys.ToDictionary(k => k, k => a.Request.Headers[k]);
                            if (Headers.ContainsKey("Range"))
                            {
                                a.Response.StatusCode = 400;
                                NotifyListenerContextQuit(a);
                                return;
                            }
                            if (Headers.ContainsKey("Accept-Charset"))
                            {
                                var AcceptCharsetParts = Headers["Accept-Charset"].Split(';');
                                if (AcceptCharsetParts.Length == 0)
                                {
                                    a.Response.StatusCode = 400;
                                    NotifyListenerContextQuit(a);
                                    return;
                                }
                                var EncodingNames = AcceptCharsetParts[0].Split(',').Select(n => n.Trim(' ')).ToArray();
                                if (!(EncodingNames.Contains("utf-8", StringComparer.OrdinalIgnoreCase) || EncodingNames.Contains("*", StringComparer.OrdinalIgnoreCase)))
                                {
                                    a.Response.StatusCode = 400;
                                    NotifyListenerContextQuit(a);
                                    return;
                                }
                            }

                            {
                                var Query = HttpListenerRequestExtension.GetQuery(a.Request);

                                if (Query.ContainsKey("sessionid"))
                                {
                                    HttpSession s = null;

                                    var SessionId = Query["sessionid"];
                                    var Close     = false;
                                    SessionSets.DoAction
                                    (
                                        ss =>
                                    {
                                        if (!ss.SessionIdToSession.ContainsKey(SessionId))
                                        {
                                            a.Response.StatusCode = 403;
                                            Close = true;
                                            return;
                                        }
                                        var CurrentSession = ss.SessionIdToSession[SessionId];
                                        if (!CurrentSession.RemoteEndPoint.Address.Equals(e.Address))
                                        {
                                            a.Response.StatusCode = 403;
                                            Close = true;
                                            return;
                                        }
                                        s = ss.SessionIdToSession[SessionId];
                                    }
                                    );
                                    if (Close)
                                    {
                                        NotifyListenerContextQuit(a);
                                        return;
                                    }
                                    var NewSessionId = Convert.ToBase64String(Cryptography.CreateRandom(64));
                                    SessionSets.DoAction
                                    (
                                        ss =>
                                    {
                                        ss.SessionIdToSession.Remove(SessionId);
                                        ss.SessionIdToSession.Add(NewSessionId, s);
                                        ss.SessionToId[s] = NewSessionId;
                                    }
                                    );
                                    if (!s.Push(a, NewSessionId))
                                    {
                                        NotifyListenerContextQuit(a);
                                        return;
                                    }
                                    return;
                                }
                            }

                            if (MaxConnectionsValue.HasValue && (SessionSets.Check(ss => ss.Sessions.Count) >= MaxConnectionsValue.Value))
                            {
                                ContextPurifyConsumer.DoOne();
                                PurifyConsumer.DoOne();
                            }
                            if (MaxConnectionsValue.HasValue && (SessionSets.Check(ss => ss.Sessions.Count) >= MaxConnectionsValue.Value))
                            {
                                a.Response.StatusCode = 503;
                                NotifyListenerContextQuit(a);
                                return;
                            }

                            if (MaxConnectionsPerIPValue.HasValue && (SessionSets.Check(ss => ss.IpSessions.ContainsKey(e.Address) ? ss.IpSessions[e.Address].Count : 0) >= MaxConnectionsPerIPValue.Value))
                            {
                                a.Response.StatusCode = 503;
                                NotifyListenerContextQuit(a);
                                return;
                            }

                            if (MaxUnauthenticatedPerIPValue.HasValue && (SessionSets.Check(ss => ss.IpSessions.ContainsKey(e.Address) ? (ss.IpSessions[e.Address].Count - ss.IpSessions[e.Address].Authenticated.Count) : 0) >= MaxUnauthenticatedPerIPValue.Value))
                            {
                                a.Response.StatusCode = 503;
                                NotifyListenerContextQuit(a);
                                return;
                            }

                            {
                                var s = new HttpSession(this, e, VirtualTransportServerFactory, QueueUserWorkItem);

                                var SessionId = Convert.ToBase64String(Cryptography.CreateRandom(64));
                                SessionSets.DoAction
                                (
                                    ss =>
                                {
                                    ss.Sessions.Add(s);
                                    if (ss.IpSessions.ContainsKey(e.Address))
                                    {
                                        ss.IpSessions[e.Address].Count += 1;
                                    }
                                    else
                                    {
                                        var isi    = new IpSessionInfo();
                                        isi.Count += 1;
                                        ss.IpSessions.Add(e.Address, isi);
                                    }
                                    ss.SessionIdToSession.Add(SessionId, s);
                                    ss.SessionToId.Add(s, SessionId);
                                }
                                );

                                s.Start();
                                if (!s.Push(a, SessionId))
                                {
                                    NotifyListenerContextQuit(a);
                                    return;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            if (ServerContext.EnableLogSystem)
                            {
                                ServerContext.RaiseSessionLog(new SessionLogEntry {
                                    Token = "", RemoteEndPoint = e ?? new IPEndPoint(IPAddress.Any, 0), Time = DateTime.UtcNow, Type = "Sys", Name = "Exception", Message = ExceptionInfo.GetExceptionInfo(ex)
                                });
                            }
                            try
                            {
                                a.Response.StatusCode = 500;
                            }
                            catch
                            {
                            }
                            NotifyListenerContextQuit(a);
                        }
                    };
                    AcceptConsumer = new AsyncConsumer <HttpListenerContext>(QueueUserWorkItem, a => { Accept(a); return(true); }, int.MaxValue);

                    ContextPurifyConsumer = new AsyncConsumer <HttpListenerContext>(QueueUserWorkItem, l => { PurifyContext(l); return(true); }, int.MaxValue);
                    PurifyConsumer        = new AsyncConsumer <HttpSession>(PurifierQueueUserWorkItem, s => { Purify(s); return(true); }, int.MaxValue);

                    if (UnauthenticatedSessionIdleTimeoutValue.HasValue || SessionIdleTimeoutValue.HasValue)
                    {
                        var TimePeriod           = TimeSpan.FromSeconds(Math.Max(TimeoutCheckPeriodValue, 1));
                        LastActiveTimeCheckTimer = new Timer(state =>
                        {
                            if (UnauthenticatedSessionIdleTimeoutValue.HasValue)
                            {
                                var CheckTime = DateTime.UtcNow.AddIntSeconds(-UnauthenticatedSessionIdleTimeoutValue.Value);
                                SessionSets.DoAction
                                (
                                    ss =>
                                {
                                    foreach (var s in ss.Sessions)
                                    {
                                        var IpAddress = s.RemoteEndPoint.Address;
                                        var isi       = ss.IpSessions[IpAddress];
                                        if (!isi.Authenticated.Contains(s))
                                        {
                                            if (s.LastActiveTime < CheckTime)
                                            {
                                                PurifyConsumer.Push(s);
                                            }
                                        }
                                    }
                                }
                                );
                            }

                            if (SessionIdleTimeoutValue.HasValue)
                            {
                                var CheckTime = DateTime.UtcNow.AddIntSeconds(-SessionIdleTimeoutValue.Value);
                                SessionSets.DoAction
                                (
                                    ss =>
                                {
                                    foreach (var s in ss.Sessions)
                                    {
                                        var IpAddress = s.RemoteEndPoint.Address;
                                        var isi       = ss.IpSessions[IpAddress];
                                        if (isi.Authenticated.Contains(s))
                                        {
                                            if (s.LastActiveTime < CheckTime)
                                            {
                                                PurifyConsumer.Push(s);
                                            }
                                        }
                                    }
                                }
                                );
                            }
                        }, null, TimePeriod, TimePeriod);
                    }

                    try
                    {
                        Listener.Start();
                    }
                    catch (HttpListenerException ex)
                    {
                        String Message;
                        if (ex.ErrorCode == 5)
                        {
                            var l = new List <String>();
                            l.Add("Under Windows, try run the following as administrator:");
                            var UserDomainName = Environment.UserDomainName;
                            var UserName       = Environment.UserName;
                            foreach (var p in BindingsValue)
                            {
                                l.Add(@"netsh http add urlacl url={0} user={1}\{2}".Formats(p, UserDomainName, UserName));
                            }
                            l.Add("and delete it when you don't need it:");
                            foreach (var p in BindingsValue)
                            {
                                l.Add(@"netsh http delete urlacl url={0}".Formats(p));
                            }
                            Message = String.Join("\r\n", l.ToArray());
                        }
                        else
                        {
                            Message = ExceptionInfo.GetExceptionInfo(ex);
                        }
                        throw new AggregateException(Message, ex);
                    }
                    Action Listen = () =>
                    {
                        if (ListeningTaskToken.IsCancellationRequested)
                        {
                            return;
                        }
                        var l  = Listener;
                        var lc = ListenConsumer;
                        l.BeginGetContext(ar =>
                        {
                            if (!l.IsListening)
                            {
                                return;
                            }
                            try
                            {
                                var a = l.EndGetContext(ar);
                                AcceptConsumer.Push(a);
                            }
                            catch (HttpListenerException)
                            {
                            }
                            catch (ObjectDisposedException)
                            {
                            }
                            lc.Push(0);
                        }, null);
                    };
                    ListenConsumer = new AsyncConsumer <int>(QueueUserWorkItem, i => { Listen(); return(true); }, 1);

                    Listen();

                    Success = true;

                    return(true);
                }
                );
            }
            finally
            {
                if (!Success)
                {
                    Stop();
                }
            }
        }
Beispiel #29
0
 public static int Main()
 {
     if (System.Diagnostics.Debugger.IsAttached)
     {
         return(MainInner());
     }
     else
     {
         AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
         TaskScheduler.UnobservedTaskException      += TaskScheduler_UnobservedTaskException;
         try
         {
             return(MainInner());
         }
         catch (Exception ex)
         {
             var Message = Times.DateTimeUtcWithMillisecondsToString(DateTime.UtcNow) + "\r\n" + ExceptionInfo.GetExceptionInfo(ex);
             Console.WriteLine(Message);
             FileLoggerSync.WriteLog("Crash.log", Message);
             return(-1);
         }
     }
 }
 private void HandleRequestException(ExceptionInfo exceptionInfo)
 {
     IsLoading = false;
     _userDialogService.ShowDialog(exceptionInfo.Message, "Error Geting Patient List", UserDialogServiceOptions.Ok);
 }
        void UpdateSelectedException(ExceptionInfo ex)
        {
            selected = ex;
            var  model    = (ListStore)stackTraceTreeView.Model;
            bool external = false;

            model.Clear();
            var parentException = ex;

            while (parentException != null)
            {
                foreach (var frame in parentException.StackTrace)
                {
                    bool isUserCode = IsUserCode(frame);

                    if (onlyShowMyCodeCheckbox.Active && !isUserCode)
                    {
                        if (!external)
                        {
                            var str = "<b>" + GettextCatalog.GetString("[External Code]") + "</b>";
                            model.AppendValues(null, str, false);
                            external = true;
                        }

                        continue;
                    }

                    model.AppendValues(frame, null, isUserCode);
                    external = false;
                }
                if (!reverseInnerExceptions.TryGetValue(parentException, out parentException))
                {
                    parentException = null;
                }
            }

            if (useNewTreeView)
            {
                controller.ClearAll();
            }
            else
            {
                ((ObjectValueTreeView)exceptionValueTreeView).ClearAll();
            }

            if (!ex.IsEvaluating && ex.Instance != null)
            {
                var opts = DebuggingService.GetUserOptions().EvaluationOptions.Clone();
                opts.FlattenHierarchy = true;

                var values = ex.Instance.GetAllChildren(opts);

                if (useNewTreeView)
                {
                    controller.AddValues(values);
                }
                else
                {
                    ((ObjectValueTreeView)exceptionValueTreeView).AddValues(values);
                }
            }

            if (ex.StackIsEvaluating)
            {
                var str = GettextCatalog.GetString("Loading...");
                model.AppendValues(null, str, false);
            }

            if (innerExceptionTypeLabel != null)
            {
                innerExceptionTypeLabel.Markup  = "<b>" + GLib.Markup.EscapeText(ex.Type) + "</b>";
                innerExceptionMessageLabel.Text = ex.Message;
                if (!string.IsNullOrEmpty(ex.HelpLink))
                {
                    innerExceptionHelpLinkButton.Label = GettextCatalog.GetString("Read More…");
                    innerExceptionHelpLink             = ex.HelpLink;
                    innerExceptionHelpLinkButton.Show();
                }
                else
                {
                    innerExceptionHelpLink = string.Empty;
                    innerExceptionHelpLinkButton.Hide();
                }
            }
        }
 internal static string GetHelpLinkMarkup(ExceptionInfo exception)
 {
     return($"<a href=\"{System.Security.SecurityElement.Escape (exception.HelpLink)}\">{GettextCatalog.GetString ("More information")}</a>");
 }
Beispiel #33
0
 public ExceptionCaughtMessage(ExceptionInfo val, FilePath file, int line, int col)
 {
     File = file;
     Line = line;
     ex   = val;
 }
Beispiel #34
0
 private void HandleCreateNewClinicalCaseRequestDispatcherException(ExceptionInfo exceptionInfo)
 {
     _userDialogService.ShowDialog(exceptionInfo.Message, "Clinical Case created failed.", UserDialogServiceOptions.Ok);
 }
Beispiel #35
0
 private static void HandleInitializationException(ExceptionInfo exceptionInfo)
 {
     throw new Exception("Load metadata for modules failed. Inner exception: " + exceptionInfo.Message);
 }
Beispiel #36
0
            private void DoHandle(Exception ex, ExceptionInfo info)
            {
                bool svnException = (ex is SvnException);

                _handler.ShowErrorDialog(ex, !svnException, !svnException, info);
            }
 private void HandleRequestDispatcherException(ExceptionInfo exceptionInfo)
 {
     IsLoading = false;
     _userDialogService.ShowDialog(exceptionInfo.Message, "NIDA Drug Questionnaire operation failed.", UserDialogServiceOptions.Ok);
 }
Beispiel #38
0
        private static void CurrentDomain_UnhandledException(Object sender, UnhandledExceptionEventArgs e)
        {
            var ex      = (Exception)(e.ExceptionObject);
            var Message = Times.DateTimeUtcWithMillisecondsToString(DateTime.UtcNow) + "\r\n" + ExceptionInfo.GetExceptionInfo(ex, null);

            Console.WriteLine(Message);
            FileLoggerSync.WriteLog("Crash.log", Message);
            Environment.Exit(-1);
        }
Beispiel #39
0
        public UnityDebugSession() : base(true)
        {
            _variableHandles = new Handles <ObjectValue[]>();
            _frameHandles    = new Handles <Mono.Debugging.Client.StackFrame>();
            _seenThreads     = new Dictionary <int, VSCodeDebug.Thread>();

            Configuration.Current.MaxConnectionAttempts     = 10;
            Configuration.Current.ConnectionAttemptInterval = 500;

            // install an event handler in SDB
            Debugger.Callback = (type, threadinfo, text) => {
                int tid;
                switch (type)
                {
                case "TargetStopped":
                    Stopped();
                    SendEvent(CreateStoppedEvent("step", threadinfo));
                    break;

                case "TargetHitBreakpoint":
                    Stopped();
                    SendEvent(CreateStoppedEvent("breakpoint", threadinfo));
                    break;

                case "TargetExceptionThrown":
                case "TargetUnhandledException":
                    Stopped();
                    ExceptionInfo ex = Debugger.ActiveException;
                    if (ex != null)
                    {
                        _exception = ex.Instance;
                    }
                    SendEvent(CreateStoppedEvent("exception", threadinfo, Debugger.ActiveException.Message));
                    break;

                case "TargetExited":
                    Terminate("target exited");
                    break;

                case "TargetThreadStarted":
                    tid = (int)threadinfo.Id;
                    lock (_seenThreads) {
                        _seenThreads[tid] = new VSCodeDebug.Thread(tid, threadinfo.Name);
                    }
                    SendEvent(new ThreadEvent("started", tid));
                    break;

                case "TargetThreadStopped":
                    tid = (int)threadinfo.Id;
                    lock (_seenThreads) {
                        _seenThreads.Remove(tid);
                    }
                    SendEvent(new ThreadEvent("exited", tid));
                    break;

                case "Output":
                    SendOutput("stdout", text);
                    break;

                case "ErrorOutput":
                    SendOutput("stderr", text);
                    break;

                default:
                    SendEvent(new Event(type));
                    break;
                }
            };
        }
Beispiel #40
0
		public bool CanRemove(ExceptionInfo info) => !info.IsOtherExceptions;
Beispiel #41
0
 internal void AddOrUpdate(ExceptionInfoKey key, bool breakOnFirstChance, bool isOtherExceptions)
 {
     if (isOtherExceptions) {
         int index = (int)key.ExceptionType;
         if ((uint)index < (uint)otherExceptions.Length)
             WriteBreakOnFirstChance(otherExceptions[index], breakOnFirstChance);
     }
     else {
         ExceptionInfo info;
         if (exceptions.TryGetValue(key, out info))
             WriteBreakOnFirstChance(info, breakOnFirstChance);
         else {
             exceptions[key] = info = new ExceptionInfo(key, breakOnFirstChance);
             if (Changed != null)
                 Changed(this, new ExceptionManagerEventArgs(ExceptionManagerEventType.Added, info));
         }
     }
 }
Beispiel #42
0
 void WriteBreakOnFirstChance(ExceptionInfo info, bool breakOnFirstChance)
 {
     if (info.BreakOnFirstChance == breakOnFirstChance)
         return;
     info.BreakOnFirstChance = breakOnFirstChance;
     BreakOnFirstChanceChanged(info);
 }
 private void HandleRequestDispatcherException(ExceptionInfo ex)
 {
     IsLoading = false;
     _userDialogService.ShowDialog(ex.Message, "Error Loading Dens Asi Interview", UserDialogServiceOptions.Ok);
 }
Beispiel #44
0
 private void DoHandle(ProgressRunnerException ex, ExceptionInfo info)
 {
     // we're only interested in the inner exception - we know where the
     // outer one comes from
     Invoke(ex.InnerException, info);
 }
Beispiel #45
0
		void Add(ExceptionInfo info) {
			var vm = new ExceptionVM(info, exceptionContext);
			int i;
			for (i = 0; i + 1 < Collection.Count; i++) {
				int res = CompareExceptionInfos(vm.ExceptionInfo, Collection[i].ExceptionInfo);
				if (res <= 0)
					break;
			}
			Collection.Insert(i, vm);
		}
Beispiel #46
0
        /// <summary>When overridden in a derived class, handles the exception asynchronously.</summary>
        /// <returns>A task representing the asynchronous exception handling operation.</returns>
        /// <param name="httpContext">The exception handler context.</param>
        // TODO: Refactor Switch statements, minimize repeated code.
        public static Task HandleAsync(HttpContext httpContext, Exception exception, IOptions <JsonOptions> options)
        {
            // Access Exception
            ExceptionInfo responseMessage = null;

            httpContext.Response.ContentType = MediaTypeNames.Application.Json;

            switch (exception)
            {
            case ICustomException customException:
                switch (customException)
                {
                case EntityNotFoundException _:
                    responseMessage = new ExceptionInfo(exception);
                    httpContext.Response.StatusCode = StatusCodes.Status404NotFound;

                    break;

                case DataAccessException _:
                case IdentityConfigurationException _:
                    // Define message for this type of exception if suited. Default 500 status code seems a fit.
                    responseMessage = new ExceptionInfo(exception);
                    httpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;

                    break;

                case BadRequestException _:
                    responseMessage = new ExceptionInfo(exception);
                    httpContext.Response.StatusCode = StatusCodes.Status400BadRequest;

                    break;

                case ForbiddenAccessException _:
                    responseMessage = new ExceptionInfo(exception);
                    httpContext.Response.StatusCode = StatusCodes.Status403Forbidden;

                    break;

                case MimeMultipartException _:
                    responseMessage = new ExceptionInfo(exception);

                    httpContext.Response.StatusCode = StatusCodes.Status415UnsupportedMediaType;

                    break;

                case BadGatewayException _:
                    responseMessage = new ExceptionInfo(exception);
                    httpContext.Response.StatusCode = StatusCodes.Status502BadGateway;

                    break;
                }
                break;

            default:

                httpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;
                responseMessage = new ExceptionInfo(DefaultErrorMessage, exception);

                break;
            }

            return(httpContext.Response.WriteAsync(JsonSerializer.Serialize(responseMessage, options.Value.JsonSerializerOptions)));
        }
Beispiel #47
0
        public override bool Generate(CommandExecutionContext context)
        {
            var target = context.NativeDbgEngTarget;
            var lastEvent = target.GetLastEventInformation();
            if (lastEvent == null)
                return false;

            var stackTraces = new UnifiedStackTraces(target.DebuggerInterface, context);
            var threadWithException = stackTraces.Threads.SingleOrDefault(t => t.OSThreadId == lastEvent.OSThreadId);
            if (threadWithException == null)
                return false;

            Exception = new ExceptionInfo
            {
                ExceptionCode = lastEvent.ExceptionRecord?.ExceptionCode ?? 0
            };
            if (Exception.ExceptionCode== 0)
                return false;

            OSThreadId = threadWithException.OSThreadId;
            ManagedThreadId = threadWithException.ManagedThread?.ManagedThreadId ?? 0;

            // Note that we want the thread's stack from the exception context,
            // and not from wherever it is right now.
            Exception.StackFrames = stackTraces.GetStackTraceFromStoredEvent()
                                                .Where(f => f.Type != UnifiedStackFrameType.Special)
                                                .Select(f => f.DisplayString)
                                                .ToList();

            // Note that we might have an exception, but if it wasn't managed
            // then the Thread.CurrentException field will be null.
            var exception = threadWithException.ManagedThread?.CurrentException;
            if (exception == null)
                return true;

            Exception.ExceptionType = exception.Type.Name;
            Exception.ExceptionMessage = exception.Message;

            exception = exception.Inner;
            var exceptionInfo = Exception;
            while (exception != null)
            {
                exceptionInfo.InnerException = new ExceptionInfo();
                exceptionInfo = exceptionInfo.InnerException;

                exceptionInfo.ExceptionType = exception.Type.Name;
                exceptionInfo.ExceptionMessage = exception.Message;
                exceptionInfo.StackFrames = exception.StackTrace.Select(f => f.DisplayString).ToList();

                exception = exception.Inner;
            }

            if (Exception != null)
                Recommendations.Add(new UnhandledExceptionOccurred { Exception = Exception });

            return true;
        }
Beispiel #48
0
 private void HandleInitializationException(ExceptionInfo exceptionInfo)
 {
     IsLoading = false;
     _userDialogService.ShowDialog(exceptionInfo.Message, "Payor editor initialization failed", UserDialogServiceOptions.Ok);
 }
Beispiel #49
0
		public void BreakOnFirstChanceChanged(ExceptionInfo info) {
			ExceptionInfo info2;
			bool b = exceptions.TryGetValue(info.Key, out info2) && ReferenceEquals(info, info2);
			Debug.Assert(b);
			if (!b)
				return;
			Changed?.Invoke(this, new ExceptionServiceEventArgs(ExceptionServiceEventType.ExceptionInfoPropertyChanged, info));
		}
Beispiel #50
0
        // TODO: expection handling
        private void bt_Save_Click(object sender, EventArgs e)
        {
            TreeNodeCollection              nodes = tagTreeView.Nodes;
            UserTextInformationFrame        tagframe;
            List <UserTextInformationFrame> save_frame_list = new List <UserTextInformationFrame>();
            List <string> tag_desc_list = new List <string>();

            try
            {
                // RemoveFrame() is invalid, workaround: save other "TXXX" first, then remove all "TXXX", add selected tags and recovery other "TXXX" at last
                foreach (TreeNode n in nodes)
                {
                    tag_desc_list.Add(n.Text);
                }

                foreach (UserTextInformationFrame fm in audioTag.GetFrames("TXXX"))
                {
                    if (!tag_desc_list.Contains(fm.Description))
                    {
                        save_frame_list.Add(fm);
                    }
                }

                // Remove all "TXXX"
                audioTag.RemoveFrames("TXXX");

                // Pre-handle comment tag for link to comment
                if (cb_LinkToComment.Checked == true)
                {
                    if (cb_AppendMode.Checked == true)
                    {
                        if (string.IsNullOrWhiteSpace(audioTag.Comment))
                        {
                            audioTag.Comment = ""; // clear comment
                        }
                        else
                        {
                            audioTag.Comment += "||"; // add a link character "||"
                        }
                    }
                    else
                    {
                        audioTag.Comment = ""; // clear comment
                    }
                }

                // Add selected tags
                foreach (TreeNode n in nodes)
                {
                    string valmixed = "";

                    foreach (TreeNode tn in n.Nodes)
                    {
                        if (tn.Checked == true)
                        {
                            valmixed += tn.Text + ";";

                            // Handle link to comment tag
                            if (cb_LinkToComment.Checked == true)
                            {
                                audioTag.Comment += tn.Text + ";";
                            }
                        }
                    }

                    tagframe      = new UserTextInformationFrame(n.Text);
                    tagframe.Text = new string[] { valmixed };
                    audioTag.AddFrame(tagframe);
                }

                // Recovery other "TXXX"
                if (save_frame_list.Count != 0)
                {
                    foreach (UserTextInformationFrame fm in save_frame_list)
                    {
                        audioTag.AddFrame(fm);
                    }
                }

                // Save file
                audioFile.Save();

                showInStatusBar("Save OK");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ExceptionInfo.ShowExceptionInfo(ex), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Beispiel #51
0
		public void Add(ExceptionInfoKey key) {
			ExceptionInfo info;
			if (exceptions.TryGetValue(key, out info))
				return;

			info = new ExceptionInfo(key, true);
			exceptions.Add(key, info);
			Changed?.Invoke(this, new ExceptionServiceEventArgs(ExceptionServiceEventType.Added, info));
		}
Beispiel #52
0
        // TODO: ape, mp4 support
        private void createTreeViewFromXmlAndMedia(string xmlpath, string path)
        {
            try
            {
                audioFile = TagLib.File.Create(path);

                // Display file name in status bar
                //statusStrip.Items[0].Text = Path.GetFileName(path);
                showInStatusBar(Path.GetFileName(path));

                audioTag = (TagLib.Id3v2.Tag)audioFile.GetTag(TagTypes.Id3v2);
                if (audioTag == null)
                {
                    MessageBox.Show("Only support ID3v2 tag", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                XmlDocument xmltag = new XmlDocument();

                xmltag.Load(xmlpath);

                XmlNode mp3tag = xmltag.SelectSingleNode("/mp3tag");

                XmlNodeList taglist = mp3tag.ChildNodes;

                // Clear all nodes first before add new nodes
                tagTreeView.Nodes.Clear();

                foreach (XmlNode tag in taglist)
                {
                    TreeNode nodetag = tagTreeView.Nodes.Add(tag.Attributes["field"].Value);
                    //Debug.WriteLine("\nField: " + tag.Attributes["field"].Value + "\n");

                    XmlNodeList valuelist = tag.ChildNodes;

                    foreach (XmlNode value in valuelist)
                    {
                        TreeNode nodevalue = new TreeNode(value.InnerText);

                        foreach (UserTextInformationFrame fm in audioTag.GetFrames("TXXX"))
                        {
                            if (fm.Description == tag.Attributes["field"].Value)
                            {
                                //Debug.WriteLine("\r\nString list length = " + fm.Text.Length + "\r\n");
                                if (fm.Text.Length == 0)
                                {
                                    continue;
                                }

                                if (fm.Text[0].Contains(nodevalue.Text))// TODO  use ; to separate
                                {
                                    nodevalue.Checked = true;
                                }
                            }
                        }

                        nodetag.Nodes.Add(nodevalue);

                        // Update node check status
                        tagTreeView.TriStateUpdateCheckStatus(nodevalue);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ExceptionInfo.ShowExceptionInfo(ex), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Beispiel #53
0
 internal void BreakOnFirstChanceChanged(ExceptionInfo info)
 {
     ExceptionInfo info2;
     bool b = exceptions.TryGetValue(info.Key, out info2) && ReferenceEquals(info, info2);
     Debug.Assert(b);
     if (!b)
         return;
     if (Changed != null)
         Changed(this, new ExceptionManagerEventArgs(ExceptionManagerEventType.ExceptionInfoPropertyChanged, info));
 }
Beispiel #54
0
 public Node Field(int i)
 {
     return(Create(ExceptionInfo.Return <int, IntPtr>(Handle, i, GroupNode_Field)));
 }
Beispiel #55
0
        public void Add(ExceptionInfoKey key)
        {
            ExceptionInfo info;
            if (exceptions.TryGetValue(key, out info))
                return;

            info = new ExceptionInfo(key, true);
            exceptions.Add(key, info);
            if (Changed != null)
                Changed(this, new ExceptionManagerEventArgs(ExceptionManagerEventType.Added, info));
        }
Beispiel #56
0
 public int FieldIndex(string name)
 {
     return(ExceptionInfo.Return <string, int>(Handle, name, GroupNode_Field_Index_By_Name));
 }
        private static ExceptionInfo GetExceptionInfo(Exception exception)
        {
            var exceptionInfo = new ExceptionInfo
            {
                StackTrace = exception.StackTrace,
                ExceptionType = exception.GetType().FullName,
                Message = exception.Message,
                Source = exception.Source,
                Data = GetExceptionData(exception),
            };

            MethodBase method = exception.TargetSite;
            if (method != null)
            {
                exceptionInfo.MethodName = string.Format("{0}.{1}", method.DeclaringType == null ? "Unknown" : method.DeclaringType.FullName, method.Name);
            }

            if (exception.InnerException != null)
            {
                exceptionInfo.InnerExceptionInfo = GetExceptionInfo(exception.InnerException);
            }

            return exceptionInfo;
        }
Beispiel #58
0
        public void Start()
        {
            var Success = false;

            try
            {
                IsRunningValue.Update
                (
                    b =>
                {
                    if (b)
                    {
                        throw new InvalidOperationException();
                    }

                    if (BindingsValue.Length == 0)
                    {
                        throw new Exception("NoValidBinding");
                    }

                    ListeningTaskTokenSource = new CancellationTokenSource();

                    var ListeningTaskToken = ListeningTaskTokenSource.Token;

                    foreach (var Binding in BindingsValue)
                    {
                        Listener.Prefixes.Add(Binding);
                    }
                    if (SessionIdleTimeoutValue.HasValue)
                    {
                        SetTimer(Listener, SessionIdleTimeoutValue.Value);
                    }
                    Action <HttpListenerContext> PurifyContext = ListenerContext =>
                    {
                        try
                        {
                            ListenerContext.Response.Close();
                        }
                        catch
                        {
                        }
                    };

                    Action <HttpListenerContext> Accept = a =>
                    {
                        IPEndPoint e = null;
                        try
                        {
                            e = (IPEndPoint)a.Request.RemoteEndPoint;
                            var XForwardedFor = a.Request.Headers["X-Forwarded-For"];
                            var Address       = e.Address;
                            if (XForwardedFor != null)
                            {
                                try
                                {
                                    Address = IPAddress.Parse(XForwardedFor.Split(',')[0].Trim(' '));
                                }
                                catch
                                {
                                }
                            }
                            var XForwardedPort = a.Request.Headers["X-Forwarded-Port"];
                            var Port           = e.Port;
                            if (XForwardedPort != null)
                            {
                                try
                                {
                                    Port = int.Parse(XForwardedPort.Split(',')[0].Trim(' '));
                                }
                                catch
                                {
                                }
                            }
                            e = new IPEndPoint(Address, Port);

                            if (ServerContext.EnableLogSystem)
                            {
                                ServerContext.RaiseSessionLog(new SessionLogEntry {
                                    Token = "", RemoteEndPoint = e, Time = DateTime.UtcNow, Type = "Sys", Name = "RequestIn", Message = ""
                                });
                            }

                            if (a.Request.ContentLength64 < 0)
                            {
                                a.Response.StatusCode = 411;
                                NotifyListenerContextQuit(a);
                                return;
                            }

                            if (a.Request.ContentLength64 > ReadBufferSize)
                            {
                                a.Response.StatusCode = 413;
                                NotifyListenerContextQuit(a);
                                return;
                            }

                            var oRelativePath = MatchBindingNameAndGetRelativePath(a.Request.Url);
                            if (oRelativePath.OnNone)
                            {
                                a.Response.StatusCode = 404;
                                NotifyListenerContextQuit(a);
                                return;
                            }
                            var RelativePath = oRelativePath.Value;

                            var Headers = a.Request.Headers.AllKeys.ToDictionary(k => k, k => a.Request.Headers[k]);
                            if (Headers.ContainsKey("Accept-Charset"))
                            {
                                var AcceptCharsetParts = Headers["Accept-Charset"].Split(';');
                                if (AcceptCharsetParts.Length == 0)
                                {
                                    a.Response.StatusCode = 400;
                                    NotifyListenerContextQuit(a);
                                    return;
                                }
                                var EncodingNames = AcceptCharsetParts[0].Split(',').Select(n => n.Trim(' ')).ToArray();
                                if (!(EncodingNames.Contains("utf-8", StringComparer.OrdinalIgnoreCase) || EncodingNames.Contains("*", StringComparer.OrdinalIgnoreCase)))
                                {
                                    a.Response.StatusCode = 400;
                                    NotifyListenerContextQuit(a);
                                    return;
                                }
                            }

                            if (RequestHandler != null)
                            {
                                RequestHandler(RelativePath, a, e, () => NotifyListenerContextQuit(a), ex =>
                                {
                                    if (ServerContext.EnableLogSystem)
                                    {
                                        ServerContext.RaiseSessionLog(new SessionLogEntry {
                                            Token = "", RemoteEndPoint = e, Time = DateTime.UtcNow, Type = "Sys", Name = "Exception", Message = ExceptionInfo.GetExceptionInfo(ex)
                                        });
                                    }
                                    NotifyListenerContextQuit(a);
                                });
                            }
                            else
                            {
                                NotifyListenerContextQuit(a);
                            }
                        }
                        catch (Exception ex)
                        {
                            if (ServerContext.EnableLogSystem)
                            {
                                ServerContext.RaiseSessionLog(new SessionLogEntry {
                                    Token = "", RemoteEndPoint = e ?? new IPEndPoint(IPAddress.Any, 0), Time = DateTime.UtcNow, Type = "Sys", Name = "Exception", Message = ExceptionInfo.GetExceptionInfo(ex)
                                });
                            }
                            try
                            {
                                a.Response.StatusCode = 500;
                            }
                            catch
                            {
                            }
                            NotifyListenerContextQuit(a);
                        }
                    };
                    AcceptConsumer = new AsyncConsumer <HttpListenerContext>(QueueUserWorkItem, a => { Accept(a); return(true); }, int.MaxValue);

                    ContextPurifyConsumer = new AsyncConsumer <HttpListenerContext>(QueueUserWorkItem, l => { PurifyContext(l); return(true); }, int.MaxValue);

                    try
                    {
                        Listener.Start();
                    }
                    catch (HttpListenerException ex)
                    {
                        String Message;
                        if (ex.ErrorCode == 5)
                        {
                            var l = new List <String>();
                            l.Add("Under Windows, try run the following as administrator:");
                            var UserDomainName = Environment.UserDomainName;
                            var UserName       = Environment.UserName;
                            foreach (var p in BindingsValue)
                            {
                                l.Add(@"netsh http add urlacl url={0} user={1}\{2}".Formats(p, UserDomainName, UserName));
                            }
                            l.Add("and delete it when you don't need it:");
                            foreach (var p in BindingsValue)
                            {
                                l.Add(@"netsh http delete urlacl url={0}".Formats(p));
                            }
                            Message = String.Join("\r\n", l.ToArray());
                        }
                        else
                        {
                            Message = ExceptionInfo.GetExceptionInfo(ex);
                        }
                        throw new AggregateException(Message, ex);
                    }
                    Action Listen = () =>
                    {
                        if (ListeningTaskToken.IsCancellationRequested)
                        {
                            return;
                        }
                        var l  = Listener;
                        var lc = ListenConsumer;
                        l.BeginGetContext(ar =>
                        {
                            if (!l.IsListening)
                            {
                                return;
                            }
                            try
                            {
                                var a = l.EndGetContext(ar);
                                AcceptConsumer.Push(a);
                            }
                            catch (HttpListenerException)
                            {
                            }
                            lc.Push(0);
                        }, null);
                    };
                    ListenConsumer = new AsyncConsumer <int>(QueueUserWorkItem, i => { Listen(); return(true); }, 1);

                    Listen();

                    Success = true;

                    return(true);
                }
                );
            }
            finally
            {
                if (!Success)
                {
                    Stop();
                }
            }
        }
Beispiel #59
0
 /// <summary>
 /// Set current exception info
 /// </summary>
 public void SetException(Exception err)
 {
     Exception = new ExceptionInfo(err);
 }
Beispiel #60
0
 private void HandleException(ExceptionInfo exceptionInfo)
 {
     IsLoading = false;
     _userDialogService.ShowDialog(exceptionInfo.Message, "Get Clinical Case Summary failed.", UserDialogServiceOptions.Ok);
 }