Mongodb in a portable C# app - c#

I am developing an app that should be portable and I am using mongodb.
By portable I means that my app has a folder with all: dlls, exes, mongo files, mongo databases. Then with this folder I can run my app in any machine.
Then I need to know:
Is there some library that allow me to run the mongod process when the app start and end
the process when the app ends ?
Exists a good practice to do that stuff ?
Advices are welcome and thanks in advance.

According to the MongoDb installation instructions it should be quite simple.
Mongodb starts as a console application waiting for connections, so when your app starts, you should run mongodb hidden. We are always assuming that ALL the mongodb files are in place with your application files and database files are in the correct directory).
When your app terminates, you should kill the process.
Yo should set the correct paths on this example:
//starting the mongod server (when app starts)
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = dir + #"\mongod.exe";
start.WindowStyle = ProcessWindowStyle.Hidden;
start.Arguments = "--dbpath d:\test\mongodb\data";
Process mongod = Process.Start(start);
//stopping the mongod server (when app is closing)
mongod.Kill();
You can see more information about the mongod configuration and running here

I needed to do the same thing and my starting point was Salvador Sarpi's answer. But, I found a couple things that needed to be added to his example.
First, you need to set UseShellExecute to false for the ProcessStartInfo object. Otherwise, you may get a security warning when the process is started asking the user if they want to run it or not. I don't think this is desired.
Second, you need to call Shutdown on the MongoServer object before killing the process. I had an issue where it locked the database and required it to be repaired if I didn't call the Shutdown method before killing the process. See Here for details on repairing
My final code is different, but for this example I used Salvador's code as the base for reference.
//starting the mongod server (when app starts)
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = dir + #"\mongod.exe";
start.WindowStyle = ProcessWindowStyle.Hidden;
// set UseShellExecute to false
start.UseShellExecute = false;
//#"" prevents need for backslashes
start.Arguments = #"--dbpath d:\test\mongodb\data";
Process mongod = Process.Start(start);
// Mongo CSharp Driver Code (see Mongo docs)
MongoClient client = new MongoClient();
MongoServer server = client.GetServer();
MongoDatabase database = server.GetDatabase("Database_Name_Here");
// Doing awesome stuff here ...
// Shutdown Server when done.
server.Shutdown();
//stopping the mongod server (when app is closing)
mongod.Kill();

Related

Start Node.js server from a C# Application

A requirement has arisen that I need to start a Node.js server from a C# application, this is as simple as running a server.js script within the Node.js console. However, I'm not entirely certain how exactly to achieve that.
Here's what I've looked into so far:
In the Node.js installation, there's a file called C:\Program Files (x86)\nodejs\nodevars.bat, this is the command prompt window for Node.js. To start the server, I could possibly be using the following steps:
Execute the nodevars.bat file.
SendKeys to the new process console window to start the server.
This approach feels a bit fragile. There's no guarantee that the target user will have their Node.js installation in the same place, also sending keys to a process may not be an ideal solution.
Another method could be:
Write a batch file that executes nodevars.bat.
Execute the batch file from the C# application.
This seems like a better approach. However, the only problem here is that the nodevars.bat opens in a new console window.
So to the question(s), is there a way I can start a node.js server script using functionality built into the node.js installation? Perhaps sending arguments to the node.exe?
If it is to serve multiple users, i.e. as a server, then you can use the os-service package, and install a Windows service. You can then start and stop the service using the standard API.
If you are to start the server as a "single purpose" server, i.e. to serve only the current user, then os-service is the wrong approach. (Typically when using this approach you will specify a unique port for the service to use, which will only be used by your application).
To start a batch file or other Console application, from C#, without showing a console window, use the standard method, but be sure to specify:
ProcessStartInfo psi = new ProcessStartInfo();
psi.UseShellExecute = false; // This is important
psi.CreateNoWindow = true; // This is what hides the command window.
psi.FileName = #"c:\Path\to\your\batchfile.cmd";
psi.Arguments = #"-any -arguments -go Here"; // Probably you will pass the port number here
using(var process = Process.Start(psi)){
// Do something with process if you want.
}
There are a few different ones but I recommend the os-service package.

Start & Stop a Windows Service from another Windows Service

I need to control a Windows service (slave) from another one (master) on the same machine (Windows 7 or Server 2008). It's unable to either start or stop the service. What do I need to do to be control the service? The master service is written in C#
UPDATE:
The master service is meant to be a sort of watchdog - it monitors an HTTP connection to the slave and restarts the slave if the slave is non-responsive (not returning any HTTP data).
You can have the master service create a new process that creates a hidden command window with an argument that causes it to call the windows command and start or stop the service. We use this model all the time at my job, the /C will cause the command window to exit as soon as the service finishes changing state.
System.Diagnostics.Process p = new System.Diagnostics.Process ();
System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo ( "cmd.exe", "/C net [start or stop] [service name]");
psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
p.StartInfo = psi;
P.Start();
You will need to replace the bracketed sections of the command, and sorry if there are any syntax errors I am typing this on my tablet.
The best way to handle windows services is to use System.ServiceProcess namespace. Check it on:
https://ourcodeworld.com/articles/read/363/how-to-start-stop-and-verify-if-a-service-exists-with-c-in-winforms
But you will have some problems trying that because you will need administrator permissions to turn other services off, so you can handle that by following this link (for debug purposes you can open your VS as admin and everything will work):
How do I force my .NET application to run as administrator?

