Why can't I install my windows service - Specified service already exists - c#

I wish I could put a grenade to my computer at this point. I'm so frustrated because I don't understand why my application won't install using installUtil.
I've just looked through this link now: Windows Service Install Ends in Rollback and unfortunately the kind suggestions on there don't help in my situation, the following error was generated after taking into consideration all of the answers posted by the good people of SO on that link and others.
I have looked for best practices on the web for task parallel processing patterns but there's nothing helpful so far. The latest error I get when attempting to install is as follows:
.exe assembly's progress. The file is located at
E:\xxx\MyService\Service_V2.InstallLog. Installing assembly
'E:\xxx\MyService\Service_V2.exe'. Affected parameters are:
logtoconsole = logfile = E:\xxx\MyService\Service_V2.InstallLog
assemblypath = E:\xxx\MyService\Service_V2.exe Installing service
Service V2... Service Service V2 has been successfully installed.
Creating EventLog source Service V2 in log Application... Installing
service Service V2... Creating EventLog source Service V2 in log
Application...
An exception occurred during the Install phase.
System.ComponentModel.Win32Exception: The specified service already
exists
The Rollback phase of the installation is beginning. See the contents
of the log file for the E:\xxx\MyService\Service_V2 .exe assembly's
progress. The file is located at
E:\xxx\MyService\Service_V2.InstallLog. Rolling back assembly
'E:\xxx\MyService\Service_V2.exe'. Affected parameters are:
logtoconsole = logfile = E:\xxx\MyService\Service_V2.InstallLog
assemblypath = E:\xxx\MyService\Service_V2.exe Restoring event log to
previous state for source Service V2. Restoring event log to previous
state for source Service V2. Service Service V2 is being removed from
the system... Service Service V2 was successfully removed from the
system.
The Rollback phase completed successfully.
The transacted install has completed. The installation failed, and the
rollback has been performed.
There was nothing written to the event log either.
Here is my OnStart() method:
protected override void OnStart(string[] args)
{
var tokenSource = new CancellationTokenSource();
var token = tokenSource.Token;
ErrorLogFileName = "Service_V2Errors" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
Service_V2LogFile = "Service_V2Log" + DateTime.Now.ToString("yyyy-MM-dd") + ".log";
ErrorLogPath = ConfigurationManager.AppSettings["Errorpath"].ToString();
CheckBatchRecord = Convert.ToInt32(ConfigurationManager.AppSettings["CheckBatchTime"].ToString());
if (!Directory.Exists(ErrorLogPath))
{
Directory.CreateDirectory(ErrorLogPath);
}
LogMessage("Starting Service " + DateTime.Now.ToString());
_ErrorLog = new StreamWriter(ErrorLogPath + "//" + ErrorLogFileName, true);
_ErrorLog.WriteLine("Error, Location, AdditionalInformation", true);
_ErrorLog.Close();
var t = Task.Run(() => Service_V2Start(), token);
try
{
t.Wait();
}
catch (AggregateException e)
{
LogMessage("Exception messages:");
foreach (var ie in e.InnerExceptions)
LogMessage(ie.GetType().Name + " : " + ie.Message);
LogMessage("\nTask status: " + t.Status);
}
finally
{
tokenSource.Dispose();
}
}
I have also set the compile mode to release for the final install files compiled.
I have done an "sc delete Servie V2" and I also checked the services console and there is no such service listed there.
I have also tried the InstallUtil.exe -u command to uninstall, but I still get this nitwit error. What should I do now?

Make sure your Program.cs file looks something like this:
static class Program
{
static void Main()
{
var service = new YourServiceName();
ServiceBase.Run(service);
}
}
Inside the InitializeComponent() method make sure that the ServiceName property value is the same as the ServiceName in the ProjectInstaller.cs
this.ServiceName = "MyServiceName";//in the YourServiceName partial class
this.myServiceInstaller.ServiceName = "MyServiceName";//in the installer
Make sure you have only one installer.
In the batch files that you created to install and uninstall your service make sure that you are pointing to the correct InstallUtil.exe.
For 64 bit architectures you can use - C:\Windows\Microsoft.NET\Framework64\v4.0.30319\installutil.exe
For 32 bit architectures you can use - C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe
Sample InstallService.bat file:
"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\installutil.exe" "PathToTheExecutables\MyServiceName.exe"
pause
Sample UninstallService.bat file:
"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\installutil.exe" /u "PathToTheExecutables\MyServiceName.exe"
pause

Make sure you run cmd as Administrator :)

Related

SharpSvn.SvnException: sqlite[S8]: attempt to write a readonly database

