private void UC_PlcDataState_Load(object sender, EventArgs e)
        {
            //다른 쓰레드에서 윈폼 컨트롤 사용가능 (비동기 작업에서 사용)
            //Control.CheckForIllegalCrossThreadCalls = false;

            if (!Directory.Exists(MyApp.RootRef))
            {
                Directory.CreateDirectory(MyApp.RootRef);
            }
            if (File.Exists(_PLCRefPath))
            {
                try
                {
                    int    iArrcnt = 0;
                    string Connstr = MyApp.RootMDB(_PLCRefPath);
                    using (OleDbConnection connDB = new OleDbConnection(Connstr))
                    {
                        connDB.Open();
                        foreach (string tbName in Share.GetMDBTable(connDB))
                        {
                            string sql = $"Select *from {tbName} " + "Order by PlcName ASC,BlockNum ASC,IndexNo ASC";

                            Array.Resize(ref tabPage, iArrcnt + 1);
                            Array.Resize(ref Uc_dgv, iArrcnt + 1);

                            tabPage[iArrcnt] = new TabPage();
                            AddTabpage(tbName, iArrcnt);

                            Uc_dgv[iArrcnt] = new UC_DGV();
                            AddDGV(iArrcnt);

                            using (DataSet dsData = new DataSet())
                            {
                                OleDbDataAdapter oledbAdapter = new OleDbDataAdapter(sql, connDB);
                                oledbAdapter.Fill(dsData);

                                //.DoubleBuffered(True)
                                Stopwatch Tchk = new Stopwatch();
                                Tchk.Start();

                                Uc_dgv[iArrcnt].DGVPlc.DataSource = dsData.Tables[0];
                                DataGridViewTextBoxColumn addrCol = new DataGridViewTextBoxColumn();

                                addrCol.Name       = "PLCVal";
                                addrCol.HeaderText = "PLCVal";

                                Uc_dgv[iArrcnt].DGVPlc.Columns.Add(addrCol);

                                Tchk.Stop();
                                Debug.Print(Tchk.Elapsed.ToString());

                                //DetailsView.Dispose();
                                oledbAdapter.Dispose();
                                oledbAdapter = null;

                                for (int i = 0; i < Uc_dgv[iArrcnt].DGVPlc.Columns.Count; i++)
                                {
                                    Uc_dgv[iArrcnt].DGVPlc.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
                                }
                            }
                            Uc_dgv[iArrcnt].DGVPlc.DoubleBuffered();
                            iArrcnt++;
                        }
                        connDB.Close();
                        connDB.Dispose();
                    }
                }
                catch (Exception ex)
                {
                    StackTrace trace      = new StackTrace(ex, true);
                    StackFrame stackFrame = trace.GetFrame(trace.FrameCount - 1);
                    int        lineNumber = stackFrame.GetFileLineNumber();

                    I_Sub.ErrorLog(($"({lineNumber}) : {ex.ToString()}"));
                }
            }
        }
Пример #2
0
 // Constructor
 public CallerInfo(StackTrace trace)
 {
     this = new CallerInfo();
     MethodName = trace.GetFrame(1).GetMethod().Name;
     ClassName = trace.GetFrame(1).GetMethod().ReflectedType.Name;
     FileName = trace.GetFrame(1).GetFileName();
     LineNumber = trace.GetFrame(1).GetFileLineNumber();
 }
    /// <summary>
    ///     Writes event to log file specified above.
    /// </summary>
    /// <param name="output"></param>
    public static void write(string output)
    {
        if (logToFile) {
            StackTrace st = new StackTrace (true);
            // TODO: Colan commented it out because it isn't used
            int lineNumber = st.GetFrame (1).GetFileLineNumber ();

            // Output format:  "(Time delta from program start in format m:ss.sss) :: (Log message)"
            writer.WriteLine (string.Format ("{0:00}:{1:00.000}", Time.realtimeSinceStartup / 60, Time.realtimeSinceStartup % 60f) + " :: \"" + st.GetFrame (1).GetMethod ().ReflectedType.Name + "\" (Line: " + lineNumber + ") :: " + output);

            // Flushes buffer to force a write
            writer.Flush ();
        }
    }
	private static bool GetProtectionDomains(List<java.security.ProtectionDomain> array, [email protected] callerID, StackTrace stack)
	{
		// first we have to skip all AccessController related frames, because we can be called from a doPrivileged implementation (not the privileged action)
		// in which case we should ignore the doPrivileged frame
		int skip = 0;
		for (; skip < stack.FrameCount; skip++)
		{
			Type type  = stack.GetFrame(skip).GetMethod().DeclaringType;
			if (type != typeof(Java_java_security_AccessController) && type != typeof(java.security.AccessController))
			{
				break;
			}
		}
		java.security.ProtectionDomain previous_protection_domain = null;
		for (int i = skip; i < stack.FrameCount; i++)
		{
			bool is_privileged = false;
			java.security.ProtectionDomain protection_domain;
			MethodBase method = stack.GetFrame(i).GetMethod();
			if (method.DeclaringType == typeof(java.security.AccessController)
				&& method.Name == "doPrivileged")
			{
				is_privileged = true;
				java.lang.Class caller = callerID.getCallerClass();
				protection_domain = caller == null ? null : Java_java_lang_Class.getProtectionDomain0(caller);
			}
			else if (Java_sun_reflect_Reflection.IsHideFromStackWalk(method))
			{
				continue;
			}
			else
			{
				protection_domain = GetProtectionDomainFromType(method.DeclaringType);
			}

			if (previous_protection_domain != protection_domain && protection_domain != null)
			{
				previous_protection_domain = protection_domain;
				array.Add(protection_domain);
			}

			if (is_privileged)
			{
				return true;
			}
		}
		return false;
	}
Пример #5
0
    public void SetAlarm(bool status)
    {
        StackTrace st = new StackTrace();
        print(st.GetFrame(1).GetMethod().Name);
        //print("ALARM SET");
        if (status)
        {
            foreach (Light l in lights)
            {
                l.intensity = 8;
                l.color = Color.red;
                if(l.name != "EnemyCamera")
                    l.GetComponent<AudioSource>().Play();

            }
        }
        else
        {
            foreach (Light l in lights)
            {
                if (l.name != "EnemyCamera")
                {
                    l.intensity = 1;
                    l.color = Color.white;
                    l.GetComponent<AudioSource>().Pause();
                }
                else
                {
                    l.color = Color.green;
                    l.intensity = 10;
                }
            }
        }
    }
Пример #6
0
 private static string GetCallingMethod(StackTrace stack)
 {
     StackFrame frame = stack.GetFrame(0);
     string className = frame.GetMethod().DeclaringType.ToString();
     string functionName = frame.GetMethod().Name;
     return string.Format("{0}.{1}", className, functionName);
 }
Пример #7
0
        protected string GetCurrentMethodName()
        {
            StackTrace stackTrace = new StackTrace();
            StackFrame stackFrame = stackTrace?.GetFrame(1);

            return(stackFrame?.GetMethod().Name ?? "<unable to resolve method name>");
        }
Пример #8
0
		/// <summary>
		/// Returns the <see cref="MethodBase"/> object identiying the caller of the current method.
		/// </summary>
		/// <returns>The MethodBase object of the caller of the current method.</returns>
		public static MethodBase CallingMethod()
		{
			var stack = new StackTrace();
			var frame = stack == null ? null : stack.GetFrame( 2 );
			var method = frame == null ? null : frame.GetMethod();

			return method;
		}
Пример #9
0
    public static void PrintMethodName()
    {
        StackTrace st = new StackTrace ();
        StackFrame sf = st.GetFrame (1);

        MethodBase currentMethodName = sf.GetMethod ();
        UnityEngine.Debug.Log ("I'm in "+currentMethodName);
    }
Пример #10
0
    public static void log(string msg, params object[] objs)
    {
        StackTrace st = new StackTrace();
        StackFrame sf = st.GetFrame(1);

        Console.Write("[{0}({1})] ", sf.GetFileName(), sf.GetFileLineNumber());
        Console.WriteLine(msg, objs);
    }
Пример #11
0
		/// <summary>
		/// Returns a string in the form "Type.Method" identifying the caller of the current method.
		/// </summary>
		/// <returns>A string identifying the caller of the current method.</returns>
		public static string CalledFrom()
		{
			var stack = new StackTrace();
			var frame = stack == null ? null : stack.GetFrame( 2 );
			var method = frame == null ? null : frame.GetMethod();

			if( method == null ) return "n/a";
			return string.Format( "{0}.{1}", method.DeclaringType.Name, method.Name );
		}
Пример #12
0
    public static void Assert(bool condition, string exprTag)
    {
        if (!condition)
		{
			StackTrace st = new StackTrace(new StackFrame(true));
			StackFrame sf = st.GetFrame(1);
			throw new Exception("Assertion( " + exprTag + " ): File '" + sf.GetFileName() + "', Line " + sf.GetFileLineNumber() + ".");
		}
    }
Пример #13
0
    static void _Log(string message, LOG_TYPE log_type)
    {
        var st = new StackTrace(true);
        var sf = st.GetFrame(2);

        var fpath = sf.GetFileName();
        var fline = sf.GetFileLineNumber();

        XCon.Inst.Log(new LogData{message= message, fpath= fpath, fline= fline, log_type= log_type});
    }
Пример #14
0
	public static void Assert(bool condition)
	{
		if (!condition)
		{
			StackTrace st = new StackTrace(new StackFrame(true));
			StackFrame sf = st.GetFrame(1);
			UnityEngine.Debug.LogError("Assertion( " + sf.ToString() + " ): File '" + sf.GetFileName() + "', Line " + sf.GetFileLineNumber() + ".");
			throw new Exception();
		}
	}
Пример #15
0
    private void InserirErro(Exception e)
    {
        string sDiretorio = ConfigurationSettings.AppSettings["LogDirectory"].ToString();

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

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

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

        StreamWriter oSw = File.AppendText(@sDiretorio + "\\" + DateTime.Now.ToString("yyyyMMdd") + ".txt");
        oSw.WriteLine(DateTime.Now.ToString("dd-MM-yyyy HH:mm.ss") + " > Class{ " + Classe + " } : Listar{ " + Metodo + " } - Message{ " + e.Message + " }");
        oSw.Flush();
        oSw.Close();
        oSw = null;
    }
		public static void ResolveCallback(IAsyncResult ar)
		{
		    Console.WriteLine("ResolveCallback()");
		    StackTrace st = new StackTrace();
		    frame_count = st.FrameCount;
	            for(int i = 0; i < st.FrameCount; i++) {
	                StackFrame sf = st.GetFrame(i);
        	        Console.WriteLine("method: {0}", sf.GetMethod());
	            }
        	    Console.WriteLine("ResolveCallback() complete");
		}
Пример #17
0
    public static GameObject InstantiatePrefab(GameObject prefab, Vector3 location, Quaternion rotation)
    {
        StackTrace st = new StackTrace(true);

        GameObject obj = Instantiate(prefab,location,rotation) as GameObject;

        objects.Add(obj, st.GetFrame(1));

        obj.AddComponent<FancyGizmos>();

        return obj;
    }
Пример #18
0
 public void LogCallMethod(bool isStart)
 {
     var stackTrace = new StackTrace();
     StackFrame stackFrame = stackTrace.GetFrame(1);
     MethodBase methodBase = stackFrame.GetMethod();
     if (isStart)
     {
         SiAuto.Main.EnterMethod(this, methodBase.Name);
     }
     else
     {
         SiAuto.Main.LeaveMethod(this, methodBase.Name);
     }
 }
Пример #19
0
        public static RegistrationToken Add(TDef def)
        {
            //Use stacktrace to find calling method for debugging.
            //TODO: Add some configuration to determine if the adding method discovery runs
            var trace = new StackTrace(false);
            var frame = trace?.GetFrame(1);

            if ((frame?.HasMethod() ?? false) && frame.GetMethod() is MethodBase method)
            {
                return(_Add(def, false, method));
            }

            return(_Add(def, false));
        }
Пример #20
0
        public static ErrorCode DebugGetError(StackTrace trace = null)
        {
            var error = GL.GetError();
            var frame = trace?.GetFrame(0);

            if (error != ErrorCode.NoError)
            {
                Debug.Print("[" + frame.GetFileName()
                            + "(" + frame.GetFileLineNumber()
                            + ")] OpenGL error: " + error.ToString()
                            + " occurred during shader debugging.");
            }
            return(error);
        }
Пример #21
0
    public static void CallStack()
    {
        //	This method reports the callstack (not including the current class).

        StackTrace st = new StackTrace(true);
        Int32 StackCount = st.FrameCount;

        for (Int32 StackNo = 2; StackNo < StackCount; StackNo++)
        {
            StackFrame sf = st.GetFrame(StackNo);
            string Caller = string.Format("{0} (line {1})",
                sf.GetMethod().DeclaringType.FullName,
                sf.GetFileLineNumber());

            Debug.WriteLine(string.Format("{0}: {1}", ClassTimeAndDate.HhMmSs(DateTime.Now), Caller));
        }
    }
