Open exe as service without "Interactive Service Detection" message in window 7 - windows-services

I have a simple application that watches a folder for any changes as following:
private void Form1_Load(object sender, EventArgs e)
> {
> FileSystemWatcher w = new FileSystemWatcher();
> w.Path = #"C:\temp";
> w.Changed += new FileSystemEventHandler(OnChanged);
> w.Created += new FileSystemEventHandler(OnChanged);
> w.Deleted += new FileSystemEventHandler(OnChanged);
> w.Renamed += new RenamedEventHandler(OnChanged);
> // Begin watching.
> w.EnableRaisingEvents = true;
}
// Define the event handlers.
private static void OnChanged(object source, FileSystemEventArgs e)
{
// Specify what is done when a file is changed, created, or deleted.
MessageBox.Show("File: " + e.FullPath + " " + e.ChangeType + Path.GetFileName(e.FullPath));
}
I added the same as service from the command prompt as
sc create <service name> binPath= <path of the exe file>
This added the exe in the services and also made the entries in Registry. But when I tried to start the service as
sc start <service name>
it showed up the "Interactive Service Detection" message.
I want to avoid this message from popping up and start the service.
I also need this to be done in c# but if anyone has any idea about doing it in cmd I can add it as a batch file and execute the same.
EDIT I
As #Seva suggested I created a service that calls the exe that I wish. I wrote the following code to start the exe on start of the service:
protected override void OnStart(string[] args)
{
base.OnStart(args);
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.RunWorkerAsync();
}
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
p.StartInfo.CreateNoWindow = false;
p.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
p.StartInfo.WorkingDirectory = #"<my exe path>";
p.StartInfo.FileName = "<myexe.exe>";
p.StartInfo.Arguments = #"<my exe path>";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.Start();
p.WaitForExit();
base.Stop();
}
I installed the service successfully but is not starting the exe on starting.
EDIT II
The exe started. The service's property had to be configured to allow service interaction with desktop, but then again the "Interactive service detection" message is coming up.

You will have to rearchitecture your windows service into two parts -- a GUI-less service process and a separate UI app that runs on user desktop. There are many ways service can communicate with UI app. These SO questions will get you started:
GUI and windows service communication
Communication between windows service and desktop app
There is no other way around. BTW, your existing approach is already broken -- for Non-admin users and for remote desktop sessions -- they won't see UI from a service even if they want to.

Related

Is it possible to upload file on server using scheduler or windows service?

I am trying to do file upload using quartz job scheduler. but, it is not working.
Is it possible to upload file to the server using job or windows sevice.
I have googled but not understand much. please provide some link for reference.
It is possible to upload file using windows service i guess. We build a similar kind of windows service for inserting to database recursively.[1]: https://www.c-sharpcorner.com/article/create-windows-services-in-c-sharp/
protected override void OnStart(string[] args)
{
WriteToFile("Service is started at " + DateTime.Now);
Fileupload();
timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
timer.Interval = 1000*60*60*10; //number in milisecinds
//timer.Interval = 1000 * 60;
timer.Enabled = true;
}
private void OnElapsedTime(object source, ElapsedEventArgs e)
{
Fileupload();
WriteToFile("Service is recall at " + DateTime.Now);
}
//you can use the above 2 functions in Serivce Cs file and you define your Custom Fileupload Function for uploading file. Hope this works for you

ASP.NET Core 2.0 application running in Linux container suffers from locking issues when there are many calls to Trace.WriteLine()