I got following error when I do `
svnclient.CleanUp(WorkDirPath);`
SharpSvn.SvnException: sqlite[S8]: attempt to write a readonly database
---> SharpSvn.SvnException: Additional errors:
---> SharpSvn.SvnException: sqlite[S8]: attempt to write a readonly database
Update
I have visual studio application and from this application i need upload/download any file to SVN server and this feature can access by end user. so for this i installed VisualSVN Server Manager Version: 4.3.3 on windows server. in my application i imported nuget for this SharpSvn.1.8-x64 to atchive this task (I am new in subversion and client).
Updated : I updated sharpSVN to 1.14001.156 thanks for it. but still my problem is not solved. i still get following error when try to add file "Failed to lock working copy" and then I tried Clean Up Command got "sqlite[S8]: attempt to write a readonly database" error. Is Visual SVN Server Version: 4.3.3 ok with SharpSVN 1.14 ?
following is my code written in C#
svnclient.Authentication.DefaultCredentials = new NetworkCredential(_svnuser, _svnpwd);
CleanCommand(svnclient,_userworkdir);
public bool AddFile(string path, SvnClient svnclient)
{
try
{
return svnclient.Add(path);
}
catch (Exception ex)
{
Log.Error(String.Format(String.Format("Exception in function AddFile := {0} FilePath :- {1}", ex.Message.ToString(), path)));
return false;
}
}
public bool CleanCommand(SvnClient svnclient, String workingdir)
{
bool res = false;
try
{
res = svnclient.CleanUp(workingdir);
}
catch (Exception ex)
{
Log.Error(String.Format(String.Format("Exception in function CleanCommand := {0}, workingdir :- {1}", ex.Message.ToString(), workingdir)));
res = false;
}
return res;
}
Note that SharpSVN 1.8 is outdated. If you use Subversion client based on SharpSVN (AnkhSVN?), it makes sense to update it or to switch to an up-to-date native Subversion 1.14.x client.
As an immediate solution, you can check out a new working copy and continue you work with it. If you have uncommitted changes in the working copy, you can copy them over into a new working copy (don't copy hidden .svn directory though).
I think that something prevents you from opening or writing the contents of the .svn metadata directory. This could be due to insufficient permissions or another program that locks your working copy:
Check NTFS permissions to the .svn directory in the root of your working copy and the .svn/wc.db file in particular (e.g., C:\Users\MyUser\MyVsProject\.svn\wc.db). You should double-check that your user account has permissions to write to C:\Users\MyUser\MyVsProject\ directory and all its contents.
Check if other SVN clients or programs work concurrently with your client and lock the working copy.

Windows Service "Timeout" instantly on startup

I'm currently running in to an issue where a Windows Service I wrote is "timing out" instantly on start up. The message I get is Error 1053: The service did not respond to the start or control request in a timely fashion. I checked Event Viewer and I see that message and another A timeout was reached (30000 milliseconds) while waiting for the X service to connect. Only problem is that it's not waiting 30 seconds to time out, it's more like half a second.
My service's OnStart()
private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private string version = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).FileVersion;
private string incomingProdFileLocation = ConfigurationManager.AppSettings["ProdIncomingFileLocation"];
private string incomingCertFileLocation = ConfigurationManager.AppSettings["CertIncomingFileLocation"];
//private string incomingCombFileLocation = ConfigurationManager.AppSettings["CombIncomingFileLocation"];
private string processedFileLocation = ConfigurationManager.AppSettings["ProcessedFileLocation"];
private string errorFileLocation = ConfigurationManager.AppSettings["ErrorFileLocation"];
FileSystemWatcher prodWatcher = new FileSystemWatcher();
FileSystemWatcher certWatcher = new FileSystemWatcher();
//FileSystemWatcher combWatcher = new FileSystemWatcher();
protected override void OnStart(string[] args) {
log.InfoFormat("Starting up Merchant Bulk Load Service v{0}", version);
if (verifyDirectories()) {
log.InfoFormat("Initialize Prod FileSystemWatcher() at {0}", incomingProdFileLocation);
prodWatcher.Path = incomingProdFileLocation;
prodWatcher.Filter = "*.csv";
prodWatcher.Created += ProdBulkLoadFileReceived;
prodWatcher.EnableRaisingEvents = true;
log.InfoFormat("Initialize Cert FileSystemWatcher() at {0}", incomingCertFileLocation);
certWatcher.Path = incomingCertFileLocation;
certWatcher.Filter = "*.csv";
certWatcher.Created += CertBulkLoadFileReceived;
certWatcher.EnableRaisingEvents = true;
/*log.InfoFormat("Initialize Comb FileSystemWatcher() at {0}", incomingCombFileLocation);
combWatcher.Path = incomingCombFileLocation;
combWatcher.Filter = "*.csv";
combWatcher.Created += CombBulkLoadFileReceived;
combWatcher.EnableRaisingEvents = true;*/
} else {
log.ErrorFormat("verifyDirectories() returned false. Service stopping");
this.Stop();
}
}
private bool verifyDirectories() {
// verify each of the necessary directories exists before setting up any FileSystemWatcher()s
if (!Directory.Exists(incomingProdFileLocation)) {
log.ErrorFormat("Incoming production file location {0} does not exist. Please create the directory or edit the configuration file.",
incomingProdFileLocation);
return false;
}
if (!Directory.Exists(incomingCertFileLocation)) {
log.ErrorFormat("Incoming cert file location {0} does not exist. Please create the directory or edit the configuration file.",
incomingCertFileLocation);
return false;
}
/*if (!Directory.Exists(incomingCombFileLocation)) {
log.ErrorFormat("Incoming combined file location {0} does not exist. Please create the directory or edit the configuration file.",
incomingCombFileLocation);
return false;
}*/
if (!Directory.Exists(processedFileLocation)) {
log.ErrorFormat("Processed file location {0} does not exist. Please create the directory or edit the configuration file.",
processedFileLocation);
return false;
}
if (!Directory.Exists(errorFileLocation)) {
log.ErrorFormat("Error file location {0} does not exist. Please create the directory or edit the configuration file.",
errorFileLocation);
return false;
}
return true;
}
My entire service works splendidly in our development and certification environments, but won't start in our production environment, it doesn't seem like it's even getting to the OnStart() because a log is never made. Things I've checked:
Made sure service had correct permissions in the necessary directories, it does
Made sure the correct version of .NET framework that my service is targeting (4) is installed, it is
Made sure Event Viewer wasn't throwing any other types of errors that might give me a hint to what's happening, there's nothing
All of the directories for the FileSystemWatcher actually exist, they do
The directory for the log4net file exists, it does
I'm at a loss at the moment; any help would be awesome.
edit
After double checking the .NET framework again I realize I checked the wrong server for the versions. A good way to be certain is to double-click on the actual exe file for the service and see what it says. In my case it literally said "Make sure 4.0 is installed" which prompted me to check again and there I saw that 4.0 wasn't installed.
Are you sure that your .net is up to date. This could happen if for instance 3.5 is on the machine and you're using 4.0.
This is an old ticket, but I just saw the same error (albeit with "90000 milliseconds" rather than 30000) on all of the Windows services we've created as part of our application (about 10 of them). .Net framework was installed and functional.
I examined the registry setting where this 90000 ms (90 second) limit was set.
In the node, HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control
The value of ServicesPipeTimeout was 90000 (Decimal).
I didn't need it to be 90000 and I don't know why it was set thus, but it certainly wasn't waiting 90 seconds -- it was failing instantly.
So I modified the value to 30000 and rebooted the server.
All services begin starting or restarting successfully.