Пример #22
0
    private static void TriggerAssert(string message)
    {
        var myTrace = new StackTrace(true);
        var myFrame = myTrace.GetFrame(2);

        var assertMsg = "Assert Hit! \n\n" + message + "\n\n" + "Filename: " + myFrame.GetFileName() + "\nMethod: " + myFrame.GetMethod() +
            "\nLine: " + myFrame.GetFileLineNumber();

        #if UNITY_EDITOR
        switch (_handleMethod)
        {
            case AssertHandleMethod.LogAndContinue:
                Debug.LogError(assertMsg);
                break;

            case AssertHandleMethod.MessageBox:

                if (!_shouldStop)
                {
                    var choice = EditorUtility.DisplayDialogComplex("Assert Hit!", assertMsg,
                                                                    "Go To", "Ignore", "Stop");

                    Debug.LogError(assertMsg);
                    if (choice == 0 || choice == 2)
                    {
                        EditorApplication.isPlaying = false;
                        _shouldStop = true;
                    }

                    if (choice == 0)
                    {
                        InternalEditorUtility.OpenFileAtLineExternal(myFrame.GetFileName(), myFrame.GetFileLineNumber());
                    }
                }

                break;

            case AssertHandleMethod.Exception:
                throw new AssertException(assertMsg);

            default:
                Util.Assert(false);
                break;
        }
        #endif
    }
Пример #23
0
	public void Log(string log, CsDLevel level, CsDComponent component)
	{
		
		if((int)_debugLevel[component] >= (int)level)
		{
			StackTrace stackTrace = new StackTrace();
			var method = stackTrace.GetFrame(1).GetMethod();
			var parentClass = method.ReflectedType;
			var parentNameSpace = parentClass.Namespace;

			string formattedLog = Mathf.Round(Time.realtimeSinceStartup * 1000)/1000 + " " + component.ToString() + " " + level.ToString() + " " 
									+ parentNameSpace + "/" + parentClass.Name + "/" + method.Name + ": " + log;

			//if log target is console log, just use debug.log
			//if is file, add the log line to the buffered log, and if it's larger than buffer size, write to file and
			//clear the buffer

			if(_logTarget == CsDLogTarget.Console || _logTarget == CsDLogTarget.Both)
			{
				if(level == CsDLevel.Error)
				{
					UnityEngine.Debug.LogAssertion(formattedLog);
				}
				else
				{
					UnityEngine.Debug.Log(formattedLog);
				}
			}

			if(_logTarget == CsDLogTarget.File || _logTarget == CsDLogTarget.Both)
			{
				_bufferedLog = _bufferedLog + formattedLog + "\r\n";
				
				if(_bufferedLog.Length > _bufferSize)
				{
					LogBufferToFile();
				}
			}

		}
	}
Пример #24
0
    private static void LogMsg(string Msg, Int32 Stacks2Jump)
    {
        if (Stacks2Jump > 0)
        {
            //	If we need to show who called us it is necessary to jump
            //	over a couple of stack frames to get the information
            //	we require.

            StackTrace st = new StackTrace(true);
            StackFrame sf = st.GetFrame(Stacks2Jump);
            MethodBase method = sf.GetMethod();
            string Caller = string.Format("{0} {1} (line {2})",
                sf.GetFileName().Substring(sf.GetFileName().LastIndexOf("\\") + 1),
                sf.GetMethod().Name,
                sf.GetFileLineNumber());

            Debug.WriteLine(string.Format("{0}: {1}", ClassTimeAndDate.HhMmSs(DateTime.Now), Caller));
        }

        Debug.WriteLine(string.Format("{0}: {1}", ClassTimeAndDate.HhMmSs(DateTime.Now), Msg));
    }
Пример #25
0
	private void LogMessage(string message, LogLevel logLevel)
	{
		StackTrace stackTrace = new StackTrace(new StackFrame(2, true));
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.Append("[");
		stringBuilder.Append(this.m_sourceName);
		stringBuilder.Append("] ");
		stringBuilder.Append(message);
		if (stackTrace != null)
		{
			StackFrame frame = stackTrace.GetFrame(0);
			if (frame != null)
			{
				stringBuilder.Append(" (");
				stringBuilder.Append(frame.GetFileName());
				stringBuilder.Append(":");
				stringBuilder.Append(frame.GetFileLineNumber());
				stringBuilder.Append(")");
			}
		}
		Log.Asset.LogLevelPrint(stringBuilder.ToString(), logLevel);
	}
Пример #26
0
	public void LogDebugStackTrace(int maxFrames, int skipFrames = 0)
	{
		for (int i = 1 + skipFrames; i < maxFrames; i++)
		{
			StackTrace stackTrace = new StackTrace(new StackFrame(i, true));
			if (stackTrace == null)
			{
				break;
			}
			StackFrame frame = stackTrace.GetFrame(0);
			if (frame == null)
			{
				break;
			}
			if (frame.GetMethod() == null || frame.GetMethod().ToString().StartsWith("<"))
			{
				break;
			}
			this.LogDebug("  > {0}", new object[]
			{
				frame.ToString()
			});
		}
	}
