Service installer with a different name - c#

I am using below cmd code to install a windows service
#echo off
:: BatchGotAdmin
::-------------------------------------
REM --> Check for permissions
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
REM --> If error flag set, we do not have admin.
if '%errorlevel%' NEQ '0' (
echo Requesting administrative privileges...
goto UACPrompt
) else ( goto gotAdmin )
:UACPrompt
echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
set params = %*:"="
echo UAC.ShellExecute "cmd.exe", "/c %~s0 %params%", "", "runas", 1 >> "%temp%\getadmin.vbs"
"%temp%\getadmin.vbs"
del "%temp%\getadmin.vbs"
exit /B
:gotAdmin
pushd "%CD%"
CD /D "%~dp0"
::--------------------------------------
::ENTER YOUR CODE BELOW:
cmd /k "C:\Windows\Microsoft.NET\Framework\v4.0.30319\installutil -i C:\fgbk\WindowsService\installer\OurIntegrationService.exe"
So this creates a service with name OurIntegrationService and i want to create another instance of same service with a different name OurIntegrationServiceStage
How can i do this ?

The ServiceName identifies the service to the Service Control Manager.
The value of this property must be identical to the name recorded for
the service in the ServiceInstaller.ServiceName property of the
corresponding installer class. In code, the ServiceName of the service
is usually set in the main() function of the executable.
https://learn.microsoft.com/en-us/dotnet/api/system.serviceprocess.servicebase.servicename?view=netframework-4.7.2
To give a different name, I suggest you change the service (if you have the code) to read name from app.config, or any other config location.
You can also change the display name (not the service name) by directly changing it in registry.

Related

Calling cmd process doesn't appear to accept path in argument

