c# How to get a meaninful name of website or executable - c#

We have an internal error reporting system (inside our functions dll) and one of the info pieces we send is the name of the application that caused it.
Current code:
string applicationname= Assembly.GetCallingAssembly().GetName().Name;
The problem is when the error is send from one of our websites as it sends application names like "App_Code.6p_c415d".
One possible way was determining if the app is an executable or a website dinamically (how do we do that?) and in the case of being a website get the folder containing it or so...
But if you have better ways we are open to any idea ^^

You can use a key in the AppSettings to identify your application.

We ended up creating the following function and it works fine:
public static string getApplicationName()
{
return string.IsNullOrEmpty(HttpRuntime.AppDomainAppId)?
Assembly.GetEntryAssembly().GetName().Name :
new DirectoryInfo(HttpContext.Current.Server.MapPath("")).Name;
}

Related

How to allow external process to launch my ASP.NET exe file

UPDATED QUESTION
I just deployed a self-contained solution to test my web app in an offline computer. When I go to the destination folder then double click on the executable I see the terminal window displaying that the ports http://locahost:5000 is open and https://localhost:5001 are open and ready to go. I then open a website and navigate to this url and sure enough I see my website working.
That takes care of part one.
Part 2 is launching my WebServer.exe from another application (called ProcessManager.exe)
This is where I am having issues...
Even though I am seeing the WebServer.exe application launching, I can't see any of the websites when I type: https://localhost:5001/SiteA. It tells me that it couldn't find the location of said url.
I go to my WebServer.exe application to see if its spitting out an error in the logs and I notice that the Content root path is wrong! It's telling me that it is looking for the contents of wwwroot folder in the wrong folder level.
Its saying Content root path:
E:\Projects\MyFirstProject\Deployments
I close everything and then I navigate to where my self-contained asp.net application is located and run WebServer.exe. Sure enough that one is displaying that it is pointing to the correct content root path which is:
E:\Projects\MyFirstProject\Deployments\WebServer
Another thing I notice when I launched my WebServer.exe from my ProcessManager.exe is that the WebServer.exe window also gives me this extra text at the very top:
Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[0]
User profile is available. Using 'C:\Users\me\AppData\Local\ASP.NET\DataProtection-Keys' as key repository and Windows DPAPI to encrypt keys at rest.
I did some minor research, and it turns out that my web application is not granting my ProcessManager.exe permissions of any kind. Or something to that effect.
This is how I am launchig my WebServer.exe from my ProcessManager project.
private const string WebServerPath = #"E:/Projects/MyFirstProject/Deployments/WebServer/WebServer.exe";
public ExternalProcess WebServerProcess
{
get { return _webServerProcess; }
}
private ExternalProcess _webServerProcess;
// constructor
public ProcessManager()
{
_webServerProcess = new ExternalProcess(WebServerPath);
}
/// <summary>
/// Start the web server
/// Gets called in MainWindowViewModel.cs
/// </summary>
public void StartWebServer()
{
string cmdLine = "";
_webServerProcess.StartProcess(cmdLine);
}
As I mentioned before my ASP.NET application launches without any problems but it does give me that issue that I mentioned above... What am I doing wrong? Can anyone help me understand what the underlying issue is?
many thanks in advance.

Why does File.ReadAllText in a service reset its directory to "C:\Windows\System32"?

I have created a service that acts also an HTTPServer, I have written html files and stored them in a folder in the same working directory, (say
E:\My_project\Pages\home.html )
I have a Library.cs file in E:\My_project\ . In my code I have this line,
string content = File.ReadAllText("Pages/home.html");
While I try to read this line, I get the following error,
mscorlib: Could not find a part of the path 'C:\WINDOWS\system32\Pages\home.html'
Earlier, it worked for some other pages, when I hardcoded the home page alone and read other pages like 404.html from those directory. Now that I have added the home page also to the pages folder, I get this error.
My Question is how to overcome this error and why does windows go to C:\Windows\System32 rather than looking in the same directory as the file.
NOTE: Yes, I have used threading, the service uses multiple threads.
Code:
Library.cs
public static List<Route> GetRoutes() {
List<Route> routes = new List<Route>();
string content = File.ReadAllText("Pages/home.html");
routes.Add(new Route
{
Name = "Hello Handler",
UrlRegex = #"^/$",
Method = "GET",
Callable = (HttpRequest request) =>
{
return HttpBuilder.GetHome();
}
});
return routes;
}
Service applications are like regular Windows applications in their understanding of "current directory". When you want to access a file and pass a relative name, your application tries to find the file by searching in:
1. The directory where an application is loaded.
2. The current directory.
3. The Windows system directory.
See more details here
Now, the current directory is something specific for every process, it can be configured on startup via parameters, or at runtime using Directory.SetWorkingDirectory link.
In you case, you need to set your working directory to where you web pages are.

Advantage Error 6082

