c# commandline no error line number - c#

If there is an exception in .NET code and and PDB file is available you normally get the errors with source code line numbers shown in the exception message. This seems to be different in command line executables, where I do not get any line number although a PDB file is available:
Anwendung: MNX.CommandLine.EpkFtpEventhandler.exe Frameworkversion: v4.0.30319 Beschreibung: Der Prozess wurde aufgrund eines Ausnahmefehlers beendet. Ausnahmeinformationen: System.Data.SqlClient.SqlException Stapel: bei System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(System.String, Boolean, Int32, Boolean) bei System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(System.Threading.Tasks.TaskCompletionSource`1, System.String, Boolean, Int32, Boolean) bei System.Data.SqlClient.SqlCommand.ExecuteNonQuery() bei MNX.DB.WriteLocal(System.String) bei MNX.DB.Write(System.String) bei MNX.CommandLine.EpkFtpEventHandler.Main(System.String[])
Does anyone know why?

Use Stack Frames and surround you code with a try catch:
try
{
throw new Exception();
}
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();
// Print the line number
Console.WriteLine($"An Error ({ex.Message}) occurred in line {line}");
}
To avoid plagiarism: I got the idea from this question.
I don't know why it isn't normally displayed in your console application though, but this should do it as well.

Try to empty symbol cache by accessing Debug > Options > Debugging > Symbols and clean your solution afterwards.

Exception.StackTrace gave back the line number, when it comes from a catch. Strangely only when I catch the exception, not when it's thrown without being catched.

Related

C# Directory.CreateDirectory stop working

I have a C# application, it works properly on many pc, laptop. But, I copied to my customer's pc (4TB HDD - windows 10 Home Edition), my application stop working!
I try to put MessageBox.Show() in some line to find where is broken. And it stop at Directory.CreateDirectory(#"D:\\mypath")
The PC have D: and I don't know why it broken.
Here is my code:
string now = DateTime.Now.ToString("HH_mm_ss");
string strDuongDan;
strDuongDan = #"D:\VideoLuuTru\" + DateTime.Now.Month.ToString() + "_" + DateTime.Now.Year.ToString();
if (!Directory.Exists(strDuongDan))
Directory.CreateDirectory(strDuongDan);
string strDuongDan2 = strDuongDan + "\\" + DateTime.Now.ToString("dd"); ;
if (!Directory.Exists(strDuongDan2))
Directory.CreateDirectory(strDuongDan2);
How can I trace exactly my errors, and is there anything wrong from my code? It running perfectly in many PCs but with this PC, it broken.
Is my problem related to large hard drive space?
My customer's IT staff installed my app on his laptop (Windows 10 Home) and installed the same windows to this pc. My app run on His laptop without errors
Thanks you!
EDIT:
My Function and my errors:
Function:
public void makevideo()
{
string now = DateTime.Now.ToString("HH_mm_ss");
string strDuongDan;
strDuongDan = #"D:\VideoLuuTru\" + DateTime.Now.Month.ToString() + "_" + DateTime.Now.Year.ToString();
if (!Directory.Exists(strDuongDan))
Directory.CreateDirectory(strDuongDan);
string strDuongDan2 = strDuongDan + "\\" + DateTime.Now.ToString("dd"); ;
if (!Directory.Exists(strDuongDan2))
Directory.CreateDirectory(strDuongDan2);
}
Call function
ThreadStart childref = new ThreadStart(() => makevideo());
Thread childThread = new Thread(childref);
try { childThread.Start(); }
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Errors:
**
Application: camera.exe Framework Version: v4.0.30319 Description: The process was terminated due to an unhandled exception.
Exception Info: System.IO.FileNotFoundException at camera.Form1.makevideo() at camera.Form1.<Form1_Load>b__6_0() at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext,
System.Threading.ContextCallback, System.Object, Boolean) at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean) at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext,
System.Threading.ContextCallback, System.Object) at
System.Threading.ThreadHelper.ThreadStart()
**
I don't usually recommend catching errors like this
However you can use a logger, or if you really must you can just push the error into a MessageBox. at least you will know the exception
Alternatively you could check the event log viewer, if your application crashes it will give you clues as to what happened.
Lastly, most likely this is a permission thing, but who knows. Make sure your client has given the appropriate permissions to that directory or run your application at an elevated privilege
try
{
// Note you don't need to check if a directory exists before you create it
// it does it for you
// if (!Directory.Exists(strDuongDan))
Directory.CreateDirectory(strDuongDan);
}
catch(Exception ex)
{
// log here
// or
MessageBox.Show("Error : " + ex.Message)
}
Directory.CreateDirectory Method (String)
Exceptions
IOException
The directory specified by path is a file.
The network name is not known.
UnauthorizedAccessException
The caller does not have the required permission.
ArgumentException
path is a zero-length string, contains only white space, or contains one or more invalid characters. You can query for invalid
characters by using the GetInvalidPathChars method.
path is prefixed with, or contains, only a colon character (:).
ArgumentNullException
path is null.
PathTooLongException
The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be
less than 248 characters and file names must be less than 260
characters.
DirectoryNotFoundException
The specified path is invalid (for example, it is on an unmapped drive).
NotSupportedException
path contains a colon character (:) that is not part of a drive label ("C:\").

C# simple exception output

I am making a program of which needs to output any errors that occur but in a timely fashion, it is a program for password recovery.
How can I change the exception text variable which is probably a string to only the actual exception minus all the unneeded stuff.
catch(Exception EX)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("AN ERROR OCCURED IN COPYING CHROMEPASSFILE: " + EX);
Console.ForegroundColor = ConsoleColor.Green;
}
Output:
AN ERROR OCCURED IN COPYING CHROMEPASSFILE: System.IO.IOException: The file 'C:\Users\Anonymous\Desktop\E_TEST\logindata.' already exists.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.File.InternalCopy(String sourceFileName, String destFileName, Boolean overwrite, Boolean checkHost)
at System.IO.File.Copy(String sourceFileName, String destFileName)
at Recover_All_Passwords.Program.Main(String[] args) in C:\Users\Anonymous\Documents\Visual Studio 2015\Projects\Recover_All_Passwords\Recover_All_Passwords\Program.cs:line 27
How can I output only that first line and none of those "At(s)"?
Just noticed the tag for exception says, I quote "An exception is a rarely occurring (exceptional!) condition that requires deviation from the program's normal flow."
Edit
Yes, the stacktrace is very helpful however I had only require the error message because the user will not be interested in anything but what had actually failed.
Rather than using EX, use the Message property on the Exception.
So your code becomes:
Console.WriteLine("AN ERROR OCCURED IN COPYING CHROMEPASSFILE: " + EX.Message);
For future reference, the "at(s)" are the StackTrace and are extremely useful for determining where your application is breaking..

PreMailer "Method Not Found" (AngleSharp.Dom.IElement.RemoveAttribute)

I have this code which inlines CSS using PreMailer;
PreMailer.Net.PreMailer cleanser = new PreMailer.Net.PreMailer(htmlString);
PreMailer.Net.InlineResult result = cleanser.MoveCssInline(ignoreElements: ".ignore");
return result.Html
But I'm getting this exception:
Method not found: 'Void AngleSharp.Dom.IElement.RemoveAttribute(System.String)'
Stack Trace
[MissingMethodException: Method not found: 'Void AngleSharp.Dom.IElement.RemoveAttribute(System.String)'.]
PreMailer.Net.StyleClassApplier.ApplyStyles(IElement domElement, StyleClass clazz) +0
PreMailer.Net.StyleClassApplier.ApplyAllStyles(Dictionary`2 elementDictionary) +125
PreMailer.Net.PreMailer.MoveCssInline(Boolean removeStyleElements, String ignoreElements, String css, Boolean stripIdAndClassAttributes, Boolean removeComments) +241
The answer is probably really obvious but I'm just not clicking on.
AngleSharp: v0.9.9
PreMailer: v1.5.4
There has been an update released for PreMailer. Upgrade to 1.5.5 to resolve this issue! No rollback for AngleSharp required!