I have a an application that runs daily and creates a log file; after a period of X days, the log files should be removed which I'm running at the end of all of the other code elements. Originally, this was being completed via PowerShell script however the client cannot run PowerShell code due to ExecutionPolicy on the machine that this application will be running. So, I'm attempting to convert to cmd process. Current code for log removal:
string arg2 = ConfigFile.OutputPaths.Log; //configuration value for log path
int arg2 = ConfigFile.DeleteLogsAfter; //configuration value for days
var processStartInfo = new ProcessStartInfo()
{
FileName = #"cmd.exe",
UseShellExecute = false,
Arguments = $"FORFILES /P \"{arg1}\" /S /M *.* /D -{arg2} /C \"cmd /c del #path\""
};
Process process = Process.Start(processStartInfo);
process.WaitForExit(1000);
This produces the following error:
Could Not Find C:\code\exe_name\debug\#path
In debug, when I view the argument, which is:
FORFILES /P "C:\Work\Clients\Test Files\Logs" /S /M *.* /D -13 /C "cmd /c del #path"
that is being created, if I copy and paste into a command prompt window, it will execute and perform the deletion as expected.
Any ideas how why it isn't accepting the path argument in the process as it does in cmd?
From forfiles help:
There are some disadvantages to using CMD.exe with FORFILES, a new process will be created and destroyed for every file that FORFILES processes, so if you loop through 1000 files, then 1000 copies of CMD.exe will be opened and closed, this will affect performance. Also any variable created with SET will be lost as soon as FORFILES moves on to the next file.
In most cases using a simple FOR command along with Parameter extensions will provide a better/less buggy solution.
Could you do someting like that:
using System. IO;
​
string[] files = Directory. GetFiles(dirName);
​
foreach (string file in files)
{
FileInfo fi = new FileInfo(file);
if (fi. LastAccessTime < DateTime. Now. AddDays(-10)) ...

ILmerge does not implement Newtonsoft.json

The second day I beat my head against the wall and can not figure it out.
How it is possible to implement this dll, any mistakes constantly jump out.
I tried many different options that are on the Internet. Nothing helped.
Help me figure out how to solve the problem.
How to implement Newtonsoft.Json in my project via ILMerge?
Thank you in advance.
Error:
leave command
""C:\Users\User\Desktop\FastFoodDemo\ILMerge\merge_all.bat"
"C:\Users\User\Desktop\FastFoodDemo\"
"C:\Users\User\Desktop\FastFoodDemo\FastFoodDemo\bin\Debug\RCC.exe"
Debug" with code 1. FastFoodDemo
Event final assembly:
"$(SolutionDir)\ILMerge\merge_all.bat" "$(SolutionDir)" "$(TargetPath)" $(ConfigurationName)
merge_all.bat
#ECHO OFF
rem # set .NET version and output folder name
set net="v4, C:\Windows\Microsoft.NET\Framework\v4.0.30319"
set output=Output
rem # process arguments
set ILMergeSolution=%1ILMerge\ILMerge.exe
rem # determine programm files of x86 for 32 and 64 Platform
IF EXIST "%PROGRAMFILES(x86)%" set prorgammFiles=%PROGRAMFILES(x86)%
IF NOT EXIST "%PROGRAMFILES(x86)%" set prorgammFiles=%PROGRAMFILES%
rem # if ILMerge.exe not in the $(SolutionDir)ILMerge\
rem # then try to use installed in prorgammFiles
IF EXIST %ILMergeSolution% set ILMerge="%ILMergeSolution%"
IF NOT EXIST %ILMergeSolution% set ILMerge=%prorgammFiles%\Microsoft\ILMerge\ILMerge.exe
set target_path=%2
set target_file=%~nx2
set target_dir=%~dp2
set ConfigurationName=%3
rem # set output path and result file path
set outdir=%target_dir%%output%
set result=%outdir%\%target_file%
rem # print info
#echo Start %ConfigurationName% Merging %target_file%.
#echo Target: %target_path%
#echo target_dir: %target_dir%
#echo Config: %ConfigurationName%
rem # recreate outdir
IF EXIST "%outdir%" rmdir /S /Q "%outdir%"
md "%outdir%"
rem # run merge cmd
#echo Merging: '"%ILMerge%" /wildcards /targetplatform:%net% /out:"%result%" %target_path% "%target_dir%*.dll"'
"%ILMerge%" /wildcards /targetplatform:%net% /out:"%result%" %target_path% "%target_dir%*.dll"
rem # if succeded
IF %ErrorLevel% EQU 0 (
rem # clear real output folder and put there result assembly
IF %ConfigurationName%==Release (
del %target_dir%*.*
del %target_dir%*.dll
del %target_dir%*.pdb
del %target_dir%*.xml
del %target_dir%*.*
copy %result% %target_dir%
rmdir /S /Q %outdir%
set result=%target_path%
#echo Result: %target_file% "-> %target_path%"
) ELSE (
#echo Result: %target_file% "-> %result%" )
set status=succeded
set errlvl=0
) ELSE (
set status=failed
set errlvl=1
)
#echo Merge %status%
exit %errlvl%

Visual Studio 2012 Post Build Events - Error Code 255

Here is my attempt to copy my application executable to another folder changing it's name:
IF $(ConfigurationName) == Release (
SET DESTINATION=$(ProjectDir)Output\Distribution
IF NOT EXIST "%DESTINATION%" ( MD "%DESTINATION%" )
XCOPY /Q /Y "$(TargetPath)" "%DESTINATION%"
RENAME "%DESTINATION%\$(TargetFileName)" "$(TargetName).Plain$(TargetExt)"
)
I've tried everything to make it work, but it always throw error code 255 or 1, it depends. Running that code with a plain batch file works like a charm!
You need to enable delayed expansion, using the SETLOCAL EnableDelayedExpansion command. Do it at the top of the post-build event. After that, you can access your variable by using not %VARIABLE_NAME%, but !VARIABLE_NAME! (use an exclamation symbol on either side of the variable name, not the percentage symbol which you would use in a regular batch file).
So, for example
SETLOCAL EnableDelayedExpansion
IF $(ConfigurationName) == Release (
SET DESTINATION=$(ProjectDir)Output\Distribution
echo My destination dir is !DESTINATION!
)
This will output something like
My destination dir is D:\Work\Projects\PBExample\Output\Distribution.
Since the Post-build event command line actually runs as a batch file you need to escape characters like % by doubling them to %%:
https://stackoverflow.com/a/13552702/74585

netsh interface set interface name="Local Area Connection 2" admin=DISABLED

I want to disable all network adapters:
I saw that it can be done via system command netsh.
When I run the following command i got an error.
C:\Windows\system32>netsh interface set interface name="Local Area Connection 2" admin=DISABLED
Area is not an acceptable value for connect.
The parameter is incorrect.
It seems that the command line parser could not get the spacing. The same happens if using single quote (instead of double quotes).
i need your help gurus.
By the way, my code is C#, I tried many examples from the web and none of worked.
System.Diagnostics.ProcessStartInfo psi =
new System.Diagnostics.ProcessStartInfo(
"netsh",
"interface set interface name=\"" + interfaceName + "\" admin=enabled");
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo = psi;
bool result = p.Start();
I use
netsh interface set interface "Local Area Connection 2" ENABLED
it works fine for me and enables "Local Area Connection 2"
probably you might use this way with your code, it should work for you.
echo ----------------------------------------------
echo Restarting network interfaces
echo ----------------------------------------------
netsh interface ipv4 show interfaces
for /F "tokens=1-3,4*" %%I in ('netsh interface ipv4 show interfaces ^| find /I "CONNECTED" ^| find /I /V "DISCONNECTED" ^| find /I /V "LOOPBACK"') do (
echo.&echo - Restarting #%%I [%%M] ...
netsh interface set interface name="%%M" admin=disabled >nul 2>&1
ping -n 1 127.0.0.1 >nul 2>&1
netsh interface set interface name="%%M" admin=enabled >nul 2>&1
ping -n 1 127.0.0.1 >nul 2>&1
if %ERRORLEVEL% EQU 0 (
echo +++ OK +++
) else (
echo --- NOK ---
)
)

Remote Process Execution using Wmi win32_Process - Getting Stdout of Process

Hi i am able to execute a remote process using Wmi and was able to get return Value and Process Id of the Process. Is there any way to get the Output of the Process which was started by Wmi. Eg. If i start an exe which prints something in console will i be able to get those values using this Api. Any help is appreciated.
You must redirect the output to a file, then read the file across the network.
Use the CMD.EXE /S /C option to do this.
Example command line to run Program.exe:
CMD.EXE /S /C " "c:\path\to\program.exe" "argument1" "argument2" > "c:\path\to\stdout.txt" 2> "c:\path\to\stderr.txt" "
Then connect to server like this \\servername\c$\path\to\stdout.txt to read the stdout results.
Note: Pay careful attention to the extra quotes around the command to run. These are necessary to ensure the command line is interpreted correctly.
You can use psexec to execute the program.exe and get the stdout by pipe
p = subprocess.Popen(cmd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
while p.poll() is None:
line = p.stdout.readline()
line = line.strip().decode('gbk')
if line:
print('Subprogram output: [{}]'.format(line))
if p.returncode == 0:
print('Subprogram success')
return True
else:
print('Subprogram failed')
return False

Categories