StackTrace class methods not working in release mode - c#

below is my piece of code which i am using to log my error details.
StackTrace sTrace = new StackTrace(true);
string functionname = Environment.NewLine + " MethodName - " + sTrace.GetFrame(1).GetMethod().Name;
string classname = Environment.NewLine + " File Path - " + sTrace.GetFrame(1).GetFileName() + Environment.NewLine + " Line No. - " + sTrace.GetFrame(1).GetFileLineNumber() + Environment.NewLine + " ClassName - " + sTrace.GetFrame(1).GetMethod().ReflectedType.Name + Environment.NewLine + " DateTime - " + DateTime.Now.ToString();
WriteLine(string.Concat("ERROR: ", errMsg, classname, functionname,
Environment.NewLine));
this works perfect in debug mode, but in relese mode, i am getting function name and class name as blank, Line Number (sTrace.GetFrame(1).GetFileLineNumber()) as 0.
is there any other best way to get function name, class name, and line number from where error originated.
thanks in advance.

StackTrace information will be most informative with Debug build configurations. By default, Debug builds include debug symbols, while Release builds do not. The debug symbols contain most of the file, method name, line number, and column information used in constructing StackFrame and StackTrace objects.
Actually, Release mode optimize code and dose not have Program DataBase file(.pdb)
In Release mode
Property -> Build -> Define Debug Constant (Check it)
Property -> Build -> Optmize Code (UnCheck it)

Here is the screenshot - http://imgur.com/Oet3SED
Properties-->Build-->Release conf-->Adv->Debug infor ( FULL).

You can get it if you are using .pdb files in your application. Please check this
You can enable it : Properties > Linker > Debugging > Generate Debug Info = "Yes"
A Note on pdb files

Related

Cannot call cmd.exe from any application when it is called via the MIM .dll

What I currently have is a MIM .dll extension for the metaverse that needs to call the command line to run some console commands. These console commands are for a web tool call GAM that will create G-Suite users. I have a test console app built-in .NET Framework 4.7.2 that works just fine. When running the code with my .dll it seems to process just fine, even returns a positive exit code of 0, but does not perform the function in cmd that is expected. The .dll is in .NET Framework 4.5. The code block is the same for both applications:
using (Process gamProcess = new Process())
{
gamProcess.StartInfo.UseShellExecute = false;
gamProcess.StartInfo.RedirectStandardOutput = true;
gamProcess.StartInfo.FileName = #"C:\Windows\System32\cmd.exe";
gamProcess.StartInfo.CreateNoWindow = true;
gamProcess.StartInfo.Arguments = "/c gam create user " + username + " firstname " + firstname + " lastname " + lastname + " password " + pass;
gamProcess.Start();
gamProcess.WaitForExit();
}
If I call this block of code directly from the .dll, it will act as if it performs the action but nothing happens. If I call this code from the standalone application, it works just fine. I have even attempted to just call this application from the .dll and pass arguments directly to it. This will work if I set the arguments in Visual Studio but it will not work if I call the application from the .dll. I'm at a loss here, I cannot figure out what is the difference between running from my extension and running from the application.
Another side note, I built an even more simplistic console application that just writes to a file. I was able to call this application from the .dll, and it works just fine. It is only the commands above that the .dll seems to not want to process correctly.
I managed to fix the above code. I did two things at the same time, so I'm not sure which was the key to this issue but it is working flawlessly now. I changed the /c in the code to a /C uppercase. The code now looks as follows:
using (Process gamProcess = new Process())
{
gamProcess.StartInfo.UseShellExecute = false;
gamProcess.StartInfo.RedirectStandardOutput = true;
gamProcess.StartInfo.FileName = #"C:\Windows\System32\cmd.exe";
gamProcess.StartInfo.CreateNoWindow = true;
gamProcess.StartInfo.Arguments = "/C gam create user " + username + " firstname " + firstname + " lastname " + lastname + " password " + pass;
gamProcess.Start();
gamProcess.WaitForExit();
}
The second action I performed was a restart of the dev server I was working on. I'm not sure which worked, especially since I was running a lowercase /c in my console app, but the code is working now. Thank you all who viewed this question.

C# Process.Start Argument with a dash fails to executr