Our application is an ASP.NET Core 2.0 WebAPI deployed in Linux Docker containers and running in Kubernetes.
During load testing, we discovered intermittent spikes in CPU usage that our application would never recover from.
We used perfcollect to collect traces from a container so that we could compare a successful test and a test with CPU spikes. We discovered that around 75% of the CPU time in the failing test was spent in JIT_MonRelaibleEnter_Protable, an interface of lock operations. The caller was System.Diagnostics.TraceSource.dll.
Our application was ported from .NET Framework and contained a lot of calls to System.Diagnostics.Trace.WriteLine(). When we removed all of these, our CPU/memory usage reduced by more than 50% and we don't see the CPU spikes anymore.
I want to understand the cause of this issue.
In the corefx repo, I can see that a default trace listener is setup in TraceInternal.cs:
public static TraceListenerCollection Listeners
{
get
{
InitializeSettings();
if (s_listeners == null)
{
lock (critSec)
{
if (s_listeners == null)
{
// In the absence of config support, the listeners by default add
// DefaultTraceListener to the listener collection.
s_listeners = new TraceListenerCollection();
TraceListener defaultListener = new DefaultTraceListener();
defaultListener.IndentLevel = t_indentLevel;
defaultListener.IndentSize = s_indentSize;
s_listeners.Add(defaultListener);
}
}
}
return s_listeners;
}
}
I can see that DefaultTraceListener.cs calls Debug.Write():
private void Write(string message, bool useLogFile)
{
if (NeedIndent)
WriteIndent();
// really huge messages mess up both VS and dbmon, so we chop it up into
// reasonable chunks if it's too big
if (message == null || message.Length <= InternalWriteSize)
{
Debug.Write(message);
}
else
{
int offset;
for (offset = 0; offset < message.Length - InternalWriteSize; offset += InternalWriteSize)
{
Debug.Write(message.Substring(offset, InternalWriteSize));
}
Debug.Write(message.Substring(offset));
}
if (useLogFile && !string.IsNullOrEmpty(LogFileName))
WriteToLogFile(message);
}
In Debug.Unix.cs, I can see that there is a call to SysLog:
private static void WriteToDebugger(string message)
{
if (Debugger.IsLogging())
{
Debugger.Log(0, null, message);
}
else
{
Interop.Sys.SysLog(Interop.Sys.SysLogPriority.LOG_USER | Interop.Sys.SysLogPriority.LOG_DEBUG, "%s", message);
}
}
I don't have a lot of experience working with Linux but I believe that I can simulate the call to SysLog by running the following command in the container:
logger --socket-errors=on 'SysLog test'
When I run that command, I get the following response:
socket /dev/log: No such file or directory
So it looks like I can't successfully make calls to SysLog from the container. If this is indeed what is going on when I call Trace.WriteLine(), why is it causing locking issues in my application?
As far as I can tell, EnvVar_DebugWriteToStdErr is not set in my container so it should not be attempting to write to StdErr.
The solution can be that rsyslog is not running. Is that installed in your container? Use a base image that has rsyslog built in.
This link can help too.

Timer job not listed in Timer Job Definitions + Sharepoint 2007

I have created a Custom Timer job which is added when a feature gets activated. The feature does get activated without any exception. But the timer job is not being listed in Timer Job definitions on Central Admin.
The same is working on Staging Server but I am facing this in Production Server.
I am working on Sharepoint2007.
Below is what I have done in Feature Activated.
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPWeb parentWeb = properties.Feature.Parent as SPWeb;
UpdateEmpReferralListTimer taskJob;
SPMinuteSchedule schedule;
foreach (SPJobDefinition job in parentWeb.Site.WebApplication.JobDefinitions)
{
if (job.Name == "xyz")
job.Delete();
}
parentWeb = properties.Feature.Parent as SPWeb;
taskJob = new UpdateEmpReferralListTimer("xyz", parentWeb.Site.WebApplication);
schedule = new SPMinuteSchedule();
schedule.BeginSecond = 0;
schedule.EndSecond = 59;
taskJob.Schedule = schedule;
taskJob.Update();
});
}
catch (Exception Ex)
{
string str = Ex.Message.ToString();
}
}
Scope of Feature is "Web"
To my knowledge trying to perform tasks that require administrator privilegies (like creating timer job) should not work from site level feature activation callback if SharePoint accounts set up properly. Account that web sites run under normally does not have adminstrative privilegies.
It likely works on your staging server due to all accounts having the same privileges. Check out SharePoint logs on your production server to see what exception is (after removing code that eats exception without rethrowing/reporting it - catch (Exception Ex) {...}).
how do you know that your feature is getting activated without error. your code has try/catch block and you are doing nothing in catch block. if your code throwing any error, your catch block will suppress it.
add this line in your catch block and check sharepoint log.
Microsoft.SharePoint.Administration.SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("Development Debugging", TraceSeverity.Unexpected, EventSeverity.Information), TraceSeverity.Unexpected, str, null);
you can find log files in C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\LOGS folder