Overwrite restricted application file?

I'm trying to manually patch my application. The application makes use of a Service which i make sure to stop and uninstall prior to attempting any overwriting of the application dll's.
The issue is that i can't overwrite, or even delete some of the dll files which are the core of the application, these dll files are used by the service i uninstalled first.
I use the following method to pass in the new file-path in order to replace the old DLL which is located inside the root directory of the application in C:\Program Files\AppName\
public static bool CopyFile(string newFile, string oldFile)
{
var newfile = new FileInfo(newFile);
var oldfile = new FileInfo(oldFile);
var f2 = new FileIOPermission(FileIOPermissionAccess.AllAccess, oldFile);
f2.AddPathList(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, newFile);
try
{
f2.Demand();
}
catch (SecurityException s)
{
Console.WriteLine(s.Message);
}
for (int x = 0; x < 100; x++)
{
try
{
File.Delete(oldfile.FullName);
newfile.CopyTo(oldfile.FullName, true);
return true;
}
catch
{
Thread.Sleep(200);
}
}
return false;
}
I just wish to provide a new file and remove the old one, replace it, overwrite it.... The application
Note: The application i run to do the patching runs as administrator.
Any idea?
I was able to fix this issue by making use of a "middle man" in other words, another application which downloads another executable and passes command line arguments to it.
Originally, my service would download an executable (call it Installer.exe). Installer.exe would then attempt to stop the service and patch the content, this did not work.
I now have the service running, it downloads "Installer.exe".
Installer.exe will load up and download PatchPayload.exe.
PatchPayload.exe runs and kills off the Service, uninstalls it and then download all required patch content from a centralized server and patch the service core files individually then install the service and run it again.