I am having some trouble trying to work my way through some C# that I'm just not comfortable with. My issue appears to stem from a dash/hyphen in one of my parameters being passed to Process.Start(). In the below code the argument list is built from data in the database. The issue occurs when sRecipient has a dash. For example Bank-Name vs BankName. Unfortunately, I can't remove the dash because it is the name of a public key provided by the bank.
sGPGParms = " -e ";
if (sUseGPGASCIIArmor.ToUpper() == "Y")
{
sGPGParms += "-a ";
}
sGPGParms += "-r \"" + sRecipient + "\" \"" + sDestinationDir + sFileName + "\"";
The next section of code is where things seem to fail. The program is using Process.Start() to pass the path and the parameters. The program does not fall into the fail condition and says that the file created successfully but it doesn't do anything. This code worked earlier today before the bank provided a new encryption key with a dash in the name. That dash is literally the only change. This code has worked since 2008 so I have isolated it to the arguments parameter in Process.Start() and how the dash is impacting things as the culprit.
Process myCmd;
if ((myCmd = Process.Start(Path, sGPGParms)) == null)
{
LogEvent(sServerLogPath, "ERROR: GPG.exe failed to start", sUserName);
SqlContext.Pipe.Send("GPG.exe failed to start");
}
else
{
LogEvent(sServerLogPath, "Bank file created successfully", sUserName);
SqlContext.Pipe.Send("Bann file created successfully");
}
As a side note, I can run the full command copied from the logging and it works. It only fails when passed through Process.Start().
This is the command that works manually but fails when passed through Process.Start() with no public key
"C:\Program Files (x86)\GNU\GnuPG\gpg2.exe" -e -r "Bank-Name" "c:\public\BankPay.txt"
Any ideas why this dash is causing an issue?
UPDATE: Working through some of the suggestions in the comments I see that I am getting an exit code of 2 with the error public key not found. The key exists because I can run the command manually and can see it when I --list-keys

DateTime not appearing as per system format c# windows services

When we use System.DateTime.Now it displays the DateTime as per what is set in our system (if I am not wrong).
Like currently my system DateTime settings are as below :
Now I created a simple Console Application with a small snippet :
Console.WriteLine(System.DateTime.Now);
Console.WriteLine(System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern+" "+System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortTimePattern);
System.IO.File.WriteAllText("E:\\perls.txt", System.DateTime.Now.ToString() + "\r\n" + System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern + " " + System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortTimePattern);
The output both console and text is :
Now same thing I am doing via windows service and Logging some information in a Text File and even creating the same file as created in above sample:
(I have a simple Log class which logs the info i am not getting into its details)
So code is something like below:
Log.Info("System Date Time : " + System.DateTime.Now);
Log.Info("Date Time format : " + System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern + " " + System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortTimePattern);
System.IO.File.WriteAllText("E:\\perls-service.txt", System.DateTime.Now.ToString() + "\r\n" + System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern + " " + System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortTimePattern);
Now in my Log File (a text file) and the text file which I created gives following output:
Both samples are executed in the same system then why is this difference?
Where am I wrong?
Or this problem is in my system only.
You must be running into the issue described here
https://social.msdn.microsoft.com/Forums/vstudio/en-US/8fbca78b-5078-4a12-8abb-4051076febbb/c-windows-service-culture-info-problem
Your Windows Service most likely runs under one of the service accounts with the culture defined in the registry.
See if you updating the registry settings below fixes the problem.
[HKEY_USERS\.DEFAULT\Control Panel\International]
"Locale"="00000409"
"LocaleName"="en-US"

HttpListenerRequest properties no longer available since converting project to VS2010

I have a project created using Visual Studio 2008 targeting .NET 3.5 which makes use of the HttpListenerRequest class. As part of a statistics collection mechanism, all properties of the class are written to a file.
I recently attempted to convert the project from a VS2008 solution to a VS2010 solution and had no errors at all during the conversion, but as soon as I attempt to build the project the compiler claims that it can't find "HttpListenerRequest.ServiceName" and "HttpListenerRequest.TransportContext".
On both of these project the target framework is .NET Framework 3.5, I have compared the DLL version numbers being referenced and everything seems identical.
I decided to examine the HttpListenerRequest classes metadata in both version of visual studio to discover that while 2010 has no reference to ServiceName and TransportContext as expected, VS2008 shows both properties, but neither have the summary description.
Then I created a project targeting .NET 4 in VS2010 which allows me to reference both the above properties.
I really need to continue to target .NET 3.5, do you know of anyway I can make this work without changing the code to exclude so much functionality?
EDIT: As requested, this is the code:
void Log(System.Net.HttpListenerContext context)
{
string line =
DateTime.Now.ToString() + "|" +
context.Request.HttpMethod + "|" +
context.Request.RawUrl + "|" +
context.Request.Url.ToString() + "|" +
context.Request.RemoteEndPoint.ToString() + "|" +
(context.Request.UrlReferrer == null ? "None" : context.Request.UrlReferrer.ToString()) + "|" +
(context.Request.ServiceName == null ? "None" : context.Request.ServiceName) + "|" + // Error Here on ServiceName
context.Request.UserHostName + "|" +
context.Request.UserAgent + "|" +
context.Request.TransportContext.ToString() + "|" + // Error here on TransportContext
context.Request.ProtocolVersion + "|" +
context.Request.ContentLength64.ToString();
WriteToFile(line);
}
So I figured it out:
Both versions of Visual Studio only supplied me with the following version info for System.dll:
v2.0.50727
But after going to the windows directory and examining the files, there is a version difference.
The one which does not include the properties is version v2.0.50727.3053, while version v2.0.50727.3634 includes them.
I assume the problem is that I have had Windows updates disabled since installing Windows.