Run a process on ASP.NET MVC

I'm new on MVC!
I want to run a process on my web app (not for bad purpose), this process can do something, for example it can write a text to a file .txt!
On my local PC, it work well but when I publish it on to host provider, it not work!
How I can do this?
This is my code:
string path = HttpContext.Current.Server.MapPath("~/App_Data/ModuleMaple/ModuleMaple.exe");
Process myproc = new Process();
myproc.StartInfo.FileName = path;
myproc.StartInfo.Arguments ="some argument"
myproc.StartInfo.UseShellExecute = false;
myproc.Start();
myproc.WaitForExit();

How to retain service settings through InstallShield upgrade install

I have an InstallScript project in IS2010. It has a handful of services that get installed. Some are C++ exes and use the "InstallShield Object for NT Services". Others are Java apps installed as services with Java Service Wrapper through LaunchAppAndWait command line calls. Tomcat is also being installed as a service through a call to its service.bat.
When the installer runs in upgrade mode, the services are reinstalled, and the settings (auto vs. manual startup, restart on fail, log-on account, etc.) are reverted to the defaults.
I would like to save the service settings before the file transfer and then repopulate them afterward, but I haven't been able to find a good mechanism to do this. How can I save and restore the service settings?
I got this working by reading the service information from the registry in OnUpdateUIBefore, storing it in a global variable, and writing the information back to the registry in OnUpdateUIAfter.
Code:
export prototype void LoadServiceSettings();
function void LoadServiceSettings()
number i, nResult;
string sServiceNameArray(11), sRegKey, sTemp;
BOOL bEntryFound;
begin
PopulateServiceNameList(sServiceNameArray);
RegDBSetDefaultRoot(HKEY_LOCAL_MACHINE);
//write service start values to the registry
for i = 0 to 10
if (ServiceExistsService(sServiceNameArray(i))) then
sRegKey = "SYSTEM\\CurrentControlSet\\Services\\" + sServiceNameArray(i);
nResult = RegDBSetKeyValueEx(sRegKey, "Start", REGDB_NUMBER, sServiceSettings(i), -1);
if(nResult < 0) then
MessageBox ("Unable to save service settings: " + sServiceNameArray(i) + ".", SEVERE);
endif;
endif;
endfor;
RegDBSetDefaultRoot(HKEY_CLASSES_ROOT); //set back to default
end;
export prototype void SaveServiceSettings();
function void SaveServiceSettings()
number i, nType, nSize, nResult;
string sServiceNameArray(11), sRegKey, sKeyValue;
begin
PopulateServiceNameList(sServiceNameArray);
RegDBSetDefaultRoot(HKEY_LOCAL_MACHINE);
for i = 0 to 10
if (ServiceExistsService(sServiceNameArray(i))) then
//get service start values from registry
sRegKey = "SYSTEM\\CurrentControlSet\\Services\\" + sServiceNameArray(i);
nResult = RegDBGetKeyValueEx(sRegKey, "Start", nType, sKeyValue, nSize);
if(nResult < 0) then
MessageBox ("Unable to save service settings: " + sServiceNameArray(i) + ".", SEVERE);
endif;
sServiceSettings(i) = sKeyValue;
endif;
endfor;
RegDBSetDefaultRoot(HKEY_CLASSES_ROOT); //set back to default
end;

Resources