How to start the bat-file at Asp.net web server side?

I need to call a console application to load data into another desktop application on the remote server that located within the corporate domain.
Users will enter the web page and upload data to asp.net web server, which after transformation should call that console application. Users are located remotely and do not have any other access except the web server.
I decided to lower the security web application context and let the asp.net working process to start the console application on the current IIS 6.0 web server
What I have done:
I changed the security account for the application pool for Local System;
I added ASPNET Account and IIS_WPG IIS Process Account to Administrators group;
I added “Allow service to interact with desctop” for “IIS Admin Service” and “World Wide Web Publishing Service” processes and restarted the machine;
I tried to start BAT-file at server side through the test page code-behind, but failed:
protected void btnStart_Click(object sender, EventArgs e)
{
Process process = new Process();
process.StartInfo.FileName = #”C:\run.bat”;
process.StartInfo.UseShellExecute = false;
process.Start();
process.WaitForExit();
}
The error was access denied.
Please help me to find any workable idea how to start the bat-file at web server side.
Thanks
Try setting UseShellExecute to true instead of false. After all, batch files run in a shell - so you need a shell to execute it. (Another option is to run cmd.exe and pass the name of the batch file in as an argument, e.g. "cmd.exe /k c:\run.bat")
You might also want to try creating a simple .NET app which just (say) creates a file with a timestamp in. That way you can test the "can I start another process" bit separately from the "can I get the batch file to work" bit.
Put that particular batch file in your application itself.
string str_Path = Server.MapPath(".") + "\\run.bat";
ProcessStartInfo processInfo = new ProcessStartInfo(str_Path);
processInfo.UseShellExecute = false;
Process batchProcess = new Process();
batchProcess.StartInfo = processInfo;
batchProcess.Start();
Take a look at this example: Run Interactive Command Shell or Batch Files From ASP.NET
It uses little different approach. They suggest running cmd.exe and executing command line by line.

Running Console application from ASP.NET

I want to know how to run my console application from ASP.NET, which is in one solution.
I want to run and stop the application.
On a client machine or on the server ?
if you are thinking client machine there is no way !
anyway this is how you do it on the application's server
Var process = new Process();
process.StartInfo.FileName = "Notepad.exe";//in your case full path with the application name
process.StartInfo.Arguments = " ";//arguments
process.Start();
// Do your magic here
process.Kill();//Dont forget to kill it when you are done
Just start it like you'd start any normal EXE.
var proc = Process.Start(#"C:\myconsole.exe");
You should place the console EXE file at a proper place though.
And you can end it with:
proc.Kill();
...
Note: that starting the process on a single request might not be a good idea. It might be better to start it on another thread and lets it spin so you can response to your users faster.

Can I stop an IIS?

In a .NET windows application to to modify a remote machine config file that is used by an ASP.NET application. However, I keep getting the error:
System.IO.IOException: The process cannot access the file '[file name]' because it is being used by another process.
Now, this may not be the problem, but I'm figuring that if I can stop the IIS, then I can modify the machine config file (without getting the exception), and then I can restart the IIS using this code:
Process proc = new Process();
proc.EnableRaisingEvents = false;
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
proc.StartInfo.FileName = "iisreset";
proc.StartInfo.Arguments = serverName;
try
{
proc.Start();
proc.WaitForExit();
...
1) Is there a way to stop the IIS without restarting it, and 2) Doe this approach to changing the server.config file even make sense?
(note, I am modifying the file with regular expressions search and replace; is this a problem?)
You should be able to do something like this. I don't have windows, so I can't check the exact name of the service, but I think it is "IISADMIN" or "w3svc". Remember this should be the service name and not the display name you see in the service control panel.
ServiceController controller = new ServiceController();
controller.MachineName = "."; // or the remote machine name
controller.ServiceName = "IISADMIN"; // or "w3svc"
string status = controller.Status.ToString();
// Stop the service
controller.Stop();
// Start the service
controller.Start();
You can also use
net stop w3svc
or
net stop IISADMIN
from the commandline or in your process in your code
Strange. A .config file should not be locked exclusively.
But to answer your question, you can also use the net command for this:
net stop w3svc
to stop the www service, and
net start w3svc
to start it again.
You can also do this programmatically as described by #monkeyp
Note that I would advice against this and first try to determine (and resolve) the cause of the lock as described by #RichardOD.
Using System.Diagnostics;
//to stop ISS
ProcessStartInfo startInfo = new ProcessStartInfo("iisreset.exe", " /stop");
System.Diagnostics.Process.Start(startInfo);
//to start ISS
ProcessStartInfo stopInfo = new ProcessStartInfo("iisreset.exe", " /start");
System.Diagnostics.Process.Start(stopInfo);
You can use the IISRESET /STOP command.
If you type IISRESET /? you will get a list of other available options.
[Edit: Pass the "/STOP" switch as the arguments property on the process' startinfo object.]
Should be "iisreset /STOP" to stop the services, then "iisreset /START" to restart them.
Use a tool like wholockme or unlocker to find the root cause of the locking.
Update- another option is to use Process Explorer (thanks fretje)- this is a good option as lots of developers have this utility on their PC.
You can often just recycle or stop/start the Application Pool IIS is running, rather than restarting IIS altogether.

Categories

Resources