Specified cast is not valid. error shows in window server 2008 r2

I made a application in asp.net c# using linq and oracle database.This application is working fine on Widows 7 32 bit local host.But When I deployed this application in windows server 2008 r2.It gives a following error.Guide me what is the following error.How Can I check this error on deployment server and How can I resolved this error
Specified cast is not valid. Description: An unhandled exception
occurred during the execution of the current web request. Please
review the stack trace for more information about the error and where
it originated in the code.
Exception Details: System.InvalidCastException: Specified cast is not
valid.
Source Error:
An unhandled exception was generated during the execution of the
current web request. Information regarding the origin and location of
the exception can be identified using the exception stack trace below.
Stack Trace:
[InvalidCastException: Specified cast is not valid.]
System.Data.UnboxT`1.ValueField(Object value) +54
sis.<>c__DisplayClass55.b__0(DataRow r) +38
System.Linq.WhereEnumerableIterator`1.MoveNext() +156
System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +165
System.Linq.d__81`1.MoveNext() +472
System.Linq.Enumerable.Count(IEnumerable`1 source) +267
sis.regreport.Page_Load(Object sender, EventArgs e) +5015
System.Web.UI.Control.LoadRecursive() +71
System.Web.UI.Page.ProcessRequestMain(Boolean
includeStagesBeforeAsyncPoint, Boolean
includeStagesAfterAsyncPoint) +3178
var vcolM = dt.AsEnumerable()
.Where(r => r.Field<string>("MAJ") == (string)vprglist
&& r.Field<string>("SPEC") == (string)vspecourse
&& r.Field<string>("L_ABR_CODE") == (string)genderEng[1]
&& r.Field<string>("reg") == (string)drRegion["reg"]
&& r.Field<decimal>("year") == syrcnt)
.Sum(r => Convert.ToInt32(r["strength"]));
All linq like above working fine in local pc.But giving error in windows server 2008.Where syrcnt is int.
The most likely cause of the InvalidCastException is the r.Field<string>("MAJ") , r.Field<decimal>("year") line. The Field<T> extension method will throw an InvalidCastException in the case where the actual type of the data doesn't match the type which was passed to Field<T>.
OR
lies in here Convert.ToInt32(r["strength"]), the strength might not be getting proper type
Honestly, I think you issues lies in the line r.Field<decimal>("year"). I may be wrong as there is not much information about the datatype of your variable syrcnt
Hence giving you the exception System.InvalidCastException: Specified cast is not valid