Automatic update a Windows application

How do I develop my Windows application so it will auto update on the client machine, like Firefox, Skype, etc.?
Is there any simple approach or any open source library which help me to do it just following some steps or a few lines of code?
ClickOnce is what you're searching for.
You might also find these SO questions interesting (which offers some different solutions):
Auto update for WinForms application
How do I implement an auto update strategy for my in-house winform app
try microsoft clickonce technology
(in MSDN)
You can use wyUpdate or .NET Application Updater Component
There is also the Update Block in the Ent Lib by msft.
The most popular frameworks are:
Google Omaha - This is what Chrome uses. Very powerful.
Squirrel - This is used in Electron applications. Easy to use but can't update machine-wide installations. Also, no graphical update notifications.
WinSparkle - Gives you graphical update notifications. But less mature than Squirrel.
AutoUpdater.NET - Both graphical and silent updates. Similar to Squirrel and WinSparkle.
I've taken these links from this article. It goes into more details about the pros and cons of each of the frameworks.
Use MD5-Update it easy only need add 5 lines at your application, no configuration need in your app only add library and publish the files.
1. Your need a web server with PHP for publish your files please include updt.exe.
2. Add index.php for make list of update files. aviable on github repository https://github.com/jrz-soft-mx/MD5-Update/blob/main/Tools/Tools.zip o create new app with this code.
<?php
$_dat = array();
$_dir=new RecursiveDirectoryIterator(".");
foreach (new RecursiveIteratorIterator($_dir) as $_itm) {
$_fil = str_replace(".".DIRECTORY_SEPARATOR, "", $_itm);
if(!is_dir($_fil) && $_fil != "index.php"){
$_dat[]=array('StrFil' => "$_fil", 'StrMd5' => strtoupper(md5_file($_fil)), 'lonSiz' => filesize($_fil));
}
}
echo json_encode($_dat, JSON_UNESCAPED_UNICODE);
?>
3. Add nuget repository at your proyect
PM> Install-Package MD5.Update
4. Call the library when your app stars, with your update folder url, update all files and download your new app on updt folder, for replace your app need updt.exe
string strUrl = "http://yourdomain.com/app/";
if (MD5Update.MD5Update.Check(strUrl, true))
{
Process.Start(AppDomain.CurrentDomain.BaseDirectory + #"updt.exe", AppDomain.CurrentDomain.FriendlyName + " " + Process.GetCurrentProcess().ProcessName);
Application.Exit();
}
5. updt.exe for replace the current app with the new app updt folder to app. aviable on github repository https://github.com/jrz-soft-mx/MD5-Update/blob/main/Tools/Tools.zip o create new app with this code.
try
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
List<string> lisArg = Environment.GetCommandLineArgs().ToList();
if (lisArg.Count < 2)
{
MessageBox.Show("Please provide App Excutable Name and Procees name");
Application.Exit();
return;
}
string strAppName = lisArg[1];
string strAppProcees = lisArg[2];
Process[] lisPro = Process.GetProcessesByName(strAppProcees);
foreach (Process Pro in lisPro)
{
if (Pro.Id != Process.GetCurrentProcess().Id)
{
Pro.Kill();
Thread.Sleep(1000);
}
}
string strAppMain = AppDomain.CurrentDomain.BaseDirectory + strAppName;
string strAppUpdate = AppDomain.CurrentDomain.BaseDirectory + #"updt\" + strAppName;
if (!File.Exists(strAppMain))
{
MessageBox.Show("App Excutable dosent exists");
Application.Exit();
return;
}
if (!File.Exists(strAppUpdate))
{
MessageBox.Show("App Excutable Updated dosent exists");
Application.Exit();
return;
}
File.Copy(strAppUpdate, strAppMain, true);
long fileSize = 0;
FileInfo currentFile = new FileInfo(strAppMain);
while (fileSize < currentFile.Length)
{
fileSize = currentFile.Length;
Thread.Sleep(1000);
currentFile.Refresh();
}
Process.Start(strAppMain);
}
catch (Exception Ex)
{
MessageBox.Show("An error ocurred");
File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + #"updt_" + DateTime.Now.ToString("yyyyMMddTHHmmss") + " .txt", Ex.ToString());
Application.Exit();
}
How about System Center 2012 Configuration Manager?
I'd add another possible variation:
https://github.com/synhershko/NAppUpdate
https://github.com/cecon/autoupdatereasy
https://github.com/NetSparkleUpdater/NetSparkle
While ClickOnce is simple and it resurrected for .NET 5, it still has a lot of limitations, so I found out that nowadays better option exists: you could use included in Windows 10 mechanism for app delivery called AppInstaller by packaging your app in MSIX bundle or package.
I covered my findings related to the topic in this answer