Пример #27
0
        public static Dictionary <String, String> getCityByCompany(String companyId, String divisionId)
        {
            Logger.LogDebug(MethodBase.GetCurrentMethod().DeclaringType.ToString(), MethodBase.GetCurrentMethod().Name, "Entry Point", Logger.logLevel.Info);
            Logger.LogDebug(MethodBase.GetCurrentMethod().DeclaringType.ToString(), MethodBase.GetCurrentMethod().Name, companyId + divisionId, Logger.logLevel.Debug);

            if (companyId.Equals("null") && divisionId.Equals("null"))
            {
                return(getAllCities());
            }

            Dictionary <String, String> dictEmp = new Dictionary <string, string>();

            SqlConnection conn = null;

            SqlDataReader reader = null;

            try
            {
                // create and open a connection object
                conn = ConnectionManager.getConnection();
                conn.Open();


                String query;
                if (!companyId.Equals("null") && !divisionId.Equals("null"))
                {
                    //query = "select TOP 500  P.id from person P,department D where P.department = D.id and D.user1 like @company and D.user2 like @division group by P.id";
                    query = "select distinct TOP 1000  P.address3 FROM person P, department D,rs_company Comp, rs_division Div";
                    query = query + " WHERE P.department = D.id AND Comp.companyId = @company AND Div.divisionId = @division AND D.user1 LIKE Comp.companyName AND D.user2 LIKE Div.divisionName";
                }
                else if (companyId.Equals("null"))
                {
                    // query = "select TOP 500  P.id from person P,department D where P.department = D.id and  D.user2 like @division group by P.id";
                    query = "select distinct TOP 1000 P.address3 FROM person P, department D, rs_division Div";
                    query = query + " WHERE P.department = D.id AND Div.divisionId = @division AND D.user2 LIKE Div.divisionName";
                }
                else
                {
                    // query = "select TOP 500  P.id from person P,department D where P.department = D.id and D.user1 like @company group by P.id";

                    query = "select distinct TOP 1000 P.address3 FROM person P, department D,rs_company Comp";
                    query = query + " WHERE P.department = D.id AND Comp.companyId = @company AND D.user1 LIKE Comp.companyName";
                }

                SqlCommand command = new SqlCommand(query, conn);
                command.Parameters.AddWithValue("@company", companyId.Trim());
                command.Parameters.AddWithValue("@division", divisionId.Trim());


                using (reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        String strZipCode = reader.GetSqlValue(0).ToString().Trim();
                        if (!(strZipCode.Equals("null") || strZipCode.Equals("NULL") || strZipCode.Equals("Null") || strZipCode.Equals("")))
                        {
                            if (!dictEmp.ContainsKey(reader.GetSqlValue(0).ToString().Trim()))
                            {
                                dictEmp.Add(reader.GetSqlValue(0).ToString().Trim(), strZipCode);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                var stackTrace = new StackTrace(ex, true);
                var line       = stackTrace.GetFrame(0).GetFileLineNumber();
                Logger.LogExceptions(MethodBase.GetCurrentMethod().DeclaringType.ToString(), MethodBase.GetCurrentMethod().Name, ex.Message, line.ToString(), Logger.logLevel.Exception);
            }
            finally
            {
                if (conn != null)
                {
                    conn.Close();
                }
                if (reader != null)
                {
                    reader.Close();
                }
            }
            dictEmp = Utilities.sortData(dictEmp);
            Logger.LogDebug(MethodBase.GetCurrentMethod().DeclaringType.ToString(), MethodBase.GetCurrentMethod().Name, "Exit Point", Logger.logLevel.Debug);
            return(dictEmp);
        }
Пример #28
0
        public bool Parse()
        {
            HttpRequest Request = HttpContext.Current.Request;

            this.rawUrl = Request.RawUrl;

            this.fullUrl =
                string.Format("http://{0}{1}", Request.ServerVariables["SERVER_NAME"], Request.RawUrl);
            this.IPAddress = Request.UserHostAddress;

            if (Request.UrlReferrer != null)
            {
                this.referer = Request.UrlReferrer.ToString();
            }

            this.browser = Request.UserAgent;

            if (Request.TotalBytes > 0 && Request.TotalBytes < 6144)
            {
                this.postBuffer =
                    Encoding.GetEncoding(1252).GetString(Request.BinaryRead(Request.TotalBytes))
                ;
                this.contentSize = Request.TotalBytes;
            }
            else if (Request.TotalBytes > 20000)             // strip the result
            {
                this.postBuffer =
                    Encoding.GetEncoding(1252).GetString(Request.BinaryRead(20000)) + "...";
                this.contentSize = Request.TotalBytes;
            }


            if (this.LastError == null)
            {
                return(false);
            }
            this.isParsed = true;


            if (LastError is FileNotFoundException)
            {
                this.errorMessage = "File not found: " + LastError.Message;
            }
            else
            {
                this.errorMessage = LastError.Message;
            }


            if (this.compactFormat)
            {
                return(true);
            }

            this.StackTrace = LastError.StackTrace;
            if (this.retrieveSourceLines)
            {
                StringBuilder sb = new StringBuilder(1024);

                StackTrace st = new StackTrace(LastError, true);
                StackFrame sf = st.GetFrame(0);
                if (sf != null)
                {
                    this.fileName = sf.GetFileName();
                    this.Line     = sf.GetFileLineNumber();
                    if (retrieveSourceLines && this.fileName != null && File.Exists(this.fileName))
                    {
                        int lineNumber = sf.GetFileLineNumber();
                        if (lineNumber > 0)
                        {
                            StreamReader sr = new StreamReader(this.fileName);

                            int x = 0;
                            for (x = 0; x < lineNumber - 4; x++)
                            {
                                sr.ReadLine();
                            }

                            sb.Append("--- Code ---\r\n");
                            sb.AppendFormat("File: {0}\r\n", fileName);
                            sb.AppendFormat("Method: {0}\r\n\r\n", LastError.TargetSite);
                            sb.AppendFormat("Line {0}: {1}\r\n", x + 1, sr.ReadLine());
                            sb.AppendFormat("Line {0}: {1}\r\n", x + 2, sr.ReadLine());
                            sb.AppendFormat("Line {0}: {1}\r\n", x + 3, sr.ReadLine());
                            sb.AppendFormat("Line {0}: {1}\r\n", x + 4, sr.ReadLine());
                            sb.AppendFormat("Line {0}: {1}\r\n", x + 5, sr.ReadLine());
                            sb.AppendFormat("Line {0}: {1}\r\n", x + 6, sr.ReadLine());
                            sb.AppendFormat("Line {0}: {1}\r\n", x + 7, sr.ReadLine());

                            sr.Close();
                        }
                    }
                }

                this.sourceCode = "<pre>" + sb.ToString() + "</pre>";
            }

            if (Request.IsAuthenticated)
            {
                this.login = HttpContext.Current.User.Identity.Name;
            }
            else
            {
                this.login = "******";
            }


            return(true);
        }
Пример #29
0
 public static java.lang.Class[] getClassContext(object thisSecurityManager)
 {
     #if FIRST_PASS
     return null;
     #else
     List<java.lang.Class> stack = new List<java.lang.Class>();
     StackTrace trace = new StackTrace();
     for (int i = 0; i < trace.FrameCount; i++)
     {
         StackFrame frame = trace.GetFrame(i);
         MethodBase method = frame.GetMethod();
         if (Java_sun_reflect_Reflection.IsHideFromStackWalk(method))
         {
             continue;
         }
         Type type = method.DeclaringType;
         if (type == typeof(java.lang.SecurityManager))
         {
             continue;
         }
         stack.Add(ClassLoaderWrapper.GetWrapperFromType(type).ClassObject);
     }
     return stack.ToArray();
     #endif
 }
Пример #30
0
        /// <devdoc>
        ///   Returns information about the top stack frames in a string format.  The input param determines the number of
        ///   frames to include.
        /// </devdoc>
        public static string StackFramesToStr(int maxFrameCount)
        {
            string trace = string.Empty;

            try
            {
                StackTrace st = new StackTrace(true);
                int        dbgUtilFrameCount = 0;

                //
                // Ignore frames for methods on this library.
                // Note: The stack frame holds the latest frame at index 0.
                //
                while (dbgUtilFrameCount < st.FrameCount)
                {
                    StackFrame sf = st.GetFrame(dbgUtilFrameCount);

                    if (sf == null || sf.GetMethod().DeclaringType != typeof(DbgUtil))
                    {
                        break;
                    }

                    dbgUtilFrameCount++;
                }

                maxFrameCount += dbgUtilFrameCount; // add ignored frames.

                if (maxFrameCount > st.FrameCount)
                {
                    maxFrameCount = st.FrameCount;
                }

                for (int i = dbgUtilFrameCount; i < maxFrameCount; i++)
                {
                    StackFrame sf = st.GetFrame(i);

                    if (sf == null)
                    {
                        continue;
                    }

                    MethodBase mi = sf.GetMethod();

                    if (mi == null)
                    {
                        continue;
                    }

                    string args     = string.Empty;
                    string fileName = sf.GetFileName();

                    int backSlashIndex = fileName == null ? -1 : fileName.LastIndexOf('\\');

                    if (backSlashIndex != -1)
                    {
                        fileName = fileName.Substring(backSlashIndex + 1, fileName.Length - backSlashIndex - 1);
                    }

                    foreach (ParameterInfo pi in mi.GetParameters())
                    {
                        args += pi.ParameterType.Name + ", ";
                    }

                    if (args.Length > 0)    // remove last comma.
                    {
                        args = args.Substring(0, args.Length - 2);
                    }

                    trace += string.Format(CultureInfo.CurrentCulture, "at {0} {1}.{2}({3})\r\n", fileName, mi.DeclaringType, mi.Name, args);
                }
            }
            catch (Exception ex)
            {
                if (DbgUtil.IsCriticalException(ex))
                {
                    throw;  //rethrow critical exception.
                }
                trace += ex.ToString();
            }

            return(trace.ToString());
        }
Пример #31
0
        internal static void InternalLog(string logEntry)
        {
            StackTrace stackTrace = new StackTrace();

            Debug.WriteLine(string.Format("{0}: {1}", stackTrace.GetFrame(1).GetMethod().Name, logEntry));
        }
Пример #32
0
        public static string CleanupAsyncStackTrace(this StackTrace stackTrace)
        {
            if (stackTrace == null)
            {
                return("");
            }

            var sb = new StringBuilder();

            for (int i = 0; i < stackTrace.FrameCount; i++)
            {
                var sf = stackTrace.GetFrame(i);

                var mb = sf.GetMethod();

                if (IgnoreLine(mb))
                {
                    continue;
                }
                if (IsAsync(mb))
                {
                    sb.Append("async ");
                    TryResolveStateMachineMethod(ref mb, out var decType);
                }

                // return type
                if (mb is MethodInfo mi)
                {
                    sb.Append(BeautifyType(mi.ReturnType, false));
                    sb.Append(" ");
                }

                // method name
                sb.Append(BeautifyType(mb.DeclaringType, false));
                if (!mb.IsConstructor)
                {
                    sb.Append(".");
                }
                sb.Append(mb.Name);
                if (mb.IsGenericMethod)
                {
                    sb.Append("<");
                    foreach (var item in mb.GetGenericArguments())
                    {
                        sb.Append(BeautifyType(item, true));
                    }
                    sb.Append(">");
                }

                // parameter
                sb.Append("(");
                sb.Append(string.Join(", ", mb.GetParameters().Select(p => BeautifyType(p.ParameterType, true) + " " + p.Name)));
                sb.Append(")");

                // file name
                if (displayFilenames && (sf.GetILOffset() != -1))
                {
                    String fileName = null;

                    try
                    {
                        fileName = sf.GetFileName();
                    }
                    catch (NotSupportedException)
                    {
                        displayFilenames = false;
                    }
                    catch (SecurityException)
                    {
                        displayFilenames = false;
                    }

                    if (fileName != null)
                    {
                        sb.Append(' ');
                        sb.AppendFormat(CultureInfo.InvariantCulture, "(at {0})", AppendHyperLink(fileName, sf.GetFileLineNumber().ToString()));
                    }
                }

                sb.AppendLine();
            }
            return(sb.ToString());
        }
Пример #33
0
    ///////////////////////////////////////////////////////////
    // performs a stack trace to see where things went wrong
    // for reporting errors. called when attempting to apply
    // a preset from memory onto a component
    ///////////////////////////////////////////////////////////
    private static string GetErrorLocation()
    {
        StackTrace stackTrace = new StackTrace();

        string result = "";
        string declaringType = "";
        for (int v = stackTrace.FrameCount - 1; v > 1; v--)
        {
            StackFrame stackFrame = stackTrace.GetFrame(v);
            if (stackFrame.GetMethod().DeclaringType.ToString() == declaringType)
                result = "";	// only report the last called method within the same class
            declaringType = stackFrame.GetMethod().DeclaringType.ToString();
            result += declaringType + ":" + stackFrame.GetMethod().Name.ToString();
            if (v > 2)
                result += " --> ";
        }
        return result;
    }
Пример #34
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="callerStackBoundaryDeclaringType">The declaring type of the method that is
        /// the stack boundary into the logging system for this call.</param>
        /// <remarks>
        /// <para>
        /// Initializes a new instance of the <see cref="LocationInfo" />
        /// class based on the current thread.
        /// </para>
        /// </remarks>
        public LocationInfo(Type callerStackBoundaryDeclaringType)
        {
            // Initialize all fields
            m_className  = NA;
            m_fileName   = NA;
            m_lineNumber = NA;
            m_methodName = NA;
            m_fullInfo   = NA;

//#if !(NETCF || NETSTANDARD1_3) // StackTrace isn't fully implemented for NETSTANDARD1_3 https://github.com/dotnet/corefx/issues/1797
            if (callerStackBoundaryDeclaringType != null)
            {
                try
                {
                    StackTrace st         = new StackTrace(true);
                    int        frameIndex = 0;

                    // skip frames not from fqnOfCallingClass
                    while (frameIndex < st.FrameCount)
                    {
                        StackFrame frame = st.GetFrame(frameIndex);
                        if (frame != null && frame.GetMethod().DeclaringType == callerStackBoundaryDeclaringType)
                        {
                            break;
                        }
                        frameIndex++;
                    }

                    // skip frames from fqnOfCallingClass
                    while (frameIndex < st.FrameCount)
                    {
                        StackFrame frame = st.GetFrame(frameIndex);
                        if (frame != null && frame.GetMethod().DeclaringType != callerStackBoundaryDeclaringType)
                        {
                            break;
                        }
                        frameIndex++;
                    }

                    if (frameIndex < st.FrameCount)
                    {
                        // take into account the frames we skip above
                        int       adjustedFrameCount = st.FrameCount - frameIndex;
                        ArrayList stackFramesList    = new ArrayList(adjustedFrameCount);
                        m_stackFrames = new StackFrameItem[adjustedFrameCount];
                        for (int i = frameIndex; i < st.FrameCount; i++)
                        {
                            stackFramesList.Add(new StackFrameItem(st.GetFrame(i)));
                        }

                        stackFramesList.CopyTo(m_stackFrames, 0);

                        // now frameIndex is the first 'user' caller frame
                        StackFrame locationFrame = st.GetFrame(frameIndex);

                        if (locationFrame != null)
                        {
                            System.Reflection.MethodBase method = locationFrame.GetMethod();

                            if (method != null)
                            {
                                m_methodName = method.Name;
                                if (method.DeclaringType != null)
                                {
                                    m_className = method.DeclaringType.FullName;
                                }
                            }
                            m_fileName   = locationFrame.GetFileName();
                            m_lineNumber = locationFrame.GetFileLineNumber().ToString(System.Globalization.NumberFormatInfo.InvariantInfo);

                            // Combine all location info
                            m_fullInfo = m_className + '.' + m_methodName + '(' + m_fileName + ':' + m_lineNumber + ')';
                        }
                    }
                }
                catch (System.Security.SecurityException)
                {
                    // This security exception will occur if the caller does not have
                    // some undefined set of SecurityPermission flags.
                    LogLog.Debug(declaringType, "Security exception while trying to get caller stack frame. Error Ignored. Location Information Not Available.");
                }
            }
//#endif
        }
Пример #35
0
        public static void Document(Action shouldMethod, ITestOutputHelper testOutputHelper, Action <ShouldMatchConfigurationBuilder>?additionConfig = null)
        {
            var stackTrace     = new StackTrace(true);
            var caller         = stackTrace.GetFrame(1) !;
            var callerFileName = caller.GetFileName() !;
            var callerMethod   = caller.GetMethod() !;

            var testMethod = FileMethodsLookup.GetOrAdd(callerFileName, fn =>
            {
                var callerFile = File.ReadAllText(fn);
                var syntaxTree = CSharpSyntaxTree.ParseText(callerFile);
                return(syntaxTree.GetRoot()
                       .DescendantNodes()
                       .OfType <MethodDeclarationSyntax>().ToList());
            }).Single(m => m.Identifier.ValueText == callerMethod.Name);

            var documentCall = testMethod.DescendantNodes()
                               .OfType <InvocationExpressionSyntax>()
                               .First();

            var shouldMethodCallSyntax = documentCall.ArgumentList.Arguments[0];
            var blockSyntax            = shouldMethodCallSyntax.DescendantNodes()
                                         .OfType <BlockSyntax>()
                                         .First();
            var enumerable = blockSyntax
                             .Statements
                             .Select(s => s.WithoutLeadingTrivia().ToFullString());
            var body          = string.Join(string.Empty, enumerable).Trim();
            var exceptionText = Should.Throw <Exception>(shouldMethod).Message;

            testOutputHelper.WriteLine("Docs body:");
            testOutputHelper.WriteLine("");
            testOutputHelper.WriteLine(body);
            testOutputHelper.WriteLine("");
            testOutputHelper.WriteLine("");
            testOutputHelper.WriteLine("Exception text:");
            testOutputHelper.WriteLine("");
            testOutputHelper.WriteLine(exceptionText);

            try
            {
                body.ShouldMatchApproved(configurationBuilder =>
                {
                    configurationBuilder
                    .WithDiscriminator("codeSample")
                    .UseCallerLocation()
                    .SubFolder("CodeExamples")
                    .WithScrubber(scrubber).WithFileExtension(".cs");

                    additionConfig?.Invoke(configurationBuilder);
                });
            }
            finally
            {
                exceptionText = $@"```
{exceptionText}
```
";
                exceptionText.ShouldMatchApproved(configurationBuilder =>
                {
                    configurationBuilder
                    .WithDiscriminator("exceptionText")
                    .UseCallerLocation()
                    .SubFolder("CodeExamples")
                    .WithScrubber(scrubber);

                    additionConfig?.Invoke(configurationBuilder);
                });
            }
        }
Пример #36
0
        public static string ExceptionToString(Exception ex, bool needFileLineInfo, TraceFormat tf)
        {
            bool   isHtml  = (tf == TraceFormat.Html);
            string newLine = isHtml ? "<br />" + Environment.NewLine : Environment.NewLine;
            var    builder = new StringBuilder(0xff);

            if (isHtml)
            {
                var exText = (ex.GetType().Name + ": " + ex.Message).Replace("\r\n", "<br />");
                builder.Append("<hr/>" + exText + "<hr/>");
            }
            if (isHtml)
            {
                builder.Append("<span style=\"font-family: Courier New; font-size: 10pt;\">");
            }
            builder.Append(getText(isHtml, GetClassName(ex)));
            string message = ex.Message;

            if (!string.IsNullOrEmpty(message))
            {
                builder.Append(": ");
                builder.Append(getText(isHtml, message));
            }
            builder.Append(newLine);
            StackTrace stackTrace      = new StackTrace(ex, needFileLineInfo);
            StackTrace fullTrace       = null;
            int        startFrameIndex = 0;

            // If use unstable version.
            if (ErrorUseNewStackTrace)
            {
                // Get full stack trace from root to the current line.
                fullTrace = new StackTrace(needFileLineInfo);
                // Get current class.
                var currentClass = fullTrace.GetFrame(0).GetMethod().DeclaringType;
                // Get deepest/top method from stack trace.
                var method = stackTrace.FrameCount > 0
                    ? stackTrace.GetFrame(0).GetMethod()
                    : null;
                // Loop through full stack trace.
                for (int i = 0; i < fullTrace.FrameCount; i++)
                {
                    // Get frame method.
                    var m = fullTrace.GetFrame(i).GetMethod();
                    if (m == null)
                    {
                        continue;
                    }
                    // If same method was found then...
                    if (m.Equals(method))
                    {
                        // Start displaying stack trace from this method
                        // when converting stack trace to string.
                        startFrameIndex = i;
                        break;
                    }
                    // If method of full frame is located inside this class then...
                    if (m.DeclaringType.Equals(currentClass))
                    {
                        // Skip this frame.
                        startFrameIndex = i + 1;
                    }
                }
            }
            // Use full trace is exists.
            var trace = fullTrace ?? stackTrace;

            if (trace.FrameCount > 0)
            {
                builder.Append(newLine);
                builder.Append(TraceToString(trace, tf, startFrameIndex));
            }
            if (ex.InnerException != null)
            {
                builder.Append(getText(isHtml, " ---> "));
                builder.Append(ExceptionToString(ex.InnerException, needFileLineInfo, tf));
                builder.Append(newLine);
            }
            if (isHtml)
            {
                builder.Append("</span>");
            }
            return(builder.ToString());
        }
Пример #37
0
        public static void ExtractFormattedStackTrace(StackTrace trace, StringBuilder sb, StackTrace skip = null)
        {
            int begin = 0;

            if (skip != null && skip.FrameCount > 0)
            {
                MethodBase m0 = skip.GetFrame(skip.FrameCount - 1).GetMethod();

                for (int i = 0; i < trace.FrameCount; i++)
                {
                    StackFrame frame  = trace.GetFrame(i);
                    MethodBase method = frame.GetMethod();

                    if (method == m0)
                    {
                        begin = i + 1;
                        break;
                    }
                }

                sb.AppendLineEx();
            }

            for (int i = begin; i < trace.FrameCount; i++)
            {
                StackFrame frame  = trace.GetFrame(i);
                MethodBase method = frame.GetMethod();

                if (method == null || method.DeclaringType == null)
                {
                    continue;
                }

                Type   declaringType = method.DeclaringType;
                string str           = declaringType.Namespace;

                if ((InstantiateCount == 0 && declaringType == typeof(UnityEngine.Object) && method.Name == "Instantiate") || //(method.Name == "Internal_CloneSingle"
                    (SendMsgCount == 0 && declaringType == typeof(GameObject) && method.Name == "SendMessage"))
                {
                    break;
                }

                if ((str != null) && (str.Length != 0))
                {
                    sb.Append(str);
                    sb.Append(".");
                }

                sb.Append(declaringType.Name);
                sb.Append(":");
                sb.Append(method.Name);
                sb.Append("(");
                int             index      = 0;
                ParameterInfo[] parameters = method.GetParameters();
                bool            flag       = true;

                while (index < parameters.Length)
                {
                    if (!flag)
                    {
                        sb.Append(", ");
                    }
                    else
                    {
                        flag = false;
                    }

                    sb.Append(parameters[index].ParameterType.Name);
                    index++;
                }

                sb.Append(")");
                string fileName = frame.GetFileName();

                if (fileName != null)
                {
                    fileName = fileName.Replace('\\', '/');
                    sb.Append(" (at ");

                    if (fileName.StartsWith(projectFolder))
                    {
                        fileName = fileName.Substring(projectFolder.Length, fileName.Length - projectFolder.Length);
                    }

                    sb.Append(fileName);
                    sb.Append(":");
                    sb.Append(frame.GetFileLineNumber().ToString());
                    sb.Append(")");
                }

                if (i != trace.FrameCount - 1)
                {
                    sb.Append("\n");
                }
            }
        }
Пример #38
0
        public static string TraceToString(StackTrace st, TraceFormat tf, int startFrameIndex = 0)
        {
            bool   isHtml  = (tf == TraceFormat.Html);
            string newLine = (isHtml) ? "<br />" + Environment.NewLine : Environment.NewLine;
            bool   flag    = true;
            bool   flag2   = true;
            var    builder = new StringBuilder(0xff);

            if (isHtml)
            {
                builder.Append("<span style=\"font-family: Courier New; font-size: 10pt;\">");
            }
            for (int i = startFrameIndex; i < st.FrameCount; i++)
            {
                StackFrame frame  = st.GetFrame(i);
                MethodBase method = frame.GetMethod();
                if (method != null)
                {
                    if (flag2)
                    {
                        flag2 = false;
                    }
                    else
                    {
                        builder.Append(newLine);
                    }
                    if (isHtml)
                    {
                        builder.Append("&nbsp;&nbsp;&nbsp;<span style=\"color: #808080;\">at</span> ");
                    }
                    else
                    {
                        builder.Append("   at ");
                    }
                    Type declaringType = method.DeclaringType;
                    bool isForm        = IsFormStackFrame(frame);
                    if (declaringType != null)
                    {
                        string ns   = declaringType.Namespace.Replace('+', '.');
                        string name = declaringType.Name.Replace('+', '.');
                        if (isHtml)
                        {
                            if (isForm)
                            {
                                builder.Append("<span style=\"font-weight: bold;\">");
                            }
                            builder.Append(System.Web.HttpUtility.HtmlEncode(ns));
                            builder.Append(".");
                            builder.AppendFormat("<span style=\"color: #2B91AF; \">{0}</span>", System.Web.HttpUtility.HtmlEncode(name));
                            if (isForm)
                            {
                                builder.Append("</span>");
                            }
                        }
                        else
                        {
                            builder.AppendFormat("{0}.{1}", ns, name);
                        }
                        builder.Append(".");
                    }
                    if (isHtml && isForm)
                    {
                        builder.Append("<span style=\"font-weight: bold; color: #800000;\">");
                    }
                    builder.Append(method.Name);
                    if ((method is MethodInfo) && ((MethodInfo)method).IsGenericMethod)
                    {
                        Type[] genericArguments = ((MethodInfo)method).GetGenericArguments();
                        builder.Append("[");
                        int  index = 0;
                        bool flag3 = true;
                        while (index < genericArguments.Length)
                        {
                            if (!flag3)
                            {
                                builder.Append(",");
                            }
                            else
                            {
                                flag3 = false;
                            }
                            builder.Append(genericArguments[index].Name);
                            index++;
                        }
                        builder.Append("]");
                    }
                    builder.Append("(");
                    ParameterInfo[] parameters = method.GetParameters();
                    bool            flag4      = true;
                    for (int j = 0; j < parameters.Length; j++)
                    {
                        var param = parameters[j];
                        if (!flag4)
                        {
                            builder.Append(", ");
                        }
                        else
                        {
                            flag4 = false;
                        }
                        string paramType = "<UnknownType>";
                        bool   isClass   = false;
                        if (param.ParameterType != null)
                        {
                            isClass   = param.ParameterType.IsClass;
                            paramType = param.ParameterType.Name;
                        }
                        if (isHtml)
                        {
                            if (isClass)
                            {
                                builder.Append("<span style=\"color: #2B91AF; \">");
                            }
                            builder.Append(System.Web.HttpUtility.HtmlEncode(paramType));
                            if (isClass)
                            {
                                builder.Append("</span>");
                            }
                            builder.Append(" ");
                            builder.Append(System.Web.HttpUtility.HtmlEncode(paramType));
                        }
                        else
                        {
                            builder.AppendFormat("{0} {1}", paramType, param.Name);
                        }
                    }
                    builder.Append(")");
                    if (isHtml && isForm)
                    {
                        builder.Append("</span>");
                    }
                    if (flag && (frame.GetILOffset() != -1))
                    {
                        string fileName = null;
                        try
                        {
                            fileName = frame.GetFileName();
                        }
                        catch (NotSupportedException)
                        {
                            flag = false;
                        }
                        catch (SecurityException)
                        {
                            flag = false;
                        }
                        if (fileName != null)
                        {
                            var    lineNumber   = frame.GetFileLineNumber();
                            var    columnNumber = frame.GetFileColumnNumber();
                            string format;
                            if (isHtml)
                            {
                                builder.Append("<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
                                var fnHtml  = System.Web.HttpUtility.HtmlEncode(fileName);
                                var fnColor = isForm ? "#800000" : "#000000";
                                var fnSpan  = string.Format("<span style=\"color: {0};\">{1}</span>", fnColor, fnHtml);
                                // Add file as link.
                                var addLink = false;
                                if (addLink)
                                {
                                    var fnLink = System.Web.HttpUtility.UrlEncode(fileName.Replace("\\", "/")).Replace("+", "%20");
                                    builder.AppendFormat("<a href=\"file:///{0}\" style=\"text-decoration: none; color: #000000;\">{1}</a>", fnLink, fnSpan);
                                }
                                else
                                {
                                    builder.AppendFormat(fnSpan);
                                }
                                builder.AppendFormat("<span style=\"color: #808080;\">,</span> {0}", lineNumber);
                                builder.AppendFormat("<span style=\"color: #808080;\">:{0}</span>", columnNumber);
                            }
                            else
                            {
                                format = " in {0}, {1}:{2}";
                                builder.AppendFormat(format, fileName, lineNumber, columnNumber);
                            }
                        }
                    }
                }
            }
            if (isHtml || tf == TraceFormat.TrailingNewLine)
            {
                builder.Append(newLine);
            }
            if (isHtml)
            {
                builder.Append("</span>");
            }
            return(builder.ToString());
        }
Пример #39
0
 protected object RenderView(ExpandoObject model)
 {
     var st = new StackTrace(1);
     var view = st.GetFrame(0).GetMethod().Name;
     return RenderView(view, model);
 }
Пример #40
0
        private void btnVistaPrevia_Click(object sender, EventArgs e)
        {
            try
            {
                //ingresa fecha del reporte, no debe ser mayor que la fecha actual
                if (Convert.ToDateTime(txtFecha.Text) > DateTime.Today)
                {
                    MessageBox.Show("Fecha del reporte no debe ser mayor que la fecha actual.", "Generacion Reportes", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                    txtFecha.Focus();
                    return;
                }

                //selecciona opcion de reporte cmbOpciones
                if (cmbOpciones.SelectedIndex == -1)
                {
                    MessageBox.Show("Debe seleccionar un tipo de reporte a generar.", "Generacion Reportes", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                    cmbOpciones.Focus();
                    return;
                }
                else if (cmbOpciones.SelectedIndex == 0)
                {        //Parte de Atención Diaria
                    vSQL = "Select C.Descripcion AS Especialidad, B.Bus, Serie + '-' + Nro_Ticket AS Ticket, " +
                           "P.Ape_Paterno + ' ' + P.Ape_Materno + ' ' + P.Nombre AS Completo, " +
                           "P.Edad, CASE WHEN P.Sexo = 'M' THEN 'MASCULINO' ELSE 'FEMENINO' END AS Sexo, " +
                           "CB.Nro_Historia,CB.Fecha_Atencion, (SELECT DISTINCT Descripcion FROM TablaTipo T1 " +
                           "WHERE T1.Id_Tipo = CB.turno " +
                           "AND EXISTS (" +
                           " SELECT 1 " +
                           " FROM TablaTipo T2 " +
                           " WHERE T1.Id_Tabla = T2.Id_Tipo " +
                           " AND LTRIM(RTRIM(T2.Descripcion)) = 'TURNOS' " +
                           " AND LTRIM(RTRIM(T2.Id_Tabla)) = '0')) AS Turno, " +
                           " M.Ape_Paterno + ' ' + M.Ape_Materno + ' ' + M.Nombres AS CMP,DC.Cie10 AS prdg, " +
                           " LTrim(RTrim(DC.Procedimiento)) AS prcn " +
                           "FROM Cab_Cie10 CB Inner Join Tickets T " +
                           "On CB.Nro_Historia = T.Nro_Historia " +
                           "Inner Join Pacientes P " +
                           "On T.Id_Paciente = P.Id_Paciente " +
                           "Left Join Det_Cie10 DC " +
                           "On CB.Nro_Historia = DC.Nro_Historia " +
                           "Inner Join Personal M " +
                           "On CB.CMP = M.Id_Personal " +
                           "Inner Join Buses B " +
                           "On CB.Id_Bus = B.Id_Bus " +
                           "Inner Join Consultorios C " +
                           "On B.Id_Esp = C.Id_Consultorio " +
                           "Where CONVERT(VARCHAR,cb.fecha_atencion, 103) = '" + txtFecha.Text + "' " +
                           "And Left(CB.Nro_Historia,3) = '" + Operativo.id_oper + "'";
                }
                else if (cmbOpciones.SelectedIndex == 1)
                {        //Consolidado de Atenciones
                    vSQL = "Select C.Descripcion Consu,B.Bus,X.Descripcion Turn,Ape_Paterno+' ' + Ape_Materno + Case " +
                           "Nombres When '' Then '' Else ', ' End + Nombres Completo,P.Descripcion Producto, " +
                           "Sum(D.Cantidad) Cantidad,D.Monto Precio,Sum(D.Cantidad*D.Monto) Total " +
                           "From Cab_Cie10 CB Inner Join Tickets T " +
                           "On CB.Nro_Historia = T.Nro_Historia " +
                           "Inner Join Detalles D " +
                           "On T.Nro_Historia = D.Nro_Historia " +
                           "Inner Join Productos P " +
                           "On D.Id_Producto = P.Id_Producto " +
                           "Inner Join Buses B " +
                           "On CB.Id_Bus = B.Id_Bus " +
                           "Inner Join Consultorios C " +
                           "On B.Id_Esp = C.Id_Consultorio " +
                           "Inner Join " +
                           "(Select Id_Tipo,Descripcion " +
                           " From TablaTipo " +
                           " Where Id_Tabla In " +
                           " (Select Id_Tipo " +
                           "  From TablaTipo " +
                           "  Where Descripcion = 'TURNOS' " +
                           "  And Id_Tabla = '0')) X " +
                           "On CB.Turno = X.Id_Tipo " +
                           "Inner Join Personal M " +
                           "On CB.CMP = M.Id_Personal " +
                           "Where CONVERT(VARCHAR,fecha_atencion, 103) = '" + txtFecha.Text + "' " +
                           "And Left(CB.Nro_Historia,3) = '" + Operativo.id_oper + "'";
                }
                else if (cmbOpciones.SelectedIndex == 2)
                {        //Consolidado de Atenciones
                    vSQL = "Select C.Descripcion Especialidad,B.Bus Consultorio,X.Descripcion Turno,Ape_Paterno+' '+Ape_Materno+Case" +
                           " Nombres When '' Then '' Else ', ' End + Nombres Especialista,P.Descripcion Producto," +
                           " Sum(D.Cantidad) Cantidad,D.Monto Precio,Sum(D.Cantidad*D.Monto) Total" +
                           " From Cab_Cie10 CB Inner Join Tickets T" +
                           " On CB.Nro_Historia = T.Nro_Historia" +
                           " Inner Join Detalles D" +
                           " On T.Nro_Historia = D.Nro_Historia" +
                           " Inner Join Productos P" +
                           " On D.Id_Producto = P.Id_Producto" +
                           " Inner Join Buses B" +
                           " On CB.Id_Bus = B.Id_Bus" +
                           " Inner Join Consultorios C" +
                           " On B.Id_Esp = C.Id_Consultorio" +
                           " Inner Join" +
                           " (Select Id_Tipo,Descripcion" +
                           "  From TablaTipo" +
                           "  Where Id_Tabla" +
                           "  In (Select Id_Tipo" +
                           " 	   From TablaTipo"+
                           "      Where Descripcion = 'TURNOS'" +
                           "      And Id_Tabla = '0')) X" +
                           " On CB.Turno = X.Id_Tipo" +
                           " Inner Join" +
                           " (Select Ape_Paterno,Ape_Materno,Nombres,Id_Personal" +
                           "  From Personal" +
                           "  Union All Select Descripcion,'','', Id_Tipo " +
                           "  From TablaTipo" +
                           "  Where Id_Tabla In" +
                           "  (Select Id_Tipo" +
                           "   From TablaTipo" +
                           "   Where Descripcion = 'VAR_EXTRAS'" +
                           "   And Id_Tabla = '0')) M" +
                           " On T.CMP = M.Id_Personal" +
                           " Where CONVERT(VARCHAR,fecha_atencion, 103) = '" + txtFecha.Text + "' " +
                           " And Left(CB.Nro_Historia,3) = '" + Operativo.id_oper + "'";
                }

                //si la especialidad esta en 'ECOGRAFIA', 'RAYOS X', 'MAMOGRAFIA' entonces D.Pagado <> ''
                int iCantE = CuentaEspecialidad(Operativo.id_oper, txtFecha.Text);

                if (cmbOpciones.SelectedIndex > 0 && iCantE > 0)
                {
                    vSQL = vSQL + "And NOT D.Pagado = '' ";
                }

                //selecciona especialidad cmbEspecialidad
                if (cmbEspecialidad.SelectedIndex == -1)
                {
                    MessageBox.Show("Debe seleccionar una especialidad.", "Generacion Reportes", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                    cmbEspecialidad.Focus();
                    return;
                }
                else
                {
                    vEspecialidad = (Combos)cmbEspecialidad.SelectedItem;
                }

                //selecciona consultorio cmbConsultorio
                if (cmbConsultorio.SelectedIndex == -1)
                {
                    MessageBox.Show("Debe seleccionar un consultorio.", "Generacion Reportes", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                    cmbConsultorio.Focus();
                    return;
                }
                else
                {
                    vConsultorio = (Combos)cmbConsultorio.SelectedItem;
                }

                //selecciona especialista cmbEspecialista
                if (cmbEspecialista.SelectedIndex == -1)
                {
                    MessageBox.Show("Debe seleccionar un especialista.", "Generacion Reportes", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                    cmbEspecialista.Focus();
                    return;
                }
                else
                {
                    vEspecialista = (Combos)cmbEspecialista.SelectedItem;
                }

                //selecciona turno cmbTurno
                if (cmbTurno.SelectedIndex == -1)
                {
                    MessageBox.Show("Debe seleccionar un turno.", "Generacion Reportes", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                    cmbTurno.Focus();
                    return;
                }
                else
                {
                    vTurno = (Combos)cmbTurno.SelectedItem;
                }

                //agrega especialidad al query de los 3 tipos
                if (vEspecialidad.id_tipo != "TODOS")
                {
                    vSQL = vSQL + "And C.Id_Consultorio = '" + vEspecialidad.id_tipo + "' ";
                }

                //agrega consultorio al query de los 3 tipos
                if (vConsultorio.id_tipo != "TODOS")
                {
                    vSQL = vSQL + "And CB.Id_Bus = '" + vConsultorio.id_tipo + "' ";
                }

                //agrega especialista al query de los 3 tipos
                if (vEspecialista.id_tipo != "TODOS")
                {
                    vSQL = vSQL + "And CB.CMP = '" + vEspecialista.id_tipo + "' ";
                }

                //agrega turno al query de los 3 tipos
                if (vTurno.id_tipo != "TODOS")
                {
                    vSQL = vSQL + "And CB.Turno = '" + vTurno.id_tipo + "' ";
                }

                //agrega ordenacion al query Parte de Atención Diaria
                if (cmbOpciones.SelectedIndex == 0)
                {
                    vSQL = vSQL + "Order By C.Descripcion,B.Bus,CB.Fecha_Atencion,CB.Turno ";
                }

                //agrega agrupacion y ordenacion al query Consolidado de Atenciones y de Consolidado de Derivaciones
                if (cmbOpciones.SelectedIndex > 0)
                {
                    vSQL = vSQL + "Group By C.Descripcion,B.Bus,X.Descripcion,Ape_Paterno,Ape_Materno,Nombres,P.Descripcion,D.Monto ";
                    vSQL = vSQL + "Order By 1,2,3,4,5";
                }

                //genera reporte y carga los datos
                object result = WaitWindow.Show(WorkerMethod, "Generando el reporte...");
                if (result == null)
                {
                    MessageBox.Show("No se pudo procesar el reporte.");
                    return;
                }

                //llama al formulario que muestra el reporte
                frmCRViewer frg = new frmCRViewer(rpt);
                frg.ShowDialog();
            }
            catch (Exception ex)
            {
                var st    = new StackTrace(ex, true);
                var frame = st.GetFrame(0);
                var line  = frame.GetFileLineNumber();
                var col   = frame.GetFileColumnNumber();
                MessageBox.Show(ex.Message + (char)13 + "Linea: " + line + " Columna: " + col);
            }
        }
Пример #41
0
    /// <summary>
    /// Performs a stack trace to see where things went wrong
    /// for error reporting.
    /// </summary>
    public static string GetErrorLocation(int level = 1)
    {
        StackTrace stackTrace = new StackTrace();
        string result = "";
        string declaringType = "";

        for (int v = stackTrace.FrameCount - 1; v > level; v--)
        {
            if (v < stackTrace.FrameCount - 1)
                result += " --> ";
            StackFrame stackFrame = stackTrace.GetFrame(v);
            if (stackFrame.GetMethod().DeclaringType.ToString() == declaringType)
                result = "";	// only report the last called method within every class
            declaringType = stackFrame.GetMethod().DeclaringType.ToString();
            result += declaringType + ":" + stackFrame.GetMethod().Name;
        }

        return result;
    }
Пример #42
0
        public static string GetMethodName()
        {
            var st = new StackTrace(new StackFrame(1));

            return(st.GetFrame(0).GetMethod().Name);
        }
Пример #43
0
        private void WorkLoop()
        {
            try
            {
                Time = _stopWatch.ElapsedMilliseconds;

                if (!Settings.Multithreaded)
                {
                    Settings.ThreadLimit = 1;
                }

                mThread     = new Thread[Settings.ThreadLimit];
                mThreadInfo = new BSThreadInfo[Settings.ThreadLimit];

                for (int a = 0; a < mThreadInfo.Length; a++)
                {
                    mThreadInfo[a] = new BSThreadInfo(a);
                }

                // Server System Boot
                //
                //
                StartCore();

                if (Settings.Multithreaded)
                {
                    for (int a = 0; a < mThreadInfo.Length; a++)
                    {
                        mThread[a] = new Thread(() => ThreadLoop(mThreadInfo[a]));
                        mThread[a].IsBackground = true;
                        mThread[a].Start();
                    }
                }

                // Server Network Boot
                //
                //

                try
                {
                    while (isRunning) // Core Thread Loop
                    {
                        Time = _stopWatch.ElapsedMilliseconds;
                    }
                }
                catch (Exception ex)
                {
                    FrmMain.Enqueue(ex);

                    var _st    = new StackTrace(ex, true);
                    var _frame = _st.GetFrame(0);
                    var _line  = _frame.GetFileLineNumber();

                    File.AppendAllText(@".\Error.txt", string.Format("[{0}] {1} at line {2}{3}", Now, ex, _line, Environment.NewLine));
                }

                // Server System Stop
                //
                //
            }
            catch (Exception ex)
            {
                FrmMain.Enqueue(ex);

                var _st    = new StackTrace(ex, true);
                var _frame = _st.GetFrame(0);
                var _line  = _frame.GetFileLineNumber();

                File.AppendAllText(@".\Error.txt", string.Format("[{0}] {1} at line {2}{3}", Now, ex, _line, Environment.NewLine));
            }
        }
Пример #44
0
        public int insertarRegistro(ref List <Ent_tticol090> parametros, ref string strError)
        {
            method = MethodBase.GetCurrentMethod();
            bool retorno = false;

            int secuencia = 0;

            try
            {
                strSentencia = recursos.readStatement(method.ReflectedType.Name, method.Name, ref owner, ref env, tabla);

                foreach (Ent_tticol090 reg in parametros)
                {
                    secuencia    = lineCleareance_verificaItemInsert(reg, strError);
                    reg.srno     = secuencia;
                    parametrosIn = AdicionaParametrosComunes(reg);
                    retorno      = DAL.BaseDAL.BaseDal.EjecutarCrud("text", strSentencia, ref parametersOut, parametrosIn, false);
                }
                return(Convert.ToInt32(retorno));
            }

            catch (Exception ex)
            {
                strError = "Error when inserting data [090]. Try again or contact your administrator";
                log.escribirError(strError + Console.Out.NewLine + ex.Message, stackTrace.GetFrame(1).GetMethod().Name, method.Name, method.ReflectedType.Name);
            }

            return(Convert.ToInt32(retorno));
        }
Пример #45
0
        public static void Write(TraceItem traceItem, HttpContext httpContext = null)
        {
            StackTrace stackTrace = new StackTrace();
            MethodBase methodBase = stackTrace.GetFrame(1).GetMethod();

            string className  = methodBase.ReflectedType.FullName;
            string methodName = methodBase.Name;
            string username   = null;
            string domain     = null;
            string sessionId  = null;
            string resource   = null;
            string clientIp   = null;
            string hostname   = null;

            if (Context.Current != null && Context.Current.User != null)
            {
                username = Context.Current.User.Username;

                if (Context.Current.User.Domain != null)
                {
                    domain = Context.Current.User.Domain.Name;
                }
            }

            if (httpContext != null)
            {
                resource  = httpContext.Request.Path;
                sessionId = httpContext.Session.Id;
                clientIp  = httpContext.Request.HttpContext.Connection.RemoteIpAddress.ToString();
                hostname  = httpContext.Request.Host.Value;
            }

            using (SqlConnection connection = new SqlConnection(Settings.Current.StorageSource))
            {
                connection.Open();

                using (SqlCommand command = new SqlCommand("Zesty_Trace", connection))
                {
                    command.CommandType = System.Data.CommandType.StoredProcedure;

                    command.Parameters.Add(new SqlParameter()
                    {
                        ParameterName = "@className", Value = className
                    });
                    command.Parameters.Add(new SqlParameter()
                    {
                        ParameterName = "@method", Value = methodName
                    });
                    command.Parameters.Add(new SqlParameter()
                    {
                        ParameterName = "@hostname", Value = hostname ?? (Object)DBNull.Value
                    });
                    command.Parameters.Add(new SqlParameter()
                    {
                        ParameterName = "@clientip", Value = clientIp ?? (Object)DBNull.Value
                    });
                    command.Parameters.Add(new SqlParameter()
                    {
                        ParameterName = "@sessionid", Value = sessionId ?? (Object)DBNull.Value
                    });
                    command.Parameters.Add(new SqlParameter()
                    {
                        ParameterName = "@username", Value = username ?? (Object)DBNull.Value
                    });
                    command.Parameters.Add(new SqlParameter()
                    {
                        ParameterName = "@domain", Value = domain ?? (Object)DBNull.Value
                    });
                    command.Parameters.Add(new SqlParameter()
                    {
                        ParameterName = "@resource", Value = resource ?? (Object)DBNull.Value
                    });
                    command.Parameters.Add(new SqlParameter()
                    {
                        ParameterName = "@message", Value = traceItem.Message ?? (Object)DBNull.Value
                    });
                    command.Parameters.Add(new SqlParameter()
                    {
                        ParameterName = "@error", Value = traceItem.Error ?? (Object)DBNull.Value
                    });
                    command.Parameters.Add(new SqlParameter()
                    {
                        ParameterName = "@millis", Value = traceItem.Millis
                    });

                    command.ExecuteNonQuery();
                }
            }
        }
Пример #46
0
        static string GetStackTrace(Exception exception)
        {
            // Output stacktrace in custom format (very similar to Exception.StackTrace property on English systems).
            // Include filenames where available, but no paths.
            StackTrace    stackTrace = new StackTrace(exception, true);
            StringBuilder b          = new StringBuilder();

            for (int i = 0; i < stackTrace.FrameCount; i++)
            {
                StackFrame frame  = stackTrace.GetFrame(i);
                MethodBase method = frame.GetMethod();
                if (method == null)
                {
                    continue;
                }

                if (b.Length > 0)
                {
                    b.AppendLine();
                }

                b.Append("   at ");
                Type declaringType = method.DeclaringType;
                if (declaringType != null)
                {
                    b.Append(declaringType.FullName.Replace('+', '.'));
                    b.Append('.');
                }
                b.Append(method.Name);
                // output type parameters, if any
                if ((method is MethodInfo) && ((MethodInfo)method).IsGenericMethod)
                {
                    Type[] genericArguments = ((MethodInfo)method).GetGenericArguments();
                    b.Append('[');
                    for (int j = 0; j < genericArguments.Length; j++)
                    {
                        if (j > 0)
                        {
                            b.Append(',');
                        }
                        b.Append(genericArguments[j].Name);
                    }
                    b.Append(']');
                }

                // output parameters, if any
                b.Append('(');
                ParameterInfo[] parameters = method.GetParameters();
                for (int j = 0; j < parameters.Length; j++)
                {
                    if (j > 0)
                    {
                        b.Append(", ");
                    }
                    if (parameters[j].ParameterType != null)
                    {
                        b.Append(parameters[j].ParameterType.Name);
                    }
                    else
                    {
                        b.Append('?');
                    }
                    if (!string.IsNullOrEmpty(parameters[j].Name))
                    {
                        b.Append(' ');
                        b.Append(parameters[j].Name);
                    }
                }
                b.Append(')');

                // source location
                if (frame.GetILOffset() >= 0)
                {
                    string filename = null;
                    try {
                        string fullpath = frame.GetFileName();
                        if (fullpath != null)
                        {
                            filename = Path.GetFileName(fullpath);
                        }
                    } catch (SecurityException) {
                        // StackFrame.GetFileName requires PathDiscovery permission
                    } catch (ArgumentException) {
                        // Path.GetFileName might throw on paths with invalid chars
                    }
                    b.Append(" in ");
                    if (filename != null)
                    {
                        b.Append(filename);
                        b.Append(":line ");
                        b.Append(frame.GetFileLineNumber());
                    }
                    else
                    {
                        b.Append("offset ");
                        b.Append(frame.GetILOffset());
                    }
                }
            }

            return(b.ToString());
        }
Пример #47
0
        private static void DownloadFile(HttpContext context)
        {
            var flushed = false;

            try
            {
                var id  = context.Request[FilesLinkUtility.FileId];
                var doc = context.Request[FilesLinkUtility.DocShareKey] ?? "";

                using (var fileDao = Global.DaoFactory.GetFileDao())
                {
                    File file;
                    var  readLink = FileShareLink.Check(doc, true, fileDao, out file);
                    if (!readLink && file == null)
                    {
                        fileDao.InvalidateCache(id);

                        int version;
                        file = int.TryParse(context.Request[FilesLinkUtility.Version], out version) && version > 0
                                   ? fileDao.GetFile(id, version)
                                   : fileDao.GetFile(id);
                    }

                    if (file == null)
                    {
                        context.Response.StatusCode = (int)HttpStatusCode.NotFound;

                        return;
                    }

                    if (!readLink && !Global.GetFilesSecurity().CanRead(file))
                    {
                        context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                        return;
                    }

                    if (!string.IsNullOrEmpty(file.Error))
                    {
                        throw new Exception(file.Error);
                    }

                    if (!fileDao.IsExistOnStorage(file))
                    {
                        Global.Logger.ErrorFormat("Download file error. File is not exist on storage. File id: {0}.", file.ID);
                        context.Response.StatusCode = (int)HttpStatusCode.NotFound;

                        return;
                    }

                    FileMarker.RemoveMarkAsNew(file);

                    context.Response.Clear();
                    context.Response.ClearHeaders();
                    context.Response.Charset = "utf-8";

                    FilesMessageService.Send(file, context.Request, MessageAction.FileDownloaded, file.Title);

                    if (string.Equals(context.Request.Headers["If-None-Match"], GetEtag(file)))
                    {
                        //Its cached. Reply 304
                        context.Response.StatusCode = (int)HttpStatusCode.NotModified;
                        context.Response.Cache.SetETag(GetEtag(file));
                    }
                    else
                    {
                        context.Response.CacheControl = "public";
                        context.Response.Cache.SetETag(GetEtag(file));
                        context.Response.Cache.SetCacheability(HttpCacheability.Public);

                        Stream fileStream = null;
                        try
                        {
                            var title = file.Title;

                            if (file.ContentLength <= SetupInfo.AvailableFileSize)
                            {
                                var ext = FileUtility.GetFileExtension(file.Title);

                                var outType = (context.Request[FilesLinkUtility.OutType] ?? "").Trim();
                                if (!string.IsNullOrEmpty(outType) &&
                                    FileUtility.ExtsConvertible.Keys.Contains(ext) &&
                                    FileUtility.ExtsConvertible[ext].Contains(outType))
                                {
                                    ext = outType;
                                }

                                long offset = 0;
                                long length;
                                if (!file.ProviderEntry &&
                                    string.Equals(context.Request["convpreview"], "true", StringComparison.InvariantCultureIgnoreCase) &&
                                    FFmpegService.IsConvertable(ext))
                                {
                                    const string mp4Name = "content.mp4";
                                    var          mp4Path = FileDao.GetUniqFilePath(file, mp4Name);
                                    var          store   = Global.GetStore();
                                    if (!store.IsFile(mp4Path))
                                    {
                                        fileStream = fileDao.GetFileStream(file);

                                        Global.Logger.InfoFormat("Converting {0} (fileId: {1}) to mp4", file.Title, file.ID);
                                        var stream = FFmpegService.Convert(fileStream, ext);
                                        store.Save(string.Empty, mp4Path, stream, mp4Name);
                                    }

                                    var fullLength = store.GetFileSize(string.Empty, mp4Path);

                                    length     = ProcessRangeHeader(context, fullLength, ref offset);
                                    fileStream = store.GetReadStream(string.Empty, mp4Path, (int)offset);

                                    title = FileUtility.ReplaceFileExtension(title, ".mp4");
                                }
                                else
                                {
                                    if (!FileConverter.EnableConvert(file, ext))
                                    {
                                        if (!readLink && fileDao.IsSupportedPreSignedUri(file))
                                        {
                                            context.Response.Redirect(fileDao.GetPreSignedUri(file, TimeSpan.FromHours(1)).ToString(), true);

                                            return;
                                        }

                                        fileStream = fileDao.GetFileStream(file); // getStream to fix file.ContentLength

                                        if (fileStream.CanSeek)
                                        {
                                            var fullLength = file.ContentLength;
                                            length = ProcessRangeHeader(context, fullLength, ref offset);
                                            fileStream.Seek(offset, SeekOrigin.Begin);
                                        }
                                        else
                                        {
                                            length = file.ContentLength;
                                        }
                                    }
                                    else
                                    {
                                        title      = FileUtility.ReplaceFileExtension(title, ext);
                                        fileStream = FileConverter.Exec(file, ext);

                                        length = fileStream.Length;
                                    }
                                }

                                SendStreamByChunks(context, length, title, fileStream, ref flushed);
                            }
                            else
                            {
                                if (!readLink && fileDao.IsSupportedPreSignedUri(file))
                                {
                                    context.Response.Redirect(fileDao.GetPreSignedUri(file, TimeSpan.FromHours(1)).ToString(), true);

                                    return;
                                }

                                fileStream = fileDao.GetFileStream(file); // getStream to fix file.ContentLength

                                long offset = 0;
                                var  length = file.ContentLength;
                                if (fileStream.CanSeek)
                                {
                                    length = ProcessRangeHeader(context, file.ContentLength, ref offset);
                                    fileStream.Seek(offset, SeekOrigin.Begin);
                                }

                                SendStreamByChunks(context, length, title, fileStream, ref flushed);
                            }
                        }
                        catch (ThreadAbortException tae)
                        {
                            Global.Logger.Error("DownloadFile", tae);
                        }
                        catch (HttpException e)
                        {
                            Global.Logger.Error("DownloadFile", e);
                            throw new HttpException((int)HttpStatusCode.BadRequest, e.Message);
                        }
                        finally
                        {
                            if (fileStream != null)
                            {
                                fileStream.Close();
                                fileStream.Dispose();
                            }
                        }

                        try
                        {
                            context.Response.Flush();
                            context.Response.SuppressContent = true;
                            context.ApplicationInstance.CompleteRequest();
                            flushed = true;
                        }
                        catch (HttpException ex)
                        {
                            Global.Logger.Error("DownloadFile", ex);
                        }
                    }
                }
            }
            catch (ThreadAbortException tae)
            {
                Global.Logger.Error("DownloadFile", tae);
            }
            catch (Exception ex)
            {
                // Get stack trace for the exception with source file information
                var st = new 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();

                Global.Logger.ErrorFormat("Url: {0} {1} IsClientConnected:{2}, line number:{3} frame:{4}", context.Request.Url, ex, context.Response.IsClientConnected, line, frame);
                if (!flushed && context.Response.IsClientConnected)
                {
                    context.Response.StatusCode = 400;
                    context.Response.Write(HttpUtility.HtmlEncode(ex.Message));
                }
            }
        }
Пример #48
0
        static void Main(string[] args)
        {
            try
            {
                #region Setup

                Console.Write("Filename: ");
                _Filename = Console.ReadLine();
                if (String.IsNullOrEmpty(_Filename))
                {
                    return;
                }

                _Settings = new DatabaseSettings(_Filename);
                _Orm      = new WatsonORM(_Settings);

                _Orm.InitializeDatabase();

                DebugSettings debug = new DebugSettings();
                debug.DatabaseQueries = true;
                debug.DatabaseResults = true;

                _Orm.Logger = Logger;
                _Orm.Debug  = debug;

                _Orm.InitializeTable(typeof(Person));
                _Orm.TruncateTable(typeof(Person));
                Console.WriteLine("Using table: " + _Orm.GetTableName(typeof(Person)));

                #endregion

                #region Create-and-Store-Records

                Person p1 = new Person("Abraham", "Lincoln", Convert.ToDateTime("1/1/1980"), null, 42, null, "initial notes p1", PersonType.Human, null, false);
                Person p2 = new Person("Ronald", "Reagan", Convert.ToDateTime("2/2/1981"), Convert.ToDateTime("3/3/1982"), 43, 43, "initial notes p2", PersonType.Cat, PersonType.Cat, true);
                Person p3 = new Person("George", "Bush", Convert.ToDateTime("3/3/1982"), null, 44, null, "initial notes p3", PersonType.Dog, PersonType.Dog, false);
                Person p4 = new Person("Barack", "Obama", Convert.ToDateTime("4/4/1983"), Convert.ToDateTime("5/5/1983"), 45, null, "initial notes p4", PersonType.Human, null, true);

                for (int i = 0; i < 8; i++)
                {
                    Console.WriteLine("");
                }
                Console.WriteLine("| Creating p1");
                p1 = _Orm.Insert <Person>(p1);

                for (int i = 0; i < 8; i++)
                {
                    Console.WriteLine("");
                }
                Console.WriteLine("| Creating p2");
                p2 = _Orm.Insert <Person>(p2);

                for (int i = 0; i < 8; i++)
                {
                    Console.WriteLine("");
                }
                Console.WriteLine("| Creating p3");
                p3 = _Orm.Insert <Person>(p3);

                for (int i = 0; i < 8; i++)
                {
                    Console.WriteLine("");
                }
                Console.WriteLine("| Creating p4");
                p4 = _Orm.Insert <Person>(p4);

                #endregion

                #region Select

                for (int i = 0; i < 8; i++)
                {
                    Console.WriteLine("");
                }
                Console.WriteLine("| Selecting many by column name");
                DbExpression  eSelect1      = new DbExpression("id", DbOperators.GreaterThan, 0);
                List <Person> selectedList1 = _Orm.SelectMany <Person>(null, null, eSelect1);
                Console.WriteLine("| Retrieved: " + selectedList1.Count + " records");
                foreach (Person curr in selectedList1)
                {
                    Console.WriteLine("  | " + curr.ToString());
                }

                for (int i = 0; i < 8; i++)
                {
                    Console.WriteLine("");
                }
                Console.WriteLine("| Selecting many by property name");
                DbExpression eSelect2 = new DbExpression(
                    _Orm.GetColumnName <Person>(nameof(Person.FirstName)),
                    DbOperators.Equals,
                    "Abraham");
                List <Person> selectedList2 = _Orm.SelectMany <Person>(null, null, eSelect2);
                Console.WriteLine("| Retrieved: " + selectedList2.Count + " records");
                foreach (Person curr in selectedList2)
                {
                    Console.WriteLine("  | " + curr.ToString());
                }

                for (int i = 0; i < 8; i++)
                {
                    Console.WriteLine("");
                }
                Console.WriteLine("| Selecting by ID");
                Person pSelected = _Orm.SelectByPrimaryKey <Person>(3);
                Console.WriteLine("| Selected: " + pSelected.ToString());

                for (int i = 0; i < 8; i++)
                {
                    Console.WriteLine("");
                }
                Console.WriteLine("| Selecting first by column name");
                DbExpression eSelect3 = new DbExpression("id", DbOperators.Equals, 4);
                pSelected = _Orm.SelectFirst <Person>(eSelect3);
                Console.WriteLine("| Selected: " + pSelected.ToString());

                #endregion

                #region Update-Records

                for (int i = 0; i < 8; i++)
                {
                    Console.WriteLine("");
                }
                Console.WriteLine("| Updating p1");
                p1.Notes = "updated notes p1";
                p1       = _Orm.Update <Person>(p1);

                for (int i = 0; i < 8; i++)
                {
                    Console.WriteLine("");
                }
                Console.WriteLine("| Updating p2");
                p2.Notes = "updated notes p2";
                p2       = _Orm.Update <Person>(p2);

                for (int i = 0; i < 8; i++)
                {
                    Console.WriteLine("");
                }
                Console.WriteLine("| Updating p3");
                p3.Notes = "updated notes p3";
                p3       = _Orm.Update <Person>(p3);

                for (int i = 0; i < 8; i++)
                {
                    Console.WriteLine("");
                }
                Console.WriteLine("| Updating p4");
                p4.Notes = "updated notes p4";
                p4       = _Orm.Update <Person>(p4);

                #endregion

                #region Update-Many-Records

                for (int i = 0; i < 8; i++)
                {
                    Console.WriteLine("");
                }
                Console.WriteLine("| Updating many records");
                Dictionary <string, object> updateVals = new Dictionary <string, object>();
                updateVals.Add(_Orm.GetColumnName <Person>("Notes"), "Updated during update many!");
                _Orm.UpdateMany <Person>(eSelect1, updateVals);

                #endregion

                #region Select

                for (int i = 0; i < 8; i++)
                {
                    Console.WriteLine("");
                }
                Console.WriteLine("| Selecting many, test 1");
                selectedList1 = _Orm.SelectMany <Person>(null, null, eSelect1);
                Console.WriteLine("| Retrieved: " + selectedList1.Count + " records");
                foreach (Person curr in selectedList1)
                {
                    Console.WriteLine("  | " + curr.ToString());
                }

                for (int i = 0; i < 8; i++)
                {
                    Console.WriteLine("");
                }
                Console.WriteLine("| Selecting by ID");
                pSelected = _Orm.SelectByPrimaryKey <Person>(3);
                Console.WriteLine("| Selected: " + pSelected.ToString());

                for (int i = 0; i < 8; i++)
                {
                    Console.WriteLine("");
                }
                Console.WriteLine("| Selecting first");
                pSelected = _Orm.SelectFirst <Person>(eSelect2);
                Console.WriteLine("| Selected: " + pSelected.ToString());

                for (int i = 0; i < 8; i++)
                {
                    Console.WriteLine("");
                }
                Console.WriteLine("| Selecting between, test 1");
                DbExpression eSelect4 = DbExpression.Between("id", new List <object> {
                    2, 4
                });
                selectedList1 = _Orm.SelectMany <Person>(null, null, eSelect4);
                Console.WriteLine("| Retrieved: " + selectedList1.Count + " records");
                foreach (Person curr in selectedList1)
                {
                    Console.WriteLine("  | " + curr.ToString());
                }

                for (int i = 0; i < 8; i++)
                {
                    Console.WriteLine("");
                }
                Console.WriteLine("| Selecting by persontype");
                DbExpression eSelect5 = new DbExpression("persontype", DbOperators.Equals, PersonType.Dog);
                selectedList1 = _Orm.SelectMany <Person>(null, null, eSelect5);
                Console.WriteLine("| Retrieved: " + selectedList1.Count + " records");
                foreach (Person curr in selectedList1)
                {
                    Console.WriteLine("  | " + curr.ToString());
                }

                for (int i = 0; i < 8; i++)
                {
                    Console.WriteLine("");
                }
                Console.WriteLine("| Selecting handsome people");
                DbExpression eSelect6 = new DbExpression("ishandsome", DbOperators.Equals, true);
                selectedList1 = _Orm.SelectMany <Person>(null, null, eSelect6);
                Console.WriteLine("| Retrieved: " + selectedList1.Count + " records");
                foreach (Person curr in selectedList1)
                {
                    Console.WriteLine("  | " + curr.ToString());
                }

                for (int i = 0; i < 8; i++)
                {
                    Console.WriteLine("");
                }
                Console.WriteLine("| Selecting by reverse ID order");
                DbExpression    eSelect7    = new DbExpression("id", DbOperators.GreaterThan, 0);
                DbResultOrder[] resultOrder = new DbResultOrder[1];
                resultOrder[0] = new DbResultOrder("id", DbOrderDirection.Descending);
                selectedList1  = _Orm.SelectMany <Person>(null, null, eSelect7, resultOrder);
                Console.WriteLine("| Retrieved: " + selectedList1.Count + " records");
                foreach (Person curr in selectedList1)
                {
                    Console.WriteLine("  | " + curr.ToString());
                }

                #endregion

                #region Exception

                for (int i = 0; i < 8; i++)
                {
                    Console.WriteLine("");
                }
                Console.WriteLine("| Catching exception and displaying query");

                try
                {
                    _Orm.Query("SELECT * FROM person (((");
                }
                catch (Exception e)
                {
                    Console.WriteLine("Exception: " + e.Message);
                    Console.WriteLine("Query    : " + e.Data["Query"]);
                }

                #endregion

                #region Delete-Records

                for (int i = 0; i < 8; i++)
                {
                    Console.WriteLine("");
                }
                Console.WriteLine("| Deleting p1");
                _Orm.Delete <Person>(p1);

                for (int i = 0; i < 8; i++)
                {
                    Console.WriteLine("");
                }
                Console.WriteLine("| Deleting p2");
                _Orm.DeleteByPrimaryKey <Person>(2);

                for (int i = 0; i < 8; i++)
                {
                    Console.WriteLine("");
                }
                Console.WriteLine("| Deleting p3 and p4");
                DbExpression eDelete = new DbExpression("id", DbOperators.GreaterThan, 2);
                _Orm.DeleteMany <Person>(eDelete);

                #endregion
            }
            catch (Exception e)
            {
                // Get stack trace for the exception with source file information
                var st = new 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();
                Console.WriteLine("Stack trace:" + Environment.NewLine + SerializeJson(st, true));
                Console.WriteLine("Stack frame: " + Environment.NewLine + SerializeJson(st, true));
                Console.WriteLine("Line number: " + line);
                Console.WriteLine("Exception: " + Environment.NewLine + SerializeJson(e, true));
            }

            Console.WriteLine("");
            Console.WriteLine("Press ENTER to exit");
            Console.ReadLine();
        }
Пример #49
0
        /// <summary>
        /// Returns a <see cref="System.String"/> that contains the caller class and method name.
        /// </summary>
        /// <returns>A <see cref="System.String"/>, containing the caller class and method name.</returns>
        public static string GetCaller()
        {
            var trace = new StackTrace();
            var callerMethodName = trace.GetFrame(1).GetMethod().Name;
            var callerClassName = trace.GetFrame(1).GetMethod().ReflectedType.Name;

            return callerClassName + "::" + callerMethodName;
        }
        void FormatStack(StackTrace stackTrace, int index1, StringBuilder stringBuilder)
        {
            var frame  = stackTrace.GetFrame(index1);
            var method = frame.GetMethod();

            if (method != null)
            {
                var declaringType = method.DeclaringType;
                if (declaringType != null)
                {
                    var str1 = declaringType.Namespace;
                    if (!string.IsNullOrEmpty(str1))
                    {
                        stringBuilder.Append(str1);
                        stringBuilder.Append(".");
                    }

                    stringBuilder.Append(declaringType.Name);
                    stringBuilder.Append(":");
                    stringBuilder.Append(method.Name);
                    stringBuilder.Append("(");
                    var index2     = 0;
                    var parameters = method.GetParameters();
                    var flag       = true;
                    for (; index2 < parameters.Length; ++index2)
                    {
                        if (!flag)
                        {
                            stringBuilder.Append(", ");
                        }
                        else
                        {
                            flag = false;
                        }
                        stringBuilder.Append(parameters[index2].ParameterType.Name);
                    }

                    stringBuilder.Append(")");
                    var str2 = frame.GetFileName();
                    if (str2 != null &&
                        (!(declaringType.Name == "Debug") || !(declaringType.Namespace == "UnityEngine")) &&
                        (!(declaringType.Name == "Logger") || !(declaringType.Namespace == "UnityEngine")) &&
                        (!(declaringType.Name == "DebugLogHandler") ||
                         !(declaringType.Namespace == "UnityEngine")) &&
                        (!(declaringType.Name == "Assert") ||
                         !(declaringType.Namespace == "UnityEngine.Assertions")) && (!(method.Name == "print") ||
                                                                                     !(declaringType.Name ==
                                                                                       "MonoBehaviour") ||
                                                                                     !(declaringType.Namespace ==
                                                                                       "UnityEngine")))
                    {
                        stringBuilder.Append(" (at ");
#if UNITY_EDITOR
                        str2 = str2.Replace(@"\", "/");
                        if (!string.IsNullOrEmpty(projectFolder) && str2.StartsWith(projectFolder))
                        {
                            str2 = str2.Substring(projectFolder.Length, str2.Length - projectFolder.Length);
                        }
#endif
                        stringBuilder.Append(str2);
                        stringBuilder.Append(":");
                        stringBuilder.Append(frame.GetFileLineNumber().ToString());
                        stringBuilder.Append(")");
                    }

                    stringBuilder.Append("\n");
                }
            }
        }
Пример #51
0
		/// <summary>
		/// used by the debug mode to fetch the callstack
		/// </summary>
		public void StoreCallingMethod()
		{
			StackTrace stackTrace = new StackTrace();

			string result = "";
			string declaringType = "";
			for (int v = 3; v < stackTrace.FrameCount; v++)
			{
				StackFrame stackFrame = stackTrace.GetFrame(v);
				declaringType = stackFrame.GetMethod().DeclaringType.ToString();
				result += " <- " + declaringType + ":" + stackFrame.GetMethod().Name.ToString();
			}

			m_CallingMethod = result;

		}
Пример #52
0
        internal void Terminate()
        {
            if (Results.Count == 0)
            {
                return;
            }

            if (ScriptCsSettings.PrettyPrintResults)
            {
                ConsoleHelper.Clear();
                Console.WriteLine();
                ConsoleHelper.DrawMessageBox(2, "F14N - Fluent Automation Console", true);
                Console.WriteLine();

                var index = 1;
                foreach (var result in Results)
                {
                    if (!result.Passed)
                    {
                        Console.ForegroundColor = result.Passed ? ConsoleColor.DarkGreen : ConsoleColor.Red;
                        Console.WriteLine("   {0}) {1}", index, result.Name);
                        Console.ResetColor();
                        if (result.Message != null)
                        {
                            Console.WriteLine();
                            ConsoleHelper.DrawMessageBox(6, result.Message + Environment.NewLine + result.Exception.StackTrace);
                            Console.WriteLine();
                        }
                    }

                    index++;
                }

                var    timeDiff   = DateTime.Now - StartTime.Value;
                string timeString = string.Empty;
                if (timeDiff.TotalSeconds <= 59)
                {
                    timeString = string.Format("{0} seconds", timeDiff.TotalSeconds);
                }
                else
                if (timeDiff.Seconds == 0)
                {
                    timeString = string.Format("{0} minutes", timeDiff.TotalMinutes);
                }
                else
                {
                    timeString = string.Format("{0} minutes, {1} seconds", timeDiff.TotalMinutes, timeDiff.Seconds);
                }

                var hasErrors = Results.Count(x => x.Passed == false) == 0;
                Console.ForegroundColor = hasErrors ? ConsoleColor.DarkGreen : ConsoleColor.Red;
                var stream = Console.Out;
                if (hasErrors)
                {
                    stream = Console.Error;
                }

                stream.WriteLine("   {0} tests complete ({1}){2}", Results.Count, timeString, Environment.NewLine);
                Console.ResetColor();
            }
            else
            {
                List <dynamic> errorResults = new List <dynamic>();
                foreach (var result in Results)
                {
                    if (!result.Passed)
                    {
                        var stackTrace = new StackTrace(result.Exception, true);
                        var errorFrame = stackTrace.GetFrame(0);

                        errorResults.Add(new
                        {
                            Column     = errorFrame.GetFileColumnNumber(),
                            Row        = errorFrame.GetFileLineNumber(),
                            Message    = result.Message,
                            StackTrace = result.Exception.StackTrace
                        });
                    }
                }

                var resultsContainer = new
                {
                    TestCount      = Results.Count,
                    ElapsedSeconds = (DateTime.Now - StartTime.Value).TotalSeconds,
                    Errors         = errorResults
                };

                var stream = Console.Out;
                if (errorResults.Count > 0)
                {
                    stream = Console.Error;
                }

                stream.WriteLine(SimpleJson.SimpleJson.SerializeObject(resultsContainer));
            }
        }
Пример #53
0
	private static void _HandleException (System.Exception e, string message, bool uncaught)
	{
		if (e == null) {
			return;
		}
		
		if (!IsInitialized) {
			return;
		}

		string name = e.GetType ().Name;
		string reason = e.Message;

		if (!string.IsNullOrEmpty (message)) {
			reason = string.Format ("{0}{1}***{2}", reason, Environment.NewLine, message);
		}

		StringBuilder stackTraceBuilder = new StringBuilder ("");

		StackTrace stackTrace = new StackTrace (e, true);
		int count = stackTrace.FrameCount;
		for (int i = 0; i < count; i++) {
			StackFrame frame = stackTrace.GetFrame (i);

			stackTraceBuilder.AppendFormat ("{0}.{1}", frame.GetMethod ().DeclaringType.Name, frame.GetMethod ().Name);

			ParameterInfo[] parameters = frame.GetMethod ().GetParameters ();
			if (parameters == null || parameters.Length == 0) {
				stackTraceBuilder.Append (" () ");
			} else {
				stackTraceBuilder.Append (" (");
				
				int pcount = parameters.Length;
				
				ParameterInfo param = null;
				for (int p = 0; p < pcount; p++) {
					param = parameters [p];
					stackTraceBuilder.AppendFormat ("{0} {1}", param.ParameterType.Name, param.Name);
					
					if (p != pcount - 1) {
						stackTraceBuilder.Append (", ");
					}
				}
				param = null;
				
				stackTraceBuilder.Append (") ");
			}

			string fileName = frame.GetFileName ();
			if (!string.IsNullOrEmpty (fileName) && !fileName.ToLower ().Equals ("unknown")) {
				fileName = fileName.Replace ("\\", "/");
				
				int loc = fileName.ToLower ().IndexOf ("/assets/");
				if (loc < 0) {
					loc = fileName.ToLower ().IndexOf ("assets/");
				}
				
				if (loc > 0) {
					fileName = fileName.Substring (loc);
				}

				stackTraceBuilder.AppendFormat ("(at {0}:{1})", fileName, frame.GetFileLineNumber ());
			}
			stackTraceBuilder.AppendLine ();
		}

		// report
		_reportException (uncaught, name, reason, stackTraceBuilder.ToString ());
	}
Пример #54
0
    public static void UpdateOverlayMessage(string message)
    {
        InvokeOnMainThread(() => {
            if (LoadingOverlay != null)
            {
                StackTrace stackTrace = new StackTrace();
                System.Diagnostics.Debug.WriteLine(typeof(Helpers).Name + " (called from " + stackTrace.GetFrame(1).GetMethod().Name + ")" + LoadingOverlay.GetHashCode());

                LoadingOverlay.SetLoadingLabel(message);
            }
        });
    }
    private static int ExecuteScript(string script, string arguments,
      out string output)
    {
        StackFrame sf = new StackFrame(true);
        StackTrace st = new StackTrace(sf);

        sf = st.GetFrame(0);
        string dir = Path.GetDirectoryName(sf.GetFileName());
        string fileName = Path.Combine(dir, script);

        AddExecutablePermissionToScript(fileName);
        return Execute(fileName, arguments, out output);
    }
Пример #56
0
        public static List <Address> getCityByCompanyList(String companyId, String divisionId, String keyStroke)
        {
            Logger.LogDebug(MethodBase.GetCurrentMethod().DeclaringType.ToString(), MethodBase.GetCurrentMethod().Name, "Entry Point", Logger.logLevel.Info);
            Logger.LogDebug(MethodBase.GetCurrentMethod().DeclaringType.ToString(), MethodBase.GetCurrentMethod().Name, companyId + divisionId + keyStroke, Logger.logLevel.Debug);

            List <Address> lstAddress = new List <Address>();

            SqlConnection conn   = null;
            SqlDataReader reader = null;

            try
            {
                // create and open a connection object
                conn = ConnectionManager.getConnection();
                conn.Open();


                String query;
                if (companyId.Equals("null") && divisionId.Equals("null"))
                {
                    query = "select distinct TOP 50  P.address3 FROM person P WHERE P.address3 LIKE '%" + keyStroke + "%'";
                }

                else if (!companyId.Equals("null") && !divisionId.Equals("null"))
                {
                    query = "select distinct TOP 50  P.address3 FROM person P, department D,rs_company Comp, rs_division Div";
                    query = query + " WHERE P.department = D.id AND Comp.companyId = @company AND Div.divisionId = @division AND D.user1 LIKE Comp.companyName AND D.user2 LIKE Div.divisionName AND P.address3 LIKE '%" + keyStroke + "%'";
                }
                else if (companyId.Equals("null"))
                {
                    query = "select distinct TOP 50  P.address3 FROM person P, department D,rs_division Div";
                    query = query + " WHERE P.department = D.id AND  Div.divisionId = @division AND D.user2 LIKE Div.divisionName AND P.address3 LIKE '%" + keyStroke + "%'";
                }
                else
                {
                    query = "select distinct TOP 50 P.address3 FROM person P, department D,rs_company Comp";
                    query = query + " WHERE P.department = D.id AND Comp.companyId = @company AND D.user1 LIKE Comp.companyName AND P.address3 LIKE '%" + keyStroke + "%'";
                }

                SqlCommand command = new SqlCommand(query, conn);
                command.Parameters.AddWithValue("@company", companyId.Trim());
                command.Parameters.AddWithValue("@division", divisionId.Trim());


                using (reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        String strAddress = reader.GetSqlValue(0).ToString().Trim();
                        if (!(strAddress.Equals("null") || strAddress.Equals("NULL") || strAddress.Equals("Null") || strAddress.Equals("")))
                        {
                            Address addressObj = new Address();
                            addressObj.key   = reader.GetSqlValue(0).ToString().Trim();
                            addressObj.value = reader.GetSqlValue(0).ToString().Trim();
                            lstAddress.Add(addressObj);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                var stackTrace = new StackTrace(ex, true);
                var line       = stackTrace.GetFrame(0).GetFileLineNumber();
                Logger.LogExceptions(MethodBase.GetCurrentMethod().DeclaringType.ToString(), MethodBase.GetCurrentMethod().Name, ex.Message, line.ToString(), Logger.logLevel.Exception);
            }
            finally
            {
                if (conn != null)
                {
                    conn.Close();
                }
                if (reader != null)
                {
                    reader.Close();
                }
            }
            lstAddress = lstAddress.OrderBy(x => x.value).ToList();
            Logger.LogDebug(MethodBase.GetCurrentMethod().DeclaringType.ToString(), MethodBase.GetCurrentMethod().Name, "Exit Point", Logger.logLevel.Debug);
            return(lstAddress);
        }
Пример #57
0
        static async Task Main(string[] args)
        {
            ThreadPool.SetMaxThreads(100, Int32.MaxValue);
            // Create the token source.
            var cts = new CancellationTokenSource();

            await using var crawlerHost = new CrawlerHost();
            var hostBuilder = CrawlerHost.CreateHostBuilder(args, (hostContext, services) =>
            {
                //Add more services to the Dependency Injection here

                //1. Scheduler
                // services.AddTransient<ISchedulerService, DefaultScheduler>();
                // services.AddHostedService(serviceProvider => serviceProvider.GetService<ISchedulerService>());
                services.AddTransient <IScheduler, CoreScheduler>();
                services.AddHostedService(serviceProvider => serviceProvider.GetService <IScheduler>());

                services.AddSingleton <ObservableConcurrentQueue <WaitingPageModel> >();
                // services.AddSingleton<AsyncBulkheadPolicy>(serviceProvider =>
                //     Policy.BulkheadAsync(Convert.ToInt32(hostContext.Configuration.GetSection("AppConfig")["MaxThreads"]),
                //         Int32.MaxValue));
                services.AddTransient <IUriBucket <WaitingPage>, DefaultWaitingUriBucket>();
                services.AddDbContextPool <UriDBContext>(options =>
                {
                    options.UseSqlite(@"Data Source=./1_Scheduler/DB/UriDB.db;");
                }, 16);

                //2. Crawler
                services.AddSingleton <IBrowsingContext>(serviceProvider =>
                {
                    //Use the default configuration for AngleSharp
                    var config = Configuration.Default
                                 .WithRequesters()     // from AngleSharp.Io
                                 .WithDefaultLoader(); // from AngleSharp

                    //Create a new context for evaluating webpages with the given config
                    var context = BrowsingContext.New(config);
                    return(context);
                });

                //3. Downloader
                services.AddHttpClient();
                services.AddTransient <IDownloader, Downloader>();

                //4. UriPolicies

                //5. Content Extractor
                services.AddTransient <IContentExtractor, ContentExtractor>();

                //6. Storage
                services.AddDbContextPool <ContentContext>((serviceProvider, options) =>
                {
                    options.UseSqlite(hostContext.Configuration.GetSection("AppConfig")["ConnectionString"]);
                    // options.UseSqlite(@"Data Source=./4_Storage/PageModels/DB/content.db;");
                }, 32);
            });

            try
            {
                Console.WriteLine("Application Starting!");

                using var host = crawlerHost.RunCrawlerEngine(hostBuilder, cts.Token);

                // var waitingQueue = host.Services.GetRequiredService<ObservableConcurrentQueue<WaitingPageModel>>();
                // waitingQueue.Enqueue(new WaitingPageModel {Uri = new Uri("https://www.webtoons.com"), Verb = "GET"});

                await host.StartAsync(cts.Token);

                Console.WriteLine("Application Started! Press <enter> to stop.");

                var waitingQueue = host.Services.GetRequiredService <ObservableConcurrentQueue <WaitingPageModel> >();
                waitingQueue.Enqueue(new WaitingPageModel {
                    Uri = new Uri("https://www.webtoons.com"), Verb = "GET"
                });

                // Console.WriteLine("Enter");

                Console.ReadLine();

                // waitingQueue = host.Services.GetRequiredService<ObservableConcurrentQueue<WaitingPageModel>>();
                // waitingQueue.Enqueue(new WaitingPageModel {Uri = new Uri("https://www.webtoons.com"), Verb = "GET"});
                //
                // Console.ReadLine();

                // cts.Cancel();

                await host.StopAsync(cts.Token);

                Console.WriteLine("Application Stopping!");
                Console.WriteLine("Main thread Stopped!");
            }
            catch (Exception e)
            {
                var trace = new StackTrace(e, true);
                var line  = trace.GetFrame(trace.FrameCount - 1).GetFileLineNumber();
                Console.WriteLine("Exception at line " + line);
                Console.WriteLine(e);
            }
            finally
            {
                cts.Dispose();
            }
        }
Пример #58
0
        private bool PrepRemoteCall(string url, object[] o, out MethodInfo method, out OSDMap map, out string serverURL)
        {
            StackTrace stackTrace = new StackTrace();
            int        upStack    = 1;
            StackFrame frame      = stackTrace.GetFrame(1);

            if (frame.GetMethod().Name.Contains("DoRemote"))
            {
                upStack = 2;
                frame   = stackTrace.GetFrame(2);
                if (frame.GetMethod().Name.Contains("DoRemote"))
                {
                    upStack = 3;
                }
            }

            CanBeReflected reflection;

            GetReflection(upStack, stackTrace, out method, out reflection);
            string methodName = reflection != null && reflection.RenamedMethod != ""
                                    ? reflection.RenamedMethod
                                    : method.Name;

            map           = new OSDMap();
            map["Method"] = methodName;
            if (reflection != null && reflection.UsePassword)
            {
                map["Password"] = m_password;
            }
            int i          = 0;
            var parameters = method.GetParameters();

            if (o.Length != parameters.Length)
            {
                MainConsole.Instance.ErrorFormat(
                    "FAILED TO GET VALID NUMBER OF PARAMETERS TO SEND REMOTELY FOR {0}, EXPECTED {1}, GOT {2}",
                    methodName, parameters.Length, o.Length);
                serverURL = "";
                return(false);
            }
            foreach (ParameterInfo info in parameters)
            {
                OSD osd = o[i] == null ? null : Util.MakeOSD(o[i], o[i].GetType());
                if (osd != null)
                {
                    map.Add(info.Name, osd);
                }
                else
                {
                    map.Add(info.Name, new OSD());
                }
                i++;
            }

            serverURL = m_configService == null ? "" : m_configService.FindValueOf(url);
            if (serverURL == "")
            {
                serverURL = url;
            }
            return(true);
        }
Пример #59
0
        public MethodBase GetCallerStackFrameMethod(int skipFrames)
        {
            StackFrame frame = StackTrace?.GetFrame(UserStackFrameNumber + skipFrames);

            return(frame?.GetMethod());
        }
Пример #60
0
        public static void ExtractFormattedStackTrace(StackTrace stackTrace, StringBuilder sb)
        {
            sb = sb ?? new StringBuilder(255);
            int iIndex;

            // need to skip over "n" frames which represent the
            // System.Diagnostics package frames
            for (iIndex = 0; iIndex < stackTrace.FrameCount; iIndex++)
            {
                StackFrame frame = stackTrace.GetFrame(iIndex);

                MethodBase mb = frame.GetMethod();
                if (mb == null)
                {
                    continue;
                }

                Type classType = mb.DeclaringType;
                if (classType == null)
                {
                    continue;
                }

                var classTypeName      = classType.Name;
                var classTypeNamespace = classType.Namespace;

                // Add namespace.classname:MethodName
                if (!string.IsNullOrEmpty(classTypeNamespace))
                {
                    sb.Append(classTypeNamespace);
                    sb.Append(".");
                }

                sb.Append(classTypeName);
                sb.Append(":");
                sb.Append(mb.Name);
                sb.Append("(");

                // Add parameters
                int             j           = 0;
                ParameterInfo[] pi          = mb.GetParameters();
                bool            fFirstParam = true;
                while (j < pi.Length)
                {
                    if (fFirstParam == false)
                    {
                        sb.Append(", ");
                    }
                    else
                    {
                        fFirstParam = false;
                    }

                    sb.Append(pi[j].ParameterType.Name);
                    j++;
                }

                sb.Append(")");

                // Add path name and line number - unless it is a Debug.Log call, then we are only interested
                // in the calling frame.
                string path = frame.GetFileName();
                if (path != null)
                {
                    bool shouldStripLineNumbers =
                        (classTypeName == "Debug" && classTypeNamespace == "UnityEngine") ||
                        (classTypeName == "Logger" && classTypeNamespace == "UnityEngine") ||
                        (classTypeName == "DebugLogHandler" && classTypeNamespace == "UnityEngine") ||
                        (classTypeName == "Assert" && classTypeNamespace == "UnityEngine.Assertions") ||
                        (mb.Name == "print" && classTypeName == "MonoBehaviour" && classTypeNamespace == "UnityEngine")
                    ;

                    if (!shouldStripLineNumbers)
                    {
                        sb.Append(" (at ");

                        if (!string.IsNullOrEmpty(s_projectFolder))
                        {
                            if (StartsWithPath(path, s_projectFolder))
                            {
                                path = path.Substring(s_projectFolder.Length, path.Length - s_projectFolder.Length);
                            }
                        }

                        sb.Append(path);
                        sb.Append(":");
                        sb.Append(frame.GetFileLineNumber().ToString());
                        sb.Append(")");
                    }
                }

                sb.Append("\n");
            }

            sb.Replace("\\", "/");
        }