RedirectFromPage do not work with special chars in the ReturnUrl

I am working on a form based auth module for MS SQL reporting Services which is described here:
So far so good, but I run into this problem.
The URL I call redirect to the login page to authenticate and then the page redirect back to the return url.
URL sample call:
http://thor/ReportServer/Pages/ReportViewer.aspx?%2fSampleUserReport&rs:Command=Render
This line crash:
FormsAuthentication.RedirectFromLoginPage(m_username, false);
Exception:
System.Web.HttpException: Der für die Umleitung von Anforderungen angegebene Rückgabe-URL ist ungültig.
bei System.Web.Security.FormsAuthentication.GetReturnUrl(Boolean useDefaultIfAbsent)
bei System.Web.Security.FormsAuthentication.GetRedirectUrl(String userName, Boolean createPersistentCookie)
bei TQsoft.Windows.Products.SSRS.Authentication.Logon.ServerBtnLogon_Click(Object sender, EventArgs e)
So after investigating and debugging I found out if I skip &rs:Command=Render it works.
So the only special char in there I can imagine making problem is the : char.
Any idea how to make it work since reporting services are working with those in the navigation a lot.
UPDATE
It turns out that I have to redirect myself like this:
Response.Redirect(Request.QueryString["ReturnUrl"].Replace(":","%3A"));
Context.ApplicationInstance.CompleteRequest();
But this throws another exception:
System.Threading.ThreadAbortException: Der Thread wurde abgebrochen.
bei System.Threading.Thread.AbortInternal()
bei System.Threading.Thread.Abort(Object stateInfo)
bei System.Web.HttpResponse.End()
bei System.Web.HttpResponse.Redirect(String url, Boolean endResponse)
bei System.Web.HttpResponse.Redirect(String url)
bei TQsoft.Windows.Products.SSRS.Authentication.Logon.ServerBtnLogon_Click(Object sender, EventArgs e)
I am really a rookie on asp.net, but start to hate it while RoR wins atm to me.
I had this issue before but with hebrew char that I wanted to pass using URL link.
Try to convert the char using %3A.
Edit
I use Google translate to convert those chars: just write the chars/String, hit translate and copy the relevant part in the URL.
Response.Redirect(HttpServerUtility.UrlEncode(Request.QueryString["ReturnUrl"]));
does this work for you, replacing characters such as a question mark (?), ampersand (&), slash mark (/), and spaces.
http://msdn.microsoft.com/it-it/library/zttxte6w.aspx

Categories

Resources