I'm creating a windows service. This service has to read data from an Advantage Database once a day.
I copied the Advantage database on my computer and it works fine but when I try the service on the server I have the following error :
"AdsException : Error 6082: Error loading the Advantage Local Server library."
According to the doc (link) I have to put the ADSLOC32.DLL in \WINDOWS\SYSTEM directory.
I try that but it does not work.
Any ideas?
EDIT : I created a console application that executes exactly the same code as my windows service, and it works exactly as it should. It seems that the problem is from my service, but I don't know what part of my service is wrong...
EDIT 2 : I checked with the process monitor and my service doesn't try to load adsloc32.dll, it tries to load adsloc64.dll. I did not found an adsloc64.dll file so I make a copy of adsloc32.dll to my application directory and named it adsloc64.dll but it didn't work.
I found the solution.
I used Process Monitor from Windows Sysinternals to know from where the program tries to load the dll files.
And it wasn't trying to load adsloc32.dll, it was loading adsloc64.dll.
I just put the adsloc64.dll file to my application directory and it works now.
Try putting adsloc32.dll to the same directory as your application. Maybe there are some problems with rights

Append to an online text log file from my offline C# app

I'm looking for customer feedback regarding one or more of my apps (optional, and they would be notified), so I'd like to send some text to be appended to an online log file from my offline C# Winforms app.
If it makes a difference, the server is Linux based, and I don't mind if the public can access it too, so no need to worry about encryption or anything (no personal details or anything like that would be stored in them).
What would be the C# code required to do such a thing? (Pretend the website is: http://www.website.com/logfile.txt). Would I have to read the file wholesale, and write it back wholesale, or is there a more efficient 'append' operation I could use?
EDIT: Looks to be harder than I imagined. If I have to make a simple PHP script to help with this task, so be it, though code for that would be appreciated as well if that's the case.
You have a couple options.
First, you could check out a service like loggly which is an online log file. You would have a personal API key to post data to from your application.
If you don't want to do that, you could write your own API that has a simple Post with a string parameter. It would then be responsible for opening the file, adding the text and saving it. The Winform could just fire and forget, knowing that the API can handle it.
In C#, you could use either RestSharp or the HttpClient to send the data to the API.
I think the problem you're going to run into, is having the Winform app save the file. If it was a local file, you can just append to a file (without reading the whole thin into memory.) But on a remote machine, you'd first have to download the entire file. The next problem would be making sure that the Winform app can save the file. Without something like an API call, you could run into a lot of issues.
This may not be robust enough for your needs, but this my solution.
The easiest way I can think of doing this is to have your C# application send the text to a web script. Since you said you didn't care if the data was encrypted I thought why not just pass the text as a get parameter to a PHP script.
This example is very simplistic; you may want to add other checks to meet your needs:
The C# code would look like:
string loggerUrl = "http://www.YourDomainExample.com/Logger.php?text=";
string textToLog = WebUtility.UrlEncode("This text came from my C# desktop application");
HttpWebRequest myWebRequest = (HttpWebRequest)HttpWebRequest.Create(loggerUrl + textToLog);
HttpWebResponse myWebResponse = (HttpWebResponse)myWebRequest.GetResponse();
myWebResponse.Close();
The PHP script residing on your web server would look like:
<?php
$text = htmlspecialchars($_GET["text"]);
$log = "log.txt";
$fh = fopen($log, 'a') or die("can't open file"); // Open log in append mode
$textToWrite = "$text\n"; //Write each comment on a line
fwrite($fh, $textToWrite);
fclose($fh);
?>
By doing it this way, basically anything that can call the url can append text to your log. So your logger could be part of a desktop application, run on a mobile phone or a web application etc.
To test that your PHP script is working correctly, you can use your Web Browser as a client and just go to http://www.YourDomainExample.com/Logger.php?text=Test from webbrowser and check for log.txt on your web server
If you want to log into a remote destination, I see two solutions. Both are using log4net:
Solution 1:
You can set up log4net to log into a database. You can see here for the configuration.
Solution 2:
You can derive your logging class from AppenderSkeleton and configure the behaviour to log into anything you want.
internal class MyAppender : AppenderSkeleton
{
/// <summary>
/// Subclasses of <see cref="T:log4net.Appender.AppenderSkeleton"/> should implement this method
/// to perform actual logging.
/// </summary>
/// <param name="loggingEvent">The event to append.</param>
protected override void Append(LoggingEvent loggingEvent)
{
/* Here you can do whatever you want with your loggingEvent */
}
}

ASP .NET C# get all text from a file in the web path

I'm trying to open a file that includes some data in a web directory that my C# is running. Basically just turns it into a string. I tried doing the following...
string email = File.ReadAllText("/orderforms/email_templates/file_to_include.txt");
I'm not sure if that is the correct method, but it seems there is a pathing problem, the whole path will change depending what web server it is running on.
This is the directory setup...
/Classes/Page.ascx.cs (the page that tries to read the text from the
file)
/orderforms/<one of multiple pages execute the above class here or in a sub directory
/orderforms/email_templates/file_to_include.txt
/orderforms/email_templates/file_to_include2.txt
What path and function should I use to read all of the contents of the file to a string?
Thanks
Try this:
string email = File.ReadAllText(Server.MapPath("~/orderforms/email_templates/file_to_include.txt"))
You need to use Server.MapPath:
http://msdn.microsoft.com/en-us/library/ie/ms524632(v=vs.90).aspx

Categories