How to get the current project name in C# code? - c#

I want to send an email to myself when an exception is thrown. Using StackFrame object, I am able to get File Name, Class Name and even class method that throw the Exception, but I also need to know the project name as many of my ASP.NET project has the same file name, class name and method.
This is my code:
public static string JndGetEmailTextForDebuggingExceptionError(this Exception Ex)
{
StackFrame sf = Ex.JndGetStackFrame();
string OutputHTML = "<i><b><u>For Developer Use Only: </u></b></i>" + "<br>" +
"<br>" +
"Project Name: " + HttpContext.Current.ApplicationInstance.GetType().Assembly.GetName().Name + "<br>" + //Under discussion
"File Name: " + sf.GetFileName() + "<br>" +
"Class Name: " + sf.GetMethod().DeclaringType + "<br>" +
"Method Name: " + sf.GetMethod() + "<br>" +
"Line Number: " + sf.GetFileLineNumber() + "<br>" +
"Line Column: " + sf.GetFileColumnNumber() + "<br>" +
"Error Message: " + Ex.Message + "<br>" +
"Inner Message : " + Ex.InnerException.Message + "<br>";
return OutputHTML;
}
Thanks ALL.

You can use Assembly.GetCallingAssembly if you have your logging code in a separate library assembly, and call directly from your ASP.NET assembly to your library, and you mark the method so that it won't be inlined:
[MethodImpl(MethodImplOptions.NoInlining)]
public static string JndGetEmailTextForDebuggingExceptionError(this Exception Ex)
{
StackFrame sf = Ex.JndGetStackFrame();
string OutputHTML = "<i><b><u>For Developer Use Only: </u></b></i>" + "<br>" +
"<br>" +
"Project Name: " + Assembly.GetCallingAssembly().GetName().Name + "<br>" +
"File Name: " + sf.GetFileName() + "<br>" +
"Class Name: " + sf.GetMethod().DeclaringType + "<br>" +
"Method Name: " + sf.GetMethod() + "<br>" +
"Line Number: " + sf.GetFileLineNumber() + "<br>" +
"Line Column: " + sf.GetFileColumnNumber() + "<br>" +
"Error Message: " + Ex.Message + "<br>" +
"Inner Message : " + Ex.InnerException.Message + "<br>";
return OutputHTML;
}
On any entry points in your library that can end up wanting to log the project name, you'd have to record the calling assembly and mark it NoInlining, then pass that around internally.
If you're using .NET 4.5, there's an alternative way to do this: CallerFilePath. It has the same restrictions on entry points, and it returns the source path on your machine instead of the assembly name (which is probably less useful), but it's easier to know that it'll work (because it compiles it, just like optional parameters are compiled in), and it allows inlining:
public static string JndGetEmailTextForDebuggingExceptionError
(this Exception Ex, [CallerFilePath] string filePath = "")
{
StackFrame sf = Ex.JndGetStackFrame();
string OutputHTML = "<i><b><u>For Developer Use Only: </u></b></i>" + "<br><br>" +
"Source File Path: " + filePath + "<br>" +
...

For anyone looking for an ASP.NET Core compatible solution, the following should work;
System.Reflection.Assembly.GetEntryAssembly().GetName().Name
.NET Core API Reference

This ought to be enough
string projectName = Assembly.GetCallingAssembly().GetName().Name;
Edit* If you are running this from another assembly then you should use GetCallingAssembly instead.

You can use
HttpContext.Current.ApplicationInstance.GetType().Assembly.GetName().Name
If this returns App_global.asax...., change it to
HttpContext.Current.ApplicationInstance.GetType().BaseType.Assembly.GetName().Name
If you aren't running in an HTTP request, you will need some way to get ahold of the HttpContext.
This will return different results if you're in a Web Site project (as opposed to Web Application).
You can also use HttpRuntime.AppDomainAppPath to get the physical path on disk to the deployed site; this will work everywhere.

Reflection is the best way to find out product name,company name version like information.
public static string ProductName
{
get
{
AssemblyProductAttribute myProduct =(AssemblyProductAttribute)AssemblyProductAttribute.GetCustomAttribute(Assembly.GetExecutingAssembly(),
typeof(AssemblyProductAttribute));
return myProduct.Product;
}
}
And Another way like get direct project name
string projectName=System.IO.Path.GetFileName(System.Reflection.Assembly.GetExecutingAssembly().Location).ToString();

Just adding my answer here.
For those who work with multiple Dlls in their projects, the correct answer is:
string projectName = Assembly.GetExecutingAssembly().FullName.Split(',')[0];

Related

Running a python script asynchronously from WPF App

I am trying to run a python script asynchronously from my WPF App because the task is time-consuming and running in synchronously causes the UI of the App to become unresponsive. Asynchronously code from the web page is not working, however. I'm working with the code form the link below. Any help is much appreciated.
https://www.codeproject.com/Articles/25983/How-to-Execute-a-Command-in-C
I'm calling the method from the web page with this code snippet:
Click2Input3 = path + #"tensorflow\classifiers\" + name2 + #"\retrained_labels.txt";
Click2Input4 = path + #"tensorflow\classifiers\" + name2 + #"\retrained_graph.pb";
toEx2 = Click2Input + " " + Click2Input2 + " " + input2 + " " + Click2Input3 + " " + Click2Input4 + " " + inputDestination;
textOut.Text = toEx2;
ExecuteCommandSync(toEx2);
textOut.Text = result;
Which in essence just does this:
C:\Users\AppData\Local\Programs\Python\Python35\python.exe C:\Users\Desktop\test\examples\image_retraining\retrain.py --bottleneck_dir=C:\Users\Desktop\test\dif_images\bottlenecks --how_many_training_steps=500 --model_dir=C:\Users\Desktop\test\images\inception --output_graph=C:\Users\Desktop\test\dif_images\retrained_graph.pb --output_labels=C:\Users\Desktop\test\dif_images\retrained_labels.txt --image_dir=C:\Users\Desktop\test\dif_images\star_wars
Have you tried
System.Diagnostics.Process.Start(toEx2);
Are you trying to get the results of the python execution back into WPF?

Passing long querystrings over urls shows page not found error(404)

I have a "error.aspx" page which is there to mail me if any exception is caught. When I open the page manually, mysite.com/error.aspx, the page opens fine but when it is redirected by a catch block with the exception.message and exception.stackTrace as querystrings, I get an error "page not found". Are the querystrings directing the browser to open a different url? It works fine when run on localhost, though.
public void send_error(Exception ex)
{
Response.Redirect("error.aspx?time=" + DateTime.Now.ToString() + "&ex=" + ex.Message + "&st=" + ex.StackTrace.Replace("\n", " "), false);
}
If you check this Article, you will see that the max query length of url string is 2048 symbols for Internet explorer. Probably the url is bigger and because of that you have this problem. One solution is to save the desire message in the session as string and after that retrieve it on other pages.
string errorMessage = DateTime.Now.ToString() + " " + ex.Message + " " + ex.StackTrace.Replace("\n", " ");
Session["__ErrMessage"] = errorMessage;
When you are in other pages you can access this string like this:
string errMessage = "";
if(Session["__ErrMessage"] != null)
errMessage = Session["ErrMessage"].ToString();

Opening a PDF with search parameters just opens the PDF

I was requested to add some searching functionality to an existing system for the collection of PDFs that we have. I know about searching PDFs and opening them with search parameters and in a test application I wrote, it works like a dream. When trying to convert it over to our existing application the PDF opens but without the search terms or the advanced find of Acrobat Reader popping up. Any help would be greatly appreciated!
Here is a snippet of the cs code :
case "PDF":
string searchTerms = SearchWordsTB.Text;
searchTerms = searchTerms.Replace(',', ' ');
launchStr = "OpenPDF('" + e.Row.Cells[9].Text.Replace("\\", "/") + "','" + HttpUtility.UrlEncode(e.Row.Cells[2].Text) + "','" + e.Row.Cells[0].Text + "','" + searchTerms + "')";
break;
We are creating the list of documents on the fly and PDF is one of the options. Assuming I am understanding this correctly, A DataGrid is created with all these clickable rows that will execute a Javascript function when clicked. The Javascript function OpenPDF is shown below:
function OpenPDF(url, filename, ID, searchTerms) {
if (searchTerms.length > 0) {
window.open('FileViewer.aspx?name=' + filename + '&ID=' + ID + '&url=' + url + '#search="' + searchTerms + '"', 'mywindow' + windowCnt, 'width=800,height=600,location=no,resizable=yes');
}
else {
window.open('FileViewer.aspx?name=' + filename + '&ID=' + ID + '&url=' + url, 'mywindow' + windowCnt, 'width=800,height=600,location=no,resizable=yes');
}
windowCnt++;
}
From following the debugging in the CS code, I know that I am properly stripping out the commas in the search terms so that shouldn't be the problem. What currently happens is the PDF file will open up just fine, but the search terms are not being used. I have tried following the debugger through the Javascript (which for me has always been spotty at best) but the breakpoint is never hit. It should also probably be noted that the Javascript function is kept in a separate Javascript File and is not inline in the aspx page. And yes, we are correctly referencing the Javascript file. I will be more than happy to update this post with any extra info that is requested. Thanks in advance for any help!
I was able to achieve the desired results by using the http encode on the launch string as shown below.
launchStr = "OpenFile('" + HttpUtility.UrlEncode(e.Row.Cells[9].Text.Replace("\\", "/") + "#search=\"" + searchTerms + "\"") + "','" + HttpUtility.UrlEncode(e.Row.Cells[2].Text) + "','" + e.Row.Cells[0].Text + "','" + e.Row.Cells[1].Text + "')";
I then used the function to just open the window with the PDF in it. The problem I had was that without the HTTP Encode, the URL was just cutting off the search parameters. I believe this is because the #search="blah" isn't normally recognized as part of a URL and was therefore truncated. If anyone has a better reason, I would love to hear it.

ActiveDirectory Domain Description?

I'm trying to get some details about the current systems Domain.
I've been able to find the Name, DomainMode and ForstMode by using the following code:
System.DirectoryServices.ActiveDirectory.Domain domain = System.DirectoryServices.ActiveDirectory.Domain.GetCurrentDomain();
Console.WriteLine("Domain: " + domain.Name);
Console.WriteLine("Domain Mode: " + domain.DomainMode);
Console.WriteLine("Forest Mode: " + domain.Forest.ForestMode);
However, I cannot seem to figure out how to get the domains description. Screenshot of what I am looking for:
Any suggestions on how I can go about getting this? I don't see any attributes on the Domain object that seems to represent it.
Figured it out. Along with the description I was also able to get the SID using the following code:
using (System.DirectoryServices.ActiveDirectory.Domain domain = System.DirectoryServices.ActiveDirectory.Domain.GetCurrentDomain())
{
using (DirectoryEntry directoryEntry = domain.GetDirectoryEntry())
{
Console.WriteLine("Domain: " + domain.Name);
Console.WriteLine("Domain Mode: " + domain.DomainMode);
Console.WriteLine("Forest Mode: " + domain.Forest.ForestMode);
var sidInBytes = directoryEntry.Properties["objectSID"].Value as byte[];
var sid = new SecurityIdentifier(sidInBytes, 0);
Console.WriteLine("Domain SID: " + sid.ToString());
Console.WriteLine("Description: " + directoryEntry.Properties["description"].Value as string);
}
}

Facebook C# SDK get user language/region

I'm using the Facebook C# SDK. How can I get language of the user, so I can display all messages accordingly without forcing the user to choose his preferred language manually?
If you are developing a web app, then you can use Accept-Language Http header to detect the language
EDIT 1
For winforms application, you can use System.Globalization.CultureInfo.CurrentCulture.Name .
EDIT2
To get the locale using FB REST API :
dynamic fbResult = new Uri("https://graph.facebook.com/AngelaMerkel?access_token=AAABkECTD......").GetDynamicJsonObject();
Console.WriteLine(
fbResult.locale ?? "-" + " > " + //<----
fbResult.location.country + " " + //<----
fbResult.location.city + " " + //<----
fbResult.name + " " +
fbResult.gender + " " +
fbResult.link + " " +
fbResult.updated_time);
You can find info about my extension method GetDynamicJsonObject here

Categories