Use C# to interact with Windows Update

Is there any API for writing a C# program that could interface with Windows update, and use it to selectively install certain updates?
I'm thinking somewhere along the lines of storing a list in a central repository of approved updates. Then the client side applications (which would have to be installed once) would interface with Windows Update to determine what updates are available, then install the ones that are on the approved list. That way the updates are still applied automatically from a client-side perspective, but I can select which updates are being applied.
This is not my role in the company by the way, I was really just wondering if there is an API for windows update and how to use it.
Add a Reference to WUApiLib to your C# project.
using WUApiLib;
protected override void OnLoad(EventArgs e){
base.OnLoad(e);
UpdateSession uSession = new UpdateSession();
IUpdateSearcher uSearcher = uSession.CreateUpdateSearcher();
uSearcher.Online = false;
try {
ISearchResult sResult = uSearcher.Search("IsInstalled=1 And IsHidden=0");
textBox1.Text = "Found " + sResult.Updates.Count + " updates" + Environment.NewLine;
foreach (IUpdate update in sResult.Updates) {
textBox1.AppendText(update.Title + Environment.NewLine);
}
}
catch (Exception ex) {
Console.WriteLine("Something went wrong: " + ex.Message);
}
}
Given you have a form with a TextBox this will give you a list of the currently installed updates. See http://msdn.microsoft.com/en-us/library/aa387102(VS.85).aspx for more documentation.
This will, however, not allow you to find KB hotfixes which are not distributed via Windows Update.
The easiest way to do what you want is using WSUS. It's free and basically lets you setup your own local windows update server where you decide which updates are "approved" for your computers. Neither the WSUS server nor the clients need to be in a domain, though it makes it easier to configure the clients if they are. If you have different sets of machines that need different sets of updates approved, that's also supported.
Not only does this accomplish your stated goal, it saves your overall network bandwidth as well by only downloading the updates once from the WSUS server.
If in your context you're allowed to use Windows Server Update Service (WSUS), it will give you access to the Microsoft.UpdateServices.Administration Namespace.
From there, you should be able to do some nice things :)
P-L right. I tried first the Christoph Grimmer-Die method, and in some case, it was not working. I guess it was due to different version of .net or OS architecture (32 or 64 bits).
Then, to be sure that my program get always the Windows Update waiting list of each of my computer domain, I did the following :
Install a serveur with WSUS (may save some internet bandwith) : http://www.microsoft.com/en-us/download/details.aspx?displaylang=en&id=5216
Add all your workstations & servers to your WSUS server
Get SimpleImpersonation Lib to run this program with different admin right (optional)
Install only the administration console component on your dev workstation and run the following program :
It will print in the console all Windows updates with UpdateInstallationStates.Downloaded
using System;
using Microsoft.UpdateServices.Administration;
using SimpleImpersonation;
namespace MAJSRS_CalendarChecker
{
class WSUS
{
public WSUS()
{
// I use impersonation to use other logon than mine. Remove the following "using" if not needed
using (Impersonation.LogonUser("mydomain.local", "admin_account_wsus", "Password", LogonType.Batch))
{
ComputerTargetScope scope = new ComputerTargetScope();
IUpdateServer server = AdminProxy.GetUpdateServer("wsus_server.mydomain.local", false, 80);
ComputerTargetCollection targets = server.GetComputerTargets(scope);
// Search
targets = server.SearchComputerTargets("any_server_name_or_ip");
// To get only on server FindTarget method
IComputerTarget target = FindTarget(targets, "any_server_name_or_ip");
Console.WriteLine(target.FullDomainName);
IUpdateSummary summary = target.GetUpdateInstallationSummary();
UpdateScope _updateScope = new UpdateScope();
// See in UpdateInstallationStates all other properties criteria
_updateScope.IncludedInstallationStates = UpdateInstallationStates.Downloaded;
UpdateInstallationInfoCollection updatesInfo = target.GetUpdateInstallationInfoPerUpdate(_updateScope);
int updateCount = updatesInfo.Count;
foreach (IUpdateInstallationInfo updateInfo in updatesInfo)
{
Console.WriteLine(updateInfo.GetUpdate().Title);
}
}
}
public IComputerTarget FindTarget(ComputerTargetCollection coll, string computername)
{
foreach (IComputerTarget target in coll)
{
if (target.FullDomainName.Contains(computername.ToLower()))
return target;
}
return null;
}
}
}

Categories

Resources