Why does StringBuilder.AppendLine not add a new line with some strings?

I'm trying to use stringbuilder to create a body of string to be used in a text (not HTML) email. However some lines (where i include dynamic data, a new line is not added, but in some the newline works as intended.
Is there something basic i'm missing when using the stringbuilder class or is there some more fundamental process that should be happening?
in the below code:
sbUser.AppendLine("Please find below confirmation of your registration details. If any of these details are incorrect, please email someone#somewhere.com");
sbUser.AppendLine();
sbUser.AppendLine("Selected event : " + ContentPage.FetchByID(int.Parse(ddlEvent.SelectedValue)).PageTitle);
sbUser.AppendLine("Date of event : " + thisEvent.EventStartDate.ToString("dd MMM yyyy"));
sbUser.AppendLine("==============================================================");
sbUser.AppendLine();
(ContentPage and thisEvent are custom classes built using Subsonic(v2). PageTitle is an output type of string)
is get this as an output:
Please find below confirmation of your registration details. If any of these details are incorrect, please email someone#somewhere.com
Selected event : My Event Date of event : 16 Sept 2012 ==============================================================
as you can see, everything after the 3rd line in the code makes everything go on to one line.
however, further down the code i use:
sbRR.AppendLine("First name : " + txtFirstname.Text.Trim());
sbRR.AppendLine("Surname : " + txtSurname.Text.Trim());
etc,
and all these appear on seperate lines correctly. I can't see why this is happening.
the email is composed as such
mailMessage.Body = sbUser.ToString() + sbRR.ToString();
adding the following code:
sbUser.AppendLine("Selected event : " + ContentPage.FetchByID(int.Parse(ddlEvent.SelectedValue)).PageTitle + Environment.NewLine);
sbUser.AppendLine("Date of event : " + thisEvent.EventStartDate.ToString("dd MMM yyyy") + Environment.NewLine);
produces the following output:
Selected event : My Event
Date of event : 16 Sept 2012
==============================================================
which works i suppose, except it's added 2 newlines (the AppendLine and the Environment.NewLine). it seems that pulling the data directly straight from the database into a stringbuilder seems to be messing with the line ending. Even if I add text after the database pull, it still stays on one line.
UPDATE
doing
StringBuilder.Append("blah"+Environment.NewLine)
produces the correct result, however i'm still not understanding why that works and .AppendLine("blah"+<database content>) doesn't work.
I know the question is old and has been marked as answered, but I thought I'd add this here in case anyone else comes across this as it's the first hit on Google for StringBuilder.AppendLine() not working.
I had the same problem and it turned out to be an Outlook issue. Outlook re-formats text based emails by removing extra line breaks. You can click "We removed extra line breaks in this message -> Restore line breaks" in the header of the individual email, or change the setting that does this nasty little trick "Options->Mail->Message Format->Remove extra line breaks in plain text messages"
The workaround (since you can't control the settings on every potential email target) I found here Newsletter Formatting And The Remove Extra Line Breaks Issue.
Basically, if you add two white space characters to the beginning of each line, Outlook won't reformat the email.
Here's an extension method to help (method name is a bit verbose so change to your liking :))
namespace System.Text
{
public static class StringBuilderExtensions
{
public static void AppendLineWithTwoWhiteSpacePrefix(this StringBuilder sb, string value)
{
sb.AppendFormat("{0}{1}{2}", " ", value, Environment.NewLine);
}
public static void AppendLineWithTwoWhiteSpacePrefix(this StringBuilder sb)
{
sb.AppendFormat("{0}{1}", " ", Environment.NewLine);
}
}
}
Instead of
sbUser.AppendLine();
Try using
sbUser.Append(Environment.NewLine);
No idea why this works...
use Environment.NewLine
sbUser.AppendLine("Please find below confirmation of your registration details. If any of these details are incorrect, please email someone#somewhere.com");
sbUser.AppendLine(Environment.NewLine);
sbUser.AppendLine("Selected event : " + ContentPage.FetchByID(int.Parse(ddlEvent.SelectedValue)).PageTitle);
sbUser.AppendLine("Date of event : " + thisEvent.EventStartDate.ToString("dd MMM yyyy"));
sbUser.AppendLine("==============================================================");
sbUser.AppendLine(Environment.NewLine);
use Environment.NewLine after each line or where you want new line
eg:-
sbUser.AppendLine("Please find below confirmation of your registration details. If any of these details are incorrect, please email someone#somewhere.com" + Environment.NewLine);
sbUser.AppendLine("Selected event : " + ContentPage.FetchByID(int.Parse(ddlEvent.SelectedValue)).PageTitle);
Windows 10 Insider preview Build 15007. The Default Line Terminator and the Environment.NewLine are both "\n". To use "\r\n" I had to create a string constant and use it instead.
First
sbUser.Appendline();
Second
sbUser.Append("texto loco ");
Voila!
=)

Categories

Resources